


'''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     :  Union[str, Any]											=    get_tests_dir("""fixtures""")
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

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

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







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[Any]       =							ViTImageProcessor.from_pretrained(
                'https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json' )







     def a						(			self ):

            '''simple docstring'''

            with self.assertRaises(snake_case__ ):
                   # config is in subfolder, the following should not work without specifying the subfolder
                   _lowerCAmelCase     :				Optional[Any]       =							AutoImageProcessor.from_pretrained('hf-internal-testing/stable-diffusion-all-variants' )

            _lowerCAmelCase     :				List[Any]       =							AutoImageProcessor.from_pretrained(
                'hf-internal-testing/stable-diffusion-all-variants'   ,						subfolder='feature_extractor' )

            self.assertIsNotNone(snake_case__ )
@is_staging_test
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     @classmethod
     def a						(			cls ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							TOKEN
            HfFolder.save_token(snake_case__ )







     @classmethod
     def a						(			cls ):

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

            '''simple docstring'''

            _lowerCAmelCase     :				Any       =							ViTImageProcessor.from_pretrained(snake_case__ )
            image_processor.push_to_hub('test-image-processor'   ,						use_auth_token=self._token )

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

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

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







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							ViTImageProcessor.from_pretrained(snake_case__ )
            image_processor.push_to_hub('valid_org/test-image-processor'   ,						use_auth_token=self._token )

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

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

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







     def a						(			self ):

            '''simple docstring'''

            CustomImageProcessor.register_for_auto_class()
            _lowerCAmelCase     :				Tuple       =							CustomImageProcessor.from_pretrained(snake_case__ )

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

            _lowerCAmelCase     :				Dict       =							AutoImageProcessor.from_pretrained(
                F'{USER}/test-dynamic-image-processor'   ,						trust_remote_code=snake_case__ )
            # 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 gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


lowerCAmelCase     :  str											=    False
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     pass
@nightly
@require_torch_gpu
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							VersatileDiffusionTextToImagePipeline.from_pretrained('shi-labs/versatile-diffusion' )
            # remove text_unet
            pipe.remove_unused_weights()
            pipe.to(snake_case__ )
            pipe.set_progress_bar_config(disable=snake_case__ )

            _lowerCAmelCase     :				Any       =							'A painting of a squirrel eating a burger '
            _lowerCAmelCase     :				List[Any]       =							torch.manual_seed(0 )
            _lowerCAmelCase     :				Any       =							pipe(
                prompt=snake_case__   ,						generator=snake_case__   ,						guidance_scale=7.5   ,						num_inference_steps=2   ,						output_type='numpy' ).images

            with tempfile.TemporaryDirectory() as tmpdirname:
                   pipe.save_pretrained(snake_case__ )
                   _lowerCAmelCase     :				Any       =							VersatileDiffusionTextToImagePipeline.from_pretrained(snake_case__ )
            pipe.to(snake_case__ )
            pipe.set_progress_bar_config(disable=snake_case__ )

            _lowerCAmelCase     :				Optional[int]       =							generator.manual_seed(0 )
            _lowerCAmelCase     :				Tuple       =							pipe(
                prompt=snake_case__   ,						generator=snake_case__   ,						guidance_scale=7.5   ,						num_inference_steps=2   ,						output_type='numpy' ).images

            assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass"







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Union[str, Any]       =							VersatileDiffusionTextToImagePipeline.from_pretrained(
                'shi-labs/versatile-diffusion'   ,						torch_dtype=torch.floataa )
            pipe.to(snake_case__ )
            pipe.set_progress_bar_config(disable=snake_case__ )

            _lowerCAmelCase     :				Dict       =							'A painting of a squirrel eating a burger '
            _lowerCAmelCase     :				Any       =							torch.manual_seed(0 )
            _lowerCAmelCase     :				int       =							pipe(
                prompt=snake_case__   ,						generator=snake_case__   ,						guidance_scale=7.5   ,						num_inference_steps=50   ,						output_type='numpy' ).images

            _lowerCAmelCase     :				Optional[int]       =							image[0, 253:256, 253:256, -1]

            assert image.shape == (1, 512, 512, 3)
            _lowerCAmelCase     :				Dict       =							np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] )

            assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2

