


'''simple docstring'''






import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
 from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
 from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
 from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


lowercase				=DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

lowercase				='main'
# Default branch name
lowercase				='f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'
# One particular commit (not the top of `main`)
lowercase				='aaaaaaa'
# This commit does not exist, so we should 404.

lowercase				='d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'
# Sha-1 of config.json on the top of `main`, for checking purposes
lowercase				='4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'





@contextlib.contextmanager
def lowerCamelCase__     (		):







   '''simple docstring'''




   print('Welcome!'				)
   yield
   print('Bye!'				)





@contextlib.contextmanager
def lowerCamelCase__     (		):







   '''simple docstring'''




   print('Bonjour!'				)
   yield
   print('Au revoir!'				)






class    __magic_name__				(						unittest.TestCase							):






       def      lowerCAmelCase						(     self)		->    Optional[Any]:




          '''simple docstring'''
          # If the spec is missing, importlib would not be able to import the module dynamically.
          assert transformers.__spec__ is not None
          assert importlib.util.find_spec('transformers') is not None






class    __magic_name__				(						unittest.TestCase							):






       @unittest.mock.patch('sys.stdout'    ,				new_callable=io.StringIO)
       def      lowerCAmelCase						(     self    ,				snake_case)		->    List[Any]:




          '''simple docstring'''
          with ContextManagers([]):
             print('Transformers are awesome!')
          # The print statement adds a new line at the end of the output
          self.assertEqual(mock_stdout.getvalue()    ,				'Transformers are awesome!\n')






       @unittest.mock.patch('sys.stdout'    ,				new_callable=io.StringIO)
       def      lowerCAmelCase						(     self    ,				snake_case)		->    Union[str, Any]:




          '''simple docstring'''
          with ContextManagers([context_en()]):
             print('Transformers are awesome!')
          # The output should be wrapped with an English welcome and goodbye
          self.assertEqual(mock_stdout.getvalue()    ,				'Welcome!\nTransformers are awesome!\nBye!\n')






       @unittest.mock.patch('sys.stdout'    ,				new_callable=io.StringIO)
       def      lowerCAmelCase						(     self    ,				snake_case)		->    int:




          '''simple docstring'''
          with ContextManagers([context_fr(), context_en()]):
             print('Transformers are awesome!')
          # The output should be wrapped with an English and French welcome and goodbye
          self.assertEqual(mock_stdout.getvalue()    ,				'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n')






       @require_torch
       def      lowerCAmelCase						(     self)		->    Optional[Any]:




          '''simple docstring'''
          self.assertEqual(find_labels(snake_case)    ,				['labels'])
          self.assertEqual(find_labels(snake_case)    ,				['labels', 'next_sentence_label'])
          self.assertEqual(find_labels(snake_case)    ,				['start_positions', 'end_positions'])






          class    __magic_name__				(						lowerCAmelCase							):
                 pass






          self.assertEqual(find_labels(snake_case)    ,				['labels'])






       @require_tf
       def      lowerCAmelCase						(     self)		->    Dict:




          '''simple docstring'''
          self.assertEqual(find_labels(snake_case)    ,				['labels'])
          self.assertEqual(find_labels(snake_case)    ,				['labels', 'next_sentence_label'])
          self.assertEqual(find_labels(snake_case)    ,				['start_positions', 'end_positions'])






          class    __magic_name__				(						lowerCAmelCase							):
                 pass






          self.assertEqual(find_labels(snake_case)    ,				['labels'])






       @require_flax
       def      lowerCAmelCase						(     self)		->    int:




          '''simple docstring'''
          # Flax models don't have labels
          self.assertEqual(find_labels(snake_case)    ,				[])
          self.assertEqual(find_labels(snake_case)    ,				[])
          self.assertEqual(find_labels(snake_case)    ,				[])






          class    __magic_name__				(						lowerCAmelCase							):
                 pass






          self.assertEqual(find_labels(snake_case)    ,				[])





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

lowercase				=logging.get_logger(__name__)






@add_end_docstrings(lowerCAmelCase							)
class    __magic_name__				(						lowerCAmelCase							):






       def __init__(     self    ,				*snake_case    ,				**snake_case)		->    Dict:




          '''simple docstring'''
          super().__init__(*snake_case    ,				**snake_case)
          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      lowerCAmelCase						(     self    ,				snake_case=None)		->    str:




          '''simple docstring'''
          _UpperCAmelCase  :  Any				       ={}
          if top_k is not None:
             _UpperCAmelCase  :  Optional[int]				       =top_k
          return {}, {}, postprocess_params






       def __call__(     self    ,				snake_case    ,				**snake_case)		->    List[str]:




          '''simple docstring'''
          return super().__call__(snake_case    ,				**snake_case)






       def      lowerCAmelCase						(     self    ,				snake_case)		->    List[str]:




          '''simple docstring'''
          _UpperCAmelCase  :  int				       =load_image(snake_case)
          _UpperCAmelCase  :  Tuple				       =self.image_processor(images=snake_case    ,				return_tensors=self.framework)
          return model_inputs






       def      lowerCAmelCase						(     self    ,				snake_case)		->    Optional[Any]:




          '''simple docstring'''
          _UpperCAmelCase  :  List[str]				       =self.model(**snake_case)
          return model_outputs






       def      lowerCAmelCase						(     self    ,				snake_case    ,				snake_case=5)		->    Any:




          '''simple docstring'''
          if top_k > self.model.config.num_labels:
             _UpperCAmelCase  :  Optional[Any]				       =self.model.config.num_labels

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

          _UpperCAmelCase  :  int				       =scores.tolist()
          _UpperCAmelCase  :  Tuple				       =ids.tolist()
          return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(snake_case    ,				snake_case)]

