


"""simple docstring"""







import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import MobileNetVaImageProcessor




class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	def __init__(				self    :       Any    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       Optional[int]=7    ,    UpperCAmelCase__    :       Tuple=3    ,    UpperCAmelCase__    :       Dict=1_8    ,    UpperCAmelCase__    :       List[Any]=3_0    ,    UpperCAmelCase__    :       List[str]=4_0_0    ,    UpperCAmelCase__    :       Union[str, Any]=True    ,    UpperCAmelCase__    :       Dict=None    ,    UpperCAmelCase__    :       Tuple=True    ,    UpperCAmelCase__    :       Tuple=None    ,    ) ->			List[str]:
						__SCREAMING_SNAKE_CASE		     =       size if size is not None else {"shortest_edge": 2_0}
						__SCREAMING_SNAKE_CASE		     =       crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
						__SCREAMING_SNAKE_CASE		     =       parent
						__SCREAMING_SNAKE_CASE		     =       batch_size
						__SCREAMING_SNAKE_CASE		     =       num_channels
						__SCREAMING_SNAKE_CASE		     =       image_size
						__SCREAMING_SNAKE_CASE		     =       min_resolution
						__SCREAMING_SNAKE_CASE		     =       max_resolution
						__SCREAMING_SNAKE_CASE		     =       do_resize
						__SCREAMING_SNAKE_CASE		     =       size
						__SCREAMING_SNAKE_CASE		     =       do_center_crop
						__SCREAMING_SNAKE_CASE		     =       crop_size




	def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			Tuple:
						return {
						    "do_resize": self.do_resize,
						    "size": self.size,
						    "do_center_crop": self.do_center_crop,
						    "crop_size": self.crop_size,
						}




@require_torch
@require_vision
class 				UpperCamelCase_			(				UpperCamelCase    ,						unittest.TestCase):

	"""simple docstring"""





	snake_case__       :						List[Any]					      =    MobileNetVaImageProcessor if is_vision_available() else None




	def 						UpperCAmelCase_   (				self    :       str     ) ->			Tuple:
						__SCREAMING_SNAKE_CASE		     =       MobileNetVaImageProcessingTester(self     )




	@property
	def 						UpperCAmelCase_   (				self    :       Any     ) ->			List[Any]:
						return self.image_processor_tester.prepare_image_processor_dict()




	def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			Optional[int]:
						__SCREAMING_SNAKE_CASE		     =       self.image_processing_class(**self.image_processor_dict     )
						self.assertTrue(hasattr(UpperCAmelCase__    ,    "do_resize"     )     )
						self.assertTrue(hasattr(UpperCAmelCase__    ,    "size"     )     )
						self.assertTrue(hasattr(UpperCAmelCase__    ,    "do_center_crop"     )     )
						self.assertTrue(hasattr(UpperCAmelCase__    ,    "crop_size"     )     )




	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			List[str]:
						__SCREAMING_SNAKE_CASE		     =       self.image_processing_class.from_dict(self.image_processor_dict     )
						self.assertEqual(image_processor.size    ,    {"shortest_edge": 2_0}     )
						self.assertEqual(image_processor.crop_size    ,    {"height": 1_8, "width": 1_8}     )

						__SCREAMING_SNAKE_CASE		     =       self.image_processing_class.from_dict(self.image_processor_dict    ,    size=4_2    ,    crop_size=8_4     )
						self.assertEqual(image_processor.size    ,    {"shortest_edge": 4_2}     )
						self.assertEqual(image_processor.crop_size    ,    {"height": 8_4, "width": 8_4}     )




	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			Tuple:
						pass




	def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			int:
						# Initialize image_processing
						__SCREAMING_SNAKE_CASE		     =       self.image_processing_class(**self.image_processor_dict     )
						# create random PIL images
						__SCREAMING_SNAKE_CASE		     =       prepare_image_inputs(self.image_processor_tester    ,    equal_resolution=UpperCAmelCase__     )
						for image in image_inputs:
											self.assertIsInstance(UpperCAmelCase__    ,    Image.Image     )

						# Test not batched input
						__SCREAMING_SNAKE_CASE		     =       image_processing(image_inputs[0]    ,    return_tensors="pt"     ).pixel_values
						self.assertEqual(
						    encoded_images.shape    ,    (
						        1,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["height"],
						        self.image_processor_tester.crop_size["width"],
						    )    ,    )

						# Test batched
						__SCREAMING_SNAKE_CASE		     =       image_processing(UpperCAmelCase__    ,    return_tensors="pt"     ).pixel_values
						self.assertEqual(
						    encoded_images.shape    ,    (
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["height"],
						        self.image_processor_tester.crop_size["width"],
						    )    ,    )




	def 						UpperCAmelCase_   (				self    :       int     ) ->			Optional[Any]:
						# Initialize image_processing
						__SCREAMING_SNAKE_CASE		     =       self.image_processing_class(**self.image_processor_dict     )
						# create random numpy tensors
						__SCREAMING_SNAKE_CASE		     =       prepare_image_inputs(self.image_processor_tester    ,    equal_resolution=UpperCAmelCase__    ,    numpify=UpperCAmelCase__     )
						for image in image_inputs:
											self.assertIsInstance(UpperCAmelCase__    ,    np.ndarray     )

						# Test not batched input
						__SCREAMING_SNAKE_CASE		     =       image_processing(image_inputs[0]    ,    return_tensors="pt"     ).pixel_values
						self.assertEqual(
						    encoded_images.shape    ,    (
						        1,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["height"],
						        self.image_processor_tester.crop_size["width"],
						    )    ,    )

						# Test batched
						__SCREAMING_SNAKE_CASE		     =       image_processing(UpperCAmelCase__    ,    return_tensors="pt"     ).pixel_values
						self.assertEqual(
						    encoded_images.shape    ,    (
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["height"],
						        self.image_processor_tester.crop_size["width"],
						    )    ,    )




	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			List[str]:
						# Initialize image_processing
						__SCREAMING_SNAKE_CASE		     =       self.image_processing_class(**self.image_processor_dict     )
						# create random PyTorch tensors
						__SCREAMING_SNAKE_CASE		     =       prepare_image_inputs(self.image_processor_tester    ,    equal_resolution=UpperCAmelCase__    ,    torchify=UpperCAmelCase__     )
						for image in image_inputs:
											self.assertIsInstance(UpperCAmelCase__    ,    torch.Tensor     )

						# Test not batched input
						__SCREAMING_SNAKE_CASE		     =       image_processing(image_inputs[0]    ,    return_tensors="pt"     ).pixel_values
						self.assertEqual(
						    encoded_images.shape    ,    (
						        1,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["height"],
						        self.image_processor_tester.crop_size["width"],
						    )    ,    )

						# Test batched
						__SCREAMING_SNAKE_CASE		     =       image_processing(UpperCAmelCase__    ,    return_tensors="pt"     ).pixel_values
						self.assertEqual(
						    encoded_images.shape    ,    (
						        self.image_processor_tester.batch_size,
						        self.image_processor_tester.num_channels,
						        self.image_processor_tester.crop_size["height"],
						        self.image_processor_tester.crop_size["width"],
						    )    ,    )




"""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()     )
