


'''simple docstring'''



import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


__lowercase	:						int       =	logging.get_logger(__name__)






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   List[str]=None						,      _SCREAMING_SNAKE_CASE      :   Optional[Any]=None   ):
					return field(default_factory=lambda: default						,      metadata=__lowerCamelCase   )





@dataclass
class 							__UpperCamelCase				:
	A_				=    list_field(
	    default=[]		,      metadata={
	        "help": (
	            "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"
	            " of all available models"
	        )
	    }		,      )

	A_				=    list_field(
	    default=[8]		,      metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"}					)

	A_				=    list_field(
	    default=[8, 32, 128, 512]		,      metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"}		,      )

	A_				=    field(
	    default=A_		,      metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."}		,      )
	A_				=    field(
	    default=A_		,      metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."}		,      )
	A_				=    field(
	    default=A_		,      metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."}					)
	A_				=    field(default=A_		,      metadata={"help": "Use FP16 to accelerate inference."}					)
	A_				=    field(default=A_		,      metadata={"help": "Benchmark training of model"}					)
	A_				=    field(default=A_		,      metadata={"help": "Verbose memory tracing"}					)
	A_				=    field(
	    default=A_		,      metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."}		,      )
	A_				=    field(
	    default=A_		,      metadata={
	        "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"
	    }		,      )
	A_				=    field(default=A_		,      metadata={"help": "Trace memory line by line"}					)
	A_				=    field(default=A_		,      metadata={"help": "Save result to a CSV file"}					)
	A_				=    field(default=A_		,      metadata={"help": "Save all print statements in a log file"}					)
	A_				=    field(default=A_		,      metadata={"help": "Whether to print environment information"}					)
	A_				=    field(
	    default=A_		,      metadata={
	        "help": (
	            "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"
	            " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"
	            " for debugging / testing and on TPU."
	        )
	    }		,      )
	A_				=    field(
	    default=f"""inference_time_{round(time()					)}.csv"""		,      metadata={"help": "CSV filename used if saving time results to csv."}		,      )
	A_				=    field(
	    default=f"""inference_memory_{round(time()					)}.csv"""		,      metadata={"help": "CSV filename used if saving memory results to csv."}		,      )
	A_				=    field(
	    default=f"""train_time_{round(time()					)}.csv"""		,      metadata={"help": "CSV filename used if saving time results to csv for training."}		,      )
	A_				=    field(
	    default=f"""train_memory_{round(time()					)}.csv"""		,      metadata={"help": "CSV filename used if saving memory results to csv for training."}		,      )
	A_				=    field(
	    default=f"""env_info_{round(time()					)}.csv"""		,      metadata={"help": "CSV filename used if saving environment information."}		,      )
	A_				=    field(
	    default=f"""log_{round(time()					)}.csv"""		,      metadata={"help": "Log filename used if print statements are saved in log."}		,      )
	A_				=    field(default=3		,      metadata={"help": "Times an experiment will be run."}					)
	A_				=    field(
	    default=A_		,      metadata={
	        "help": (
	            "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"
	            " model weights."
	        )
	    }		,      )




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						warnings.warn(
						    f"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils"""
						    ' are deprecated in general and it is advised to use external Benchmarking libraries '
						    ' to benchmark Transformer models.'						,				_snake_case						,				)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						return json.dumps(dataclasses.asdict(self							)						,				indent=2							)




	@property
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						if len(self.models							) <= 0:
											raise ValueError(
											    'Please make sure you provide at least one model name / model identifier, *e.g.* `--models'
											    ' bert-base-cased` or `args.models = [\'bert-base-cased\'].'							)
						return self.models





	@property
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						if not self.multi_process:
											return False
						elif self.is_tpu:
											logger.info('Multiprocessing is currently not possible on TPU.'							)
											return False
						else:
											return True








"""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

lowerCAmelCase_   						=   logging.get_logger(__name__)
@add_end_docstrings(A_    )
class        __A       (	A_    ):







		'''simple docstring'''





		def __init__(	self						:  List[str]			,**_snake_case						:  Dict						)					->		List[Any]:






				"""simple docstring"""



				super().__init__(**_snake_case						)

				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						:  Optional[int]			,_snake_case						:  Union[str, List[str], "Image", List["Image"]]			,**_snake_case						:  int						)					->		Optional[Any]:






				"""simple docstring"""



				return super().__call__(_snake_case			,**_snake_case						)







		def 					UpperCAmelCase    (	self						:  Dict			,**_snake_case						:  Optional[int]						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    List[str]				=			{}
				if "candidate_labels" in kwargs:
						lowercase__   :    Any				=			kwargs['''candidate_labels''']
				if "hypothesis_template" in kwargs:
						lowercase__   :    Optional[Any]				=			kwargs['''hypothesis_template''']

				return preprocess_params, {}, {}







		def 					UpperCAmelCase    (	self						:  Optional[Any]			,_snake_case						:  Optional[int]			,_snake_case						:  Dict=None			,_snake_case						:  Union[str, Any]="This is a photo of {}."						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			load_image(_snake_case						)
				lowercase__   :    int				=			self.image_processor(images=[image]			,return_tensors=self.framework						)
				lowercase__   :    str				=			candidate_labels
				lowercase__   :    Dict				=			[hypothesis_template.format(_snake_case						) for x in candidate_labels]
				lowercase__   :    Any				=			self.tokenizer(_snake_case			,return_tensors=self.framework			,padding=_snake_case						)
				lowercase__   :    Optional[int]				=			[text_inputs]
				return inputs







		def 					UpperCAmelCase    (	self						:  Optional[Any]			,_snake_case						:  Optional[int]						)					->		List[Any]:






				"""simple docstring"""



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

				lowercase__   :    Tuple				=			self.model(**_snake_case			,**_snake_case						)

				lowercase__   :    Union[str, Any]				=			{
				    '''candidate_labels''': candidate_labels,
				    '''logits''': outputs.logits_per_image,
				}
				return model_outputs







		def 					UpperCAmelCase    (	self						:  Any			,_snake_case						:  Tuple						)					->		Any:






				"""simple docstring"""



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

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