


"""simple docstring"""



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


__snake_case   			=    get_tests_dir("""fixtures""")







class _lowerCAmelCase				(      unittest.TestCase	):







   def  lowerCamelCase		(	self						)	->		Optional[int]:

       '''simple docstring'''




       snake_case    :      Any      					=    mock.Mock()
       snake_case    :      Optional[int]      					=    500
       snake_case    :      Any      					=    {}
       snake_case    :      Optional[int]      					=    HTTPError
       snake_case    :      List[Any]      					=    {}

       # Download this model to make sure it's in the cache.
       snake_case    :      Tuple      					=    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=UpperCamelCase__						) as mock_head:
           snake_case    :      List[str]      					=    ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit"						)
           # This check we did call the fake head request
           mock_head.assert_called()







   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




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







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       with self.assertRaises(UpperCamelCase__						):
           # config is in subfolder, the following should not work without specifying the subfolder
           snake_case    :      List[str]      					=    AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants"						)

       snake_case    :      List[str]      					=    AutoImageProcessor.from_pretrained(
           "hf-internal-testing/stable-diffusion-all-variants"						,	subfolder="feature_extractor"						)

       self.assertIsNotNone(UpperCamelCase__						)







@is_staging_test
class _lowerCAmelCase				(      unittest.TestCase	):







   @classmethod
   def  lowerCamelCase		(	cls						)	->		Tuple:

       '''simple docstring'''




       snake_case    :      Tuple      					=    TOKEN
       HfFolder.save_token(UpperCamelCase__						)







   @classmethod
   def  lowerCamelCase		(	cls						)	->		str:

       '''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  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       snake_case    :      Tuple      					=    ViTImageProcessor.from_pretrained(UpperCamelCase__						)
       image_processor.push_to_hub("test-image-processor"						,	use_auth_token=self._token						)

       snake_case    :      Optional[Any]      					=    ViTImageProcessor.from_pretrained(F'{USER}/test-image-processor'						)
       for k, v in image_processor.__dict__.items():
           self.assertEqual(UpperCamelCase__						,	getattr(UpperCamelCase__						,	UpperCamelCase__						)						)

       # 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(
               UpperCamelCase__						,	repo_id="test-image-processor"						,	push_to_hub=UpperCamelCase__						,	use_auth_token=self._token						)

       snake_case    :      Tuple      					=    ViTImageProcessor.from_pretrained(F'{USER}/test-image-processor'						)
       for k, v in image_processor.__dict__.items():
           self.assertEqual(UpperCamelCase__						,	getattr(UpperCamelCase__						,	UpperCamelCase__						)						)







   def  lowerCamelCase		(	self						)	->		List[str]:

       '''simple docstring'''




       snake_case    :      int      					=    ViTImageProcessor.from_pretrained(UpperCamelCase__						)
       image_processor.push_to_hub("valid_org/test-image-processor"						,	use_auth_token=self._token						)

       snake_case    :      Any      					=    ViTImageProcessor.from_pretrained("valid_org/test-image-processor"						)
       for k, v in image_processor.__dict__.items():
           self.assertEqual(UpperCamelCase__						,	getattr(UpperCamelCase__						,	UpperCamelCase__						)						)

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

       snake_case    :      Any      					=    ViTImageProcessor.from_pretrained("valid_org/test-image-processor-org"						)
       for k, v in image_processor.__dict__.items():
           self.assertEqual(UpperCamelCase__						,	getattr(UpperCamelCase__						,	UpperCamelCase__						)						)







   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       CustomImageProcessor.register_for_auto_class()
       snake_case    :      Union[str, Any]      					=    CustomImageProcessor.from_pretrained(UpperCamelCase__						)

       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    :      Any      					=    AutoImageProcessor.from_pretrained(
           F'{USER}/test-dynamic-image-processor'						,	trust_remote_code=UpperCamelCase__						)
       # 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"						)









"""simple docstring"""



from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__snake_case   			=    logging.get_logger(__name__)

__snake_case   			=    {
    """facebook/xmod-base""": """https://huggingface.co/facebook/xmod-base/resolve/main/config.json""",
    """facebook/xmod-large-prenorm""": """https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json""",
    """facebook/xmod-base-13-125k""": """https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json""",
    """facebook/xmod-base-30-125k""": """https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json""",
    """facebook/xmod-base-30-195k""": """https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json""",
    """facebook/xmod-base-60-125k""": """https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json""",
    """facebook/xmod-base-60-265k""": """https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json""",
    """facebook/xmod-base-75-125k""": """https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json""",
    """facebook/xmod-base-75-269k""": """https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json""",
}







class _lowerCAmelCase				(      snake_case_	):
   __UpperCAmelCase :       Optional[Any]							  =  '''xmod'''







   def __init__(	self						,	UpperCamelCase__=3_0522						,	UpperCamelCase__=768						,	UpperCamelCase__=12						,	UpperCamelCase__=12						,	UpperCamelCase__=3072						,	UpperCamelCase__="gelu"						,	UpperCamelCase__=0.1						,	UpperCamelCase__=0.1						,	UpperCamelCase__=512						,	UpperCamelCase__=2						,	UpperCamelCase__=0.02						,	UpperCamelCase__=1e-12						,	UpperCamelCase__=1						,	UpperCamelCase__=0						,	UpperCamelCase__=2						,	UpperCamelCase__="absolute"						,	UpperCamelCase__=True						,	UpperCamelCase__=None						,	UpperCamelCase__=False						,	UpperCamelCase__=2						,	UpperCamelCase__=False						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__=("en_XX",)						,	UpperCamelCase__=None						,	**UpperCamelCase__						,	)	->		int:

       '''simple docstring'''




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

       snake_case    :      List[Any]      					=    vocab_size
       snake_case    :      List[Any]      					=    hidden_size
       snake_case    :      Union[str, Any]      					=    num_hidden_layers
       snake_case    :      Any      					=    num_attention_heads
       snake_case    :      List[str]      					=    hidden_act
       snake_case    :      Union[str, Any]      					=    intermediate_size
       snake_case    :      int      					=    hidden_dropout_prob
       snake_case    :      Any      					=    attention_probs_dropout_prob
       snake_case    :      Optional[int]      					=    max_position_embeddings
       snake_case    :      Tuple      					=    type_vocab_size
       snake_case    :      List[str]      					=    initializer_range
       snake_case    :      int      					=    layer_norm_eps
       snake_case    :      Optional[Any]      					=    position_embedding_type
       snake_case    :      int      					=    use_cache
       snake_case    :      Dict      					=    classifier_dropout
       snake_case    :      Dict      					=    pre_norm
       snake_case    :      Union[str, Any]      					=    adapter_reduction_factor
       snake_case    :      Any      					=    adapter_layer_norm
       snake_case    :      Optional[int]      					=    adapter_reuse_layer_norm
       snake_case    :      List[Any]      					=    ln_before_adapter
       snake_case    :      str      					=    list(UpperCamelCase__						)
       snake_case    :      int      					=    default_language







class _lowerCAmelCase				(      snake_case_	):







   @property
   def  lowerCamelCase		(	self						)	->		Mapping[str, Mapping[int, str]]:

       '''simple docstring'''




       if self.task == "multiple-choice":
           snake_case    :      Optional[int]      					=    {0: "batch", 1: "choice", 2: "sequence"}
       else:
           snake_case    :      Optional[Any]      					=    {0: "batch", 1: "sequence"}
       return OrderedDict(
           [
               ("input_ids", dynamic_axis),
               ("attention_mask", dynamic_axis),
           ]						)





