




'''simple docstring'''



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_tf_available():
      import tensorflow as tf

      from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
      from ..tf_utils import stable_softmax

if is_torch_available():
      from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

UpperCamelCase_    	=				logging.get_logger(__name__)






@add_end_docstrings(SCREAMING_SNAKE_CASE )
class 							_a				(			SCREAMING_SNAKE_CASE ):





       '''simple docstring'''






       def __init__(      self,							*A,							**A  ):







             '''simple docstring'''







             super().__init__(*A,							**A  )
             requires_backends(self,							'vision'  )
             self.check_model_type(
                 TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
                 if self.framework == 'tf'
                 else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING  )







       def        UpperCamelCase_							(      self,							A=None  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[str]    					=						{}
             if top_k is not None:
                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						top_k
             return {}, {}, postprocess_params







       def __call__(      self,							A,							**A  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Any    					=						load_image(A  )
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.image_processor(images=A,							return_tensors=self.framework  )
             return model_inputs







       def        UpperCamelCase_							(      self,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.model(**A  )
             return model_outputs







       def        UpperCamelCase_							(      self,							A,							A=5  ):







             '''simple docstring'''







             if top_k > self.model.config.num_labels:
                   SCREAMING_SNAKE_CASE   :      int    					=						self.model.config.num_labels

             if self.framework == "pt":
                   SCREAMING_SNAKE_CASE   :      str    					=						model_outputs.logits.softmax(-1  )[0]
                   SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      str    					=						probs.topk(A  )
             elif self.framework == "tf":
                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						stable_softmax(model_outputs.logits,							axis=-1  )[0]
                   SCREAMING_SNAKE_CASE   :      int    					=						tf.math.top_k(A,							k=A  )
                   SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      List[str]    					=						topk.values.numpy(), topk.indices.numpy()
             else:
                   raise ValueError(F"Unsupported framework: {self.framework}"  )

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						scores.tolist()
             SCREAMING_SNAKE_CASE   :      str    					=						ids.tolist()
             return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(A,							A  )]










import os
import sys
import unittest


__a:     Tuple   					=					os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__a:     Tuple   					=					os.path.join(git_repo_path, '''src''', '''transformers''')

__a:     Optional[Any]   					=					'''
{0} = None
'''

__a:     List[Any]   					=					'''
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
'''


__a:     int   					=					'''
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
'''
class 		SCREAMING_SNAKE_CASE__	(  unittest.TestCase     ):

  '''simple docstring'''







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


         """simple docstring"""
         _UpperCAmelCase							=    find_backend("""    _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")"""							)
         self.assertIsNone(lowerCamelCase							)

         _UpperCAmelCase							=    find_backend("""    if not is_tokenizers_available():"""							)
         self.assertEqual(lowerCamelCase       ,				"""tokenizers"""							)

         _UpperCAmelCase							=    find_backend("""    if not is_tensorflow_text_available():"""							)
         self.assertEqual(lowerCamelCase       ,				"""tensorflow_text"""							)

         _UpperCAmelCase							=    find_backend("""    if not (is_sentencepiece_available() and is_tokenizers_available()):"""							)
         self.assertEqual(lowerCamelCase       ,				"""sentencepiece_and_tokenizers"""							)

         _UpperCAmelCase							=    find_backend(
             """    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"""							)
         self.assertEqual(lowerCamelCase       ,				"""sentencepiece_and_tensorflow_text"""							)

         _UpperCAmelCase							=    find_backend(
             """    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):"""							)
         self.assertEqual(lowerCamelCase       ,				"""sentencepiece_and_tokenizers_and_vision"""							)


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


         """simple docstring"""
         _UpperCAmelCase							=    read_init()
         # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
         self.assertIn("""torch"""       ,				lowerCamelCase							)
         self.assertIn("""tensorflow_text"""       ,				lowerCamelCase							)
         self.assertIn("""sentencepiece_and_tokenizers"""       ,				lowerCamelCase							)

         # Likewise, we can't assert on the exact content of a key
         self.assertIn("""BertModel"""       ,				objects["""torch"""]							)
         self.assertIn("""TFBertModel"""       ,				objects["""tf"""]							)
         self.assertIn("""FlaxBertModel"""       ,				objects["""flax"""]							)
         self.assertIn("""BertModel"""       ,				objects["""torch"""]							)
         self.assertIn("""TFBertTokenizer"""       ,				objects["""tensorflow_text"""]							)
         self.assertIn("""convert_slow_tokenizer"""       ,				objects["""sentencepiece_and_tokenizers"""]							)


  def  lowerCamelCase       (      self		:			int							)						->	Any:


         """simple docstring"""
         _UpperCAmelCase							=    create_dummy_object("""CONSTANT"""       ,				"""'torch'"""							)
         self.assertEqual(lowerCamelCase       ,				"""\nCONSTANT = None\n"""							)

         _UpperCAmelCase							=    create_dummy_object("""function"""       ,				"""'torch'"""							)
         self.assertEqual(
             lowerCamelCase       ,				"""\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""							)

         _UpperCAmelCase							=    """
class FakeClass(metaclass=DummyObject):
    _backends = 'torch'

    def __init__(self, *args, **kwargs):
        requires_backends(self, 'torch')
"""
         _UpperCAmelCase							=    create_dummy_object("""FakeClass"""       ,				"""'torch'"""							)
         self.assertEqual(lowerCamelCase       ,				lowerCamelCase							)





  def  lowerCamelCase       (      self		:			Dict							)						->	List[str]:


         """simple docstring"""
         _UpperCAmelCase							=    """# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, [\"torch\"])


class FakeClass(metaclass=DummyObject):
    _backends = [\"torch\"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, [\"torch\"])
"""
         _UpperCAmelCase							=    create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}							)
         self.assertEqual(dummy_files["""torch"""]       ,				lowerCamelCase							)