





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    : Optional[Any]    	=  {"""LayoutLMv2Config""", """LayoutLMv3Config"""}

@is_pipeline_test
class  __A(						unittest.TestCase ):
					__A	  =       MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
					__A	  =       TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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

					@require_torch
					def 	_UpperCamelCase     (      self      ):





												"""simple docstring"""

												_UpperCamelCase              =						pipeline(
												    task='''text-classification''',       model='''hf-internal-testing/tiny-random-distilbert''',       framework='''pt'''      )

												_UpperCamelCase              =						text_classifier('''This is great !'''      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''LABEL_0''', '''score''': 0.504}]      )

												_UpperCamelCase              =						text_classifier('''This is great !''',       top_k=2      )
												self.assertEqual(
												    nested_simplify(A      ),       [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}]      )

												_UpperCamelCase              =						text_classifier(['''This is great !''', '''This is bad'''],       top_k=2      )
												self.assertEqual(
												    nested_simplify(A      ),       [
												        [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
												        [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
												    ],       )

												_UpperCamelCase              =						text_classifier('''This is great !''',       top_k=1      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''LABEL_0''', '''score''': 0.504}]      )

												# Legacy behavior
												_UpperCamelCase              =						text_classifier('''This is great !''',       return_all_scores=A      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''LABEL_0''', '''score''': 0.504}]      )

												_UpperCamelCase              =						text_classifier('''This is great !''',       return_all_scores=A      )
												self.assertEqual(
												    nested_simplify(A      ),       [[{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}]]      )

												_UpperCamelCase              =						text_classifier(['''This is great !''', '''Something else'''],       return_all_scores=A      )
												self.assertEqual(
												    nested_simplify(A      ),       [
												        [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
												        [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
												    ],       )

												_UpperCamelCase              =						text_classifier(['''This is great !''', '''Something else'''],       return_all_scores=A      )
												self.assertEqual(
												    nested_simplify(A      ),       [
												        {'''label''': '''LABEL_0''', '''score''': 0.504},
												        {'''label''': '''LABEL_0''', '''score''': 0.504},
												    ],       )

					@require_torch
					def 	_UpperCamelCase     (      self      ):





												"""simple docstring"""

												import torch

												_UpperCamelCase              =						pipeline(
												    task='''text-classification''',       model='''hf-internal-testing/tiny-random-distilbert''',       framework='''pt''',       device=torch.device('''cpu'''      ),       )

												_UpperCamelCase              =						text_classifier('''This is great !'''      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''LABEL_0''', '''score''': 0.504}]      )

					@require_tf
					def 	_UpperCamelCase     (      self      ):





												"""simple docstring"""

												_UpperCamelCase              =						pipeline(
												    task='''text-classification''',       model='''hf-internal-testing/tiny-random-distilbert''',       framework='''tf'''      )

												_UpperCamelCase              =						text_classifier('''This is great !'''      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''LABEL_0''', '''score''': 0.504}]      )

					@slow
					@require_torch
					def 	_UpperCamelCase     (      self      ):





												"""simple docstring"""

												_UpperCamelCase              =						pipeline('''text-classification'''      )

												_UpperCamelCase              =						text_classifier('''This is great !'''      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''POSITIVE''', '''score''': 1.0}]      )
												_UpperCamelCase              =						text_classifier('''This is bad !'''      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''NEGATIVE''', '''score''': 1.0}]      )
												_UpperCamelCase              =						text_classifier('''Birds are a type of animal'''      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''POSITIVE''', '''score''': 0.988}]      )

					@slow
					@require_tf
					def 	_UpperCamelCase     (      self      ):





												"""simple docstring"""

												_UpperCamelCase              =						pipeline('''text-classification''',       framework='''tf'''      )

												_UpperCamelCase              =						text_classifier('''This is great !'''      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''POSITIVE''', '''score''': 1.0}]      )
												_UpperCamelCase              =						text_classifier('''This is bad !'''      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''NEGATIVE''', '''score''': 1.0}]      )
												_UpperCamelCase              =						text_classifier('''Birds are a type of animal'''      )
												self.assertEqual(nested_simplify(A      ),       [{'''label''': '''POSITIVE''', '''score''': 0.988}]      )

					def 	_UpperCamelCase     (      self,       A,       A,       A      ):





												"""simple docstring"""

												_UpperCamelCase              =						TextClassificationPipeline(model=A,       tokenizer=A      )
												return text_classifier, ["HuggingFace is in", "This is another test"]



					def 	_UpperCamelCase     (      self,       A,       A      ):





												"""simple docstring"""

												_UpperCamelCase              =						text_classifier.model
												# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
												_UpperCamelCase              =						'''HuggingFace is in'''
												_UpperCamelCase              =						text_classifier(A      )

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

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

												_UpperCamelCase              =						{'''text''': '''HuggingFace is in ''', '''text_pair''': '''Paris is in France'''}
												_UpperCamelCase              =						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.
												_UpperCamelCase              =						[['''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
												_UpperCamelCase              =						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()      )













import os
import sys
import unittest


lowercase    : Any    	=  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
lowercase    : int    	=  os.path.join(git_repo_path, """src""", """transformers""")

lowercase    : str    	=  """
{0} = None
"""

lowercase    : Union[str, Any]    	=  """
class {0}(metaclass=DummyObject):
    _backends = {1}

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


lowercase    : Optional[Any]    	=  """
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
"""

class  __A(						unittest.TestCase ):

     def 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						find_backend('''    _import_structure["models.albert"].append("AlbertTokenizerFast")'''      )
            self.assertIsNone(A      )

            _UpperCamelCase              =						find_backend('''    if not is_tokenizers_available():'''      )
            self.assertEqual(A,       '''tokenizers'''      )

            _UpperCamelCase              =						find_backend('''    if not is_tensorflow_text_available():'''      )
            self.assertEqual(A,       '''tensorflow_text'''      )

            _UpperCamelCase              =						find_backend('''    if not (is_sentencepiece_available() and is_tokenizers_available()):'''      )
            self.assertEqual(A,       '''sentencepiece_and_tokenizers'''      )

            _UpperCamelCase              =						find_backend(
                '''    if not (is_sentencepiece_available() and is_tensorflow_text_available()):'''      )
            self.assertEqual(A,       '''sentencepiece_and_tensorflow_text'''      )

            _UpperCamelCase              =						find_backend(
                '''    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):'''      )
            self.assertEqual(A,       '''sentencepiece_and_tokenizers_and_vision'''      )

     def 	_UpperCamelCase     (      self      ):





            """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''',       A      )
            self.assertIn('''tensorflow_text''',       A      )
            self.assertIn('''sentencepiece_and_tokenizers''',       A      )

            # 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 	_UpperCamelCase     (      self      ):





            """simple docstring"""

            _UpperCamelCase              =						create_dummy_object('''CONSTANT''',       '''\'torch\''''      )
            self.assertEqual(A,       '''\nCONSTANT = None\n'''      )

            _UpperCamelCase              =						create_dummy_object('''function''',       '''\'torch\''''      )
            self.assertEqual(
                A,       '''\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(A,       A      )



     def 	_UpperCamelCase     (      self      ):





            """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'''],       A      )






