




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 __snake_case			(			a		):







   def __get__(      self		:						List[str]					,						_snake_case		:						Union[str, Any]					,						_snake_case		:						int=None):

        """simple docstring"""


        if obj is None:
             return self
        if self.fget is None:
             raise AttributeError('''unreadable attribute''')
        UpperCAmelCase_          =							'''__cached_''' + self.fget.__name__
        UpperCAmelCase_          =							getattr(_snake_case					,						_snake_case					,						_snake_case)
        if cached is None:
             UpperCAmelCase_          =							self.fget(_snake_case)
             setattr(_snake_case					,						_snake_case					,						_snake_case)
        return cached







def    A						(__A   :    Tuple       )   ->      str:







     """simple docstring"""


     UpperCAmelCase_          =							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    A						(__A   :    Tuple       )   ->      str:







     """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    A						(__A   :    str       )   ->      Dict:







     """simple docstring"""


     return isinstance(__A   ,				np.ndarray       )


def    A						(__A   :    Dict       )   ->      Any:







     """simple docstring"""


     return _is_numpy(__A       )


def    A						(__A   :    Union[str, Any]       )   ->      int:







     """simple docstring"""


     import torch

     return isinstance(__A   ,				torch.Tensor       )


def    A						(__A   :    Any       )   ->      List[str]:







     """simple docstring"""


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


def    A						(__A   :    Optional[int]       )   ->      List[str]:







     """simple docstring"""


     import torch

     return isinstance(__A   ,				torch.device       )


def    A						(__A   :    Union[str, Any]       )   ->      Any:







     """simple docstring"""


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


def    A						(__A   :    Union[str, Any]       )   ->      Tuple:







     """simple docstring"""


     import torch

     if isinstance(__A   ,				__A       ):
          if hasattr(__A   ,				__A       ):
               UpperCAmelCase_          =							getattr(__A   ,				__A       )
          else:
               return False
     return isinstance(__A   ,				torch.dtype       )


def    A						(__A   :    Optional[Any]       )   ->      Tuple:







     """simple docstring"""


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


def    A						(__A   :    Union[str, Any]       )   ->      List[Any]:







     """simple docstring"""


     import tensorflow as tf

     return isinstance(__A   ,				tf.Tensor       )


def    A						(__A   :    Tuple       )   ->      int:







     """simple docstring"""


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


def    A						(__A   :    Tuple       )   ->      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    A						(__A   :    Union[str, Any]       )   ->      Union[str, Any]:







     """simple docstring"""


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


def    A						(__A   :    Optional[Any]       )   ->      str:







     """simple docstring"""


     import jax.numpy as jnp  # noqa: F811

     return isinstance(__A   ,				jnp.ndarray       )


def    A						(__A   :    int       )   ->      Optional[Any]:







     """simple docstring"""


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


def    A						(__A   :    List[str]       )   ->      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    A						(__A   :    Dict       )   ->      List[Any]:







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







   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


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







   def __delitem__(      self		:						Tuple					,						*_snake_case		:						str					,						**_snake_case		:						Dict):

        """simple docstring"""


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







   def lowerCamelCase						(      self		:						int					,						*_snake_case		:						Optional[int]					,						**_snake_case		:						Dict):

        """simple docstring"""


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







   def lowerCamelCase						(      self		:						Dict					,						*_snake_case		:						Optional[int]					,						**_snake_case		:						Optional[int]):

        """simple docstring"""


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







   def lowerCamelCase						(      self		:						Optional[int]					,						*_snake_case		:						int					,						**_snake_case		:						Optional[Any]):

        """simple docstring"""


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







   def __getitem__(      self		:						Any					,						_snake_case		:						Optional[int]):

        """simple docstring"""


        if isinstance(_snake_case					,						_snake_case):
             UpperCAmelCase_          =							dict(self.items())
             return inner_dict[k]
        else:
             return self.to_tuple()[k]







   def __setattr__(      self		:						List[Any]					,						_snake_case		:						List[Any]					,						_snake_case		:						List[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		:						Dict					,						_snake_case		:						Optional[Any]					,						_snake_case		:						List[str]):

        """simple docstring"""


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







   def lowerCamelCase						(      self		:						Dict):

        """simple docstring"""


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







class __snake_case			(			a ,  a		):







   @classmethod
   def lowerCamelCase						(      cls		:						List[Any]					,						_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 __snake_case			(			a		):
   UpperCAmelCase__  :    Tuple          =  '''longest'''
   UpperCAmelCase__  :    Dict          =  '''max_length'''
   UpperCAmelCase__  :    List[Any]          =  '''do_not_pad'''







class __snake_case			(			a		):
   UpperCAmelCase__  :    str          =  '''pt'''
   UpperCAmelCase__  :    List[str]          =  '''tf'''
   UpperCAmelCase__  :    List[str]          =  '''np'''
   UpperCAmelCase__  :    Optional[Any]          =  '''jax'''







class __snake_case			:







   def __init__(      self		:						List[str]					,						_snake_case		:						List[ContextManager]):

        """simple docstring"""


        UpperCAmelCase_          =							context_managers
        UpperCAmelCase_          =							ExitStack()







   def __enter__(      self		:						str):

        """simple docstring"""


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







   def __exit__(      self		:						int					,						*_snake_case		:						List[str]					,						**_snake_case		:						Optional[Any]):

        """simple docstring"""


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







def    A						(__A   :    List[Any]       )   ->      str:







     """simple docstring"""


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







     """simple docstring"""


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







     """simple docstring"""


     def _flatten_dict(__A   :    Optional[Any]   ,				__A   :    int=""   ,				__A   :    Any="."       ):
          for k, v in d.items():
               UpperCAmelCase_          =							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    A						(__A   :    Dict   ,				__A   :    bool = False       )   ->      str:







     """simple docstring"""


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


def    A						(__A   :    List[str]   ,				__A   :    Optional[int]=None       )   ->      Any:







     """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    A						(__A   :    str   ,				__A   :    List[Any]       )   ->      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    A						(__A   :    List[str]   ,				__A   :    Dict=None       )   ->      int:







     """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    A						(__A   :    str   ,				__A   :    Dict       )   ->      List[str]:







     """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    A						(__A   :    List[str]       )   ->      Optional[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    A						(__A   :    int   ,				__A   :    Dict       )   ->      Dict:







     """simple docstring"""


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

     return auto_map


def    A						(__A   :    List[str]       )   ->      List[str]:







     """simple docstring"""


     for base_class in inspect.getmro(__A       ):
          UpperCAmelCase_          =							base_class.__module__
          UpperCAmelCase_          =							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 typing import List, Optional, Union

from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType







class __snake_case			(			a		):
   UpperCAmelCase__  :    Dict          =  ['''image_processor''', '''tokenizer''']
   UpperCAmelCase__  :    Dict          =  '''FlavaImageProcessor'''
   UpperCAmelCase__  :    Dict          =  ('''BertTokenizer''', '''BertTokenizerFast''')







   def __init__(      self		:						Union[str, Any]					,						_snake_case		:						List[str]=None					,						_snake_case		:						str=None					,						**_snake_case		:						int):

        """simple docstring"""


        UpperCAmelCase_          =							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					,						)
             UpperCAmelCase_          =							kwargs.pop('''feature_extractor''')

        UpperCAmelCase_          =							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)
        UpperCAmelCase_          =							self.image_processor







   def __call__(      self		:						List[Any]					,						_snake_case		:						Optional[ImageInput] = None					,						_snake_case		:						Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None					,						_snake_case		:						bool = True					,						_snake_case		:						Union[bool, str, PaddingStrategy] = False					,						_snake_case		:						Union[bool, str, TruncationStrategy] = False					,						_snake_case		:						Optional[int] = None					,						_snake_case		:						int = 0					,						_snake_case		:						Optional[int] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = True					,						_snake_case		:						Optional[Union[str, TensorType]] = None					,						**_snake_case		:						Any					,						):

        """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:
             UpperCAmelCase_          =							self.tokenizer(
                 text=_snake_case					,						add_special_tokens=_snake_case					,						padding=_snake_case					,						truncation=_snake_case					,						max_length=_snake_case					,						stride=_snake_case					,						pad_to_multiple_of=_snake_case					,						return_token_type_ids=_snake_case					,						return_attention_mask=_snake_case					,						return_overflowing_tokens=_snake_case					,						return_special_tokens_mask=_snake_case					,						return_offsets_mapping=_snake_case					,						return_length=_snake_case					,						verbose=_snake_case					,						return_tensors=_snake_case					,						**_snake_case					,						)
        if images is not None:
             UpperCAmelCase_          =							self.image_processor(
                 _snake_case					,						return_image_mask=_snake_case					,						return_codebook_pixels=_snake_case					,						return_tensors=_snake_case					,						**_snake_case					,						)

        if text is not None and images is not None:
             encoding.update(_snake_case)
             return encoding
        elif text is not None:
             return encoding
        else:
             return BatchEncoding(data=dict(**_snake_case)					,						tensor_type=_snake_case)







   def lowerCamelCase						(      self		:						Any					,						*_snake_case		:						Optional[Any]					,						**_snake_case		:						int):

        """simple docstring"""


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







   def lowerCamelCase						(      self		:						Optional[int]					,						*_snake_case		:						int					,						**_snake_case		:						Dict):

        """simple docstring"""


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







   @property
   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


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







   @property
   def lowerCamelCase						(      self		:						str):

        """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 lowerCamelCase						(      self		:						Any):

        """simple docstring"""


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






