





# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


_SCREAMING_SNAKE_CASE      	=		{
    """configuration_vivit""": ["""VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VivitConfig"""],
}
try:
						if not is_vision_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						_SCREAMING_SNAKE_CASE      	=		["""VivitImageProcessor"""]


try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						_SCREAMING_SNAKE_CASE      	=		[
						    """VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
						    """VivitModel""",
						    """VivitPreTrainedModel""",
						    """VivitForVideoClassification""",
						]


if TYPE_CHECKING:
						from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig

						try:
												if not is_vision_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .image_processing_vivit import VivitImageProcessor

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_vivit import (
												    VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
												    VivitForVideoClassification,
												    VivitModel,
												    VivitPreTrainedModel,
												)


else:
						import sys

						_SCREAMING_SNAKE_CASE      	=		_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)








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 							SCREAMING_SNAKE_CASE__						(    __a   , __a   ):
	# Load checkpoint
	snake_case_		:			Union[str, Any]											=	torch.load(__a   , map_location='cpu'   )

	snake_case_		:			Union[str, Any]											=	chkpt['model']

	# We have the base model one level deeper than the original XLM repository
	snake_case_		:			str											=	{}
	for k, v in state_dict.items():
		if "pred_layer" in k:
			snake_case_		:			Tuple											=	v
		else:
			snake_case_		:			Dict											=	v

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

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

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

	print(f"""Save PyTorch model to {pytorch_weights_dump_path}"""   )
	torch.save(__a   , __a   )

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

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


if __name__ == "__main__":
						_SCREAMING_SNAKE_CASE      	=		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."""
						)
						_SCREAMING_SNAKE_CASE      	=		parser.parse_args()
						convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)

