
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


UpperCAmelCase__		:     Union[str, Any]     			=      get_tests_dir('fixtures')






class UpperCAmelCase   (						unittest.TestCase   ):





   '''simple docstring'''


   def  __magic_name__				(					self     :							Any     ):

      """simple docstring"""
      # A mock response for an HTTP head request to emulate server down
      _A:  Any					=       mock.Mock()
      _A:  Dict					=       5_0_0
      _A:  Optional[Any]					=       {}
      _A:  Optional[Any]					=       HTTPError
      _A:  Optional[Any]					=       {}

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


   def  __magic_name__				(					self     :							Tuple     ):

      """simple docstring"""
      # This test is for deprecated behavior and can be removed in v5
      _A:  Tuple					=       ViTImageProcessor.from_pretrained(
          '''https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'''     )


   def  __magic_name__				(					self     :							Any     ):

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

      _A:  Optional[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  __magic_name__				(					cls     :							int     ):

      """simple docstring"""
      _A:  List[Any]					=       TOKEN
      HfFolder.save_token(lowerCAmelCase_     )


   @classmethod
   def  __magic_name__				(					cls     :							Tuple     ):

      """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  __magic_name__				(					self     :							Tuple     ):

      """simple docstring"""
      _A:  Any					=       ViTImageProcessor.from_pretrained(lowerCAmelCase_     )
      image_processor.push_to_hub('''test-image-processor'''			,			use_auth_token=self._token     )

      _A:  List[str]					=       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     )

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


   def  __magic_name__				(					self     :							Optional[Any]     ):

      """simple docstring"""
      _A:  str					=       ViTImageProcessor.from_pretrained(lowerCAmelCase_     )
      image_processor.push_to_hub('''valid_org/test-image-processor'''			,			use_auth_token=self._token     )

      _A:  List[str]					=       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     )

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


   def  __magic_name__				(					self     :							Any     ):

      """simple docstring"""
      CustomImageProcessor.register_for_auto_class()
      _A:  Any					=       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'''}			,			)

      _A:  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'''     )





from typing import List, Optional, Union

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


UpperCAmelCase__		:     Optional[Any]     			=      logging.get_logger(__name__)

UpperCAmelCase__		:     Any     			=      {
    'huggingface/informer-tourism-monthly': (
        'https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json'
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}






class UpperCAmelCase   (						SCREAMING_SNAKE_CASE__   ):





   '''simple docstring'''
   __UpperCamelCase		:    List[Any] 				=    '''informer'''
   __UpperCamelCase		:    List[str] 				=    {
       '''hidden_size''': '''d_model''',
       '''num_attention_heads''': '''encoder_attention_heads''',
       '''num_hidden_layers''': '''encoder_layers''',
   }


   def __init__(					self     :							Optional[Any]			,			lowerCAmelCase_     :							Optional[int] = None			,			lowerCAmelCase_     :							Optional[int] = None			,			lowerCAmelCase_     :							str = "student_t"			,			lowerCAmelCase_     :							str = "nll"			,			lowerCAmelCase_     :							int = 1			,			lowerCAmelCase_     :							List[int] = None			,			lowerCAmelCase_     :							Optional[Union[str, bool]] = "mean"			,			lowerCAmelCase_     :							int = 0			,			lowerCAmelCase_     :							int = 0			,			lowerCAmelCase_     :							int = 0			,			lowerCAmelCase_     :							int = 0			,			lowerCAmelCase_     :							Optional[List[int]] = None			,			lowerCAmelCase_     :							Optional[List[int]] = None			,			lowerCAmelCase_     :							int = 6_4			,			lowerCAmelCase_     :							int = 3_2			,			lowerCAmelCase_     :							int = 3_2			,			lowerCAmelCase_     :							int = 2			,			lowerCAmelCase_     :							int = 2			,			lowerCAmelCase_     :							int = 2			,			lowerCAmelCase_     :							int = 2			,			lowerCAmelCase_     :							bool = True			,			lowerCAmelCase_     :							str = "gelu"			,			lowerCAmelCase_     :							float = 0.05			,			lowerCAmelCase_     :							float = 0.1			,			lowerCAmelCase_     :							float = 0.1			,			lowerCAmelCase_     :							float = 0.1			,			lowerCAmelCase_     :							float = 0.1			,			lowerCAmelCase_     :							int = 1_0_0			,			lowerCAmelCase_     :							float = 0.02			,			lowerCAmelCase_     :							Tuple=True			,			lowerCAmelCase_     :							str = "prob"			,			lowerCAmelCase_     :							int = 5			,			lowerCAmelCase_     :							bool = True			,			**lowerCAmelCase_     :							str			,			):

      """simple docstring"""
      # time series specific configuration
      _A:  Optional[Any]					=       prediction_length
      _A:  Optional[Any]					=       context_length or prediction_length
      _A:  Dict					=       distribution_output
      _A:  List[str]					=       loss
      _A:  int					=       input_size
      _A:  List[str]					=       num_time_features
      _A:  Optional[Any]					=       lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
      _A:  str					=       scaling
      _A:  Optional[Any]					=       num_dynamic_real_features
      _A:  List[Any]					=       num_static_real_features
      _A:  Tuple					=       num_static_categorical_features

      # set cardinality
      if cardinality and num_static_categorical_features > 0:
         if len(lowerCAmelCase_     ) != num_static_categorical_features:
            raise ValueError(
                '''The cardinality should be a list of the same length as `num_static_categorical_features`'''     )
         _A:  str					=       cardinality
      else:
         _A:  Union[str, Any]					=       [0]

      # set embedding_dimension
      if embedding_dimension and num_static_categorical_features > 0:
         if len(lowerCAmelCase_     ) != num_static_categorical_features:
            raise ValueError(
                '''The embedding dimension should be a list of the same length as `num_static_categorical_features`'''     )
         _A:  List[str]					=       embedding_dimension
      else:
         _A:  Union[str, Any]					=       [min(5_0			,			(cat + 1) // 2     ) for cat in self.cardinality]

      _A:  int					=       num_parallel_samples

      # Transformer architecture configuration
      _A:  Union[str, Any]					=       input_size * len(self.lags_sequence     ) + self._number_of_features
      _A:  Union[str, Any]					=       d_model
      _A:  Optional[Any]					=       encoder_attention_heads
      _A:  Optional[Any]					=       decoder_attention_heads
      _A:  Optional[Any]					=       encoder_ffn_dim
      _A:  Union[str, Any]					=       decoder_ffn_dim
      _A:  Any					=       encoder_layers
      _A:  str					=       decoder_layers

      _A:  List[str]					=       dropout
      _A:  Any					=       attention_dropout
      _A:  Optional[int]					=       activation_dropout
      _A:  List[Any]					=       encoder_layerdrop
      _A:  str					=       decoder_layerdrop

      _A:  int					=       activation_function
      _A:  Tuple					=       init_std

      _A:  Union[str, Any]					=       use_cache

      # Informer
      _A:  Union[str, Any]					=       attention_type
      _A:  str					=       sampling_factor
      _A:  List[str]					=       distil

      super().__init__(is_encoder_decoder=lowerCAmelCase_			,			**lowerCAmelCase_     )


   @property
   def  __magic_name__				(					self     :							List[str]     ):

      """simple docstring"""
      return (
          sum(self.embedding_dimension     )
          + self.num_dynamic_real_features
          + self.num_time_features
          + self.num_static_real_features
          + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
      )



