





# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
       import tensorflow as tf





class A_      (    TensorFormatter[Mapping, """tf.Tensor""", Mapping]     ):




   def __init__(self			:Union[str, Any]					,     _UpperCamelCase			:int=None					,     **_UpperCamelCase			:Union[str, Any]				)->      Optional[Any]:
         super().__init__(features=_UpperCamelCase				)
         __A      =       tf_tensor_kwargs
         import tensorflow as tf  # noqa: import tf at initialization




   def _lowerCAmelCase   (self			:int					,     _UpperCamelCase			:Union[str, Any]				)->      Optional[Any]:
         import tensorflow as tf

         if isinstance(_UpperCamelCase					,     _UpperCamelCase				) and column:
               if all(
                   isinstance(_UpperCamelCase					,     tf.Tensor				) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column				):
                     return tf.stack(_UpperCamelCase				)
               elif all(
                   isinstance(_UpperCamelCase					,     (tf.Tensor, tf.RaggedTensor)				) and x.ndim == 1 and x.dtype == column[0].dtype
                   for x in column				):
                     # only rag 1-D tensors, otherwise some dimensions become ragged even though they were consolidated
                     return tf.ragged.stack(_UpperCamelCase				)

         return column




   def _lowerCAmelCase   (self			:str					,     _UpperCamelCase			:Dict				)->      str:
         import tensorflow as tf

         if value is None:
               return value

         __A      =       {}

         if isinstance(_UpperCamelCase					,     (np.number, np.ndarray)				) and np.issubdtype(value.dtype					,     np.integer				):
               __A      =       {'''dtype''': tf.intaa}
         elif isinstance(_UpperCamelCase					,     (np.number, np.ndarray)				) and np.issubdtype(value.dtype					,     np.floating				):
               __A      =       {'''dtype''': tf.floataa}
         elif config.PIL_AVAILABLE and "PIL" in sys.modules:
               import PIL.Image

               if isinstance(_UpperCamelCase					,     PIL.Image.Image				):
                     __A      =       np.asarray(_UpperCamelCase				)

         return tf.convert_to_tensor(_UpperCamelCase					,     **{**default_dtype, **self.tf_tensor_kwargs}				)




   def _lowerCAmelCase   (self			:Any					,     _UpperCamelCase			:List[Any]				)->      int:
         import tensorflow as tf

         # support for torch, tf, jax etc.
         if config.TORCH_AVAILABLE and "torch" in sys.modules:
               import torch

               if isinstance(_UpperCamelCase					,     torch.Tensor				):
                     return self._tensorize(data_struct.detach().cpu().numpy()[()]				)
         if hasattr(_UpperCamelCase					,     '''__array__'''				) and not isinstance(_UpperCamelCase					,     tf.Tensor				):
               __A      =       data_struct.__array__()
         # support for nested types like struct of list of struct
         if isinstance(_UpperCamelCase					,     np.ndarray				):
               if data_struct.dtype == object:  # tf tensors cannot be instantied from an array of objects
                     return self._consolidate([self.recursive_tensorize(_UpperCamelCase				) for substruct in data_struct]				)
         elif isinstance(_UpperCamelCase					,     (list, tuple)				):
               return self._consolidate([self.recursive_tensorize(_UpperCamelCase				) for substruct in data_struct]				)
         return self._tensorize(_UpperCamelCase				)




   def _lowerCAmelCase   (self			:str					,     _UpperCamelCase			:dict				)->      List[Any]:
         return map_nested(self._recursive_tensorize					,     _UpperCamelCase					,     map_list=_UpperCamelCase				)




   def _lowerCAmelCase   (self			:Dict					,     _UpperCamelCase			:pa.Table				)->      Mapping:
         __A      =       self.numpy_arrow_extractor().extract_row(_UpperCamelCase				)
         __A      =       self.python_features_decoder.decode_row(_UpperCamelCase				)
         return self.recursive_tensorize(_UpperCamelCase				)




   def _lowerCAmelCase   (self			:Any					,     _UpperCamelCase			:pa.Table				)->      "tf.Tensor":
         __A      =       self.numpy_arrow_extractor().extract_column(_UpperCamelCase				)
         __A      =       self.python_features_decoder.decode_column(_UpperCamelCase					,     pa_table.column_names[0]				)
         __A      =       self.recursive_tensorize(_UpperCamelCase				)
         __A      =       self._consolidate(_UpperCamelCase				)
         return column






   def _lowerCAmelCase   (self			:Any					,     _UpperCamelCase			:pa.Table				)->      Mapping:
         __A      =       self.numpy_arrow_extractor().extract_batch(_UpperCamelCase				)
         __A      =       self.python_features_decoder.decode_batch(_UpperCamelCase				)
         __A      =       self.recursive_tensorize(_UpperCamelCase				)
         for column_name in batch:
               __A      =       self._consolidate(batch[column_name]				)
         return batch












from typing import TYPE_CHECKING

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


snake_case__      :							Optional[int]									=  {'configuration_cvt': ['CVT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CvtConfig']}


try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       snake_case__      :							Union[str, Any]									=  [
           'CVT_PRETRAINED_MODEL_ARCHIVE_LIST',
           'CvtForImageClassification',
           'CvtModel',
           'CvtPreTrainedModel',
       ]

try:
       if not is_tf_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       snake_case__      :							List[str]									=  [
           'TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST',
           'TFCvtForImageClassification',
           'TFCvtModel',
           'TFCvtPreTrainedModel',
       ]

if TYPE_CHECKING:
       from .configuration_cvt import CVT_PRETRAINED_CONFIG_ARCHIVE_MAP, CvtConfig

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_cvt import (
                  CVT_PRETRAINED_MODEL_ARCHIVE_LIST,
                  CvtForImageClassification,
                  CvtModel,
                  CvtPreTrainedModel,
              )

       try:
              if not is_tf_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_tf_cvt import (
                  TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST,
                  TFCvtForImageClassification,
                  TFCvtModel,
                  TFCvtPreTrainedModel,
              )


else:
       import sys

       snake_case__      :							Dict									=  _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)





