




'''simple docstring'''
import importlib
import os
import sys


# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append(".")





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		List[Any]:
			A_									= test_file.split(os.path.sep     )
			if components[0:2] != ["tests", "models"]:
						raise ValueError(
						    '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got '
						    F'{test_file} instead.'     )
			A_									= components[-1]
			if not test_fn.endswith('py'     ):
						raise ValueError(F'`test_file` should be a python file. Got {test_fn} instead.'     )
			if not test_fn.startswith('test_modeling_'     ):
						raise ValueError(
						    F'`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.'     )

			A_									= components[:-1] + [test_fn.replace('.py'       ,''     )]
			A_									= '.'.join(SCREAMING_SNAKE_CASE_     )

			return test_module_path





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		int:
			A_									= get_module_path(SCREAMING_SNAKE_CASE_     )
			A_									= importlib.import_module(SCREAMING_SNAKE_CASE_     )

			return test_module





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		Optional[Any]:
			A_									= []
			A_									= get_test_module(SCREAMING_SNAKE_CASE_     )
			for attr in dir(SCREAMING_SNAKE_CASE_     ):
						if attr.endswith('ModelTester'     ):
									tester_classes.append(getattr(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )     )

    # sort with class names
			return sorted(SCREAMING_SNAKE_CASE_       ,key=lambda SCREAMING_SNAKE_CASE_     : x.__name__     )





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		Union[str, Any]:
			A_									= []
			A_									= get_test_module(SCREAMING_SNAKE_CASE_     )
			for attr in dir(SCREAMING_SNAKE_CASE_     ):
						A_									= getattr(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )
						# (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
						# `all_model_classes` is not empty (which also excludes other special classes).
						A_									= getattr(SCREAMING_SNAKE_CASE_       ,'all_model_classes'       ,[]     )
						if len(SCREAMING_SNAKE_CASE_     ) > 0:
									test_classes.append(SCREAMING_SNAKE_CASE_     )

    # sort with class names
			return sorted(SCREAMING_SNAKE_CASE_       ,key=lambda SCREAMING_SNAKE_CASE_     : x.__name__     )





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		List[Any]:
			A_									= get_test_classes(SCREAMING_SNAKE_CASE_     )
			A_									= set()
			for test_class in test_classes:
						model_classes.update(test_class.all_model_classes     )

			# sort with class names
			return sorted(SCREAMING_SNAKE_CASE_       ,key=lambda SCREAMING_SNAKE_CASE_     : x.__name__     )





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		int:
			A_									= test_class()
			if hasattr(SCREAMING_SNAKE_CASE_       ,'setUp'     ):
						test.setUp()

			A_									= None
			if hasattr(SCREAMING_SNAKE_CASE_       ,'model_tester'     ):
						# `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
						if test.model_tester is not None:
									A_									= test.model_tester.__class__

			return model_tester





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )		->		Tuple:
			A_									= get_test_classes(SCREAMING_SNAKE_CASE_     )

			A_									= []
			for test_class in test_classes:
						if model_class in test_class.all_model_classes:
									target_test_classes.append(SCREAMING_SNAKE_CASE_     )

    # sort with class names
			return sorted(SCREAMING_SNAKE_CASE_       ,key=lambda SCREAMING_SNAKE_CASE_     : x.__name__     )





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )		->		Optional[int]:
			A_									= get_test_classes_for_model(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )

			A_									= []
			for test_class in test_classes:
						A_									= get_model_tester_from_test_class(SCREAMING_SNAKE_CASE_     )
						if tester_class is not None:
									tester_classes.append(SCREAMING_SNAKE_CASE_     )

    # sort with class names
			return sorted(SCREAMING_SNAKE_CASE_       ,key=lambda SCREAMING_SNAKE_CASE_     : x.__name__     )





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		Union[str, Any]:
			A_									= get_test_classes(SCREAMING_SNAKE_CASE_     )
			A_									= {test_class: get_model_tester_from_test_class(SCREAMING_SNAKE_CASE_     ) for test_class in test_classes}
			return test_tester_mapping





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		List[str]:
			A_									= get_model_classes(SCREAMING_SNAKE_CASE_     )
			A_									= {
			    model_class: get_test_classes_for_model(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     ) for model_class in model_classes
			}
			return model_test_mapping





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		str:
			A_									= get_model_classes(SCREAMING_SNAKE_CASE_     )
			A_									= {
			    model_class: get_tester_classes_for_model(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     ) for model_class in model_classes
			}
			return model_to_tester_mapping






def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		str:
			if isinstance(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     ):
						return o
			elif isinstance(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     ):
						return o.__name__
			elif isinstance(SCREAMING_SNAKE_CASE_       ,(list, tuple)     ):
						return [to_json(SCREAMING_SNAKE_CASE_     ) for x in o]
			elif isinstance(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     ):
						return {to_json(SCREAMING_SNAKE_CASE_     ): to_json(SCREAMING_SNAKE_CASE_     ) for k, v in o.items()}
			else:
						return o










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

_SCREAMING_SNAKE_CASE			=						logging.get_logger(__name__)
@add_end_docstrings(lowerCAmelCase				)
class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					def __init__(	self     :						int      ,       **_lowercase     :						List[Any])    ->							Union[str, Any]:
								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     :						Optional[Any]      ,       _lowercase     :						Union[str, List[str], "Image", List["Image"]]      ,       **_lowercase     :						List[Any])    ->							Any:
								return super().__call__(_lowercase      ,       **_lowercase)



					def     __snake_case						(	self     :						int      ,       **_lowercase     :						Union[str, Any])    ->							Any:
								A_									= {}
								if "candidate_labels" in kwargs:
											A_									= kwargs['candidate_labels']
								if "hypothesis_template" in kwargs:
											A_									= kwargs['hypothesis_template']

								return preprocess_params, {}, {}



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



					def     __snake_case						(	self     :						Optional[int]      ,       _lowercase     :						Tuple)    ->							Optional[int]:
								A_									= model_inputs.pop('candidate_labels')
								A_									= model_inputs.pop('text_inputs')
								if isinstance(text_inputs[0]      ,       _lowercase):
											A_									= text_inputs[0]
								else:
											# Batching case.
											A_									= text_inputs[0][0]

								A_									= self.model(**_lowercase      ,       **_lowercase)

								A_									= {
								    'candidate_labels': candidate_labels,
								    'logits': outputs.logits_per_image,
								}
								return model_outputs



					def     __snake_case						(	self     :						List[str]      ,       _lowercase     :						int)    ->							Optional[int]:
								A_									= model_outputs.pop('candidate_labels')
								A_									= model_outputs['logits'][0]
								if self.framework == "pt":
											A_									= logits.softmax(dim=-1).squeeze(-1)
											A_									= probs.tolist()
											if not isinstance(_lowercase      ,       _lowercase):
														A_									= [scores]
								elif self.framework == "tf":
											A_									= stable_softmax(_lowercase      ,       axis=-1)
											A_									= probs.numpy().tolist()
								else:
											raise ValueError(F'Unsupported framework: {self.framework}')

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




