



"""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.
_lowerCAmelCase    :Union[str, Any]     =					{'LayoutLMv2Config', 'LayoutLMv3Config'}
@is_pipeline_test
class 							_UpperCAmelCase							( unittest.TestCase      ):





     '''simple docstring'''



     a__									=MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
     a__									=TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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





     @require_torch
     def  __lowerCAmelCase	(					self		)							->					str:
         _UpperCAmelCase							:  Optional[int]											=    pipeline(
             task='''text-classification'''       ,	model='''hf-internal-testing/tiny-random-distilbert'''       ,	framework='''pt'''		)

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

         _UpperCAmelCase							:  Union[str, Any]											=    text_classifier('''This is great !'''       ,	top_k=2		)
         self.assertEqual(
             nested_simplify(A		)       ,	[{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}]		)

         _UpperCAmelCase							:  Union[str, Any]											=    text_classifier(['''This is great !''', '''This is bad''']       ,	top_k=2		)
         self.assertEqual(
             nested_simplify(A		)       ,	[
                 [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
                 [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
             ]       ,	)

         _UpperCAmelCase							:  Optional[Any]											=    text_classifier('''This is great !'''       ,	top_k=1		)
         self.assertEqual(nested_simplify(A		)       ,	[{'''label''': '''LABEL_0''', '''score''': 0.504}]		)

         # Legacy behavior
         _UpperCAmelCase							:  List[Any]											=    text_classifier('''This is great !'''       ,	return_all_scores=A		)
         self.assertEqual(nested_simplify(A		)       ,	[{'''label''': '''LABEL_0''', '''score''': 0.504}]		)

         _UpperCAmelCase							:  Union[str, Any]											=    text_classifier('''This is great !'''       ,	return_all_scores=A		)
         self.assertEqual(
             nested_simplify(A		)       ,	[[{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}]]		)

         _UpperCAmelCase							:  str											=    text_classifier(['''This is great !''', '''Something else''']       ,	return_all_scores=A		)
         self.assertEqual(
             nested_simplify(A		)       ,	[
                 [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
                 [{'''label''': '''LABEL_0''', '''score''': 0.504}, {'''label''': '''LABEL_1''', '''score''': 0.496}],
             ]       ,	)

         _UpperCAmelCase							:  Tuple											=    text_classifier(['''This is great !''', '''Something else''']       ,	return_all_scores=A		)
         self.assertEqual(
             nested_simplify(A		)       ,	[
                 {'''label''': '''LABEL_0''', '''score''': 0.504},
                 {'''label''': '''LABEL_0''', '''score''': 0.504},
             ]       ,	)





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

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

         _UpperCAmelCase							:  str											=    text_classifier('''This is great !'''		)
         self.assertEqual(nested_simplify(A		)       ,	[{'''label''': '''LABEL_0''', '''score''': 0.504}]		)





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

         _UpperCAmelCase							:  Any											=    text_classifier('''This is great !'''		)
         self.assertEqual(nested_simplify(A		)       ,	[{'''label''': '''LABEL_0''', '''score''': 0.504}]		)





     @slow
     @require_torch
     def  __lowerCAmelCase	(					self		)							->					Dict:
         _UpperCAmelCase							:  Union[str, Any]											=    pipeline('''text-classification'''		)

         _UpperCAmelCase							:  Optional[int]											=    text_classifier('''This is great !'''		)
         self.assertEqual(nested_simplify(A		)       ,	[{'''label''': '''POSITIVE''', '''score''': 1.0}]		)
         _UpperCAmelCase							:  Optional[int]											=    text_classifier('''This is bad !'''		)
         self.assertEqual(nested_simplify(A		)       ,	[{'''label''': '''NEGATIVE''', '''score''': 1.0}]		)
         _UpperCAmelCase							:  Union[str, Any]											=    text_classifier('''Birds are a type of animal'''		)
         self.assertEqual(nested_simplify(A		)       ,	[{'''label''': '''POSITIVE''', '''score''': 0.988}]		)





     @slow
     @require_tf
     def  __lowerCAmelCase	(					self		)							->					int:
         _UpperCAmelCase							:  str											=    pipeline('''text-classification'''       ,	framework='''tf'''		)

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





     def  __lowerCAmelCase	(					self       ,	A       ,	A       ,	A		)							->					int:
         _UpperCAmelCase							:  Any											=    TextClassificationPipeline(model=A       ,	tokenizer=A		)
         return text_classifier, ["HuggingFace is in", "This is another test"]





     def  __lowerCAmelCase	(					self       ,	A       ,	A		)							->					Optional[int]:
         _UpperCAmelCase							:  List[str]											=    text_classifier.model
         # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
         _UpperCAmelCase							:  int											=    '''HuggingFace is in'''
         _UpperCAmelCase							:  Tuple											=    text_classifier(A		)

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

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

         _UpperCAmelCase							:  List[str]											=    {'''text''': '''HuggingFace is in ''', '''text_pair''': '''Paris is in France'''}
         _UpperCAmelCase							:  Optional[Any]											=    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.
         _UpperCAmelCase							:  List[str]											=    [['''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
         _UpperCAmelCase							:  Optional[Any]											=    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"""
import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin
@skip_mps
class 							_UpperCAmelCase							( a		,a		,unittest.TestCase      ):





     '''simple docstring'''



     a__									=IFImgaImgSuperResolutionPipeline
     a__									=TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''}
     a__									=TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''}      )
     a__									=PipelineTesterMixin.required_optional_params - {'''latents'''}





     def  __lowerCAmelCase	(					self		)							->					List[str]:
         return self._get_superresolution_dummy_components()





     def  __lowerCAmelCase	(					self       ,	A       ,	A=0		)							->					Union[str, Any]:
         if str(A		).startswith('''mps'''		):
             _UpperCAmelCase							:  Any											=    torch.manual_seed(A		)
         else:
             _UpperCAmelCase							:  int											=    torch.Generator(device=A		).manual_seed(A		)

         _UpperCAmelCase							:  str											=    floats_tensor((1, 3, 3_2, 3_2)       ,	rng=random.Random(A		)		).to(A		)
         _UpperCAmelCase							:  Dict											=    floats_tensor((1, 3, 1_6, 1_6)       ,	rng=random.Random(A		)		).to(A		)

         _UpperCAmelCase							:  List[Any]											=    {
             '''prompt''': '''A painting of a squirrel eating a burger''',
             '''image''': image,
             '''original_image''': original_image,
             '''generator''': generator,
             '''num_inference_steps''': 2,
             '''output_type''': '''numpy''',
         }

         return inputs





     @unittest.skipIf(
         torch_device != '''cuda''' or not is_xformers_available()       ,	reason='''XFormers attention is only available with CUDA and `xformers` installed'''       ,	)
     def  __lowerCAmelCase	(					self		)							->					List[Any]:
         self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3		)





     def  __lowerCAmelCase	(					self		)							->					List[str]:
         self._test_save_load_optional_components()





     @unittest.skipIf(torch_device != '''cuda'''       ,	reason='''float16 requires CUDA'''		)
     def  __lowerCAmelCase	(					self		)							->					Optional[Any]:
         # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
         super().test_save_load_floataa(expected_max_diff=1E-1		)





     def  __lowerCAmelCase	(					self		)							->					int:
         self._test_attention_slicing_forward_pass(expected_max_diff=1E-2		)





     def  __lowerCAmelCase	(					self		)							->					Union[str, Any]:
         self._test_save_load_local()





     def  __lowerCAmelCase	(					self		)							->					Union[str, Any]:
         self._test_inference_batch_single_identical(
             expected_max_diff=1E-2       ,	)


