





"""simple docstring"""





import gc
import unittest

import numpy as np
import torch

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class    _lowerCAmelCase  (	a    ,  unittest.TestCase			):
       """simple docstring"""




       __magic_name__	:Optional[Any]						    =   DiTPipeline
       __magic_name__	:Optional[Any]						    =   CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
       __magic_name__	:Dict						    =   PipelineTesterMixin.required_optional_params - {
           """latents""",
           """num_images_per_prompt""",
           """callback""",
           """callback_steps""",
       }
       __magic_name__	:List[Any]						    =   CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
       __magic_name__	:Dict						    =   False






       def 	snake_case		(       self ):



         '''simple docstring'''

         torch.manual_seed(0 )
         lowerCAmelCase__     :str											=				TransformeraDModel(
             sample_size=1_6       ,					num_layers=2       ,					patch_size=4       ,					attention_head_dim=8       ,					num_attention_heads=2       ,					in_channels=4       ,					out_channels=8       ,					attention_bias=__UpperCAmelCase       ,					activation_fn='gelu-approximate'       ,					num_embeds_ada_norm=1_0_0_0       ,					norm_type='ada_norm_zero'       ,					norm_elementwise_affine=__UpperCAmelCase       ,					)
         lowerCAmelCase__     :int											=				AutoencoderKL()
         lowerCAmelCase__     :Union[str, Any]											=				DDIMScheduler()
         lowerCAmelCase__     :List[Any]											=				{'transformer': transformer.eval(), 'vae': vae.eval(), 'scheduler': scheduler}
         return components






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase=0 ):



         '''simple docstring'''

         if str(__UpperCAmelCase ).startswith('mps' ):
           lowerCAmelCase__     :int											=				torch.manual_seed(__UpperCAmelCase )
         else:
           lowerCAmelCase__     :List[str]											=				torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase )
         lowerCAmelCase__     :Optional[int]											=				{
             'class_labels': [1],
             'generator': generator,
             'num_inference_steps': 2,
             'output_type': 'numpy',
         }
         return inputs






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :Union[str, Any]											=				'cpu'

         lowerCAmelCase__     :str											=				self.get_dummy_components()
         lowerCAmelCase__     :Any											=				self.pipeline_class(**__UpperCAmelCase )
         pipe.to(__UpperCAmelCase )
         pipe.set_progress_bar_config(disable=__UpperCAmelCase )

         lowerCAmelCase__     :Tuple											=				self.get_dummy_inputs(__UpperCAmelCase )
         lowerCAmelCase__     :Dict											=				pipe(**__UpperCAmelCase ).images
         lowerCAmelCase__     :Optional[int]											=				image[0, -3:, -3:, -1]

         self.assertEqual(image.shape       ,					(1, 1_6, 1_6, 3) )
         lowerCAmelCase__     :List[str]											=				np.array([0.29_46, 0.66_01, 0.43_29, 0.32_96, 0.41_44, 0.53_19, 0.72_73, 0.50_13, 0.44_57] )
         lowerCAmelCase__     :Optional[int]											=				np.abs(image_slice.flatten() - expected_slice ).max()
         self.assertLessEqual(__UpperCAmelCase       ,					1E-3 )






       def 	snake_case		(       self ):



         '''simple docstring'''

         self._test_inference_batch_single_identical(relax_max_difference=__UpperCAmelCase       ,					expected_max_diff=1E-3 )






       @unittest.skipIf(
           torch_device != 'cuda' or not is_xformers_available()       ,					reason='XFormers attention is only available with CUDA and `xformers` installed'       ,					)
       def 	snake_case		(       self ):



         '''simple docstring'''

         self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 )






@require_torch_gpu
@slow
class    _lowerCAmelCase  (	unittest.TestCase			):
       """simple docstring"""




       def 	snake_case		(       self ):



         '''simple docstring'''

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






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :Any											=				torch.manual_seed(0 )

         lowerCAmelCase__     :Optional[int]											=				DiTPipeline.from_pretrained('facebook/DiT-XL-2-256' )
         pipe.to('cuda' )

         lowerCAmelCase__     :Union[str, Any]											=				['vase', 'umbrella', 'white shark', 'white wolf']
         lowerCAmelCase__     :Tuple											=				pipe.get_label_ids(__UpperCAmelCase )

         lowerCAmelCase__     :List[Any]											=				pipe(__UpperCAmelCase       ,					generator=__UpperCAmelCase       ,					num_inference_steps=4_0       ,					output_type='np' ).images

         for word, image in zip(__UpperCAmelCase       ,					__UpperCAmelCase ):
           lowerCAmelCase__     :Optional[Any]											=				load_numpy(
               F"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy" )
           assert np.abs((expected_image - image).max() ) < 1E-2






       def 	snake_case		(       self ):



         '''simple docstring'''

         lowerCAmelCase__     :int											=				DiTPipeline.from_pretrained('facebook/DiT-XL-2-512' )
         lowerCAmelCase__     :Optional[Any]											=				DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
         pipe.to('cuda' )

         lowerCAmelCase__     :Optional[int]											=				['vase', 'umbrella']
         lowerCAmelCase__     :Optional[Any]											=				pipe.get_label_ids(__UpperCAmelCase )

         lowerCAmelCase__     :List[Any]											=				torch.manual_seed(0 )
         lowerCAmelCase__     :int											=				pipe(__UpperCAmelCase       ,					generator=__UpperCAmelCase       ,					num_inference_steps=2_5       ,					output_type='np' ).images

         for word, image in zip(__UpperCAmelCase       ,					__UpperCAmelCase ):
           lowerCAmelCase__     :Optional[int]											=				load_numpy(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
               F"/dit/{word}_512.npy" )

           assert np.abs((expected_image - image).max() ) < 1E-1




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


__snake_case    					=					get_tests_dir('fixtures')

class 				_SCREAMING_SNAKE_CASE				(							unittest.TestCase  ):
   """simple docstring"""



   def 					UpperCAmelCase__(						self						)      ->							str:
    # A mock response for an HTTP head request to emulate server down
    lowercase__       :       List[str]				=						mock.Mock()
    lowercase__       :       Dict				=						500
    lowercase__       :       Any				=						{}
    lowercase__       :       int				=						HTTPError
    lowercase__       :       Optional[int]				=						{}

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







   def 					UpperCAmelCase__(						self						)      ->							Tuple:
    with self.assertRaises(lowerCamelCase__						):
     # config is in subfolder, the following should not work without specifying the subfolder
     lowercase__       :       List[str]				=						AutoImageProcessor.from_pretrained("""hf-internal-testing/stable-diffusion-all-variants"""						)

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

    self.assertIsNotNone(lowerCamelCase__						)

@is_staging_test
class 				_SCREAMING_SNAKE_CASE				(							unittest.TestCase  ):
   """simple docstring"""



   @classmethod
   def 					UpperCAmelCase__(						cls						)      ->							int:
    lowercase__       :       str				=						TOKEN
    HfFolder.save_token(lowerCamelCase__						)


   @classmethod
   def 					UpperCAmelCase__(						cls						)      ->							List[str]:
    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						)      ->							int:
    lowercase__       :       List[str]				=						ViTImageProcessor.from_pretrained(lowerCamelCase__						)
    image_processor.push_to_hub("""test-image-processor""" ,     use_auth_token=self._token						)

    lowercase__       :       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						)

    lowercase__       :       Union[str, Any]				=						ViTImageProcessor.from_pretrained(F'''{USER}/test-image-processor'''						)
    for k, v in image_processor.__dict__.items():
     self.assertEqual(lowerCamelCase__ ,     getattr(lowerCamelCase__ ,     lowerCamelCase__						)						)


   def 					UpperCAmelCase__(						self						)      ->							Optional[int]:
    lowercase__       :       Tuple				=						ViTImageProcessor.from_pretrained(lowerCamelCase__						)
    image_processor.push_to_hub("""valid_org/test-image-processor""" ,     use_auth_token=self._token						)

    lowercase__       :       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						)

    lowercase__       :       List[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 					UpperCAmelCase__(						self						)      ->							Dict:
    CustomImageProcessor.register_for_auto_class()
    lowercase__       :       List[str]				=						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"""} ,     )

    lowercase__       :       Dict				=						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"""						)