


"""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.
UpperCAmelCase__  							={"LayoutLMv2Config", "LayoutLMv3Config"}





@is_pipeline_test
class    lowerCamelCase__						(		unittest.TestCase    ):
      a :     List[Any]											=		MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
      a :     List[str]											=		TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

      if model_mapping is not None:
            a :     List[str]											=		{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
      if tf_model_mapping is not None:
            a :     List[Any]											=		{
                config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
            }
      @require_torch
      def SCREAMING_SNAKE_CASE_	(		self	:	Dict							):






       '''simple docstring'''


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

       __lowercase									=	text_classifier("""This is great !"""							)
       self.assertEqual(nested_simplify(A_							)      ,       [{"""label""": """LABEL_0""", """score""": 0.5_04}]							)

       __lowercase									=	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}]							)

       __lowercase									=	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}],
           ]      ,       )

       __lowercase									=	text_classifier("""This is great !"""      ,       top_k=1							)
       self.assertEqual(nested_simplify(A_							)      ,       [{"""label""": """LABEL_0""", """score""": 0.5_04}]							)

       # Legacy behavior
       __lowercase									=	text_classifier("""This is great !"""      ,       return_all_scores=A_							)
       self.assertEqual(nested_simplify(A_							)      ,       [{"""label""": """LABEL_0""", """score""": 0.5_04}]							)

       __lowercase									=	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}]]							)

       __lowercase									=	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}],
           ]      ,       )

       __lowercase									=	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	:	Union[str, Any]							):






       '''simple docstring'''


       import torch

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

       __lowercase									=	text_classifier("""This is great !"""							)
       self.assertEqual(nested_simplify(A_							)      ,       [{"""label""": """LABEL_0""", """score""": 0.5_04}]							)
      @require_tf
      def SCREAMING_SNAKE_CASE_	(		self	:	int							):






       '''simple docstring'''


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

       __lowercase									=	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	:	Optional[int]							):






       '''simple docstring'''


       __lowercase									=	pipeline("""text-classification"""							)

       __lowercase									=	text_classifier("""This is great !"""							)
       self.assertEqual(nested_simplify(A_							)      ,       [{"""label""": """POSITIVE""", """score""": 1.0}]							)
       __lowercase									=	text_classifier("""This is bad !"""							)
       self.assertEqual(nested_simplify(A_							)      ,       [{"""label""": """NEGATIVE""", """score""": 1.0}]							)
       __lowercase									=	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	:	Optional[int]							):






       '''simple docstring'''


       __lowercase									=	pipeline("""text-classification"""      ,       framework="""tf"""							)

       __lowercase									=	text_classifier("""This is great !"""							)
       self.assertEqual(nested_simplify(A_							)      ,       [{"""label""": """POSITIVE""", """score""": 1.0}]							)
       __lowercase									=	text_classifier("""This is bad !"""							)
       self.assertEqual(nested_simplify(A_							)      ,       [{"""label""": """NEGATIVE""", """score""": 1.0}]							)
       __lowercase									=	text_classifier("""Birds are a type of animal"""							)
       self.assertEqual(nested_simplify(A_							)      ,       [{"""label""": """POSITIVE""", """score""": 0.9_88}]							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Tuple      ,       A_	:	Any      ,       A_	:	Dict      ,       A_	:	List[Any]							):






       '''simple docstring'''


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






      def SCREAMING_SNAKE_CASE_	(		self	:	Union[str, Any]      ,       A_	:	Tuple      ,       A_	:	Tuple							):






       '''simple docstring'''


       __lowercase									=	text_classifier.model
       # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
       __lowercase									=	"""HuggingFace is in"""
       __lowercase									=	text_classifier(A_							)

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

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

       __lowercase									=	{"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""}
       __lowercase									=	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.
       __lowercase									=	[["""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
       __lowercase									=	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 List

from .keymap import KEYMAP, get_character


def lowerCAmelCase_      (				UpperCamelCase__	: str ):






 """simple docstring"""







 def decorator(UpperCamelCase__	: Tuple ):
  __lowercase									=	getattr(UpperCamelCase__				,   """handle_key"""				,   [] )
  handle += [key]
  setattr(UpperCamelCase__				,   """handle_key"""				,   UpperCamelCase__ )
  return func

 return decorator


def lowerCAmelCase_      (				*UpperCamelCase__	: List[str] ):






 """simple docstring"""







 def decorator(UpperCamelCase__	: Tuple ):
  __lowercase									=	getattr(UpperCamelCase__				,   """handle_key"""				,   [] )
  handle += keys
  setattr(UpperCamelCase__				,   """handle_key"""				,   UpperCamelCase__ )
  return func

 return decorator





class    lowerCamelCase__						(		_a    ):
      def __new__(		cls	:	str      ,       A_	:	Optional[Any]      ,       A_	:	Union[str, Any]      ,       A_	:	int							):






       '''simple docstring'''


       __lowercase									=	super().__new__(cls      ,       A_      ,       A_      ,       A_							)
       if not hasattr(A_      ,       """key_handler"""							):
        setattr(A_      ,       """key_handler"""      ,       {}							)
       setattr(A_      ,       """handle_input"""      ,       KeyHandler.handle_input							)

       for value in attrs.values():
        __lowercase									=	getattr(A_      ,       """handle_key"""      ,       []							)
        for key in handled_keys:
         __lowercase									=	value
       return new_cls






      @staticmethod
      def SCREAMING_SNAKE_CASE_	(		cls	:	Dict							):






       '''simple docstring'''


       __lowercase									=	get_character()
       if char != KEYMAP["undefined"]:
        __lowercase									=	ord(A_							)
       __lowercase									=	cls.key_handler.get(A_							)
       if handler:
        __lowercase									=	char
        return handler(cls							)
       else:
        return None






def lowerCAmelCase_      (				cls	: int ):






 """simple docstring"""







 return KeyHandler(cls.__name__				,   cls.__bases__				,   cls.__dict__.copy() )
