





from typing import SupportsIndex

import numpy as np
from scipy.ndimage import convolve







def    UpperCAmelCase				(  _lowerCamelCase   :	np.ndarray      , _lowerCamelCase   :	np.ndarray      , _lowerCamelCase   :	np.ndarray  ):





						'''simple docstring'''


						SCREAMING_SNAKE_CASE__  :					int =       np.stack((horizontal_flow, vertical_flow)      , 2  )

						# Create a grid of all pixel coordinates and subtract the flow to get the
						# target pixels coordinates
						SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       np.stack(
						    np.meshgrid(np.arange(0      , image.shape[1]  )      , np.arange(0      , image.shape[0]  )  )      , 2  )
						SCREAMING_SNAKE_CASE__  :					List[Any] =       np.round(grid - flow  ).astype(np.intaa  )

						# Find the locations outside of the original image
						SCREAMING_SNAKE_CASE__  :					Optional[Any] =       (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]]  ))
						SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       0

						SCREAMING_SNAKE_CASE__  :					Optional[int] =       image[grid[:, :, 1], grid[:, :, 0]]

						# Set pixels at invalid locations to 0
						SCREAMING_SNAKE_CASE__  :					List[Any] =       0

						return warped







def    UpperCAmelCase				(  _lowerCamelCase   :	np.ndarray      , _lowerCamelCase   :	np.ndarray      , _lowerCamelCase   :	SupportsIndex      , _lowerCamelCase   :	float | None = None      , ):





						'''simple docstring'''


						if alpha is None:
												SCREAMING_SNAKE_CASE__  :					Dict =       0.1

						# Initialize flow
						SCREAMING_SNAKE_CASE__  :					Dict =       np.zeros_like(_lowerCamelCase  )
						SCREAMING_SNAKE_CASE__  :					List[str] =       np.zeros_like(_lowerCamelCase  )

						# Prepare kernels for the calculation of the derivatives and the average velocity
						SCREAMING_SNAKE_CASE__  :					Optional[Any] =       np.array([[-1, 1], [-1, 1]]  ) * 0.2_5
						SCREAMING_SNAKE_CASE__  :					Dict =       np.array([[-1, -1], [1, 1]]  ) * 0.2_5
						SCREAMING_SNAKE_CASE__  :					Dict =       np.array([[1, 1], [1, 1]]  ) * 0.2_5
						SCREAMING_SNAKE_CASE__  :					Optional[int] =       np.array(
						    [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]]  )

						# Iteratively refine the flow
						for _ in range(_lowerCamelCase  ):
												SCREAMING_SNAKE_CASE__  :					List[str] =       warp(_lowerCamelCase      , _lowerCamelCase      , _lowerCamelCase  )
												SCREAMING_SNAKE_CASE__  :					List[str] =       convolve(_lowerCamelCase      , _lowerCamelCase  ) + convolve(_lowerCamelCase      , _lowerCamelCase  )
												SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       convolve(_lowerCamelCase      , _lowerCamelCase  ) + convolve(_lowerCamelCase      , _lowerCamelCase  )
												SCREAMING_SNAKE_CASE__  :					Tuple =       convolve(_lowerCamelCase      , _lowerCamelCase  ) + convolve(_lowerCamelCase      , -kernel_t  )

												SCREAMING_SNAKE_CASE__  :					List[Any] =       convolve(_lowerCamelCase      , _lowerCamelCase  )
												SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       convolve(_lowerCamelCase      , _lowerCamelCase  )

												# This updates the flow as proposed in the paper (Step 12)
												SCREAMING_SNAKE_CASE__  :					str =       (
												    derivative_x * avg_horizontal_velocity
												    + derivative_y * avg_vertical_velocity
												    + derivative_t
												)
												SCREAMING_SNAKE_CASE__  :					Dict =       update / (alpha**2 + derivative_x**2 + derivative_y**2)

												SCREAMING_SNAKE_CASE__  :					Any =       avg_horizontal_velocity - derivative_x * update
												SCREAMING_SNAKE_CASE__  :					Dict =       avg_vertical_velocity - derivative_y * update

						return horizontal_flow, vertical_flow


if __name__ == "__main__":
				import doctest

				doctest.testmod()






from typing import List, Optional, Tuple, Union

import torch

from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput



class  _a  (					lowercase__				):






							"""simple docstring"""

							def __init__(   self					:  Dict				,						a					:  str				,						a					:  Optional[Any]     )						->Any:
													super().__init__()
													self.register_modules(unet=a				,						scheduler=a     )






							@torch.no_grad()
							def __call__(   self					:  int				,						a					:  int = 1				,						a					:  Optional[Union[torch.Generator, List[torch.Generator]]] = None				,						a					:  int = 10_00				,						a					:  Optional[str] = "pil"				,						a					:  bool = True				,						)						->Union[ImagePipelineOutput, Tuple]:
													# Sample gaussian noise to begin loop
													if isinstance(self.unet.config.sample_size				,						a     ):
																			SCREAMING_SNAKE_CASE__  :					int =       (
																			    batch_size,
																			    self.unet.config.in_channels,
																			    self.unet.config.sample_size,
																			    self.unet.config.sample_size,
																			)
													else:
																			SCREAMING_SNAKE_CASE__  :					Dict =       (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size)

													if self.device.type == "mps":
																			# randn does not work reproducibly on mps
																			SCREAMING_SNAKE_CASE__  :					List[str] =       randn_tensor(a				,						generator=a     )
																			SCREAMING_SNAKE_CASE__  :					Optional[int] =       image.to(self.device     )
													else:
																			SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       randn_tensor(a				,						generator=a				,						device=self.device     )

													# set step values
													self.scheduler.set_timesteps(a     )

													for t in self.progress_bar(self.scheduler.timesteps     ):
																			# 1. predict noise model_output
																			SCREAMING_SNAKE_CASE__  :					Optional[Any] =       self.unet(a				,						a     ).sample

																			# 2. compute previous image: x_t -> x_t-1
																			SCREAMING_SNAKE_CASE__  :					Tuple =       self.scheduler.step(a				,						a				,						a				,						generator=a     ).prev_sample

													SCREAMING_SNAKE_CASE__  :					List[str] =       (image / 2 + 0.5).clamp(0				,						1     )
													SCREAMING_SNAKE_CASE__  :					Tuple =       image.cpu().permute(0				,						2				,						3				,						1     ).numpy()
													if output_type == "pil":
																			SCREAMING_SNAKE_CASE__  :					Dict =       self.numpy_to_pil(a     )

													if not return_dict:
																			return (image,)

													return ImagePipelineOutput(images=a     )