




'''simple docstring'''



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


UpperCAmelCase_							:	Dict	     =		logging.get_logger(__name__)


UpperCAmelCase_							:	Dict	     =		TypeVar('''DatasetType''', Dataset, IterableDataset)







def       _UpperCamelCase			(_lowerCamelCase				:  List[DatasetType] ,						_lowerCamelCase				:  Optional[List[float]] = None ,						_lowerCamelCase				:  Optional[int] = None ,						_lowerCamelCase				:  Optional[DatasetInfo] = None ,						_lowerCamelCase				:  Optional[NamedSplit] = None ,						_lowerCamelCase				:  Literal["first_exhausted", "all_exhausted"] = "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(_lowerCamelCase						):
          if not isinstance(_lowerCamelCase ,						(Dataset, IterableDataset)						):
               if isinstance(_lowerCamelCase ,						(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(_lowerCamelCase						)}\n'''
                        f'''Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(_lowerCamelCase						)						)}\']'''						)
               raise ValueError(
                   f'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_lowerCamelCase						).__name__}.'''						)
          if i == 0:
               __snake_case       ,     __snake_case            =	(
                   (Dataset, IterableDataset) if isinstance(_lowerCamelCase ,						_lowerCamelCase						) else (IterableDataset, Dataset)
               )
          elif not isinstance(_lowerCamelCase ,						_lowerCamelCase						):
               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(
              _lowerCamelCase ,						_lowerCamelCase ,						_lowerCamelCase ,						info=_lowerCamelCase ,						split=_lowerCamelCase ,						stopping_strategy=_lowerCamelCase						)
     else:
          return _interleave_iterable_datasets(
              _lowerCamelCase ,						_lowerCamelCase ,						_lowerCamelCase ,						info=_lowerCamelCase ,						split=_lowerCamelCase ,						stopping_strategy=_lowerCamelCase						)







def       _UpperCamelCase			(_lowerCamelCase				:  List[DatasetType] ,						_lowerCamelCase				:  Optional[DatasetInfo] = None ,						_lowerCamelCase				:  Optional[NamedSplit] = None ,						_lowerCamelCase				:  int = 0 ,						)-> DatasetType:




     '''simple docstring'''





     if not dsets:
          raise ValueError('''Unable to concatenate an empty list of datasets.'''						)
     for i, dataset in enumerate(_lowerCamelCase						):
          if not isinstance(_lowerCamelCase ,						(Dataset, IterableDataset)						):
               if isinstance(_lowerCamelCase ,						(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(_lowerCamelCase						)}\n'''
                        f'''Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(_lowerCamelCase						)						)}\']'''						)
               raise ValueError(
                   f'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_lowerCamelCase						).__name__}.'''						)
          if i == 0:
               __snake_case       ,     __snake_case            =	(
                   (Dataset, IterableDataset) if isinstance(_lowerCamelCase ,						_lowerCamelCase						) else (IterableDataset, Dataset)
               )
          elif not isinstance(_lowerCamelCase ,						_lowerCamelCase						):
               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(_lowerCamelCase ,						info=_lowerCamelCase ,						split=_lowerCamelCase ,						axis=_lowerCamelCase						)
     else:
          return _concatenate_iterable_datasets(_lowerCamelCase ,						info=_lowerCamelCase ,						split=_lowerCamelCase ,						axis=_lowerCamelCase						)












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

UpperCAmelCase_							:	str	     =		logging.get_logger(__name__)





@add_end_docstrings(__lowerCAmelCase)
class      lowerCAmelCase (			__lowerCAmelCase):


       def __init__( self     ,	**__SCREAMING_SNAKE_CASE	)   ->	Optional[int]:



            '''simple docstring'''




            super().__init__(**__SCREAMING_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     ,	__SCREAMING_SNAKE_CASE     ,	**__SCREAMING_SNAKE_CASE	)   ->	List[Any]:



            '''simple docstring'''




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


       def    lowerCAmelCase   ( self     ,	**__SCREAMING_SNAKE_CASE	)   ->	Tuple:



            '''simple docstring'''




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

            return preprocess_params, {}, {}


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE=None     ,	__SCREAMING_SNAKE_CASE="This is a photo of {}."	)   ->	Optional[Any]:



            '''simple docstring'''




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


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE	)   ->	Dict:



            '''simple docstring'''




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

            __snake_case            =	self.model(**__SCREAMING_SNAKE_CASE     ,	**__SCREAMING_SNAKE_CASE	)

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




       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE	)   ->	str:



            '''simple docstring'''




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

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






