



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


_lowerCAmelCase       :Tuple	=   get_tests_dir('fixtures')
class 				_UpperCAmelCase				(					unittest.TestCase ):





     '''simple docstring'''



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

         # Download this model to make sure it's in the cache.
         _UpperCAmelCase				:    List[str]											=       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=lowerCAmelCase_						) as mock_head:
             _UpperCAmelCase				:    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						)				->   Tuple:
         # This test is for deprecated behavior and can be removed in v5
         _UpperCAmelCase				:    Any											=       ViTImageProcessor.from_pretrained(
             '''https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'''						)





     def 					__lowerCAmelCase      (   self						)				->   int:
         with self.assertRaises(lowerCAmelCase_						):
             # config is in subfolder, the following should not work without specifying the subfolder
             _UpperCAmelCase				:    str											=       AutoImageProcessor.from_pretrained('''hf-internal-testing/stable-diffusion-all-variants'''						)

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

         self.assertIsNotNone(lowerCAmelCase_						)



@is_staging_test
class 				_UpperCAmelCase				(					unittest.TestCase ):





     '''simple docstring'''



     @classmethod
     def 					__lowerCAmelCase      (   cls						)				->   Tuple:
         _UpperCAmelCase				:    Any											=       TOKEN
         HfFolder.save_token(lowerCAmelCase_						)





     @classmethod
     def 					__lowerCAmelCase      (   cls						)				->   int:
         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						)				->   str:
         _UpperCAmelCase				:    List[Any]											=       ViTImageProcessor.from_pretrained(lowerCAmelCase_						)
         image_processor.push_to_hub('''test-image-processor'''			,      use_auth_token=self._token						)

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

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

         _UpperCAmelCase				:    List[Any]											=       ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor'						)
         for k, v in image_processor.__dict__.items():
             self.assertEqual(lowerCAmelCase_			,      getattr(lowerCAmelCase_			,      lowerCAmelCase_						)						)





     def 					__lowerCAmelCase      (   self						)				->   Any:
         _UpperCAmelCase				:    List[Any]											=       ViTImageProcessor.from_pretrained(lowerCAmelCase_						)
         image_processor.push_to_hub('''valid_org/test-image-processor'''			,      use_auth_token=self._token						)

         _UpperCAmelCase				:    Union[str, Any]											=       ViTImageProcessor.from_pretrained('''valid_org/test-image-processor'''						)
         for k, v in image_processor.__dict__.items():
             self.assertEqual(lowerCAmelCase_			,      getattr(lowerCAmelCase_			,      lowerCAmelCase_						)						)

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

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





     def 					__lowerCAmelCase      (   self						)				->   List[Any]:
         CustomImageProcessor.register_for_auto_class()
         _UpperCAmelCase				:    Dict											=       CustomImageProcessor.from_pretrained(lowerCAmelCase_						)

         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'''}			,      )

         _UpperCAmelCase				:    Optional[int]											=       AutoImageProcessor.from_pretrained(
             f'{USER}/test-dynamic-image-processor'			,      trust_remote_code=lowerCAmelCase_						)
         # 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"""
import copy
from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


if TYPE_CHECKING:
			from ... import PreTrainedTokenizerBase, TensorType

lowerCamelCase_							      = logging.get_logger(__name__)







class      UpperCamelCase_			(__A	):
	__magic_name__       =							'''vision-encoder-decoder'''
	__magic_name__       =							True





	def __init__( self   :					Union[str, Any]      ,      **lowerCAmelCase_   :					List[Any]		)		->     Union[str, Any]:
				super().__init__(**lowerCAmelCase_		)
				if "encoder" not in kwargs or "decoder" not in kwargs:
							raise ValueError(
							    f"""A configuraton of type {self.model_type} cannot be instantiated because """
							    f"""not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}"""		)

				UpperCAmelCase_	:					str     	=   kwargs.pop("encoder"		)
				UpperCAmelCase_	:					Dict     	=   encoder_config.pop("model_type"		)
				UpperCAmelCase_	:					List[Any]     	=   kwargs.pop("decoder"		)
				UpperCAmelCase_	:					Dict     	=   decoder_config.pop("model_type"		)

				UpperCAmelCase_	:					Union[str, Any]     	=   AutoConfig.for_model(lowerCAmelCase_      ,      **lowerCAmelCase_		)
				UpperCAmelCase_	:					List[str]     	=   AutoConfig.for_model(lowerCAmelCase_      ,      **lowerCAmelCase_		)
				UpperCAmelCase_	:					Tuple     	=   True





	@classmethod
	def 	_SCREAMING_SNAKE_CASE ( cls   :					List[str]      ,      lowerCAmelCase_   :					PretrainedConfig      ,      lowerCAmelCase_   :					PretrainedConfig      ,      **lowerCAmelCase_   :					Dict		)		->     PretrainedConfig:
				logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config"		)
				UpperCAmelCase_	:					Tuple     	=   True
				UpperCAmelCase_	:					str     	=   True

				return cls(encoder=encoder_config.to_dict()      ,      decoder=decoder_config.to_dict()      ,      **lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     List[Any]:
				UpperCAmelCase_	:					Union[str, Any]     	=   copy.deepcopy(self.__dict__		)
				UpperCAmelCase_	:					List[str]     	=   self.encoder.to_dict()
				UpperCAmelCase_	:					List[Any]     	=   self.decoder.to_dict()
				UpperCAmelCase_	:					Any     	=   self.__class__.model_type
				return output







class      UpperCamelCase_			(__A	):
	__magic_name__       =							version.parse('''1.11'''	)





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]		)		->     Mapping[str, Mapping[int, str]]:
				return OrderedDict(
				    [
				        ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
				    ]		)





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     float:
				return 1e-4





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					Any		)		->     Mapping[str, Mapping[int, str]]:
				return OrderedDict({"last_hidden_state": {0: "batch", 1: "encoder_sequence"}}		)







class      UpperCamelCase_			(__A	):





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     Mapping[str, Mapping[int, str]]:
				UpperCAmelCase_	:					List[Any]     	=   OrderedDict()
				UpperCAmelCase_	:					int     	=   {0: "batch", 1: "past_decoder_sequence + sequence"}
				UpperCAmelCase_	:					Dict     	=   {0: "batch", 1: "past_decoder_sequence + sequence"}
				UpperCAmelCase_	:					Union[str, Any]     	=   {0: "batch", 1: "encoder_sequence"}

				return common_inputs





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[Any]      ,      lowerCAmelCase_   :					"PreTrainedTokenizerBase"      ,      lowerCAmelCase_   :					int = -1      ,      lowerCAmelCase_   :					int = -1      ,      lowerCAmelCase_   :					bool = False      ,      lowerCAmelCase_   :					Optional["TensorType"] = None      ,      )		->     Mapping[str, Any]:
				import torch

				UpperCAmelCase_	:					Optional[int]     	=   OrderedDict()

				UpperCAmelCase_	:					Any     	=   super().generate_dummy_inputs(
				    lowerCAmelCase_      ,      batch_size=lowerCAmelCase_      ,      seq_length=lowerCAmelCase_      ,      is_pair=lowerCAmelCase_      ,      framework=lowerCAmelCase_		)

				UpperCAmelCase_	,      UpperCAmelCase_	:					Optional[Any]     	=   dummy_input["input_ids"].shape
				UpperCAmelCase_	:					List[str]     	=   (batch, encoder_sequence, self._config.encoder_hidden_size)
				UpperCAmelCase_	:					List[str]     	=   dummy_input.pop("input_ids"		)
				UpperCAmelCase_	:					List[str]     	=   dummy_input.pop("attention_mask"		)
				UpperCAmelCase_	:					List[Any]     	=   torch.zeros(lowerCAmelCase_		)

				return common_inputs







class      UpperCamelCase_			(__A	):





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     None:
				pass





	def 	_SCREAMING_SNAKE_CASE ( self   :					Any      ,      lowerCAmelCase_   :					PretrainedConfig		)		->     OnnxConfig:
				return VisionEncoderDecoderEncoderOnnxConfig(lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					PretrainedConfig      ,      lowerCAmelCase_   :					PretrainedConfig      ,      lowerCAmelCase_   :					str = "default"		)		->     OnnxConfig:
				UpperCAmelCase_	:					Optional[int]     	=   encoder_config.hidden_size
				return VisionEncoderDecoderDecoderOnnxConfig(lowerCAmelCase_      ,      lowerCAmelCase_		)



