




from unittest import TestCase

from datasets import Sequence, Value
from datasets.arrow_dataset import Dataset



class    lowercase_		(SCREAMING_SNAKE_CASE__ ):



						def 	__a					(			self	:   List[Any]  ):

								"""simple docstring"""

								return [
								    {"col_1": 3, "col_2": "a"},
								    {"col_1": 2, "col_2": "b"},
								    {"col_1": 1, "col_2": "c"},
								    {"col_1": 0, "col_2": "d"},
								]



						def 	__a					(			self	:   List[Any]  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							{'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
								return Dataset.from_dict(snake_case__  )



						def 	__a					(			self	:   List[Any]  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							self._create_example_records()
								SCREAMING_SNAKE_CASE_					      =							Dataset.from_list(snake_case__  )
								self.assertListEqual(dset.column_names					,							['col_1', 'col_2']  )
								for i, r in enumerate(snake_case__  ):
										self.assertDictEqual(snake_case__					,							example_records[i]  )



						def 	__a					(			self	:   Optional[int]  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							self._create_example_records()
								SCREAMING_SNAKE_CASE_					      =							Dataset.from_list(snake_case__  )
								SCREAMING_SNAKE_CASE_					      =							Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]}  )
								self.assertEqual(dset.info					,							dset_from_dict.info  )



						def 	__a					(			self	:   Union[str, Any]  ):  # checks what happens with missing columns

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							[{'col_1': 1}, {'col_2': 'x'}]
								SCREAMING_SNAKE_CASE_					      =							Dataset.from_list(snake_case__  )
								self.assertDictEqual(dset[0]					,							{'col_1': 1}  )
								self.assertDictEqual(dset[1]					,							{'col_1': None}  )  # NB: first record is used for columns



						def 	__a					(			self	:   Optional[int]  ):  # checks if the type can be inferred from the second record

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							[{'col_1': []}, {'col_1': [1, 2]}]
								SCREAMING_SNAKE_CASE_					      =							Dataset.from_list(snake_case__  )
								self.assertEqual(dset.info.features['col_1']					,							Sequence(Value('int64'  )  )  )






						def 	__a					(			self	:   int  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							Dataset.from_list([]  )
								self.assertEqual(len(snake_case__  )					,							0  )
								self.assertListEqual(dset.column_names					,							[]  )





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:     Optional[int]									= logging.get_logger(__name__)



@add_end_docstrings(SCREAMING_SNAKE_CASE__ )
class    lowercase_		(SCREAMING_SNAKE_CASE__ ):



						def __init__(			self	:   Any					,							**snake_case__	:   str  ):

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

								"""simple docstring"""

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



						def 	__a					(			self	:   str					,							**snake_case__	:   str  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							{}
								if "candidate_labels" in kwargs:
										SCREAMING_SNAKE_CASE_					      =							kwargs['candidate_labels']
								if "hypothesis_template" in kwargs:
										SCREAMING_SNAKE_CASE_					      =							kwargs['hypothesis_template']

								return preprocess_params, {}, {}



						def 	__a					(			self	:   List[str]					,							snake_case__	:   Optional[int]					,							snake_case__	:   Optional[Any]=None					,							snake_case__	:   List[str]="This is a photo of {}."  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							load_image(snake_case__  )
								SCREAMING_SNAKE_CASE_					      =							self.image_processor(images=[image]					,							return_tensors=self.framework  )
								SCREAMING_SNAKE_CASE_					      =							candidate_labels
								SCREAMING_SNAKE_CASE_					      =							[hypothesis_template.format(snake_case__  ) for x in candidate_labels]
								SCREAMING_SNAKE_CASE_					      =							self.tokenizer(snake_case__					,							return_tensors=self.framework					,							padding=snake_case__  )
								SCREAMING_SNAKE_CASE_					      =							[text_inputs]
								return inputs



						def 	__a					(			self	:   List[Any]					,							snake_case__	:   Any  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							model_inputs.pop('candidate_labels'  )
								SCREAMING_SNAKE_CASE_					      =							model_inputs.pop('text_inputs'  )
								if isinstance(text_inputs[0]					,							snake_case__  ):
										SCREAMING_SNAKE_CASE_					      =							text_inputs[0]
								else:
										# Batching case.
										SCREAMING_SNAKE_CASE_					      =							text_inputs[0][0]

								SCREAMING_SNAKE_CASE_					      =							self.model(**snake_case__					,							**snake_case__  )

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






						def 	__a					(			self	:   List[Any]					,							snake_case__	:   Optional[Any]  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							model_outputs.pop('candidate_labels'  )
								SCREAMING_SNAKE_CASE_					      =							model_outputs['logits'][0]
								if self.framework == "pt":
										SCREAMING_SNAKE_CASE_					      =							logits.softmax(dim=-1  ).squeeze(-1  )
										SCREAMING_SNAKE_CASE_					      =							probs.tolist()
										if not isinstance(snake_case__					,							snake_case__  ):
												SCREAMING_SNAKE_CASE_					      =							[scores]
								elif self.framework == "tf":
										SCREAMING_SNAKE_CASE_					      =							stable_softmax(snake_case__					,							axis=-1  )
										SCREAMING_SNAKE_CASE_					      =							probs.numpy().tolist()
								else:
										raise ValueError(f'''Unsupported framework: {self.framework}'''  )

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