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





     """simple docstring"""







     def __get__(				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE=None	)	-> Dict:




           """simple docstring"""







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


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      UpperCamelCase__     : 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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):


      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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      return isinstance(_UpperCamelCase			,		np.ndarray		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      return _is_numpy(_UpperCamelCase		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      import torch

      return isinstance(_UpperCamelCase			,		torch.Tensor		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      return False if not is_torch_available() else _is_torch(_UpperCamelCase		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      import torch

      return isinstance(_UpperCamelCase			,		torch.device		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      return False if not is_torch_available() else _is_torch_device(_UpperCamelCase		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      import torch

      if isinstance(_UpperCamelCase			,		_UpperCamelCase		):
            if hasattr(_UpperCamelCase			,		_UpperCamelCase		):
                  UpperCamelCase__     : str											=					getattr(_UpperCamelCase			,		_UpperCamelCase		)
            else:
                  return False
      return isinstance(_UpperCamelCase			,		torch.dtype		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      return False if not is_torch_available() else _is_torch_dtype(_UpperCamelCase		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      import tensorflow as tf

      return isinstance(_UpperCamelCase			,		tf.Tensor		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      return False if not is_tf_available() else _is_tensorflow(_UpperCamelCase		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      return False if not is_tf_available() else _is_tf_symbolic_tensor(_UpperCamelCase		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      import jax.numpy as jnp  # noqa: F811

      return isinstance(_UpperCamelCase			,		jnp.ndarray		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      return False if not is_flax_available() else _is_jax(_UpperCamelCase		)


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):


      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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):


      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 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     def  __SCREAMING_SNAKE_CASE      (				self	)	-> List[str]:




           """simple docstring"""







           UpperCamelCase__     : str											=					fields(self	)

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

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

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






     def __delitem__(				self    ,    *__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)	-> Any:




           """simple docstring"""







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






     def  __SCREAMING_SNAKE_CASE      (				self    ,    *__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)	-> Dict:




           """simple docstring"""







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






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




           """simple docstring"""







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






     def  __SCREAMING_SNAKE_CASE      (				self    ,    *__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)	-> str:




           """simple docstring"""







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






     def __getitem__(				self    ,    __SCREAMING_SNAKE_CASE	)	-> str:




           """simple docstring"""







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






     def __setattr__(				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE	)	-> str:




           """simple docstring"""







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






     def __setitem__(				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE	)	-> Optional[int]:




           """simple docstring"""







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






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Tuple:




           """simple docstring"""







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




class 					_lowerCamelCase			(   UpperCamelCase_						,				UpperCamelCase_			):





     """simple docstring"""







     @classmethod
     def  __SCREAMING_SNAKE_CASE      (				cls    ,    __SCREAMING_SNAKE_CASE	)	-> Optional[Any]:




           """simple docstring"""







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




class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		 =	'''longest'''
     SCREAMING_SNAKE_CASE_		 =	'''max_length'''
     SCREAMING_SNAKE_CASE_		 =	'''do_not_pad'''




class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		 =	'''pt'''
     SCREAMING_SNAKE_CASE_		 =	'''tf'''
     SCREAMING_SNAKE_CASE_		 =	'''np'''
     SCREAMING_SNAKE_CASE_		 =	'''jax'''




class 					_lowerCamelCase			:





     """simple docstring"""







     def __init__(				self    ,    __SCREAMING_SNAKE_CASE	)	-> Optional[Any]:




           """simple docstring"""







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






     def __enter__(				self	)	-> Optional[int]:




           """simple docstring"""







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






     def __exit__(				self    ,    *__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)	-> Optional[Any]:




           """simple docstring"""







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


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      UpperCamelCase__     : Tuple											=					infer_framework(_UpperCamelCase		)
      if framework == "tf":
            UpperCamelCase__     : Optional[int]											=					inspect.signature(model_class.call		)  # TensorFlow models
      elif framework == "pt":
            UpperCamelCase__     : int											=					inspect.signature(model_class.forward		)  # PyTorch models
      else:
            UpperCamelCase__     : Tuple											=					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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):
      UpperCamelCase__     : int											=					model_class.__name__
      UpperCamelCase__     : Any											=					infer_framework(_UpperCamelCase		)
      if framework == "tf":
            UpperCamelCase__     : Any											=					inspect.signature(model_class.call		)  # TensorFlow models
      elif framework == "pt":
            UpperCamelCase__     : int											=					inspect.signature(model_class.forward		)  # PyTorch models
      else:
            UpperCamelCase__     : Optional[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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__ = ""			,		UpperCamelCase__ = "."		):


      def _flatten_dict(UpperCamelCase__			,		UpperCamelCase__=""			,		UpperCamelCase__="."		):
            for k, v in d.items():
                  UpperCamelCase__     : int											=					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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__ = False		):


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


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__=None		):


      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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__		):


      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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__=None		):


      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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__		):


      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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):


      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 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__			,		UpperCamelCase__		):


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

      return auto_map


def 				SCREAMING_SNAKE_CASE_   (      UpperCamelCase__		):


      for base_class in inspect.getmro(_UpperCamelCase		):
            UpperCamelCase__     : Dict											=					base_class.__module__
            UpperCamelCase__     : Union[str, Any]											=					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 warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding




class   UpperCamelCase			(  SCREAMING_SNAKE_CASE ):
    __UpperCamelCase    =["image_processor", "tokenizer"]
    __UpperCamelCase    ="CLIPImageProcessor"
    __UpperCamelCase    =("CLIPTokenizer", "CLIPTokenizerFast")

    def __init__(      self			:   int				,     snake_case__			:   List[Any]=None				,     snake_case__			:   Any=None				,     **snake_case__			:   Any     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      None
     if "feature_extractor" in kwargs:
      warnings.warn(
          'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
          ' instead.'				,     snake_case__				,     )
      SCREAMING_SNAKE_CASE		    =      kwargs.pop('feature_extractor'     )

     SCREAMING_SNAKE_CASE		    =      image_processor if image_processor is not None else feature_extractor
     if image_processor is None:
      raise ValueError('You need to specify an `image_processor`.'     )
     if tokenizer is None:
      raise ValueError('You need to specify a `tokenizer`.'     )

     super().__init__(snake_case__				,     snake_case__     )

    def __call__(      self			:   List[Any]				,     snake_case__			:   Tuple=None				,     snake_case__			:   Optional[int]=None				,     snake_case__			:   List[str]=None				,     **snake_case__			:   Dict     ):

     """simple docstring"""






     if text is None and images is None:
      raise ValueError('You have to specify either text or images. Both cannot be none.'     )

     if text is not None:
      SCREAMING_SNAKE_CASE		    =      self.tokenizer(snake_case__				,     return_tensors=snake_case__				,     **snake_case__     )

     if images is not None:
      SCREAMING_SNAKE_CASE		    =      self.image_processor(snake_case__				,     return_tensors=snake_case__				,     **snake_case__     )

     if text is not None and images is not None:
      SCREAMING_SNAKE_CASE		    =      image_features.pixel_values
      return encoding
     elif text is not None:
      return encoding
     else:
      return BatchEncoding(data=dict(**snake_case__     )				,     tensor_type=snake_case__     )

    def UpperCamelCase      (      self			:   Union[str, Any]				,     *snake_case__			:   Optional[Any]				,     **snake_case__			:   Optional[int]     ):

     """simple docstring"""






     return self.tokenizer.batch_decode(*snake_case__				,     **snake_case__     )

    def UpperCamelCase      (      self			:   Dict				,     *snake_case__			:   Optional[Any]				,     **snake_case__			:   Dict     ):

     """simple docstring"""






     return self.tokenizer.decode(*snake_case__				,     **snake_case__     )

    @property
    def UpperCamelCase      (      self			:   Any     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.tokenizer.model_input_names
     SCREAMING_SNAKE_CASE		    =      self.image_processor.model_input_names
     return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names     )     )

    @property
    def UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     warnings.warn(
         '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'				,     snake_case__				,     )
     return self.image_processor_class




    @property
    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     warnings.warn(
         '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'				,     snake_case__				,     )
     return self.image_processor

