





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
A_ :				str						 =    'src/transformers'
A_ :				Union[str, Any]						 =    'docs/source/en/tasks'

def 		UpperCamelCase      (lowercase_:				List[Any]					,   lowercase_:				List[str]					,   lowercase_:				List[Any]      )  ->   Tuple:





	with open(_lowerCamelCase					,   """r"""					,   encoding="""utf-8"""					,   newline="""\n"""      ) as f:
		A__							:					Dict       =	f.readlines()
	# Find the start prompt.
	A__							:					str       =	0
	while not lines[start_index].startswith(_lowerCamelCase      ):
		start_index += 1
	start_index += 1

	A__							:					List[str]       =	start_index
	while not lines[end_index].startswith(_lowerCamelCase      ):
		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.
A_ :				Dict						 =    direct_transformers_import(TRANSFORMERS_PATH)

A_ :				Dict						 =    {
    '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`).
A_ :				Optional[Any]						 =    {
    'summarization.md': ('nllb',),
    'translation.md': ('nllb',),
}

def 		UpperCamelCase      (lowercase_:				Union[str, Any]      )  ->   List[str]:
	A__							:					Optional[int]       =	TASK_GUIDE_TO_MODELS[task_guide]
	A__							:					str       =	SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(_lowerCamelCase					,   set()      )
	A__							:					Optional[int]       =	{
	    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 		UpperCamelCase      (lowercase_:				Tuple					,   lowercase_:				int=False      )  ->   Any:
	A__							:					List[str]       =	_find_text_in_file(
	    filename=os.path.join(_lowerCamelCase					,   _lowerCamelCase      )					,   start_prompt="""<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->"""					,   end_prompt="""<!--End of the generated tip-->"""					,   )

	A__							:					str       =	get_model_list_for_task(_lowerCamelCase      )

	if current_list != new_list:
		if overwrite:
			with open(os.path.join(_lowerCamelCase					,   _lowerCamelCase      )					,   """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__":
	A_ :				Tuple						 =    argparse.ArgumentParser()
	parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
	A_ :				Dict						 =    parser.parse_args()

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






import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    TextToVideoSDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



@skip_mps
class 					_a		(__magic_name__	,     unittest.TestCase       ):


					'''simple docstring'''






					UpperCAmelCase__:     Any													= TextToVideoSDPipeline
					UpperCAmelCase__:     Any													= TEXT_TO_IMAGE_PARAMS
					UpperCAmelCase__:     Optional[Any]													= TEXT_TO_IMAGE_BATCH_PARAMS
					# No `output_type`.
					UpperCAmelCase__:     Optional[int]													= frozenset(
					    [
					        '''num_inference_steps''',
					        '''generator''',
					        '''latents''',
					        '''return_dict''',
					        '''callback''',
					        '''callback_steps''',
					    ]       )






					def 						__A    (				self    ):
						torch.manual_seed(0    )
						A__							:					Optional[int]       =	UNetaDConditionModel(
						    block_out_channels=(32, 64, 64, 64)					, layers_per_block=2					, sample_size=32					, in_channels=4					, out_channels=4					, down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""")					, up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""")					, cross_attention_dim=32					, attention_head_dim=4					, )
						A__							:					Optional[int]       =	DDIMScheduler(
						    beta_start=0.0_0_0_8_5					, beta_end=0.0_1_2					, beta_schedule="""scaled_linear"""					, clip_sample=A__					, set_alpha_to_one=A__					, )
						torch.manual_seed(0    )
						A__							:					Union[str, Any]       =	AutoencoderKL(
						    block_out_channels=[32, 64]					, in_channels=3					, out_channels=3					, down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]					, up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]					, latent_channels=4					, sample_size=128					, )
						torch.manual_seed(0    )
						A__							:					Union[str, Any]       =	CLIPTextConfig(
						    bos_token_id=0					, eos_token_id=2					, hidden_size=32					, intermediate_size=37					, layer_norm_eps=1e-05					, num_attention_heads=4					, num_hidden_layers=5					, pad_token_id=1					, vocab_size=1000					, hidden_act="""gelu"""					, projection_dim=512					, )
						A__							:					Union[str, Any]       =	CLIPTextModel(A__    )
						A__							:					Tuple       =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )

						A__							:					Dict       =	{
						    """unet""": unet,
						    """scheduler""": scheduler,
						    """vae""": vae,
						    """text_encoder""": text_encoder,
						    """tokenizer""": tokenizer,
						}
						return components






					def 						__A    (				self					, A__					, A__=0    ):
						if str(A__    ).startswith("""mps"""    ):
							A__							:					Tuple       =	torch.manual_seed(A__    )
						else:
							A__							:					List[str]       =	torch.Generator(device=A__    ).manual_seed(A__    )
						A__							:					List[str]       =	{
						    """prompt""": """A painting of a squirrel eating a burger""",
						    """generator""": generator,
						    """num_inference_steps""": 2,
						    """guidance_scale""": 6.0,
						    """output_type""": """pt""",
						}
						return inputs






					def 						__A    (				self    ):
						A__							:					List[str]       =	"""cpu"""  # ensure determinism for the device-dependent torch.Generator
						A__							:					Union[str, Any]       =	self.get_dummy_components()
						A__							:					Union[str, Any]       =	TextToVideoSDPipeline(**A__    )
						A__							:					int       =	sd_pipe.to(A__    )
						sd_pipe.set_progress_bar_config(disable=A__    )

						A__							:					int       =	self.get_dummy_inputs(A__    )
						A__							:					int       =	"""np"""
						A__							:					Any       =	sd_pipe(**A__    ).frames
						A__							:					Dict       =	frames[0][-3:, -3:, -1]

						assert frames[0].shape == (64, 64, 3)
						A__							:					Optional[Any]       =	np.array([1_5_8.0, 1_6_0.0, 1_5_3.0, 1_2_5.0, 1_0_0.0, 1_2_1.0, 1_1_1.0, 9_3.0, 1_1_3.0]    )

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






					def 						__A    (				self    ):
						self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A__					, expected_max_diff=3e-3    )






					@unittest.skipIf(
					    torch_device != """cuda""" or not is_xformers_available()					, reason="""XFormers attention is only available with CUDA and `xformers` installed"""					, )
					def 						__A    (				self    ):
						self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A__					, expected_max_diff=1e-2    )






					@unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""    )
					def 						__A    (				self    ):
						pass






					@unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""    )
					def 						__A    (				self    ):
						pass






					@unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline."""    )
					def 						__A    (				self    ):
						pass






					def 						__A    (				self    ):
						return super().test_progress_bar()



@slow
@skip_mps
class 					_a		(unittest.TestCase       ):


					'''simple docstring'''






					def 						__A    (				self    ):
						A__							:					Union[str, Any]       =	load_numpy(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy"""    )

						A__							:					Tuple       =	TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b"""    )
						A__							:					Any       =	DPMSolverMultistepScheduler.from_config(pipe.scheduler.config    )
						A__							:					int       =	pipe.to("""cuda"""    )

						A__							:					Optional[Any]       =	"""Spiderman is surfing"""
						A__							:					List[str]       =	torch.Generator(device="""cpu"""    ).manual_seed(0    )

						A__							:					Optional[Any]       =	pipe(A__					, generator=A__					, num_inference_steps=25					, output_type="""pt"""    ).frames
						A__							:					Dict       =	video_frames.cpu().numpy()

						assert np.abs(expected_video - video    ).mean() < 5e-2






					def 						__A    (				self    ):
						A__							:					List[Any]       =	load_numpy(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy"""    )

						A__							:					Optional[int]       =	TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b"""    )
						A__							:					List[str]       =	pipe.to("""cuda"""    )

						A__							:					Dict       =	"""Spiderman is surfing"""
						A__							:					Union[str, Any]       =	torch.Generator(device="""cpu"""    ).manual_seed(0    )

						A__							:					Optional[int]       =	pipe(A__					, generator=A__					, num_inference_steps=2					, output_type="""pt"""    ).frames
						A__							:					Optional[int]       =	video_frames.cpu().numpy()

						assert np.abs(expected_video - video    ).mean() < 5e-2



