
"""simple docstring"""




import argparse
import json

import numpy
import torch

from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

def lowercase_    (  _snake_case  ,_snake_case		):
							# Load checkpoint
							SCREAMING_SNAKE_CASE__		:			List[str]	 =  torch.load(_snake_case  ,map_location="""cpu"""		)

							SCREAMING_SNAKE_CASE__		:			str	 =  chkpt['''model''']

							# We have the base model one level deeper than the original XLM repository
							SCREAMING_SNAKE_CASE__		:			Optional[int]	 =  {}
							for k, v in state_dict.items():
														if "pred_layer" in k:
																					SCREAMING_SNAKE_CASE__		:			Dict	 =  v
														else:
																					SCREAMING_SNAKE_CASE__		:			Any	 =  v

							SCREAMING_SNAKE_CASE__		:			List[Any]	 =  chkpt['''params''']
							SCREAMING_SNAKE_CASE__		:			Any	 =  {n: v for n, v in config.items() if not isinstance(_snake_case  ,(torch.FloatTensor, numpy.ndarray)		)}

							SCREAMING_SNAKE_CASE__		:			Optional[Any]	 =  chkpt['''dico_word2id''']
							SCREAMING_SNAKE_CASE__		:			Union[str, Any]	 =  {s + '''</w>''' if s.find("""@@"""		) == -1 and i > 13 else s.replace("""@@"""  ,""""""		): i for s, i in vocab.items()}

							# Save pytorch-model
							SCREAMING_SNAKE_CASE__		:			Dict	 =  pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
							SCREAMING_SNAKE_CASE__		:			Any	 =  pytorch_dump_folder_path + '''/''' + CONFIG_NAME
							SCREAMING_SNAKE_CASE__		:			List[str]	 =  pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''vocab_file''']

							print(f'''Save PyTorch model to {pytorch_weights_dump_path}'''		)
							torch.save(_snake_case  ,_snake_case		)

							print(f'''Save configuration file to {pytorch_config_dump_path}'''		)
							with open(_snake_case  ,"""w"""  ,encoding="""utf-8"""		) as f:
														f.write(json.dumps(_snake_case  ,indent=2		) + """\n"""		)

							print(f'''Save vocab file to {pytorch_config_dump_path}'''		)
							with open(_snake_case  ,"""w"""  ,encoding="""utf-8"""		) as f:
														f.write(json.dumps(_snake_case  ,indent=2		) + """\n"""		)


if __name__ == "__main__":
					UpperCAmelCase__ :       Any       				=					argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    '--xlm_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.'
					)
					parser.add_argument(
					    '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
					)
					UpperCAmelCase__ :       str       				=					parser.parse_args()
					convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)












'''simple docstring'''





import importlib
import inspect
import json
import os
import re
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional, Union
from urllib import request

from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
from packaging import version

from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging


_UpperCamelCase						:						Union[str, Any]  =					(
    'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py'
)


_UpperCamelCase						:						Optional[int]  =					logging.get_logger(__name__)  # pylint: disable=invalid-name
def __UpperCAmelCase   (					)    ->   List[str]:
			UpperCAmelCase_      :       int          =       '''https://pypi.org/pypi/diffusers/json'''
			UpperCAmelCase_      :       List[str]          =       json.loads(request.urlopen(A		).read()		)['''releases'''].keys()
			return sorted(A			,       key=lambda A		: version.Version(A		)		)
def __UpperCAmelCase   (					)    ->   List[Any]:
			# This function has already been executed if HF_MODULES_CACHE already is in the Python path.
			if HF_MODULES_CACHE in sys.path:
						return

			sys.path.append(A		)
			os.makedirs(A			,       exist_ok=A		)
			UpperCAmelCase_      :       Tuple          =       Path(A		) / '''__init__.py'''
			if not init_path.exists():
						init_path.touch()
def __UpperCAmelCase   (					A					:			Union[str, os.PathLike]		)    ->   str:
			init_hf_modules()
			UpperCAmelCase_      :       Any          =       Path(A		) / name
			# If the parent module does not exist yet, recursively create it.
			if not dynamic_module_path.parent.exists():
						create_dynamic_module(dynamic_module_path.parent		)
			os.makedirs(A			,       exist_ok=A		)
			UpperCAmelCase_      :       str          =       dynamic_module_path / '''__init__.py'''
			if not init_path.exists():
						init_path.touch()
def __UpperCAmelCase   (					A					:			Dict		)    ->   Optional[int]:
			with open(A			,       '''r'''			,       encoding='''utf-8'''		) as f:
						UpperCAmelCase_      :       List[Any]          =       f.read()

			# Imports of the form `import .xxx`
			UpperCAmelCase_      :       Any          =       re.findall('''^\s*import\s+\.(\S+)\s*$'''			,       A			,       flags=re.MULTILINE		)
			# Imports of the form `from .xxx import yyy`
			relative_imports += re.findall('''^\s*from\s+\.(\S+)\s+import'''			,       A			,       flags=re.MULTILINE		)
			# Unique-ify
			return list(set(A		)		)
def __UpperCAmelCase   (					A					:			Tuple		)    ->   List[str]:
			UpperCAmelCase_      :       Dict          =       False
			UpperCAmelCase_      :       List[str]          =       [module_file]
			UpperCAmelCase_      :       str          =       []

			# Let's recurse through all relative imports
			while not no_change:
						UpperCAmelCase_      :       Any          =       []
						for f in files_to_check:
									new_imports.extend(get_relative_imports(A		)		)

						UpperCAmelCase_      :       Tuple          =       Path(A		).parent
						UpperCAmelCase_      :       Union[str, Any]          =       [str(module_path / m		) for m in new_imports]
						UpperCAmelCase_      :       str          =       [f for f in new_import_files if f not in all_relative_imports]
						UpperCAmelCase_      :       str          =       [F"{f}.py" for f in new_import_files]

						UpperCAmelCase_      :       Optional[int]          =       len(A		) == 0
						all_relative_imports.extend(A		)

			return all_relative_imports
def __UpperCAmelCase   (					A					:			List[str]		)    ->   Union[str, Any]:
			with open(A			,       '''r'''			,       encoding='''utf-8'''		) as f:
						UpperCAmelCase_      :       List[str]          =       f.read()

			# Imports of the form `import xxx`
			UpperCAmelCase_      :       Optional[Any]          =       re.findall('''^\s*import\s+(\S+)\s*$'''			,       A			,       flags=re.MULTILINE		)
			# Imports of the form `from xxx import yyy`
			imports += re.findall('''^\s*from\s+(\S+)\s+import'''			,       A			,       flags=re.MULTILINE		)
			# Only keep the top-level module
			UpperCAmelCase_      :       List[str]          =       [imp.split('''.'''		)[0] for imp in imports if not imp.startswith('''.'''		)]

			# Unique-ify and test we got them all
			UpperCAmelCase_      :       str          =       list(set(A		)		)
			UpperCAmelCase_      :       int          =       []
			for imp in imports:
						try:
									importlib.import_module(A		)
						except ImportError:
									missing_packages.append(A		)

			if len(A		) > 0:
						raise ImportError(
						    '''This modeling file requires the following packages that were not found in your environment: '''
						    F"{', '.join(A		)}. Run `pip install {' '.join(A		)}`"		)

			return get_relative_imports(A		)
def __UpperCAmelCase   (					A					:			Optional[Any]			,       A					:			Optional[int]		)    ->   Union[str, Any]:
			UpperCAmelCase_      :       int          =       module_path.replace(os.path.sep			,       '''.'''		)
			UpperCAmelCase_      :       int          =       importlib.import_module(A		)

			if class_name is None:
						return find_pipeline_class(A		)
			return getattr(A			,       A		)
def __UpperCAmelCase   (					A					:			str		)    ->   List[str]:
			from ..pipelines import DiffusionPipeline

			UpperCAmelCase_      :       List[Any]          =       dict(inspect.getmembers(A			,       inspect.isclass		)		)

			UpperCAmelCase_      :       Optional[int]          =       None
			for cls_name, cls in cls_members.items():
						if (
						    cls_name != DiffusionPipeline.__name__
						    and issubclass(cls			,       A		)
						    and cls.__module__.split('''.'''		)[0] != "diffusers"
						):
									if pipeline_class is not None:
												raise ValueError(
												    F"Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:"
												    F" {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in"
												    F" {loaded_module}."		)
									UpperCAmelCase_      :       int          =       cls

			return pipeline_class
def __UpperCAmelCase   (					A					:			Union[str, os.PathLike]			,       A					:			str			,       A					:			Optional[Union[str, os.PathLike]] = None			,       A					:			bool = False			,       A					:			bool = False			,       A					:			Optional[Dict[str, str]] = None			,       A					:			Optional[Union[bool, str]] = None			,       A					:			Optional[str] = None			,       A					:			bool = False			,       )    ->   str:
			UpperCAmelCase_      :       Any          =       str(A		)

			UpperCAmelCase_      :       List[Any]          =       os.path.join(A			,       A		)

			if os.path.isfile(A		):
						UpperCAmelCase_      :       Optional[Any]          =       module_file_or_url
						UpperCAmelCase_      :       List[str]          =       '''local'''
			elif pretrained_model_name_or_path.count('''/'''		) == 0:
						UpperCAmelCase_      :       List[str]          =       get_diffusers_versions()
						# cut ".dev0"
						UpperCAmelCase_      :       Dict          =       '''v''' + '''.'''.join(__version__.split('''.'''		)[:3]		)

						# retrieve github version that matches
						if revision is None:
									UpperCAmelCase_      :       List[str]          =       latest_version if latest_version[1:] in available_versions else '''main'''
									logger.info(F"Defaulting to latest_version: {revision}."		)
						elif revision in available_versions:
									UpperCAmelCase_      :       List[str]          =       F"v{revision}"
						elif revision == "main":
									UpperCAmelCase_      :       Dict          =       revision
						else:
									raise ValueError(
									    F"`custom_revision`: {revision} does not exist. Please make sure to choose one of"
									    F" {', '.join(available_versions + ['main']		)}."		)

						# community pipeline on GitHub
						UpperCAmelCase_      :       Tuple          =       COMMUNITY_PIPELINES_URL.format(revision=A			,       pipeline=A		)
						try:
									UpperCAmelCase_      :       List[Any]          =       cached_download(
									    A			,       cache_dir=A			,       force_download=A			,       proxies=A			,       resume_download=A			,       local_files_only=A			,       use_auth_token=A			,       )
									UpperCAmelCase_      :       List[str]          =       '''git'''
									UpperCAmelCase_      :       Union[str, Any]          =       pretrained_model_name_or_path + '''.py'''
						except EnvironmentError:
									logger.error(F"Could not locate the {module_file} inside {pretrained_model_name_or_path}."		)
									raise
			else:
						try:
									# Load from URL or cache if already cached
									UpperCAmelCase_      :       List[str]          =       hf_hub_download(
									    A			,       A			,       cache_dir=A			,       force_download=A			,       proxies=A			,       resume_download=A			,       local_files_only=A			,       use_auth_token=A			,       )
									UpperCAmelCase_      :       Tuple          =       os.path.join('''local'''			,       '''--'''.join(pretrained_model_name_or_path.split('''/'''		)		)		)
						except EnvironmentError:
									logger.error(F"Could not locate the {module_file} inside {pretrained_model_name_or_path}."		)
									raise

    # Check we have all the requirements in our environment
			UpperCAmelCase_      :       Any          =       check_imports(A		)

			# Now we move the module inside our cached dynamic modules.
			UpperCAmelCase_      :       List[str]          =       DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
			create_dynamic_module(A		)
			UpperCAmelCase_      :       Optional[Any]          =       Path(A		) / full_submodule
			if submodule == "local" or submodule == "git":
						# We always copy local files (we could hash the file to see if there was a change, and give them the name of
						# that hash, to only copy when there is a modification but it seems overkill for now).
						# The only reason we do the copy is to avoid putting too many folders in sys.path.
						shutil.copy(A			,       submodule_path / module_file		)
						for module_needed in modules_needed:
									UpperCAmelCase_      :       int          =       F"{module_needed}.py"
									shutil.copy(os.path.join(A			,       A		)			,       submodule_path / module_needed		)
			else:
						# Get the commit hash
						# TODO: we will get this info in the etag soon, so retrieve it from there and not here.
						if isinstance(A			,       A		):
									UpperCAmelCase_      :       Tuple          =       use_auth_token
						elif use_auth_token is True:
									UpperCAmelCase_      :       Tuple          =       HfFolder.get_token()
						else:
									UpperCAmelCase_      :       str          =       None

						UpperCAmelCase_      :       List[Any]          =       model_info(A			,       revision=A			,       token=A		).sha

						# The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
						# benefit of versioning.
						UpperCAmelCase_      :       Optional[Any]          =       submodule_path / commit_hash
						UpperCAmelCase_      :       str          =       full_submodule + os.path.sep + commit_hash
						create_dynamic_module(A		)

						if not (submodule_path / module_file).exists():
									shutil.copy(A			,       submodule_path / module_file		)
						# Make sure we also have every file with relative
						for module_needed in modules_needed:
									if not (submodule_path / module_needed).exists():
												get_cached_module_file(
												    A			,       F"{module_needed}.py"			,       cache_dir=A			,       force_download=A			,       resume_download=A			,       proxies=A			,       use_auth_token=A			,       revision=A			,       local_files_only=A			,       )
			return os.path.join(A			,       A		)







def __UpperCAmelCase   (					A					:			Union[str, os.PathLike]			,       A					:			str			,       A					:			Optional[str] = None			,       A					:			Optional[Union[str, os.PathLike]] = None			,       A					:			bool = False			,       A					:			bool = False			,       A					:			Optional[Dict[str, str]] = None			,       A					:			Optional[Union[bool, str]] = None			,       A					:			Optional[str] = None			,       A					:			bool = False			,       **A					:			Optional[int]			,       )    ->   Optional[Any]:
			UpperCAmelCase_      :       Tuple          =       get_cached_module_file(
			    A			,       A			,       cache_dir=A			,       force_download=A			,       resume_download=A			,       proxies=A			,       use_auth_token=A			,       revision=A			,       local_files_only=A			,       )
			return get_class_in_module(A			,       final_module.replace('''.py'''			,       ''''''		)		)


