

import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402


lowerCAmelCase__	   = get_tests_dir("""fixtures/dummy-config.json""")

class 					a__						(					unittest.TestCase			):
			"""simple docstring"""







			def      UpperCamelCase		(    self       )  ->						Dict:
							'''simple docstring'''






							A__        =			0


			def      UpperCamelCase		(    self       )  ->						int:
							'''simple docstring'''






							self.assertIsNotNone(transformers.models.auto.__spec__       )
							self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto"       )       )


			def      UpperCamelCase		(    self       )  ->						Any:
							'''simple docstring'''






							A__        =			AutoConfig.from_pretrained("bert-base-uncased"       )
							self.assertIsInstance(lowercase      ,      lowercase       )


			def      UpperCamelCase		(    self       )  ->						Tuple:
							'''simple docstring'''






							A__        =			AutoConfig.from_pretrained(lowercase       )
							self.assertIsInstance(lowercase      ,      lowercase       )


			def      UpperCamelCase		(    self       )  ->						Union[str, Any]:
							'''simple docstring'''






							A__        =			AutoConfig.from_pretrained(lowercase       )
							self.assertIsInstance(lowercase      ,      lowercase       )


			def      UpperCamelCase		(    self       )  ->						Union[str, Any]:
							'''simple docstring'''






							A__        =			AutoConfig.for_model("roberta"       )
							self.assertIsInstance(lowercase      ,      lowercase       )


			def      UpperCamelCase		(    self       )  ->						Dict:
							'''simple docstring'''






							with tempfile.TemporaryDirectory() as tmp_dir:
											# This model name contains bert and roberta, but roberta ends up being picked.
											A__        =			os.path.join(lowercase      ,      "fake-roberta"       )
											os.makedirs(lowercase      ,      exist_ok=lowercase       )
											with open(os.path.join(lowercase      ,      "config.json"       )      ,      "w"       ) as f:
															f.write(json.dumps({}       )       )
											A__        =			AutoConfig.from_pretrained(lowercase       )
											self.assertEqual(type(lowercase       )      ,      lowercase       )


			def      UpperCamelCase		(    self       )  ->						Optional[Any]:
							'''simple docstring'''






							try:
											AutoConfig.register("custom"      ,      lowercase       )
											# Wrong model type will raise an error
											with self.assertRaises(lowercase       ):
															AutoConfig.register("model"      ,      lowercase       )
											# Trying to register something existing in the Transformers library will raise an error
											with self.assertRaises(lowercase       ):
															AutoConfig.register("bert"      ,      lowercase       )

											# Now that the config is registered, it can be used as any other config with the auto-API
											A__        =			CustomConfig()
											with tempfile.TemporaryDirectory() as tmp_dir:
															config.save_pretrained(lowercase       )
															A__        =			AutoConfig.from_pretrained(lowercase       )
															self.assertIsInstance(lowercase      ,      lowercase       )

							finally:
											if "custom" in CONFIG_MAPPING._extra_content:
															del CONFIG_MAPPING._extra_content["custom"]


			def      UpperCamelCase		(    self       )  ->						List[Any]:
							'''simple docstring'''






							with self.assertRaisesRegex(
							    lowercase      ,      "bert-base is not a local folder and is not a valid model identifier"       ):
											A__        =			AutoConfig.from_pretrained("bert-base"       )


			def      UpperCamelCase		(    self       )  ->						Optional[int]:
							'''simple docstring'''






							with self.assertRaisesRegex(
							    lowercase      ,      R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"       ):
											A__        =			AutoConfig.from_pretrained(lowercase      ,      revision="aaaaaa"       )


			def      UpperCamelCase		(    self       )  ->						Any:
							'''simple docstring'''






							with self.assertRaisesRegex(
							    lowercase      ,      "hf-internal-testing/no-config-test-repo does not appear to have a file named config.json."      ,      ):
											A__        =			AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo"       )


			def      UpperCamelCase		(    self       )  ->						List[str]:
							'''simple docstring'''






							with self.assertRaises(lowercase       ):
											A__        =			AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"       )
							# If remote code is disabled, we can't load this config.
							with self.assertRaises(lowercase       ):
											A__        =			AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"      ,      trust_remote_code=lowercase       )

							A__        =			AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"      ,      trust_remote_code=lowercase       )
							self.assertEqual(config.__class__.__name__      ,      "NewModelConfig"       )

							# Test config can be reloaded.
							with tempfile.TemporaryDirectory() as tmp_dir:
											config.save_pretrained(lowercase       )
											A__        =			AutoConfig.from_pretrained(lowercase      ,      trust_remote_code=lowercase       )
							self.assertEqual(reloaded_config.__class__.__name__      ,      "NewModelConfig"       )


			def      UpperCamelCase		(    self       )  ->						Dict:
							'''simple docstring'''






							class 					a__						(					snake_case			):
										"""simple docstring"""







										__lowerCamelCase        =       'new-model'

							try:
											AutoConfig.register("new-model"      ,      lowercase       )
											# If remote code is not set, the default is to use local
											A__        =			AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"       )
											self.assertEqual(config.__class__.__name__      ,      "NewModelConfigLocal"       )

											# If remote code is disabled, we load the local one.
											A__        =			AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"      ,      trust_remote_code=lowercase       )
											self.assertEqual(config.__class__.__name__      ,      "NewModelConfigLocal"       )

											# If remote is enabled, we load from the Hub
											A__        =			AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model"      ,      trust_remote_code=lowercase       )
											self.assertEqual(config.__class__.__name__      ,      "NewModelConfig"       )

							finally:
											if "new-model" in CONFIG_MAPPING._extra_content:
															del CONFIG_MAPPING._extra_content["new-model"]




from argparse import ArgumentParser, Namespace

from ..utils import logging
from . import BaseTransformersCLICommand



def 					lowerCAmelCase__							(	SCREAMING_SNAKE_CASE_:							Namespace      )			->      Tuple:




				'''simple docstring'''





				return ConvertCommand(
				    args.model_type	,       args.tf_checkpoint	,       args.pytorch_dump_output	,       args.config	,       args.finetuning_task_name      )


lowerCAmelCase__	   = """
transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires
TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.
"""





class 					a__						(					snake_case			):
			"""simple docstring"""







			@staticmethod
			def      UpperCamelCase		(    lowercase       )  ->						Optional[int]:
							'''simple docstring'''






							A__        =			parser.add_parser(
							    "convert"      ,      help="CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints."      ,      )
							train_parser.add_argument("--model_type"      ,      type=lowercase      ,      required=lowercase      ,      help="Model's type."       )
							train_parser.add_argument(
							    "--tf_checkpoint"      ,      type=lowercase      ,      required=lowercase      ,      help="TensorFlow checkpoint path or folder."       )
							train_parser.add_argument(
							    "--pytorch_dump_output"      ,      type=lowercase      ,      required=lowercase      ,      help="Path to the PyTorch saved model output."       )
							train_parser.add_argument("--config"      ,      type=lowercase      ,      default=""      ,      help="Configuration file path or folder."       )
							train_parser.add_argument(
							    "--finetuning_task_name"      ,      type=lowercase      ,      default=lowercase      ,      help="Optional fine-tuning task name if the TF model was a finetuned model."      ,      )
							train_parser.set_defaults(func=lowercase       )


			def __init__(    self      ,      lowercase      ,      lowercase      ,      lowercase      ,      lowercase      ,      lowercase      ,      *lowercase      ,      )  ->						Union[str, Any]:
							'''simple docstring'''






							A__        =			logging.get_logger("transformers-cli/converting"       )

							self._logger.info(F'Loading model {model_type}'       )
							A__        =			model_type
							A__        =			tf_checkpoint
							A__        =			pytorch_dump_output
							A__        =			config
							A__        =			finetuning_task_name


			def      UpperCamelCase		(    self       )  ->						Union[str, Any]:
							'''simple docstring'''






							if self._model_type == "albert":
											try:
															from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
															    convert_tf_checkpoint_to_pytorch,
															)
											except ImportError:
															raise ImportError(lowercase       )

											convert_tf_checkpoint_to_pytorch(self._tf_checkpoint      ,      self._config      ,      self._pytorch_dump_output       )
							elif self._model_type == "bert":
											try:
															from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
															    convert_tf_checkpoint_to_pytorch,
															)
											except ImportError:
															raise ImportError(lowercase       )

											convert_tf_checkpoint_to_pytorch(self._tf_checkpoint      ,      self._config      ,      self._pytorch_dump_output       )
							elif self._model_type == "funnel":
											try:
															from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
															    convert_tf_checkpoint_to_pytorch,
															)
											except ImportError:
															raise ImportError(lowercase       )

											convert_tf_checkpoint_to_pytorch(self._tf_checkpoint      ,      self._config      ,      self._pytorch_dump_output       )
							elif self._model_type == "t5":
											try:
															from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
											except ImportError:
															raise ImportError(lowercase       )

											convert_tf_checkpoint_to_pytorch(self._tf_checkpoint      ,      self._config      ,      self._pytorch_dump_output       )
							elif self._model_type == "gpt":
											from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
											    convert_openai_checkpoint_to_pytorch,
											)

											convert_openai_checkpoint_to_pytorch(self._tf_checkpoint      ,      self._config      ,      self._pytorch_dump_output       )
							elif self._model_type == "transfo_xl":
											try:
															from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import (
															    convert_transfo_xl_checkpoint_to_pytorch,
															)
											except ImportError:
															raise ImportError(lowercase       )

											if "ckpt" in self._tf_checkpoint.lower():
															A__        =			self._tf_checkpoint
															A__        =			""
											else:
															A__        =			self._tf_checkpoint
															A__        =			""
											convert_transfo_xl_checkpoint_to_pytorch(
											    lowercase      ,      self._config      ,      self._pytorch_dump_output      ,      lowercase       )
							elif self._model_type == "gpt2":
											try:
															from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import (
															    convert_gpta_checkpoint_to_pytorch,
															)
											except ImportError:
															raise ImportError(lowercase       )

											convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint      ,      self._config      ,      self._pytorch_dump_output       )
							elif self._model_type == "xlnet":
											try:
															from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
															    convert_xlnet_checkpoint_to_pytorch,
															)
											except ImportError:
															raise ImportError(lowercase       )

											convert_xlnet_checkpoint_to_pytorch(
											    self._tf_checkpoint      ,      self._config      ,      self._pytorch_dump_output      ,      self._finetuning_task_name       )
							elif self._model_type == "xlm":
											from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
											    convert_xlm_checkpoint_to_pytorch,
											)

											convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint      ,      self._pytorch_dump_output       )
							elif self._model_type == "lxmert":
											from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
											    convert_lxmert_checkpoint_to_pytorch,
											)

											convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint      ,      self._pytorch_dump_output       )
							elif self._model_type == "rembert":
											from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
											    convert_rembert_tf_checkpoint_to_pytorch,
											)

											convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint      ,      self._config      ,      self._pytorch_dump_output       )
							else:
											raise ValueError(
											    "--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]"       )

