



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






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


        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("""unreadable attribute"""		)
        A			:	Tuple										=       """__cached_""" + self.fget.__name__
        A			:	List[Any]										=       getattr(__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase		)
        if cached is None:
            A			:	Any										=       self.fget(__UpperCAmelCase		)
            setattr(__UpperCAmelCase,		__UpperCAmelCase,		__UpperCAmelCase		)
        return cached




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  int:



    """simple docstring"""






    A			:	Tuple										=       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     (  _lowerCAmelCase		)	->  Optional[Any]:



    """simple docstring"""






    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      __UpperCamelCase     (  _lowerCAmelCase		)	->  Optional[Any]:



    """simple docstring"""






    return isinstance(_lowerCAmelCase				,					np.ndarray		)




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  Tuple:



    """simple docstring"""






    return _is_numpy(_lowerCAmelCase		)




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  Union[str, Any]:



    """simple docstring"""






    import torch

    return isinstance(_lowerCAmelCase				,					torch.Tensor		)




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  str:



    """simple docstring"""






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




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  List[Any]:



    """simple docstring"""






    import torch

    return isinstance(_lowerCAmelCase				,					torch.device		)




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  Dict:



    """simple docstring"""






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




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  Any:



    """simple docstring"""






    import torch

    if isinstance(_lowerCAmelCase				,					_lowerCAmelCase		):
        if hasattr(_lowerCAmelCase				,					_lowerCAmelCase		):
            A			:	int										=       getattr(_lowerCAmelCase				,					_lowerCAmelCase		)
        else:
            return False
    return isinstance(_lowerCAmelCase				,					torch.dtype		)




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  str:



    """simple docstring"""






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




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  List[Any]:



    """simple docstring"""






    import tensorflow as tf

    return isinstance(_lowerCAmelCase				,					tf.Tensor		)




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  Optional[int]:



    """simple docstring"""






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




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  str:



    """simple docstring"""






    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      __UpperCamelCase     (  _lowerCAmelCase		)	->  str:



    """simple docstring"""






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




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  List[Any]:



    """simple docstring"""






    import jax.numpy as jnp  # noqa: F811

    return isinstance(_lowerCAmelCase				,					jnp.ndarray		)




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  Dict:



    """simple docstring"""






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




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  List[Any]:



    """simple docstring"""






    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      __UpperCamelCase     (  _lowerCAmelCase		)	->  Optional[Any]:



    """simple docstring"""






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






    def       _lowerCAmelCase (	self		):
        A			:	Optional[int]										=       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.'''		)

        A			:	List[Any]										=       getattr(self,		class_fields[0].name		)
        A			:	List[Any]										=       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		):
                A			:	Dict										=       first_field.items()
                A			:	Tuple										=       True
            else:
                try:
                    A			:	Union[str, Any]										=       iter(__UpperCAmelCase		)
                    A			:	int										=       True
                except TypeError:
                    A			:	Optional[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
                            A			:	Optional[Any]										=       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			:	Dict										=       element[1]
            elif first_field is not None:
                A			:	str										=       first_field
        else:
            for field in class_fields:
                A			:	int										=       getattr(self,		field.name		)
                if v is not None:
                    A			:	Dict										=       v






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






    def       _lowerCAmelCase (	self,		*lowerCamelCase__,		**lowerCamelCase__		):
        raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''		)






    def       _lowerCAmelCase (	self,		*lowerCamelCase__,		**lowerCamelCase__		):
        raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''		)






    def       _lowerCAmelCase (	self,		*lowerCamelCase__,		**lowerCamelCase__		):
        raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''		)






    def __getitem__(	self,		lowerCamelCase__		):


        if isinstance(__UpperCAmelCase,		__UpperCAmelCase		):
            A			:	Union[str, Any]										=       dict(self.items()		)
            return inner_dict[k]
        else:
            return self.to_tuple()[k]






    def __setattr__(	self,		lowerCamelCase__,		lowerCamelCase__		):


        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,		lowerCamelCase__,		lowerCamelCase__		):
        super().__setitem__(__UpperCAmelCase,		__UpperCAmelCase		)
        # Don't call self.__setattr__ to avoid recursion errors
        super().__setattr__(__UpperCAmelCase,		__UpperCAmelCase		)






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






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__			,						SCREAMING_SNAKE_CASE__   ):






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






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):
    __lowerCamelCase      :			Union[str, Any] =				"longest"
    __lowerCamelCase      :			Optional[Any] =				"max_length"
    __lowerCamelCase      :			Optional[int] =				"do_not_pad"






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):
    __lowerCamelCase      :			Tuple =				"pt"
    __lowerCamelCase      :			Tuple =				"tf"
    __lowerCamelCase      :			Dict =				"np"
    __lowerCamelCase      :			Optional[Any] =				"jax"






class SCREAMING_SNAKE_CASE__					:






    def __init__(	self,		lowerCamelCase__		):
        A			:	Tuple										=       context_managers
        A			:	Any										=       ExitStack()






    def __enter__(	self		):


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






    def __exit__(	self,		*lowerCamelCase__,		**lowerCamelCase__		):
        self.stack.__exit__(*__UpperCAmelCase,		**__UpperCAmelCase		)




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  List[Any]:



    """simple docstring"""






    A			:	str										=       infer_framework(_lowerCAmelCase		)
    if framework == "tf":
        A			:	Dict										=       inspect.signature(model_class.call		)  # TensorFlow models
    elif framework == "pt":
        A			:	Tuple										=       inspect.signature(model_class.forward		)  # PyTorch models
    else:
        A			:	List[str]										=       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     (  _lowerCAmelCase		)	->  Tuple:



    """simple docstring"""






    A			:	Optional[int]										=       model_class.__name__
    A			:	str										=       infer_framework(_lowerCAmelCase		)
    if framework == "tf":
        A			:	List[str]										=       inspect.signature(model_class.call		)  # TensorFlow models
    elif framework == "pt":
        A			:	str										=       inspect.signature(model_class.forward		)  # PyTorch models
    else:
        A			:	Union[str, Any]										=       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     (  _lowerCAmelCase				,					_lowerCAmelCase = ""				,					_lowerCAmelCase = "."		)	->  Any:



    """simple docstring"""






    def _flatten_dict(_lowerCAmelCase				,					_lowerCAmelCase=""				,					_lowerCAmelCase="."		):
        for k, v in d.items():
            A			:	Dict										=       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      __UpperCamelCase     (  _lowerCAmelCase				,					_lowerCAmelCase = False		)	->  Any:



    """simple docstring"""






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




def      __UpperCamelCase     (  _lowerCAmelCase				,					_lowerCAmelCase=None		)	->  Any:



    """simple docstring"""






    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      __UpperCamelCase     (  _lowerCAmelCase				,					_lowerCAmelCase		)	->  Optional[Any]:



    """simple docstring"""






    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      __UpperCamelCase     (  _lowerCAmelCase				,					_lowerCAmelCase=None		)	->  Any:



    """simple docstring"""






    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      __UpperCamelCase     (  _lowerCAmelCase				,					_lowerCAmelCase		)	->  Optional[Any]:



    """simple docstring"""






    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      __UpperCamelCase     (  _lowerCAmelCase		)	->  Union[str, Any]:



    """simple docstring"""






    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      __UpperCamelCase     (  _lowerCAmelCase				,					_lowerCAmelCase		)	->  Optional[int]:



    """simple docstring"""






    for key, value in auto_map.items():
        if isinstance(_lowerCAmelCase				,					(tuple, list)		):
            A			:	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:
            A			:	List[Any]										=       f'''{repo_id}--{value}'''

    return auto_map




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  Optional[int]:



    """simple docstring"""






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







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


SCREAMING_SNAKE_CASE_:Any					=						{
    """configuration_mobilenet_v2""": [
        """MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """MobileNetV2Config""",
        """MobileNetV2OnnxConfig""",
    ],
}

try:
     if not is_vision_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     SCREAMING_SNAKE_CASE_:List[Any]					=						["""MobileNetV2FeatureExtractor"""]
     SCREAMING_SNAKE_CASE_:Tuple					=						["""MobileNetV2ImageProcessor"""]


try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     SCREAMING_SNAKE_CASE_:Any					=						[
         """MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """MobileNetV2ForImageClassification""",
         """MobileNetV2ForSemanticSegmentation""",
         """MobileNetV2Model""",
         """MobileNetV2PreTrainedModel""",
         """load_tf_weights_in_mobilenet_v2""",
     ]


if TYPE_CHECKING:
     from .configuration_mobilenet_va import (
         MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP,
         MobileNetVaConfig,
         MobileNetVaOnnxConfig,
     )

     try:
          if not is_vision_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .feature_extraction_mobilenet_va import MobileNetVaFeatureExtractor
          from .image_processing_mobilenet_va import MobileNetVaImageProcessor

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_mobilenet_va import (
              MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST,
              MobileNetVaForImageClassification,
              MobileNetVaForSemanticSegmentation,
              MobileNetVaModel,
              MobileNetVaPreTrainedModel,
              load_tf_weights_in_mobilenet_va,
          )


else:
     import sys

     SCREAMING_SNAKE_CASE_:Optional[Any]					=						_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


