



import os
import sys
import unittest


__snake_case		:Union[str, Any]   	=  os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__snake_case		:List[str]   	=  os.path.join(git_repo_path, '''src''', '''transformers''')

__snake_case		:Any   	=  '''
{0} = None
'''

__snake_case		:Dict   	=  '''
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
'''


__snake_case		:str   	=  '''
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
'''

class 					_A (			unittest.TestCase					):



       def 	_lowerCamelCase    (	self							:  List[Any]):


           '''simple docstring'''

           __a		 =       find_backend('''    _import_structure["models.albert"].append("AlbertTokenizerFast")''')
           self.assertIsNone(__SCREAMING_SNAKE_CASE)

           __a		 =       find_backend('''    if not is_tokenizers_available():''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''tokenizers''')

           __a		 =       find_backend('''    if not is_tensorflow_text_available():''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''tensorflow_text''')

           __a		 =       find_backend('''    if not (is_sentencepiece_available() and is_tokenizers_available()):''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''sentencepiece_and_tokenizers''')

           __a		 =       find_backend(
               '''    if not (is_sentencepiece_available() and is_tensorflow_text_available()):''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''sentencepiece_and_tensorflow_text''')

           __a		 =       find_backend(
               '''    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''sentencepiece_and_tokenizers_and_vision''')



       def 	_lowerCamelCase    (	self							:  Optional[Any]):


           '''simple docstring'''

           __a		 =       read_init()
           # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
           self.assertIn('''torch'''  ,	__SCREAMING_SNAKE_CASE)
           self.assertIn('''tensorflow_text'''  ,	__SCREAMING_SNAKE_CASE)
           self.assertIn('''sentencepiece_and_tokenizers'''  ,	__SCREAMING_SNAKE_CASE)

           # Likewise, we can't assert on the exact content of a key
           self.assertIn('''BertModel'''  ,	objects['''torch'''])
           self.assertIn('''TFBertModel'''  ,	objects['''tf'''])
           self.assertIn('''FlaxBertModel'''  ,	objects['''flax'''])
           self.assertIn('''BertModel'''  ,	objects['''torch'''])
           self.assertIn('''TFBertTokenizer'''  ,	objects['''tensorflow_text'''])
           self.assertIn('''convert_slow_tokenizer'''  ,	objects['''sentencepiece_and_tokenizers'''])



       def 	_lowerCamelCase    (	self							:  Any):


           '''simple docstring'''

           __a		 =       create_dummy_object('''CONSTANT'''  ,	'''\'torch\'''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	'''\nCONSTANT = None\n''')

           __a		 =       create_dummy_object('''function'''  ,	'''\'torch\'''')
           self.assertEqual(
               __SCREAMING_SNAKE_CASE  ,	'''\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n''')

           __a		 =       '''
class FakeClass(metaclass=DummyObject):
    _backends = \'torch\'

    def __init__(self, *args, **kwargs):
        requires_backends(self, \'torch\')
'''
           __a		 =       create_dummy_object('''FakeClass'''  ,	'''\'torch\'''')
           self.assertEqual(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)





       def 	_lowerCamelCase    (	self							:  Optional[Any]):


           '''simple docstring'''

           __a		 =       '''# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, ["torch"])


class FakeClass(metaclass=DummyObject):
    _backends = ["torch"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, ["torch"])
'''
           __a		 =       create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']})
           self.assertEqual(dummy_files['''torch''']  ,	__SCREAMING_SNAKE_CASE)










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

import numpy as np
import pyarrow as pa

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


if TYPE_CHECKING:
 import jax
 import jaxlib

__snake_case		:str   	=  get_logger()

__snake_case		:Optional[dict]   	=  None

class 					_A (			TensorFormatter[Mapping, '''jax.Array''', Mapping]					):



       def __init__(	self							:  str  ,	__SCREAMING_SNAKE_CASE							:  int=None  ,	__SCREAMING_SNAKE_CASE							:  List[Any]=None  ,	**__SCREAMING_SNAKE_CASE							:  Any):


           '''simple docstring'''

           super().__init__(features=__SCREAMING_SNAKE_CASE)
           import jax
           from jaxlib.xla_client import Device

           if isinstance(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE):
               raise ValueError(
                   F'Expected {device} to be a `str` not {type(__SCREAMING_SNAKE_CASE)}, as `jaxlib.xla_extension.Device` '
                   '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround '''
                   '''the device with `str()` to get its string identifier that will be internally mapped '''
                   '''to the actual `jaxlib.xla_extension.Device`.''')
           __a		 =       device if isinstance(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE) else str(jax.devices()[0])
           # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
           # with `pickle` nor with `dill`, so we need to use a global variable instead
           global DEVICE_MAPPING
           if DEVICE_MAPPING is None:
               __a		 =       self._map_devices_to_str()
           if self.device not in list(DEVICE_MAPPING.keys()):
               logger.warning(
                   F'Device with string identifier {self.device} not listed among the available '
                   F'devices: {list(DEVICE_MAPPING.keys())}, so falling back to the default '
                   F'device: {str(jax.devices()[0])}.')
               __a		 =       str(jax.devices()[0])
           __a		 =       jnp_array_kwargs



       @staticmethod
       def 	_lowerCamelCase    (	):


           '''simple docstring'''

           import jax

           return {str(__SCREAMING_SNAKE_CASE): device for device in jax.devices()}



       def 	_lowerCamelCase    (	self							:  Union[str, Any]  ,	__SCREAMING_SNAKE_CASE							:  Tuple):


           '''simple docstring'''

           import jax
           import jax.numpy as jnp

           if isinstance(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE) and column:
               if all(
                   isinstance(__SCREAMING_SNAKE_CASE  ,	jax.Array) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column):
                   return jnp.stack(__SCREAMING_SNAKE_CASE  ,	axis=0)
           return column



       def 	_lowerCamelCase    (	self							:  str  ,	__SCREAMING_SNAKE_CASE							:  str):


           '''simple docstring'''

           import jax
           import jax.numpy as jnp

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

           __a		 =       {}

           if isinstance(__SCREAMING_SNAKE_CASE  ,	(np.number, np.ndarray)) and np.issubdtype(value.dtype  ,	np.integer):
               # the default int precision depends on the jax config
               # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
               if jax.config.jax_enable_xaa:
                   __a		 =       {'''dtype''': jnp.intaa}
               else:
                   __a		 =       {'''dtype''': jnp.intaa}
           elif isinstance(__SCREAMING_SNAKE_CASE  ,	(np.number, np.ndarray)) and np.issubdtype(value.dtype  ,	np.floating):
               __a		 =       {'''dtype''': jnp.floataa}
           elif config.PIL_AVAILABLE and "PIL" in sys.modules:
               import PIL.Image

               if isinstance(__SCREAMING_SNAKE_CASE  ,	PIL.Image.Image):
                   __a		 =       np.asarray(__SCREAMING_SNAKE_CASE)

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
           global DEVICE_MAPPING
           if DEVICE_MAPPING is None:
               __a		 =       self._map_devices_to_str()

           with jax.default_device(DEVICE_MAPPING[self.device]):
               # calling jnp.array on a np.ndarray does copy the data
               # see https://github.com/google/jax/issues/4486
               return jnp.array(__SCREAMING_SNAKE_CASE  ,	**{**default_dtype, **self.jnp_array_kwargs})



       def 	_lowerCamelCase    (	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  str):


           '''simple docstring'''

           import jax

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

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



       def 	_lowerCamelCase    (	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  dict):


           '''simple docstring'''

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



       def 	_lowerCamelCase    (	self							:  str  ,	__SCREAMING_SNAKE_CASE							:  pa.Table):


           '''simple docstring'''

           __a		 =       self.numpy_arrow_extractor().extract_row(__SCREAMING_SNAKE_CASE)
           __a		 =       self.python_features_decoder.decode_row(__SCREAMING_SNAKE_CASE)
           return self.recursive_tensorize(__SCREAMING_SNAKE_CASE)



       def 	_lowerCamelCase    (	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  pa.Table):


           '''simple docstring'''

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





       def 	_lowerCamelCase    (	self							:  Union[str, Any]  ,	__SCREAMING_SNAKE_CASE							:  pa.Table):


           '''simple docstring'''

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





