





"""simple docstring"""





import unittest

import numpy as np
import torch

from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




class  _lowerCAmelCase  (     lowercase					,unittest.TestCase       ):







 """simple docstring"""







 __UpperCAmelCase     : List[str]       		=     DDIMPipeline
 __UpperCAmelCase     : Any       		=     UNCONDITIONAL_IMAGE_GENERATION_PARAMS
 __UpperCAmelCase     : str       		=     PipelineTesterMixin.required_optional_params - {
     "num_images_per_prompt",
     "latents",
     "callback",
     "callback_steps",
 }
 __UpperCAmelCase     : Dict       		=     UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
 __UpperCAmelCase     : Dict       		=     False


 def  _lowercase			(      self							:      Optional[int]     ):
    torch.manual_seed(0     )
    __lowercase								=						UNetaDModel(
        block_out_channels=(3_2, 6_4), layers_per_block=2, sample_size=3_2, in_channels=3, out_channels=3, down_block_types=("DownBlock2D", "AttnDownBlock2D"), up_block_types=("AttnUpBlock2D", "UpBlock2D"), )
    __lowercase								=						DDIMScheduler()
    __lowercase								=						{"unet": unet, "scheduler": scheduler}
    return components


 def  _lowercase			(      self							:      Optional[Any], UpperCAmelCase__							:      Optional[Any], UpperCAmelCase__							:      List[str]=0     ):
    if str(UpperCAmelCase__     ).startswith("mps"     ):
       __lowercase								=						torch.manual_seed(UpperCAmelCase__     )
    else:
       __lowercase								=						torch.Generator(device=UpperCAmelCase__     ).manual_seed(UpperCAmelCase__     )
    __lowercase								=						{
        "batch_size": 1,
        "generator": generator,
        "num_inference_steps": 2,
        "output_type": "numpy",
    }
    return inputs


 def  _lowercase			(      self							:      Any     ):
    __lowercase								=						"cpu"

    __lowercase								=						self.get_dummy_components()
    __lowercase								=						self.pipeline_class(**UpperCAmelCase__     )
    pipe.to(UpperCAmelCase__     )
    pipe.set_progress_bar_config(disable=UpperCAmelCase__     )

    __lowercase								=						self.get_dummy_inputs(UpperCAmelCase__     )
    __lowercase								=						pipe(**UpperCAmelCase__     ).images
    __lowercase								=						image[0, -3:, -3:, -1]

    self.assertEqual(image.shape, (1, 3_2, 3_2, 3)     )
    __lowercase								=						np.array(
        [1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04]     )
    __lowercase								=						np.abs(image_slice.flatten() - expected_slice     ).max()
    self.assertLessEqual(UpperCAmelCase__, 1E-3     )


 def  _lowercase			(      self							:      int     ):
    super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3     )


 def  _lowercase			(      self							:      List[str]     ):
    super().test_save_load_local(expected_max_difference=3E-3     )


 def  _lowercase			(      self							:      List[str]     ):
    super().test_save_load_optional_components(expected_max_difference=3E-3     )



 def  _lowercase			(      self							:      List[str]     ):
    super().test_inference_batch_single_identical(expected_max_diff=3E-3     )







@slow
@require_torch_gpu
class  _lowerCAmelCase  (     unittest.TestCase       ):







 """simple docstring"""







 def  _lowercase			(      self							:      str     ):
    __lowercase								=						"google/ddpm-cifar10-32"

    __lowercase								=						UNetaDModel.from_pretrained(UpperCAmelCase__     )
    __lowercase								=						DDIMScheduler()

    __lowercase								=						DDIMPipeline(unet=UpperCAmelCase__, scheduler=UpperCAmelCase__     )
    ddim.to(UpperCAmelCase__     )
    ddim.set_progress_bar_config(disable=UpperCAmelCase__     )

    __lowercase								=						torch.manual_seed(0     )
    __lowercase								=						ddim(generator=UpperCAmelCase__, eta=0.0, output_type="numpy"     ).images

    __lowercase								=						image[0, -3:, -3:, -1]

    assert image.shape == (1, 3_2, 3_2, 3)
    __lowercase								=						np.array([0.1_723, 0.1_617, 0.1_600, 0.1_626, 0.1_497, 0.1_513, 0.1_505, 0.1_442, 0.1_453]     )

    assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2



 def  _lowercase			(      self							:      int     ):
    __lowercase								=						"google/ddpm-ema-bedroom-256"

    __lowercase								=						UNetaDModel.from_pretrained(UpperCAmelCase__     )
    __lowercase								=						DDIMScheduler.from_pretrained(UpperCAmelCase__     )

    __lowercase								=						DDIMPipeline(unet=UpperCAmelCase__, scheduler=UpperCAmelCase__     )
    ddpm.to(UpperCAmelCase__     )
    ddpm.set_progress_bar_config(disable=UpperCAmelCase__     )

    __lowercase								=						torch.manual_seed(0     )
    __lowercase								=						ddpm(generator=UpperCAmelCase__, output_type="numpy"     ).images

    __lowercase								=						image[0, -3:, -3:, -1]

    assert image.shape == (1, 2_5_6, 2_5_6, 3)
    __lowercase								=						np.array([0.0_060, 0.0_201, 0.0_344, 0.0_024, 0.0_018, 0.0_002, 0.0_022, 0.0_000, 0.0_069]     )

    assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2







"""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  _lowerCAmelCase  (     unittest.TestCase       ):







 """simple docstring"""







 __UpperCAmelCase     : str       		=     MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
 __UpperCAmelCase     : str       		=     TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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


 @require_torch
 def  _lowercase			(      self							:      Optional[int]     ):
    __lowercase								=						pipeline(
        task="text-classification", model="hf-internal-testing/tiny-random-distilbert", framework="pt"     )

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

    __lowercase								=						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}]     )

    __lowercase								=						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}],
        ], )

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

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

    __lowercase								=						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}]]     )

    __lowercase								=						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}],
        ], )

    __lowercase								=						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  _lowercase			(      self							:      Dict     ):
    import torch

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

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


 @require_tf
 def  _lowercase			(      self							:      Union[str, Any]     ):
    __lowercase								=						pipeline(
        task="text-classification", model="hf-internal-testing/tiny-random-distilbert", framework="tf"     )

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


 @slow
 @require_torch
 def  _lowercase			(      self							:      Dict     ):
    __lowercase								=						pipeline("text-classification"     )

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


 @slow
 @require_tf
 def  _lowercase			(      self							:      Tuple     ):
    __lowercase								=						pipeline("text-classification", framework="tf"     )

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


 def  _lowercase			(      self							:      Union[str, Any], UpperCAmelCase__							:      str, UpperCAmelCase__							:      int, UpperCAmelCase__							:      Tuple     ):
    __lowercase								=						TextClassificationPipeline(model=UpperCAmelCase__, tokenizer=UpperCAmelCase__     )
    return text_classifier, ["HuggingFace is in", "This is another test"]



 def  _lowercase			(      self							:      Any, UpperCAmelCase__							:      List[Any], UpperCAmelCase__							:      str     ):
    __lowercase								=						text_classifier.model
    # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
    __lowercase								=						"HuggingFace is in"
    __lowercase								=						text_classifier(UpperCAmelCase__     )

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

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

    __lowercase								=						{"text": "HuggingFace is in ", "text_pair": "Paris is in France"}
    __lowercase								=						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.
    __lowercase								=						[["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
    __lowercase								=						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()     )




