

from argparse import ArgumentParser

from .add_new_model import AddNewModelCommand
from .add_new_model_like import AddNewModelLikeCommand
from .convert import ConvertCommand
from .download import DownloadCommand
from .env import EnvironmentCommand
from .lfs import LfsCommands
from .pt_to_tf import PTtoTFCommand
from .run import RunCommand
from .serving import ServeCommand
from .user import UserCommands

def 							__SCREAMING_SNAKE_CASE							(			)				->    List[Any]:
				_UpperCAmelCase    :						Any							=      ArgumentParser("Transformers CLI tool"					, usage="transformers-cli <command> [<args>]"	)
				_UpperCAmelCase    :						Tuple							=      parser.add_subparsers(help="transformers-cli command helpers"	)

				# Register commands
				ConvertCommand.register_subcommand(lowerCAmelCase	)
				DownloadCommand.register_subcommand(lowerCAmelCase	)
				EnvironmentCommand.register_subcommand(lowerCAmelCase	)
				RunCommand.register_subcommand(lowerCAmelCase	)
				ServeCommand.register_subcommand(lowerCAmelCase	)
				UserCommands.register_subcommand(lowerCAmelCase	)
				AddNewModelCommand.register_subcommand(lowerCAmelCase	)
				AddNewModelLikeCommand.register_subcommand(lowerCAmelCase	)
				LfsCommands.register_subcommand(lowerCAmelCase	)
				PTtoTFCommand.register_subcommand(lowerCAmelCase	)

				# Let's go
				_UpperCAmelCase    :						Union[str, Any]							=      parser.parse_args()

				if not hasattr(lowerCAmelCase					, "func"	):
								parser.print_help()
								exit(1	)

				# Run
				_UpperCAmelCase    :						Dict							=      args.func(lowerCAmelCase	)
				service.run()


if __name__ == "__main__":
					main()





import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
					import jax.numpy as jnp

class 			a					(		UpperCAmelCase			):


						def __get__(    self  ,   A_  ,   A_=None		):







										'''simple docstring'''


										if obj is None:
														return self
										if self.fget is None:
														raise AttributeError("unreadable attribute"		)
										_UpperCAmelCase    :						Optional[int]							=      "__cached_" + self.fget.__name__
										_UpperCAmelCase    :						Union[str, Any]							=      getattr(A_  ,   A_  ,   A_		)
										if cached is None:
														_UpperCAmelCase    :						Dict							=      self.fget(A_		)
														setattr(A_  ,   A_  ,   A_		)
										return cached







def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]	)				->    int:
				_UpperCAmelCase    :						str							=      val.lower()
				if val in {"y", "yes", "t", "true", "on", "1"}:
								return 1
				if val in {"n", "no", "f", "false", "off", "0"}:
								return 0
				raise ValueError(F'invalid truth value {val!r}'	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Any	)				->    int:
				if is_torch_fx_proxy(lowerCAmelCase	):
								return True
				if is_torch_available():
								import torch

								if isinstance(lowerCAmelCase					, torch.Tensor	):
												return True
				if is_tf_available():
								import tensorflow as tf

								if isinstance(lowerCAmelCase					, tf.Tensor	):
												return True

				if is_flax_available():
								import jax.numpy as jnp
								from jax.core import Tracer

								if isinstance(lowerCAmelCase					, (jnp.ndarray, Tracer)	):
												return True

				return isinstance(lowerCAmelCase					, np.ndarray	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Any	)				->    Dict:
				return isinstance(lowerCAmelCase					, np.ndarray	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]	)				->    Any:
				return _is_numpy(lowerCAmelCase	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Optional[int]:
				import torch

				return isinstance(lowerCAmelCase					, torch.Tensor	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Any	)				->    Optional[int]:
				return False if not is_torch_available() else _is_torch(lowerCAmelCase	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[Any]	)				->    List[Any]:
				import torch

				return isinstance(lowerCAmelCase					, torch.device	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					int	)				->    Tuple:
				return False if not is_torch_available() else _is_torch_device(lowerCAmelCase	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[str]	)				->    Tuple:
				import torch

				if isinstance(lowerCAmelCase					, lowerCAmelCase	):
								if hasattr(lowerCAmelCase					, lowerCAmelCase	):
												_UpperCAmelCase    :						Any							=      getattr(lowerCAmelCase					, lowerCAmelCase	)
								else:
												return False
				return isinstance(lowerCAmelCase					, torch.dtype	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Any	)				->    int:
				return False if not is_torch_available() else _is_torch_dtype(lowerCAmelCase	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[Any]	)				->    Optional[Any]:
				import tensorflow as tf

				return isinstance(lowerCAmelCase					, tf.Tensor	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					str	)				->    Optional[Any]:
				return False if not is_tf_available() else _is_tensorflow(lowerCAmelCase	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[int]	)				->    Any:
				import tensorflow as tf

				# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
				if hasattr(lowerCAmelCase					, "is_symbolic_tensor"	):
								return tf.is_symbolic_tensor(lowerCAmelCase	)
				return type(lowerCAmelCase	) == tf.Tensor

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Optional[Any]:
				return False if not is_tf_available() else _is_tf_symbolic_tensor(lowerCAmelCase	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]	)				->    List[str]:
				import jax.numpy as jnp  # noqa: F811

				return isinstance(lowerCAmelCase					, jnp.ndarray	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[Any]	)				->    str:
				return False if not is_flax_available() else _is_jax(lowerCAmelCase	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					str	)				->    Tuple:
				if isinstance(lowerCAmelCase					, (dict, UserDict)	):
								return {k: to_py_obj(lowerCAmelCase	) for k, v in obj.items()}
				elif isinstance(lowerCAmelCase					, (list, tuple)	):
								return [to_py_obj(lowerCAmelCase	) for o in obj]
				elif is_tf_tensor(lowerCAmelCase	):
								return obj.numpy().tolist()
				elif is_torch_tensor(lowerCAmelCase	):
								return obj.detach().cpu().tolist()
				elif is_jax_tensor(lowerCAmelCase	):
								return np.asarray(lowerCAmelCase	).tolist()
				elif isinstance(lowerCAmelCase					, (np.ndarray, np.number)	):  # tolist also works on 0d np arrays
								return obj.tolist()
				else:
								return obj

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]	)				->    List[Any]:
				if isinstance(lowerCAmelCase					, (dict, UserDict)	):
								return {k: to_numpy(lowerCAmelCase	) for k, v in obj.items()}
				elif isinstance(lowerCAmelCase					, (list, tuple)	):
								return np.array(lowerCAmelCase	)
				elif is_tf_tensor(lowerCAmelCase	):
								return obj.numpy()
				elif is_torch_tensor(lowerCAmelCase	):
								return obj.detach().cpu().numpy()
				elif is_jax_tensor(lowerCAmelCase	):
								return np.asarray(lowerCAmelCase	)
				else:
								return obj

class 			a					(		UpperCAmelCase			):


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[Any]							=      fields(self		)

										# Safety and consistency checks
										if not len(A_		):
														raise ValueError(f'{self.__class__.__name__} has no fields.'		)
										if not all(field.default is None for field in class_fields[1:]		):
														raise ValueError(f'{self.__class__.__name__} should not have more than one required field.'		)

										_UpperCAmelCase    :						Any							=      getattr(self  ,   class_fields[0].name		)
										_UpperCAmelCase    :						List[str]							=      all(getattr(self  ,   field.name		) is None for field in class_fields[1:]		)

										if other_fields_are_none and not is_tensor(A_		):
														if isinstance(A_  ,   A_		):
																		_UpperCAmelCase    :						Union[str, Any]							=      first_field.items()
																		_UpperCAmelCase    :						Optional[int]							=      True
														else:
																		try:
																						_UpperCAmelCase    :						Tuple							=      iter(A_		)
																						_UpperCAmelCase    :						Any							=      True
																		except TypeError:
																						_UpperCAmelCase    :						str							=      False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
														if first_field_iterator:
																		for idx, element in enumerate(A_		):
																						if (
																						    not isinstance(A_  ,   (list, tuple)		)
																						    or not len(A_		) == 2
																						    or not isinstance(element[0]  ,   A_		)
																						):
																										if idx == 0:
																														# If we do not have an iterator of key/values, set it as attribute
																														_UpperCAmelCase    :						str							=      first_field
																										else:
																														# If we have a mixed iterator, raise an error
																														raise ValueError(
																														    f'Cannot set key/value for {element}. It needs to be a tuple (key, value).'		)
																										break
																						setattr(self  ,   element[0]  ,   element[1]		)
																						if element[1] is not None:
																										_UpperCAmelCase    :						List[str]							=      element[1]
														elif first_field is not None:
																		_UpperCAmelCase    :						Tuple							=      first_field
										else:
														for field in class_fields:
																		_UpperCAmelCase    :						int							=      getattr(self  ,   field.name		)
																		if v is not None:
																						_UpperCAmelCase    :						Union[str, Any]							=      v


						def __delitem__(    self  ,   *A_  ,   **A_		):







										'''simple docstring'''


										raise Exception(f'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'		)


						def     _UpperCAmelCase			(    self  ,   *A_  ,   **A_		):







										'''simple docstring'''


										raise Exception(f'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'		)


						def     _UpperCAmelCase			(    self  ,   *A_  ,   **A_		):







										'''simple docstring'''


										raise Exception(f'You cannot use ``pop`` on a {self.__class__.__name__} instance.'		)


						def     _UpperCAmelCase			(    self  ,   *A_  ,   **A_		):







										'''simple docstring'''


										raise Exception(f'You cannot use ``update`` on a {self.__class__.__name__} instance.'		)


						def __getitem__(    self  ,   A_		):







										'''simple docstring'''


										if isinstance(A_  ,   A_		):
														_UpperCAmelCase    :						Optional[int]							=      dict(self.items()		)
														return inner_dict[k]
										else:
														return self.to_tuple()[k]


						def __setattr__(    self  ,   A_  ,   A_		):







										'''simple docstring'''


										if name in self.keys() and value is not None:
														# Don't call self.__setitem__ to avoid recursion errors
														super().__setitem__(A_  ,   A_		)
										super().__setattr__(A_  ,   A_		)


						def __setitem__(    self  ,   A_  ,   A_		):







										'''simple docstring'''


										super().__setitem__(A_  ,   A_		)
										# Don't call self.__setattr__ to avoid recursion errors
										super().__setattr__(A_  ,   A_		)





						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return tuple(self[k] for k in self.keys()		)







class 			a					(		UpperCAmelCase							,	UpperCAmelCase			):


						@classmethod
						def     _UpperCAmelCase			(    cls  ,   A_		):







										'''simple docstring'''


										raise ValueError(
										    f'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()		)}'		)







class 			a					(		UpperCAmelCase			):
						_lowercase        =     "longest"
						_lowercase        =     "max_length"
						_lowercase        =     "do_not_pad"







class 			a					(		UpperCAmelCase			):
						_lowercase        =     "pt"
						_lowercase        =     "tf"
						_lowercase        =     "np"
						_lowercase        =     "jax"







class 			a					:


						def __init__(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						Tuple							=      context_managers
										_UpperCAmelCase    :						Dict							=      ExitStack()


						def __enter__(    self		):







										'''simple docstring'''


										for context_manager in self.context_managers:
														self.stack.enter_context(A_		)





						def __exit__(    self  ,   *A_  ,   **A_		):







										'''simple docstring'''


										self.stack.__exit__(*A_  ,   **A_		)







def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					int	)				->    Optional[Any]:
				_UpperCAmelCase    :						Optional[Any]							=      infer_framework(lowerCAmelCase	)
				if framework == "tf":
								_UpperCAmelCase    :						Union[str, Any]							=      inspect.signature(model_class.call	)  # TensorFlow models
				elif framework == "pt":
								_UpperCAmelCase    :						Optional[int]							=      inspect.signature(model_class.forward	)  # PyTorch models
				else:
								_UpperCAmelCase    :						Dict							=      inspect.signature(model_class.__call__	)  # Flax models

				for p in signature.parameters:
								if p == "return_loss" and signature.parameters[p].default is True:
												return True

				return False

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[str]	)				->    List[str]:
				_UpperCAmelCase    :						List[Any]							=      model_class.__name__
				_UpperCAmelCase    :						Dict							=      infer_framework(lowerCAmelCase	)
				if framework == "tf":
								_UpperCAmelCase    :						Dict							=      inspect.signature(model_class.call	)  # TensorFlow models
				elif framework == "pt":
								_UpperCAmelCase    :						Dict							=      inspect.signature(model_class.forward	)  # PyTorch models
				else:
								_UpperCAmelCase    :						Tuple							=      inspect.signature(model_class.__call__	)  # Flax models

				if "QuestionAnswering" in model_name:
								return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
				else:
								return [p for p in signature.parameters if "label" in p]

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					MutableMapping					, lowerCAmelCase:					str = ""					, lowerCAmelCase:					str = "."	)				->    List[Any]:

				def _flatten_dict(lowerCAmelCase:					int					, lowerCAmelCase:					Tuple=""					, lowerCAmelCase:					List[str]="."	):
								for k, v in d.items():
												_UpperCAmelCase    :						Optional[int]							=      str(lowerCAmelCase	) + delimiter + str(lowerCAmelCase	) if parent_key else k
												if v and isinstance(lowerCAmelCase					, lowerCAmelCase	):
																yield from flatten_dict(lowerCAmelCase					, lowerCAmelCase					, delimiter=lowerCAmelCase	).items()
												else:
																yield key, v

				return dict(_flatten_dict(lowerCAmelCase					, lowerCAmelCase					, lowerCAmelCase	)	)

@contextmanager
def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Union[str, Any]					, lowerCAmelCase:					bool = False	)				->    List[Any]:
				if use_temp_dir:
								with tempfile.TemporaryDirectory() as tmp_dir:
												yield tmp_dir
				else:
								yield working_dir

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Dict					, lowerCAmelCase:					Tuple=None	)				->    List[str]:
				if is_numpy_array(lowerCAmelCase	):
								return np.transpose(lowerCAmelCase					, axes=lowerCAmelCase	)
				elif is_torch_tensor(lowerCAmelCase	):
								return array.T if axes is None else array.permute(*lowerCAmelCase	)
				elif is_tf_tensor(lowerCAmelCase	):
								import tensorflow as tf

								return tf.transpose(lowerCAmelCase					, perm=lowerCAmelCase	)
				elif is_jax_tensor(lowerCAmelCase	):
								return jnp.transpose(lowerCAmelCase					, axes=lowerCAmelCase	)
				else:
								raise ValueError(F'Type not supported for transpose: {type(lowerCAmelCase	)}.'	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]					, lowerCAmelCase:					Any	)				->    int:
				if is_numpy_array(lowerCAmelCase	):
								return np.reshape(lowerCAmelCase					, lowerCAmelCase	)
				elif is_torch_tensor(lowerCAmelCase	):
								return array.reshape(*lowerCAmelCase	)
				elif is_tf_tensor(lowerCAmelCase	):
								import tensorflow as tf

								return tf.reshape(lowerCAmelCase					, lowerCAmelCase	)
				elif is_jax_tensor(lowerCAmelCase	):
								return jnp.reshape(lowerCAmelCase					, lowerCAmelCase	)
				else:
								raise ValueError(F'Type not supported for reshape: {type(lowerCAmelCase	)}.'	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					str					, lowerCAmelCase:					Union[str, Any]=None	)				->    Union[str, Any]:
				if is_numpy_array(lowerCAmelCase	):
								return np.squeeze(lowerCAmelCase					, axis=lowerCAmelCase	)
				elif is_torch_tensor(lowerCAmelCase	):
								return array.squeeze() if axis is None else array.squeeze(dim=lowerCAmelCase	)
				elif is_tf_tensor(lowerCAmelCase	):
								import tensorflow as tf

								return tf.squeeze(lowerCAmelCase					, axis=lowerCAmelCase	)
				elif is_jax_tensor(lowerCAmelCase	):
								return jnp.squeeze(lowerCAmelCase					, axis=lowerCAmelCase	)
				else:
								raise ValueError(F'Type not supported for squeeze: {type(lowerCAmelCase	)}.'	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Dict					, lowerCAmelCase:					List[str]	)				->    Union[str, Any]:
				if is_numpy_array(lowerCAmelCase	):
								return np.expand_dims(lowerCAmelCase					, lowerCAmelCase	)
				elif is_torch_tensor(lowerCAmelCase	):
								return array.unsqueeze(dim=lowerCAmelCase	)
				elif is_tf_tensor(lowerCAmelCase	):
								import tensorflow as tf

								return tf.expand_dims(lowerCAmelCase					, axis=lowerCAmelCase	)
				elif is_jax_tensor(lowerCAmelCase	):
								return jnp.expand_dims(lowerCAmelCase					, axis=lowerCAmelCase	)
				else:
								raise ValueError(F'Type not supported for expand_dims: {type(lowerCAmelCase	)}.'	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[Any]	)				->    int:
				if is_numpy_array(lowerCAmelCase	):
								return np.size(lowerCAmelCase	)
				elif is_torch_tensor(lowerCAmelCase	):
								return array.numel()
				elif is_tf_tensor(lowerCAmelCase	):
								import tensorflow as tf

								return tf.size(lowerCAmelCase	)
				elif is_jax_tensor(lowerCAmelCase	):
								return array.size
				else:
								raise ValueError(F'Type not supported for expand_dims: {type(lowerCAmelCase	)}.'	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[str]					, lowerCAmelCase:					List[Any]	)				->    List[Any]:
				for key, value in auto_map.items():
								if isinstance(lowerCAmelCase					, (tuple, list)	):
												_UpperCAmelCase    :						List[Any]							=      [F'{repo_id}--{v}' if (v is not None and "--" not in v) else v for v in value]
								elif value is not None and "--" not in value:
												_UpperCAmelCase    :						Tuple							=      F'{repo_id}--{value}'

				return auto_map





def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Any	)				->    List[Any]:
				for base_class in inspect.getmro(lowerCAmelCase	):
								_UpperCAmelCase    :						int							=      base_class.__module__
								_UpperCAmelCase    :						Dict							=      base_class.__name__
								if module.startswith("tensorflow"	) or module.startswith("keras"	) or name == "TFPreTrainedModel":
												return "tf"
								elif module.startswith("torch"	) or name == "PreTrainedModel":
												return "pt"
								elif module.startswith("flax"	) or module.startswith("jax"	) or name == "FlaxPreTrainedModel":
												return "flax"
				else:
								raise TypeError(F'Could not infer framework from class {model_class}.'	)


