


import gc
import unittest

import numpy as np
import torch

from diffusers import (
    AudioDiffusionPipeline,
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    DiffusionPipeline,
    Mel,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()







class        UpperCamelCase__   ( unittest.TestCase   ):

					def   UpperCAmelCase__       (     self       :   Tuple       ):






										'''simple docstring'''






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

					@property
					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






										torch.manual_seed(0       )
										lowercase_  							=			UNetaDModel(
										    sample_size=(32, 64)							,					in_channels=1							,					out_channels=1							,					layers_per_block=2							,					block_out_channels=(128, 128)							,					down_block_types=("""AttnDownBlock2D""", """DownBlock2D""")							,					up_block_types=("""UpBlock2D""", """AttnUpBlock2D""")							,					)
										return model

					@property
					def   UpperCAmelCase__       (     self       :   List[Any]       ):






										'''simple docstring'''






										torch.manual_seed(0       )
										lowercase_  							=			UNetaDConditionModel(
										    sample_size=(64, 32)							,					in_channels=1							,					out_channels=1							,					layers_per_block=2							,					block_out_channels=(128, 128)							,					down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""")							,					up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""")							,					cross_attention_dim=10							,					)
										return model

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






										'''simple docstring'''






										torch.manual_seed(0       )
										lowercase_  							=			AutoencoderKL(
										    sample_size=(128, 64)							,					in_channels=1							,					out_channels=1							,					latent_channels=1							,					layers_per_block=2							,					block_out_channels=(128, 128)							,					down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""")							,					up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""")							,					)
										lowercase_  							=			UNetaDModel(
										    sample_size=(64, 32)							,					in_channels=1							,					out_channels=1							,					layers_per_block=2							,					block_out_channels=(128, 128)							,					down_block_types=("""AttnDownBlock2D""", """DownBlock2D""")							,					up_block_types=("""UpBlock2D""", """AttnUpBlock2D""")							,					)
										return vqvae, unet







					@slow
					def   UpperCAmelCase__       (     self       :   str       ):






										'''simple docstring'''






										lowercase_  							=			"""cpu"""  # ensure determinism for the device-dependent torch.Generator
										lowercase_  							=			Mel(
										    x_res=self.dummy_unet.config.sample_size[1]							,					y_res=self.dummy_unet.config.sample_size[0]							,					)

										lowercase_  							=			DDPMScheduler()
										lowercase_  							=			AudioDiffusionPipeline(vqvae=UpperCamelCase__							,					unet=self.dummy_unet							,					mel=UpperCamelCase__							,					scheduler=UpperCamelCase__       )
										lowercase_  							=			pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

										lowercase_  							=			torch.Generator(device=UpperCamelCase__       ).manual_seed(42       )
										lowercase_  							=			pipe(generator=UpperCamelCase__							,					steps=4       )
										lowercase_  							=			output.audios[0]
										lowercase_  							=			output.images[0]

										lowercase_  							=			torch.Generator(device=UpperCamelCase__       ).manual_seed(42       )
										lowercase_  							=			pipe(generator=UpperCamelCase__							,					steps=4							,					return_dict=UpperCamelCase__       )
										lowercase_  							=			output[0][0]

										assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length)
										assert (
										    image.height == self.dummy_unet.config.sample_size[0]
										    and image.width == self.dummy_unet.config.sample_size[1]
										)
										lowercase_  							=			np.frombuffer(image.tobytes()							,					dtype="""uint8"""       )[:10]
										lowercase_  							=			np.frombuffer(image_from_tuple.tobytes()							,					dtype="""uint8"""       )[:10]
										lowercase_  							=			np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127]       )

										assert np.abs(image_slice.flatten() - expected_slice       ).max() == 0
										assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() == 0

										lowercase_  							=			Mel(
										    x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1]							,					y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0]							,					)

										lowercase_  							=			DDIMScheduler()
										lowercase_  							=			self.dummy_vqvae_and_unet
										lowercase_  							=			AudioDiffusionPipeline(
										    vqvae=self.dummy_vqvae_and_unet[0]							,					unet=dummy_vqvae_and_unet[1]							,					mel=UpperCamelCase__							,					scheduler=UpperCamelCase__       )
										lowercase_  							=			pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

										np.random.seed(0       )
										lowercase_  							=			np.random.uniform(-1							,					1							,					((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)       )
										lowercase_  							=			torch.Generator(device=UpperCamelCase__       ).manual_seed(42       )
										lowercase_  							=			pipe(raw_audio=UpperCamelCase__							,					generator=UpperCamelCase__							,					start_step=5							,					steps=10       )
										lowercase_  							=			output.images[0]

										assert (
										    image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0]
										    and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1]
										)
										lowercase_  							=			np.frombuffer(image.tobytes()							,					dtype="""uint8"""       )[:10]
										lowercase_  							=			np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121]       )

										assert np.abs(image_slice.flatten() - expected_slice       ).max() == 0

										lowercase_  							=			self.dummy_unet_condition
										lowercase_  							=			AudioDiffusionPipeline(
										    vqvae=self.dummy_vqvae_and_unet[0]							,					unet=UpperCamelCase__							,					mel=UpperCamelCase__							,					scheduler=UpperCamelCase__       )
										lowercase_  							=			pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

										np.random.seed(0       )
										lowercase_  							=			torch.rand((1, 1, 10)       )
										lowercase_  							=			pipe(generator=UpperCamelCase__							,					encoding=UpperCamelCase__       )
										lowercase_  							=			output.images[0]
										lowercase_  							=			np.frombuffer(image.tobytes()							,					dtype="""uint8"""       )[:10]
										lowercase_  							=			np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111]       )

										assert np.abs(image_slice.flatten() - expected_slice       ).max() == 0







@slow
@require_torch_gpu
class        UpperCamelCase__   ( unittest.TestCase   ):

					def   UpperCAmelCase__       (     self       :   List[str]       ):






										'''simple docstring'''






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







					def   UpperCAmelCase__       (     self       :   List[str]       ):






										'''simple docstring'''






										lowercase_  							=			torch_device

										lowercase_  							=			DiffusionPipeline.from_pretrained("""teticio/audio-diffusion-ddim-256"""       )
										lowercase_  							=			pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

										lowercase_  							=			torch.Generator(device=UpperCamelCase__       ).manual_seed(42       )
										lowercase_  							=			pipe(generator=UpperCamelCase__       )
										lowercase_  							=			output.audios[0]
										lowercase_  							=			output.images[0]

										assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length)
										assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1]
										lowercase_  							=			np.frombuffer(image.tobytes()							,					dtype="""uint8"""       )[:10]
										lowercase_  							=			np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26]       )

										assert np.abs(image_slice.flatten() - expected_slice       ).max() == 0






import io
import math
from typing import Dict, Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    get_image_size,
    infer_channel_dimension_format,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_vision_available, logging
from ...utils.import_utils import requires_backends


if is_vision_available():
							import textwrap

							from PIL import Image, ImageDraw, ImageFont

if is_torch_available():
							import torch

							from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
							a					  =     False


a					  =     logging.get_logger(__name__)
a					  =     'ybelkada/fonts'


def 			UpperCAmelCase_				(      ):
					if is_torch_available() and not is_torch_greater_or_equal_than_1_11:
										raise ImportError(
										    F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use '''
										    """Pix2StructImageProcessor. Please upgrade torch."""  )


def 			UpperCAmelCase_				(      UpperCAmelCase__						,							UpperCAmelCase__						,							UpperCAmelCase__  ):
					requires_backends(UpperCAmelCase__						,							["""torch"""]  )
					_check_torch_version()

					lowercase_  							=			image_tensor.unsqueeze(0  )
					lowercase_  							=			torch.nn.functional.unfold(UpperCAmelCase__						,							(patch_height, patch_width)						,							stride=(patch_height, patch_width)  )
					lowercase_  							=			patches.reshape(image_tensor.size(0  )						,							image_tensor.size(1  )						,							UpperCAmelCase__						,							UpperCAmelCase__						,							-1  )
					lowercase_  							=			patches.permute(0						,							4						,							2						,							3						,							1  ).reshape(
					    image_tensor.size(2  ) // patch_height						,							image_tensor.size(3  ) // patch_width						,							image_tensor.size(1  ) * patch_height * patch_width						,							)
					return patches.unsqueeze(0  )


def 			UpperCAmelCase_				(      UpperCAmelCase__						,							UpperCAmelCase__ = 3_6						,							UpperCAmelCase__ = "black"						,							UpperCAmelCase__ = "white"						,							UpperCAmelCase__ = 5						,							UpperCAmelCase__ = 5						,							UpperCAmelCase__ = 5						,							UpperCAmelCase__ = 5						,							UpperCAmelCase__ = None						,							UpperCAmelCase__ = None						,							):
					requires_backends(UpperCAmelCase__						,							"""vision"""  )
					# Add new lines so that each line is no more than 80 characters.

					lowercase_  							=			textwrap.TextWrapper(width=8_0  )
					lowercase_  							=			wrapper.wrap(text=UpperCAmelCase__  )
					lowercase_  							=			"""\n""".join(UpperCAmelCase__  )

					if font_bytes is not None and font_path is None:
										lowercase_  							=			io.BytesIO(UpperCAmelCase__  )
					elif font_path is not None:
										lowercase_  							=			font_path
					else:
										lowercase_  							=			hf_hub_download(UpperCAmelCase__						,							"""Arial.TTF"""  )
					lowercase_  							=			ImageFont.truetype(UpperCAmelCase__						,							encoding="""UTF-8"""						,							size=UpperCAmelCase__  )

					# Use a temporary canvas to determine the width and height in pixels when
					# rendering the text.
					lowercase_  							=			ImageDraw.Draw(Image.new("""RGB"""						,							(1, 1)						,							UpperCAmelCase__  )  )
					lowercase_							,					lowercase_							,					lowercase_							,					lowercase_  							=			temp_draw.textbbox((0, 0)						,							UpperCAmelCase__						,							UpperCAmelCase__  )

					# Create the actual image with a bit of padding around the text.
					lowercase_  							=			text_width + left_padding + right_padding
					lowercase_  							=			text_height + top_padding + bottom_padding
					lowercase_  							=			Image.new("""RGB"""						,							(image_width, image_height)						,							UpperCAmelCase__  )
					lowercase_  							=			ImageDraw.Draw(UpperCAmelCase__  )
					draw.text(xy=(left_padding, top_padding)						,							text=UpperCAmelCase__						,							fill=UpperCAmelCase__						,							font=UpperCAmelCase__  )
					return image


def 			UpperCAmelCase_				(      UpperCAmelCase__						,							UpperCAmelCase__						,							**UpperCAmelCase__  ):
					requires_backends(UpperCAmelCase__						,							"""vision"""  )

					# Convert to PIL image if necessary
					lowercase_  							=			to_pil_image(UpperCAmelCase__  )

					lowercase_  							=			render_text(UpperCAmelCase__						,							**UpperCAmelCase__  )
					lowercase_  							=			max(header_image.width						,							image.width  )

					lowercase_  							=			int(image.height * (new_width / image.width)  )
					lowercase_  							=			int(header_image.height * (new_width / header_image.width)  )

					lowercase_  							=			Image.new("""RGB"""						,							(new_width, new_height + new_header_height)						,							"""white"""  )
					new_image.paste(header_image.resize((new_width, new_header_height)  )						,							(0, 0)  )
					new_image.paste(image.resize((new_width, new_height)  )						,							(0, new_header_height)  )

					# Convert back to the original framework if necessary
					lowercase_  							=			to_numpy_array(UpperCAmelCase__  )

					if infer_channel_dimension_format(UpperCAmelCase__  ) == ChannelDimension.LAST:
										lowercase_  							=			to_channel_dimension_format(UpperCAmelCase__						,							ChannelDimension.LAST  )

					return new_image







class        UpperCamelCase__   (	__magic_name__   ):
					__SCREAMING_SNAKE_CASE       :  Tuple						=   ['flattened_patches']

					def __init__(     self       :   str							,					UpperCamelCase__       :   bool = True							,					UpperCamelCase__       :   bool = True							,					UpperCamelCase__       :   Dict[str, int] = None							,					UpperCamelCase__       :   int = 2_048							,					UpperCamelCase__       :   bool = False							,					**UpperCamelCase__       :   Optional[int]							,					):






										'''simple docstring'''






										super().__init__(**UpperCamelCase__       )
										lowercase_  							=			patch_size if patch_size is not None else {"""height""": 16, """width""": 16}
										lowercase_  							=			do_normalize
										lowercase_  							=			do_convert_rgb
										lowercase_  							=			max_patches
										lowercase_  							=			is_vqa

					def   UpperCAmelCase__       (     self       :   Optional[Any]							,					UpperCamelCase__       :   np.ndarray							,					UpperCamelCase__       :   int							,					UpperCamelCase__       :   dict							,					**UpperCamelCase__       :   Optional[int]       ):






										'''simple docstring'''






										requires_backends(self.extract_flattened_patches							,					"""torch"""       )
										_check_torch_version()

										# convert to torch
										lowercase_  							=			to_channel_dimension_format(UpperCamelCase__							,					ChannelDimension.FIRST       )
										lowercase_  							=			torch.from_numpy(UpperCamelCase__       )

										lowercase_							,					lowercase_  							=			patch_size["""height"""], patch_size["""width"""]
										lowercase_							,					lowercase_  							=			get_image_size(UpperCamelCase__       )

										# maximize scale s.t.
										lowercase_  							=			math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width)       )
										lowercase_  							=			max(min(math.floor(scale * image_height / patch_height       )							,					UpperCamelCase__       )							,					1       )
										lowercase_  							=			max(min(math.floor(scale * image_width / patch_width       )							,					UpperCamelCase__       )							,					1       )
										lowercase_  							=			max(num_feasible_rows * patch_height							,					1       )
										lowercase_  							=			max(num_feasible_cols * patch_width							,					1       )

										lowercase_  							=			torch.nn.functional.interpolate(
										    image.unsqueeze(0       )							,					size=(resized_height, resized_width)							,					mode="""bilinear"""							,					align_corners=UpperCamelCase__							,					antialias=UpperCamelCase__							,					).squeeze(0       )

										# [1, rows, columns, patch_height * patch_width * image_channels]
										lowercase_  							=			torch_extract_patches(UpperCamelCase__							,					UpperCamelCase__							,					UpperCamelCase__       )

										lowercase_  							=			patches.shape
										lowercase_  							=			patches_shape[1]
										lowercase_  							=			patches_shape[2]
										lowercase_  							=			patches_shape[3]

										# [rows * columns, patch_height * patch_width * image_channels]
										lowercase_  							=			patches.reshape([rows * columns, depth]       )

										# [rows * columns, 1]
										lowercase_  							=			torch.arange(UpperCamelCase__       ).reshape([rows, 1]       ).repeat(1							,					UpperCamelCase__       ).reshape([rows * columns, 1]       )
										lowercase_  							=			torch.arange(UpperCamelCase__       ).reshape([1, columns]       ).repeat(UpperCamelCase__							,					1       ).reshape([rows * columns, 1]       )

										# Offset by 1 so the ids do not contain zeros, which represent padding.
										row_ids += 1
										col_ids += 1

										# Prepare additional patch features.
										# [rows * columns, 1]
										lowercase_  							=			row_ids.to(torch.floataa       )
										lowercase_  							=			col_ids.to(torch.floataa       )

										# [rows * columns, 2 + patch_height * patch_width * image_channels]
										lowercase_  							=			torch.cat([row_ids, col_ids, patches]							,					-1       )

										# [max_patches, 2 + patch_height * patch_width * image_channels]
										lowercase_  							=			torch.nn.functional.pad(UpperCamelCase__							,					[0, 0, 0, max_patches - (rows * columns)]       ).float()

										lowercase_  							=			to_numpy_array(UpperCamelCase__       )

										return result

					def   UpperCAmelCase__       (     self       :   List[Any]							,					UpperCamelCase__       :   np.ndarray							,					UpperCamelCase__       :   Optional[Union[str, ChannelDimension]] = None							,					**UpperCamelCase__       :   Dict       ):






										'''simple docstring'''






										if image.dtype == np.uinta:
															lowercase_  							=			image.astype(np.floataa       )

										# take mean across the whole `image`
										lowercase_  							=			np.mean(UpperCamelCase__       )
										lowercase_  							=			np.std(UpperCamelCase__       )
										lowercase_  							=			max(UpperCamelCase__							,					1.0 / math.sqrt(np.prod(image.shape       )       )       )

										return normalize(UpperCamelCase__							,					mean=UpperCamelCase__							,					std=UpperCamelCase__							,					**UpperCamelCase__       )







					def   UpperCAmelCase__       (     self       :   str							,					UpperCamelCase__       :   ImageInput							,					UpperCamelCase__       :   Optional[str] = None							,					UpperCamelCase__       :   bool = None							,					UpperCamelCase__       :   Optional[bool] = None							,					UpperCamelCase__       :   Optional[int] = None							,					UpperCamelCase__       :   Optional[Dict[str, int]] = None							,					UpperCamelCase__       :   Optional[Union[str, TensorType]] = None							,					UpperCamelCase__       :   ChannelDimension = ChannelDimension.FIRST							,					**UpperCamelCase__       :   Union[str, Any]							,					):






										'''simple docstring'''






										lowercase_  							=			do_normalize if do_normalize is not None else self.do_normalize
										lowercase_  							=			do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
										lowercase_  							=			patch_size if patch_size is not None else self.patch_size
										lowercase_  							=			max_patches if max_patches is not None else self.max_patches
										lowercase_  							=			self.is_vqa

										if kwargs.get("""data_format"""							,					UpperCamelCase__       ) is not None:
															raise ValueError("""data_format is not an accepted input as the outputs are """       )

										lowercase_  							=			make_list_of_images(UpperCamelCase__       )

										if not valid_images(UpperCamelCase__       ):
															raise ValueError(
															    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
															    """torch.Tensor, tf.Tensor or jax.ndarray."""       )

										# PIL RGBA images are converted to RGB
										if do_convert_rgb:
															lowercase_  							=			[convert_to_rgb(UpperCamelCase__       ) for image in images]

										# All transformations expect numpy arrays.
										lowercase_  							=			[to_numpy_array(UpperCamelCase__       ) for image in images]

										if is_vqa:
															if header_text is None:
																				raise ValueError("""A header text must be provided for VQA models."""       )
															lowercase_  							=			kwargs.pop("""font_bytes"""							,					UpperCamelCase__       )
															lowercase_  							=			kwargs.pop("""font_path"""							,					UpperCamelCase__       )

															if isinstance(UpperCamelCase__							,					UpperCamelCase__       ):
																				lowercase_  							=			[header_text] * len(UpperCamelCase__       )

															lowercase_  							=			[
															    render_header(UpperCamelCase__							,					header_text[i]							,					font_bytes=UpperCamelCase__							,					font_path=UpperCamelCase__       )
															    for i, image in enumerate(UpperCamelCase__       )
															]

										if do_normalize:
															lowercase_  							=			[self.normalize(image=UpperCamelCase__       ) for image in images]

										# convert to torch tensor and permute
										lowercase_  							=			[
										    self.extract_flattened_patches(image=UpperCamelCase__							,					max_patches=UpperCamelCase__							,					patch_size=UpperCamelCase__       )
										    for image in images
										]

										# create attention mask in numpy
										lowercase_  							=			[(image.sum(axis=-1       ) != 0).astype(np.floataa       ) for image in images]

										lowercase_  							=			BatchFeature(
										    data={"""flattened_patches""": images, """attention_mask""": attention_masks}							,					tensor_type=UpperCamelCase__       )

										return encoded_outputs


