






"""simple docstring"""





import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


UpperCamelCase					=     logging.get_logger(__name__)  # pylint: disable=invalid-name

UpperCamelCase					=     """
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = \"a shark\"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
        ```
"""







@dataclass
class 						_a  (		lowercase_       ):





   '''simple docstring'''






   UpperCamelCase__     	=							42







class 						_a  (		lowercase_       ):





   '''simple docstring'''






   def __init__(       self					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, )			->   Tuple:




          '''simple docstring'''




          super().__init__()

          self.register_modules(
              prior=UpperCAmelCase_					, text_encoder=UpperCAmelCase_					, tokenizer=UpperCAmelCase_					, scheduler=UpperCAmelCase_					, renderer=UpperCAmelCase_					, )





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_)			->   Tuple:




          '''simple docstring'''




          if latents is None:
                 lowercase__:							int         =     randn_tensor(UpperCAmelCase_					, generator=UpperCAmelCase_					, device=UpperCAmelCase_					, dtype=UpperCAmelCase_)
          else:
                 if latents.shape != shape:
                        raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""")
                 lowercase__:							str         =     latents.to(UpperCAmelCase_)

          lowercase__:							Optional[int]         =     latents * scheduler.init_noise_sigma
          return latents





   def __lowercase							(       self					, UpperCAmelCase_=0)			->   Tuple:




          '''simple docstring'''




          if is_accelerate_available():
                 from accelerate import cpu_offload
          else:
                 raise ImportError("Please install accelerate via `pip install accelerate`")

          lowercase__:							Tuple         =     torch.device(F"""cuda:{gpu_id}""")

          lowercase__:							List[str]         =     [self.text_encoder, self.prior]
          for cpu_offloaded_model in models:
                 if cpu_offloaded_model is not None:
                        cpu_offload(UpperCAmelCase_					, UpperCAmelCase_)





   def __lowercase							(       self					, UpperCAmelCase_=0)			->   List[str]:




          '''simple docstring'''




          if is_accelerate_available() and is_accelerate_version(">="					, "0.17.0.dev0"):
                 from accelerate import cpu_offload_with_hook
          else:
                 raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")

          lowercase__:							Tuple         =     torch.device(F"""cuda:{gpu_id}""")

          if self.device.type != "cpu":
                 self.to("cpu"					, silence_dtype_warnings=UpperCAmelCase_)
                 torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

          lowercase__:							Union[str, Any]         =     None
          for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
                 lowercase__    ,      lowercase__:							Tuple         =     cpu_offload_with_hook(UpperCAmelCase_					, UpperCAmelCase_					, prev_module_hook=UpperCAmelCase_)

          if self.safety_checker is not None:
                 lowercase__    ,      lowercase__:							str         =     cpu_offload_with_hook(self.safety_checker					, UpperCAmelCase_					, prev_module_hook=UpperCAmelCase_)

          # We'll offload the last model manually.
          lowercase__:							Dict         =     hook





   @property
   def __lowercase							(       self)			->   Dict:




          '''simple docstring'''




          if self.device != torch.device("meta") or not hasattr(self.text_encoder					, "_hf_hook"):
                 return self.device
          for module in self.text_encoder.modules():
                 if (
                     hasattr(UpperCAmelCase_					, "_hf_hook")
                     and hasattr(module._hf_hook					, "execution_device")
                     and module._hf_hook.execution_device is not None
                 ):
                        return torch.device(module._hf_hook.execution_device)
          return self.device





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, )			->   Dict:




          '''simple docstring'''




          len(UpperCAmelCase_) if isinstance(UpperCAmelCase_					, UpperCAmelCase_) else 1

          # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
          lowercase__:							Optional[Any]         =     0
          # get prompt text embeddings
          lowercase__:							List[Any]         =     self.tokenizer(
              UpperCAmelCase_					, padding="max_length"					, max_length=self.tokenizer.model_max_length					, truncation=UpperCAmelCase_					, return_tensors="pt"					, )
          lowercase__:							Optional[int]         =     text_inputs.input_ids
          lowercase__:							List[Any]         =     self.tokenizer(UpperCAmelCase_					, padding="longest"					, return_tensors="pt").input_ids

          if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(UpperCAmelCase_					, UpperCAmelCase_):
                 lowercase__:							Union[str, Any]         =     self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
                 logger.warning(
                     "The following part of your input was truncated because CLIP can only handle sequences up to"
                     F""" {self.tokenizer.model_max_length} tokens: {removed_text}""")

          lowercase__:							Union[str, Any]         =     self.text_encoder(text_input_ids.to(UpperCAmelCase_))
          lowercase__:							str         =     text_encoder_output.text_embeds

          lowercase__:							Tuple         =     prompt_embeds.repeat_interleave(UpperCAmelCase_					, dim=0)
          # in Shap-E it normalize the prompt_embeds and then later rescale it
          lowercase__:							Any         =     prompt_embeds / torch.linalg.norm(UpperCAmelCase_					, dim=-1					, keepdim=UpperCAmelCase_)

          if do_classifier_free_guidance:
                 lowercase__:							str         =     torch.zeros_like(UpperCAmelCase_)

                 # For classifier free guidance, we need to do two forward passes.
                 # Here we concatenate the unconditional and text embeddings into a single batch
                 # to avoid doing two forward passes
                 lowercase__:							List[Any]         =     torch.cat([negative_prompt_embeds, prompt_embeds])

          # Rescale the features to have unit variance
          lowercase__:							str         =     math.sqrt(prompt_embeds.shape[1]) * prompt_embeds

          return prompt_embeds





   @torch.no_grad()
   @replace_example_docstring(UpperCAmelCase_)
   def __call__(       self					, UpperCAmelCase_					, UpperCAmelCase_ = 1					, UpperCAmelCase_ = 25					, UpperCAmelCase_ = None					, UpperCAmelCase_ = None					, UpperCAmelCase_ = 4.0					, UpperCAmelCase_ = 64					, UpperCAmelCase_ = "pil"					, UpperCAmelCase_ = True					, )			->   Union[str, Any]:




          '''simple docstring'''




          if isinstance(UpperCAmelCase_					, UpperCAmelCase_):
                 lowercase__:							List[str]         =     1
          elif isinstance(UpperCAmelCase_					, UpperCAmelCase_):
                 lowercase__:							List[str]         =     len(UpperCAmelCase_)
          else:
                 raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase_)}""")

          lowercase__:							Tuple         =     self._execution_device

          lowercase__:							int         =     batch_size * num_images_per_prompt

          lowercase__:							List[Any]         =     guidance_scale > 1.0
          lowercase__:							str         =     self._encode_prompt(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_)

          # prior

          self.scheduler.set_timesteps(UpperCAmelCase_					, device=UpperCAmelCase_)
          lowercase__:							Optional[int]         =     self.scheduler.timesteps

          lowercase__:							Optional[Any]         =     self.prior.config.num_embeddings
          lowercase__:							List[Any]         =     self.prior.config.embedding_dim

          lowercase__:							Optional[Any]         =     self.prepare_latents(
              (batch_size, num_embeddings * embedding_dim)					, prompt_embeds.dtype					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, self.scheduler					, )

          # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
          lowercase__:							Tuple         =     latents.reshape(latents.shape[0]					, UpperCAmelCase_					, UpperCAmelCase_)

          for i, t in enumerate(self.progress_bar(UpperCAmelCase_)):
                 # expand the latents if we are doing classifier free guidance
                 lowercase__:							Optional[Any]         =     torch.cat([latents] * 2) if do_classifier_free_guidance else latents
                 lowercase__:							Dict         =     self.scheduler.scale_model_input(UpperCAmelCase_					, UpperCAmelCase_)

                 lowercase__:							int         =     self.prior(
                     UpperCAmelCase_					, timestep=UpperCAmelCase_					, proj_embedding=UpperCAmelCase_					, ).predicted_image_embedding

                 # remove the variance
                 lowercase__    ,      lowercase__:							List[str]         =     noise_pred.split(
                     scaled_model_input.shape[2]					, dim=2)  # batch_size, num_embeddings, embedding_dim

                 if do_classifier_free_guidance is not None:
                        lowercase__    ,      lowercase__:							List[str]         =     noise_pred.chunk(2)
                        lowercase__:							Any         =     noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

                 lowercase__:							List[Any]         =     self.scheduler.step(
                     UpperCAmelCase_					, timestep=UpperCAmelCase_					, sample=UpperCAmelCase_					, ).prev_sample

          if output_type == "latent":
                 return ShapEPipelineOutput(images=UpperCAmelCase_)

          lowercase__:							int         =     []
          for i, latent in enumerate(UpperCAmelCase_):
                 lowercase__:							Dict         =     self.renderer.decode(
                     latent[None, :]					, UpperCAmelCase_					, size=UpperCAmelCase_					, ray_batch_size=4_096					, n_coarse_samples=64					, n_fine_samples=128					, )
                 images.append(UpperCAmelCase_)

          lowercase__:							Tuple         =     torch.stack(UpperCAmelCase_)

          if output_type not in ["np", "pil"]:
                 raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}""")

          lowercase__:							List[str]         =     images.cpu().numpy()

          if output_type == "pil":
                 lowercase__:							Optional[int]         =     [self.numpy_to_pil(UpperCAmelCase_) for image in images]

          # Offload last model to CPU
          if hasattr(self					, "final_offload_hook") and self.final_offload_hook is not None:
                 self.final_offload_hook.offload()

          if not return_dict:
                 return (images,)

          return ShapEPipelineOutput(images=UpperCAmelCase_)














"""simple docstring"""





UpperCamelCase					=     float("""inf""")







class 						_a  :





   '''simple docstring'''






   def __init__(       self					, UpperCAmelCase_)			->   List[str]:




          '''simple docstring'''




          lowercase__:							Optional[Any]         =     [0] * n
          lowercase__:							Dict         =     [0] * n
          lowercase__:							List[Any]         =     [0] * n
          lowercase__:							str         =     [[] for _ in range(UpperCAmelCase_)]





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_=0)			->   Optional[int]:




          '''simple docstring'''




          self.adj[a].append([b, len(self.adj[b]), c, 0])
          self.adj[b].append([a, len(self.adj[a]) - 1, rcap, 0])





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_)			->   Union[str, Any]:




          '''simple docstring'''




          if vertex == sink or not flow:
                 return flow

          for i in range(self.ptr[vertex]					, len(self.adj[vertex])):
                 lowercase__:							Optional[Any]         =     self.adj[vertex][i]
                 if self.lvl[e[0]] == self.lvl[vertex] + 1:
                        lowercase__:							Optional[int]         =     self.depth_first_search(e[0]					, UpperCAmelCase_					, min(UpperCAmelCase_					, e[2] - e[3]))
                        if p:
                               self.adj[vertex][i][3] += p
                               self.adj[e[0]][e[1]][3] -= p
                               return p
                 lowercase__:							int         =     self.ptr[vertex] + 1
          return 0





   def __lowercase							(       self					, UpperCAmelCase_					, UpperCAmelCase_)			->   str:




          '''simple docstring'''




          lowercase__    ,      lowercase__:							Union[str, Any]         =     0, source
          for l in range(31):  # noqa: E741  l = 30 maybe faster for random data
                 while True:
                        lowercase__    ,      lowercase__:							Union[str, Any]         =     [0] * len(self.q), [0] * len(self.q)
                        lowercase__    ,      lowercase__    ,      lowercase__:							str         =     0, 1, 1
                        while qi < qe and not self.lvl[sink]:
                               lowercase__:							Tuple         =     self.q[qi]
                               qi += 1
                               for e in self.adj[v]:
                                      if not self.lvl[e[0]] and (e[2] - e[3]) >> (30 - l):
                                             lowercase__:							Optional[int]         =     e[0]
                                             qe += 1
                                             lowercase__:							str         =     self.lvl[v] + 1

                        lowercase__:							List[str]         =     self.depth_first_search(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_)
                        while p:
                               flow += p
                               lowercase__:							Any         =     self.depth_first_search(UpperCAmelCase_					, UpperCAmelCase_					, UpperCAmelCase_)

                        if not self.lvl[sink]:
                               break

          return flow
UpperCamelCase					=     Dinic(10)
UpperCamelCase					=     0
UpperCamelCase					=     9
for vertex in range(1, 5):
  graph.add_edge(source, vertex, 1)
for vertex in range(5, 9):
  graph.add_edge(vertex, sink, 1)
for vertex in range(1, 5):
  graph.add_edge(vertex, vertex + 4, 1)

# Now we can know that is the maximum flow(source -> sink)
print(graph.max_flow(source, sink))






