





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(SCREAMING_SNAKE_CASE__       )
class 		UpperCamelCase__			(				SCREAMING_SNAKE_CASE__       ):



     '''simple docstring'''

     def __init__(							self						:   Dict						,**lowerCamelCase__						:   Union[str, Any]	)					->		Tuple:




           '''simple docstring'''


           super().__init__(**A__	)

           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]						,lowerCamelCase__						:   Optional[int]						,**lowerCamelCase__						:   List[str]	)					->		str:




           '''simple docstring'''


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






     def     SCREAMING_SNAKE_CASE__  (							self						:   List[Any]						,**lowerCamelCase__						:   Optional[int]	)					->		int:




           '''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     SCREAMING_SNAKE_CASE__  (							self						:   Any						,lowerCamelCase__						:   str						,lowerCamelCase__						:   str=None						,lowerCamelCase__						:   Union[str, Any]="This is a photo of {}."	)					->		Optional[int]:




           '''simple docstring'''


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






     def     SCREAMING_SNAKE_CASE__  (							self						:   Optional[Any]						,lowerCamelCase__						:   Tuple	)					->		List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						model_inputs.pop("""candidate_labels"""	)
           SCREAMING_SNAKE_CASE		=						model_inputs.pop("""text_inputs"""	)
           if isinstance(text_inputs[0]						,A__	):
                 SCREAMING_SNAKE_CASE		=						text_inputs[0]
           else:
                 # Batching case.
                 SCREAMING_SNAKE_CASE		=						text_inputs[0][0]

           SCREAMING_SNAKE_CASE		=						self.model(**A__						,**A__	)

           SCREAMING_SNAKE_CASE		=						{
               """candidate_labels""": candidate_labels,
               """logits""": outputs.logits_per_image,
           }
           return model_outputs






     def     SCREAMING_SNAKE_CASE__  (							self						:   List[str]						,lowerCamelCase__						:   List[Any]	)					->		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(A__						,A__	):
                       SCREAMING_SNAKE_CASE		=						[scores]
           elif self.framework == "tf":
                 SCREAMING_SNAKE_CASE		=						stable_softmax(A__						,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(A__						,A__	)						,key=lambda lowerCamelCase__	: -x[0]	)
           ]
           return result









from typing import List, Optional, TypeVar

from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .info import DatasetInfo
from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets
from .splits import NamedSplit
from .utils import logging
from .utils.py_utils import Literal


SCREAMING_SNAKE_CASE_						       =	logging.get_logger(__name__)


SCREAMING_SNAKE_CASE_						       =	TypeVar("""DatasetType""", Dataset, IterableDataset)



def        __lowercase       (				_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE = None			,						_SCREAMING_SNAKE_CASE = None			,						_SCREAMING_SNAKE_CASE = None			,						_SCREAMING_SNAKE_CASE = None			,						_SCREAMING_SNAKE_CASE = "first_exhausted"			,						)			->       DatasetType:


      '''simple docstring'''


      from .arrow_dataset import Dataset
      from .iterable_dataset import IterableDataset

      if not datasets:
            raise ValueError("""Unable to interleave an empty list of datasets."""     )
      for i, dataset in enumerate(_SCREAMING_SNAKE_CASE     ):
            if not isinstance(_SCREAMING_SNAKE_CASE			,						(Dataset, IterableDataset)     ):
                  if isinstance(_SCREAMING_SNAKE_CASE			,						(DatasetDict, IterableDatasetDict)     ):
                        if not dataset:
                              raise ValueError(
                                  F"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} """
                                  """is an empty dataset dictionary."""     )
                        raise ValueError(
                            F"""Dataset at position {i} has at least one split: {list(_SCREAMING_SNAKE_CASE     )}\n"""
                            F"""Please pick one to interleave with the other datasets, for example: dataset['{next(iter(_SCREAMING_SNAKE_CASE     )     )}']"""     )
                  raise ValueError(
                      F"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_SCREAMING_SNAKE_CASE     ).__name__}."""     )
            if i == 0:
                  SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE		=						(
                      (Dataset, IterableDataset) if isinstance(_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE     ) else (IterableDataset, Dataset)
                  )
            elif not isinstance(_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE     ):
                  raise ValueError(
                      F"""Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects."""     )
      if stopping_strategy not in ["first_exhausted", "all_exhausted"]:
            raise ValueError(F"""{stopping_strategy} is not supported. Please enter a valid stopping_strategy."""     )
      if dataset_type is Dataset:
            return _interleave_map_style_datasets(
                _SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE			,						info=_SCREAMING_SNAKE_CASE			,						split=_SCREAMING_SNAKE_CASE			,						stopping_strategy=_SCREAMING_SNAKE_CASE     )
      else:
            return _interleave_iterable_datasets(
                _SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE			,						info=_SCREAMING_SNAKE_CASE			,						split=_SCREAMING_SNAKE_CASE			,						stopping_strategy=_SCREAMING_SNAKE_CASE     )



def        __lowercase       (				_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE = None			,						_SCREAMING_SNAKE_CASE = None			,						_SCREAMING_SNAKE_CASE = 0			,						)			->       DatasetType:


      '''simple docstring'''


      if not dsets:
            raise ValueError("""Unable to concatenate an empty list of datasets."""     )
      for i, dataset in enumerate(_SCREAMING_SNAKE_CASE     ):
            if not isinstance(_SCREAMING_SNAKE_CASE			,						(Dataset, IterableDataset)     ):
                  if isinstance(_SCREAMING_SNAKE_CASE			,						(DatasetDict, IterableDatasetDict)     ):
                        if not dataset:
                              raise ValueError(
                                  F"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} """
                                  """is an empty dataset dictionary."""     )
                        raise ValueError(
                            F"""Dataset at position {i} has at least one split: {list(_SCREAMING_SNAKE_CASE     )}\n"""
                            F"""Please pick one to interleave with the other datasets, for example: dataset['{next(iter(_SCREAMING_SNAKE_CASE     )     )}']"""     )
                  raise ValueError(
                      F"""Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_SCREAMING_SNAKE_CASE     ).__name__}."""     )
            if i == 0:
                  SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE		=						(
                      (Dataset, IterableDataset) if isinstance(_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE     ) else (IterableDataset, Dataset)
                  )
            elif not isinstance(_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE     ):
                  raise ValueError(
                      F"""Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects."""     )
      if dataset_type is Dataset:
            return _concatenate_map_style_datasets(_SCREAMING_SNAKE_CASE			,						info=_SCREAMING_SNAKE_CASE			,						split=_SCREAMING_SNAKE_CASE			,						axis=_SCREAMING_SNAKE_CASE     )
      else:
            return _concatenate_iterable_datasets(_SCREAMING_SNAKE_CASE			,						info=_SCREAMING_SNAKE_CASE			,						split=_SCREAMING_SNAKE_CASE			,						axis=_SCREAMING_SNAKE_CASE     )


