


'''simple docstring'''






from typing import List, Optional, Union

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


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

a_   :      Dict				    =      {
    "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 	a       (       _SCREAMING_SNAKE_CASE    ):
 _lowerCAmelCase	   =		"""informer"""
 _lowerCAmelCase	   =		{
     """hidden_size""": """d_model""",
     """num_attention_heads""": """encoder_attention_heads""",
     """num_hidden_layers""": """encoder_layers""",
 }
 def __init__(	self ,			__magic_name__ = None ,			__magic_name__ = None ,			__magic_name__ = "student_t" ,			__magic_name__ = "nll" ,			__magic_name__ = 1 ,			__magic_name__ = None ,			__magic_name__ = "mean" ,			__magic_name__ = 0 ,			__magic_name__ = 0 ,			__magic_name__ = 0 ,			__magic_name__ = 0 ,			__magic_name__ = None ,			__magic_name__ = None ,			__magic_name__ = 64 ,			__magic_name__ = 32 ,			__magic_name__ = 32 ,			__magic_name__ = 2 ,			__magic_name__ = 2 ,			__magic_name__ = 2 ,			__magic_name__ = 2 ,			__magic_name__ = True ,			__magic_name__ = "gelu" ,			__magic_name__ = 0.0_5 ,			__magic_name__ = 0.1 ,			__magic_name__ = 0.1 ,			__magic_name__ = 0.1 ,			__magic_name__ = 0.1 ,			__magic_name__ = 1_00 ,			__magic_name__ = 0.0_2 ,			__magic_name__=True ,			__magic_name__ = "prob" ,			__magic_name__ = 5 ,			__magic_name__ = True ,			**__magic_name__ ,			)   ->							str:
      # time series specific configuration
      _a      =							prediction_length
      _a      =							context_length or prediction_length
      _a      =							distribution_output
      _a      =							loss
      _a      =							input_size
      _a      =							num_time_features
      _a      =							lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
      _a      =							scaling
      _a      =							num_dynamic_real_features
      _a      =							num_static_real_features
      _a      =							num_static_categorical_features

      # set cardinality
      if cardinality and num_static_categorical_features > 0:
           if len(__magic_name__  ) != num_static_categorical_features:
                raise ValueError(
                    'The cardinality should be a list of the same length as `num_static_categorical_features`'  )
           _a      =							cardinality
      else:
           _a      =							[0]

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

      _a      =							num_parallel_samples

      # Transformer architecture configuration
      _a      =							input_size * len(self.lags_sequence  ) + self._number_of_features
      _a      =							d_model
      _a      =							encoder_attention_heads
      _a      =							decoder_attention_heads
      _a      =							encoder_ffn_dim
      _a      =							decoder_ffn_dim
      _a      =							encoder_layers
      _a      =							decoder_layers

      _a      =							dropout
      _a      =							attention_dropout
      _a      =							activation_dropout
      _a      =							encoder_layerdrop
      _a      =							decoder_layerdrop

      _a      =							activation_function
      _a      =							init_std

      _a      =							use_cache

      # Informer
      _a      =							attention_type
      _a      =							sampling_factor
      _a      =							distil

      super().__init__(is_encoder_decoder=__magic_name__ ,			**__magic_name__  )
 @property
 def 							__UpperCAmelCase						(	self  )   ->							int:
      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
      )





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


a_   :      Tuple				    =      get_tests_dir("fixtures")




class 	a       (       unittest.TestCase    ):
 def 							__UpperCAmelCase						(	self  )   ->							str:
      # A mock response for an HTTP head request to emulate server down
      _a      =							mock.Mock()
      _a      =							5_00
      _a      =							{}
      _a      =							HTTPError
      _a      =							{}

      # Download this model to make sure it's in the cache.
      _a      =							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=__magic_name__  ) as mock_head:
           _a      =							ViTImageProcessor.from_pretrained('hf-internal-testing/tiny-random-vit'  )
           # This check we did call the fake head request
           mock_head.assert_called()
 def 							__UpperCAmelCase						(	self  )   ->							Optional[int]:
      # This test is for deprecated behavior and can be removed in v5
      _a      =							ViTImageProcessor.from_pretrained(
          'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json'  )




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

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

      self.assertIsNotNone(__magic_name__  )





@is_staging_test
class 	a       (       unittest.TestCase    ):
 @classmethod
 def 							__UpperCAmelCase						(	cls  )   ->							Dict:
      _a      =							TOKEN
      HfFolder.save_token(__magic_name__  )
 @classmethod
 def 							__UpperCAmelCase						(	cls  )   ->							List[Any]:
      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 							__UpperCAmelCase						(	self  )   ->							str:
      _a      =							ViTImageProcessor.from_pretrained(__magic_name__  )
      image_processor.push_to_hub('test-image-processor' ,			use_auth_token=self._token  )

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

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

      _a      =							ViTImageProcessor.from_pretrained(f'{USER}/test-image-processor'  )
      for k, v in image_processor.__dict__.items():
           self.assertEqual(__magic_name__ ,			getattr(__magic_name__ ,			__magic_name__  )  )
 def 							__UpperCAmelCase						(	self  )   ->							Optional[Any]:
      _a      =							ViTImageProcessor.from_pretrained(__magic_name__  )
      image_processor.push_to_hub('valid_org/test-image-processor' ,			use_auth_token=self._token  )

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

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

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




 def 							__UpperCAmelCase						(	self  )   ->							Any:
      CustomImageProcessor.register_for_auto_class()
      _a      =							CustomImageProcessor.from_pretrained(__magic_name__  )

      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      =							AutoImageProcessor.from_pretrained(
          f'{USER}/test-dynamic-image-processor' ,			trust_remote_code=__magic_name__  )
      # 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'  )

