


"""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							( snake_case_      ):







   def __get__(      self		,      UpperCamelCase__		,      UpperCamelCase__=None		)      ->						Union[str, Any]:

       '''simple docstring'''




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







def     __lowerCAmelCase		(		lowercase    :    Dict					)      ->		Dict:


    """simple docstring"""





    snake_case       : List[Any]    =       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     __lowerCAmelCase		(		lowercase    :    Tuple					)      ->		Optional[Any]:


    """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     __lowerCAmelCase		(		lowercase    :    int					)      ->		Any:


    """simple docstring"""





    return isinstance(lowercase		,				np.ndarray					)







def     __lowerCAmelCase		(		lowercase    :    str					)      ->		int:


    """simple docstring"""





    return _is_numpy(lowercase					)







def     __lowerCAmelCase		(		lowercase    :    Tuple					)      ->		Optional[Any]:


    """simple docstring"""





    import torch

    return isinstance(lowercase		,				torch.Tensor					)







def     __lowerCAmelCase		(		lowercase    :    Dict					)      ->		Dict:


    """simple docstring"""





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







def     __lowerCAmelCase		(		lowercase    :    str					)      ->		str:


    """simple docstring"""





    import torch

    return isinstance(lowercase		,				torch.device					)







def     __lowerCAmelCase		(		lowercase    :    Optional[Any]					)      ->		Optional[Any]:


    """simple docstring"""





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







def     __lowerCAmelCase		(		lowercase    :    str					)      ->		Optional[Any]:


    """simple docstring"""





    import torch

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







def     __lowerCAmelCase		(		lowercase    :    Dict					)      ->		Optional[int]:


    """simple docstring"""





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







def     __lowerCAmelCase		(		lowercase    :    Dict					)      ->		Any:


    """simple docstring"""





    import tensorflow as tf

    return isinstance(lowercase		,				tf.Tensor					)







def     __lowerCAmelCase		(		lowercase    :    List[str]					)      ->		int:


    """simple docstring"""





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







def     __lowerCAmelCase		(		lowercase    :    List[str]					)      ->		Dict:


    """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     __lowerCAmelCase		(		lowercase    :    int					)      ->		str:


    """simple docstring"""





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







def     __lowerCAmelCase		(		lowercase    :    Any					)      ->		Optional[Any]:


    """simple docstring"""





    import jax.numpy as jnp  # noqa: F811

    return isinstance(lowercase		,				jnp.ndarray					)







def     __lowerCAmelCase		(		lowercase    :    List[str]					)      ->		Optional[int]:


    """simple docstring"""





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







def     __lowerCAmelCase		(		lowercase    :    Any					)      ->		Tuple:


    """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     __lowerCAmelCase		(		lowercase    :    Union[str, Any]					)      ->		List[str]:


    """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							( snake_case_      ):







   def 					lowerCamelCase						(      self		)      ->						Dict:

       '''simple docstring'''




       snake_case       : Dict    =       fields(self		)

       # Safety and consistency checks
       if not len(UpperCamelCase__		):
           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       : List[Any]    =       getattr(self		,      class_fields[0].name		)
       snake_case       : int    =       all(getattr(self		,      field.name		) is None for field in class_fields[1:]		)

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







   def __delitem__(      self		,      *UpperCamelCase__		,      **UpperCamelCase__		)      ->						Optional[int]:

       '''simple docstring'''




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







   def 					lowerCamelCase						(      self		,      *UpperCamelCase__		,      **UpperCamelCase__		)      ->						Tuple:

       '''simple docstring'''




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







   def 					lowerCamelCase						(      self		,      *UpperCamelCase__		,      **UpperCamelCase__		)      ->						Any:

       '''simple docstring'''




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







   def 					lowerCamelCase						(      self		,      *UpperCamelCase__		,      **UpperCamelCase__		)      ->						Any:

       '''simple docstring'''




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







   def __getitem__(      self		,      UpperCamelCase__		)      ->						Dict:

       '''simple docstring'''




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







   def __setattr__(      self		,      UpperCamelCase__		,      UpperCamelCase__		)      ->						List[Any]:

       '''simple docstring'''




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







   def __setitem__(      self		,      UpperCamelCase__		,      UpperCamelCase__		)      ->						List[Any]:

       '''simple docstring'''




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







   def 					lowerCamelCase						(      self		)      ->						Tuple[Any]:

       '''simple docstring'''




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







class _lowerCAmelCase							( snake_case_       ,				snake_case_      ):







   @classmethod
   def 					lowerCamelCase						(      cls		,      UpperCamelCase__		)      ->						List[str]:

       '''simple docstring'''




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







class _lowerCAmelCase							( snake_case_      ):
   __UpperCAmelCase					:			Optional[Any]				    =    '''longest'''
   __UpperCAmelCase					:			Tuple				    =    '''max_length'''
   __UpperCAmelCase					:			Optional[Any]				    =    '''do_not_pad'''







class _lowerCAmelCase							( snake_case_      ):
   __UpperCAmelCase					:			Tuple				    =    '''pt'''
   __UpperCAmelCase					:			int				    =    '''tf'''
   __UpperCAmelCase					:			List[str]				    =    '''np'''
   __UpperCAmelCase					:			Union[str, Any]				    =    '''jax'''







class _lowerCAmelCase							:







   def __init__(      self		,      UpperCamelCase__		)      ->						Dict:

       '''simple docstring'''




       snake_case       : Tuple    =       context_managers
       snake_case       : Union[str, Any]    =       ExitStack()







   def __enter__(      self		)      ->						List[Any]:

       '''simple docstring'''




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







   def __exit__(      self		,      *UpperCamelCase__		,      **UpperCamelCase__		)      ->						Optional[int]:

       '''simple docstring'''




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







def     __lowerCAmelCase		(		lowercase    :    List[Any]					)      ->		List[str]:


    """simple docstring"""





    snake_case       : str    =       infer_framework(lowercase					)
    if framework == "tf":
        snake_case       : Tuple    =       inspect.signature(model_class.call					)  # TensorFlow models
    elif framework == "pt":
        snake_case       : Dict    =       inspect.signature(model_class.forward					)  # PyTorch models
    else:
        snake_case       : Optional[Any]    =       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     __lowerCAmelCase		(		lowercase    :    int					)      ->		Optional[int]:


    """simple docstring"""





    snake_case       : Tuple    =       model_class.__name__
    snake_case       : Dict    =       infer_framework(lowercase					)
    if framework == "tf":
        snake_case       : str    =       inspect.signature(model_class.call					)  # TensorFlow models
    elif framework == "pt":
        snake_case       : Optional[int]    =       inspect.signature(model_class.forward					)  # PyTorch models
    else:
        snake_case       : List[str]    =       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     __lowerCAmelCase		(		lowercase    :    MutableMapping		,				lowercase    :    str = ""		,				lowercase    :    str = "."					)      ->		Tuple:


    """simple docstring"""





    def _flatten_dict(lowercase    :    List[Any]		,				lowercase    :    str=""		,				lowercase    :    Tuple="."					):
        for k, v in d.items():
            snake_case       : Any    =       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     __lowerCAmelCase		(		lowercase    :    str		,				lowercase    :    bool = False					)      ->		Union[str, Any]:


    """simple docstring"""





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







def     __lowerCAmelCase		(		lowercase    :    List[Any]		,				lowercase    :    Any=None					)      ->		Optional[int]:


    """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     __lowerCAmelCase		(		lowercase    :    Union[str, Any]		,				lowercase    :    Any					)      ->		Union[str, Any]:


    """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     __lowerCAmelCase		(		lowercase    :    str		,				lowercase    :    List[Any]=None					)      ->		str:


    """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     __lowerCAmelCase		(		lowercase    :    Optional[Any]		,				lowercase    :    List[Any]					)      ->		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     __lowerCAmelCase		(		lowercase    :    Optional[Any]					)      ->		Union[str, Any]:


    """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     __lowerCAmelCase		(		lowercase    :    str		,				lowercase    :    Any					)      ->		Tuple:


    """simple docstring"""





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

    return auto_map







def     __lowerCAmelCase		(		lowercase    :    Optional[Any]					)      ->		Optional[Any]:


    """simple docstring"""





    for base_class in inspect.getmro(lowercase					):
        snake_case       : Dict    =       base_class.__module__
        snake_case       : int    =       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 warnings

from ...utils import logging
from .image_processing_segformer import SegformerImageProcessor


__snake_case       =       logging.get_logger(__name__)







class _lowerCAmelCase							( snake_case_      ):







   def __init__(      self		,      *UpperCamelCase__		,      **UpperCamelCase__		)      ->						None:

       '''simple docstring'''




       warnings.warn(
           "The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
           " Please use SegformerImageProcessor instead."		,      UpperCamelCase__		,      )
       super().__init__(*UpperCamelCase__		,      **UpperCamelCase__		)





