



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"    )




import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding





class    lowerCamelCase__  (						UpperCAmelCase_):
     """simple docstring"""



     _A       =			['image_processor', 'tokenizer']
     _A       =			'CLIPImageProcessor'
     _A       =			('CLIPTokenizer', 'CLIPTokenizerFast')







     def __init__(self				,			__a=None				,			__a=None				,			**__a    ):






           '''simple docstring'''



           lowerCamelCase								=		None
           if "feature_extractor" in kwargs:
                 warnings.warn(
                     "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
                     " instead."				,			__a				,			)
                 lowerCamelCase								=		kwargs.pop("feature_extractor"    )

           lowerCamelCase								=		image_processor if image_processor is not None else feature_extractor
           if image_processor is None:
                 raise ValueError("You need to specify an `image_processor`."    )
           if tokenizer is None:
                 raise ValueError("You need to specify a `tokenizer`."    )

           super().__init__(__a				,			__a    )







     def __call__(self				,			__a=None				,			__a=None				,			__a=None				,			**__a    ):






           '''simple docstring'''



           if text is None and images is None:
                 raise ValueError("You have to specify either text or images. Both cannot be none."    )

           if text is not None:
                 lowerCamelCase								=		self.tokenizer(__a				,			return_tensors=__a				,			**__a    )

           if images is not None:
                 lowerCamelCase								=		self.image_processor(__a				,			return_tensors=__a				,			**__a    )

           if text is not None and images is not None:
                 lowerCamelCase								=		image_features.pixel_values
                 return encoding
           elif text is not None:
                 return encoding
           else:
                 return BatchEncoding(data=dict(**__a    )				,			tensor_type=__a    )







     def 						_a      (self				,			*__a				,			**__a    ):






           '''simple docstring'''



           return self.tokenizer.batch_decode(*__a				,			**__a    )







     def 						_a      (self				,			*__a				,			**__a    ):






           '''simple docstring'''



           return self.tokenizer.decode(*__a				,			**__a    )







     @property
     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.tokenizer.model_input_names
           lowerCamelCase								=		self.image_processor.model_input_names
           return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names    )    )







     @property
     def 						_a      (self    ):






           '''simple docstring'''



           warnings.warn(
               "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."				,			__a				,			)
           return self.image_processor_class







     @property
     def 						_a      (self    ):






           '''simple docstring'''



           warnings.warn(
               "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."				,			__a				,			)
           return self.image_processor