




import copy
import json
import os
import tempfile

from transformers import is_torch_available

from .test_configuration_utils import config_common_kwargs


class 				UpperCamelCase_    ( SCREAMING_SNAKE_CASE_     ):

    '''simple docstring'''






    def __init__(			self      :	Union[str, Any]					, UpperCAmelCase__      :	int					, UpperCAmelCase__      :	Tuple=None					, UpperCAmelCase__      :	Tuple=True					, UpperCAmelCase__      :	str=None					, **UpperCAmelCase__      :	List[str])						->Dict:





           '''simple docstring'''

           A__       =    parent
           A__       =    config_class
           A__       =    has_text_modality
           A__       =    kwargs
           A__       =    common_properties


    def        SCREAMING_SNAKE_CASE							(			self      :	Union[str, Any])						->List[Any]:





           '''simple docstring'''

           A__       =    self.config_class(**self.inputs_dict)
           A__       =    (
               ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""]
               if self.common_properties is None
               else self.common_properties
           )

           # Add common fields for text models
           if self.has_text_modality:
                  common_properties.extend(['''vocab_size'''])

           # Test that config has the common properties as getters
           for prop in common_properties:
                  self.parent.assertTrue(hasattr(__UpperCAmelCase					, __UpperCAmelCase)					, msg=f"""`{prop}` does not exist""")

           # Test that config has the common properties as setter
           for idx, name in enumerate(__UpperCAmelCase):
                  try:
                         setattr(__UpperCAmelCase					, __UpperCAmelCase					, __UpperCAmelCase)
                         self.parent.assertEqual(
                             getattr(__UpperCAmelCase					, __UpperCAmelCase)					, __UpperCAmelCase					, msg=f"""`{name} value {idx} expected, but was {getattr(__UpperCAmelCase					, __UpperCAmelCase)}""")
                  except NotImplementedError:
                         # Some models might not be able to implement setters for common_properties
                         # In that case, a NotImplementedError is raised
                         pass

        # Test if config class can be called with Config(prop_name=..)
           for idx, name in enumerate(__UpperCAmelCase):
                  try:
                         A__       =    self.config_class(**{name: idx})
                         self.parent.assertEqual(
                             getattr(__UpperCAmelCase					, __UpperCAmelCase)					, __UpperCAmelCase					, msg=f"""`{name} value {idx} expected, but was {getattr(__UpperCAmelCase					, __UpperCAmelCase)}""")
                  except NotImplementedError:
                         # Some models might not be able to implement setters for common_properties
                         # In that case, a NotImplementedError is raised
                         pass


    def        SCREAMING_SNAKE_CASE							(			self      :	str)						->List[str]:





           '''simple docstring'''

           A__       =    self.config_class(**self.inputs_dict)
           A__       =    json.loads(config.to_json_string())
           for key, value in self.inputs_dict.items():
                  self.parent.assertEqual(obj[key]					, __UpperCAmelCase)


    def        SCREAMING_SNAKE_CASE							(			self      :	List[str])						->Tuple:





           '''simple docstring'''

           A__       =    self.config_class(**self.inputs_dict)

           with tempfile.TemporaryDirectory() as tmpdirname:
                  A__       =    os.path.join(__UpperCAmelCase					, '''config.json''')
                  config_first.to_json_file(__UpperCAmelCase)
                  A__       =    self.config_class.from_json_file(__UpperCAmelCase)

           self.parent.assertEqual(config_second.to_dict()					, config_first.to_dict())


    def        SCREAMING_SNAKE_CASE							(			self      :	Dict)						->Optional[int]:





           '''simple docstring'''

           A__       =    self.config_class(**self.inputs_dict)

           with tempfile.TemporaryDirectory() as tmpdirname:
                  config_first.save_pretrained(__UpperCAmelCase)
                  A__       =    self.config_class.from_pretrained(__UpperCAmelCase)

           self.parent.assertEqual(config_second.to_dict()					, config_first.to_dict())


    def        SCREAMING_SNAKE_CASE							(			self      :	Any)						->List[Any]:





           '''simple docstring'''

           A__       =    self.config_class(**self.inputs_dict)

           A__       =    """test"""
           with tempfile.TemporaryDirectory() as tmpdirname:
                  A__       =    os.path.join(__UpperCAmelCase					, __UpperCAmelCase)
                  config_first.save_pretrained(__UpperCAmelCase)
                  A__       =    self.config_class.from_pretrained(__UpperCAmelCase					, subfolder=__UpperCAmelCase)

           self.parent.assertEqual(config_second.to_dict()					, config_first.to_dict())


    def        SCREAMING_SNAKE_CASE							(			self      :	Any)						->Dict:





           '''simple docstring'''

           A__       =    self.config_class(**self.inputs_dict					, num_labels=5)
           self.parent.assertEqual(len(config.idalabel)					, 5)
           self.parent.assertEqual(len(config.labelaid)					, 5)

           A__       =    3
           self.parent.assertEqual(len(config.idalabel)					, 3)
           self.parent.assertEqual(len(config.labelaid)					, 3)


    def        SCREAMING_SNAKE_CASE							(			self      :	Optional[Any])						->str:





           '''simple docstring'''

           if self.config_class.is_composition:
                  return
           A__       =    self.config_class()
           self.parent.assertIsNotNone(__UpperCAmelCase)


    def        SCREAMING_SNAKE_CASE							(			self      :	Optional[int])						->List[str]:





           '''simple docstring'''

           A__       =    copy.deepcopy(__UpperCAmelCase)
           A__       =    self.config_class(**__UpperCAmelCase)
           A__       =    []
           for key, value in config_common_kwargs.items():
                  if key == "torch_dtype":
                         if not is_torch_available():
                                continue
                         else:
                                import torch

                                if config.torch_dtype != torch.floataa:
                                       wrong_values.append(('''torch_dtype''', config.torch_dtype, torch.floataa))
                  elif getattr(__UpperCAmelCase					, __UpperCAmelCase) != value:
                         wrong_values.append((key, getattr(__UpperCAmelCase					, __UpperCAmelCase), value))

           if len(__UpperCAmelCase) > 0:
                  A__       =    """\n""".join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values])
                  raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""")





    def        SCREAMING_SNAKE_CASE							(			self      :	Optional[int])						->Tuple:





           '''simple docstring'''

           self.create_and_test_config_common_properties()
           self.create_and_test_config_to_json_string()
           self.create_and_test_config_to_json_file()
           self.create_and_test_config_from_and_save_pretrained()
           self.create_and_test_config_from_and_save_pretrained_subfolder()
           self.create_and_test_config_with_num_labels()
           self.check_config_can_be_init_without_params()
           self.check_config_arguments_init()







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

_lowerCAmelCase      						=	logging.get_logger(__name__)






@add_end_docstrings(SCREAMING_SNAKE_CASE_     )
class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




  def __init__(    self  ,**__UpperCAmelCase      )    ->		Tuple:
      super().__init__(**__UpperCAmelCase      )

      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      )    ->		str:
      return super().__call__(__UpperCAmelCase  ,**__UpperCAmelCase      )




  def 							UpperCAmelCase_	(    self  ,**__UpperCAmelCase      )    ->		str:
      lowerCAmelCase__ :  List[Any]							      =					{}
      if "candidate_labels" in kwargs:
          lowerCAmelCase__ :  int							      =					kwargs["""candidate_labels"""]
      if "hypothesis_template" in kwargs:
          lowerCAmelCase__ :  Optional[int]							      =					kwargs["""hypothesis_template"""]

      return preprocess_params, {}, {}




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase=None  ,__UpperCAmelCase="This is a photo of {}."      )    ->		int:
      lowerCAmelCase__ :  str							      =					load_image(__UpperCAmelCase      )
      lowerCAmelCase__ :  Dict							      =					self.image_processor(images=[image]  ,return_tensors=self.framework      )
      lowerCAmelCase__ :  List[Any]							      =					candidate_labels
      lowerCAmelCase__ :  List[str]							      =					[hypothesis_template.format(__UpperCAmelCase      ) for x in candidate_labels]
      lowerCAmelCase__ :  Optional[Any]							      =					self.tokenizer(__UpperCAmelCase  ,return_tensors=self.framework  ,padding=__UpperCAmelCase      )
      lowerCAmelCase__ :  Tuple							      =					[text_inputs]
      return inputs




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Union[str, Any]:
      lowerCAmelCase__ :  Tuple							      =					model_inputs.pop("""candidate_labels"""      )
      lowerCAmelCase__ :  Union[str, Any]							      =					model_inputs.pop("""text_inputs"""      )
      if isinstance(text_inputs[0]  ,__UpperCAmelCase      ):
          lowerCAmelCase__ :  int							      =					text_inputs[0]
      else:
          # Batching case.
          lowerCAmelCase__ :  Dict							      =					text_inputs[0][0]

      lowerCAmelCase__ :  Any							      =					self.model(**__UpperCAmelCase  ,**__UpperCAmelCase      )

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






  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Any:
      lowerCAmelCase__ :  Union[str, Any]							      =					model_outputs.pop("""candidate_labels"""      )
      lowerCAmelCase__ :  List[str]							      =					model_outputs["""logits"""][0]
      if self.framework == "pt":
          lowerCAmelCase__ :  List[str]							      =					logits.softmax(dim=-1      ).squeeze(-1      )
          lowerCAmelCase__ :  Optional[Any]							      =					probs.tolist()
          if not isinstance(__UpperCAmelCase  ,__UpperCAmelCase      ):
              lowerCAmelCase__ :  Dict							      =					[scores]
      elif self.framework == "tf":
          lowerCAmelCase__ :  Any							      =					stable_softmax(__UpperCAmelCase  ,axis=-1      )
          lowerCAmelCase__ :  List[Any]							      =					probs.numpy().tolist()
      else:
          raise ValueError(F"""Unsupported framework: {self.framework}"""      )

      lowerCAmelCase__ :  Tuple							      =					[
          {"""score""": score, """label""": candidate_label}
          for score, candidate_label in sorted(zip(__UpperCAmelCase  ,__UpperCAmelCase      )  ,key=lambda __UpperCAmelCase      : -x[0]      )
      ]
      return result


