

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


__A     						=      {
    '''configuration_align''': [
        '''ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''AlignConfig''',
        '''AlignTextConfig''',
        '''AlignVisionConfig''',
    ],
    '''processing_align''': ['''AlignProcessor'''],
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __A     						=      [
     '''ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''AlignModel''',
     '''AlignPreTrainedModel''',
     '''AlignTextModel''',
     '''AlignVisionModel''',
 ]

if TYPE_CHECKING:
 from .configuration_align import (
     ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP,
     AlignConfig,
     AlignTextConfig,
     AlignVisionConfig,
 )
 from .processing_align import AlignProcessor

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_align import (
      ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST,
      AlignModel,
      AlignPreTrainedModel,
      AlignTextModel,
      AlignVisionModel,
  )

else:
 import sys

 __A     						=      _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)




import sys
from collections.abc import Mapping

import numpy as np
import pyarrow as pa

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



class     lowercase_       (    TensorFormatter[Mapping, np.ndarray, Mapping]	):



      def __init__(     self :							Union[str, Any]     ,   A__ :							Dict=None     ,   **A__ :							str						)       ->	Any:
        super().__init__(features=A__						)
        _snake_case		=				np_array_kwargs



      def 		UpperCamelCase_						(     self :							str     ,   A__ :							Dict						)       ->	Dict:
        if isinstance(A__     ,   A__						):
          if column and all(
              isinstance(A__     ,   np.ndarray						) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column						):
            return np.stack(A__						)
          else:
            # don't use np.array(column, dtype=object)
            # since it fails in certain cases
            # see https://stackoverflow.com/q/51005699
            _snake_case		=				np.empty(len(A__						)     ,   dtype=A__						)
            _snake_case		=				column
            return out
        return column



      def 		UpperCamelCase_						(     self :							Tuple     ,   A__ :							Optional[int]						)       ->	Optional[Any]:
        if isinstance(A__     ,   (str, bytes, type(A__						))						):
          return value
        elif isinstance(A__     ,   (np.character, np.ndarray)						) and np.issubdtype(value.dtype     ,   np.character						):
          return value
        elif isinstance(A__     ,   np.number						):
          return value

        _snake_case		=				{}

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

          if isinstance(A__     ,   PIL.Image.Image						):
            return np.asarray(A__     ,   **self.np_array_kwargs						)

        return np.asarray(A__     ,   **{**default_dtype, **self.np_array_kwargs}						)



      def 		UpperCamelCase_						(     self :							Union[str, Any]     ,   A__ :							Union[str, Any]						)       ->	int:
        # support for torch, tf, jax etc.
        if config.TORCH_AVAILABLE and "torch" in sys.modules:
          import torch

          if isinstance(A__     ,   torch.Tensor						):
            return self._tensorize(data_struct.detach().cpu().numpy()[()]						)
        if hasattr(A__     ,   '''__array__'''						) and not isinstance(A__     ,   (np.ndarray, np.character, np.number)						):
          _snake_case		=				data_struct.__array__()
        # support for nested types like struct of list of struct
        if isinstance(A__     ,   np.ndarray						):
          if data_struct.dtype == object:
            return self._consolidate([self.recursive_tensorize(A__						) for substruct in data_struct]						)
        if isinstance(A__     ,   (list, tuple)						):
          return self._consolidate([self.recursive_tensorize(A__						) for substruct in data_struct]						)
        return self._tensorize(A__						)



      def 		UpperCamelCase_						(     self :							List[Any]     ,   A__ :							dict						)       ->	Tuple:
        return map_nested(self._recursive_tensorize     ,   A__     ,   map_list=A__						)



      def 		UpperCamelCase_						(     self :							str     ,   A__ :							pa.Table						)       ->	Mapping:
        _snake_case		=				self.numpy_arrow_extractor().extract_row(A__						)
        _snake_case		=				self.python_features_decoder.decode_row(A__						)
        return self.recursive_tensorize(A__						)



      def 		UpperCamelCase_						(     self :							Optional[Any]     ,   A__ :							pa.Table						)       ->	np.ndarray:
        _snake_case		=				self.numpy_arrow_extractor().extract_column(A__						)
        _snake_case		=				self.python_features_decoder.decode_column(A__     ,   pa_table.column_names[0]						)
        _snake_case		=				self.recursive_tensorize(A__						)
        _snake_case		=				self._consolidate(A__						)
        return column







      def 		UpperCamelCase_						(     self :							Dict     ,   A__ :							pa.Table						)       ->	Mapping:
        _snake_case		=				self.numpy_arrow_extractor().extract_batch(A__						)
        _snake_case		=				self.python_features_decoder.decode_batch(A__						)
        _snake_case		=				self.recursive_tensorize(A__						)
        for column_name in batch:
          _snake_case		=				self._consolidate(batch[column_name]						)
        return batch

