

"""simple docstring"""






import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


_lowerCAmelCase						=		get_tests_dir("""fixtures""")
_lowerCAmelCase						=		get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
_lowerCAmelCase						=		get_tests_dir("""fixtures/dummy-config.json""")







class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    0

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    AutoFeatureExtractor.from_pretrained('facebook/wav2vec2-base-960h'      )
      self.assertIsInstance(_A    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    AutoFeatureExtractor.from_pretrained(_A      )
      self.assertIsInstance(_A    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      with tempfile.TemporaryDirectory() as tmpdirname:
          _lowerCAmelCase       :   int  =    WavaVecaConfig()

          # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
          _lowerCAmelCase       :   Any  =    AutoFeatureExtractor.from_pretrained(_A      ).to_dict()

          config_dict.pop('feature_extractor_type'      )
          _lowerCAmelCase       :   str  =    WavaVecaFeatureExtractor(**_A      )

          # save in new folder
          model_config.save_pretrained(_A      )
          config.save_pretrained(_A      )

          _lowerCAmelCase       :   List[str]  =    AutoFeatureExtractor.from_pretrained(_A      )

          # make sure private variable is not incorrectly saved
          _lowerCAmelCase       :   Dict  =    json.loads(config.to_json_string()      )
          self.assertTrue('_processor_class' not in dict_as_saved      )

      self.assertIsInstance(_A    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    AutoFeatureExtractor.from_pretrained(_A      )
      self.assertIsInstance(_A    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      with self.assertRaisesRegex(
          _A    ,'bert-base is not a local folder and is not a valid model identifier'      ):
          _lowerCAmelCase       :   Union[str, Any]  =    AutoFeatureExtractor.from_pretrained('bert-base'      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      with self.assertRaisesRegex(
          _A    ,r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'      ):
          _lowerCAmelCase       :   Union[str, Any]  =    AutoFeatureExtractor.from_pretrained(_A    ,revision='aaaaaa'      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      with self.assertRaisesRegex(
          _A    ,'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'    ,):
          _lowerCAmelCase       :   str  =    AutoFeatureExtractor.from_pretrained('hf-internal-testing/config-no-model'      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      with self.assertRaises(_A      ):
          _lowerCAmelCase       :   List[Any]  =    AutoFeatureExtractor.from_pretrained(
              'hf-internal-testing/test_dynamic_feature_extractor'      )
      # If remote code is disabled, we can't load this config.
      with self.assertRaises(_A      ):
          _lowerCAmelCase       :   Optional[Any]  =    AutoFeatureExtractor.from_pretrained(
              'hf-internal-testing/test_dynamic_feature_extractor'    ,trust_remote_code=_A      )

      _lowerCAmelCase       :   Union[str, Any]  =    AutoFeatureExtractor.from_pretrained(
          'hf-internal-testing/test_dynamic_feature_extractor'    ,trust_remote_code=_A      )
      self.assertEqual(feature_extractor.__class__.__name__    ,'NewFeatureExtractor'      )

      # Test feature extractor can be reloaded.
      with tempfile.TemporaryDirectory() as tmp_dir:
          feature_extractor.save_pretrained(_A      )
          _lowerCAmelCase       :   str  =    AutoFeatureExtractor.from_pretrained(_A    ,trust_remote_code=_A      )
      self.assertEqual(reloaded_feature_extractor.__class__.__name__    ,'NewFeatureExtractor'      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      try:
          AutoConfig.register('custom'    ,_A      )
          AutoFeatureExtractor.register(_A    ,_A      )
          # Trying to register something existing in the Transformers library will raise an error
          with self.assertRaises(_A      ):
              AutoFeatureExtractor.register(_A    ,_A      )

          # Now that the config is registered, it can be used as any other config with the auto-API
          _lowerCAmelCase       :   Tuple  =    CustomFeatureExtractor.from_pretrained(_A      )
          with tempfile.TemporaryDirectory() as tmp_dir:
              feature_extractor.save_pretrained(_A      )
              _lowerCAmelCase       :   Union[str, Any]  =    AutoFeatureExtractor.from_pretrained(_A      )
              self.assertIsInstance(_A    ,_A      )

      finally:
          if "custom" in CONFIG_MAPPING._extra_content:
              del CONFIG_MAPPING._extra_content["custom"]
          if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
              del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      class 	__UpperCamelCase    (    a__						):
        _UpperCAmelCase          =		True

      try:
          AutoConfig.register('custom'    ,_A      )
          AutoFeatureExtractor.register(_A    ,_A      )
          # If remote code is not set, the default is to use local
          _lowerCAmelCase       :   Tuple  =    AutoFeatureExtractor.from_pretrained(
              'hf-internal-testing/test_dynamic_feature_extractor'      )
          self.assertEqual(feature_extractor.__class__.__name__    ,'NewFeatureExtractor'      )
          self.assertTrue(feature_extractor.is_local      )

          # If remote code is disabled, we load the local one.
          _lowerCAmelCase       :   Dict  =    AutoFeatureExtractor.from_pretrained(
              'hf-internal-testing/test_dynamic_feature_extractor'    ,trust_remote_code=_A      )
          self.assertEqual(feature_extractor.__class__.__name__    ,'NewFeatureExtractor'      )
          self.assertTrue(feature_extractor.is_local      )

          # If remote is enabled, we load from the Hub
          _lowerCAmelCase       :   Optional[int]  =    AutoFeatureExtractor.from_pretrained(
              'hf-internal-testing/test_dynamic_feature_extractor'    ,trust_remote_code=_A      )
          self.assertEqual(feature_extractor.__class__.__name__    ,'NewFeatureExtractor'      )
          self.assertTrue(not hasattr(_A    ,'is_local'      )      )

      finally:
          if "custom" in CONFIG_MAPPING._extra_content:
              del CONFIG_MAPPING._extra_content["custom"]
          if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
              del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]








"""simple docstring"""






# 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

_lowerCAmelCase						=		get_logger()

_lowerCAmelCase						=		None







class 	__UpperCamelCase    (    TensorFormatter[Mapping, "jax.Array", Mapping]						):

  def __init__(		self    ,_A=None    ,_A=None    ,**_A      ):
      '''simple docstring'''

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

      if isinstance(_A    ,_A      ):
          raise ValueError(
              F"""Expected {device} to be a `str` not {type(_A      )}, 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`.'      )
      _lowerCAmelCase       :   int  =    device if isinstance(_A    ,_A      ) 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:
          _lowerCAmelCase       :   Any  =    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]      )}."""      )
          _lowerCAmelCase       :   List[str]  =    str(jax.devices()[0]      )
      _lowerCAmelCase       :   int  =    jnp_array_kwargs

  @staticmethod
  def __lowerCamelCase		(		):
      '''simple docstring'''

      import jax

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

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      import jax
      import jax.numpy as jnp

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

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      import jax
      import jax.numpy as jnp

      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.tolist()

      _lowerCAmelCase       :   Optional[Any]  =    {}

      if isinstance(_A    ,(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:
              _lowerCAmelCase       :   List[str]  =    {'dtype': jnp.intaa}
          else:
              _lowerCAmelCase       :   Tuple  =    {'dtype': jnp.intaa}
      elif isinstance(_A    ,(np.number, np.ndarray)      ) and np.issubdtype(value.dtype    ,np.floating      ):
          _lowerCAmelCase       :   Any  =    {'dtype': jnp.floataa}
      elif config.PIL_AVAILABLE and "PIL" in sys.modules:
          import PIL.Image

          if isinstance(_A    ,PIL.Image.Image      ):
              _lowerCAmelCase       :   int  =    np.asarray(_A      )

        # 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:
          _lowerCAmelCase       :   Optional[Any]  =    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(_A    ,**{**default_dtype, **self.jnp_array_kwargs}      )

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      import jax

      # 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    ,jax.Array      ):
          _lowerCAmelCase       :   Optional[Any]  =    data_struct.__array__()
      # support for nested types like struct of list of struct
      if isinstance(_A    ,np.ndarray      ):
          if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
              return self._consolidate([self.recursive_tensorize(_A      ) for substruct in data_struct]      )
      elif isinstance(_A    ,(list, tuple)      ):
          return self._consolidate([self.recursive_tensorize(_A      ) for substruct in data_struct]      )
      return self._tensorize(_A      )

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

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

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self.numpy_arrow_extractor().extract_row(_A      )
      _lowerCAmelCase       :   int  =    self.python_features_decoder.decode_row(_A      )
      return self.recursive_tensorize(_A      )

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Dict  =    self.numpy_arrow_extractor().extract_column(_A      )
      _lowerCAmelCase       :   List[Any]  =    self.python_features_decoder.decode_column(_A    ,pa_table.column_names[0]      )
      _lowerCAmelCase       :   Optional[Any]  =    self.recursive_tensorize(_A      )
      _lowerCAmelCase       :   Optional[Any]  =    self._consolidate(_A      )
      return column







  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    self.numpy_arrow_extractor().extract_batch(_A      )
      _lowerCAmelCase       :   Any  =    self.python_features_decoder.decode_batch(_A      )
      _lowerCAmelCase       :   str  =    self.recursive_tensorize(_A      )
      for column_name in batch:
          _lowerCAmelCase       :   Optional[Any]  =    self._consolidate(batch[column_name]      )
      return batch





