




"""simple docstring"""





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   =       """src/transformers"""
A   =       """docs/source/en/tasks"""

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase				,       UpperCamelCase							)			->			Union[str, Any]:


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

			__UpperCAmelCase	: Tuple		=					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.
A   =       direct_transformers_import(TRANSFORMERS_PATH)

A   =       {
    """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   =       {
    """summarization.md""": ("""nllb""",),
    """translation.md""": ("""nllb""",),
}

def 					_UpperCamelCase    (			UpperCamelCase							)			->			Optional[int]:


			"""simple docstring"""
			__UpperCAmelCase	: Optional[Any]		=					TASK_GUIDE_TO_MODELS[task_guide]
			__UpperCAmelCase	: List[Any]		=					SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(UpperCamelCase				,       set()							)
			__UpperCAmelCase	: Tuple		=					{
			    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    (			UpperCamelCase				,       UpperCamelCase=False							)			->			Union[str, Any]:


			"""simple docstring"""
			__UpperCAmelCase	,     __UpperCAmelCase	,     __UpperCAmelCase	,     __UpperCAmelCase	: List[str]		=					_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	: Optional[Any]		=					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__":
					A   =       argparse.ArgumentParser()
					parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
					A   =       parser.parse_args()

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










"""simple docstring"""





import argparse

import torch
from datasets import load_dataset
from donut import DonutModel

from transformers import (
    DonutImageProcessor,
    DonutProcessor,
    DonutSwinConfig,
    DonutSwinModel,
    MBartConfig,
    MBartForCausalLM,
    VisionEncoderDecoderModel,
    XLMRobertaTokenizerFast,
)

def 					_UpperCamelCase    (			UpperCamelCase							)			->			Tuple:


			"""simple docstring"""
			__UpperCAmelCase	: str		=					model.config

			__UpperCAmelCase	: int		=					DonutSwinConfig(
			    image_size=original_config.input_size				,       patch_size=4				,       depths=original_config.encoder_layer				,       num_heads=[4, 8, 16, 32]				,       window_size=original_config.window_size				,       embed_dim=128				,       )
			__UpperCAmelCase	: Union[str, Any]		=					MBartConfig(
			    is_decoder=UpperCamelCase				,       is_encoder_decoder=UpperCamelCase				,       add_cross_attention=UpperCamelCase				,       decoder_layers=original_config.decoder_layer				,       max_position_embeddings=original_config.max_position_embeddings				,       vocab_size=len(
			        model.decoder.tokenizer							)				,       scale_embedding=UpperCamelCase				,       add_final_layer_norm=UpperCamelCase				,       )

			return encoder_config, decoder_config

def 					_UpperCamelCase    (			UpperCamelCase							)			->			Union[str, Any]:


			"""simple docstring"""
			if "encoder.model" in name:
						__UpperCAmelCase	: Union[str, Any]		=					name.replace("encoder.model"				,       "encoder"							)
			if "decoder.model" in name:
						__UpperCAmelCase	: Dict		=					name.replace("decoder.model"				,       "decoder"							)
			if "patch_embed.proj" in name:
						__UpperCAmelCase	: Dict		=					name.replace("patch_embed.proj"				,       "embeddings.patch_embeddings.projection"							)
			if "patch_embed.norm" in name:
						__UpperCAmelCase	: str		=					name.replace("patch_embed.norm"				,       "embeddings.norm"							)
			if name.startswith("encoder"							):
						if "layers" in name:
									__UpperCAmelCase	: Dict		=					"encoder." + name
						if "attn.proj" in name:
									__UpperCAmelCase	: List[Any]		=					name.replace("attn.proj"				,       "attention.output.dense"							)
						if "attn" in name and "mask" not in name:
									__UpperCAmelCase	: int		=					name.replace("attn"				,       "attention.self"							)
						if "norm1" in name:
									__UpperCAmelCase	: Optional[Any]		=					name.replace("norm1"				,       "layernorm_before"							)
						if "norm2" in name:
									__UpperCAmelCase	: str		=					name.replace("norm2"				,       "layernorm_after"							)
						if "mlp.fc1" in name:
									__UpperCAmelCase	: str		=					name.replace("mlp.fc1"				,       "intermediate.dense"							)
						if "mlp.fc2" in name:
									__UpperCAmelCase	: Union[str, Any]		=					name.replace("mlp.fc2"				,       "output.dense"							)

						if name == "encoder.norm.weight":
									__UpperCAmelCase	: List[Any]		=					"encoder.layernorm.weight"
						if name == "encoder.norm.bias":
									__UpperCAmelCase	: Tuple		=					"encoder.layernorm.bias"

			return name

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase							)			->			List[Any]:


			"""simple docstring"""
			for key in orig_state_dict.copy().keys():
						__UpperCAmelCase	: Any		=					orig_state_dict.pop(UpperCamelCase							)

						if "qkv" in key:
									__UpperCAmelCase	: Any		=					key.split("."							)
									__UpperCAmelCase	: List[Any]		=					int(key_split[3]							)
									__UpperCAmelCase	: Any		=					int(key_split[5]							)
									__UpperCAmelCase	: str		=					model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size

									if "weight" in key:
												__UpperCAmelCase	: List[Any]		=					val[:dim, :]
												__UpperCAmelCase	: Union[str, Any]		=					val[dim : dim * 2, :]
												__UpperCAmelCase	: Any		=					val[-dim:, :]
									else:
												__UpperCAmelCase	: List[str]		=					val[:dim]
												__UpperCAmelCase	: List[Any]		=					val[dim : dim * 2]
												__UpperCAmelCase	: Tuple		=					val[-dim:]
						elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]:
									# HuggingFace implementation doesn't use attn_mask buffer
									# and model doesn't use final LayerNorms for the encoder
									pass
						else:
									__UpperCAmelCase	: Dict		=					val

			return orig_state_dict

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase=None				,       UpperCamelCase=False							)			->			List[str]:


			"""simple docstring"""
			# load original model
			__UpperCAmelCase	: Dict		=					DonutModel.from_pretrained(UpperCamelCase							).eval()

			# load HuggingFace model
			__UpperCAmelCase	,     __UpperCAmelCase	: List[str]		=					get_configs(UpperCamelCase							)
			__UpperCAmelCase	: Tuple		=					DonutSwinModel(UpperCamelCase							)
			__UpperCAmelCase	: Optional[Any]		=					MBartForCausalLM(UpperCamelCase							)
			__UpperCAmelCase	: int		=					VisionEncoderDecoderModel(encoder=UpperCamelCase				,       decoder=UpperCamelCase							)
			model.eval()

			__UpperCAmelCase	: Union[str, Any]		=					original_model.state_dict()
			__UpperCAmelCase	: List[str]		=					convert_state_dict(UpperCamelCase				,       UpperCamelCase							)
			model.load_state_dict(UpperCamelCase							)

			# verify results on scanned document
			__UpperCAmelCase	: List[Any]		=					load_dataset("hf-internal-testing/example-documents"							)
			__UpperCAmelCase	: Any		=					dataset["test"][0]["image"].convert("RGB"							)

			__UpperCAmelCase	: Union[str, Any]		=					XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase				,       from_slow=UpperCamelCase							)
			__UpperCAmelCase	: str		=					DonutImageProcessor(
			    do_align_long_axis=original_model.config.align_long_axis				,       size=original_model.config.input_size[::-1]							)
			__UpperCAmelCase	: Union[str, Any]		=					DonutProcessor(UpperCamelCase				,       UpperCamelCase							)
			__UpperCAmelCase	: Union[str, Any]		=					processor(UpperCamelCase				,       return_tensors="pt"							).pixel_values

			if model_name == "naver-clova-ix/donut-base-finetuned-docvqa":
						__UpperCAmelCase	: List[Any]		=					"<s_docvqa><s_question>{user_input}</s_question><s_answer>"
						__UpperCAmelCase	: Any		=					"When is the coffee break?"
						__UpperCAmelCase	: Dict		=					task_prompt.replace("{user_input}"				,       UpperCamelCase							)
			elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip":
						__UpperCAmelCase	: int		=					"<s_rvlcdip>"
			elif model_name in [
			    "naver-clova-ix/donut-base-finetuned-cord-v1",
			    "naver-clova-ix/donut-base-finetuned-cord-v1-2560",
			]:
						__UpperCAmelCase	: Union[str, Any]		=					"<s_cord>"
			elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2":
						__UpperCAmelCase	: Dict		=					"s_cord-v2>"
			elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket":
						__UpperCAmelCase	: str		=					"<s_zhtrainticket>"
			elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]:
						# use a random prompt
						__UpperCAmelCase	: Tuple		=					"hello world"
			else:
						raise ValueError("Model name not supported"							)
			__UpperCAmelCase	: Dict		=					original_model.decoder.tokenizer(UpperCamelCase				,       add_special_tokens=UpperCamelCase				,       return_tensors="pt"							)[
			    "input_ids"
			]

			__UpperCAmelCase	: int		=					original_model.encoder.model.patch_embed(UpperCamelCase							)
			__UpperCAmelCase	,     __UpperCAmelCase	: Tuple		=					model.encoder.embeddings(UpperCamelCase							)
			assert torch.allclose(UpperCamelCase				,       UpperCamelCase				,       atol=1e-3							)

			# verify encoder hidden states
			__UpperCAmelCase	: int		=					original_model.encoder(UpperCamelCase							)
			__UpperCAmelCase	: Union[str, Any]		=					model.encoder(UpperCamelCase							).last_hidden_state
			assert torch.allclose(UpperCamelCase				,       UpperCamelCase				,       atol=1e-2							)

			# verify decoder hidden states
			__UpperCAmelCase	: int		=					original_model(UpperCamelCase				,       UpperCamelCase				,       UpperCamelCase							).logits
			__UpperCAmelCase	: List[str]		=					model(UpperCamelCase				,       decoder_input_ids=UpperCamelCase							).logits
			assert torch.allclose(UpperCamelCase				,       UpperCamelCase				,       atol=1e-3							)
			print("Looks ok!"							)

			if pytorch_dump_folder_path is not None:
						print(f"Saving model and processor to {pytorch_dump_folder_path}"							)
						model.save_pretrained(UpperCamelCase							)
						processor.save_pretrained(UpperCamelCase							)

			if push_to_hub:
						model.push_to_hub("nielsr/" + model_name.split("/"							)[-1]				,       commit_message="Update model"							)
						processor.push_to_hub("nielsr/" + model_name.split("/"							)[-1]				,       commit_message="Update model"							)


if __name__ == "__main__":
					A   =       argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    """--model_name""",
					    default="""naver-clova-ix/donut-base-finetuned-docvqa""",
					    required=False,
					    type=str,
					    help="""Name of the original model you'd like to convert.""",
					)
					parser.add_argument(
					    """--pytorch_dump_folder_path""",
					    default=None,
					    required=False,
					    type=str,
					    help="""Path to the output PyTorch model directory.""",
					)
					parser.add_argument(
					    """--push_to_hub""",
					    action="""store_true""",
					    help="""Whether or not to push the converted model and processor to the 🤗 hub.""",
					)

					A   =       parser.parse_args()
					convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)


