

'''simple docstring'''

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 	lowerCAmelCase  (   A ):







       def __get__(				self      :			Union[str, Any]    ,   __lowercase      :			List[str]    ,   __lowercase      :			int=None   ):







            """simple docstring"""







            if obj is None:
                 return self
            if self.fget is None:
                 raise AttributeError('unreadable attribute'   )
            __lowercase      		='__cached_' + self.fget.__name__
            __lowercase      		=getattr(__lowercase    ,   __lowercase    ,   __lowercase   )
            if cached is None:
                 __lowercase      		=self.fget(__lowercase   )
                 setattr(__lowercase    ,   __lowercase    ,   __lowercase   )
            return cached






def 					__UpperCamelCase				(						lowercase__    :	str			):






     '''simple docstring'''





     __lowercase      		=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 					__UpperCamelCase				(						lowercase__    :	Optional[int]			):






     '''simple docstring'''





     if is_torch_fx_proxy(lowercase__			):
          return True
     if is_torch_available():
          import torch

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

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

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

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

     return isinstance(lowercase__,       np.ndarray			)

def 					__UpperCamelCase				(						lowercase__    :	Union[str, Any]			):






     '''simple docstring'''





     return isinstance(lowercase__,       np.ndarray			)

def 					__UpperCamelCase				(						lowercase__    :	Dict			):






     '''simple docstring'''





     return _is_numpy(lowercase__			)

def 					__UpperCamelCase				(						lowercase__    :	Optional[int]			):






     '''simple docstring'''





     import torch

     return isinstance(lowercase__,       torch.Tensor			)

def 					__UpperCamelCase				(						lowercase__    :	Any			):






     '''simple docstring'''





     return False if not is_torch_available() else _is_torch(lowercase__			)

def 					__UpperCamelCase				(						lowercase__    :	Optional[int]			):






     '''simple docstring'''





     import torch

     return isinstance(lowercase__,       torch.device			)

def 					__UpperCamelCase				(						lowercase__    :	str			):






     '''simple docstring'''





     return False if not is_torch_available() else _is_torch_device(lowercase__			)

def 					__UpperCamelCase				(						lowercase__    :	List[Any]			):






     '''simple docstring'''





     import torch

     if isinstance(lowercase__,       lowercase__			):
          if hasattr(lowercase__,       lowercase__			):
               __lowercase      		=getattr(lowercase__,       lowercase__			)
          else:
               return False
     return isinstance(lowercase__,       torch.dtype			)

def 					__UpperCamelCase				(						lowercase__    :	Optional[Any]			):






     '''simple docstring'''





     return False if not is_torch_available() else _is_torch_dtype(lowercase__			)

def 					__UpperCamelCase				(						lowercase__    :	int			):






     '''simple docstring'''





     import tensorflow as tf

     return isinstance(lowercase__,       tf.Tensor			)

def 					__UpperCamelCase				(						lowercase__    :	Optional[int]			):






     '''simple docstring'''





     return False if not is_tf_available() else _is_tensorflow(lowercase__			)

def 					__UpperCamelCase				(						lowercase__    :	Any			):






     '''simple docstring'''





     import tensorflow as tf

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

def 					__UpperCamelCase				(						lowercase__    :	Dict			):






     '''simple docstring'''





     return False if not is_tf_available() else _is_tf_symbolic_tensor(lowercase__			)

def 					__UpperCamelCase				(						lowercase__    :	str			):






     '''simple docstring'''





     import jax.numpy as jnp  # noqa: F811

     return isinstance(lowercase__,       jnp.ndarray			)

def 					__UpperCamelCase				(						lowercase__    :	List[str]			):






     '''simple docstring'''





     return False if not is_flax_available() else _is_jax(lowercase__			)

def 					__UpperCamelCase				(						lowercase__    :	Optional[Any]			):






     '''simple docstring'''





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

def 					__UpperCamelCase				(						lowercase__    :	Any			):






     '''simple docstring'''





     if isinstance(lowercase__,       (dict, UserDict)			):
          return {k: to_numpy(lowercase__			) for k, v in obj.items()}
     elif isinstance(lowercase__,       (list, tuple)			):
          return np.array(lowercase__			)
     elif is_tf_tensor(lowercase__			):
          return obj.numpy()
     elif is_torch_tensor(lowercase__			):
          return obj.detach().cpu().numpy()
     elif is_jax_tensor(lowercase__			):
          return np.asarray(lowercase__			)
     else:
          return obj


class 	lowerCAmelCase  (   A ):







       def       snake_case (				self      :			Tuple   ):







            """simple docstring"""







            __lowercase      		=fields(self   )

            # Safety and consistency checks
            if not len(__lowercase   ):
                 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.'''   )

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

            if other_fields_are_none and not is_tensor(__lowercase   ):
                 if isinstance(__lowercase    ,   __lowercase   ):
                      __lowercase      		=first_field.items()
                      __lowercase      		=True
                 else:
                      try:
                           __lowercase      		=iter(__lowercase   )
                           __lowercase      		=True
                      except TypeError:
                           __lowercase      		=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(__lowercase   ):
                           if (
                               not isinstance(__lowercase    ,   (list, tuple)   )
                               or not len(__lowercase   ) == 2
                               or not isinstance(element[0]    ,   __lowercase   )
                           ):
                                if idx == 0:
                                     # If we do not have an iterator of key/values, set it as attribute
                                     __lowercase      		=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:
                                __lowercase      		=element[1]
                 elif first_field is not None:
                      __lowercase      		=first_field
            else:
                 for field in class_fields:
                      __lowercase      		=getattr(self    ,   field.name   )
                      if v is not None:
                           __lowercase      		=v







       def __delitem__(				self      :			Optional[int]    ,   *__lowercase      :			List[str]    ,   **__lowercase      :			str   ):







            """simple docstring"""







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







       def       snake_case (				self      :			Any    ,   *__lowercase      :			int    ,   **__lowercase      :			str   ):







            """simple docstring"""







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







       def       snake_case (				self      :			Optional[Any]    ,   *__lowercase      :			List[str]    ,   **__lowercase      :			List[Any]   ):







            """simple docstring"""







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







       def       snake_case (				self      :			List[Any]    ,   *__lowercase      :			Any    ,   **__lowercase      :			str   ):







            """simple docstring"""







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







       def __getitem__(				self      :			Optional[int]    ,   __lowercase      :			int   ):







            """simple docstring"""







            if isinstance(__lowercase    ,   __lowercase   ):
                 __lowercase      		=dict(self.items()   )
                 return inner_dict[k]
            else:
                 return self.to_tuple()[k]







       def __setattr__(				self      :			int    ,   __lowercase      :			Optional[int]    ,   __lowercase      :			int   ):







            """simple docstring"""







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







       def __setitem__(				self      :			Optional[int]    ,   __lowercase      :			Union[str, Any]    ,   __lowercase      :			Optional[Any]   ):







            """simple docstring"""







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







       def       snake_case (				self      :			Any   ):







            """simple docstring"""







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






class 	lowerCAmelCase  (   A ,      A ):







       @classmethod
       def       snake_case (				cls      :			Dict    ,   __lowercase      :			str   ):







            """simple docstring"""







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






class 	lowerCAmelCase  (   A ):
       lowerCAmelCase_												=			"longest"
       lowerCAmelCase_												=			"max_length"
       lowerCAmelCase_												=			"do_not_pad"






class 	lowerCAmelCase  (   A ):
       lowerCAmelCase_												=			"pt"
       lowerCAmelCase_												=			"tf"
       lowerCAmelCase_												=			"np"
       lowerCAmelCase_												=			"jax"






class 	lowerCAmelCase  :







       def __init__(				self      :			List[Any]    ,   __lowercase      :			List[ContextManager]   ):







            """simple docstring"""







            __lowercase      		=context_managers
            __lowercase      		=ExitStack()







       def __enter__(				self      :			Tuple   ):







            """simple docstring"""







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







       def __exit__(				self      :			str    ,   *__lowercase      :			Optional[Any]    ,   **__lowercase      :			str   ):







            """simple docstring"""







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






def 					__UpperCamelCase				(						lowercase__    :	Any			):






     '''simple docstring'''





     __lowercase      		=infer_framework(lowercase__			)
     if framework == "tf":
          __lowercase      		=inspect.signature(model_class.call			)  # TensorFlow models
     elif framework == "pt":
          __lowercase      		=inspect.signature(model_class.forward			)  # PyTorch models
     else:
          __lowercase      		=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 					__UpperCamelCase				(						lowercase__    :	str			):






     '''simple docstring'''





     __lowercase      		=model_class.__name__
     __lowercase      		=infer_framework(lowercase__			)
     if framework == "tf":
          __lowercase      		=inspect.signature(model_class.call			)  # TensorFlow models
     elif framework == "pt":
          __lowercase      		=inspect.signature(model_class.forward			)  # PyTorch models
     else:
          __lowercase      		=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 					__UpperCamelCase				(						lowercase__    :	MutableMapping,       lowercase__    :	str = "",       lowercase__    :	str = "."			):






     '''simple docstring'''





     def _flatten_dict(lowercase__    :	str,       lowercase__    :	Optional[Any]="",       lowercase__    :	Optional[Any]="."			):
          for k, v in d.items():
               __lowercase      		=str(lowercase__			) + delimiter + str(lowercase__			) if parent_key else k
               if v and isinstance(lowercase__,       lowercase__			):
                    yield from flatten_dict(lowercase__,       lowercase__,       delimiter=lowercase__			).items()
               else:
                    yield key, v

     return dict(_flatten_dict(lowercase__,       lowercase__,       lowercase__			)			)

@contextmanager
def 					__UpperCamelCase				(						lowercase__    :	List[str],       lowercase__    :	bool = False			):






     '''simple docstring'''





     if use_temp_dir:
          with tempfile.TemporaryDirectory() as tmp_dir:
               yield tmp_dir
     else:
          yield working_dir

def 					__UpperCamelCase				(						lowercase__    :	Tuple,       lowercase__    :	List[Any]=None			):






     '''simple docstring'''





     if is_numpy_array(lowercase__			):
          return np.transpose(lowercase__,       axes=lowercase__			)
     elif is_torch_tensor(lowercase__			):
          return array.T if axes is None else array.permute(*lowercase__			)
     elif is_tf_tensor(lowercase__			):
          import tensorflow as tf

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

def 					__UpperCamelCase				(						lowercase__    :	List[str],       lowercase__    :	str			):






     '''simple docstring'''





     if is_numpy_array(lowercase__			):
          return np.reshape(lowercase__,       lowercase__			)
     elif is_torch_tensor(lowercase__			):
          return array.reshape(*lowercase__			)
     elif is_tf_tensor(lowercase__			):
          import tensorflow as tf

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

def 					__UpperCamelCase				(						lowercase__    :	List[Any],       lowercase__    :	str=None			):






     '''simple docstring'''





     if is_numpy_array(lowercase__			):
          return np.squeeze(lowercase__,       axis=lowercase__			)
     elif is_torch_tensor(lowercase__			):
          return array.squeeze() if axis is None else array.squeeze(dim=lowercase__			)
     elif is_tf_tensor(lowercase__			):
          import tensorflow as tf

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

def 					__UpperCamelCase				(						lowercase__    :	Tuple,       lowercase__    :	Optional[Any]			):






     '''simple docstring'''





     if is_numpy_array(lowercase__			):
          return np.expand_dims(lowercase__,       lowercase__			)
     elif is_torch_tensor(lowercase__			):
          return array.unsqueeze(dim=lowercase__			)
     elif is_tf_tensor(lowercase__			):
          import tensorflow as tf

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

def 					__UpperCamelCase				(						lowercase__    :	Tuple			):






     '''simple docstring'''





     if is_numpy_array(lowercase__			):
          return np.size(lowercase__			)
     elif is_torch_tensor(lowercase__			):
          return array.numel()
     elif is_tf_tensor(lowercase__			):
          import tensorflow as tf

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

def 					__UpperCamelCase				(						lowercase__    :	str,       lowercase__    :	Tuple			):






     '''simple docstring'''





     for key, value in auto_map.items():
          if isinstance(lowercase__,       (tuple, list)			):
               __lowercase      		=[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:
               __lowercase      		=F'''{repo_id}--{value}'''

     return auto_map







def 					__UpperCamelCase				(						lowercase__    :	Optional[int]			):






     '''simple docstring'''





     for base_class in inspect.getmro(lowercase__			):
          __lowercase      		=base_class.__module__
          __lowercase      		=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}.'''			)





'''simple docstring'''

import importlib.util
import os
import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import (
    is_accelerate_available,
    is_flax_available,
    is_safetensors_available,
    is_tf_available,
    is_torch_available,
)
from . import BaseTransformersCLICommand

def 					__UpperCamelCase				(						lowercase__    :	Union[str, Any]			):






     '''simple docstring'''





     return EnvironmentCommand()

def 					__UpperCamelCase				(						lowercase__    :	Any			):






     '''simple docstring'''





     return EnvironmentCommand(args.accelerate_config_file			)







class 	lowerCAmelCase  (   A ):







       @staticmethod
       def       snake_case (				__lowercase      :			ArgumentParser   ):







            """simple docstring"""







            __lowercase      		=parser.add_parser('env'   )
            download_parser.set_defaults(func=__lowercase   )
            download_parser.add_argument(
                '--accelerate-config_file'    ,   default=__lowercase    ,   help='The accelerate config file to use for the default values in the launching script.'    ,   )
            download_parser.set_defaults(func=__lowercase   )







       def __init__(				self      :			int    ,   __lowercase      :			Any    ,   *__lowercase      :			str   ):







            """simple docstring"""







            __lowercase      		=accelerate_config_file







       def       snake_case (				self      :			Optional[int]   ):







            """simple docstring"""







            __lowercase      		='not installed'
            if is_safetensors_available():
                 import safetensors

                 __lowercase      		=safetensors.__version__
            elif importlib.util.find_spec('safetensors'   ) is not None:
                 import safetensors

                 __lowercase      		=f'''{safetensors.__version__} but is ignored because of PyTorch version too old.'''

            __lowercase      		='not installed'
            __lowercase      		=__lowercase      		='not found'
            if is_accelerate_available():
                 import accelerate
                 from accelerate.commands.config import default_config_file, load_config_from_file

                 __lowercase      		=accelerate.__version__
                 # Get the default from the config file.
                 if self._accelerate_config_file is not None or os.path.isfile(__lowercase   ):
                      __lowercase      		=load_config_from_file(self._accelerate_config_file   ).to_dict()

                 __lowercase      		=(
                     '\n'.join([f'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]   )
                     if isinstance(__lowercase    ,   __lowercase   )
                     else f'''\t{accelerate_config}'''
                 )

            __lowercase      		='not installed'
            __lowercase      		='NA'
            if is_torch_available():
                 import torch

                 __lowercase      		=torch.__version__
                 __lowercase      		=torch.cuda.is_available()

            __lowercase      		='not installed'
            __lowercase      		='NA'
            if is_tf_available():
                 import tensorflow as tf

                 __lowercase      		=tf.__version__
                 try:
                      # deprecated in v2.1
                      __lowercase      		=tf.test.is_gpu_available()
                 except AttributeError:
                      # returns list of devices, convert to bool
                      __lowercase      		=bool(tf.config.list_physical_devices('GPU'   )   )

            __lowercase      		='not installed'
            __lowercase      		='not installed'
            __lowercase      		='not installed'
            __lowercase      		='NA'
            if is_flax_available():
                 import flax
                 import jax
                 import jaxlib

                 __lowercase      		=flax.__version__
                 __lowercase      		=jax.__version__
                 __lowercase      		=jaxlib.__version__
                 __lowercase      		=jax.lib.xla_bridge.get_backend().platform

            __lowercase      		={
                '`transformers` version': version,
                'Platform': platform.platform(),
                'Python version': platform.python_version(),
                'Huggingface_hub version': huggingface_hub.__version__,
                'Safetensors version': f'''{safetensors_version}''',
                'Accelerate version': f'''{accelerate_version}''',
                'Accelerate config': f'''{accelerate_config_str}''',
                'PyTorch version (GPU?)': f'''{pt_version} ({pt_cuda_available})''',
                'Tensorflow version (GPU?)': f'''{tf_version} ({tf_cuda_available})''',
                'Flax version (CPU?/GPU?/TPU?)': f'''{flax_version} ({jax_backend})''',
                'Jax version': f'''{jax_version}''',
                'JaxLib version': f'''{jaxlib_version}''',
                'Using GPU in script?': '<fill in>',
                'Using distributed or parallel set-up in script?': '<fill in>',
            }

            print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n'   )
            print(self.format_dict(__lowercase   )   )

            return info







       @staticmethod
       def       snake_case (				__lowercase      :			Optional[Any]   ):







            """simple docstring"""







            return "\n".join([f'''- {prop}: {val}''' for prop, val in d.items()]   ) + "\n"


