



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   (      A    ,						unittest.TestCase						):
			UpperCamelCase        =					KandinskyVaaControlnetPipeline
			UpperCamelCase        =					['''image_embeds''', '''negative_image_embeds''', '''hint''']
			UpperCamelCase        =					['''image_embeds''', '''negative_image_embeds''', '''hint''']
			UpperCamelCase        =					[
			    '''generator''',
			    '''height''',
			    '''width''',
			    '''latents''',
			    '''guidance_scale''',
			    '''num_inference_steps''',
			    '''return_dict''',
			    '''guidance_scale''',
			    '''num_images_per_prompt''',
			    '''output_type''',
			    '''return_dict''',
			]
			UpperCamelCase        =					False



			@property
			def    _lowerCamelCase	(						self       :  Dict)       ->   Tuple:



						"""simple docstring"""






						return 32



			@property
			def    _lowerCamelCase	(						self       :  Any)       ->   int:



						"""simple docstring"""






						return 32



			@property
			def    _lowerCamelCase	(						self       :  str)       ->   List[str]:



						"""simple docstring"""






						return self.time_input_dim



			@property
			def    _lowerCamelCase	(						self       :  Union[str, Any])       ->   str:



						"""simple docstring"""






						return self.time_input_dim * 4



			@property
			def    _lowerCamelCase	(						self       :  Union[str, Any])       ->   List[Any]:



						"""simple docstring"""






						return 1_00



			@property
			def    _lowerCamelCase	(						self       :  Union[str, Any])       ->   Any:



						"""simple docstring"""






						torch.manual_seed(0)

						_UpperCAmelCase			=       {
						    '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,
						}

						_UpperCAmelCase			=       UNetaDConditionModel(**A)
						return model



			@property
			def    _lowerCamelCase	(						self       :  Tuple)       ->   List[str]:



						"""simple docstring"""






						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    _lowerCamelCase	(						self       :  List[Any])       ->   Dict:



						"""simple docstring"""






						torch.manual_seed(0)
						_UpperCAmelCase			=       VQModel(**self.dummy_movq_kwargs)
						return model



			def    _lowerCamelCase	(						self       :  Optional[int])       ->   Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       self.dummy_unet
						_UpperCAmelCase			=       self.dummy_movq

						_UpperCAmelCase			=       DDIMScheduler(
						    num_train_timesteps=10_00			,		beta_schedule='linear'			,		beta_start=0.0_0_0_8_5			,		beta_end=0.0_1_2			,		clip_sample=A			,		set_alpha_to_one=A			,		steps_offset=1			,		prediction_type='epsilon'			,		thresholding=A			,		)

						_UpperCAmelCase			=       {
						    'unet': unet,
						    'scheduler': scheduler,
						    'movq': movq,
						}
						return components



			def    _lowerCamelCase	(						self       :  List[str]			,		A       :  Tuple			,		A       :  Any=0)       ->   int:



						"""simple docstring"""






						_UpperCAmelCase			=       floats_tensor((1, self.text_embedder_hidden_size)			,		rng=random.Random(A)).to(A)
						_UpperCAmelCase			=       floats_tensor((1, self.text_embedder_hidden_size)			,		rng=random.Random(seed + 1)).to(
						    A)

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

						if str(A).startswith('mps'):
									_UpperCAmelCase			=       torch.manual_seed(A)
						else:
									_UpperCAmelCase			=       torch.Generator(device=A).manual_seed(A)
						_UpperCAmelCase			=       {
						    '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    _lowerCamelCase	(						self       :  Any)       ->   Any:



						"""simple docstring"""






						_UpperCAmelCase			=       'cpu'

						_UpperCAmelCase			=       self.get_dummy_components()

						_UpperCAmelCase			=       self.pipeline_class(**A)
						_UpperCAmelCase			=       pipe.to(A)

						pipe.set_progress_bar_config(disable=A)

						_UpperCAmelCase			=       pipe(**self.get_dummy_inputs(A))
						_UpperCAmelCase			=       output.images

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

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

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

						_UpperCAmelCase			=       np.array(
						    [0.6_9_5_9_8_2_6, 0.8_6_8_2_7_9, 0.7_5_5_8_0_9_2, 0.6_8_7_6_9_4_6_7, 0.8_5_8_0_5_8_0_4, 0.6_5_9_7_7_4_9_6, 0.4_4_8_8_5_3_0_2, 0.5_9_5_9_1_1_1, 0.4_2_5_1_5_9_5])

						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    _lowerCamelCase	(						self       :  Any)       ->   List[Any]:



						"""simple docstring"""






						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()



			def    _lowerCamelCase	(						self       :  Tuple)       ->   Union[str, Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       load_numpy(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
						    '/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy')

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

						_UpperCAmelCase			=       KandinskyVaaPriorPipeline.from_pretrained(
						    'kandinsky-community/kandinsky-2-2-prior'			,		torch_dtype=torch.floataa)
						pipe_prior.to(A)

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

						_UpperCAmelCase			=       'A robot, 4k photo'

						_UpperCAmelCase			=       torch.Generator(device='cuda').manual_seed(0)
						_UpperCAmelCase	,					_UpperCAmelCase			=       pipe_prior(
						    A			,		generator=A			,		num_inference_steps=5			,		negative_prompt=''			,		).to_tuple()

						_UpperCAmelCase			=       torch.Generator(device='cuda').manual_seed(0)
						_UpperCAmelCase			=       pipeline(
						    image_embeds=A			,		negative_image_embeds=A			,		hint=A			,		generator=A			,		num_inference_steps=1_00			,		output_type='np'			,		)

						_UpperCAmelCase			=       output.images[0]

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

						assert_mean_pixel_difference(A			,		A)





import argparse
import os

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_task_guides.py
UpperCAmelCase__       =	"src/transformers"
UpperCAmelCase__       =	"docs/source/en/tasks"





def 							A     (					_UpperCAmelCase    :       List[Any]							,       _UpperCAmelCase    :       Optional[int]							,       _UpperCAmelCase    :       Any   )    ->			int:







			'''simple docstring'''
			with open(_UpperCAmelCase							,       'r'							,       encoding='utf-8'							,       newline='\n'   ) as f:
						_UpperCAmelCase			=       f.readlines()
			# Find the start prompt.
			_UpperCAmelCase			=       0
			while not lines[start_index].startswith(_UpperCAmelCase   ):
						start_index += 1
			start_index += 1

			_UpperCAmelCase			=       start_index
			while not lines[end_index].startswith(_UpperCAmelCase   ):
						end_index += 1
			end_index -= 1

			while len(lines[start_index]   ) <= 1:
						start_index += 1
			while len(lines[end_index]   ) <= 1:
						end_index -= 1
			end_index += 1
			return "".join(lines[start_index:end_index]   ), start_index, end_index, lines


# This is to make sure the transformers module imported is the one in the repo.
UpperCAmelCase__       =	direct_transformers_import(TRANSFORMERS_PATH)

UpperCAmelCase__       =	{
    "asr.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES,
    "audio_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES,
    "language_modeling.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,
    "image_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,
    "masked_language_modeling.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES,
    "multiple_choice.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES,
    "object_detection.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,
    "question_answering.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES,
    "semantic_segmentation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES,
    "sequence_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,
    "summarization.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
    "token_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
    "translation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
    "video_classification.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES,
    "document_question_answering.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES,
    "monocular_depth_estimation.md": transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES,
}

# This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any
# `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`).
UpperCAmelCase__       =	{
    "summarization.md": ("nllb",),
    "translation.md": ("nllb",),
}





def 							A     (					_UpperCAmelCase    :       List[Any]   )    ->			int:







			'''simple docstring'''
			_UpperCAmelCase			=       TASK_GUIDE_TO_MODELS[task_guide]
			_UpperCAmelCase			=       SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(_UpperCAmelCase							,       set()   )
			_UpperCAmelCase			=       {
			    code: name
			    for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
			    if (code in model_maping_names or code in special_model_types)
			}
			return ", ".join([F"[{name}](../model_doc/{code})" for code, name in model_names.items()]   ) + "\n"





def 							A     (					_UpperCAmelCase    :       Tuple							,       _UpperCAmelCase    :       Dict=False   )    ->			List[Any]:







			'''simple docstring'''
			_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase	,					_UpperCAmelCase			=       _find_text_in_file(
			    filename=os.path.join(_UpperCAmelCase							,       _UpperCAmelCase   )							,       start_prompt='<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->'							,       end_prompt='<!--End of the generated tip-->'							,       )

			_UpperCAmelCase			=       get_model_list_for_task(_UpperCAmelCase   )

			if current_list != new_list:
						if overwrite:
									with open(os.path.join(_UpperCAmelCase							,       _UpperCAmelCase   )							,       'w'							,       encoding='utf-8'							,       newline='\n'   ) as f:
												f.writelines(lines[:start_index] + [new_list] + lines[end_index:]   )
						else:
									raise ValueError(
									    F"The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`"
									    ' to fix this.'   )


if __name__ == "__main__":
							UpperCAmelCase__       =	argparse.ArgumentParser()
							parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
							UpperCAmelCase__       =	parser.parse_args()

							for task_guide in TASK_GUIDE_TO_MODELS.keys():
														check_model_list_for_task(task_guide, args.fix_and_overwrite)
