



"""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_			   =					{'''LayoutLMv2Config''', '''LayoutLMv3Config'''}







@is_pipeline_test
class    __lowercase     (					unittest.TestCase):







						"""simple docstring"""







						_A		:							List[Any]							       =		MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
						_A		:							Tuple							       =		TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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







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

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

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

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

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

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

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

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

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







						@require_torch
						def 						__UpperCamelCase							(self       ):
											import torch

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

											snake_case_					:		Optional[Any] 					=					text_classifier("""This is great !"""       )
											self.assertEqual(nested_simplify(lowercase__       )   ,		[{"""label""": """LABEL_0""", """score""": 0.504}]       )







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

											snake_case_					:		Optional[int] 					=					text_classifier("""This is great !"""       )
											self.assertEqual(nested_simplify(lowercase__       )   ,		[{"""label""": """LABEL_0""", """score""": 0.504}]       )







						@slow
						@require_torch
						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Tuple 					=					pipeline("""text-classification"""       )

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







						@slow
						@require_tf
						def 						__UpperCamelCase							(self       ):
											snake_case_					:		int 					=					pipeline("""text-classification"""   ,		framework="""tf"""       )

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







						def 						__UpperCamelCase							(self   ,		lowercase__   ,		lowercase__   ,		lowercase__       ):
											snake_case_					:		int 					=					TextClassificationPipeline(model=lowercase__   ,		tokenizer=lowercase__       )
											return text_classifier, ["HuggingFace is in", "This is another test"]







						def 						__UpperCamelCase							(self   ,		lowercase__   ,		lowercase__       ):
											snake_case_					:		Dict 					=					text_classifier.model
											# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
											snake_case_					:		Union[str, Any] 					=					"""HuggingFace is in"""
											snake_case_					:		str 					=					text_classifier(lowercase__       )

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

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

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

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









"""simple docstring"""

import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import CONFIG_MAPPING


a_			   =					logging.get_logger(__name__)







class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						_A		:							Optional[int]							       =		"""upernet"""







						def __init__(self   ,		lowercase__=None   ,		lowercase__=5_12   ,		lowercase__=0.02   ,		lowercase__=[1, 2, 3, 6]   ,		lowercase__=True   ,		lowercase__=0.4   ,		lowercase__=3_84   ,		lowercase__=2_56   ,		lowercase__=1   ,		lowercase__=False   ,		lowercase__=2_55   ,		**lowercase__   ,		):
											super().__init__(**lowercase__       )

											if backbone_config is None:
																logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone."""       )
																snake_case_					:		List[Any] 					=					CONFIG_MAPPING["""resnet"""](out_features=["""stage1""", """stage2""", """stage3""", """stage4"""]       )
											elif isinstance(lowercase__   ,		lowercase__       ):
																snake_case_					:		Tuple 					=					backbone_config.get("""model_type"""       )
																snake_case_					:		List[str] 					=					CONFIG_MAPPING[backbone_model_type]
																snake_case_					:		List[Any] 					=					config_class.from_dict(lowercase__       )

											snake_case_					:		List[Any] 					=					backbone_config
											snake_case_					:		Optional[Any] 					=					hidden_size
											snake_case_					:		Any 					=					initializer_range
											snake_case_					:		str 					=					pool_scales
											snake_case_					:		Dict 					=					use_auxiliary_head
											snake_case_					:		str 					=					auxiliary_loss_weight
											snake_case_					:		List[str] 					=					auxiliary_in_channels
											snake_case_					:		Optional[Any] 					=					auxiliary_channels
											snake_case_					:		Any 					=					auxiliary_num_convs
											snake_case_					:		List[Any] 					=					auxiliary_concat_input
											snake_case_					:		List[str] 					=					loss_ignore_index







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Dict 					=					copy.deepcopy(self.__dict__       )
											snake_case_					:		Union[str, Any] 					=					self.backbone_config.to_dict()
											snake_case_					:		Any 					=					self.__class__.model_type
											return output




