






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_				(      lowerCamelCase ):







				def __get__(						self       ,					__lowerCAmelCase       ,					__lowerCAmelCase=None     ):
								"""simple docstring"""
								# See docs.python.org/3/howto/descriptor.html#properties
								if obj is None:
												return self
								if self.fget is None:
												raise AttributeError('''unreadable attribute'''     )
								__magic_name__		:str        =      '''__cached_''' + self.fget.__name__
								__magic_name__		:Optional[int]        =      getattr(__lowerCAmelCase       ,					__lowerCAmelCase       ,					__lowerCAmelCase     )
								if cached is None:
												__magic_name__		:Dict        =      self.fget(__lowerCAmelCase     )
												setattr(__lowerCAmelCase       ,					__lowerCAmelCase       ,					__lowerCAmelCase     )
								return cached







def      __lowercase					( snake_case ):







				"""simple docstring"""






				__magic_name__		:List[Any]        =      val.lower()
				if val in {"y", "yes", "t", "true", "on", "1"}:
								return 1
				if val in {"n", "no", "f", "false", "off", "0"}:
								return 0
				raise ValueError(f'''invalid truth value {val!r}''' )

def      __lowercase					( snake_case ):







				"""simple docstring"""






				if is_torch_fx_proxy(snake_case ):
								return True
				if is_torch_available():
								import torch

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

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

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

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

				return isinstance(snake_case,  np.ndarray )

def      __lowercase					( snake_case ):







				"""simple docstring"""






				return isinstance(snake_case,  np.ndarray )

def      __lowercase					( snake_case ):







				"""simple docstring"""






				return _is_numpy(snake_case )

def      __lowercase					( snake_case ):







				"""simple docstring"""






				import torch

				return isinstance(snake_case,  torch.Tensor )

def      __lowercase					( snake_case ):







				"""simple docstring"""






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

def      __lowercase					( snake_case ):







				"""simple docstring"""






				import torch

				return isinstance(snake_case,  torch.device )

def      __lowercase					( snake_case ):







				"""simple docstring"""






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

def      __lowercase					( snake_case ):







				"""simple docstring"""






				import torch

				if isinstance(snake_case,  snake_case ):
								if hasattr(snake_case,  snake_case ):
												__magic_name__		:Optional[Any]        =      getattr(snake_case,  snake_case )
								else:
												return False
				return isinstance(snake_case,  torch.dtype )

def      __lowercase					( snake_case ):







				"""simple docstring"""






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

def      __lowercase					( snake_case ):







				"""simple docstring"""






				import tensorflow as tf

				return isinstance(snake_case,  tf.Tensor )

def      __lowercase					( snake_case ):







				"""simple docstring"""






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

def      __lowercase					( snake_case ):







				"""simple docstring"""






				import tensorflow as tf

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

def      __lowercase					( snake_case ):







				"""simple docstring"""






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

def      __lowercase					( snake_case ):







				"""simple docstring"""






				import jax.numpy as jnp  # noqa: F811

				return isinstance(snake_case,  jnp.ndarray )

def      __lowercase					( snake_case ):







				"""simple docstring"""






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

def      __lowercase					( snake_case ):







				"""simple docstring"""






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

def      __lowercase					( snake_case ):







				"""simple docstring"""






				if isinstance(snake_case,  (dict, UserDict) ):
								return {k: to_numpy(snake_case ) for k, v in obj.items()}
				elif isinstance(snake_case,  (list, tuple) ):
								return np.array(snake_case )
				elif is_tf_tensor(snake_case ):
								return obj.numpy()
				elif is_torch_tensor(snake_case ):
								return obj.detach().cpu().numpy()
				elif is_jax_tensor(snake_case ):
								return np.asarray(snake_case )
				else:
								return obj
class 						lowerCamelCase_				(      lowerCamelCase ):







				def 			A	(						self     ):
								"""simple docstring"""
								__magic_name__		:Tuple        =      fields(self     )

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

								__magic_name__		:List[Any]        =      getattr(self       ,					class_fields[0].name     )
								__magic_name__		:Any        =      all(getattr(self       ,					field.name     ) is None for field in class_fields[1:]     )

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







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







				def 			A	(						self       ,					*__lowerCAmelCase       ,					**__lowerCAmelCase     ):
								"""simple docstring"""
								raise Exception(F'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''     )







				def 			A	(						self       ,					*__lowerCAmelCase       ,					**__lowerCAmelCase     ):
								"""simple docstring"""
								raise Exception(F'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''     )







				def 			A	(						self       ,					*__lowerCAmelCase       ,					**__lowerCAmelCase     ):
								"""simple docstring"""
								raise Exception(F'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''     )







				def __getitem__(						self       ,					__lowerCAmelCase     ):
								"""simple docstring"""
								if isinstance(__lowerCAmelCase       ,					__lowerCAmelCase     ):
												__magic_name__		:List[Any]        =      dict(self.items()     )
												return inner_dict[k]
								else:
												return self.to_tuple()[k]







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







				def __setitem__(						self       ,					__lowerCAmelCase       ,					__lowerCAmelCase     ):
								"""simple docstring"""
								# Will raise a KeyException if needed
								super().__setitem__(__lowerCAmelCase       ,					__lowerCAmelCase     )
								# Don't call self.__setattr__ to avoid recursion errors
								super().__setattr__(__lowerCAmelCase       ,					__lowerCAmelCase     )







				def 			A	(						self     ):
								"""simple docstring"""
								return tuple(self[k] for k in self.keys()     )







class 						lowerCamelCase_				(      lowerCamelCase			,				lowerCamelCase ):







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







class 						lowerCamelCase_				(      lowerCamelCase ):
				a__					       =  '''longest'''
				a__					       =  '''max_length'''
				a__					       =  '''do_not_pad'''







class 						lowerCamelCase_				(      lowerCamelCase ):
				a__					       =  '''pt'''
				a__					       =  '''tf'''
				a__					       =  '''np'''
				a__					       =  '''jax'''







class 						lowerCamelCase_				:







				def __init__(						self       ,					__lowerCAmelCase     ):
								"""simple docstring"""
								__magic_name__		:int        =      context_managers
								__magic_name__		:str        =      ExitStack()







				def __enter__(						self     ):
								"""simple docstring"""
								for context_manager in self.context_managers:
												self.stack.enter_context(__lowerCAmelCase     )







				def __exit__(						self       ,					*__lowerCAmelCase       ,					**__lowerCAmelCase     ):
								"""simple docstring"""
								self.stack.__exit__(*__lowerCAmelCase       ,					**__lowerCAmelCase     )







def      __lowercase					( snake_case ):







				"""simple docstring"""






				__magic_name__		:Tuple        =      infer_framework(snake_case )
				if framework == "tf":
								__magic_name__		:Tuple        =      inspect.signature(model_class.call )  # TensorFlow models
				elif framework == "pt":
								__magic_name__		:int        =      inspect.signature(model_class.forward )  # PyTorch models
				else:
								__magic_name__		:Union[str, Any]        =      inspect.signature(model_class.__call__ )  # Flax models

				for p in signature.parameters:
								if p == "return_loss" and signature.parameters[p].default is True:
												return True

				return False

def      __lowercase					( snake_case ):







				"""simple docstring"""






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







				"""simple docstring"""






				def _flatten_dict(snake_case,  snake_case="",  snake_case="." ):
								for k, v in d.items():
												__magic_name__		:str        =      str(snake_case ) + delimiter + str(snake_case ) if parent_key else k
												if v and isinstance(snake_case,  snake_case ):
																yield from flatten_dict(snake_case,  snake_case,  delimiter=snake_case ).items()
												else:
																yield key, v

				return dict(_flatten_dict(snake_case,  snake_case,  snake_case ) )

@contextmanager
def      __lowercase					( snake_case,  snake_case = False ):







				"""simple docstring"""






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

def      __lowercase					( snake_case,  snake_case=None ):







				"""simple docstring"""






				if is_numpy_array(snake_case ):
								return np.transpose(snake_case,  axes=snake_case )
				elif is_torch_tensor(snake_case ):
								return array.T if axes is None else array.permute(*snake_case )
				elif is_tf_tensor(snake_case ):
								import tensorflow as tf

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

def      __lowercase					( snake_case,  snake_case ):







				"""simple docstring"""






				if is_numpy_array(snake_case ):
								return np.reshape(snake_case,  snake_case )
				elif is_torch_tensor(snake_case ):
								return array.reshape(*snake_case )
				elif is_tf_tensor(snake_case ):
								import tensorflow as tf

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

def      __lowercase					( snake_case,  snake_case=None ):







				"""simple docstring"""






				if is_numpy_array(snake_case ):
								return np.squeeze(snake_case,  axis=snake_case )
				elif is_torch_tensor(snake_case ):
								return array.squeeze() if axis is None else array.squeeze(dim=snake_case )
				elif is_tf_tensor(snake_case ):
								import tensorflow as tf

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

def      __lowercase					( snake_case,  snake_case ):







				"""simple docstring"""






				if is_numpy_array(snake_case ):
								return np.expand_dims(snake_case,  snake_case )
				elif is_torch_tensor(snake_case ):
								return array.unsqueeze(dim=snake_case )
				elif is_tf_tensor(snake_case ):
								import tensorflow as tf

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

def      __lowercase					( snake_case ):







				"""simple docstring"""






				if is_numpy_array(snake_case ):
								return np.size(snake_case )
				elif is_torch_tensor(snake_case ):
								return array.numel()
				elif is_tf_tensor(snake_case ):
								import tensorflow as tf

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

def      __lowercase					( snake_case,  snake_case ):







				"""simple docstring"""






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

				return auto_map

def      __lowercase					( snake_case ):







				"""simple docstring"""






				for base_class in inspect.getmro(snake_case ):
								__magic_name__		:Union[str, Any]        =      base_class.__module__
								__magic_name__		: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}.''' )














from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


SCREAMING_SNAKE_CASE__      :			Tuple							=		{
    """configuration_table_transformer""": [
        """TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """TableTransformerConfig""",
        """TableTransformerOnnxConfig""",
    ]
}

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__      :			List[str]							=		[
					    """TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
					    """TableTransformerForObjectDetection""",
					    """TableTransformerModel""",
					    """TableTransformerPreTrainedModel""",
					]


if TYPE_CHECKING:
					from .configuration_table_transformer import (
					    TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
					    TableTransformerConfig,
					    TableTransformerOnnxConfig,
					)

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_table_transformer import (
										    TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
										    TableTransformerForObjectDetection,
										    TableTransformerModel,
										    TableTransformerPreTrainedModel,
										)

else:
					import sys

					SCREAMING_SNAKE_CASE__      :			Union[str, Any]							=		_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)






