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


SCREAMING_SNAKE_CASE			  =  get_tests_dir("""fixtures""")



class 	__a	(   unittest.TestCase						):






       def 						_SCREAMING_SNAKE_CASE							(	self			:				str      )->	Tuple:







              """simple docstring"""
              # A mock response for an HTTP head request to emulate server down
              UpperCamelCase       			=		mock.Mock()
              UpperCamelCase       			=		500
              UpperCamelCase       			=		{}
              UpperCamelCase       			=		HTTPError
              UpperCamelCase       			=		{}

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






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	List[Any]:







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






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	int:







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

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

              self.assertIsNotNone(UpperCAmelCase_      )





@is_staging_test
class 	__a	(   unittest.TestCase						):






       @classmethod
       def 						_SCREAMING_SNAKE_CASE							(	cls			:				List[Any]      )->	Tuple:







              """simple docstring"""
              UpperCamelCase       			=		TOKEN
              HfFolder.save_token(UpperCAmelCase_      )






       @classmethod
       def 						_SCREAMING_SNAKE_CASE							(	cls			:				List[Any]      )->	Optional[int]:







              """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 						_SCREAMING_SNAKE_CASE							(	self			:				int      )->	Optional[int]:







              """simple docstring"""
              UpperCamelCase       			=		ViTImageProcessor.from_pretrained(UpperCAmelCase_      )
              image_processor.push_to_hub("test-image-processor"							,   use_auth_token=self._token      )

              UpperCamelCase       			=		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      )

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






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[Any]      )->	Optional[int]:







              """simple docstring"""
              UpperCamelCase       			=		ViTImageProcessor.from_pretrained(UpperCAmelCase_      )
              image_processor.push_to_hub("valid_org/test-image-processor"							,   use_auth_token=self._token      )

              UpperCamelCase       			=		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      )

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






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	Any:







              """simple docstring"""
              CustomImageProcessor.register_for_auto_class()
              UpperCamelCase       			=		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"}							,   )

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


import unittest

import torch

from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()



class 	__a	(   _lowerCAmelCase     ,  _lowerCAmelCase     ,  unittest.TestCase						):
       UpperCamelCase_		:       Any				=      VQModel
       UpperCamelCase_		:       Dict				=      '''sample'''






       @property
       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[str]							,   UpperCAmelCase_			:				List[str]=(32, 32)      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		4
              UpperCamelCase       			=		3

              UpperCamelCase       			=		floats_tensor((batch_size, num_channels) + sizes      ).to(UpperCAmelCase_      )

              return {"sample": image}






       @property
       def 						_SCREAMING_SNAKE_CASE							(	self			:				int      )->	List[Any]:







              """simple docstring"""
              return (3, 32, 32)






       @property
       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[Any]      )->	Tuple:







              """simple docstring"""
              return (3, 32, 32)






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[Any]      )->	Optional[int]:







              """simple docstring"""
              UpperCamelCase       			=		{
                  "block_out_channels": [32, 64],
                  "in_channels": 3,
                  "out_channels": 3,
                  "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"],
                  "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"],
                  "latent_channels": 3,
              }
              UpperCamelCase       			=		self.dummy_input
              return init_dict, inputs_dict






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	List[Any]:







              """simple docstring"""
              pass






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Any      )->	str:







              """simple docstring"""
              pass






       def 						_SCREAMING_SNAKE_CASE							(	self			:				Optional[int]      )->	List[Any]:







              """simple docstring"""
              UpperCamelCase			,							UpperCamelCase       			=		VQModel.from_pretrained("fusing/vqgan-dummy"							,   output_loading_info=UpperCAmelCase_      )
              self.assertIsNotNone(UpperCAmelCase_      )
              self.assertEqual(len(loading_info["missing_keys"]      )							,   0      )

              model.to(UpperCAmelCase_      )
              UpperCamelCase       			=		model(**self.dummy_input      )

              assert image is not None, "Make sure output is not None"






       def 						_SCREAMING_SNAKE_CASE							(	self			:				List[Any]      )->	List[str]:







              """simple docstring"""
              UpperCamelCase       			=		VQModel.from_pretrained("fusing/vqgan-dummy"      )
              model.to(UpperCAmelCase_      ).eval()

              torch.manual_seed(0      )
              if torch.cuda.is_available():
                     torch.cuda.manual_seed_all(0      )

              UpperCamelCase       			=		torch.randn(1							,   model.config.in_channels							,   model.config.sample_size							,   model.config.sample_size      )
              UpperCamelCase       			=		image.to(UpperCAmelCase_      )
              with torch.no_grad():
                     UpperCamelCase       			=		model(UpperCAmelCase_      ).sample

              UpperCamelCase       			=		output[0, -1, -3:, -3:].flatten().cpu()
              # fmt: off
              UpperCamelCase       			=		torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143]      )
              # fmt: on
              self.assertTrue(torch.allclose(UpperCAmelCase_							,   UpperCAmelCase_							,   atol=1e-3      )      )





