



"""simple docstring"""

from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
     from PIL import Image

     from ..image_utils import load_image

if is_torch_available():
     from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
     from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
     from ..tf_utils import stable_softmax

lowercase__					:						List[Any]												=			logging.get_logger(__name__)




@add_end_docstrings(lowerCAmelCase__)
class  _UpperCAmelCase (    lowerCAmelCase__):

 def __init__(  self	: Tuple						,  **lowercase_	: Dict       ):
     super().__init__(**lowercase_       )

     requires_backends(self						,  '''vision'''       )
     self.check_model_type(
         TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
         if self.framework == '''tf'''
         else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING       )

 def __call__(  self	: List[Any]						,  lowercase_	: Union[str, List[str], "Image", List["Image"]]						,  **lowercase_	: Optional[int]       ):
     return super().__call__(lowercase_						,  **lowercase_       )

 def 		_snake_case      (  self	: Optional[int]						,  **lowercase_	: Optional[Any]       ):
     snake_case_				:  List[str]       =			{}
     if "candidate_labels" in kwargs:
         snake_case_				:  List[str]       =			kwargs['''candidate_labels''']
     if "hypothesis_template" in kwargs:
         snake_case_				:  Optional[Any]       =			kwargs['''hypothesis_template''']

     return preprocess_params, {}, {}

 def 		_snake_case      (  self	: Any						,  lowercase_	: Union[str, Any]						,  lowercase_	: str=None						,  lowercase_	: int="This is a photo of {}."       ):
     snake_case_				:  Tuple       =			load_image(lowercase_       )
     snake_case_				:  Dict       =			self.image_processor(images=[image]						,  return_tensors=self.framework       )
     snake_case_				:  Union[str, Any]       =			candidate_labels
     snake_case_				:  Dict       =			[hypothesis_template.format(lowercase_       ) for x in candidate_labels]
     snake_case_				:  List[str]       =			self.tokenizer(lowercase_						,  return_tensors=self.framework						,  padding=lowercase_       )
     snake_case_				:  Optional[Any]       =			[text_inputs]
     return inputs

 def 		_snake_case      (  self	: Optional[Any]						,  lowercase_	: int       ):
     snake_case_				:  List[str]       =			model_inputs.pop('''candidate_labels'''       )
     snake_case_				:  Any       =			model_inputs.pop('''text_inputs'''       )
     if isinstance(text_inputs[0]						,  lowercase_       ):
         snake_case_				:  List[Any]       =			text_inputs[0]
     else:
         # Batching case.
         snake_case_				:  Any       =			text_inputs[0][0]

     snake_case_				:  Any       =			self.model(**lowercase_						,  **lowercase_       )

     snake_case_				:  Optional[Any]       =			{
         '''candidate_labels''': candidate_labels,
         '''logits''': outputs.logits_per_image,
     }
     return model_outputs






 def 		_snake_case      (  self	: Any						,  lowercase_	: List[Any]       ):
     snake_case_				:  Union[str, Any]       =			model_outputs.pop('''candidate_labels'''       )
     snake_case_				:  Dict       =			model_outputs['''logits'''][0]
     if self.framework == "pt":
         snake_case_				:  Dict       =			logits.softmax(dim=-1       ).squeeze(-1       )
         snake_case_				:  List[str]       =			probs.tolist()
         if not isinstance(lowercase_						,  lowercase_       ):
             snake_case_				:  Dict       =			[scores]
     elif self.framework == "tf":
         snake_case_				:  Optional[int]       =			stable_softmax(lowercase_						,  axis=-1       )
         snake_case_				:  Optional[int]       =			probs.numpy().tolist()
     else:
         raise ValueError(f"Unsupported framework: {self.framework}"       )

     snake_case_				:  str       =			[
         {'''score''': score, '''label''': candidate_label}
         for score, candidate_label in sorted(zip(lowercase_						,  lowercase_       )						,  key=lambda lowercase_       : -x[0]       )
     ]
     return result










"""simple docstring"""

import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, 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 (    lowerCAmelCase__):

 def __init__(  self	: List[Any]						,  *lowercase_	: List[Any]						,  lowercase_	: Optional[Any]=None						,  lowercase_	: Tuple=None						,  **lowercase_	: Union[str, Any]       ):
     super().__init__(*lowercase_						,  **lowercase_       )
     snake_case_				:  str       =			eval_examples
     snake_case_				:  Optional[Any]       =			post_process_function

 def 		_snake_case      (  self	: Union[str, Any]						,  lowercase_	: Optional[Dataset] = None						,  lowercase_	: str=None						,  lowercase_	: Optional[List[str]] = None						,  lowercase_	: str = "eval"						,  **lowercase_	: Dict						,  ):
     snake_case_				:  int       =			gen_kwargs.copy()
     snake_case_				:  Dict       =			(
         gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length'''       ) is not None else self.args.generation_max_length
     )
     snake_case_				:  Tuple       =			(
         gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams'''       ) is not None else self.args.generation_num_beams
     )
     snake_case_				:  Optional[Any]       =			gen_kwargs

     snake_case_				:  Optional[int]       =			self.eval_dataset if eval_dataset is None else eval_dataset
     snake_case_				:  Optional[Any]       =			self.get_eval_dataloader(lowercase_       )
     snake_case_				:  Dict       =			self.eval_examples if eval_examples is None else eval_examples

     # Temporarily disable metric computation, we will do it in the loop here.
     snake_case_				:  Optional[int]       =			self.compute_metrics
     snake_case_				:  str       =			None
     snake_case_				:  int       =			time.time()
     snake_case_				:  Any       =			self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
     try:
         snake_case_				:  str       =			eval_loop(
             lowercase_						,  description='''Evaluation'''						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=lowercase_						,  metric_key_prefix=lowercase_						,  )
     finally:
         snake_case_				:  Optional[int]       =			compute_metrics
     snake_case_				:  Dict       =			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(
             lowercase_						,  lowercase_						,  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
         snake_case_				:  Tuple       =			self.post_process_function(lowercase_						,  lowercase_						,  lowercase_       )
         snake_case_				:  Optional[int]       =			self.compute_metrics(lowercase_       )

         # Prefix all keys with metric_key_prefix + '_'
         for key in list(metrics.keys()       ):
             if not key.startswith(f"{metric_key_prefix}_"       ):
                 snake_case_				:  int       =			metrics.pop(lowercase_       )

         metrics.update(output.metrics       )
     else:
         snake_case_				:  Tuple       =			output.metrics

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

     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()       )

     snake_case_				:  str       =			self.callback_handler.on_evaluate(self.args						,  self.state						,  self.control						,  lowercase_       )
     return metrics






 def 		_snake_case      (  self	: Any						,  lowercase_	: int						,  lowercase_	: List[str]						,  lowercase_	: str=None						,  lowercase_	: str = "test"						,  **lowercase_	: Dict       ):
     snake_case_				:  Dict       =			gen_kwargs.copy()

     snake_case_				:  Dict       =			self.get_test_dataloader(lowercase_       )

     # Temporarily disable metric computation, we will do it in the loop here.
     snake_case_				:  Tuple       =			self.compute_metrics
     snake_case_				:  int       =			None
     snake_case_				:  List[Any]       =			time.time()
     snake_case_				:  int       =			self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
     try:
         snake_case_				:  List[str]       =			eval_loop(
             lowercase_						,  description='''Prediction'''						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=lowercase_						,  metric_key_prefix=lowercase_						,  )
     finally:
         snake_case_				:  str       =			compute_metrics

     snake_case_				:  int       =			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(
             lowercase_						,  lowercase_						,  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

     snake_case_				:  Tuple       =			self.post_process_function(lowercase_						,  lowercase_						,  lowercase_						,  '''predict'''       )
     snake_case_				:  Dict       =			self.compute_metrics(lowercase_       )

     # Prefix all keys with metric_key_prefix + '_'
     for key in list(metrics.keys()       ):
         if not key.startswith(f"{metric_key_prefix}_"       ):
             snake_case_				:  Union[str, Any]       =			metrics.pop(lowercase_       )
     metrics.update(output.metrics       )
     return PredictionOutput(predictions=predictions.predictions						,  label_ids=predictions.label_ids						,  metrics=lowercase_       )





