

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

_snake_case         =  logging.get_logger(__name__)


@add_end_docstrings(lowerCamelCase_  )
class        a__  (							lowerCamelCase_  ):


   def __init__(			self      ,    **_UpperCamelCase  ):





      """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      ,    _UpperCamelCase      ,    **_UpperCamelCase  ):





      """simple docstring"""





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


   def 						_lowerCamelCase       (			self      ,    **_UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       {}
      if "candidate_labels" in kwargs:
         _lowercase      :				Union[str, Any]      					=       kwargs["candidate_labels"]
      if "hypothesis_template" in kwargs:
         _lowercase      :				Any      					=       kwargs["hypothesis_template"]

      return preprocess_params, {}, {}


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase=None      ,    _UpperCamelCase="This is a photo of {}."  ):





      """simple docstring"""





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


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				List[Any]      					=       model_inputs.pop("candidate_labels"  )
      _lowercase      :				List[str]      					=       model_inputs.pop("text_inputs"  )
      if isinstance(text_inputs[0]      ,    __A  ):
         _lowercase      :				int      					=       text_inputs[0]
      else:
         # Batching case.
         _lowercase      :				str      					=       text_inputs[0][0]

      _lowercase      :				int      					=       self.model(**__A      ,    **__A  )

      _lowercase      :				Optional[int]      					=       {
          "candidate_labels": candidate_labels,
          "logits": outputs.logits_per_image,
      }
      return model_outputs






   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





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

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









'''simple docstring'''
import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


_snake_case         =  logging.getLogger()


@unittest.skip('Temporarily disable the doc tests.'  )
@require_torch
@require_tf
@slow
class        a__  (							unittest.TestCase  ):


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase = None      ,    _UpperCamelCase = None      ,    _UpperCamelCase = None      ,    _UpperCamelCase = True      ,    ):





      """simple docstring"""





      _lowercase      :				str      					=       [file for file in os.listdir(_UpperCamelCase  ) if os.path.isfile(os.path.join(_UpperCamelCase      ,    _UpperCamelCase  )  )]

      if identifier is not None:
         _lowercase      :				str      					=       [file for file in files if identifier in file]

      if n_identifier is not None:
         if isinstance(_UpperCamelCase      ,    _UpperCamelCase  ):
            for n_ in n_identifier:
               _lowercase      :				Dict      					=       [file for file in files if n_ not in file]
         else:
            _lowercase      :				Optional[Any]      					=       [file for file in files if n_identifier not in file]

      _lowercase      :				Dict      					=       ignore_files or []
      ignore_files.append("__init__.py"  )
      _lowercase      :				List[str]      					=       [file for file in files if file not in ignore_files]

      for file in files:
         # Open all files
         print("Testing"      ,    _UpperCamelCase  )

         if only_modules:
            _lowercase      :				Optional[Any]      					=       file.split("."  )[0]
            try:
               _lowercase      :				Union[str, Any]      					=       getattr(_UpperCamelCase      ,    _UpperCamelCase  )
               _lowercase      :				Optional[int]      					=       doctest.DocTestSuite(_UpperCamelCase  )
               _lowercase      :				Tuple      					=       unittest.TextTestRunner().run(_UpperCamelCase  )
               self.assertIs(len(result.failures  )      ,    0  )
            except AttributeError:
               logger.info(f'''{module_identifier} is not a module.'''  )
         else:
            _lowercase      :				Optional[Any]      					=       doctest.testfile(str(".." / directory / file  )      ,    optionflags=doctest.ELLIPSIS  )
            self.assertIs(result.failed      ,    0  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Tuple      					=       Path("src/transformers"  )
      _lowercase      :				str      					=       "modeling"
      _lowercase      :				Tuple      					=       [
          "modeling_ctrl.py",
          "modeling_tf_ctrl.py",
      ]
      self.analyze_directory(_UpperCamelCase      ,    identifier=_UpperCamelCase      ,    ignore_files=_UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Optional[int]      					=       Path("src/transformers"  )
      _lowercase      :				Any      					=       "tokenization"
      self.analyze_directory(_UpperCamelCase      ,    identifier=_UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Tuple      					=       Path("src/transformers"  )
      _lowercase      :				Optional[Any]      					=       "configuration"
      self.analyze_directory(_UpperCamelCase      ,    identifier=_UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Union[str, Any]      					=       Path("src/transformers"  )
      _lowercase      :				List[Any]      					=       ["configuration", "modeling", "tokenization"]
      self.analyze_directory(_UpperCamelCase      ,    n_identifier=_UpperCamelCase  )






   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Dict      					=       Path("docs/source"  )
      _lowercase      :				int      					=       ["favicon.ico"]
      self.analyze_directory(_UpperCamelCase      ,    ignore_files=_UpperCamelCase      ,    only_modules=_UpperCamelCase  )






