

"""simple docstring"""





import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaImgaImgPipeline,
    KandinskyVaaPriorPipeline,
    UNetaDConditionModel,
    VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()




class  _lowerCAmelCase  (     lowercase					,unittest.TestCase       ):







 """simple docstring"""







 __UpperCAmelCase     : Dict       		=     KandinskyVaaImgaImgPipeline
 __UpperCAmelCase     : Tuple       		=     ["image_embeds", "negative_image_embeds", "image"]
 __UpperCAmelCase     : Tuple       		=     [
     "image_embeds",
     "negative_image_embeds",
     "image",
 ]
 __UpperCAmelCase     : Any       		=     [
     "generator",
     "height",
     "width",
     "strength",
     "guidance_scale",
     "num_inference_steps",
     "return_dict",
     "guidance_scale",
     "num_images_per_prompt",
     "output_type",
     "return_dict",
 ]
 __UpperCAmelCase     : Tuple       		=     False


 @property
 def  _lowercase			(      self							:      Tuple     ):
    return 3_2


 @property
 def  _lowercase			(      self							:      Tuple     ):
    return 3_2


 @property
 def  _lowercase			(      self							:      Optional[Any]     ):
    return self.time_input_dim


 @property
 def  _lowercase			(      self							:      List[Any]     ):
    return self.time_input_dim * 4


 @property
 def  _lowercase			(      self							:      str     ):
    return 1_0_0


 @property
 def  _lowercase			(      self							:      Dict     ):
    torch.manual_seed(0     )

    __lowercase								=						{
        "in_channels": 4,
        # Out channels is double in channels because predicts mean and variance
        "out_channels": 8,
        "addition_embed_type": "image",
        "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
        "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
        "mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
        "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
        "layers_per_block": 1,
        "encoder_hid_dim": self.text_embedder_hidden_size,
        "encoder_hid_dim_type": "image_proj",
        "cross_attention_dim": self.cross_attention_dim,
        "attention_head_dim": 4,
        "resnet_time_scale_shift": "scale_shift",
        "class_embed_type": None,
    }

    __lowercase								=						UNetaDConditionModel(**UpperCAmelCase__     )
    return model


 @property
 def  _lowercase			(      self							:      Dict     ):
    return {
        "block_out_channels": [3_2, 6_4],
        "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
        "in_channels": 3,
        "latent_channels": 4,
        "layers_per_block": 1,
        "norm_num_groups": 8,
        "norm_type": "spatial",
        "num_vq_embeddings": 1_2,
        "out_channels": 3,
        "up_block_types": [
            "AttnUpDecoderBlock2D",
            "UpDecoderBlock2D",
        ],
        "vq_embed_dim": 4,
    }


 @property
 def  _lowercase			(      self							:      int     ):
    torch.manual_seed(0     )
    __lowercase								=						VQModel(**self.dummy_movq_kwargs     )
    return model


 def  _lowercase			(      self							:      int     ):
    __lowercase								=						self.dummy_unet
    __lowercase								=						self.dummy_movq

    __lowercase								=						{
        "num_train_timesteps": 1_0_0_0,
        "beta_schedule": "linear",
        "beta_start": 0.00_085,
        "beta_end": 0.012,
        "clip_sample": False,
        "set_alpha_to_one": False,
        "steps_offset": 0,
        "prediction_type": "epsilon",
        "thresholding": False,
    }

    __lowercase								=						DDIMScheduler(**UpperCAmelCase__     )

    __lowercase								=						{
        "unet": unet,
        "scheduler": scheduler,
        "movq": movq,
    }

    return components


 def  _lowercase			(      self							:      Any, UpperCAmelCase__							:      Any, UpperCAmelCase__							:      Any=0     ):
    __lowercase								=						floats_tensor((1, self.text_embedder_hidden_size), rng=random.Random(UpperCAmelCase__     )     ).to(UpperCAmelCase__     )
    __lowercase								=						floats_tensor((1, self.text_embedder_hidden_size), rng=random.Random(seed + 1     )     ).to(
        UpperCAmelCase__     )
    # create init_image
    __lowercase								=						floats_tensor((1, 3, 6_4, 6_4), rng=random.Random(UpperCAmelCase__     )     ).to(UpperCAmelCase__     )
    __lowercase								=						image.cpu().permute(0, 2, 3, 1     )[0]
    __lowercase								=						Image.fromarray(np.uinta(UpperCAmelCase__     )     ).convert("RGB"     ).resize((2_5_6, 2_5_6)     )

    if str(UpperCAmelCase__     ).startswith("mps"     ):
       __lowercase								=						torch.manual_seed(UpperCAmelCase__     )
    else:
       __lowercase								=						torch.Generator(device=UpperCAmelCase__     ).manual_seed(UpperCAmelCase__     )
    __lowercase								=						{
        "image": init_image,
        "image_embeds": image_embeds,
        "negative_image_embeds": negative_image_embeds,
        "generator": generator,
        "height": 6_4,
        "width": 6_4,
        "num_inference_steps": 1_0,
        "guidance_scale": 7.0,
        "strength": 0.2,
        "output_type": "np",
    }
    return inputs



 def  _lowercase			(      self							:      List[Any]     ):
    __lowercase								=						"cpu"

    __lowercase								=						self.get_dummy_components()

    __lowercase								=						self.pipeline_class(**UpperCAmelCase__     )
    __lowercase								=						pipe.to(UpperCAmelCase__     )

    pipe.set_progress_bar_config(disable=UpperCAmelCase__     )

    __lowercase								=						pipe(**self.get_dummy_inputs(UpperCAmelCase__     )     )
    __lowercase								=						output.images

    __lowercase								=						pipe(
        **self.get_dummy_inputs(UpperCAmelCase__     ), return_dict=UpperCAmelCase__, )[0]

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

    assert image.shape == (1, 6_4, 6_4, 3)

    __lowercase								=						np.array(
        [0.6_199_778, 0.63_984_406, 0.46_145_785, 0.62_944_984, 0.5_622_215, 0.47_306_132, 0.47_441_456, 0.4_607_606, 0.48_719_263]     )
    assert (
        np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2
    ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}"""
    assert (
        np.abs(image_from_tuple_slice.flatten() - expected_slice     ).max() < 1E-2
    ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"""







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







 """simple docstring"""







 def  _lowercase			(      self							:      Tuple     ):
    # clean up the VRAM after each test
    super().tearDown()
    gc.collect()
    torch.cuda.empty_cache()



 def  _lowercase			(      self							:      str     ):
    __lowercase								=						load_numpy(
        "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
        "/kandinskyv22/kandinskyv22_img2img_frog.npy"     )

    __lowercase								=						load_image(
        "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png"     )
    __lowercase								=						"A red cartoon frog, 4k"

    __lowercase								=						KandinskyVaaPriorPipeline.from_pretrained(
        "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.floataa     )
    pipe_prior.to(UpperCAmelCase__     )

    __lowercase								=						KandinskyVaaImgaImgPipeline.from_pretrained(
        "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.floataa     )
    __lowercase								=						pipeline.to(UpperCAmelCase__     )

    pipeline.set_progress_bar_config(disable=UpperCAmelCase__     )

    __lowercase								=						torch.Generator(device="cpu"     ).manual_seed(0     )
    __lowercase		,__lowercase								=						pipe_prior(
        UpperCAmelCase__, generator=UpperCAmelCase__, num_inference_steps=5, negative_prompt="", ).to_tuple()

    __lowercase								=						pipeline(
        image=UpperCAmelCase__, image_embeds=UpperCAmelCase__, negative_image_embeds=UpperCAmelCase__, generator=UpperCAmelCase__, num_inference_steps=1_0_0, height=7_6_8, width=7_6_8, strength=0.2, output_type="np", )

    __lowercase								=						output.images[0]

    assert image.shape == (7_6_8, 7_6_8, 3)

    assert_mean_pixel_difference(UpperCAmelCase__, UpperCAmelCase__     )







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




