


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

@is_pipeline_test
class        a	(unittest.TestCase   ):




							"""simple docstring"""


							__UpperCAmelCase					:							Union[str, Any]  						=						MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
							__UpperCAmelCase					:							Optional[int]  						=						TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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

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

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

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

														__snake_case	:    int											=     text_classifier(["This is great !", "This is bad"]					,			top_k=2       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			[
														        [{"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}],
														    ]					,			)

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

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

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

														__snake_case	:    Tuple											=     text_classifier(["This is great !", "Something else"]					,			return_all_scores=lowerCamelCase       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			[
														        [{"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}],
														    ]					,			)

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

							@require_torch
							def 					__snake_case      (							self :						Optional[int]       )			->					List[Any]:
														import torch

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

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

							@require_tf
							def 					__snake_case      (							self :						Any       )			->					Tuple:
														__snake_case	:    List[Any]											=     pipeline(
														    task="text-classification"					,			model="hf-internal-testing/tiny-random-distilbert"					,			framework="tf"       )

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

							@slow
							@require_torch
							def 					__snake_case      (							self :						int       )			->					int:
														__snake_case	:    Dict											=     pipeline("text-classification"       )

														__snake_case	:    Dict											=     text_classifier("This is great !"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "POSITIVE", "score": 1.0}]       )
														__snake_case	:    int											=     text_classifier("This is bad !"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "NEGATIVE", "score": 1.0}]       )
														__snake_case	:    str											=     text_classifier("Birds are a type of animal"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "POSITIVE", "score": 0.9_88}]       )

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

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

							def 					__snake_case      (							self :						str					,			lowerCamelCase :						Tuple					,			lowerCamelCase :						Any					,			lowerCamelCase :						Union[str, Any]       )			->					List[Any]:
														__snake_case	:    Union[str, Any]											=     TextClassificationPipeline(model=lowerCamelCase					,			tokenizer=lowerCamelCase       )
														return text_classifier, ["HuggingFace is in", "This is another test"]






							def 					__snake_case      (							self :						List[str]					,			lowerCamelCase :						Optional[Any]					,			lowerCamelCase :						Tuple       )			->					str:
														__snake_case	:    Tuple											=     text_classifier.model
														# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
														__snake_case	:    Any											=     "HuggingFace is in"
														__snake_case	:    Tuple											=     text_classifier(lowerCamelCase       )

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

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

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

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





import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
			from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
			import torch_xla.core.xla_model as xm







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if is_torch_version("<"							,			"2.0.0"			) or not hasattr(__lowerCamelCase							,			"_dynamo"			):
														return False
							return isinstance(__lowerCamelCase							,			torch._dynamo.eval_frame.OptimizedModule			)







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase = True			):
							__snake_case	:    Optional[Any]											=     (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

							__snake_case	:    Tuple											=     is_compiled_module(__lowerCamelCase			)
							if is_compiled:
														__snake_case	:    Tuple											=     model
														__snake_case	:    List[str]											=     model._orig_mod

							if is_deepspeed_available():
														options += (DeepSpeedEngine,)

							while isinstance(__lowerCamelCase							,			__lowerCamelCase			):
														__snake_case	:    List[Any]											=     model.module

							if not keep_fpaa_wrapper:
														__snake_case	:    Tuple											=     getattr(__lowerCamelCase							,			"forward"			)
														__snake_case	:    int											=     model.__dict__.pop("_original_forward"							,			__lowerCamelCase			)
														if original_forward is not None:
																					while hasattr(__lowerCamelCase							,			"__wrapped__"			):
																												__snake_case	:    str											=     forward.__wrapped__
																												if forward == original_forward:
																																			break
																					__snake_case	:    Dict											=     forward
														if getattr(__lowerCamelCase							,			"_converted_to_transformer_engine"							,			__lowerCamelCase			):
																					convert_model(__lowerCamelCase							,			to_transformer_engine=__lowerCamelCase			)

							if is_compiled:
														__snake_case	:    Tuple											=     model
														__snake_case	:    str											=     compiled_model

							return model







def        lowerCAmelCase_  (      ):
							PartialState().wait_for_everyone()







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase			):
							if PartialState().distributed_type == DistributedType.TPU:
														xm.save(__lowerCamelCase							,			__lowerCamelCase			)
							elif PartialState().local_process_index == 0:
														torch.save(__lowerCamelCase							,			__lowerCamelCase			)







@contextmanager
def        lowerCAmelCase_  (      **__lowerCamelCase			):
							for key, value in kwargs.items():
														__snake_case	:    Union[str, Any]											=     str(__lowerCamelCase			)

							yield

							for key in kwargs:
														if key.upper() in os.environ:
																					del os.environ[key.upper()]







def        lowerCAmelCase_  (      __lowerCamelCase			):
							if not hasattr(__lowerCamelCase							,			"__qualname__"			) and not hasattr(__lowerCamelCase							,			"__name__"			):
														__snake_case	:    Dict											=     getattr(__lowerCamelCase							,			"__class__"							,			__lowerCamelCase			)
							if hasattr(__lowerCamelCase							,			"__qualname__"			):
														return obj.__qualname__
							if hasattr(__lowerCamelCase							,			"__name__"			):
														return obj.__name__
							return str(__lowerCamelCase			)







def        lowerCAmelCase_  (      __lowerCamelCase							,			__lowerCamelCase			):
							for key, value in source.items():
														if isinstance(__lowerCamelCase							,			__lowerCamelCase			):
																					__snake_case	:    Tuple											=     destination.setdefault(__lowerCamelCase							,			{}			)
																					merge_dicts(__lowerCamelCase							,			__lowerCamelCase			)
														else:
																					__snake_case	:    Union[str, Any]											=     value

							return destination







def        lowerCAmelCase_  (      __lowerCamelCase = None			):
							if port is None:
														__snake_case	:    List[str]											=     2_9_5_0_0
							with socket.socket(socket.AF_INET							,			socket.SOCK_STREAM			) as s:
														return s.connect_ex(("localhost", port)			) == 0

