



"""simple docstring"""







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.
lowercase__		:    List[str]				   =     {'''LayoutLMv2Config''', '''LayoutLMv3Config'''}







@is_pipeline_test
class 				UpperCamelCase__       (     unittest.TestCase  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
      _SCREAMING_SNAKE_CASE      =					TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

      if model_mapping is not None:
            _SCREAMING_SNAKE_CASE      =					{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
      if tf_model_mapping is not None:
            _SCREAMING_SNAKE_CASE      =					{
                config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
            }



      @require_torch
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any	):
        lowerCAmelCase_       :    Tuple								=			pipeline(
            task='text-classification'   ,      model='hf-internal-testing/tiny-random-distilbert'   ,      framework='pt'	)

        lowerCAmelCase_       :    int								=			text_classifier('This is great !'	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'LABEL_0', 'score': 0.5_04}]	)

        lowerCAmelCase_       :    Tuple								=			text_classifier('This is great !'   ,      top_k=2	)
        self.assertEqual(
            nested_simplify(__a	)   ,      [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}]	)

        lowerCAmelCase_       :    Any								=			text_classifier(['This is great !', 'This is bad']   ,      top_k=2	)
        self.assertEqual(
            nested_simplify(__a	)   ,      [
                [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}],
                [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}],
            ]   ,      )

        lowerCAmelCase_       :    List[Any]								=			text_classifier('This is great !'   ,      top_k=1	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'LABEL_0', 'score': 0.5_04}]	)

        # Legacy behavior
        lowerCAmelCase_       :    Optional[Any]								=			text_classifier('This is great !'   ,      return_all_scores=__a	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'LABEL_0', 'score': 0.5_04}]	)

        lowerCAmelCase_       :    Optional[Any]								=			text_classifier('This is great !'   ,      return_all_scores=__a	)
        self.assertEqual(
            nested_simplify(__a	)   ,      [[{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}]]	)

        lowerCAmelCase_       :    str								=			text_classifier(['This is great !', 'Something else']   ,      return_all_scores=__a	)
        self.assertEqual(
            nested_simplify(__a	)   ,      [
                [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}],
                [{'label': 'LABEL_0', 'score': 0.5_04}, {'label': 'LABEL_1', 'score': 0.4_96}],
            ]   ,      )

        lowerCAmelCase_       :    Tuple								=			text_classifier(['This is great !', 'Something else']   ,      return_all_scores=__a	)
        self.assertEqual(
            nested_simplify(__a	)   ,      [
                {'label': 'LABEL_0', 'score': 0.5_04},
                {'label': 'LABEL_0', 'score': 0.5_04},
            ]   ,      )



      @require_torch
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        import torch

        lowerCAmelCase_       :    Optional[Any]								=			pipeline(
            task='text-classification'   ,      model='hf-internal-testing/tiny-random-distilbert'   ,      framework='pt'   ,      device=torch.device('cpu'	)   ,      )

        lowerCAmelCase_       :    Dict								=			text_classifier('This is great !'	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'LABEL_0', 'score': 0.5_04}]	)



      @require_tf
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        lowerCAmelCase_       :    Dict								=			pipeline(
            task='text-classification'   ,      model='hf-internal-testing/tiny-random-distilbert'   ,      framework='tf'	)

        lowerCAmelCase_       :    Dict								=			text_classifier('This is great !'	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'LABEL_0', 'score': 0.5_04}]	)



      @slow
      @require_torch
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict	):
        lowerCAmelCase_       :    int								=			pipeline('text-classification'	)

        lowerCAmelCase_       :    Optional[Any]								=			text_classifier('This is great !'	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'POSITIVE', 'score': 1.0}]	)
        lowerCAmelCase_       :    List[str]								=			text_classifier('This is bad !'	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'NEGATIVE', 'score': 1.0}]	)
        lowerCAmelCase_       :    Optional[Any]								=			text_classifier('Birds are a type of animal'	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'POSITIVE', 'score': 0.9_88}]	)



      @slow
      @require_tf
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict	):
        lowerCAmelCase_       :    Optional[Any]								=			pipeline('text-classification'   ,      framework='tf'	)

        lowerCAmelCase_       :    Dict								=			text_classifier('This is great !'	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'POSITIVE', 'score': 1.0}]	)
        lowerCAmelCase_       :    List[str]								=			text_classifier('This is bad !'	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'NEGATIVE', 'score': 1.0}]	)
        lowerCAmelCase_       :    List[Any]								=			text_classifier('Birds are a type of animal'	)
        self.assertEqual(nested_simplify(__a	)   ,      [{'label': 'POSITIVE', 'score': 0.9_88}]	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				int	):
        lowerCAmelCase_       :    List[str]								=			TextClassificationPipeline(model=__a   ,      tokenizer=__a	)
        return text_classifier, ["HuggingFace is in", "This is another test"]





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Dict	):
        lowerCAmelCase_       :    Optional[int]								=			text_classifier.model
        # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
        lowerCAmelCase_       :    Union[str, Any]								=			'HuggingFace is in'
        lowerCAmelCase_       :    Tuple								=			text_classifier(__a	)

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

        lowerCAmelCase_       :    int								=			['HuggingFace is in ', 'Paris is in France']
        lowerCAmelCase_       :    Dict								=			text_classifier(__a	)
        self.assertEqual(
            nested_simplify(__a	)   ,      [{'label': ANY(__a	), 'score': ANY(__a	)}, {'label': ANY(__a	), 'score': ANY(__a	)}]   ,      )
        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
        lowerCAmelCase_       :    Tuple								=			text_classifier(__a   ,      top_k=__a	)
        lowerCAmelCase_       :    Optional[int]								=			len(model.config.idalabel.values()	)
        self.assertEqual(
            nested_simplify(__a	)   ,      [[{'label': ANY(__a	), 'score': ANY(__a	)}] * N, [{'label': ANY(__a	), 'score': ANY(__a	)}] * N]   ,      )

        lowerCAmelCase_       :    str								=			{'text': 'HuggingFace is in ', 'text_pair': 'Paris is in France'}
        lowerCAmelCase_       :    Optional[int]								=			text_classifier(__a	)
        self.assertEqual(
            nested_simplify(__a	)   ,      {'label': ANY(__a	), 'score': ANY(__a	)}   ,      )
        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.
        lowerCAmelCase_       :    Optional[Any]								=			[['HuggingFace is in ', 'Paris is in France']]
        with self.assertRaises(__a	):
          text_classifier(__a	)

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










"""simple docstring"""







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


lowercase__		:    Optional[int]				   =     {
    """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRConfig"""],
    """processing_trocr""": ["""TrOCRProcessor"""],
}


try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowercase__		:    Dict				   =     [
         """TROCR_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """TrOCRForCausalLM""",
         """TrOCRPreTrainedModel""",
     ]


if TYPE_CHECKING:
     from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
     from .processing_trocr import TrOCRProcessor

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel

else:
     import sys

     lowercase__		:    int				   =     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)





