



"""simple docstring"""





# 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 				lowercase__       (   TensorFormatter[Mapping, '''torch.Tensor''', Mapping]				):







       '''simple docstring'''


       def __init__(							self      :  Optional[Any]		,    _UpperCAmelCase      :  Union[str, Any]=None		,    **_UpperCAmelCase      :  Tuple   )			->						Any:


             '''simple docstring'''




             super().__init__(features=_UpperCAmelCase   )
             UpperCAmelCase_      			=							torch_tensor_kwargs
             import torch  # noqa import torch at initialization



       def 					lowercase__    (							self      :  str		,    _UpperCAmelCase      :  List[str]   )			->						Dict:


             '''simple docstring'''




             import torch

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



       def 					lowercase__    (							self      :  str		,    _UpperCAmelCase      :  List[str]   )			->						Tuple:


             '''simple docstring'''




             import torch

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

             UpperCAmelCase_      			=							{}

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

                   if isinstance(_UpperCAmelCase		,    PIL.Image.Image   ):
                         UpperCAmelCase_      			=							np.asarray(_UpperCAmelCase   )
             return torch.tensor(_UpperCAmelCase		,    **{**default_dtype, **self.torch_tensor_kwargs}   )



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  Any   )			->						int:


             '''simple docstring'''




             import torch

             # support for torch, tf, jax etc.
             if hasattr(_UpperCAmelCase		,    "__array__"   ) and not isinstance(_UpperCAmelCase		,    torch.Tensor   ):
                   UpperCAmelCase_      			=							data_struct.__array__()
             # support for nested types like struct of list of struct
             if isinstance(_UpperCAmelCase		,    np.ndarray   ):
                   if data_struct.dtype == object:  # torch 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 					lowercase__    (							self      :  Dict		,    _UpperCAmelCase      :  dict   )			->						Union[str, Any]:


             '''simple docstring'''




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



       def 					lowercase__    (							self      :  str		,    _UpperCAmelCase      :  pa.Table   )			->						Mapping:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.numpy_arrow_extractor().extract_row(_UpperCAmelCase   )
             UpperCAmelCase_      			=							self.python_features_decoder.decode_row(_UpperCAmelCase   )
             return self.recursive_tensorize(_UpperCAmelCase   )



       def 					lowercase__    (							self      :  Optional[int]		,    _UpperCAmelCase      :  pa.Table   )			->						"torch.Tensor":


             '''simple docstring'''




             UpperCAmelCase_      			=							self.numpy_arrow_extractor().extract_column(_UpperCAmelCase   )
             UpperCAmelCase_      			=							self.python_features_decoder.decode_column(_UpperCAmelCase		,    pa_table.column_names[0]   )
             UpperCAmelCase_      			=							self.recursive_tensorize(_UpperCAmelCase   )
             UpperCAmelCase_      			=							self._consolidate(_UpperCAmelCase   )
             return column







       def 					lowercase__    (							self      :  List[str]		,    _UpperCAmelCase      :  pa.Table   )			->						Mapping:


             '''simple docstring'''




             UpperCAmelCase_      			=							self.numpy_arrow_extractor().extract_batch(_UpperCAmelCase   )
             UpperCAmelCase_      			=							self.python_features_decoder.decode_batch(_UpperCAmelCase   )
             UpperCAmelCase_      			=							self.recursive_tensorize(_UpperCAmelCase   )
             for column_name in batch:
                   UpperCAmelCase_      			=							self._consolidate(batch[column_name]   )
             return batch









"""simple docstring"""





# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


lowerCamelCase       	=						{
    """configuration_mgp_str""": ["""MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MgpstrConfig"""],
    """processing_mgp_str""": ["""MgpstrProcessor"""],
    """tokenization_mgp_str""": ["""MgpstrTokenizer"""],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowerCamelCase       	=						[
      """MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """MgpstrModel""",
      """MgpstrPreTrainedModel""",
      """MgpstrForSceneTextRecognition""",
  ]

if TYPE_CHECKING:
  from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig
  from .processing_mgp_str import MgpstrProcessor
  from .tokenization_mgp_str import MgpstrTokenizer

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_mgp_str import (
        MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST,
        MgpstrForSceneTextRecognition,
        MgpstrModel,
        MgpstrPreTrainedModel,
    )
else:
  import sys

  lowerCamelCase       	=						_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




