



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_						:     Tuple	     =		get_tests_dir('fixtures')





class    lowerCamelCase__  (						unittest.TestCase):
     """simple docstring"""



     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		mock.Mock()
           lowerCamelCase								=		5_00
           lowerCamelCase								=		{}
           lowerCamelCase								=		HTTPError
           lowerCamelCase								=		{}

           # Download this model to make sure it's in the cache.
           lowerCamelCase								=		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=__a    ) as mock_head:
                 lowerCamelCase								=		WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2"    )
                 # This check we did call the fake head request
                 mock_head.assert_called()







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		WavaVecaFeatureExtractor.from_pretrained(
               "https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json"    )





@is_staging_test
class    lowerCamelCase__  (						unittest.TestCase):
     """simple docstring"""



     @classmethod
     def 						_a      (cls    ):






           '''simple docstring'''



           lowerCamelCase								=		TOKEN
           HfFolder.save_token(__a    )







     @classmethod
     def 						_a      (cls    ):






           '''simple docstring'''



           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 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		WavaVecaFeatureExtractor.from_pretrained(__a    )
           feature_extractor.push_to_hub("test-feature-extractor"				,			use_auth_token=self._token    )

           lowerCamelCase								=		WavaVecaFeatureExtractor.from_pretrained(F"""{USER}/test-feature-extractor"""    )
           for k, v in feature_extractor.__dict__.items():
                 self.assertEqual(__a				,			getattr(__a				,			__a    )    )

           # 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(
                     __a				,			repo_id="test-feature-extractor"				,			push_to_hub=__a				,			use_auth_token=self._token    )

           lowerCamelCase								=		WavaVecaFeatureExtractor.from_pretrained(F"""{USER}/test-feature-extractor"""    )
           for k, v in feature_extractor.__dict__.items():
                 self.assertEqual(__a				,			getattr(__a				,			__a    )    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		WavaVecaFeatureExtractor.from_pretrained(__a    )
           feature_extractor.push_to_hub("valid_org/test-feature-extractor"				,			use_auth_token=self._token    )

           lowerCamelCase								=		WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor"    )
           for k, v in feature_extractor.__dict__.items():
                 self.assertEqual(__a				,			getattr(__a				,			__a    )    )

           # 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(
                     __a				,			repo_id="valid_org/test-feature-extractor-org"				,			push_to_hub=__a				,			use_auth_token=self._token    )

           lowerCamelCase								=		WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org"    )
           for k, v in feature_extractor.__dict__.items():
                 self.assertEqual(__a				,			getattr(__a				,			__a    )    )







     def 						_a      (self    ):






           '''simple docstring'''



           CustomFeatureExtractor.register_for_auto_class()
           lowerCamelCase								=		CustomFeatureExtractor.from_pretrained(__a    )

           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								=		AutoFeatureExtractor.from_pretrained(
               F"""{USER}/test-dynamic-feature-extractor"""				,			trust_remote_code=__a    )
           # 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"    )




from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import MagicMock, patch

from transformers import AutoModel, TFAutoModel
from transformers.onnx import FeaturesManager
from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch





@require_torch
@require_tf
class    lowerCamelCase__  (						UpperCAmelCase_):
     """simple docstring"""



     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		SMALL_MODEL_IDENTIFIER
           lowerCamelCase								=		"pt"
           lowerCamelCase								=		"tf"







     def 						_a      (self				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		AutoModel.from_pretrained(self.test_model    )
           model_pt.save_pretrained(__a    )







     def 						_a      (self				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		TFAutoModel.from_pretrained(self.test_model				,			from_pt=__a    )
           model_tf.save_pretrained(__a    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"mock_framework"

           # Framework provided - return whatever the user provides
           lowerCamelCase								=		FeaturesManager.determine_framework(self.test_model				,			__a    )
           self.assertEqual(__a				,			__a    )

           # Local checkpoint and framework provided - return provided framework
           # PyTorch checkpoint
           with TemporaryDirectory() as local_pt_ckpt:
                 self._setup_pt_ckpt(__a    )
                 lowerCamelCase								=		FeaturesManager.determine_framework(__a				,			__a    )
                 self.assertEqual(__a				,			__a    )

           # TensorFlow checkpoint
           with TemporaryDirectory() as local_tf_ckpt:
                 self._setup_tf_ckpt(__a    )
                 lowerCamelCase								=		FeaturesManager.determine_framework(__a				,			__a    )
                 self.assertEqual(__a				,			__a    )







     def 						_a      (self    ):






           '''simple docstring'''



           with TemporaryDirectory() as local_pt_ckpt:
                 self._setup_pt_ckpt(__a    )
                 lowerCamelCase								=		FeaturesManager.determine_framework(__a    )
                 self.assertEqual(__a				,			self.framework_pt    )

           # TensorFlow checkpoint
           with TemporaryDirectory() as local_tf_ckpt:
                 self._setup_tf_ckpt(__a    )
                 lowerCamelCase								=		FeaturesManager.determine_framework(__a    )
                 self.assertEqual(__a				,			self.framework_tf    )

           # Invalid local checkpoint
           with TemporaryDirectory() as local_invalid_ckpt:
                 with self.assertRaises(__a    ):
                       lowerCamelCase								=		FeaturesManager.determine_framework(__a    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		MagicMock(return_value=__a    )
           with patch("transformers.onnx.features.is_tf_available"				,			__a    ):
                 lowerCamelCase								=		FeaturesManager.determine_framework(self.test_model    )
                 self.assertEqual(__a				,			self.framework_pt    )

           # PyTorch not in environment -> use TensorFlow
           lowerCamelCase								=		MagicMock(return_value=__a    )
           with patch("transformers.onnx.features.is_torch_available"				,			__a    ):
                 lowerCamelCase								=		FeaturesManager.determine_framework(self.test_model    )
                 self.assertEqual(__a				,			self.framework_tf    )

           # Both in environment -> use PyTorch
           lowerCamelCase								=		MagicMock(return_value=__a    )
           lowerCamelCase								=		MagicMock(return_value=__a    )
           with patch("transformers.onnx.features.is_tf_available"				,			__a    ), patch(
               "transformers.onnx.features.is_torch_available"				,			__a    ):
                 lowerCamelCase								=		FeaturesManager.determine_framework(self.test_model    )
                 self.assertEqual(__a				,			self.framework_pt    )

           # Both not in environment -> raise error
           lowerCamelCase								=		MagicMock(return_value=__a    )
           lowerCamelCase								=		MagicMock(return_value=__a    )
           with patch("transformers.onnx.features.is_tf_available"				,			__a    ), patch(
               "transformers.onnx.features.is_torch_available"				,			__a    ):
                 with self.assertRaises(__a    ):
                       lowerCamelCase								=		FeaturesManager.determine_framework(self.test_model    )