






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




      """simple docstring"""




      def __init__( self			:		Tuple     ,      UpperCAmelCase			:		Optional[int]=None     ,      **UpperCAmelCase			:		List[str]		)  ->  int:


       '''simple docstring'''

       super().__init__(features=UpperCAmelCase		)
       lowercase					:   Tuple				  =torch_tensor_kwargs
       import torch  # noqa import torch at initialization






      def 				A__      ( self			:		int     ,      UpperCAmelCase			:		Optional[int]		)  ->  int:


       '''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 				A__      ( self			:		List[str]     ,      UpperCAmelCase			:		Union[str, Any]		)  ->  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()

       lowercase					:   Union[str, Any]				  ={}

       if isinstance(UpperCAmelCase     ,      (np.number, np.ndarray)		) and np.issubdtype(value.dtype     ,      np.integer		):
        lowercase					:   List[str]				  ={"dtype": torch.intaa}
       elif isinstance(UpperCAmelCase     ,      (np.number, np.ndarray)		) and np.issubdtype(value.dtype     ,      np.floating		):
        lowercase					:   Optional[Any]				  ={"dtype": torch.floataa}
       elif config.PIL_AVAILABLE and "PIL" in sys.modules:
        import PIL.Image

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






      def 				A__      ( self			:		List[Any]     ,      UpperCAmelCase			:		List[str]		)  ->  Optional[int]:


       '''simple docstring'''

       import torch

       # support for torch, tf, jax etc.
       if hasattr(UpperCAmelCase     ,      '''__array__'''		) and not isinstance(UpperCAmelCase     ,      torch.Tensor		):
        lowercase					:   List[str]				  =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 				A__      ( self			:		Tuple     ,      UpperCAmelCase			:		dict		)  ->  Dict:


       '''simple docstring'''

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






      def 				A__      ( self			:		List[str]     ,      UpperCAmelCase			:		pa.Table		)  ->  str:


       '''simple docstring'''

       lowercase					:   Dict				  =self.numpy_arrow_extractor().extract_row(UpperCAmelCase		)
       lowercase					:   Union[str, Any]				  =self.python_features_decoder.decode_row(UpperCAmelCase		)
       return self.recursive_tensorize(UpperCAmelCase		)






      def 				A__      ( self			:		Optional[int]     ,      UpperCAmelCase			:		pa.Table		)  ->  Optional[Any]:


       '''simple docstring'''

       lowercase					:   Optional[int]				  =self.numpy_arrow_extractor().extract_column(UpperCAmelCase		)
       lowercase					:   str				  =self.python_features_decoder.decode_column(UpperCAmelCase     ,      pa_table.column_names[0]		)
       lowercase					:   Optional[int]				  =self.recursive_tensorize(UpperCAmelCase		)
       lowercase					:   Tuple				  =self._consolidate(UpperCAmelCase		)
       return column






      def 				A__      ( self			:		Dict     ,      UpperCAmelCase			:		pa.Table		)  ->  Optional[Any]:


       '''simple docstring'''

       lowercase					:   Tuple				  =self.numpy_arrow_extractor().extract_batch(UpperCAmelCase		)
       lowercase					:   List[Any]				  =self.python_features_decoder.decode_batch(UpperCAmelCase		)
       lowercase					:   Any				  =self.recursive_tensorize(UpperCAmelCase		)
       for column_name in batch:
        lowercase					:   List[Any]				  =self._consolidate(batch[column_name]		)
       return batch











'''simple docstring'''



def 							lowercase_				(    __A :       int					,      __A :       int			)       ->      str:



 """simple docstring"""




 if number < 0 or shift_amount < 0:
  raise ValueError('''both inputs must be positive integers'''			)

 lowercase					:   List[Any]				  =str(bin(__A			)			)
 binary_number += "0" * shift_amount
 return binary_number


def 							lowercase_				(    __A :       int					,      __A :       int			)       ->      str:



 """simple docstring"""




 if number < 0 or shift_amount < 0:
  raise ValueError('''both inputs must be positive integers'''			)

 lowercase					:   Union[str, Any]				  =str(bin(__A			)			)[2:]
 if shift_amount >= len(__A			):
  return "0b0"
 lowercase					:   Any				  =binary_number[: len(__A			) - shift_amount]
 return "0b" + shifted_binary_number


def 							lowercase_				(    __A :       int					,      __A :       int			)       ->      str:



 """simple docstring"""




 if number >= 0:  # Get binary representation of positive number
  lowercase					:   str				  ='''0''' + str(bin(__A			)			).strip('''-'''			)[2:]
 else:  # Get binary (2's complement) representation of negative number
  lowercase					:   Dict				  =len(bin(__A			)[3:]			)  # Find 2's complement of number
  lowercase					:   Optional[Any]				  =bin(abs(__A			) - (1 << binary_number_length)			)[3:]
  lowercase					:   int				  =(
      '''1''' + '''0''' * (binary_number_length - len(__A			)) + binary_number
  )

 if shift_amount >= len(__A			):
  return "0b" + binary_number[0] * len(__A			)
 return (
     "0b"
     + binary_number[0] * shift_amount
     + binary_number[: len(__A			) - shift_amount]
 )


if __name__ == "__main__":
      import doctest

      doctest.testmod()



