

from typing import List, Optional, Union

from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType






class  UpperCAmelCase__	( A__ ):






  """simple docstring"""


  a     =      ["image_processor", "tokenizer"]
  a     =      "BlipImageProcessor"
  a     =      "AutoTokenizer"






  def __init__(							self		:	Optional[int]			,     __lowerCamelCase		:	Union[str, Any]			,     __lowerCamelCase		:	Union[str, Any]      )	->							str:
       SCREAMING_SNAKE_CASE__     :   str					=					False
       super().__init__(__lowerCamelCase			,     __lowerCamelCase      )
       SCREAMING_SNAKE_CASE__     :   List[Any]					=					self.image_processor






  def __call__(							self		:	Optional[Any]			,     __lowerCamelCase		:	ImageInput = None			,     __lowerCamelCase		:	Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None			,     __lowerCamelCase		:	bool = True			,     __lowerCamelCase		:	Union[bool, str, PaddingStrategy] = False			,     __lowerCamelCase		:	Union[bool, str, TruncationStrategy] = None			,     __lowerCamelCase		:	Optional[int] = None			,     __lowerCamelCase		:	int = 0			,     __lowerCamelCase		:	Optional[int] = None			,     __lowerCamelCase		:	Optional[bool] = None			,     __lowerCamelCase		:	bool = False			,     __lowerCamelCase		:	bool = False			,     __lowerCamelCase		:	bool = False			,     __lowerCamelCase		:	bool = False			,     __lowerCamelCase		:	bool = False			,     __lowerCamelCase		:	bool = True			,     __lowerCamelCase		:	Optional[Union[str, TensorType]] = None			,     **__lowerCamelCase		:	List[str]			,     )	->							BatchEncoding:
       if images is None and text is None:
            raise ValueError('''You have to specify either images or text.'''      )

       # Get only text
       if images is None:
            SCREAMING_SNAKE_CASE__     :   str					=					self.tokenizer
            SCREAMING_SNAKE_CASE__     :   Union[str, Any]					=					self.tokenizer(
                text=__lowerCamelCase			,     add_special_tokens=__lowerCamelCase			,     padding=__lowerCamelCase			,     truncation=__lowerCamelCase			,     max_length=__lowerCamelCase			,     stride=__lowerCamelCase			,     pad_to_multiple_of=__lowerCamelCase			,     return_attention_mask=__lowerCamelCase			,     return_overflowing_tokens=__lowerCamelCase			,     return_special_tokens_mask=__lowerCamelCase			,     return_offsets_mapping=__lowerCamelCase			,     return_token_type_ids=__lowerCamelCase			,     return_length=__lowerCamelCase			,     verbose=__lowerCamelCase			,     return_tensors=__lowerCamelCase			,     **__lowerCamelCase			,     )
            return text_encoding

       # add pixel_values
       SCREAMING_SNAKE_CASE__     :   Optional[Any]					=					self.image_processor(__lowerCamelCase			,     return_tensors=__lowerCamelCase      )

       if text is not None:
            SCREAMING_SNAKE_CASE__     :   Tuple					=					self.tokenizer(
                text=__lowerCamelCase			,     add_special_tokens=__lowerCamelCase			,     padding=__lowerCamelCase			,     truncation=__lowerCamelCase			,     max_length=__lowerCamelCase			,     stride=__lowerCamelCase			,     pad_to_multiple_of=__lowerCamelCase			,     return_attention_mask=__lowerCamelCase			,     return_overflowing_tokens=__lowerCamelCase			,     return_special_tokens_mask=__lowerCamelCase			,     return_offsets_mapping=__lowerCamelCase			,     return_token_type_ids=__lowerCamelCase			,     return_length=__lowerCamelCase			,     verbose=__lowerCamelCase			,     return_tensors=__lowerCamelCase			,     **__lowerCamelCase			,     )
       else:
            SCREAMING_SNAKE_CASE__     :   Any					=					None

       if text_encoding is not None:
            encoding_image_processor.update(__lowerCamelCase      )

       return encoding_image_processor






  def    lowercase_	(							self		:	List[str]			,     *__lowerCamelCase		:	Optional[int]			,     **__lowerCamelCase		:	Tuple      )	->							List[Any]:
       return self.tokenizer.batch_decode(*__lowerCamelCase			,     **__lowerCamelCase      )






  def    lowercase_	(							self		:	Any			,     *__lowerCamelCase		:	Dict			,     **__lowerCamelCase		:	Optional[int]      )	->							List[str]:
       return self.tokenizer.decode(*__lowerCamelCase			,     **__lowerCamelCase      )







  @property
  # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
  def    lowercase_	(							self		:	Optional[Any]      )	->							Optional[int]:
       SCREAMING_SNAKE_CASE__     :   Any					=					self.tokenizer.model_input_names
       SCREAMING_SNAKE_CASE__     :   Optional[int]					=					self.image_processor.model_input_names
       return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names      )      )





import math
import time

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
       import torch_xla.core.xla_model as xm
       import torch_xla.debug.metrics as met






class  UpperCAmelCase__	( A__ ):






  """simple docstring"""


  def __init__(							self		:	Tuple			,     *__lowerCamelCase		:	List[str]			,     __lowerCamelCase		:	Any=None			,     __lowerCamelCase		:	Optional[int]=None			,     **__lowerCamelCase		:	Optional[int]      )	->							List[str]:
       super().__init__(*__lowerCamelCase			,     **__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					eval_examples
       SCREAMING_SNAKE_CASE__					=					post_process_function






  def    lowercase_	(							self		:	Optional[Any]			,     __lowerCamelCase		:	Dict=None			,     __lowerCamelCase		:	int=None			,     __lowerCamelCase		:	str=None			,     __lowerCamelCase		:	str = "eval"      )	->							Optional[Any]:
       SCREAMING_SNAKE_CASE__					=					self.eval_dataset if eval_dataset is None else eval_dataset
       SCREAMING_SNAKE_CASE__					=					self.get_eval_dataloader(__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					self.eval_examples if eval_examples is None else eval_examples

       # Temporarily disable metric computation, we will do it in the loop here.
       SCREAMING_SNAKE_CASE__					=					self.compute_metrics
       SCREAMING_SNAKE_CASE__					=					None
       SCREAMING_SNAKE_CASE__					=					self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
       SCREAMING_SNAKE_CASE__					=					time.time()
       try:
            SCREAMING_SNAKE_CASE__					=					eval_loop(
                __lowerCamelCase			,     description='''Evaluation'''			,     prediction_loss_only=True if compute_metrics is None else None			,     ignore_keys=__lowerCamelCase			,     metric_key_prefix=__lowerCamelCase			,     )
       finally:
            SCREAMING_SNAKE_CASE__					=					compute_metrics
       SCREAMING_SNAKE_CASE__					=					self.args.eval_batch_size * self.args.world_size
       if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
            start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time''']
       output.metrics.update(
           speed_metrics(
               __lowerCamelCase			,     __lowerCamelCase			,     num_samples=output.num_samples			,     num_steps=math.ceil(output.num_samples / total_batch_size      )			,     )      )
       if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
            # Only the main node write the results by default
            SCREAMING_SNAKE_CASE__					=					self.post_process_function(__lowerCamelCase			,     __lowerCamelCase			,     output.predictions      )
            SCREAMING_SNAKE_CASE__					=					self.compute_metrics(__lowerCamelCase      )

            # Prefix all keys with metric_key_prefix + '_'
            for key in list(metrics.keys()      ):
                 if not key.startswith(f'''{metric_key_prefix}_'''      ):
                      SCREAMING_SNAKE_CASE__					=					metrics.pop(__lowerCamelCase      )
            metrics.update(output.metrics      )
       else:
            SCREAMING_SNAKE_CASE__					=					output.metrics

       if self.args.should_log:
            # Only the main node log the results by default
            self.log(__lowerCamelCase      )

       if self.args.tpu_metrics_debug or self.args.debug:
            # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
            xm.master_print(met.metrics_report()      )

       SCREAMING_SNAKE_CASE__					=					self.callback_handler.on_evaluate(self.args			,     self.state			,     self.control			,     __lowerCamelCase      )
       return metrics







  def    lowercase_	(							self		:	Dict			,     __lowerCamelCase		:	Dict			,     __lowerCamelCase		:	str			,     __lowerCamelCase		:	str=None			,     __lowerCamelCase		:	str = "test"      )	->							Any:
       SCREAMING_SNAKE_CASE__					=					self.get_test_dataloader(__lowerCamelCase      )

       # Temporarily disable metric computation, we will do it in the loop here.
       SCREAMING_SNAKE_CASE__					=					self.compute_metrics
       SCREAMING_SNAKE_CASE__					=					None
       SCREAMING_SNAKE_CASE__					=					self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
       SCREAMING_SNAKE_CASE__					=					time.time()
       try:
            SCREAMING_SNAKE_CASE__					=					eval_loop(
                __lowerCamelCase			,     description='''Prediction'''			,     prediction_loss_only=True if compute_metrics is None else None			,     ignore_keys=__lowerCamelCase			,     metric_key_prefix=__lowerCamelCase			,     )
       finally:
            SCREAMING_SNAKE_CASE__					=					compute_metrics
       SCREAMING_SNAKE_CASE__					=					self.args.eval_batch_size * self.args.world_size
       if f'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
            start_time += output.metrics[f'''{metric_key_prefix}_jit_compilation_time''']
       output.metrics.update(
           speed_metrics(
               __lowerCamelCase			,     __lowerCamelCase			,     num_samples=output.num_samples			,     num_steps=math.ceil(output.num_samples / total_batch_size      )			,     )      )

       if self.post_process_function is None or self.compute_metrics is None:
            return output

       SCREAMING_SNAKE_CASE__					=					self.post_process_function(__lowerCamelCase			,     __lowerCamelCase			,     output.predictions			,     '''predict'''      )
       SCREAMING_SNAKE_CASE__					=					self.compute_metrics(__lowerCamelCase      )

       # Prefix all keys with metric_key_prefix + '_'
       for key in list(metrics.keys()      ):
            if not key.startswith(f'''{metric_key_prefix}_'''      ):
                 SCREAMING_SNAKE_CASE__					=					metrics.pop(__lowerCamelCase      )
       metrics.update(output.metrics      )
       return PredictionOutput(predictions=predictions.predictions			,     label_ids=predictions.label_ids			,     metrics=__lowerCamelCase      )


