
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 AutoImageProcessor, ViTImageProcessor
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_image_processing import CustomImageProcessor  # noqa E402


_lowerCamelCase	:    Optional[int]          =      get_tests_dir('''fixtures''')




class        SCREAMING_SNAKE_CASE__					(     unittest.TestCase ):





	'''simple docstring'''



	def 			A							(  self     :   Tuple     ):


				'''simple docstring'''


				_snake_case          =      mock.Mock()
				_snake_case          =      500
				_snake_case          =      {}
				_snake_case          =      HTTPError
				_snake_case          =      {}

				# Download this model to make sure it's in the cache.
				_snake_case          =      ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'     )
				# Under the mock environment we get a 500 error when trying to reach the model.
				with mock.patch('requests.Session.request'      ,  return_value=lowercase     ) as mock_head:
							_snake_case          =      ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'     )
							# This check we did call the fake head request
							mock_head.assert_called()



	def 			A							(  self     :   List[str]     ):


				'''simple docstring'''


				_snake_case          =      ViTImageProcessor.from_pretrained(
				    'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'     )





	def 			A							(  self     :   str     ):


				'''simple docstring'''


				with self.assertRaises(lowercase     ):
							# config is in subfolder, the following should not work without specifying the subfolder
							_snake_case          =      AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants'     )

				_snake_case          =      AutoImageProcessor.from_pretrained(
				    'hf-internal-testing/stable-diffusion-all-variants'      ,  subfolder='feature_extractor'     )

				self.assertIsNotNone(lowercase     )




@is_staging_test
class        SCREAMING_SNAKE_CASE__					(     unittest.TestCase ):





	'''simple docstring'''



	@classmethod
	def 			A							(  cls     :   int     ):


				'''simple docstring'''


				_snake_case          =      TOKEN
				HfFolder.save_token(lowercase     )



	@classmethod
	def 			A							(  cls     :   Optional[Any]     ):


				'''simple docstring'''


				try:
							delete_repo(token=cls._token      ,  repo_id='test-image-processor'     )
				except HTTPError:
							pass

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

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



	def 			A							(  self     :   Dict     ):


				'''simple docstring'''


				_snake_case          =      ViTImageProcessor.from_pretrained(lowercase     )
				image_processor.push_to_hub('test-image-processor'      ,  use_auth_token=self._token     )

				_snake_case          =      ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor'''     )
				for k, v in image_processor.__dict__.items():
							self.assertEqual(lowercase      ,  getattr(lowercase      ,  lowercase     )     )

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

				# Push to hub via save_pretrained
				with tempfile.TemporaryDirectory() as tmp_dir:
							image_processor.save_pretrained(
							    lowercase      ,  repo_id='test-image-processor'      ,  push_to_hub=lowercase      ,  use_auth_token=self._token     )

				_snake_case          =      ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor'''     )
				for k, v in image_processor.__dict__.items():
							self.assertEqual(lowercase      ,  getattr(lowercase      ,  lowercase     )     )



	def 			A							(  self     :   int     ):


				'''simple docstring'''


				_snake_case          =      ViTImageProcessor.from_pretrained(lowercase     )
				image_processor.push_to_hub('valid_org/test-image-processor'      ,  use_auth_token=self._token     )

				_snake_case          =      ViTImageProcessor.from_pretrained('valid_org/test-image-processor'     )
				for k, v in image_processor.__dict__.items():
							self.assertEqual(lowercase      ,  getattr(lowercase      ,  lowercase     )     )

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

				# Push to hub via save_pretrained
				with tempfile.TemporaryDirectory() as tmp_dir:
							image_processor.save_pretrained(
							    lowercase      ,  repo_id='valid_org/test-image-processor-org'      ,  push_to_hub=lowercase      ,  use_auth_token=self._token     )

				_snake_case          =      ViTImageProcessor.from_pretrained('valid_org/test-image-processor-org'     )
				for k, v in image_processor.__dict__.items():
							self.assertEqual(lowercase      ,  getattr(lowercase      ,  lowercase     )     )





	def 			A							(  self     :   Any     ):


				'''simple docstring'''


				CustomImageProcessor.register_for_auto_class()
				_snake_case          =      CustomImageProcessor.from_pretrained(lowercase     )

				image_processor.push_to_hub('test-dynamic-image-processor'      ,  use_auth_token=self._token     )

				# This has added the proper auto_map field to the config
				self.assertDictEqual(
				    image_processor.auto_map      ,  {'AutoImageProcessor': 'custom_image_processing.CustomImageProcessor'}      ,  )

				_snake_case          =      AutoImageProcessor.from_pretrained(
				    f'''{USER}/test-dynamic-image-processor'''      ,  trust_remote_code=lowercase     )
				# Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
				self.assertEqual(new_image_processor.__class__.__name__      ,  'CustomImageProcessor'     )

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCamelCase	:    Tuple          =      logging.get_logger(__name__)

_lowerCamelCase	:    Union[str, Any]          =      {
    '''google/canine-s''': '''https://huggingface.co/google/canine-s/resolve/main/config.json''',
    # See all CANINE models at https://huggingface.co/models?filter=canine
}




class        SCREAMING_SNAKE_CASE__					(     UpperCAmelCase ):





	'''simple docstring'''



	_UpperCAmelCase	:		Any          = "canine"



	def __init__(  self     :   int      ,  lowercase     :   Optional[int]=768      ,  lowercase     :   Tuple=12      ,  lowercase     :   Union[str, Any]=12      ,  lowercase     :   Optional[int]=3_072      ,  lowercase     :   Tuple="gelu"      ,  lowercase     :   Optional[Any]=0.1      ,  lowercase     :   Tuple=0.1      ,  lowercase     :   int=16_384      ,  lowercase     :   Optional[int]=16      ,  lowercase     :   Optional[int]=0.02      ,  lowercase     :   Optional[Any]=1E-12      ,  lowercase     :   Optional[Any]=0      ,  lowercase     :   Dict=0xE000      ,  lowercase     :   Optional[Any]=0xE001      ,  lowercase     :   Union[str, Any]=4      ,  lowercase     :   str=4      ,  lowercase     :   Optional[int]=8      ,  lowercase     :   List[str]=16_384      ,  lowercase     :   Union[str, Any]=128      ,  **lowercase     :   Optional[Any]      ,  ):


				'''simple docstring'''


				super().__init__(pad_token_id=lowercase      ,  bos_token_id=lowercase      ,  eos_token_id=lowercase      ,  **lowercase     )

				_snake_case          =      max_position_embeddings
				_snake_case          =      hidden_size
				_snake_case          =      num_hidden_layers
				_snake_case          =      num_attention_heads
				_snake_case          =      intermediate_size
				_snake_case          =      hidden_act
				_snake_case          =      hidden_dropout_prob
				_snake_case          =      attention_probs_dropout_prob
				_snake_case          =      initializer_range
				_snake_case          =      type_vocab_size
				_snake_case          =      layer_norm_eps

				# Character config:
				_snake_case          =      downsampling_rate
				_snake_case          =      upsampling_kernel_size
				_snake_case          =      num_hash_functions
				_snake_case          =      num_hash_buckets
				_snake_case          =      local_transformer_stride