

"""simple docstring"""




import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata

def 		A    (       snake_case__      ):




			'''simple docstring'''


			SCREAMING_SNAKE_CASE__									= min(re.search("""^ +"""						,			lowercase__      ).end() if t.startswith(""" """      ) else 0 for t in string.splitlines()      )
			return "\n".join([line[indent_level:] for line in string.splitlines() if indent_level < len(lowercase__      )]      )


A_							:     List[str]     =	"\\n---\nlanguage:\n- zh\n- en\ntask_ids:\n- sentiment-classification\n---\n# Begin of markdown\n\nSome cool dataset card\n"

A_							:     List[str]     =	"\\n---\n---\n# Begin of markdown\n\nSome cool dataset card\n"


A_							:     str     =	"\\n# Begin of markdown\n\nSome cool dataset card\n"





class 				lowerCamelCase  (unittest.TestCase     ):

			def    SCREAMING_SNAKE_CASE			(   self			:  List[Any]    )				->      Union[str, Any]:



						with tempfile.TemporaryDirectory() as tmp_dir:
									SCREAMING_SNAKE_CASE__									= Path(lowerCamelCase__    ) / """README.md"""
									with open(lowerCamelCase__      ,			"""w+"""    ) as readme_file:
												readme_file.write(lowerCamelCase__    )
									SCREAMING_SNAKE_CASE__									= DatasetMetadata.from_readme(lowerCamelCase__    )
									self.assertDictEqual(lowerCamelCase__      ,			{"""language""": ["""zh""", """en"""], """task_ids""": ["""sentiment-classification"""]}    )

									with open(lowerCamelCase__      ,			"""w+"""    ) as readme_file:
												readme_file.write(lowerCamelCase__    )
									SCREAMING_SNAKE_CASE__									= DatasetMetadata.from_readme(lowerCamelCase__    )
									self.assertDictEqual(lowerCamelCase__      ,			{}    )

									with open(lowerCamelCase__      ,			"""w+"""    ) as readme_file:
												readme_file.write(lowerCamelCase__    )
									SCREAMING_SNAKE_CASE__									= DatasetMetadata.from_readme(lowerCamelCase__    )
									self.assertEqual(lowerCamelCase__      ,			{}    )





			def    SCREAMING_SNAKE_CASE			(   self			:  List[str]    )				->      List[Any]:
						SCREAMING_SNAKE_CASE__									= _dedent(
						    """\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            """    )
						assert DatasetMetadata.from_yaml_string(lowerCamelCase__    )

						SCREAMING_SNAKE_CASE__									= _dedent(
						    """\
            annotations_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            task_ids:
            - open-domain-qa
            """    )
						with self.assertRaises(lowerCamelCase__    ):
									DatasetMetadata.from_yaml_string(lowerCamelCase__    )

						SCREAMING_SNAKE_CASE__									= _dedent(
						    """\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - text-classification
            task_ids:
            - multi-class-classification
            paperswithcode_id:
            - squad
            configs:
            - en
            train-eval-index:
            - config: en
              task: text-classification
              task_id: multi_class_classification
              splits:
                train_split: train
                eval_split: test
              col_mapping:
                text: text
                label: target
              metrics:
                - type: accuracy
                  name: Accuracy
            extra_gated_prompt: |
              By clicking on “Access repository” below, you also agree to ImageNet Terms of Access:
              [RESEARCHER_FULLNAME] (the \"Researcher\") has requested permission to use the ImageNet database (the \"Database\") at Princeton University and Stanford University. In exchange for such permission, Researcher hereby agrees to the following terms and conditions:
              1. Researcher shall use the Database only for non-commercial research and educational purposes.
            extra_gated_fields:
              Company: text
              Country: text
              I agree to use this model for non-commerical use ONLY: checkbox
            """    )
						assert DatasetMetadata.from_yaml_string(lowerCamelCase__    )





"""simple docstring"""




import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, 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  (A__     ,unittest.TestCase     ):
			lowerCamelCase__				:						Optional[Any]   						=							KandinskyPipeline
			lowerCamelCase__				:						Union[str, Any]   						=							[
			    'prompt',
			    'image_embeds',
			    'negative_image_embeds',
			]
			lowerCamelCase__				:						Optional[Any]   						=							['prompt', 'negative_prompt', 'image_embeds', 'negative_image_embeds']
			lowerCamelCase__				:						Union[str, Any]   						=							[
			    'generator',
			    'height',
			    'width',
			    'latents',
			    'guidance_scale',
			    'negative_prompt',
			    'num_inference_steps',
			    'return_dict',
			    'guidance_scale',
			    'num_images_per_prompt',
			    'output_type',
			    'return_dict',
			]
			lowerCamelCase__				:						Optional[Any]   						=							False

			@property
			def    SCREAMING_SNAKE_CASE			(   self			:  List[str]    )				->      List[str]:
						return 3_2

			@property
			def    SCREAMING_SNAKE_CASE			(   self			:  Any    )				->      int:
						return 3_2

			@property
			def    SCREAMING_SNAKE_CASE			(   self			:  Union[str, Any]    )				->      Any:
						return self.time_input_dim

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

			@property
			def    SCREAMING_SNAKE_CASE			(   self			:  List[str]    )				->      Optional[Any]:
						return 1_0_0

			@property
			def    SCREAMING_SNAKE_CASE			(   self			:  List[Any]    )				->      List[str]:
						SCREAMING_SNAKE_CASE__									= XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base"""    )
						return tokenizer

			@property
			def    SCREAMING_SNAKE_CASE			(   self			:  Any    )				->      Dict:
						torch.manual_seed(0    )
						SCREAMING_SNAKE_CASE__									= MCLIPConfig(
						    numDims=self.cross_attention_dim      ,			transformerDimensions=self.text_embedder_hidden_size      ,			hidden_size=self.text_embedder_hidden_size      ,			intermediate_size=3_7      ,			num_attention_heads=4      ,			num_hidden_layers=5      ,			vocab_size=1_0_0_5      ,			)

						SCREAMING_SNAKE_CASE__									= MultilingualCLIP(__UpperCAmelCase    )
						SCREAMING_SNAKE_CASE__									= text_encoder.eval()

						return text_encoder

			@property
			def    SCREAMING_SNAKE_CASE			(   self			:  str    )				->      int:
						torch.manual_seed(0    )

						SCREAMING_SNAKE_CASE__									= {
						    """in_channels""": 4,
						    # Out channels is double in channels because predicts mean and variance
						    """out_channels""": 8,
						    """addition_embed_type""": """text_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""": """text_image_proj""",
						    """cross_attention_dim""": self.cross_attention_dim,
						    """attention_head_dim""": 4,
						    """resnet_time_scale_shift""": """scale_shift""",
						    """class_embed_type""": None,
						}

						SCREAMING_SNAKE_CASE__									= UNetaDConditionModel(**__UpperCAmelCase    )
						return model

			@property
			def    SCREAMING_SNAKE_CASE			(   self			:  List[Any]    )				->      Union[str, Any]:
						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    SCREAMING_SNAKE_CASE			(   self			:  int    )				->      List[str]:
						torch.manual_seed(0    )
						SCREAMING_SNAKE_CASE__									= VQModel(**self.dummy_movq_kwargs    )
						return model

			def    SCREAMING_SNAKE_CASE			(   self			:  Any    )				->      Tuple:
						SCREAMING_SNAKE_CASE__									= self.dummy_text_encoder
						SCREAMING_SNAKE_CASE__									= self.dummy_tokenizer
						SCREAMING_SNAKE_CASE__									= self.dummy_unet
						SCREAMING_SNAKE_CASE__									= self.dummy_movq

						SCREAMING_SNAKE_CASE__									= DDIMScheduler(
						    num_train_timesteps=1_0_0_0      ,			beta_schedule="""linear"""      ,			beta_start=0.00_085      ,			beta_end=0.012      ,			clip_sample=__UpperCAmelCase      ,			set_alpha_to_one=__UpperCAmelCase      ,			steps_offset=1      ,			prediction_type="""epsilon"""      ,			thresholding=__UpperCAmelCase      ,			)

						SCREAMING_SNAKE_CASE__									= {
						    """text_encoder""": text_encoder,
						    """tokenizer""": tokenizer,
						    """unet""": unet,
						    """scheduler""": scheduler,
						    """movq""": movq,
						}
						return components

			def    SCREAMING_SNAKE_CASE			(   self			:  Optional[Any]      ,			__UpperCAmelCase			:  Dict      ,			__UpperCAmelCase			:  Optional[Any]=0    )				->      str:
						SCREAMING_SNAKE_CASE__									= floats_tensor((1, self.cross_attention_dim)      ,			rng=random.Random(__UpperCAmelCase    )    ).to(__UpperCAmelCase    )
						SCREAMING_SNAKE_CASE__									= floats_tensor((1, self.cross_attention_dim)      ,			rng=random.Random(seed + 1    )    ).to(__UpperCAmelCase    )
						if str(__UpperCAmelCase    ).startswith("""mps"""    ):
									SCREAMING_SNAKE_CASE__									= torch.manual_seed(__UpperCAmelCase    )
						else:
									SCREAMING_SNAKE_CASE__									= torch.Generator(device=__UpperCAmelCase    ).manual_seed(__UpperCAmelCase    )
						SCREAMING_SNAKE_CASE__									= {
						    """prompt""": """horse""",
						    """image_embeds""": image_embeds,
						    """negative_image_embeds""": negative_image_embeds,
						    """generator""": generator,
						    """height""": 6_4,
						    """width""": 6_4,
						    """guidance_scale""": 4.0,
						    """num_inference_steps""": 2,
						    """output_type""": """np""",
						}
						return inputs





			def    SCREAMING_SNAKE_CASE			(   self			:  List[str]    )				->      int:
						SCREAMING_SNAKE_CASE__									= """cpu"""

						SCREAMING_SNAKE_CASE__									= self.get_dummy_components()

						SCREAMING_SNAKE_CASE__									= self.pipeline_class(**__UpperCAmelCase    )
						SCREAMING_SNAKE_CASE__									= pipe.to(__UpperCAmelCase    )

						pipe.set_progress_bar_config(disable=__UpperCAmelCase    )

						SCREAMING_SNAKE_CASE__									= pipe(**self.get_dummy_inputs(__UpperCAmelCase    )    )
						SCREAMING_SNAKE_CASE__									= output.images

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

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

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

						SCREAMING_SNAKE_CASE__									= np.array(
						    [0.328_663, 1.0, 0.23_216_873, 1.0, 0.92_717_564, 0.4_639_046, 0.96_894_777, 0.31_713_378, 0.6_293_953]    )

						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    SCREAMING_SNAKE_CASE			(   self			:  Optional[Any]    )				->      List[str]:
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()





			def    SCREAMING_SNAKE_CASE			(   self			:  List[str]    )				->      Optional[int]:
						SCREAMING_SNAKE_CASE__									= load_numpy(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
						    """/kandinsky/kandinsky_text2img_cat_fp16.npy"""    )

						SCREAMING_SNAKE_CASE__									= KandinskyPriorPipeline.from_pretrained(
						    """kandinsky-community/kandinsky-2-1-prior"""      ,			torch_dtype=torch.floataa    )
						pipe_prior.to(__UpperCAmelCase    )

						SCREAMING_SNAKE_CASE__									= KandinskyPipeline.from_pretrained("""kandinsky-community/kandinsky-2-1"""      ,			torch_dtype=torch.floataa    )
						SCREAMING_SNAKE_CASE__									= pipeline.to(__UpperCAmelCase    )
						pipeline.set_progress_bar_config(disable=__UpperCAmelCase    )

						SCREAMING_SNAKE_CASE__									= """red cat, 4k photo"""

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

						SCREAMING_SNAKE_CASE__									= torch.Generator(device="""cuda"""    ).manual_seed(0    )
						SCREAMING_SNAKE_CASE__									= pipeline(
						    __UpperCAmelCase      ,			image_embeds=__UpperCAmelCase      ,			negative_image_embeds=__UpperCAmelCase      ,			generator=__UpperCAmelCase      ,			num_inference_steps=1_0_0      ,			output_type="""np"""      ,			)

						SCREAMING_SNAKE_CASE__									= output.images[0]

						assert image.shape == (5_1_2, 5_1_2, 3)

						assert_mean_pixel_difference(__UpperCAmelCase      ,			__UpperCAmelCase    )


