
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		(  lowerCAmelCase__  ):





     def __get__(self				:   List[Any]    ,   _A				:   Tuple    ,   _A				:   Optional[Any]=None       )						->						Dict:
         # See docs.python.org/3/howto/descriptor.html#properties
         if obj is None:
             return self
         if self.fget is None:
             raise AttributeError("unreadable attribute"       )
         snake_case								= "__cached_" + self.fget.__name__
         snake_case								= getattr(a__    ,   a__    ,   a__       )
         if cached is None:
             snake_case								= self.fget(a__       )
             setattr(a__    ,   a__    ,   a__       )
         return cached



def 						lowercase_      (       A__		)							->							Tuple:
    """simple docstring"""

    snake_case								= 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 						lowercase_      (       A__		)							->							Tuple:
    """simple docstring"""

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

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

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

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

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

    return isinstance(A__			,		np.ndarray		)



def 						lowercase_      (       A__		)							->							List[Any]:
    """simple docstring"""

    return isinstance(A__			,		np.ndarray		)



def 						lowercase_      (       A__		)							->							int:
    """simple docstring"""

    return _is_numpy(A__		)



def 						lowercase_      (       A__		)							->							Optional[Any]:
    """simple docstring"""

    import torch

    return isinstance(A__			,		torch.Tensor		)



def 						lowercase_      (       A__		)							->							Dict:
    """simple docstring"""

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



def 						lowercase_      (       A__		)							->							Optional[int]:
    """simple docstring"""

    import torch

    return isinstance(A__			,		torch.device		)



def 						lowercase_      (       A__		)							->							Any:
    """simple docstring"""

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



def 						lowercase_      (       A__		)							->							int:
    """simple docstring"""

    import torch

    if isinstance(A__			,		A__		):
        if hasattr(A__			,		A__		):
            snake_case								= getattr(A__			,		A__		)
        else:
            return False
    return isinstance(A__			,		torch.dtype		)



def 						lowercase_      (       A__		)							->							List[Any]:
    """simple docstring"""

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



def 						lowercase_      (       A__		)							->							Union[str, Any]:
    """simple docstring"""

    import tensorflow as tf

    return isinstance(A__			,		tf.Tensor		)



def 						lowercase_      (       A__		)							->							str:
    """simple docstring"""

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



def 						lowercase_      (       A__		)							->							int:
    """simple docstring"""

    import tensorflow as tf

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



def 						lowercase_      (       A__		)							->							Optional[int]:
    """simple docstring"""

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



def 						lowercase_      (       A__		)							->							Optional[int]:
    """simple docstring"""

    import jax.numpy as jnp  # noqa: F811

    return isinstance(A__			,		jnp.ndarray		)



def 						lowercase_      (       A__		)							->							List[str]:
    """simple docstring"""

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



def 						lowercase_      (       A__		)							->							int:
    """simple docstring"""

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



def 						lowercase_      (       A__		)							->							Tuple:
    """simple docstring"""

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







class 					lowerCamelCase		(  lowerCAmelCase__  ):





     def 		UpperCAmelCase(self				:   List[Any]       )						->						Any:
         snake_case								= 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.'       )

         snake_case								= getattr(self    ,   class_fields[0].name       )
         snake_case								= 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__       ):
                 snake_case								= first_field.items()
                 snake_case								= True
             else:
                 try:
                     snake_case								= iter(a__       )
                     snake_case								= True
                 except TypeError:
                     snake_case								= 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
                             snake_case								= 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:
                         snake_case								= element[1]
             elif first_field is not None:
                 snake_case								= first_field
         else:
             for field in class_fields:
                 snake_case								= getattr(self    ,   field.name       )
                 if v is not None:
                     snake_case								= v





     def __delitem__(self				:   Any    ,   *_A				:   List[str]    ,   **_A				:   Optional[Any]       )						->						List[str]:
         raise Exception(f'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'       )





     def 		UpperCAmelCase(self				:   int    ,   *_A				:   Optional[Any]    ,   **_A				:   int       )						->						List[Any]:
         raise Exception(f'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'       )





     def 		UpperCAmelCase(self				:   Tuple    ,   *_A				:   Tuple    ,   **_A				:   Tuple       )						->						List[str]:
         raise Exception(f'You cannot use ``pop`` on a {self.__class__.__name__} instance.'       )





     def 		UpperCAmelCase(self				:   int    ,   *_A				:   Union[str, Any]    ,   **_A				:   Any       )						->						Union[str, Any]:
         raise Exception(f'You cannot use ``update`` on a {self.__class__.__name__} instance.'       )





     def __getitem__(self				:   Tuple    ,   _A				:   List[str]       )						->						Optional[Any]:
         if isinstance(a__    ,   a__       ):
             snake_case								= dict(self.items()       )
             return inner_dict[k]
         else:
             return self.to_tuple()[k]





     def __setattr__(self				:   List[str]    ,   _A				:   str    ,   _A				:   List[str]       )						->						List[str]:
         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				:   Any    ,   _A				:   Tuple    ,   _A				:   Optional[Any]       )						->						Tuple:
         # Will raise a KeyException if needed
         super().__setitem__(a__    ,   a__       )
         # Don't call self.__setattr__ to avoid recursion errors
         super().__setattr__(a__    ,   a__       )





     def 		UpperCAmelCase(self				:   Tuple       )						->						List[str]:
         return tuple(self[k] for k in self.keys()       )







class 					lowerCamelCase		(  lowerCAmelCase__							,			lowerCAmelCase__  ):





     @classmethod
     def 		UpperCAmelCase(cls				:   Tuple    ,   _A				:   int       )						->						Optional[Any]:
         raise ValueError(
             f'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()       )}'       )







class 					lowerCamelCase		(  lowerCAmelCase__  ):
     UpperCAmelCase__    :							List[str]									=		"longest"
     UpperCAmelCase__    :							int									=		"max_length"
     UpperCAmelCase__    :							Union[str, Any]									=		"do_not_pad"







class 					lowerCamelCase		(  lowerCAmelCase__  ):
     UpperCAmelCase__    :							int									=		"pt"
     UpperCAmelCase__    :							str									=		"tf"
     UpperCAmelCase__    :							List[Any]									=		"np"
     UpperCAmelCase__    :							Optional[Any]									=		"jax"







class 					lowerCamelCase		:





     def __init__(self				:   Any    ,   _A				:   Union[str, Any]       )						->						Dict:
         snake_case								= context_managers
         snake_case								= ExitStack()





     def __enter__(self				:   Optional[int]       )						->						Dict:
         for context_manager in self.context_managers:
             self.stack.enter_context(a__       )





     def __exit__(self				:   Any    ,   *_A				:   List[Any]    ,   **_A				:   Optional[int]       )						->						Union[str, Any]:
         self.stack.__exit__(*a__    ,   **a__       )



def 						lowercase_      (       A__		)							->							List[str]:
    """simple docstring"""

    snake_case								= infer_framework(A__		)
    if framework == "tf":
        snake_case								= inspect.signature(model_class.call		)  # TensorFlow models
    elif framework == "pt":
        snake_case								= inspect.signature(model_class.forward		)  # PyTorch models
    else:
        snake_case								= 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 						lowercase_      (       A__		)							->							List[Any]:
    """simple docstring"""

    snake_case								= model_class.__name__
    snake_case								= infer_framework(A__		)
    if framework == "tf":
        snake_case								= inspect.signature(model_class.call		)  # TensorFlow models
    elif framework == "pt":
        snake_case								= inspect.signature(model_class.forward		)  # PyTorch models
    else:
        snake_case								= 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 						lowercase_      (       A__			,		A__ = ""			,		A__ = "."		)							->							Any:
    """simple docstring"""

    def _flatten_dict(A__			,		A__=""			,		A__="."		):
        for k, v in d.items():
            snake_case								= str(A__		) + delimiter + str(A__		) if parent_key else k
            if v and isinstance(A__			,		A__		):
                yield from flatten_dict(A__			,		A__			,		delimiter=A__		).items()
            else:
                yield key, v

    return dict(_flatten_dict(A__			,		A__			,		A__		)		)



@contextmanager
def 						lowercase_      (       A__			,		A__ = False		)							->							Optional[int]:
    """simple docstring"""

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



def 						lowercase_      (       A__			,		A__=None		)							->							str:
    """simple docstring"""

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

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



def 						lowercase_      (       A__			,		A__		)							->							Union[str, Any]:
    """simple docstring"""

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

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



def 						lowercase_      (       A__			,		A__=None		)							->							Dict:
    """simple docstring"""

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

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



def 						lowercase_      (       A__			,		A__		)							->							Tuple:
    """simple docstring"""

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

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



def 						lowercase_      (       A__		)							->							Union[str, Any]:
    """simple docstring"""

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

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



def 						lowercase_      (       A__			,		A__		)							->							Optional[Any]:
    """simple docstring"""

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

    return auto_map





def 						lowercase_      (       A__		)							->							Tuple:
    """simple docstring"""

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






import unittest

from transformers.utils.backbone_utils import (
    BackboneMixin,
    get_aligned_output_features_output_indices,
    verify_out_features_out_indices,
)







class 					lowerCamelCase		(  unittest.TestCase  ):





     def 		UpperCAmelCase(self				:   Tuple       )						->						List[str]:
         snake_case								= ["a", "b", "c"]

         # Defaults to last layer if both are None
         snake_case					,							snake_case								= get_aligned_output_features_output_indices(_A    ,   _A    ,   _A       )
         self.assertEqual(_A    ,   ["c"]       )
         self.assertEqual(_A    ,   [2]       )

         # Out indices set to match out features
         snake_case					,							snake_case								= get_aligned_output_features_output_indices(["a", "c"]    ,   _A    ,   _A       )
         self.assertEqual(_A    ,   ["a", "c"]       )
         self.assertEqual(_A    ,   [0, 2]       )

         # Out features set to match out indices
         snake_case					,							snake_case								= get_aligned_output_features_output_indices(_A    ,   [0, 2]    ,   _A       )
         self.assertEqual(_A    ,   ["a", "c"]       )
         self.assertEqual(_A    ,   [0, 2]       )

         # Out features selected from negative indices
         snake_case					,							snake_case								= get_aligned_output_features_output_indices(_A    ,   [-3, -1]    ,   _A       )
         self.assertEqual(_A    ,   ["a", "c"]       )
         self.assertEqual(_A    ,   [-3, -1]       )





     def 		UpperCAmelCase(self				:   Optional[int]       )						->						str:
         # Stage names must be set
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(["a", "b"]    ,   (0, 1)    ,   _A       )

         # Out features must be a list
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(("a", "b")    ,   (0, 1)    ,   ["a", "b"]       )

         # Out features must be a subset of stage names
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(["a", "b"]    ,   (0, 1)    ,   ["a"]       )

         # Out indices must be a list or tuple
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(_A    ,   0    ,   ["a", "b"]       )

         # Out indices must be a subset of stage names
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(_A    ,   (0, 1)    ,   ["a"]       )

         # Out features and out indices must be the same length
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(["a", "b"]    ,   (0,)    ,   ["a", "b", "c"]       )

         # Out features should match out indices
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(["a", "b"]    ,   (0, 2)    ,   ["a", "b", "c"]       )

         # Out features and out indices should be in order
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(["b", "a"]    ,   (0, 1)    ,   ["a", "b"]       )

         # Check passes with valid inputs
         verify_out_features_out_indices(["a", "b", "d"]    ,   (0, 1, -1)    ,   ["a", "b", "c", "d"]       )





     def 		UpperCAmelCase(self				:   List[str]       )						->						str:
         snake_case								= BackboneMixin()

         snake_case								= ["a", "b", "c"]
         snake_case								= ["a", "c"]
         snake_case								= [0, 2]

         # Check that the output features and indices are set correctly
         self.assertEqual(backbone.out_features    ,   ["a", "c"]       )
         self.assertEqual(backbone.out_indices    ,   [0, 2]       )

         # Check out features and indices are updated correctly
         snake_case								= ["a", "b"]
         self.assertEqual(backbone.out_features    ,   ["a", "b"]       )
         self.assertEqual(backbone.out_indices    ,   [0, 1]       )

         snake_case								= [-3, -1]
         self.assertEqual(backbone.out_features    ,   ["a", "c"]       )
         self.assertEqual(backbone.out_indices    ,   [-3, -1]       )

