



'''simple docstring'''




import inspect
import unittest

import requests

from transformers import MgpstrConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch
							from torch import nn

							from transformers import MgpstrForSceneTextRecognition


if is_vision_available():
							from PIL import Image

							from transformers import MgpstrProcessor

class      UpperCamelCase_					:





	def __init__(    self						,						A						,						A=False						,						A=13						,						A=(32, 128)						,						A=4						,						A=3						,						A=27						,						A=38						,						A=99						,						A=99						,						A=32						,						A=5						,						A=4						,						A=4.0						,						A=257						,						A=None						,						)     ->     int:
								UpperCAmelCase	:						Union[str, Any]					=						parent
								UpperCAmelCase	:						Tuple					=						is_training
								UpperCAmelCase	:						str					=						batch_size
								UpperCAmelCase	:						Dict					=						image_size
								UpperCAmelCase	:						str					=						patch_size
								UpperCAmelCase	:						int					=						num_channels
								UpperCAmelCase	:						int					=						max_token_length
								UpperCAmelCase	:						int					=						num_character_labels
								UpperCAmelCase	:						Optional[Any]					=						num_bpe_labels
								UpperCAmelCase	:						Dict					=						num_wordpiece_labels
								UpperCAmelCase	:						Any					=						hidden_size
								UpperCAmelCase	:						Tuple					=						num_hidden_layers
								UpperCAmelCase	:						Optional[int]					=						num_attention_heads
								UpperCAmelCase	:						Optional[Any]					=						mlp_ratio
								UpperCAmelCase	:						Union[str, Any]					=						patch_embeds_hidden_size
								UpperCAmelCase	:						Any					=						output_hidden_states





	def 					_lowercase(    self       )     ->     int:
								UpperCAmelCase	:						str					=						floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]       )
								UpperCAmelCase	:						Optional[int]					=						self.get_config()
								return config, pixel_values





	def 					_lowercase(    self       )     ->     List[Any]:
								return MgpstrConfig(
								    image_size=self.image_size						,						patch_size=self.patch_size						,						num_channels=self.num_channels						,						max_token_length=self.max_token_length						,						num_character_labels=self.num_character_labels						,						num_bpe_labels=self.num_bpe_labels						,						num_wordpiece_labels=self.num_wordpiece_labels						,						hidden_size=self.hidden_size						,						num_hidden_layers=self.num_hidden_layers						,						num_attention_heads=self.num_attention_heads						,						mlp_ratio=self.mlp_ratio						,						output_hidden_states=self.output_hidden_states						,						)





	def 					_lowercase(    self						,						A						,						A       )     ->     List[str]:
								UpperCAmelCase	:						Any					=						MgpstrForSceneTextRecognition(A       )
								model.to(A       )
								model.eval()
								with torch.no_grad():
															UpperCAmelCase	:						List[str]					=						model(A       )
								self.parent.assertEqual(
								    generated_ids[0][0].shape						,						(self.batch_size, self.max_token_length, self.num_character_labels)       )






	def 					_lowercase(    self       )     ->     Union[str, Any]:
								UpperCAmelCase	:						List[Any]					=						self.prepare_config_and_inputs()
								UpperCAmelCase	,	UpperCAmelCase	:						Optional[int]					=						config_and_inputs
								UpperCAmelCase	:						List[Any]					=						{"""pixel_values""": pixel_values}
								return config, inputs_dict




@require_torch
class      UpperCamelCase_					(				__magic_name__ ,	__magic_name__ ,	unittest.TestCase     ):
	lowercase		=					(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
	lowercase		=					{'feature-extraction': MgpstrForSceneTextRecognition} if is_torch_available() else {}
	lowercase		=					False

	lowercase		=					False
	lowercase		=					False
	lowercase		=					False
	lowercase		=					False





	def 					_lowercase(    self       )     ->     Optional[int]:
								UpperCAmelCase	:						Optional[int]					=						MgpstrModelTester(self       )
								UpperCAmelCase	:						Dict					=						ConfigTester(self						,						config_class=A						,						has_text_modality=A       )





	def 					_lowercase(    self       )     ->     Union[str, Any]:
								self.config_tester.run_common_tests()





	def 					_lowercase(    self       )     ->     Dict:
								UpperCAmelCase	:						Tuple					=						self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A       )





	@unittest.skip(reason="""MgpstrModel does not use inputs_embeds"""       )
	def 					_lowercase(    self       )     ->     Tuple:
								pass





	def 					_lowercase(    self       )     ->     Any:
								UpperCAmelCase	,	UpperCAmelCase	:						int					=						self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase	:						Dict					=						model_class(A       )
															self.assertIsInstance(model.get_input_embeddings()						,						(nn.Module)       )
															UpperCAmelCase	:						Optional[Any]					=						model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(A						,						nn.Linear       )       )





	def 					_lowercase(    self       )     ->     int:
								UpperCAmelCase	,	UpperCAmelCase	:						Tuple					=						self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase	:						Union[str, Any]					=						model_class(A       )
															UpperCAmelCase	:						List[Any]					=						inspect.signature(model.forward       )
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															UpperCAmelCase	:						Dict					=						[*signature.parameters.keys()]

															UpperCAmelCase	:						List[Any]					=						["""pixel_values"""]
															self.assertListEqual(arg_names[:1]						,						A       )





	@unittest.skip(reason="""MgpstrModel does not support feedforward chunking"""       )
	def 					_lowercase(    self       )     ->     List[Any]:
								pass





	def 					_lowercase(    self       )     ->     List[str]:
								UpperCAmelCase	,	UpperCAmelCase	:						Optional[Any]					=						self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															if not model_class.supports_gradient_checkpointing:
																						continue

															UpperCAmelCase	:						Any					=						True
															UpperCAmelCase	:						str					=						model_class(A       )
															self.assertTrue(model.is_gradient_checkpointing       )





	def 					_lowercase(    self       )     ->     Optional[int]:
								def check_hidden_states_output(A						,						A						,						A       ):
															UpperCAmelCase	:						List[Any]					=						model_class(A       )
															model.to(A       )
															model.eval()

															with torch.no_grad():
																						UpperCAmelCase	:						Tuple					=						model(**self._prepare_for_class(A						,						A       )       )

															UpperCAmelCase	:						Any					=						outputs.hidden_states

															UpperCAmelCase	:						str					=						getattr(
															    self.model_tester						,						"""expected_num_hidden_layers"""						,						self.model_tester.num_hidden_layers + 1       )
															self.assertEqual(len(A       )						,						A       )

															self.assertListEqual(
															    list(hidden_states[0].shape[-2:]       )						,						[self.model_tester.patch_embeds_hidden_size, self.model_tester.hidden_size]						,						)

								UpperCAmelCase	,	UpperCAmelCase	:						Tuple					=						self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															UpperCAmelCase	:						str					=						True
															check_hidden_states_output(A						,						A						,						A       )

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															UpperCAmelCase	:						str					=						True

															check_hidden_states_output(A						,						A						,						A       )





	def 					_lowercase(    self       )     ->     Dict:
								UpperCAmelCase	,	UpperCAmelCase	:						Any					=						self.model_tester.prepare_config_and_inputs_for_common()

								UpperCAmelCase	:						Tuple					=						_config_zero_init(A       )
								for model_class in self.all_model_classes:
															UpperCAmelCase	:						Tuple					=						model_class(config=A       )
															for name, param in model.named_parameters():
																						if isinstance(A						,						(nn.Linear, nn.Convad, nn.LayerNorm)       ):
																													if param.requires_grad:
																																				self.assertIn(
																																				    ((param.data.mean() * 1e9).round() / 1e9).item()						,						[0.0, 1.0]						,						msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''						,						)






	@unittest.skip(reason="""Retain_grad is tested in individual model tests"""       )
	def 					_lowercase(    self       )     ->     Union[str, Any]:
								pass




def  __lowerCamelCase    (   ) ->     Tuple:
							UpperCAmelCase	:						str					=						"""https://i.postimg.cc/ZKwLg2Gw/367-14.png"""
							UpperCAmelCase	:						int					=						Image.open(requests.get(_lowercase      ,							stream=_lowercase						).raw						).convert("""RGB"""						)
							return im


@require_vision
@require_torch
class      UpperCamelCase_					(				unittest.TestCase     ):





	@slow
	def 					_lowercase(    self       )     ->     int:
								UpperCAmelCase	:						Optional[int]					=						"""alibaba-damo/mgp-str-base"""
								UpperCAmelCase	:						Dict					=						MgpstrForSceneTextRecognition.from_pretrained(A       ).to(A       )
								UpperCAmelCase	:						List[Any]					=						MgpstrProcessor.from_pretrained(A       )

								UpperCAmelCase	:						Optional[int]					=						prepare_img()
								UpperCAmelCase	:						List[Any]					=						processor(images=A						,						return_tensors="""pt"""       ).pixel_values.to(A       )

								# forward pass
								with torch.no_grad():
															UpperCAmelCase	:						Tuple					=						model(A       )

								# verify the logits
								self.assertEqual(outputs.logits[0].shape						,						torch.Size((1, 27, 38)       )       )

								UpperCAmelCase	:						str					=						processor.batch_decode(outputs.logits       )
								UpperCAmelCase	:						Tuple					=						"""ticket"""

								self.assertEqual(out_strs["""generated_text"""][0]						,						A       )

								UpperCAmelCase	:						Optional[int]					=						torch.tensor(
								    [[[-3_9.5_3_9_7, -4_4.4_0_2_4, -3_6.1_8_4_4], [-6_1.4_7_0_9, -6_3.8_6_3_9, -5_8.3_4_5_4], [-7_4.0_2_2_5, -6_8.5_4_9_4, -7_1.2_1_6_4]]]						,						device=A						,						)

								self.assertTrue(torch.allclose(outputs.logits[0][:, 1:4, 1:4]						,						A						,						atol=1e-4       )       )






'''simple docstring'''




import argparse
import json
import sys
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import List

import torch
import torch.nn as nn
from huggingface_hub import cached_download, hf_hub_download
from torch import Tensor

from transformers import AutoImageProcessor, VanConfig, VanForImageClassification
from transformers.models.deprecated.van.modeling_van import VanLayerScaling
from transformers.utils import logging


logging.set_verbosity_info()
a  :     Any       =       logging.get_logger(__name__)

@dataclass
class      UpperCamelCase_					:
	lowercase		=					42
	lowercase		=					field(default_factory=__magic_name__     )
	lowercase		=					field(default_factory=__magic_name__     )





	def 					_lowercase(    self						,						A						,						A						,						A       )     ->     Optional[Any]:
								UpperCAmelCase	:						Tuple					=						len(list(m.modules()       )       ) == 1 or isinstance(A						,						nn.Convad       ) or isinstance(A						,						nn.BatchNormad       )
								if has_not_submodules:
															if not isinstance(A						,						A       ):
																						self.traced.append(A       )





	def __call__(    self						,						A       )     ->     Dict:
								for m in self.module.modules():
															self.handles.append(m.register_forward_hook(self._forward_hook       )       )
								self.module(A       )
								[x.remove() for x in self.handles]
								return self






	@property
	def 					_lowercase(    self       )     ->     Dict:
								# check the len of the state_dict keys to see if we have learnable params
								return list(filter(lambda A       : len(list(x.state_dict().keys()       )       ) > 0						,						self.traced       )       )




@dataclass
class      UpperCamelCase_					:
	lowercase		=					42
	lowercase		=					42
	lowercase		=					0
	lowercase		=					field(default_factory=__magic_name__     )
	lowercase		=					field(default_factory=__magic_name__     )





	def __call__(    self						,						A       )     ->     str:
								UpperCAmelCase	:						Dict					=						Tracker(self.dest       )(A       ).parametrized
								UpperCAmelCase	:						Union[str, Any]					=						Tracker(self.src       )(A       ).parametrized

								UpperCAmelCase	:						Optional[int]					=						list(filter(lambda A       : type(A       ) not in self.src_skip						,						A       )       )
								UpperCAmelCase	:						Optional[int]					=						list(filter(lambda A       : type(A       ) not in self.dest_skip						,						A       )       )

								if len(A       ) != len(A       ):
															raise Exception(
															    f'''Numbers of operations are different. Source module has {len(A       )} operations while'''
															    f''' destination module has {len(A       )}.'''       )

								for dest_m, src_m in zip(A						,						A       ):
															dest_m.load_state_dict(src_m.state_dict()       )
															if self.verbose == 1:
																						print(f'''Transfered from={src_m} to={dest_m}'''       )




def  __lowerCamelCase    (   _lowercase      ,							_lowercase						) ->     nn.Module:
							# nn.Parameter cannot be tracked by the Tracker, thus we need to manually convert them
							UpperCAmelCase	:						Optional[Any]					=						from_model.state_dict()
							UpperCAmelCase	:						int					=						our_model.state_dict()
							UpperCAmelCase	:						Optional[int]					=						our_model.config
							UpperCAmelCase	:						str					=						[]
							for stage_idx in range(len(config.hidden_sizes						)						):
														for block_id in range(config.depths[stage_idx]						):
																					UpperCAmelCase	:						List[Any]					=						F'''block{stage_idx + 1}.{block_id}.layer_scale_1'''
																					UpperCAmelCase	:						Any					=						F'''van.encoder.stages.{stage_idx}.layers.{block_id}.attention_scaling.weight'''

																					all_keys.append((from_key, to_key)						)
																					UpperCAmelCase	:						Optional[int]					=						F'''block{stage_idx + 1}.{block_id}.layer_scale_2'''
																					UpperCAmelCase	:						str					=						F'''van.encoder.stages.{stage_idx}.layers.{block_id}.mlp_scaling.weight'''

																					all_keys.append((from_key, to_key)						)

							for from_key, to_key in all_keys:
														UpperCAmelCase	:						List[Any]					=						from_state_dict.pop(_lowercase						)

							our_model.load_state_dict(_lowercase						)
							return our_model



def  __lowerCamelCase    (   _lowercase      ,							_lowercase      ,							_lowercase      ,							_lowercase      ,							_lowercase      ,							_lowercase = True      ,							) ->     List[Any]:
							print(F'''Downloading weights for {name}...'''						)
							UpperCAmelCase	:						List[str]					=						cached_download(_lowercase						)
							print(F'''Converting {name}...'''						)
							UpperCAmelCase	:						int					=						torch.load(_lowercase						)["""state_dict"""]
							from_model.load_state_dict(_lowercase						)
							from_model.eval()
							with torch.no_grad():
														UpperCAmelCase	:						Tuple					=						VanForImageClassification(_lowercase						).eval()
														UpperCAmelCase	:						int					=						ModuleTransfer(src=_lowercase      ,							dest=_lowercase						)
														UpperCAmelCase	:						Any					=						torch.randn((1, 3, 2_2_4, 2_2_4)						)
														module_transfer(_lowercase						)
														UpperCAmelCase	:						Tuple					=						copy_parameters(_lowercase      ,							_lowercase						)

							if not torch.allclose(from_model(_lowercase						)      ,							our_model(_lowercase						).logits						):
														raise ValueError("""The model logits don't match the original one."""						)

							UpperCAmelCase	:						List[str]					=						name
							print(_lowercase						)

							if push_to_hub:
														our_model.push_to_hub(
														    repo_path_or_name=save_directory / checkpoint_name      ,							commit_message="""Add model"""      ,							use_temp_dir=_lowercase      ,							)

														# we can use the convnext one
														UpperCAmelCase	:						Dict					=						AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k"""						)
														image_processor.push_to_hub(
														    repo_path_or_name=save_directory / checkpoint_name      ,							commit_message="""Add image processor"""      ,							use_temp_dir=_lowercase      ,							)

														print(F'''Pushed {checkpoint_name}'''						)



def  __lowerCamelCase    (   _lowercase      ,							_lowercase = None      ,							_lowercase = True						) ->     List[Any]:
							UpperCAmelCase	:						int					=						"""imagenet-1k-id2label.json"""
							UpperCAmelCase	:						List[Any]					=						1_0_0_0

							UpperCAmelCase	:						str					=						"""huggingface/label-files"""
							UpperCAmelCase	:						Optional[Any]					=						num_labels
							UpperCAmelCase	:						str					=						json.load(open(hf_hub_download(_lowercase      ,							_lowercase      ,							repo_type="""dataset"""						)      ,							"""r"""						)						)
							UpperCAmelCase	:						Any					=						{int(_lowercase						): v for k, v in idalabel.items()}

							UpperCAmelCase	:						Any					=						idalabel
							UpperCAmelCase	:						List[str]					=						{v: k for k, v in idalabel.items()}

							UpperCAmelCase	:						Any					=						partial(_lowercase      ,							num_labels=_lowercase      ,							idalabel=_lowercase      ,							labelaid=_lowercase						)

							UpperCAmelCase	:						Optional[Any]					=						{
							    """van-tiny""": ImageNetPreTrainedConfig(
							        hidden_sizes=[3_2, 6_4, 1_6_0, 2_5_6]      ,							depths=[3, 3, 5, 2]      ,							mlp_ratios=[8, 8, 4, 4]      ,							),
							    """van-small""": ImageNetPreTrainedConfig(
							        hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2]      ,							depths=[2, 2, 4, 2]      ,							mlp_ratios=[8, 8, 4, 4]      ,							),
							    """van-base""": ImageNetPreTrainedConfig(
							        hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2]      ,							depths=[3, 3, 1_2, 3]      ,							mlp_ratios=[8, 8, 4, 4]      ,							),
							    """van-large""": ImageNetPreTrainedConfig(
							        hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2]      ,							depths=[3, 5, 2_7, 3]      ,							mlp_ratios=[8, 8, 4, 4]      ,							),
							}

							UpperCAmelCase	:						Optional[Any]					=						{
							    """van-tiny""": van_tiny,
							    """van-small""": van_small,
							    """van-base""": van_base,
							    """van-large""": van_large,
							}

							UpperCAmelCase	:						Optional[int]					=						{
							    """van-tiny""": (
							        """https://huggingface.co/Visual-Attention-Network/VAN-Tiny-original/resolve/main/van_tiny_754.pth.tar"""
							    ),
							    """van-small""": (
							        """https://huggingface.co/Visual-Attention-Network/VAN-Small-original/resolve/main/van_small_811.pth.tar"""
							    ),
							    """van-base""": (
							        """https://huggingface.co/Visual-Attention-Network/VAN-Base-original/resolve/main/van_base_828.pth.tar"""
							    ),
							    """van-large""": (
							        """https://huggingface.co/Visual-Attention-Network/VAN-Large-original/resolve/main/van_large_839.pth.tar"""
							    ),
							}

							if model_name:
														convert_weight_and_push(
														    _lowercase      ,							names_to_config[model_name]      ,							checkpoint=names_to_original_checkpoints[model_name]      ,							from_model=names_to_original_models[model_name]()      ,							save_directory=_lowercase      ,							push_to_hub=_lowercase      ,							)
							else:
														for model_name, config in names_to_config.items():
																					convert_weight_and_push(
																					    _lowercase      ,							_lowercase      ,							checkpoint=names_to_original_checkpoints[model_name]      ,							from_model=names_to_original_models[model_name]()      ,							save_directory=_lowercase      ,							push_to_hub=_lowercase      ,							)


if __name__ == "__main__":
							a  :     int       =       argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    """--model-name""",
							    default=None,
							    type=str,
							    help=(
							        """The name of the model you wish to convert, it must be one of the supported resnet* architecture,"""
							        """ currently: van-tiny/small/base/large. If `None`, all of them will the converted."""
							    ),
							)
							parser.add_argument(
							    """--pytorch_dump_folder_path""",
							    default=None,
							    type=Path,
							    required=True,
							    help="""Path to the output PyTorch model directory.""",
							)
							parser.add_argument(
							    """--van_dir""",
							    required=True,
							    type=Path,
							    help=(
							        """A path to VAN's original implementation directory. You can download from here:"""
							        """ https://github.com/Visual-Attention-Network/VAN-Classification"""
							    ),
							)
							parser.add_argument(
							    """--push_to_hub""",
							    default=True,
							    type=bool,
							    required=False,
							    help="""If True, push model and image processor to the hub.""",
							)

							a  :     List[str]       =       parser.parse_args()
							a  :     Path       =       args.pytorch_dump_folder_path
							pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
							a  :     Union[str, Any]       =       args.van_dir
							# append the path to the parents to maskformer dir
							sys.path.append(str(van_dir.parent))
							from van.models.van import van_base, van_large, van_small, van_tiny

							convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)

