"""simple docstring"""







import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class 			_lowerCamelCase      (lowercase__    ,				unittest.TestCase  ):
				_snake_case  =	KandinskyPriorPipeline
				_snake_case  =	["prompt"]
				_snake_case  =	["prompt", "negative_prompt"]
				_snake_case  =	[
				    "num_images_per_prompt",
				    "generator",
				    "num_inference_steps",
				    "latents",
				    "negative_prompt",
				    "guidance_scale",
				    "output_type",
				    "return_dict",
				]
				_snake_case  =	False







				@property
				def 				__UpperCAmelCase       (			self     :							Union[str, Any]    ):

					"""simple docstring"""






					return 3_2







				@property
				def 				__UpperCAmelCase       (			self     :							Optional[Any]    ):

					"""simple docstring"""






					return 3_2







				@property
				def 				__UpperCAmelCase       (			self     :							Tuple    ):

					"""simple docstring"""






					return self.time_input_dim







				@property
				def 				__UpperCAmelCase       (			self     :							Dict    ):

					"""simple docstring"""






					return self.time_input_dim * 4







				@property
				def 				__UpperCAmelCase       (			self     :							Dict    ):

					"""simple docstring"""






					return 1_0_0







				@property
				def 				__UpperCAmelCase       (			self     :							List[Any]    ):

					"""simple docstring"""






					_lowercase			:     int      					=				CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    )
					return tokenizer







				@property
				def 				__UpperCAmelCase       (			self     :							int    ):

					"""simple docstring"""






					torch.manual_seed(0    )
					_lowercase			:     Any      					=				CLIPTextConfig(
					    bos_token_id=0      ,       eos_token_id=2      ,       hidden_size=self.text_embedder_hidden_size      ,       projection_dim=self.text_embedder_hidden_size      ,       intermediate_size=3_7      ,       layer_norm_eps=1E-05      ,       num_attention_heads=4      ,       num_hidden_layers=5      ,       pad_token_id=1      ,       vocab_size=1_0_0_0      ,       )
					return CLIPTextModelWithProjection(__lowerCamelCase    )







				@property
				def 				__UpperCAmelCase       (			self     :							Tuple    ):

					"""simple docstring"""






					torch.manual_seed(0    )

					_lowercase			:     Optional[int]      					=				{
					    "num_attention_heads": 2,
					    "attention_head_dim": 1_2,
					    "embedding_dim": self.text_embedder_hidden_size,
					    "num_layers": 1,
					}

					_lowercase			:     Optional[Any]      					=				PriorTransformer(**__lowerCamelCase    )
					# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
					_lowercase			:     Dict      					=				nn.Parameter(torch.ones(model.clip_std.shape    )    )
					return model







				@property
				def 				__UpperCAmelCase       (			self     :							Any    ):

					"""simple docstring"""






					torch.manual_seed(0    )
					_lowercase			:     List[str]      					=				CLIPVisionConfig(
					    hidden_size=self.text_embedder_hidden_size      ,       image_size=2_2_4      ,       projection_dim=self.text_embedder_hidden_size      ,       intermediate_size=3_7      ,       num_attention_heads=4      ,       num_channels=3      ,       num_hidden_layers=5      ,       patch_size=1_4      ,       )

					_lowercase			:     Union[str, Any]      					=				CLIPVisionModelWithProjection(__lowerCamelCase    )
					return model







				@property
				def 				__UpperCAmelCase       (			self     :							List[str]    ):

					"""simple docstring"""






					_lowercase			:     List[str]      					=				CLIPImageProcessor(
					    crop_size=2_2_4      ,       do_center_crop=__lowerCamelCase      ,       do_normalize=__lowerCamelCase      ,       do_resize=__lowerCamelCase      ,       image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073]      ,       image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711]      ,       resample=3      ,       size=2_2_4      ,       )

					return image_processor







				def 				__UpperCAmelCase       (			self     :							List[str]    ):

					"""simple docstring"""






					_lowercase			:     Dict      					=				self.dummy_prior
					_lowercase			:     Any      					=				self.dummy_image_encoder
					_lowercase			:     Union[str, Any]      					=				self.dummy_text_encoder
					_lowercase			:     List[Any]      					=				self.dummy_tokenizer
					_lowercase			:     Union[str, Any]      					=				self.dummy_image_processor

					_lowercase			:     Union[str, Any]      					=				UnCLIPScheduler(
					    variance_type='fixed_small_log'      ,       prediction_type='sample'      ,       num_train_timesteps=1_0_0_0      ,       clip_sample=__lowerCamelCase      ,       clip_sample_range=1_0.0      ,       )

					_lowercase			:     str      					=				{
					    "prior": prior,
					    "image_encoder": image_encoder,
					    "text_encoder": text_encoder,
					    "tokenizer": tokenizer,
					    "scheduler": scheduler,
					    "image_processor": image_processor,
					}

					return components







				def 				__UpperCAmelCase       (			self     :							List[Any]      ,       lowerCamelCase_     :							Tuple      ,       lowerCamelCase_     :							Any=0    ):

					"""simple docstring"""






					if str(__lowerCamelCase    ).startswith('mps'    ):
						_lowercase			:     List[str]      					=				torch.manual_seed(__lowerCamelCase    )
					else:
						_lowercase			:     Tuple      					=				torch.Generator(device=__lowerCamelCase    ).manual_seed(__lowerCamelCase    )
					_lowercase			:     Any      					=				{
					    "prompt": "horse",
					    "generator": generator,
					    "guidance_scale": 4.0,
					    "num_inference_steps": 2,
					    "output_type": "np",
					}
					return inputs







				def 				__UpperCAmelCase       (			self     :							Union[str, Any]    ):

					"""simple docstring"""






					_lowercase			:     str      					=				"cpu"

					_lowercase			:     List[str]      					=				self.get_dummy_components()

					_lowercase			:     str      					=				self.pipeline_class(**__lowerCamelCase    )
					_lowercase			:     str      					=				pipe.to(__lowerCamelCase    )

					pipe.set_progress_bar_config(disable=__lowerCamelCase    )

					_lowercase			:     int      					=				pipe(**self.get_dummy_inputs(__lowerCamelCase    )    )
					_lowercase			:     Any      					=				output.image_embeds

					_lowercase			:     Any      					=				pipe(
					    **self.get_dummy_inputs(__lowerCamelCase    )      ,       return_dict=__lowerCamelCase      ,       )[0]

					_lowercase			:     int      					=				image[0, -1_0:]
					_lowercase			:     List[str]      					=				image_from_tuple[0, -1_0:]

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

					_lowercase			:     str      					=				np.array(
					    [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156]    )

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







				@skip_mps
				def 				__UpperCAmelCase       (			self     :							Dict    ):

					"""simple docstring"""






					_lowercase			:     Optional[Any]      					=				torch_device == "cpu"
					_lowercase			:     Tuple      					=				True
					_lowercase			:     Optional[Any]      					=				False

					self._test_inference_batch_single_identical(
					    test_max_difference=__lowerCamelCase      ,       relax_max_difference=__lowerCamelCase      ,       test_mean_pixel_difference=__lowerCamelCase      ,       )







				@skip_mps
				def 				__UpperCAmelCase       (			self     :							Optional[Any]    ):

					"""simple docstring"""






					_lowercase			:     int      					=				torch_device == "cpu"
					_lowercase			:     Any      					=				False

					self._test_attention_slicing_forward_pass(
					    test_max_difference=__lowerCamelCase      ,       test_mean_pixel_difference=__lowerCamelCase      ,       )







import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata

def  lowercase_						(						_A     :       str		):

      """simple docstring"""




      lowerCamelCase__						:							Optional[Any]       =    min(re.search("^ +"       ,   _A		).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(_A		)]		)


A :       Optional[int]						=   "\\n---\nlanguage:\n- zh\n- en\ntask_ids:\n- sentiment-classification\n---\n# Begin of markdown\n\nSome cool dataset card\n"

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


A :       Optional[Any]						=   "\\n# Begin of markdown\n\nSome cool dataset card\n"







class      _lowercase					(				unittest.TestCase):


       """simple docstring"""




       def 		lowerCAmelCase	(  self				:     List[Any]			):


             '''simple docstring'''



             with tempfile.TemporaryDirectory() as tmp_dir:
                   lowerCamelCase__						:							List[str]       =    Path(__lowerCamelCase			) / "README.md"
                   with open(__lowerCamelCase   , "w+"			) as readme_file:
                         readme_file.write(__lowerCamelCase			)
                   lowerCamelCase__						:							Dict       =    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			)
                   lowerCamelCase__						:							Optional[Any]       =    DatasetMetadata.from_readme(__lowerCamelCase			)
                   self.assertDictEqual(__lowerCamelCase   , {}			)

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





       def 		lowerCAmelCase	(  self				:     Any			):


             '''simple docstring'''



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

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

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


