


import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
_SCREAMING_SNAKE_CASE     :			Tuple        =							{'LayoutLMv2Config', 'LayoutLMv3Config'}



@is_pipeline_test
class        A     (		unittest.TestCase	):







     '''simple docstring'''







     lowerCamelCase :						str            =   MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
     lowerCamelCase :						Tuple            =   TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

     if model_mapping is not None:
          lowerCamelCase :						Union[str, Any]            =   {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
     if tf_model_mapping is not None:
          lowerCamelCase :						Union[str, Any]            =   {
              config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
          }

     @require_torch
     def 					UpperCAmelCase__       (				self    :							Optional[Any]):
      _lowercase:       Dict						=				pipeline(
          task="text-classification"			,				model="hf-internal-testing/tiny-random-distilbert"			,				framework="pt")

      _lowercase:       Optional[int]						=				text_classifier("This is great !")
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "LABEL_0", "score": 0.5_0_4}])

      _lowercase:       Tuple						=				text_classifier("This is great !"			,				top_k=2)
      self.assertEqual(
          nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}])

      _lowercase:       Union[str, Any]						=				text_classifier(["This is great !", "This is bad"]			,				top_k=2)
      self.assertEqual(
          nested_simplify(_SCREAMING_SNAKE_CASE)			,				[
              [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
              [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
          ]			,				)

      _lowercase:       int						=				text_classifier("This is great !"			,				top_k=1)
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "LABEL_0", "score": 0.5_0_4}])

      # Legacy behavior
      _lowercase:       int						=				text_classifier("This is great !"			,				return_all_scores=_SCREAMING_SNAKE_CASE)
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "LABEL_0", "score": 0.5_0_4}])

      _lowercase:       Optional[int]						=				text_classifier("This is great !"			,				return_all_scores=_SCREAMING_SNAKE_CASE)
      self.assertEqual(
          nested_simplify(_SCREAMING_SNAKE_CASE)			,				[[{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}]])

      _lowercase:       Any						=				text_classifier(["This is great !", "Something else"]			,				return_all_scores=_SCREAMING_SNAKE_CASE)
      self.assertEqual(
          nested_simplify(_SCREAMING_SNAKE_CASE)			,				[
              [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
              [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
          ]			,				)

      _lowercase:       Tuple						=				text_classifier(["This is great !", "Something else"]			,				return_all_scores=_SCREAMING_SNAKE_CASE)
      self.assertEqual(
          nested_simplify(_SCREAMING_SNAKE_CASE)			,				[
              {"label": "LABEL_0", "score": 0.5_0_4},
              {"label": "LABEL_0", "score": 0.5_0_4},
          ]			,				)

     @require_torch
     def 					UpperCAmelCase__       (				self    :							Any):
      import torch

      _lowercase:       int						=				pipeline(
          task="text-classification"			,				model="hf-internal-testing/tiny-random-distilbert"			,				framework="pt"			,				device=torch.device("cpu")			,				)

      _lowercase:       Optional[int]						=				text_classifier("This is great !")
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "LABEL_0", "score": 0.5_0_4}])

     @require_tf
     def 					UpperCAmelCase__       (				self    :							Tuple):
      _lowercase:       Tuple						=				pipeline(
          task="text-classification"			,				model="hf-internal-testing/tiny-random-distilbert"			,				framework="tf")

      _lowercase:       Tuple						=				text_classifier("This is great !")
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "LABEL_0", "score": 0.5_0_4}])

     @slow
     @require_torch
     def 					UpperCAmelCase__       (				self    :							int):
      _lowercase:       Union[str, Any]						=				pipeline("text-classification")

      _lowercase:       Optional[Any]						=				text_classifier("This is great !")
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "POSITIVE", "score": 1.0}])
      _lowercase:       Tuple						=				text_classifier("This is bad !")
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "NEGATIVE", "score": 1.0}])
      _lowercase:       Tuple						=				text_classifier("Birds are a type of animal")
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "POSITIVE", "score": 0.9_8_8}])

     @slow
     @require_tf
     def 					UpperCAmelCase__       (				self    :							Optional[Any]):
      _lowercase:       Union[str, Any]						=				pipeline("text-classification"			,				framework="tf")

      _lowercase:       List[Any]						=				text_classifier("This is great !")
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "POSITIVE", "score": 1.0}])
      _lowercase:       Any						=				text_classifier("This is bad !")
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "NEGATIVE", "score": 1.0}])
      _lowercase:       Optional[Any]						=				text_classifier("Birds are a type of animal")
      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": "POSITIVE", "score": 0.9_8_8}])

     def 					UpperCAmelCase__       (				self    :							Tuple			,				_UpperCamelCase    :							Union[str, Any]			,				_UpperCamelCase    :							Dict			,				_UpperCamelCase    :							Union[str, Any]):
      _lowercase:       Optional[int]						=				TextClassificationPipeline(model=_SCREAMING_SNAKE_CASE			,				tokenizer=_SCREAMING_SNAKE_CASE)
      return text_classifier, ["HuggingFace is in", "This is another test"]






     def 					UpperCAmelCase__       (				self    :							int			,				_UpperCamelCase    :							Dict			,				_UpperCamelCase    :							List[Any]):
      _lowercase:       Tuple						=				text_classifier.model
      # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
      _lowercase:       Tuple						=				'''HuggingFace is in'''
      _lowercase:       str						=				text_classifier(_SCREAMING_SNAKE_CASE)

      self.assertEqual(nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": ANY(_SCREAMING_SNAKE_CASE), "score": ANY(_SCREAMING_SNAKE_CASE)}])
      self.assertTrue(outputs[0]["label"] in model.config.idalabel.values())

      _lowercase:       int						=				['''HuggingFace is in ''', '''Paris is in France''']
      _lowercase:       Optional[Any]						=				text_classifier(_SCREAMING_SNAKE_CASE)
      self.assertEqual(
          nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": ANY(_SCREAMING_SNAKE_CASE), "score": ANY(_SCREAMING_SNAKE_CASE)}, {"label": ANY(_SCREAMING_SNAKE_CASE), "score": ANY(_SCREAMING_SNAKE_CASE)}]			,				)
      self.assertTrue(outputs[0]["label"] in model.config.idalabel.values())
      self.assertTrue(outputs[1]["label"] in model.config.idalabel.values())

      # Forcing to get all results with `top_k=None`
      # This is NOT the legacy format
      _lowercase:       Optional[Any]						=				text_classifier(_SCREAMING_SNAKE_CASE			,				top_k=_SCREAMING_SNAKE_CASE)
      _lowercase:       Union[str, Any]						=				len(model.config.idalabel.values())
      self.assertEqual(
          nested_simplify(_SCREAMING_SNAKE_CASE)			,				[[{"label": ANY(_SCREAMING_SNAKE_CASE), "score": ANY(_SCREAMING_SNAKE_CASE)}] * N, [{"label": ANY(_SCREAMING_SNAKE_CASE), "score": ANY(_SCREAMING_SNAKE_CASE)}] * N]			,				)

      _lowercase:       List[str]						=				{'''text''': '''HuggingFace is in ''', '''text_pair''': '''Paris is in France'''}
      _lowercase:       Any						=				text_classifier(_SCREAMING_SNAKE_CASE)
      self.assertEqual(
          nested_simplify(_SCREAMING_SNAKE_CASE)			,				{"label": ANY(_SCREAMING_SNAKE_CASE), "score": ANY(_SCREAMING_SNAKE_CASE)}			,				)
      self.assertTrue(outputs["label"] in model.config.idalabel.values())

      # This might be used a text pair, but tokenizer + pipe interaction
      # makes it hard to understand that it's not using the pair properly
      # https://github.com/huggingface/transformers/issues/17305
      # We disabled this usage instead as it was outputting wrong outputs.
      _lowercase:       Union[str, Any]						=				[['''HuggingFace is in ''', '''Paris is in France''']]
      with self.assertRaises(_SCREAMING_SNAKE_CASE):
       text_classifier(_SCREAMING_SNAKE_CASE)

      # This used to be valid for doing text pairs
      # We're keeping it working because of backward compatibility
      _lowercase:       Optional[int]						=				text_classifier([[["HuggingFace is in ", "Paris is in France"]]])
      self.assertEqual(
          nested_simplify(_SCREAMING_SNAKE_CASE)			,				[{"label": ANY(_SCREAMING_SNAKE_CASE), "score": ANY(_SCREAMING_SNAKE_CASE)}]			,				)
      self.assertTrue(outputs[0]["label"] in model.config.idalabel.values())







import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image

     from transformers import PoolFormerImageProcessor

class     __a(	unittest.TestCase  ):






    """simple docstring"""





    def __init__( self  ,_SCREAMING_SNAKE_CASE  ,_SCREAMING_SNAKE_CASE=7  ,_SCREAMING_SNAKE_CASE=3  ,_SCREAMING_SNAKE_CASE=30  ,_SCREAMING_SNAKE_CASE=400  ,_SCREAMING_SNAKE_CASE=True  ,_SCREAMING_SNAKE_CASE=None  ,_SCREAMING_SNAKE_CASE=0.9  ,_SCREAMING_SNAKE_CASE=None  ,_SCREAMING_SNAKE_CASE=True  ,_SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5]  ,_SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5]  ,)					->						Optional[int]:
         UpperCAmelCase_     :				int  =     size if size is not None else {'''shortest_edge''': 30}
         UpperCAmelCase_     :				List[str]  =     crop_size if crop_size is not None else {'''height''': 30, '''width''': 30}
         UpperCAmelCase_     :				Dict  =     parent
         UpperCAmelCase_     :				int  =     batch_size
         UpperCAmelCase_     :				int  =     num_channels
         UpperCAmelCase_     :				Any  =     min_resolution
         UpperCAmelCase_     :				Tuple  =     max_resolution
         UpperCAmelCase_     :				Optional[int]  =     do_resize_and_center_crop
         UpperCAmelCase_     :				Tuple  =     size
         UpperCAmelCase_     :				List[str]  =     crop_pct
         UpperCAmelCase_     :				List[str]  =     crop_size
         UpperCAmelCase_     :				Any  =     do_normalize
         UpperCAmelCase_     :				str  =     image_mean
         UpperCAmelCase_     :				List[Any]  =     image_std





    def 				a__ ( self    )					->						str:
         return {
             "size": self.size,
             "do_resize_and_center_crop": self.do_resize_and_center_crop,
             "crop_pct": self.crop_pct,
             "crop_size": self.crop_size,
             "do_normalize": self.do_normalize,
             "image_mean": self.image_mean,
             "image_std": self.image_std,
         }


@require_torch
@require_vision
class     __a(	_a							,		unittest.TestCase  ):






    """simple docstring"""





    lowerCAmelCase         = PoolFormerImageProcessor if is_vision_available() else None





    def 				a__ ( self    )					->						Dict:
         UpperCAmelCase_     :				str  =     PoolFormerImageProcessingTester(self    )





    @property
    def 				a__ ( self    )					->						Optional[int]:
         return self.image_processor_tester.prepare_image_processor_dict()





    def 				a__ ( self    )					->						Optional[int]:
         UpperCAmelCase_     :				List[Any]  =     self.image_processing_class(**self.image_processor_dict    )
         self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE  ,'''do_resize_and_center_crop'''    )    )
         self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE  ,'''size'''    )    )
         self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE  ,'''crop_pct'''    )    )
         self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE  ,'''do_normalize'''    )    )
         self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE  ,'''image_mean'''    )    )
         self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE  ,'''image_std'''    )    )





    def 				a__ ( self    )					->						Union[str, Any]:
         UpperCAmelCase_     :				Any  =     self.image_processing_class.from_dict(self.image_processor_dict    )
         self.assertEqual(image_processor.size  ,{'''shortest_edge''': 30}    )
         self.assertEqual(image_processor.crop_size  ,{'''height''': 30, '''width''': 30}    )

         UpperCAmelCase_     :				Optional[Any]  =     self.image_processing_class.from_dict(self.image_processor_dict  ,size=42  ,crop_size=84    )
         self.assertEqual(image_processor.size  ,{'''shortest_edge''': 42}    )
         self.assertEqual(image_processor.crop_size  ,{'''height''': 84, '''width''': 84}    )





    def 				a__ ( self    )					->						Optional[int]:
         pass





    def 				a__ ( self    )					->						Dict:
         # Initialize image_processing
         UpperCAmelCase_     :				str  =     self.image_processing_class(**self.image_processor_dict    )
         # create random PIL images
         UpperCAmelCase_     :				int  =     prepare_image_inputs(self.image_processor_tester  ,equal_resolution=_SCREAMING_SNAKE_CASE    )
         for image in image_inputs:
              self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,Image.Image    )

         # Test not batched input
         UpperCAmelCase_     :				Optional[int]  =     image_processing(image_inputs[0]  ,return_tensors='''pt'''    ).pixel_values

         self.assertEqual(
             encoded_images.shape  ,(
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )  ,)

         # Test batched
         UpperCAmelCase_     :				Union[str, Any]  =     image_processing(_SCREAMING_SNAKE_CASE  ,return_tensors='''pt'''    ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,(
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )  ,)





    def 				a__ ( self    )					->						List[Any]:
         # Initialize image_processing
         UpperCAmelCase_     :				Any  =     self.image_processing_class(**self.image_processor_dict    )
         # create random numpy tensors
         UpperCAmelCase_     :				List[str]  =     prepare_image_inputs(self.image_processor_tester  ,equal_resolution=_SCREAMING_SNAKE_CASE  ,numpify=_SCREAMING_SNAKE_CASE    )
         for image in image_inputs:
              self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,np.ndarray    )

         # Test not batched input
         UpperCAmelCase_     :				Tuple  =     image_processing(image_inputs[0]  ,return_tensors='''pt'''    ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,(
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )  ,)

         # Test batched
         UpperCAmelCase_     :				List[Any]  =     image_processing(_SCREAMING_SNAKE_CASE  ,return_tensors='''pt'''    ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,(
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )  ,)





    def 				a__ ( self    )					->						Union[str, Any]:
         # Initialize image_processing
         UpperCAmelCase_     :				List[Any]  =     self.image_processing_class(**self.image_processor_dict    )
         # create random PyTorch tensors
         UpperCAmelCase_     :				Optional[Any]  =     prepare_image_inputs(self.image_processor_tester  ,equal_resolution=_SCREAMING_SNAKE_CASE  ,torchify=_SCREAMING_SNAKE_CASE    )
         for image in image_inputs:
              self.assertIsInstance(_SCREAMING_SNAKE_CASE  ,torch.Tensor    )

         # Test not batched input
         UpperCAmelCase_     :				Tuple  =     image_processing(image_inputs[0]  ,return_tensors='''pt'''    ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,(
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )  ,)

         # Test batched
         UpperCAmelCase_     :				List[Any]  =     image_processing(_SCREAMING_SNAKE_CASE  ,return_tensors='''pt'''    ).pixel_values
         self.assertEqual(
             encoded_images.shape  ,(
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.crop_size['''height'''],
                 self.image_processor_tester.crop_size['''width'''],
             )  ,)