



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      _UpperCAmelCase      (							A__  ):




     def __get__(					self			,    a__			,    a__=None):
         # See docs.python.org/3/howto/descriptor.html#properties
         if obj is None:
             return self
         if self.fget is None:
             raise AttributeError('''unreadable attribute''')
         A__					=       '''__cached_''' + self.fget.__name__
         A__					=       getattr(a__			,    a__			,    a__)
         if cached is None:
             A__					=       self.fget(a__)
             setattr(a__			,    a__			,    a__)
         return cached







def 		lowerCAmelCase__     (       UpperCamelCase_					:							Any						)->	Dict:
    A__					=       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__     (       UpperCamelCase_					:							Union[str, Any]						)->	List[str]:
    if is_torch_fx_proxy(UpperCamelCase_						):
        return True
    if is_torch_available():
        import torch

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

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

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

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

    return isinstance(UpperCamelCase_			,							np.ndarray						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Optional[int]						)->	Optional[Any]:
    return isinstance(UpperCamelCase_			,							np.ndarray						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Tuple						)->	Optional[Any]:
    return _is_numpy(UpperCamelCase_						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Optional[int]						)->	Union[str, Any]:
    import torch

    return isinstance(UpperCamelCase_			,							torch.Tensor						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							List[Any]						)->	Any:
    return False if not is_torch_available() else _is_torch(UpperCamelCase_						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							List[str]						)->	Optional[Any]:
    import torch

    return isinstance(UpperCamelCase_			,							torch.device						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Any						)->	List[Any]:
    return False if not is_torch_available() else _is_torch_device(UpperCamelCase_						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Dict						)->	Any:
    import torch

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



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Optional[Any]						)->	List[str]:
    return False if not is_torch_available() else _is_torch_dtype(UpperCamelCase_						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Tuple						)->	List[Any]:
    import tensorflow as tf

    return isinstance(UpperCamelCase_			,							tf.Tensor						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Dict						)->	Dict:
    return False if not is_tf_available() else _is_tensorflow(UpperCamelCase_						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Optional[int]						)->	Optional[int]:
    import tensorflow as tf

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



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Any						)->	int:
    return False if not is_tf_available() else _is_tf_symbolic_tensor(UpperCamelCase_						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							List[str]						)->	List[str]:
    import jax.numpy as jnp  # noqa: F811

    return isinstance(UpperCamelCase_			,							jnp.ndarray						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Optional[int]						)->	Dict:
    return False if not is_flax_available() else _is_jax(UpperCamelCase_						)



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



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



class      _UpperCAmelCase      (							A__  ):




     def 		snake_case_		(					self):
         A__					=       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.")

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




     def __delitem__(					self			,    *a__			,    **a__):
         raise Exception(F"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")




     def 		snake_case_		(					self			,    *a__			,    **a__):
         raise Exception(F"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")




     def 		snake_case_		(					self			,    *a__			,    **a__):
         raise Exception(F"You cannot use ``pop`` on a {self.__class__.__name__} instance.")




     def 		snake_case_		(					self			,    *a__			,    **a__):
         raise Exception(F"You cannot use ``update`` on a {self.__class__.__name__} instance.")




     def __getitem__(					self			,    a__):
         if isinstance(a__			,    a__):
             A__					=       dict(self.items())
             return inner_dict[k]
         else:
             return self.to_tuple()[k]




     def __setattr__(					self			,    a__			,    a__):
         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__):
         # Will raise a KeyException if needed
         super().__setitem__(a__			,    a__)
         # Don't call self.__setattr__ to avoid recursion errors
         super().__setattr__(a__			,    a__)




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







class      _UpperCAmelCase      (							A__      ,   A__  ):




     @classmethod
     def 		snake_case_		(					cls			,    a__):
         raise ValueError(
             F"{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys())}")







class      _UpperCAmelCase      (							A__  ):
     UpperCamelCase__		     =					'''longest'''
     UpperCamelCase__		     =					'''max_length'''
     UpperCamelCase__		     =					'''do_not_pad'''







class      _UpperCAmelCase      (							A__  ):
     UpperCamelCase__		     =					'''pt'''
     UpperCamelCase__		     =					'''tf'''
     UpperCamelCase__		     =					'''np'''
     UpperCamelCase__		     =					'''jax'''







class      _UpperCAmelCase      :




     def __init__(					self			,    a__):
         A__					=       context_managers
         A__					=       ExitStack()




     def __enter__(					self):
         for context_manager in self.context_managers:
             self.stack.enter_context(a__)




     def __exit__(					self			,    *a__			,    **a__):
         self.stack.__exit__(*a__			,    **a__)







def 		lowerCAmelCase__     (       UpperCamelCase_					:							List[str]						)->	Optional[Any]:
    A__					=       infer_framework(UpperCamelCase_						)
    if framework == "tf":
        A__					=       inspect.signature(model_class.call						)  # TensorFlow models
    elif framework == "pt":
        A__					=       inspect.signature(model_class.forward						)  # PyTorch models
    else:
        A__					=       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__     (       UpperCamelCase_					:							str						)->	List[str]:
    A__					=       model_class.__name__
    A__					=       infer_framework(UpperCamelCase_						)
    if framework == "tf":
        A__					=       inspect.signature(model_class.call						)  # TensorFlow models
    elif framework == "pt":
        A__					=       inspect.signature(model_class.forward						)  # PyTorch models
    else:
        A__					=       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__     (       UpperCamelCase_					:							MutableMapping			,							UpperCamelCase_					:							str = ""			,							UpperCamelCase_					:							str = "."						)->	Optional[Any]:

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

    return dict(_flatten_dict(UpperCamelCase_			,							UpperCamelCase_			,							UpperCamelCase_						)						)



@contextmanager
def 		lowerCAmelCase__     (       UpperCamelCase_					:							List[Any]			,							UpperCamelCase_					:							bool = False						)->	Tuple:
    if use_temp_dir:
        with tempfile.TemporaryDirectory() as tmp_dir:
            yield tmp_dir
    else:
        yield working_dir



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Tuple			,							UpperCamelCase_					:							Tuple=None						)->	Optional[Any]:
    if is_numpy_array(UpperCamelCase_						):
        return np.transpose(UpperCamelCase_			,							axes=UpperCamelCase_						)
    elif is_torch_tensor(UpperCamelCase_						):
        return array.T if axes is None else array.permute(*UpperCamelCase_						)
    elif is_tf_tensor(UpperCamelCase_						):
        import tensorflow as tf

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



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Union[str, Any]			,							UpperCamelCase_					:							Any						)->	Dict:
    if is_numpy_array(UpperCamelCase_						):
        return np.reshape(UpperCamelCase_			,							UpperCamelCase_						)
    elif is_torch_tensor(UpperCamelCase_						):
        return array.reshape(*UpperCamelCase_						)
    elif is_tf_tensor(UpperCamelCase_						):
        import tensorflow as tf

        return tf.reshape(UpperCamelCase_			,							UpperCamelCase_						)
    elif is_jax_tensor(UpperCamelCase_						):
        return jnp.reshape(UpperCamelCase_			,							UpperCamelCase_						)
    else:
        raise ValueError(f"Type not supported for reshape: {type(UpperCamelCase_						)}."						)



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

        return tf.squeeze(UpperCamelCase_			,							axis=UpperCamelCase_						)
    elif is_jax_tensor(UpperCamelCase_						):
        return jnp.squeeze(UpperCamelCase_			,							axis=UpperCamelCase_						)
    else:
        raise ValueError(f"Type not supported for squeeze: {type(UpperCamelCase_						)}."						)



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

        return tf.expand_dims(UpperCamelCase_			,							axis=UpperCamelCase_						)
    elif is_jax_tensor(UpperCamelCase_						):
        return jnp.expand_dims(UpperCamelCase_			,							axis=UpperCamelCase_						)
    else:
        raise ValueError(f"Type not supported for expand_dims: {type(UpperCamelCase_						)}."						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Any						)->	Union[str, Any]:
    if is_numpy_array(UpperCamelCase_						):
        return np.size(UpperCamelCase_						)
    elif is_torch_tensor(UpperCamelCase_						):
        return array.numel()
    elif is_tf_tensor(UpperCamelCase_						):
        import tensorflow as tf

        return tf.size(UpperCamelCase_						)
    elif is_jax_tensor(UpperCamelCase_						):
        return array.size
    else:
        raise ValueError(f"Type not supported for expand_dims: {type(UpperCamelCase_						)}."						)



def 		lowerCAmelCase__     (       UpperCamelCase_					:							List[str]			,							UpperCamelCase_					:							Dict						)->	Any:
    for key, value in auto_map.items():
        if isinstance(UpperCamelCase_			,							(tuple, list)						):
            A__					=       [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:
            A__					=       f"{repo_id}--{value}"

    return auto_map



def 		lowerCAmelCase__     (       UpperCamelCase_					:							Tuple						)->	Union[str, Any]:
    for base_class in inspect.getmro(UpperCamelCase_						):
        A__					=       base_class.__module__
        A__					=       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}."						)





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_lowercase    	=		{
    "configuration_upernet": ["UperNetConfig"],
}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _lowercase    	=		[
       "UperNetForSemanticSegmentation",
       "UperNetPreTrainedModel",
   ]


if TYPE_CHECKING:
   from .configuration_upernet import UperNetConfig

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel


else:
   import sys

   _lowercase    	=		_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
