





'''simple docstring'''


import gc
import random
import unittest

import numpy as np
import torch

from diffusers import (
    DDIMScheduler,
    KandinskyVaaControlnetPipeline,
    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_		(		__magic_name__						,unittest.TestCase		):
 __lowerCamelCase						:							List[Any]         =					KandinskyVaaControlnetPipeline
 __lowerCamelCase						:							Dict         =					["image_embeds", "negative_image_embeds", "hint"]
 __lowerCamelCase						:							List[Any]         =					["image_embeds", "negative_image_embeds", "hint"]
 __lowerCamelCase						:							List[str]         =					[
     "generator",
     "height",
     "width",
     "latents",
     "guidance_scale",
     "num_inference_steps",
     "return_dict",
     "guidance_scale",
     "num_images_per_prompt",
     "output_type",
     "return_dict",
 ]
 __lowerCamelCase						:							List[str]         =					False




 @property
 def 							_snake_case   (	self		)    ->							Union[str, Any]:
     return 32




 @property
 def 							_snake_case   (	self		)    ->							Tuple:
     return 32




 @property
 def 							_snake_case   (	self		)    ->							Tuple:
     return self.time_input_dim




 @property
 def 							_snake_case   (	self		)    ->							List[str]:
     return self.time_input_dim * 4




 @property
 def 							_snake_case   (	self		)    ->							List[str]:
     return 100




 @property
 def 							_snake_case   (	self		)    ->							Optional[int]:
     torch.manual_seed(0		)

     _lowerCAmelCase				=      {
         "in_channels": 8,
         # Out channels is double in channels because predicts mean and variance
         "out_channels": 8,
         "addition_embed_type": "image_hint",
         "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,
     }

     _lowerCAmelCase				=      UNetaDConditionModel(**_lowerCAmelCase		)
     return model




 @property
 def 							_snake_case   (	self		)    ->							int:
     return {
         "block_out_channels": [32, 32, 64, 64],
         "down_block_types": [
             "DownEncoderBlock2D",
             "DownEncoderBlock2D",
             "DownEncoderBlock2D",
             "AttnDownEncoderBlock2D",
         ],
         "in_channels": 3,
         "latent_channels": 4,
         "layers_per_block": 1,
         "norm_num_groups": 8,
         "norm_type": "spatial",
         "num_vq_embeddings": 12,
         "out_channels": 3,
         "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
         "vq_embed_dim": 4,
     }




 @property
 def 							_snake_case   (	self		)    ->							List[Any]:
     torch.manual_seed(0		)
     _lowerCAmelCase				=      VQModel(**self.dummy_movq_kwargs		)
     return model




 def 							_snake_case   (	self		)    ->							Tuple:
     _lowerCAmelCase				=      self.dummy_unet
     _lowerCAmelCase				=      self.dummy_movq

     _lowerCAmelCase				=      DDIMScheduler(
         num_train_timesteps=1000			,     beta_schedule="linear"			,     beta_start=0.00085			,     beta_end=0.012			,     clip_sample=_lowerCAmelCase			,     set_alpha_to_one=_lowerCAmelCase			,     steps_offset=1			,     prediction_type="epsilon"			,     thresholding=_lowerCAmelCase			,     )

     _lowerCAmelCase				=      {
         "unet": unet,
         "scheduler": scheduler,
         "movq": movq,
     }
     return components




 def 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase=0		)    ->							int:
     _lowerCAmelCase				=      floats_tensor((1, self.text_embedder_hidden_size)			,     rng=random.Random(_lowerCAmelCase		)		).to(_lowerCAmelCase		)
     _lowerCAmelCase				=      floats_tensor((1, self.text_embedder_hidden_size)			,     rng=random.Random(seed + 1		)		).to(
         _lowerCAmelCase		)

     # create hint
     _lowerCAmelCase				=      floats_tensor((1, 3, 64, 64)			,     rng=random.Random(_lowerCAmelCase		)		).to(_lowerCAmelCase		)

     if str(_lowerCAmelCase		).startswith("mps"		):
         _lowerCAmelCase				=      torch.manual_seed(_lowerCAmelCase		)
     else:
         _lowerCAmelCase				=      torch.Generator(device=_lowerCAmelCase		).manual_seed(_lowerCAmelCase		)
     _lowerCAmelCase				=      {
         "image_embeds": image_embeds,
         "negative_image_embeds": negative_image_embeds,
         "hint": hint,
         "generator": generator,
         "height": 64,
         "width": 64,
         "guidance_scale": 4.0,
         "num_inference_steps": 2,
         "output_type": "np",
     }
     return inputs





 def 							_snake_case   (	self		)    ->							Union[str, Any]:
     _lowerCAmelCase				=      "cpu"

     _lowerCAmelCase				=      self.get_dummy_components()

     _lowerCAmelCase				=      self.pipeline_class(**_lowerCAmelCase		)
     _lowerCAmelCase				=      pipe.to(_lowerCAmelCase		)

     pipe.set_progress_bar_config(disable=_lowerCAmelCase		)

     _lowerCAmelCase				=      pipe(**self.get_dummy_inputs(_lowerCAmelCase		)		)
     _lowerCAmelCase				=      output.images

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

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

     assert image.shape == (1, 64, 64, 3)

     _lowerCAmelCase				=      np.array(
         [0.6959826, 0.868279, 0.7558092, 0.68769467, 0.85805804, 0.65977496, 0.44885302, 0.5959111, 0.4251595]		)

     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		):




 def 							_snake_case   (	self		)    ->							int:
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()





 def 							_snake_case   (	self		)    ->							Optional[int]:
     _lowerCAmelCase				=      load_numpy(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
         "/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy"		)

     _lowerCAmelCase				=      load_image(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
         "/kandinskyv22/hint_image_cat.png"		)
     _lowerCAmelCase				=      torch.from_numpy(np.array(_lowerCAmelCase		)		).float() / 255.0
     _lowerCAmelCase				=      hint.permute(2			,     0			,     1		).unsqueeze(0		)

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

     _lowerCAmelCase				=      KandinskyVaaControlnetPipeline.from_pretrained(
         "kandinsky-community/kandinsky-2-2-controlnet-depth"			,     torch_dtype=torch.floataa		)
     _lowerCAmelCase				=      pipeline.to(_lowerCAmelCase		)
     pipeline.set_progress_bar_config(disable=_lowerCAmelCase		)

     _lowerCAmelCase				=      "A robot, 4k photo"

     _lowerCAmelCase				=      torch.Generator(device="cuda"		).manual_seed(0		)
     _lowerCAmelCase			,			_lowerCAmelCase				=      pipe_prior(
         _lowerCAmelCase			,     generator=_lowerCAmelCase			,     num_inference_steps=5			,     negative_prompt=""			,     ).to_tuple()

     _lowerCAmelCase				=      torch.Generator(device="cuda"		).manual_seed(0		)
     _lowerCAmelCase				=      pipeline(
         image_embeds=_lowerCAmelCase			,     negative_image_embeds=_lowerCAmelCase			,     hint=_lowerCAmelCase			,     generator=_lowerCAmelCase			,     num_inference_steps=100			,     output_type="np"			,     )

     _lowerCAmelCase				=      output.images[0]

     assert image.shape == (512, 512, 3)

     assert_mean_pixel_difference(_lowerCAmelCase			,     _lowerCAmelCase		)









'''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.
_SCREAMING_SNAKE_CASE	 =							{"LayoutLMv2Config", "LayoutLMv3Config"}

@is_pipeline_test
class    lowerCAmelCase_		(		unittest.TestCase		):
 __lowerCamelCase						:							Optional[Any]         =					MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
 __lowerCamelCase						:							str         =					TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

 if model_mapping is not None:
  __lowerCamelCase						:							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:
  __lowerCamelCase						:							List[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:
     _lowerCAmelCase				=      pipeline(
         task="text-classification"			,     model="hf-internal-testing/tiny-random-distilbert"			,     framework="pt"		)

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

     _lowerCAmelCase				=      text_classifier("This is great !"			,     top_k=2		)
     self.assertEqual(
         nested_simplify(_lowerCAmelCase		)			,     [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]		)

     _lowerCAmelCase				=      text_classifier(["This is great !", "This is bad"]			,     top_k=2		)
     self.assertEqual(
         nested_simplify(_lowerCAmelCase		)			,     [
             [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
             [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
         ]			,     )

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

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

     _lowerCAmelCase				=      text_classifier("This is great !"			,     return_all_scores=_lowerCAmelCase		)
     self.assertEqual(
         nested_simplify(_lowerCAmelCase		)			,     [[{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]]		)

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

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




 @require_torch
 def 							_snake_case   (	self		)    ->							Tuple:
     import torch

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

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




 @require_tf
 def 							_snake_case   (	self		)    ->							Any:
     _lowerCAmelCase				=      pipeline(
         task="text-classification"			,     model="hf-internal-testing/tiny-random-distilbert"			,     framework="tf"		)

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




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

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




 @slow
 @require_tf
 def 							_snake_case   (	self		)    ->							Any:
     _lowerCAmelCase				=      pipeline("text-classification"			,     framework="tf"		)

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




 def 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase			,     _lowerCAmelCase		)    ->							str:
     _lowerCAmelCase				=      TextClassificationPipeline(model=_lowerCAmelCase			,     tokenizer=_lowerCAmelCase		)
     return text_classifier, ["HuggingFace is in", "This is another test"]





 def 							_snake_case   (	self			,     _lowerCAmelCase			,     _lowerCAmelCase		)    ->							Union[str, Any]:
     _lowerCAmelCase				=      text_classifier.model
     # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
     _lowerCAmelCase				=      "HuggingFace is in"
     _lowerCAmelCase				=      text_classifier(_lowerCAmelCase		)

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

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

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


