'''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  							="\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = \"a shark\"\n\n        >>> images = pipe(\n        ...     prompt,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")\n        ```\n"




@dataclass
class 					a__   (     UpperCAmelCase__				):
     lowerCamelCase						:  Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]




class 					a__   (     UpperCAmelCase__				):






     def __init__(				self	:	Dict						,       a	:	PriorTransformer						,       a	:	CLIPTextModelWithProjection						,       a	:	CLIPTokenizer						,       a	:	HeunDiscreteScheduler						,       a	:	ShapERenderer						,       ):





         """simple docstring"""



         super().__init__()

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






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict						,       a	:	List[Any]						,       a	:	str						,       a	:	Tuple						,       a	:	Any						,       a	:	Optional[int]						,       a	:	List[Any]					):





         """simple docstring"""



         if latents is None:
             __lowerCamelCase						=						randn_tensor(a						,       generator=a						,       device=a						,       dtype=a					)
         else:
             if latents.shape != shape:
                 raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}"""					)
             __lowerCamelCase						=						latents.to(a					)

         __lowerCamelCase						=						latents * scheduler.init_noise_sigma
         return latents






     def      SCREAMING_SNAKE_CASE__     (				self	:	Union[str, Any]						,       a	:	int=0					):





         """simple docstring"""



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

         __lowerCamelCase						=						torch.device(f"""cuda:{gpu_id}"""					)

         __lowerCamelCase						=						[self.text_encoder, self.prior]
         for cpu_offloaded_model in models:
             if cpu_offloaded_model is not None:
                 cpu_offload(a						,       a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	int						,       a	:	str=0					):





         """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.'''					)

         __lowerCamelCase						=						torch.device(f"""cuda:{gpu_id}"""					)

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

         __lowerCamelCase						=						None
         for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
             __lowerCamelCase			,						__lowerCamelCase						=						cpu_offload_with_hook(a						,       a						,       prev_module_hook=a					)

         if self.safety_checker is not None:
             __lowerCamelCase			,						__lowerCamelCase						=						cpu_offload_with_hook(self.safety_checker						,       a						,       prev_module_hook=a					)

         # We'll offload the last model manually.
         __lowerCamelCase						=						hook






     @property
     def      SCREAMING_SNAKE_CASE__     (				self	:	Tuple					):





         """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(a						,       '''_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      SCREAMING_SNAKE_CASE__     (				self	:	Optional[int]						,       a	:	List[Any]						,       a	:	Union[str, Any]						,       a	:	int						,       a	:	int						,       ):





         """simple docstring"""



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

         # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
         __lowerCamelCase						=						0
         # get prompt text embeddings
         __lowerCamelCase						=						self.tokenizer(
             a						,       padding='''max_length'''						,       max_length=self.tokenizer.model_max_length						,       truncation=a						,       return_tensors='''pt'''						,       )
         __lowerCamelCase						=						text_inputs.input_ids
         __lowerCamelCase						=						self.tokenizer(a						,       padding='''longest'''						,       return_tensors='''pt'''					).input_ids

         if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(a						,       a					):
             __lowerCamelCase						=						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}"""					)

         __lowerCamelCase						=						self.text_encoder(text_input_ids.to(a					)					)
         __lowerCamelCase						=						text_encoder_output.text_embeds

         __lowerCamelCase						=						prompt_embeds.repeat_interleave(a						,       dim=0					)
         # in Shap-E it normalize the prompt_embeds and then later rescale it
         __lowerCamelCase						=						prompt_embeds / torch.linalg.norm(a						,       dim=-1						,       keepdim=a					)

         if do_classifier_free_guidance:
             __lowerCamelCase						=						torch.zeros_like(a					)

             # 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
             __lowerCamelCase						=						torch.cat([negative_prompt_embeds, prompt_embeds]					)

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

         return prompt_embeds






     @torch.no_grad()
     @replace_example_docstring(a					)
     def __call__(				self	:	str						,       a	:	str						,       a	:	int = 1						,       a	:	int = 25						,       a	:	Optional[Union[torch.Generator, List[torch.Generator]]] = None						,       a	:	Optional[torch.FloatTensor] = None						,       a	:	float = 4.0						,       a	:	int = 64						,       a	:	Optional[str] = "pil"						,       a	:	bool = True						,       ):





         """simple docstring"""



         if isinstance(a						,       a					):
             __lowerCamelCase						=						1
         elif isinstance(a						,       a					):
             __lowerCamelCase						=						len(a					)
         else:
             raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(a					)}"""					)

         __lowerCamelCase						=						self._execution_device

         __lowerCamelCase						=						batch_size * num_images_per_prompt

         __lowerCamelCase						=						guidance_scale > 1.0
         __lowerCamelCase						=						self._encode_prompt(a						,       a						,       a						,       a					)

         # prior

         self.scheduler.set_timesteps(a						,       device=a					)
         __lowerCamelCase						=						self.scheduler.timesteps

         __lowerCamelCase						=						self.prior.config.num_embeddings
         __lowerCamelCase						=						self.prior.config.embedding_dim

         __lowerCamelCase						=						self.prepare_latents(
             (batch_size, num_embeddings * embedding_dim)						,       prompt_embeds.dtype						,       a						,       a						,       a						,       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
         __lowerCamelCase						=						latents.reshape(latents.shape[0]						,       a						,       a					)

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

             __lowerCamelCase						=						self.prior(
                 a						,       timestep=a						,       proj_embedding=a						,       ).predicted_image_embedding

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

             if do_classifier_free_guidance is not None:
                 __lowerCamelCase			,						__lowerCamelCase						=						noise_pred.chunk(2					)
                 __lowerCamelCase						=						noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

             __lowerCamelCase						=						self.scheduler.step(
                 a						,       timestep=a						,       sample=a						,       ).prev_sample

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

         __lowerCamelCase						=						[]
         for i, latent in enumerate(a					):
             __lowerCamelCase						=						self.renderer.decode(
                 latent[None, :]						,       a						,       size=a						,       ray_batch_size=40_96						,       n_coarse_samples=64						,       n_fine_samples=1_28						,       )
             images.append(a					)

         __lowerCamelCase						=						torch.stack(a					)

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

         __lowerCamelCase						=						images.cpu().numpy()

         if output_type == "pil":
             __lowerCamelCase						=						[self.numpy_to_pil(a					) 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=a					)

'''simple docstring'''




from __future__ import annotations






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )			->					tuple[float, float]:
    assert (
        c % greatest_common_divisor(UpperCamelCase__       ,						UpperCamelCase__       ) == 0
    )  # greatest_common_divisor(a,b) function implemented below
    ((__lowerCamelCase)			,						(__lowerCamelCase)			,						(__lowerCamelCase))						=						extended_gcd(UpperCamelCase__       ,						UpperCamelCase__       )  # extended_gcd(a,b) function implemented below
    __lowerCamelCase						=						c / d
    return (r * x, r * y)






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__ = 2       )			->					None:
    ((__lowerCamelCase)			,						(__lowerCamelCase))						=						diophantine(UpperCamelCase__       ,						UpperCamelCase__       ,						UpperCamelCase__       )  # Initial value
    __lowerCamelCase						=						greatest_common_divisor(UpperCamelCase__       ,						UpperCamelCase__       )
    __lowerCamelCase						=						a // d
    __lowerCamelCase						=						b // d

    for i in range(UpperCamelCase__       ):
        __lowerCamelCase						=						xa + i * q
        __lowerCamelCase						=						ya - i * p
        print(UpperCamelCase__       ,						UpperCamelCase__       )






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       )			->					int:
    if a < b:
        __lowerCamelCase			,						__lowerCamelCase						=						b, a

    while a % b != 0:
        __lowerCamelCase			,						__lowerCamelCase						=						b, a % b

    return b






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       )			->					tuple[int, int, int]:
    assert a >= 0 and b >= 0

    if b == 0:
        __lowerCamelCase			,						__lowerCamelCase			,						__lowerCamelCase						=						a, 1, 0
    else:
        ((__lowerCamelCase)			,						(__lowerCamelCase)			,						(__lowerCamelCase))						=						extended_gcd(UpperCamelCase__       ,						a % b       )
        __lowerCamelCase						=						q
        __lowerCamelCase						=						p - q * (a // b)

    assert a % d == 0 and b % d == 0
    assert d == a * x + b * y

    return (d, x, y)


if __name__ == "__main__":
  from doctest import testmod

  testmod(name="diophantine", verbose=True)
  testmod(name="diophantine_all_soln", verbose=True)
  testmod(name="extended_gcd", verbose=True)
  testmod(name="greatest_common_divisor", verbose=True)
