


"""simple docstring"""







from importlib import import_module

from .logging import get_logger


a__        =  get_logger(__name__)




class 				UpperCamelCase_			:

	"""simple docstring"""





	def __init__(				self    :       List[str]    ,    UpperCAmelCase__    :       Optional[Any]    ,    UpperCAmelCase__    :       Optional[Any]=None     ) ->			Union[str, Any]:
						__SCREAMING_SNAKE_CASE		     =       attrs or []
						if module is not None:
											for key in module.__dict__:
																if key in attrs or not key.startswith("__"     ):
																					setattr(self    ,    __A    ,    getattr(__A    ,    __A     )     )
						__SCREAMING_SNAKE_CASE		     =       module._original_module if isinstance(__A    ,    _PatchedModuleObj     ) else module




class 				UpperCamelCase_			:

	"""simple docstring"""





	snake_case__       :						Optional[int]					      =    []




	def __init__(				self    :       Any    ,    UpperCAmelCase__    :       int    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       List[str]    ,    UpperCAmelCase__    :       Optional[Any]=None     ) ->			str:
						__SCREAMING_SNAKE_CASE		     =       obj
						__SCREAMING_SNAKE_CASE		     =       target
						__SCREAMING_SNAKE_CASE		     =       new
						__SCREAMING_SNAKE_CASE		     =       target.split("."     )[0]
						__SCREAMING_SNAKE_CASE		     =       {}
						__SCREAMING_SNAKE_CASE		     =       attrs or []




	def __enter__(				self    :       Optional[Any]     ) ->			Any:
						__SCREAMING_SNAKE_CASE		     =       self.target.split("."     )

						# Patch modules:
						# it's used to patch attributes of submodules like "os.path.join";
						# in this case we need to patch "os" and "os.path"

						for i in range(len(__A     )     ):
											try:
																__SCREAMING_SNAKE_CASE		     =       import_module(".".join(submodules[: i + 1]     )     )
											except ModuleNotFoundError:
																continue
											# We iterate over all the globals in self.obj in case we find "os" or "os.path"
											for attr in self.obj.__dir__():
																__SCREAMING_SNAKE_CASE		     =       getattr(self.obj    ,    __A     )
																# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
																# This allows to patch renamed modules like "from os import path as ospath".
																if obj_attr is submodule or (
																    (isinstance(__A    ,    _PatchedModuleObj     ) and obj_attr._original_module is submodule)
																):
																					__SCREAMING_SNAKE_CASE		     =       obj_attr
																					# patch at top level
																					setattr(self.obj    ,    __A    ,    _PatchedModuleObj(__A    ,    attrs=self.attrs     )     )
																					__SCREAMING_SNAKE_CASE		     =       getattr(self.obj    ,    __A     )
																					# construct lower levels patches
																					for key in submodules[i + 1 :]:
																										setattr(__A    ,    __A    ,    _PatchedModuleObj(getattr(__A    ,    __A    ,    __A     )    ,    attrs=self.attrs     )     )
																										__SCREAMING_SNAKE_CASE		     =       getattr(__A    ,    __A     )
																					# finally set the target attribute
																					setattr(__A    ,    __A    ,    self.new     )

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

						if submodules:  # if it's an attribute of a submodule like "os.path.join"
											try:
																__SCREAMING_SNAKE_CASE		     =       getattr(import_module(".".join(__A     )     )    ,    __A     )
											except (AttributeError, ModuleNotFoundError):
																return
											# We iterate over all the globals in self.obj in case we find "os.path.join"
											for attr in self.obj.__dir__():
																# We don't check for the name of the global, but rather if its value *is* "os.path.join".
																# This allows to patch renamed attributes like "from os.path import join as pjoin".
																if getattr(self.obj    ,    __A     ) is attr_value:
																					__SCREAMING_SNAKE_CASE		     =       getattr(self.obj    ,    __A     )
																					setattr(self.obj    ,    __A    ,    self.new     )
						elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
											__SCREAMING_SNAKE_CASE		     =       globals()["__builtins__"][target_attr]
											setattr(self.obj    ,    __A    ,    self.new     )
						else:
											raise RuntimeError(F"""Tried to patch attribute {target_attr} instead of a submodule."""     )




	def __exit__(				self    :       Dict    ,    *UpperCAmelCase__    :       int     ) ->			List[Any]:
						for attr in list(self.original     ):
											setattr(self.obj    ,    __A    ,    self.original.pop(__A     )     )




	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			int:
						self.__enter__()
						self._active_patches.append(self     )




	def 						UpperCAmelCase_   (				self    :       int     ) ->			Optional[Any]:
						try:
											self._active_patches.remove(self     )
						except ValueError:
											# If the patch hasn't been started this will fail
											return None

						return self.__exit__()




"""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.
a__       :							Dict        =  {'''LayoutLMv2Config''', '''LayoutLMv3Config'''}




@is_pipeline_test
class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	snake_case__       :						str					      =    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
	snake_case__       :						Tuple					      =    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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




	@require_torch
	def 						UpperCAmelCase_   (				self    :       str     ) ->			Tuple:
						__SCREAMING_SNAKE_CASE		     =       pipeline(
						    task="text-classification"    ,    model="hf-internal-testing/tiny-random-distilbert"    ,    framework="pt"     )

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "LABEL_0", "score": 0.504}]     )

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

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

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

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

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

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

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




	@require_torch
	def 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			Optional[int]:
						import torch

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

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "LABEL_0", "score": 0.504}]     )




	@require_tf
	def 						UpperCAmelCase_   (				self    :       Dict     ) ->			Optional[int]:
						__SCREAMING_SNAKE_CASE		     =       pipeline(
						    task="text-classification"    ,    model="hf-internal-testing/tiny-random-distilbert"    ,    framework="tf"     )

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "LABEL_0", "score": 0.504}]     )




	@slow
	@require_torch
	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			int:
						__SCREAMING_SNAKE_CASE		     =       pipeline("text-classification"     )

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




	@slow
	@require_tf
	def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			List[str]:
						__SCREAMING_SNAKE_CASE		     =       pipeline("text-classification"    ,    framework="tf"     )

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




	def 						UpperCAmelCase_   (				self    :       Any    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       Tuple     ) ->			Dict:
						__SCREAMING_SNAKE_CASE		     =       TextClassificationPipeline(model=UpperCAmelCase__    ,    tokenizer=UpperCAmelCase__     )
						return text_classifier, ["HuggingFace is in", "This is another test"]




	def 						UpperCAmelCase_   (				self    :       str    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       Optional[int]     ) ->			Dict:
						__SCREAMING_SNAKE_CASE		     =       text_classifier.model
						# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
						__SCREAMING_SNAKE_CASE		     =       "HuggingFace is in"
						__SCREAMING_SNAKE_CASE		     =       text_classifier(UpperCAmelCase__     )

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

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

						__SCREAMING_SNAKE_CASE		     =       {"text": "HuggingFace is in ", "text_pair": "Paris is in France"}
						__SCREAMING_SNAKE_CASE		     =       text_classifier(UpperCAmelCase__     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__     )    ,    {"label": ANY(UpperCAmelCase__     ), "score": ANY(UpperCAmelCase__     )}    ,    )
						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.
						__SCREAMING_SNAKE_CASE		     =       [["HuggingFace is in ", "Paris is in France"]]
						with self.assertRaises(UpperCAmelCase__     ):
											text_classifier(UpperCAmelCase__     )

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