





import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


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

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


_A					:    Any   =  get_tests_dir('fixtures')


class    __SCREAMING_SNAKE_CASE			( unittest.TestCase					):







       def 						__lowerCamelCase    (      self     :	Tuple			)   ->int:
          # A mock response for an HTTP head request to emulate server down
          lowerCamelCase__   :						Optional[int]					   =							mock.Mock()
          lowerCamelCase__   :						Any					   =							5_0_0
          lowerCamelCase__   :						str					   =							{}
          lowerCamelCase__   :						Any					   =							HTTPError
          lowerCamelCase__   :						List[str]					   =							{}

          # Download this model to make sure it's in the cache.
          lowerCamelCase__   :						Union[str, Any]					   =							WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2'''			)
          # Under the mock environment we get a 500 error when trying to reach the model.
          with mock.patch('''requests.Session.request'''		,					return_value=_UpperCamelCase			) as mock_head:
             lowerCamelCase__   :						Tuple					   =							WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2'''			)
             # This check we did call the fake head request
             mock_head.assert_called()







       def 						__lowerCamelCase    (      self     :	Dict			)   ->Tuple:
          # This test is for deprecated behavior and can be removed in v5
          lowerCamelCase__   :						int					   =							WavaVecaFeatureExtractor.from_pretrained(
              '''https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json'''			)


@is_staging_test
class    __SCREAMING_SNAKE_CASE			( unittest.TestCase					):







       @classmethod
       def 						__lowerCamelCase    (      cls     :	Optional[Any]			)   ->Tuple:
          lowerCamelCase__   :						Any					   =							TOKEN
          HfFolder.save_token(_UpperCamelCase			)







       @classmethod
       def 						__lowerCamelCase    (      cls     :	List[str]			)   ->Optional[int]:
          try:
             delete_repo(token=cls._token		,					repo_id='''test-feature-extractor'''			)
          except HTTPError:
             pass

          try:
             delete_repo(token=cls._token		,					repo_id='''valid_org/test-feature-extractor-org'''			)
          except HTTPError:
             pass

          try:
             delete_repo(token=cls._token		,					repo_id='''test-dynamic-feature-extractor'''			)
          except HTTPError:
             pass







       def 						__lowerCamelCase    (      self     :	Any			)   ->Optional[Any]:
          lowerCamelCase__   :						Any					   =							WavaVecaFeatureExtractor.from_pretrained(_UpperCamelCase			)
          feature_extractor.push_to_hub('''test-feature-extractor'''		,					use_auth_token=self._token			)

          lowerCamelCase__   :						List[Any]					   =							WavaVecaFeatureExtractor.from_pretrained(F"{USER}/test-feature-extractor"			)
          for k, v in feature_extractor.__dict__.items():
             self.assertEqual(_UpperCamelCase		,					getattr(_UpperCamelCase		,					_UpperCamelCase			)			)

          # Reset repo
          delete_repo(token=self._token		,					repo_id='''test-feature-extractor'''			)

          # Push to hub via save_pretrained
          with tempfile.TemporaryDirectory() as tmp_dir:
             feature_extractor.save_pretrained(
                 _UpperCamelCase		,					repo_id='''test-feature-extractor'''		,					push_to_hub=_UpperCamelCase		,					use_auth_token=self._token			)

          lowerCamelCase__   :						Optional[Any]					   =							WavaVecaFeatureExtractor.from_pretrained(F"{USER}/test-feature-extractor"			)
          for k, v in feature_extractor.__dict__.items():
             self.assertEqual(_UpperCamelCase		,					getattr(_UpperCamelCase		,					_UpperCamelCase			)			)







       def 						__lowerCamelCase    (      self     :	Union[str, Any]			)   ->Optional[int]:
          lowerCamelCase__   :						Union[str, Any]					   =							WavaVecaFeatureExtractor.from_pretrained(_UpperCamelCase			)
          feature_extractor.push_to_hub('''valid_org/test-feature-extractor'''		,					use_auth_token=self._token			)

          lowerCamelCase__   :						Dict					   =							WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor'''			)
          for k, v in feature_extractor.__dict__.items():
             self.assertEqual(_UpperCamelCase		,					getattr(_UpperCamelCase		,					_UpperCamelCase			)			)

          # Reset repo
          delete_repo(token=self._token		,					repo_id='''valid_org/test-feature-extractor'''			)

          # Push to hub via save_pretrained
          with tempfile.TemporaryDirectory() as tmp_dir:
             feature_extractor.save_pretrained(
                 _UpperCamelCase		,					repo_id='''valid_org/test-feature-extractor-org'''		,					push_to_hub=_UpperCamelCase		,					use_auth_token=self._token			)

          lowerCamelCase__   :						List[str]					   =							WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor-org'''			)
          for k, v in feature_extractor.__dict__.items():
             self.assertEqual(_UpperCamelCase		,					getattr(_UpperCamelCase		,					_UpperCamelCase			)			)







       def 						__lowerCamelCase    (      self     :	Tuple			)   ->int:
          CustomFeatureExtractor.register_for_auto_class()
          lowerCamelCase__   :						Optional[int]					   =							CustomFeatureExtractor.from_pretrained(_UpperCamelCase			)

          feature_extractor.push_to_hub('''test-dynamic-feature-extractor'''		,					use_auth_token=self._token			)

          # This has added the proper auto_map field to the config
          self.assertDictEqual(
              feature_extractor.auto_map		,					{'''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor'''}		,					)

          lowerCamelCase__   :						List[Any]					   =							AutoFeatureExtractor.from_pretrained(
              F"{USER}/test-dynamic-feature-extractor"		,					trust_remote_code=_UpperCamelCase			)
          # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
          self.assertEqual(new_feature_extractor.__class__.__name__		,					'''CustomFeatureExtractor'''			)











__UpperCAmelCase								=						{
    'Pillow': 'Pillow<10.0.0',
    'accelerate': 'accelerate>=0.20.3',
    'av': 'av==9.2.0',
    'beautifulsoup4': 'beautifulsoup4',
    'black': 'black~=23.1',
    'codecarbon': 'codecarbon==1.2.0',
    'cookiecutter': 'cookiecutter==1.7.3',
    'dataclasses': 'dataclasses',
    'datasets': 'datasets!=2.5.0',
    'decord': 'decord==0.6.0',
    'deepspeed': 'deepspeed>=0.9.3',
    'diffusers': 'diffusers',
    'dill': 'dill<0.3.5',
    'evaluate': 'evaluate>=0.2.0',
    'fairscale': 'fairscale>0.3',
    'faiss-cpu': 'faiss-cpu',
    'fastapi': 'fastapi',
    'filelock': 'filelock',
    'flax': 'flax>=0.4.1,<=0.7.0',
    'ftfy': 'ftfy',
    'fugashi': 'fugashi>=1.0',
    'GitPython': 'GitPython<3.1.19',
    'hf-doc-builder': 'hf-doc-builder>=0.3.0',
    'huggingface-hub': 'huggingface-hub>=0.14.1,<1.0',
    'importlib_metadata': 'importlib_metadata',
    'ipadic': 'ipadic>=1.0.0,<2.0',
    'isort': 'isort>=5.5.4',
    'jax': 'jax>=0.2.8,!=0.3.2,<=0.4.13',
    'jaxlib': 'jaxlib>=0.1.65,<=0.4.13',
    'jieba': 'jieba',
    'kenlm': 'kenlm',
    'keras-nlp': 'keras-nlp>=0.3.1',
    'librosa': 'librosa',
    'nltk': 'nltk',
    'natten': 'natten>=0.14.6',
    'numpy': 'numpy>=1.17',
    'onnxconverter-common': 'onnxconverter-common',
    'onnxruntime-tools': 'onnxruntime-tools>=1.4.2',
    'onnxruntime': 'onnxruntime>=1.4.0',
    'opencv-python': 'opencv-python',
    'optuna': 'optuna',
    'optax': 'optax>=0.0.8,<=0.1.4',
    'packaging': 'packaging>=20.0',
    'parameterized': 'parameterized',
    'phonemizer': 'phonemizer',
    'protobuf': 'protobuf',
    'psutil': 'psutil',
    'pyyaml': 'pyyaml>=5.1',
    'pydantic': 'pydantic<2',
    'pytest': 'pytest>=7.2.0',
    'pytest-timeout': 'pytest-timeout',
    'pytest-xdist': 'pytest-xdist',
    'python': 'python>=3.8.0',
    'ray[tune]': 'ray[tune]',
    'regex': 'regex!=2019.12.17',
    'requests': 'requests',
    'rhoknp': 'rhoknp>=1.1.0,<1.3.1',
    'rjieba': 'rjieba',
    'rouge-score': 'rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1',
    'ruff': 'ruff>=0.0.241,<=0.0.259',
    'sacrebleu': 'sacrebleu>=1.4.12,<2.0.0',
    'sacremoses': 'sacremoses',
    'safetensors': 'safetensors>=0.3.1',
    'sagemaker': 'sagemaker>=2.31.0',
    'scikit-learn': 'scikit-learn',
    'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92',
    'sigopt': 'sigopt',
    'starlette': 'starlette',
    'sudachipy': 'sudachipy>=0.6.6',
    'sudachidict_core': 'sudachidict_core>=20220729',
    'tensorflow-cpu': 'tensorflow-cpu>=2.6,<2.14',
    'tensorflow': 'tensorflow>=2.6,<2.14',
    'tensorflow-text': 'tensorflow-text<2.14',
    'tf2onnx': 'tf2onnx',
    'timeout-decorator': 'timeout-decorator',
    'timm': 'timm',
    'tokenizers': 'tokenizers>=0.11.1,!=0.11.3,<0.14',
    'torch': 'torch>=1.9,!=1.12.0',
    'torchaudio': 'torchaudio',
    'torchvision': 'torchvision',
    'pyctcdecode': 'pyctcdecode>=0.4.0',
    'tqdm': 'tqdm>=4.27',
    'unidic': 'unidic>=1.0.2',
    'unidic_lite': 'unidic_lite>=1.0.7',
    'urllib3': 'urllib3<2.0.0',
    'uvicorn': 'uvicorn',
}






