
"""simple docstring"""

from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block
@dataclass
class    _UpperCAmelCase							(						SCREAMING_SNAKE_CASE_							):
      __SCREAMING_SNAKE_CASE      :							torch.FloatTensor

class    _UpperCAmelCase							(						SCREAMING_SNAKE_CASE_   ,	SCREAMING_SNAKE_CASE_							):




      @register_to_config
      def __init__(							self      ,				lowercase_ = None      ,				lowercase_ = 3      ,				lowercase_ = 3      ,				lowercase_ = False      ,				lowercase_ = "positional"      ,				lowercase_ = 0      ,				lowercase_ = True      ,				lowercase_ = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")      ,				lowercase_ = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")      ,				lowercase_ = (2_2_4, 4_4_8, 6_7_2, 8_9_6)      ,				lowercase_ = 2      ,				lowercase_ = 1      ,				lowercase_ = 1      ,				lowercase_ = "conv"      ,				lowercase_ = "conv"      ,				lowercase_ = "silu"      ,				lowercase_ = 8      ,				lowercase_ = 3_2      ,				lowercase_ = 1E-5      ,				lowercase_ = "default"      ,				lowercase_ = True      ,				lowercase_ = None      ,				lowercase_ = None      ,				)  ->    List[Any]:
          super().__init__()

          UpperCAmelCase  	=    sample_size
          UpperCAmelCase  	=    block_out_channels[0] * 4

          # Check inputs
          if len(lowercase_							) != len(lowercase_							):
              raise ValueError(
                  F"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."							)

          if len(lowercase_							) != len(lowercase_							):
              raise ValueError(
                  F"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."							)

          # input
          UpperCAmelCase  	=    nn.Convad(lowercase_      ,				block_out_channels[0]      ,				kernel_size=3      ,				padding=(1, 1)							)

          # time
          if time_embedding_type == "fourier":
              UpperCAmelCase  	=    GaussianFourierProjection(embedding_size=block_out_channels[0]      ,				scale=1_6							)
              UpperCAmelCase  	=    2 * block_out_channels[0]
          elif time_embedding_type == "positional":
              UpperCAmelCase  	=    Timesteps(block_out_channels[0]      ,				lowercase_      ,				lowercase_							)
              UpperCAmelCase  	=    block_out_channels[0]

          UpperCAmelCase  	=    TimestepEmbedding(lowercase_      ,				lowercase_							)

          # class embedding
          if class_embed_type is None and num_class_embeds is not None:
              UpperCAmelCase  	=    nn.Embedding(lowercase_      ,				lowercase_							)
          elif class_embed_type == "timestep":
              UpperCAmelCase  	=    TimestepEmbedding(lowercase_      ,				lowercase_							)
          elif class_embed_type == "identity":
              UpperCAmelCase  	=    nn.Identity(lowercase_      ,				lowercase_							)
          else:
              UpperCAmelCase  	=    None

          UpperCAmelCase  	=    nn.ModuleList([]							)
          UpperCAmelCase  	=    None
          UpperCAmelCase  	=    nn.ModuleList([]							)

          # down
          UpperCAmelCase  	=    block_out_channels[0]
          for i, down_block_type in enumerate(lowercase_							):
              UpperCAmelCase  	=    output_channel
              UpperCAmelCase  	=    block_out_channels[i]
              UpperCAmelCase  	=    i == len(lowercase_							) - 1

              UpperCAmelCase  	=    get_down_block(
                  lowercase_      ,				num_layers=lowercase_      ,				in_channels=lowercase_      ,				out_channels=lowercase_      ,				temb_channels=lowercase_      ,				add_downsample=not is_final_block      ,				resnet_eps=lowercase_      ,				resnet_act_fn=lowercase_      ,				resnet_groups=lowercase_      ,				attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel      ,				downsample_padding=lowercase_      ,				resnet_time_scale_shift=lowercase_      ,				downsample_type=lowercase_      ,				)
              self.down_blocks.append(lowercase_							)

          # mid
          UpperCAmelCase  	=    UNetMidBlockaD(
              in_channels=block_out_channels[-1]      ,				temb_channels=lowercase_      ,				resnet_eps=lowercase_      ,				resnet_act_fn=lowercase_      ,				output_scale_factor=lowercase_      ,				resnet_time_scale_shift=lowercase_      ,				attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]      ,				resnet_groups=lowercase_      ,				add_attention=lowercase_      ,				)

          # up
          UpperCAmelCase  	=    list(reversed(lowercase_							)							)
          UpperCAmelCase  	=    reversed_block_out_channels[0]
          for i, up_block_type in enumerate(lowercase_							):
              UpperCAmelCase  	=    output_channel
              UpperCAmelCase  	=    reversed_block_out_channels[i]
              UpperCAmelCase  	=    reversed_block_out_channels[min(i + 1      ,				len(lowercase_							) - 1							)]

              UpperCAmelCase  	=    i == len(lowercase_							) - 1

              UpperCAmelCase  	=    get_up_block(
                  lowercase_      ,				num_layers=layers_per_block + 1      ,				in_channels=lowercase_      ,				out_channels=lowercase_      ,				prev_output_channel=lowercase_      ,				temb_channels=lowercase_      ,				add_upsample=not is_final_block      ,				resnet_eps=lowercase_      ,				resnet_act_fn=lowercase_      ,				resnet_groups=lowercase_      ,				attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel      ,				resnet_time_scale_shift=lowercase_      ,				upsample_type=lowercase_      ,				)
              self.up_blocks.append(lowercase_							)
              UpperCAmelCase  	=    output_channel

          # out
          UpperCAmelCase  	=    norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4      ,				3_2							)
          UpperCAmelCase  	=    nn.GroupNorm(num_channels=block_out_channels[0]      ,				num_groups=lowercase_      ,				eps=lowercase_							)
          UpperCAmelCase  	=    nn.SiLU()
          UpperCAmelCase  	=    nn.Convad(block_out_channels[0]      ,				lowercase_      ,				kernel_size=3      ,				padding=1							)




      def 			a_					(							self      ,				lowercase_      ,				lowercase_      ,				lowercase_ = None      ,				lowercase_ = True      ,				)  ->    Union[UNetaDOutput, Tuple]:
          # 0. center input if necessary
          if self.config.center_input_sample:
              UpperCAmelCase  	=    2 * sample - 1.0

          # 1. time
          UpperCAmelCase  	=    timestep
          if not torch.is_tensor(lowercase_							):
              UpperCAmelCase  	=    torch.tensor([timesteps]      ,				dtype=torch.long      ,				device=sample.device							)
          elif torch.is_tensor(lowercase_							) and len(timesteps.shape							) == 0:
              UpperCAmelCase  	=    timesteps[None].to(sample.device							)

          # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
          UpperCAmelCase  	=    timesteps * torch.ones(sample.shape[0]      ,				dtype=timesteps.dtype      ,				device=timesteps.device							)

          UpperCAmelCase  	=    self.time_proj(lowercase_							)

          # timesteps does not contain any weights and will always return f32 tensors
          # but time_embedding might actually be running in fp16. so we need to cast here.
          # there might be better ways to encapsulate this.
          UpperCAmelCase  	=    t_emb.to(dtype=self.dtype							)
          UpperCAmelCase  	=    self.time_embedding(lowercase_							)

          if self.class_embedding is not None:
              if class_labels is None:
                  raise ValueError('class_labels should be provided when doing class conditioning'							)

              if self.config.class_embed_type == "timestep":
                  UpperCAmelCase  	=    self.time_proj(lowercase_							)

              UpperCAmelCase  	=    self.class_embedding(lowercase_							).to(dtype=self.dtype							)
              UpperCAmelCase  	=    emb + class_emb

          # 2. pre-process
          UpperCAmelCase  	=    sample
          UpperCAmelCase  	=    self.conv_in(lowercase_							)

          # 3. down
          UpperCAmelCase  	=    (sample,)
          for downsample_block in self.down_blocks:
              if hasattr(lowercase_      ,				'skip_conv'							):
                  UpperCAmelCase	,							UpperCAmelCase	,							UpperCAmelCase  	=    downsample_block(
                      hidden_states=lowercase_      ,				temb=lowercase_      ,				skip_sample=lowercase_							)
              else:
                  UpperCAmelCase	,							UpperCAmelCase  	=    downsample_block(hidden_states=lowercase_      ,				temb=lowercase_							)

              down_block_res_samples += res_samples

          # 4. mid
          UpperCAmelCase  	=    self.mid_block(lowercase_      ,				lowercase_							)

          # 5. up
          UpperCAmelCase  	=    None
          for upsample_block in self.up_blocks:
              UpperCAmelCase  	=    down_block_res_samples[-len(upsample_block.resnets							) :]
              UpperCAmelCase  	=    down_block_res_samples[: -len(upsample_block.resnets							)]

              if hasattr(lowercase_      ,				'skip_conv'							):
                  UpperCAmelCase	,							UpperCAmelCase  	=    upsample_block(lowercase_      ,				lowercase_      ,				lowercase_      ,				lowercase_							)
              else:
                  UpperCAmelCase  	=    upsample_block(lowercase_      ,				lowercase_      ,				lowercase_							)

        # 6. post-process
          UpperCAmelCase  	=    self.conv_norm_out(lowercase_							)
          UpperCAmelCase  	=    self.conv_act(lowercase_							)
          UpperCAmelCase  	=    self.conv_out(lowercase_							)

          if skip_sample is not None:
              sample += skip_sample

          if self.config.time_embedding_type == "fourier":
              UpperCAmelCase  	=    timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]							)))							)
              UpperCAmelCase  	=    sample / timesteps

          if not return_dict:
              return (sample,)

          return UNetaDOutput(sample=lowercase_							)





"""simple docstring"""

from typing import SupportsIndex

import numpy as np
from scipy.ndimage import convolve




def 			lowercase__  (    lowerCAmelCase :    np.ndarray       , lowerCAmelCase :    np.ndarray       , lowerCAmelCase :    np.ndarray       )       ->					np.ndarray:






    """simple docstring"""




    UpperCAmelCase  	=    np.stack((horizontal_flow, vertical_flow)       , 2       )

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

    # Find the locations outside of the original image
    UpperCAmelCase  	=    (grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]]       ))
    UpperCAmelCase  	=    0

    UpperCAmelCase  	=    image[grid[:, :, 1], grid[:, :, 0]]

    # Set pixels at invalid locations to 0
    UpperCAmelCase  	=    0

    return warped




def 			lowercase__  (    lowerCAmelCase :    np.ndarray       , lowerCAmelCase :    np.ndarray       , lowerCAmelCase :    SupportsIndex       , lowerCAmelCase :    float | None = None       , )       ->					tuple[np.ndarray, np.ndarray]:






    """simple docstring"""




    if alpha is None:
        UpperCAmelCase  	=    0.1

    # Initialize flow
    UpperCAmelCase  	=    np.zeros_like(lowerCAmelCase       )
    UpperCAmelCase  	=    np.zeros_like(lowerCAmelCase       )

    # Prepare kernels for the calculation of the derivatives and the average velocity
    UpperCAmelCase  	=    np.array([[-1, 1], [-1, 1]]       ) * 0.25
    UpperCAmelCase  	=    np.array([[-1, -1], [1, 1]]       ) * 0.25
    UpperCAmelCase  	=    np.array([[1, 1], [1, 1]]       ) * 0.25
    UpperCAmelCase  	=    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       ):
        UpperCAmelCase  	=    warp(lowerCAmelCase       , lowerCAmelCase       , lowerCAmelCase       )
        UpperCAmelCase  	=    convolve(lowerCAmelCase       , lowerCAmelCase       ) + convolve(lowerCAmelCase       , lowerCAmelCase       )
        UpperCAmelCase  	=    convolve(lowerCAmelCase       , lowerCAmelCase       ) + convolve(lowerCAmelCase       , lowerCAmelCase       )
        UpperCAmelCase  	=    convolve(lowerCAmelCase       , lowerCAmelCase       ) + convolve(lowerCAmelCase       , -kernel_t       )

        UpperCAmelCase  	=    convolve(lowerCAmelCase       , lowerCAmelCase       )
        UpperCAmelCase  	=    convolve(lowerCAmelCase       , lowerCAmelCase       )

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

        UpperCAmelCase  	=    avg_horizontal_velocity - derivative_x * update
        UpperCAmelCase  	=    avg_vertical_velocity - derivative_y * update

    return horizontal_flow, vertical_flow


if __name__ == "__main__":
   import doctest

   doctest.testmod()



