


'''simple docstring'''







import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel
from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings
from diffusers.utils import load_numpy, slow, torch_device
from diffusers.utils.testing_utils import require_torch_gpu


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



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

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







     @property
     def a						(			self ):

            '''simple docstring'''

            return 12







     @property
     def a						(			self ):

            '''simple docstring'''

            return 12







     @property
     def a						(			self ):

            '''simple docstring'''

            return 32







     @property
     def a						(			self ):

            '''simple docstring'''

            torch.manual_seed(0 )
            _lowerCAmelCase     :				Union[str, Any]       =							VQModel(
                block_out_channels=[32, 64]   ,						in_channels=3   ,						out_channels=3   ,						down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']   ,						up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']   ,						latent_channels=3   ,						num_vq_embeddings=self.num_embed   ,						vq_embed_dim=3   ,						)
            return model







     @property
     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[int]       =							CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
            return tokenizer







     @property
     def a						(			self ):

            '''simple docstring'''

            torch.manual_seed(0 )
            _lowerCAmelCase     :				List[str]       =							CLIPTextConfig(
                bos_token_id=0   ,						eos_token_id=2   ,						hidden_size=self.text_embedder_hidden_size   ,						intermediate_size=37   ,						layer_norm_eps=1E-05   ,						num_attention_heads=4   ,						num_hidden_layers=5   ,						pad_token_id=1   ,						vocab_size=1000   ,						)
            return CLIPTextModel(snake_case__ )







     @property
     def a						(			self ):

            '''simple docstring'''

            torch.manual_seed(0 )

            _lowerCAmelCase     :				List[str]       =							12
            _lowerCAmelCase     :				Optional[Any]       =							12

            _lowerCAmelCase     :				Optional[Any]       =							{
                'attention_bias': True,
                'cross_attention_dim': 32,
                'attention_head_dim': height * width,
                'num_attention_heads': 1,
                'num_vector_embeds': self.num_embed,
                'num_embeds_ada_norm': self.num_embeds_ada_norm,
                'norm_num_groups': 32,
                'sample_size': width,
                'activation_fn': 'geglu-approximate',
            }

            _lowerCAmelCase     :				int       =							TransformeraDModel(**snake_case__ )
            return model







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							'cpu'

            _lowerCAmelCase     :				Dict       =							self.dummy_vqvae
            _lowerCAmelCase     :				List[str]       =							self.dummy_text_encoder
            _lowerCAmelCase     :				int       =							self.dummy_tokenizer
            _lowerCAmelCase     :				Optional[int]       =							self.dummy_transformer
            _lowerCAmelCase     :				List[str]       =							VQDiffusionScheduler(self.num_embed )
            _lowerCAmelCase     :				str       =							LearnedClassifierFreeSamplingEmbeddings(learnable=snake_case__ )

            _lowerCAmelCase     :				List[str]       =							VQDiffusionPipeline(
                vqvae=snake_case__   ,						text_encoder=snake_case__   ,						tokenizer=snake_case__   ,						transformer=snake_case__   ,						scheduler=snake_case__   ,						learned_classifier_free_sampling_embeddings=snake_case__   ,						)
            _lowerCAmelCase     :				Union[str, Any]       =							pipe.to(snake_case__ )
            pipe.set_progress_bar_config(disable=snake_case__ )

            _lowerCAmelCase     :				int       =							'teddy bear playing in the pool'

            _lowerCAmelCase     :				Tuple       =							torch.Generator(device=snake_case__ ).manual_seed(0 )
            _lowerCAmelCase     :				str       =							pipe([prompt]   ,						generator=snake_case__   ,						num_inference_steps=2   ,						output_type='np' )
            _lowerCAmelCase     :				List[str]       =							output.images

            _lowerCAmelCase     :				Dict       =							torch.Generator(device=snake_case__ ).manual_seed(0 )
            _lowerCAmelCase     :				str       =							pipe(
                [prompt]   ,						generator=snake_case__   ,						output_type='np'   ,						return_dict=snake_case__   ,						num_inference_steps=2 )[0]

            _lowerCAmelCase     :				int       =							image[0, -3:, -3:, -1]
            _lowerCAmelCase     :				Any       =							image_from_tuple[0, -3:, -3:, -1]

            assert image.shape == (1, 24, 24, 3)

            _lowerCAmelCase     :				str       =							np.array([0.6551, 0.6168, 0.5008, 0.5676, 0.5659, 0.4295, 0.6073, 0.5599, 0.4992] )

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







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Any       =							'cpu'

            _lowerCAmelCase     :				Optional[int]       =							self.dummy_vqvae
            _lowerCAmelCase     :				int       =							self.dummy_text_encoder
            _lowerCAmelCase     :				str       =							self.dummy_tokenizer
            _lowerCAmelCase     :				List[str]       =							self.dummy_transformer
            _lowerCAmelCase     :				Optional[Any]       =							VQDiffusionScheduler(self.num_embed )
            _lowerCAmelCase     :				List[Any]       =							LearnedClassifierFreeSamplingEmbeddings(
                learnable=snake_case__   ,						hidden_size=self.text_embedder_hidden_size   ,						length=tokenizer.model_max_length )

            _lowerCAmelCase     :				List[Any]       =							VQDiffusionPipeline(
                vqvae=snake_case__   ,						text_encoder=snake_case__   ,						tokenizer=snake_case__   ,						transformer=snake_case__   ,						scheduler=snake_case__   ,						learned_classifier_free_sampling_embeddings=snake_case__   ,						)
            _lowerCAmelCase     :				Optional[int]       =							pipe.to(snake_case__ )
            pipe.set_progress_bar_config(disable=snake_case__ )

            _lowerCAmelCase     :				List[Any]       =							'teddy bear playing in the pool'

            _lowerCAmelCase     :				Optional[int]       =							torch.Generator(device=snake_case__ ).manual_seed(0 )
            _lowerCAmelCase     :				Optional[Any]       =							pipe([prompt]   ,						generator=snake_case__   ,						num_inference_steps=2   ,						output_type='np' )
            _lowerCAmelCase     :				List[str]       =							output.images

            _lowerCAmelCase     :				Optional[int]       =							torch.Generator(device=snake_case__ ).manual_seed(0 )
            _lowerCAmelCase     :				Dict       =							pipe(
                [prompt]   ,						generator=snake_case__   ,						output_type='np'   ,						return_dict=snake_case__   ,						num_inference_steps=2 )[0]

            _lowerCAmelCase     :				Optional[int]       =							image[0, -3:, -3:, -1]
            _lowerCAmelCase     :				Dict       =							image_from_tuple[0, -3:, -3:, -1]

            assert image.shape == (1, 24, 24, 3)

            _lowerCAmelCase     :				Any       =							np.array([0.6693, 0.6075, 0.4959, 0.5701, 0.5583, 0.4333, 0.6171, 0.5684, 0.4988] )

            assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0
            assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
@slow
@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     :				str       =							load_numpy(
                'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
                '/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy' )

            _lowerCAmelCase     :				Dict       =							VQDiffusionPipeline.from_pretrained('microsoft/vq-diffusion-ithq' )
            _lowerCAmelCase     :				List[Any]       =							pipeline.to(snake_case__ )
            pipeline.set_progress_bar_config(disable=snake_case__ )

            # requires GPU generator for gumbel softmax
            # don't use GPU generator in tests though
            _lowerCAmelCase     :				List[str]       =							torch.Generator(device=snake_case__ ).manual_seed(0 )
            _lowerCAmelCase     :				List[str]       =							pipeline(
                'teddy bear playing in the pool'   ,						num_images_per_prompt=1   ,						generator=snake_case__   ,						output_type='np'   ,						)

            _lowerCAmelCase     :				str       =							output.images[0]

            assert image.shape == (256, 256, 3)
            assert np.abs(expected_image - image ).max() < 2.0









import unittest

import numpy as np
import requests

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

    from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
    _SCREAMING_SNAKE_CASE   =  False

if is_vision_available():
    from PIL import Image

    from transformers import PixaStructImageProcessor






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


       def __init__(				self	:str,      snake_case	:int,      snake_case	:Dict=7,      snake_case	:List[Any]=3,      snake_case	:int=18,      snake_case	:List[str]=30,      snake_case	:str=400,      snake_case	:int=None,      snake_case	:List[Any]=True,      snake_case	:Optional[int]=True,      snake_case	:Union[str, Any]=None,      ):



          """simple docstring"""

          _lowercase              =size if size is not None else {'height': 20, 'width': 20}
          _lowercase              =parent
          _lowercase              =batch_size
          _lowercase              =num_channels
          _lowercase              =image_size
          _lowercase              =min_resolution
          _lowercase              =max_resolution
          _lowercase              =size
          _lowercase              =do_normalize
          _lowercase              =do_convert_rgb
          _lowercase              =[512, 1024, 2048, 4096]
          _lowercase              =patch_size if patch_size is not None else {'height': 16, 'width': 16}





       def 				UpperCamelCase__						(				self	:Any):



          """simple docstring"""

          return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}





       def 				UpperCamelCase__						(				self	:int):



          """simple docstring"""

          _lowercase              ='https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
          _lowercase              =Image.open(requests.get(snake_case,      stream=snake_case).raw).convert('RGB')
          return raw_image






@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11  ,						reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.'''  ,						)
@require_torch
@require_vision
class 					SCREAMING_SNAKE_CASE_  (       _a  ,						unittest.TestCase ):
       """simple docstring"""


       __lowerCAmelCase    :		Tuple					=PixaStructImageProcessor if is_vision_available() else None





       def 				UpperCamelCase__						(				self	:str):



          """simple docstring"""

          _lowercase              =PixaStructImageProcessingTester(self)





       @property
       def 				UpperCamelCase__						(				self	:Optional[int]):



          """simple docstring"""

          return self.image_processor_tester.prepare_image_processor_dict()





       def 				UpperCamelCase__						(				self	:str):



          """simple docstring"""

          _lowercase              =self.image_processing_class(**self.image_processor_dict)
          self.assertTrue(hasattr(snake_case,      'do_normalize'))
          self.assertTrue(hasattr(snake_case,      'do_convert_rgb'))





       def 				UpperCamelCase__						(				self	:Any):



          """simple docstring"""

          _lowercase              =self.image_processor_tester.prepare_dummy_image()

          _lowercase              =self.image_processing_class(**self.image_processor_dict)
          _lowercase              =2048

          _lowercase              =image_processor(snake_case,      return_tensors='pt',      max_patches=snake_case)
          self.assertTrue(torch.allclose(inputs.flattened_patches.mean(),      torch.tensor(0.0_6_0_6),      atol=1e-3,      rtol=1e-3))





       def 				UpperCamelCase__						(				self	:int):



          """simple docstring"""

          _lowercase              =self.image_processing_class(**self.image_processor_dict)
          # create random PIL images
          _lowercase              =prepare_image_inputs(self.image_processor_tester,      equal_resolution=snake_case)
          for image in image_inputs:
             self.assertIsInstance(snake_case,      Image.Image)

          # Test not batched input
          _lowercase              =(
              (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
              * self.image_processor_tester.num_channels
          ) + 2

          for max_patch in self.image_processor_tester.max_patches:
             # Test not batched input
             _lowercase              =image_processor(
                 image_inputs[0],      return_tensors='pt',      max_patches=snake_case).flattened_patches
             self.assertEqual(
                 encoded_images.shape,      (1, max_patch, expected_hidden_dim),      )

             # Test batched
             _lowercase              =image_processor(
                 snake_case,      return_tensors='pt',      max_patches=snake_case).flattened_patches
             self.assertEqual(
                 encoded_images.shape,      (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),      )





       def 				UpperCamelCase__						(				self	:Union[str, Any]):



          """simple docstring"""

          _lowercase              =self.image_processing_class(**self.image_processor_dict)
          # create random PIL images
          _lowercase              =prepare_image_inputs(self.image_processor_tester,      equal_resolution=snake_case)
          for image in image_inputs:
             self.assertIsInstance(snake_case,      Image.Image)

          # Test not batched input
          _lowercase              =(
              (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
              * self.image_processor_tester.num_channels
          ) + 2

          _lowercase              =True

          for max_patch in self.image_processor_tester.max_patches:
             # Test not batched input
             with self.assertRaises(snake_case):
                _lowercase              =image_processor(
                    image_inputs[0],      return_tensors='pt',      max_patches=snake_case).flattened_patches

             _lowercase              ='Hello'

             _lowercase              =image_processor(
                 image_inputs[0],      return_tensors='pt',      max_patches=snake_case,      header_text=snake_case).flattened_patches
             self.assertEqual(
                 encoded_images.shape,      (1, max_patch, expected_hidden_dim),      )

             # Test batched
             _lowercase              =image_processor(
                 snake_case,      return_tensors='pt',      max_patches=snake_case,      header_text=snake_case).flattened_patches
             self.assertEqual(
                 encoded_images.shape,      (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),      )





       def 				UpperCamelCase__						(				self	:int):



          """simple docstring"""

          _lowercase              =self.image_processing_class(**self.image_processor_dict)
          # create random numpy tensors
          _lowercase              =prepare_image_inputs(self.image_processor_tester,      equal_resolution=snake_case,      numpify=snake_case)
          for image in image_inputs:
             self.assertIsInstance(snake_case,      np.ndarray)

          _lowercase              =(
              (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
              * self.image_processor_tester.num_channels
          ) + 2

          for max_patch in self.image_processor_tester.max_patches:
             # Test not batched input
             _lowercase              =image_processor(
                 image_inputs[0],      return_tensors='pt',      max_patches=snake_case).flattened_patches
             self.assertEqual(
                 encoded_images.shape,      (1, max_patch, expected_hidden_dim),      )

             # Test batched
             _lowercase              =image_processor(
                 snake_case,      return_tensors='pt',      max_patches=snake_case).flattened_patches
             self.assertEqual(
                 encoded_images.shape,      (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),      )





       def 				UpperCamelCase__						(				self	:Any):



          """simple docstring"""

          _lowercase              =self.image_processing_class(**self.image_processor_dict)
          # create random PyTorch tensors
          _lowercase              =prepare_image_inputs(self.image_processor_tester,      equal_resolution=snake_case,      torchify=snake_case)
          for image in image_inputs:
             self.assertIsInstance(snake_case,      torch.Tensor)

          # Test not batched input
          _lowercase              =(
              (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
              * self.image_processor_tester.num_channels
          ) + 2

          for max_patch in self.image_processor_tester.max_patches:
             # Test not batched input
             _lowercase              =image_processor(
                 image_inputs[0],      return_tensors='pt',      max_patches=snake_case).flattened_patches
             self.assertEqual(
                 encoded_images.shape,      (1, max_patch, expected_hidden_dim),      )

             # Test batched
             _lowercase              =image_processor(
                 snake_case,      return_tensors='pt',      max_patches=snake_case).flattened_patches
             self.assertEqual(
                 encoded_images.shape,      (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),      )






@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11  ,						reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.'''  ,						)
@require_torch
@require_vision
class 					SCREAMING_SNAKE_CASE_  (       _a  ,						unittest.TestCase ):
       """simple docstring"""


       __lowerCAmelCase    :		Optional[Any]					=PixaStructImageProcessor if is_vision_available() else None





       def 				UpperCamelCase__						(				self	:Optional[int]):



          """simple docstring"""

          _lowercase              =PixaStructImageProcessingTester(self,      num_channels=4)
          _lowercase              =3





       @property
       def 				UpperCamelCase__						(				self	:str):



          """simple docstring"""

          return self.image_processor_tester.prepare_image_processor_dict()





       def 				UpperCamelCase__						(				self	:Optional[int]):



          """simple docstring"""

          _lowercase              =self.image_processing_class(**self.image_processor_dict)
          self.assertTrue(hasattr(snake_case,      'do_normalize'))
          self.assertTrue(hasattr(snake_case,      'do_convert_rgb'))





       def 				UpperCamelCase__						(				self	:Optional[Any]):



          """simple docstring"""

          _lowercase              =self.image_processing_class(**self.image_processor_dict)
          # create random PIL images
          _lowercase              =prepare_image_inputs(self.image_processor_tester,      equal_resolution=snake_case)
          for image in image_inputs:
             self.assertIsInstance(snake_case,      Image.Image)

          # Test not batched input
          _lowercase              =(
              (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
              * (self.image_processor_tester.num_channels - 1)
          ) + 2

          for max_patch in self.image_processor_tester.max_patches:
             # Test not batched input
             _lowercase              =image_processor(
                 image_inputs[0],      return_tensors='pt',      max_patches=snake_case).flattened_patches
             self.assertEqual(
                 encoded_images.shape,      (1, max_patch, expected_hidden_dim),      )

             # Test batched
             _lowercase              =image_processor(
                 snake_case,      return_tensors='pt',      max_patches=snake_case).flattened_patches
             self.assertEqual(
                 encoded_images.shape,      (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),      )


