





"""simple docstring"""





from math import acos, sin
from typing import List, Tuple, Union

import numpy as np
import torch
from PIL import Image

from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel
class 		SCREAMING_SNAKE_CASE_				(     snake_case__ ):
				"""simple docstring"""
				__snake_case :							Optional[int]									=		["""vqvae"""]




				def __init__(  self	:Tuple    ,     __lowercase	:AutoencoderKL    ,     __lowercase	:UNetaDConditionModel    ,     __lowercase	:Mel    ,     __lowercase	:Union[DDIMScheduler, DDPMScheduler]    ,     ):
											super().__init__()
											self.register_modules(unet=__lowercase    ,     scheduler=__lowercase    ,     mel=__lowercase    ,     vqvae=__lowercase      )




				def        __lowercase	(  self	:Dict      ):
											return 50 if isinstance(self.scheduler    ,     __lowercase      ) else 1000




				@torch.no_grad()
				def __call__(  self	:int    ,     __lowercase	:int = 1    ,     __lowercase	:str = None    ,     __lowercase	:np.ndarray = None    ,     __lowercase	:int = 0    ,     __lowercase	:int = 0    ,     __lowercase	:int = None    ,     __lowercase	:torch.Generator = None    ,     __lowercase	:float = 0    ,     __lowercase	:float = 0    ,     __lowercase	:torch.Generator = None    ,     __lowercase	:float = 0    ,     __lowercase	:torch.Tensor = None    ,     __lowercase	:torch.Tensor = None    ,     __lowercase	:List[Any]=True    ,     ):
											__lowerCamelCase   :   List[str]       =steps or self.get_default_steps()
											self.scheduler.set_timesteps(__lowercase      )
											__lowerCamelCase   :   Tuple       =step_generator or generator
											# For backwards compatibility
											if type(self.unet.config.sample_size      ) == int:
																		__lowerCamelCase   :   Union[str, Any]       =(self.unet.config.sample_size, self.unet.config.sample_size)
											if noise is None:
																		__lowerCamelCase   :   str       =randn_tensor(
																		    (
																		        batch_size,
																		        self.unet.config.in_channels,
																		        self.unet.config.sample_size[0],
																		        self.unet.config.sample_size[1],
																		    )    ,     generator=__lowercase    ,     device=self.device    ,     )
											__lowerCamelCase   :   Union[str, Any]       =noise
											__lowerCamelCase   :   Optional[Any]       =None

											if audio_file is not None or raw_audio is not None:
																		self.mel.load_audio(__lowercase    ,     __lowercase      )
																		__lowerCamelCase   :   Any       =self.mel.audio_slice_to_image(__lowercase      )
																		__lowerCamelCase   :   Any       =np.frombuffer(input_image.tobytes()    ,     dtype='''uint8'''      ).reshape(
																		    (input_image.height, input_image.width)      )
																		__lowerCamelCase   :   Any       =(input_image / 255) * 2 - 1
																		__lowerCamelCase   :   Optional[int]       =torch.tensor(input_image[np.newaxis, :, :]    ,     dtype=torch.float      ).to(self.device      )

																		if self.vqvae is not None:
																									__lowerCamelCase   :   str       =self.vqvae.encode(torch.unsqueeze(__lowercase    ,     0      )      ).latent_dist.sample(
																									    generator=__lowercase      )[0]
																									__lowerCamelCase   :   Any       =self.vqvae.config.scaling_factor * input_images

																		if start_step > 0:
																									__lowerCamelCase   :   Optional[Any]       =self.scheduler.add_noise(__lowercase    ,     __lowercase    ,     self.scheduler.timesteps[start_step - 1]      )

																		__lowerCamelCase   :   List[str]       =(
																		    self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
																		)
																		__lowerCamelCase   :   Tuple       =int(mask_start_secs * pixels_per_second      )
																		__lowerCamelCase   :   Optional[int]       =int(mask_end_secs * pixels_per_second      )
																		__lowerCamelCase   :   Union[str, Any]       =self.scheduler.add_noise(__lowercase    ,     __lowercase    ,     torch.tensor(self.scheduler.timesteps[start_step:]      )      )

											for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]      )      ):
																		if isinstance(self.unet    ,     __lowercase      ):
																									__lowerCamelCase   :   Tuple       =self.unet(__lowercase    ,     __lowercase    ,     __lowercase      )['''sample''']
																		else:
																									__lowerCamelCase   :   Optional[Any]       =self.unet(__lowercase    ,     __lowercase      )['''sample''']

																		if isinstance(self.scheduler    ,     __lowercase      ):
																									__lowerCamelCase   :   Dict       =self.scheduler.step(
																									    model_output=__lowercase    ,     timestep=__lowercase    ,     sample=__lowercase    ,     eta=__lowercase    ,     generator=__lowercase    ,     )['''prev_sample''']
																		else:
																									__lowerCamelCase   :   Union[str, Any]       =self.scheduler.step(
																									    model_output=__lowercase    ,     timestep=__lowercase    ,     sample=__lowercase    ,     generator=__lowercase    ,     )['''prev_sample''']

																		if mask is not None:
																									if mask_start > 0:
																																__lowerCamelCase   :   List[Any]       =mask[:, step, :, :mask_start]
																									if mask_end > 0:
																																__lowerCamelCase   :   List[str]       =mask[:, step, :, -mask_end:]

											if self.vqvae is not None:
																		# 0.18215 was scaling factor used in training to ensure unit variance
																		__lowerCamelCase   :   Dict       =1 / self.vqvae.config.scaling_factor * images
																		__lowerCamelCase   :   str       =self.vqvae.decode(__lowercase      )['''sample''']

											__lowerCamelCase   :   str       =(images / 2 + 0.5).clamp(0    ,     1      )
											__lowerCamelCase   :   Any       =images.cpu().permute(0    ,     2    ,     3    ,     1      ).numpy()
											__lowerCamelCase   :   int       =(images * 255).round().astype('''uint8'''      )
											__lowerCamelCase   :   List[Any]       =list(
											    (Image.fromarray(_[:, :, 0]      ) for _ in images)
											    if images.shape[3] == 1
											    else (Image.fromarray(__lowercase    ,     mode='''RGB'''      ).convert('''L'''      ) for _ in images)      )

											__lowerCamelCase   :   List[str]       =[self.mel.image_to_audio(__lowercase      ) for _ in images]
											if not return_dict:
																		return images, (self.mel.get_sample_rate(), audios)

											return BaseOutput(**AudioPipelineOutput(np.array(__lowercase      )[:, np.newaxis, :]      )    ,     **ImagePipelineOutput(__lowercase      )      )




				@torch.no_grad()
				def        __lowercase	(  self	:str    ,     __lowercase	:List[Image.Image]    ,     __lowercase	:int = 50      ):
											assert isinstance(self.scheduler    ,     __lowercase      )
											self.scheduler.set_timesteps(__lowercase      )
											__lowerCamelCase   :   Optional[Any]       =np.array(
											    [np.frombuffer(image.tobytes()    ,     dtype='''uint8'''      ).reshape((1, image.height, image.width)      ) for image in images]      )
											__lowerCamelCase   :   Optional[int]       =(sample / 255) * 2 - 1
											__lowerCamelCase   :   List[str]       =torch.Tensor(__lowercase      ).to(self.device      )

											for t in self.progress_bar(torch.flip(self.scheduler.timesteps    ,     (0,)      )      ):
																		__lowerCamelCase   :   List[str]       =t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
																		__lowerCamelCase   :   Union[str, Any]       =self.scheduler.alphas_cumprod[t]
																		__lowerCamelCase   :   Optional[int]       =(
																		    self.scheduler.alphas_cumprod[prev_timestep]
																		    if prev_timestep >= 0
																		    else self.scheduler.final_alpha_cumprod
																		)
																		__lowerCamelCase   :   Dict       =1 - alpha_prod_t
																		__lowerCamelCase   :   Optional[Any]       =self.unet(__lowercase    ,     __lowercase      )['''sample''']
																		__lowerCamelCase   :   int       =(1 - alpha_prod_t_prev) ** 0.5 * model_output
																		__lowerCamelCase   :   Union[str, Any]       =(sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
																		__lowerCamelCase   :   Tuple       =sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

											return sample




				@staticmethod
				def        __lowercase	(  __lowercase	:torch.Tensor    ,     __lowercase	:torch.Tensor    ,     __lowercase	:float      ):
											__lowerCamelCase   :   Tuple       =acos(torch.dot(torch.flatten(__lowercase      )    ,     torch.flatten(__lowercase      )      ) / torch.norm(__lowercase      ) / torch.norm(__lowercase      )      )
											return sin((1 - alpha) * theta      ) * xa / sin(__lowercase      ) + sin(alpha * theta      ) * xa / sin(__lowercase      )











"""simple docstring"""





from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
							import torch


_UpperCamelCase					      =   logging.get_logger(__name__)
class 		SCREAMING_SNAKE_CASE_				(     snake_case__ ):
				"""simple docstring"""
				__snake_case :							Optional[int]									=		["""pixel_values"""]




				def __init__(  self	:Optional[Any]    ,     __lowercase	:bool = True    ,     __lowercase	:Optional[Dict[str, int]] = None    ,     __lowercase	:PILImageResampling = PILImageResampling.BILINEAR    ,     __lowercase	:bool = True    ,     __lowercase	:Dict[str, int] = None    ,     __lowercase	:bool = True    ,     __lowercase	:Union[int, float] = 1 / 255    ,     __lowercase	:bool = True    ,     __lowercase	:Optional[Union[float, List[float]]] = None    ,     __lowercase	:Optional[Union[float, List[float]]] = None    ,     **__lowercase	:Tuple    ,     ):
											super().__init__(**__lowercase      )
											__lowerCamelCase   :   int       =size if size is not None else {'''shortest_edge''': 256}
											__lowerCamelCase   :   int       =get_size_dict(__lowercase    ,     default_to_square=__lowercase      )
											__lowerCamelCase   :   Optional[Any]       =crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
											__lowerCamelCase   :   List[str]       =get_size_dict(__lowercase    ,     param_name='''crop_size'''      )
											__lowerCamelCase   :   List[str]       =do_resize
											__lowerCamelCase   :   Optional[Any]       =size
											__lowerCamelCase   :   Tuple       =resample
											__lowerCamelCase   :   int       =do_center_crop
											__lowerCamelCase   :   Optional[Any]       =crop_size
											__lowerCamelCase   :   int       =do_rescale
											__lowerCamelCase   :   str       =rescale_factor
											__lowerCamelCase   :   int       =do_normalize
											__lowerCamelCase   :   Union[str, Any]       =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
											__lowerCamelCase   :   Tuple       =image_std if image_std is not None else IMAGENET_STANDARD_STD




				def        __lowercase	(  self	:Union[str, Any]    ,     __lowercase	:np.ndarray    ,     __lowercase	:Dict[str, int]    ,     __lowercase	:PILImageResampling = PILImageResampling.BICUBIC    ,     __lowercase	:Optional[Union[str, ChannelDimension]] = None    ,     **__lowercase	:str    ,     ):
											__lowerCamelCase   :   Tuple       =get_size_dict(__lowercase    ,     default_to_square=__lowercase      )
											if "shortest_edge" not in size:
																		raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'      )
											__lowerCamelCase   :   List[Any]       =get_resize_output_image_size(__lowercase    ,     size=size['''shortest_edge''']    ,     default_to_square=__lowercase      )
											return resize(__lowercase    ,     size=__lowercase    ,     resample=__lowercase    ,     data_format=__lowercase    ,     **__lowercase      )




				def        __lowercase	(  self	:Union[str, Any]    ,     __lowercase	:np.ndarray    ,     __lowercase	:Dict[str, int]    ,     __lowercase	:Optional[Union[str, ChannelDimension]] = None    ,     **__lowercase	:int    ,     ):
											__lowerCamelCase   :   List[Any]       =get_size_dict(__lowercase      )
											if "height" not in size or "width" not in size:
																		raise ValueError(f'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}'      )
											return center_crop(__lowercase    ,     size=(size['''height'''], size['''width'''])    ,     data_format=__lowercase    ,     **__lowercase      )




				def        __lowercase	(  self	:str    ,     __lowercase	:np.ndarray    ,     __lowercase	:float    ,     __lowercase	:Optional[Union[str, ChannelDimension]] = None    ,     **__lowercase	:str      ):
											return rescale(__lowercase    ,     scale=__lowercase    ,     data_format=__lowercase    ,     **__lowercase      )




				def        __lowercase	(  self	:Union[str, Any]    ,     __lowercase	:np.ndarray    ,     __lowercase	:Union[float, List[float]]    ,     __lowercase	:Union[float, List[float]]    ,     __lowercase	:Optional[Union[str, ChannelDimension]] = None    ,     **__lowercase	:Union[str, Any]    ,     ):
											return normalize(__lowercase    ,     mean=__lowercase    ,     std=__lowercase    ,     data_format=__lowercase    ,     **__lowercase      )




				def        __lowercase	(  self	:List[str]    ,     __lowercase	:ImageInput    ,     __lowercase	:Optional[bool] = None    ,     __lowercase	:Dict[str, int] = None    ,     __lowercase	:PILImageResampling = None    ,     __lowercase	:bool = None    ,     __lowercase	:Dict[str, int] = None    ,     __lowercase	:Optional[bool] = None    ,     __lowercase	:Optional[float] = None    ,     __lowercase	:Optional[bool] = None    ,     __lowercase	:Optional[Union[float, List[float]]] = None    ,     __lowercase	:Optional[Union[float, List[float]]] = None    ,     __lowercase	:Optional[Union[str, TensorType]] = None    ,     __lowercase	:Union[str, ChannelDimension] = ChannelDimension.FIRST    ,     **__lowercase	:Optional[Any]    ,     ):
											__lowerCamelCase   :   Optional[Any]       =do_resize if do_resize is not None else self.do_resize
											__lowerCamelCase   :   Optional[Any]       =size if size is not None else self.size
											__lowerCamelCase   :   List[str]       =get_size_dict(__lowercase    ,     default_to_square=__lowercase      )
											__lowerCamelCase   :   List[str]       =resample if resample is not None else self.resample
											__lowerCamelCase   :   Optional[int]       =do_center_crop if do_center_crop is not None else self.do_center_crop
											__lowerCamelCase   :   Any       =crop_size if crop_size is not None else self.crop_size
											__lowerCamelCase   :   Union[str, Any]       =get_size_dict(__lowercase    ,     param_name='''crop_size'''      )
											__lowerCamelCase   :   Any       =do_rescale if do_rescale is not None else self.do_rescale
											__lowerCamelCase   :   List[str]       =rescale_factor if rescale_factor is not None else self.rescale_factor
											__lowerCamelCase   :   List[Any]       =do_normalize if do_normalize is not None else self.do_normalize
											__lowerCamelCase   :   List[Any]       =image_mean if image_mean is not None else self.image_mean
											__lowerCamelCase   :   int       =image_std if image_std is not None else self.image_std

											__lowerCamelCase   :   int       =make_list_of_images(__lowercase      )

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

											if do_resize and size is None:
																		raise ValueError('''Size must be specified if do_resize is True.'''      )

											if do_center_crop and crop_size is None:
																		raise ValueError('''Crop size must be specified if do_center_crop is True.'''      )

											if do_rescale and rescale_factor is None:
																		raise ValueError('''Rescale factor must be specified if do_rescale is True.'''      )

											if do_normalize and (image_mean is None or image_std is None):
																		raise ValueError('''Image mean and std must be specified if do_normalize is True.'''      )

											# All transformations expect numpy arrays.
											__lowerCamelCase   :   int       =[to_numpy_array(__lowercase      ) for image in images]

											if do_resize:
																		__lowerCamelCase   :   Tuple       =[self.resize(image=__lowercase    ,     size=__lowercase    ,     resample=__lowercase      ) for image in images]

											if do_center_crop:
																		__lowerCamelCase   :   Any       =[self.center_crop(image=__lowercase    ,     size=__lowercase      ) for image in images]

											if do_rescale:
																		__lowerCamelCase   :   Optional[Any]       =[self.rescale(image=__lowercase    ,     scale=__lowercase      ) for image in images]

											if do_normalize:
																		__lowerCamelCase   :   Tuple       =[self.normalize(image=__lowercase    ,     mean=__lowercase    ,     std=__lowercase      ) for image in images]

											__lowerCamelCase   :   List[str]       =[to_channel_dimension_format(__lowercase    ,     __lowercase      ) for image in images]

											__lowerCamelCase   :   Union[str, Any]       ={'''pixel_values''': images}
											return BatchFeature(data=__lowercase    ,     tensor_type=__lowercase      )




				def        __lowercase	(  self	:Dict    ,     __lowercase	:Dict    ,     __lowercase	:List[Tuple] = None      ):
											__lowerCamelCase   :   Dict       =outputs.logits

											# Resize logits and compute semantic segmentation maps
											if target_sizes is not None:
																		if len(__lowercase      ) != len(__lowercase      ):
																									raise ValueError(
																									    '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''      )

																		if is_torch_tensor(__lowercase      ):
																									__lowerCamelCase   :   Optional[int]       =target_sizes.numpy()

																		__lowerCamelCase   :   List[Any]       =[]

																		for idx in range(len(__lowercase      )      ):
																									__lowerCamelCase   :   Optional[int]       =torch.nn.functional.interpolate(
																									    logits[idx].unsqueeze(dim=0      )    ,     size=target_sizes[idx]    ,     mode='''bilinear'''    ,     align_corners=__lowercase      )
																									__lowerCamelCase   :   Union[str, Any]       =resized_logits[0].argmax(dim=0      )
																									semantic_segmentation.append(__lowercase      )
											else:
																		__lowerCamelCase   :   Union[str, Any]       =logits.argmax(dim=1      )
																		__lowerCamelCase   :   Optional[int]       =[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]      )]

											return semantic_segmentation




