





import builtins
import sys

from ...utils.imports import _is_package_available
from . import cursor, input
from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
from .keymap import KEYMAP


__A     =    False
try:
      __A     =    _is_package_available("google.colab")
except ModuleNotFoundError:
      pass



@input.register
class        _SCREAMING_SNAKE_CASE						:







 '''simple docstring'''

 def __init__(self    :       str	,			UpperCAmelCase_    :       str = None	,			UpperCAmelCase_    :       list = [])	->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:				Union[str, Any]        =0
   lowerCamelCase__:				Dict        =choices
   lowerCamelCase__:				Union[str, Any]        =prompt
   if sys.platform == "win32":
     lowerCamelCase__:				Optional[Any]        ="*"
   else:
     lowerCamelCase__:				int        ="➔ "

 def 							SCREAMING_SNAKE_CASE_ (self    :       str	,			UpperCAmelCase_    :       Union[str, Any]	,			UpperCAmelCase_    :       str = "")	->Any:



   '''simple docstring'''



   if sys.platform != "win32":
     writeColor(self.choices[index]	,			32	,			UpperCAmelCase_)
   else:
     forceWrite(self.choices[index]	,			UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_ (self    :       Dict	,			UpperCAmelCase_    :       int)	->Optional[int]:



   '''simple docstring'''



   if index == self.position:
     forceWrite(F""" {self.arrow_char} """)
     self.write_choice(UpperCAmelCase_)
   else:
     forceWrite(F"""    {self.choices[index]}""")
   reset_cursor()

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any	,			UpperCAmelCase_    :       Direction	,			UpperCAmelCase_    :       int = 1)	->Any:



   '''simple docstring'''



   lowerCamelCase__:				Optional[int]        =self.position
   if direction == Direction.DOWN:
     if self.position + 1 >= len(self.choices):
       return
     self.position += num_spaces
   else:
     if self.position - 1 < 0:
       return
     self.position -= num_spaces
   clear_line()
   self.print_choice(UpperCAmelCase_)
   move_cursor(UpperCAmelCase_	,			direction.name)
   self.print_choice(self.position)

 @input.mark(KEYMAP["up"])
 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any])	->str:



   '''simple docstring'''



   self.move_direction(Direction.UP)

 @input.mark(KEYMAP["down"])
 def 							SCREAMING_SNAKE_CASE_ (self    :       str)	->str:



   '''simple docstring'''



   self.move_direction(Direction.DOWN)

 @input.mark(KEYMAP["newline"])
 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->int:



   '''simple docstring'''



   move_cursor(len(self.choices) - self.position	,			"DOWN")
   return self.position

 @input.mark(KEYMAP["interrupt"])
 def 							SCREAMING_SNAKE_CASE_ (self    :       Any)	->Tuple:



   '''simple docstring'''



   move_cursor(len(self.choices) - self.position	,			"DOWN")
   raise KeyboardInterrupt

 @input.mark_multiple(*[KEYMAP[str(UpperCAmelCase_)] for number in range(10)])
 def 							SCREAMING_SNAKE_CASE_ (self    :       str)	->str:



   '''simple docstring'''



   lowerCamelCase__:				str        =int(chr(self.current_selection))
   lowerCamelCase__:				Optional[int]        =index - self.position
   if index == self.position:
     return
   if index < len(self.choices):
     if self.position > index:
       self.move_direction(Direction.UP	,			-movement)
     elif self.position < index:
       self.move_direction(Direction.DOWN	,			UpperCAmelCase_)
     else:
       return
   else:
     return







 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str]	,			UpperCAmelCase_    :       int = 0)	->Union[str, Any]:



   '''simple docstring'''



   if self.prompt:
     linebreak()
     forceWrite(self.prompt	,			"\n")
     if in_colab:
       forceWrite("Please input a choice index (starting from 0), and press enter"	,			"\n")
     else:
       forceWrite("Please select a choice using the arrow or number keys, and selecting with enter"	,			"\n")
   lowerCamelCase__:				Dict        =default_choice
   for i in range(len(self.choices)):
     self.print_choice(UpperCAmelCase_)
     forceWrite("\n")
   move_cursor(len(self.choices) - self.position	,			"UP")
   with cursor.hide():
     while True:
       if in_colab:
         try:
           lowerCamelCase__:				Optional[Any]        =int(builtins.input())
         except ValueError:
           lowerCamelCase__:				Optional[Any]        =default_choice
       else:
         lowerCamelCase__:				List[Any]        =self.handle_input()
       if choice is not None:
         reset_cursor()
         for _ in range(len(self.choices) + 1):
           move_cursor(1	,			"UP")
           clear_line()
         self.write_choice(UpperCAmelCase_	,			"\n")
         return choice








from argparse import ArgumentParser, Namespace

from ..utils import logging
from . import BaseTransformersCLICommand





def 					lowerCAmelCase_			(	__a		)					->		int:







  """simple docstring"""





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


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






class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ):







 '''simple docstring'''

 @staticmethod
 def 							SCREAMING_SNAKE_CASE_ (UpperCAmelCase_    :       ArgumentParser)	->str:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =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=UpperCAmelCase_	,			required=UpperCAmelCase_	,			help="Model's type.")
   train_parser.add_argument(
       "--tf_checkpoint"	,			type=UpperCAmelCase_	,			required=UpperCAmelCase_	,			help="TensorFlow checkpoint path or folder.")
   train_parser.add_argument(
       "--pytorch_dump_output"	,			type=UpperCAmelCase_	,			required=UpperCAmelCase_	,			help="Path to the PyTorch saved model output.")
   train_parser.add_argument("--config"	,			type=UpperCAmelCase_	,			default=""	,			help="Configuration file path or folder.")
   train_parser.add_argument(
       "--finetuning_task_name"	,			type=UpperCAmelCase_	,			default=UpperCAmelCase_	,			help="Optional fine-tuning task name if the TF model was a finetuned model."	,			)
   train_parser.set_defaults(func=UpperCAmelCase_)

 def __init__(self    :       List[Any]	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			UpperCAmelCase_    :       str	,			*UpperCAmelCase_    :       Optional[int]	,			)	->List[str]:



   '''simple docstring'''



   lowerCamelCase__:				Dict        =logging.get_logger("transformers-cli/converting")

   self._logger.info(F"""Loading model {model_type}""")
   lowerCamelCase__:				Any        =model_type
   lowerCamelCase__:				Optional[int]        =tf_checkpoint
   lowerCamelCase__:				Any        =pytorch_dump_output
   lowerCamelCase__:				Union[str, Any]        =config
   lowerCamelCase__:				str        =finetuning_task_name







 def 							SCREAMING_SNAKE_CASE_ (self    :       Union[str, Any])	->Tuple:



   '''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(UpperCAmelCase_)

     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(UpperCAmelCase_)

     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(UpperCAmelCase_)

     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(UpperCAmelCase_)

     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(UpperCAmelCase_)

     if "ckpt" in self._tf_checkpoint.lower():
       lowerCamelCase__:				Tuple        =self._tf_checkpoint
       lowerCamelCase__:				List[str]        =""
     else:
       lowerCamelCase__:				Any        =self._tf_checkpoint
       lowerCamelCase__:				Dict        =""
     convert_transfo_xl_checkpoint_to_pytorch(
         UpperCAmelCase_	,			self._config	,			self._pytorch_dump_output	,			UpperCAmelCase_)
   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(UpperCAmelCase_)

     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(UpperCAmelCase_)

     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]")

