





# 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 torch







class 				__lowerCAmelCase       (    TensorFormatter[Mapping, """torch.Tensor""", Mapping]):







      def __init__(    self		,      lowerCAmelCase__=None		,      **lowerCAmelCase__							)   ->						List[Any]:



        '''simple docstring'''




        super().__init__(features=lowerCAmelCase__							)
        a__	:					List[str]										=torch_tensor_kwargs
        import torch  # noqa import torch at initialization







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						Union[str, Any]:



        '''simple docstring'''




        import torch

        if isinstance(lowerCAmelCase__		,      lowerCAmelCase__							) and column:
          if all(
              isinstance(lowerCAmelCase__		,      torch.Tensor							) and x.shape == column[0].shape and x.dtype == column[0].dtype
              for x in column							):
            return torch.stack(lowerCAmelCase__							)
        return column







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						List[Any]:



        '''simple docstring'''




        import torch

        if isinstance(lowerCAmelCase__		,      (str, bytes, type(lowerCAmelCase__							))							):
          return value
        elif isinstance(lowerCAmelCase__		,      (np.character, np.ndarray)							) and np.issubdtype(value.dtype		,      np.character							):
          return value.tolist()

        a__	:					Optional[Any]										={}

        if isinstance(lowerCAmelCase__		,      (np.number, np.ndarray)							) and np.issubdtype(value.dtype		,      np.integer							):
          a__	:					Dict										={"dtype": torch.intaa}
        elif isinstance(lowerCAmelCase__		,      (np.number, np.ndarray)							) and np.issubdtype(value.dtype		,      np.floating							):
          a__	:					Dict										={"dtype": torch.floataa}
        elif config.PIL_AVAILABLE and "PIL" in sys.modules:
          import PIL.Image

          if isinstance(lowerCAmelCase__		,      PIL.Image.Image							):
            a__	:					Optional[int]										=np.asarray(lowerCAmelCase__							)
        return torch.tensor(lowerCAmelCase__		,      **{**default_dtype, **self.torch_tensor_kwargs}							)







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						int:



        '''simple docstring'''




        import torch

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







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						int:



        '''simple docstring'''




        return map_nested(self._recursive_tensorize		,      lowerCAmelCase__		,      map_list=lowerCAmelCase__							)







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						Mapping:



        '''simple docstring'''




        a__	:					List[Any]										=self.numpy_arrow_extractor().extract_row(lowerCAmelCase__							)
        a__	:					Tuple										=self.python_features_decoder.decode_row(lowerCAmelCase__							)
        return self.recursive_tensorize(lowerCAmelCase__							)







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						"torch.Tensor":



        '''simple docstring'''




        a__	:					Tuple										=self.numpy_arrow_extractor().extract_column(lowerCAmelCase__							)
        a__	:					Any										=self.python_features_decoder.decode_column(lowerCAmelCase__		,      pa_table.column_names[0]							)
        a__	:					Optional[int]										=self.recursive_tensorize(lowerCAmelCase__							)
        a__	:					int										=self._consolidate(lowerCAmelCase__							)
        return column







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						Mapping:



        '''simple docstring'''




        a__	:					str										=self.numpy_arrow_extractor().extract_batch(lowerCAmelCase__							)
        a__	:					List[str]										=self.python_features_decoder.decode_batch(lowerCAmelCase__							)
        a__	:					Optional[Any]										=self.recursive_tensorize(lowerCAmelCase__							)
        for column_name in batch:
          a__	:					List[Any]										=self._consolidate(batch[column_name]							)
        return batch













from typing import TYPE_CHECKING

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


UpperCAmelCase	:	Any		     =       {
    """configuration_convbert""": ["""CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConvBertConfig""", """ConvBertOnnxConfig"""],
    """tokenization_convbert""": ["""ConvBertTokenizer"""],
}

try:
     if not is_tokenizers_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCAmelCase	:	List[Any]		     =       ["""ConvBertTokenizerFast"""]

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCAmelCase	:	List[str]		     =       [
         """CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """ConvBertForMaskedLM""",
         """ConvBertForMultipleChoice""",
         """ConvBertForQuestionAnswering""",
         """ConvBertForSequenceClassification""",
         """ConvBertForTokenClassification""",
         """ConvBertLayer""",
         """ConvBertModel""",
         """ConvBertPreTrainedModel""",
         """load_tf_weights_in_convbert""",
     ]


try:
     if not is_tf_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCAmelCase	:	Union[str, Any]		     =       [
         """TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """TFConvBertForMaskedLM""",
         """TFConvBertForMultipleChoice""",
         """TFConvBertForQuestionAnswering""",
         """TFConvBertForSequenceClassification""",
         """TFConvBertForTokenClassification""",
         """TFConvBertLayer""",
         """TFConvBertModel""",
         """TFConvBertPreTrainedModel""",
     ]


if TYPE_CHECKING:
     from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig
     from .tokenization_convbert import ConvBertTokenizer

     try:
          if not is_tokenizers_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .tokenization_convbert_fast import ConvBertTokenizerFast

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_convbert import (
              CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
              ConvBertForMaskedLM,
              ConvBertForMultipleChoice,
              ConvBertForQuestionAnswering,
              ConvBertForSequenceClassification,
              ConvBertForTokenClassification,
              ConvBertLayer,
              ConvBertModel,
              ConvBertPreTrainedModel,
              load_tf_weights_in_convbert,
          )

     try:
          if not is_tf_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_tf_convbert import (
              TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
              TFConvBertForMaskedLM,
              TFConvBertForMultipleChoice,
              TFConvBertForQuestionAnswering,
              TFConvBertForSequenceClassification,
              TFConvBertForTokenClassification,
              TFConvBertLayer,
              TFConvBertModel,
              TFConvBertPreTrainedModel,
          )


else:
     import sys

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






