'''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_			    =							logging.get_logger(__name__)




@add_end_docstrings(__lowercase    )
class  __magic_name__  (		__lowercase    ):





   """simple docstring"""




   def __init__(	self					:  Any		,  **_lowercase					:  Any							):



    """simple docstring"""



    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					:  List[str]		,  _lowercase					:  Union[str, List[str], "Image", List["Image"]]		,  **_lowercase					:  Dict							):



    """simple docstring"""



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



   def   lowerCAmelCase						(	self					:  int		,  **_lowercase					:  Any							):



    """simple docstring"""



    _UpperCamelCase:     Dict							= {}
    if "candidate_labels" in kwargs:
     _UpperCamelCase:     List[str]							= kwargs["candidate_labels"]
    if "hypothesis_template" in kwargs:
     _UpperCamelCase:     List[Any]							= kwargs["hypothesis_template"]

    return preprocess_params, {}, {}



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



    """simple docstring"""



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



   def   lowerCAmelCase						(	self					:  int		,  _lowercase					:  str							):



    """simple docstring"""



    _UpperCamelCase:     int							= model_inputs.pop('''candidate_labels'''							)
    _UpperCamelCase:     Optional[int]							= model_inputs.pop('''text_inputs'''							)
    if isinstance(text_inputs[0]		,  _lowercase							):
     _UpperCamelCase:     int							= text_inputs[0]
    else:
     # Batching case.
     _UpperCamelCase:     Optional[int]							= text_inputs[0][0]

    _UpperCamelCase:     Any							= self.model(**_lowercase		,  **_lowercase							)

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



   def   lowerCAmelCase						(	self					:  Optional[int]		,  _lowercase					:  Union[str, Any]							):



    """simple docstring"""



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

    _UpperCamelCase:     Any							= [
        {"score": score, "label": candidate_label}
        for score, candidate_label in sorted(zip(_lowercase		,  _lowercase							)		,  key=lambda _lowercase							: -x[0]							)
    ]
    return result
import pytest

from datasets.splits import SplitDict, SplitInfo
from datasets.utils.py_utils import asdict




@pytest.mark.parametrize(
    '''split_dict'''  ,					[
        SplitDict(),
        SplitDict({'''train''': SplitInfo(name='''train'''  ,					num_bytes=1_337  ,					num_examples=42  ,					dataset_name='''my_dataset'''		)}		),
        SplitDict({'''train''': SplitInfo(name='''train'''  ,					num_bytes=1_337  ,					num_examples=42		)}		),
        SplitDict({'''train''': SplitInfo()}		),
    ]  ,					)
def       lowerCAmelCase_     (		lowercase:							SplitDict		)    ->				List[str]:







 '''simple docstring'''
 _UpperCamelCase:     List[str]							= split_dict._to_yaml_list()
 assert len(lowercase		) == len(lowercase		)
 _UpperCamelCase:     Tuple							= SplitDict._from_yaml_list(lowercase		)
 for split_name, split_info in split_dict.items():
  # dataset_name field is deprecated, and is therefore not part of the YAML dump
  _UpperCamelCase:     Optional[Any]							= None
  # the split name of split_dict takes over the name of the split info object
  _UpperCamelCase:     Any							= split_name
 assert split_dict == reloaded





@pytest.mark.parametrize(
    '''split_info'''  ,					[SplitInfo(), SplitInfo(dataset_name=lowercase		), SplitInfo(dataset_name='''my_dataset'''		)]		)
def       lowerCAmelCase_     (		lowercase:							str		)    ->				Tuple:







 '''simple docstring'''
 # For backward compatibility, we need asdict(split_dict) to return split info dictrionaries with the "dataset_name"
 # field even if it's deprecated. This way old versionso of `datasets` can still reload dataset_infos.json files
 _UpperCamelCase:     Optional[Any]							= asdict(SplitDict({'''train''': split_info}		)		)
 assert "dataset_name" in split_dict_asdict["train"]
 assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name