
"""simple docstring"""






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

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

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


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

_lowercase							=				'''
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

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

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

        >>> guidance_scale = 3.0
        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"
        >>> image = load_image(image_url).convert("RGB")

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

        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")
        ```
'''

@dataclass
class 					__a     ( __a       ):



							'''simple docstring'''







							_lowerCamelCase					:			Union[PIL.Image.Image, np.ndarray]





class 					__a     ( __a       ):



							'''simple docstring'''







							def __init__(     self  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    )			->							Optional[int]:




										'''simple docstring'''
										super().__init__()

										self.register_modules(
										    prior=_lowerCamelCase  ,    image_encoder=_lowerCamelCase  ,    image_processor=_lowerCamelCase  ,    scheduler=_lowerCamelCase  ,    renderer=_lowerCamelCase  ,    )
							def   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase       )			->							List[Any]:




										'''simple docstring'''
										if latents is None:
													__lowercase       =       randn_tensor(_lowerCamelCase  ,    generator=_lowerCamelCase  ,    device=_lowerCamelCase  ,    dtype=_lowerCamelCase       )
										else:
													if latents.shape != shape:
																raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''       )
													__lowercase       =       latents.to(_lowerCamelCase       )

										__lowercase       =       latents * scheduler.init_noise_sigma
										return latents
							def   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase=0       )			->							Any:




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

										__lowercase       =       torch.device(f'''cuda:{gpu_id}'''       )

										__lowercase       =       [self.image_encoder, self.prior]
										for cpu_offloaded_model in models:
													if cpu_offloaded_model is not None:
																cpu_offload(_lowerCamelCase  ,    _lowerCamelCase       )
							@property
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Optional[int]:




										'''simple docstring'''
										if self.device != torch.device("meta"       ) or not hasattr(self.image_encoder  ,    "_hf_hook"       ):
													return self.device
										for module in self.image_encoder.modules():
													if (
													    hasattr(_lowerCamelCase  ,    "_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  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    )			->							Optional[Any]:




										'''simple docstring'''
										if isinstance(_lowerCamelCase  ,    _lowerCamelCase       ) and isinstance(image[0]  ,    torch.Tensor       ):
													__lowercase       =       torch.cat(_lowerCamelCase  ,    axis=0       ) if image[0].ndim == 4 else torch.stack(_lowerCamelCase  ,    axis=0       )

										if not isinstance(_lowerCamelCase  ,    torch.Tensor       ):
													__lowercase       =       self.image_processor(_lowerCamelCase  ,    return_tensors="pt"       ).pixel_values[0].unsqueeze(0       )

										__lowercase       =       image.to(dtype=self.image_encoder.dtype  ,    device=_lowerCamelCase       )

										__lowercase       =       self.image_encoder(_lowerCamelCase       )["last_hidden_state"]
										__lowercase       =       image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

										__lowercase       =       image_embeds.repeat_interleave(_lowerCamelCase  ,    dim=0       )

										if do_classifier_free_guidance:
													__lowercase       =       torch.zeros_like(_lowerCamelCase       )

													# 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       =       torch.cat([negative_image_embeds, image_embeds]       )

										return image_embeds





							@torch.no_grad()
							@replace_example_docstring(_lowerCamelCase       )
							def __call__(     self  ,    _lowerCamelCase  ,    _lowerCamelCase = 1  ,    _lowerCamelCase = 25  ,    _lowerCamelCase = None  ,    _lowerCamelCase = None  ,    _lowerCamelCase = 4.0  ,    _lowerCamelCase = 64  ,    _lowerCamelCase = "pil"  ,    _lowerCamelCase = True  ,    )			->							Tuple:




										'''simple docstring'''

										if isinstance(_lowerCamelCase  ,    PIL.Image.Image       ):
													__lowercase       =       1
										elif isinstance(_lowerCamelCase  ,    torch.Tensor       ):
													__lowercase       =       image.shape[0]
										elif isinstance(_lowerCamelCase  ,    _lowerCamelCase       ) and isinstance(image[0]  ,    (torch.Tensor, PIL.Image.Image)       ):
													__lowercase       =       len(_lowerCamelCase       )
										else:
													raise ValueError(
													    f'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_lowerCamelCase       )}'''       )

										__lowercase       =       self._execution_device

										__lowercase       =       batch_size * num_images_per_prompt

										__lowercase       =       guidance_scale > 1.0
										__lowercase       =       self._encode_image(_lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase       )

										# prior

										self.scheduler.set_timesteps(_lowerCamelCase  ,    device=_lowerCamelCase       )
										__lowercase       =       self.scheduler.timesteps

										__lowercase       =       self.prior.config.num_embeddings
										__lowercase       =       self.prior.config.embedding_dim

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

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

													__lowercase       =       self.prior(
													    _lowerCamelCase  ,    timestep=_lowerCamelCase  ,    proj_embedding=_lowerCamelCase  ,    ).predicted_image_embedding

													# remove the variance
													__lowercase   ,					__lowercase       =       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       =       noise_pred.chunk(2       )
																__lowercase       =       noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

													__lowercase       =       self.scheduler.step(
													    _lowerCamelCase  ,    timestep=_lowerCamelCase  ,    sample=_lowerCamelCase  ,    ).prev_sample

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

										__lowercase       =       []
										for i, latent in enumerate(_lowerCamelCase       ):
													print()
													__lowercase       =       self.renderer.decode(
													    latent[None, :]  ,    _lowerCamelCase  ,    size=_lowerCamelCase  ,    ray_batch_size=4_096  ,    n_coarse_samples=64  ,    n_fine_samples=128  ,    )

													images.append(_lowerCamelCase       )

										__lowercase       =       torch.stack(_lowerCamelCase       )

										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       =       images.cpu().numpy()

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







"""simple docstring"""






import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
from .feature_extraction_wavaveca import WavaVecaFeatureExtractor
from .tokenization_wavaveca import WavaVecaCTCTokenizer

class 					__a     ( __a       ):



							'''simple docstring'''







							_lowerCamelCase					:			List[Any]          =   """Wav2Vec2FeatureExtractor"""
							_lowerCamelCase					:			Any          =   """AutoTokenizer"""
							def __init__(     self  ,    _lowerCamelCase  ,    _lowerCamelCase       )			->							List[str]:




										'''simple docstring'''
										super().__init__(_lowerCamelCase  ,    _lowerCamelCase       )
										__lowercase       =       self.feature_extractor
										__lowercase       =       False
							@classmethod
							def   SCREAMING_SNAKE_CASE						(     cls  ,    _lowerCamelCase  ,    **_lowerCamelCase       )			->							Any:




										'''simple docstring'''
										try:
													return super().from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )
										except OSError:
													warnings.warn(
													    f'''Loading a tokenizer inside {cls.__name__} from a config that does not'''
													    " include a `tokenizer_class` attribute is deprecated and will be "
													    "removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`"
													    " attribute to either your `config.json` or `tokenizer_config.json` "
													    "file to suppress this warning: "  ,    _lowerCamelCase  ,    )

													__lowercase       =       WavaVecaFeatureExtractor.from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )
													__lowercase       =       WavaVecaCTCTokenizer.from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )

													return cls(feature_extractor=_lowerCamelCase  ,    tokenizer=_lowerCamelCase       )
							def __call__(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							List[Any]:




										'''simple docstring'''
										# For backward compatibility
										if self._in_target_context_manager:
													return self.current_processor(*_lowerCamelCase  ,    **_lowerCamelCase       )

										if "raw_speech" in kwargs:
													warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."       )
													__lowercase       =       kwargs.pop("raw_speech"       )
										else:
													__lowercase       =       kwargs.pop("audio"  ,    _lowerCamelCase       )
										__lowercase       =       kwargs.pop("sampling_rate"  ,    _lowerCamelCase       )
										__lowercase       =       kwargs.pop("text"  ,    _lowerCamelCase       )
										if len(_lowerCamelCase       ) > 0:
													__lowercase       =       args[0]
													__lowercase       =       args[1:]

										if audio is None and text is None:
													raise ValueError("You need to specify either an `audio` or `text` input to process."       )

										if audio is not None:
													__lowercase       =       self.feature_extractor(_lowerCamelCase  ,    *_lowerCamelCase  ,    sampling_rate=_lowerCamelCase  ,    **_lowerCamelCase       )
										if text is not None:
													__lowercase       =       self.tokenizer(_lowerCamelCase  ,    **_lowerCamelCase       )

										if text is None:
													return inputs
										elif audio is None:
													return encodings
										else:
													__lowercase       =       encodings["input_ids"]
													return inputs
							def   SCREAMING_SNAKE_CASE						(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							List[str]:




										'''simple docstring'''
										# For backward compatibility
										if self._in_target_context_manager:
													return self.current_processor.pad(*_lowerCamelCase  ,    **_lowerCamelCase       )

										__lowercase       =       kwargs.pop("input_features"  ,    _lowerCamelCase       )
										__lowercase       =       kwargs.pop("labels"  ,    _lowerCamelCase       )
										if len(_lowerCamelCase       ) > 0:
													__lowercase       =       args[0]
													__lowercase       =       args[1:]

										if input_features is not None:
													__lowercase       =       self.feature_extractor.pad(_lowerCamelCase  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )
										if labels is not None:
													__lowercase       =       self.tokenizer.pad(_lowerCamelCase  ,    **_lowerCamelCase       )

										if labels is None:
													return input_features
										elif input_features is None:
													return labels
										else:
													__lowercase       =       labels["input_ids"]
													return input_features
							def   SCREAMING_SNAKE_CASE						(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							Optional[int]:




										'''simple docstring'''
										return self.tokenizer.batch_decode(*_lowerCamelCase  ,    **_lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self  ,    *_lowerCamelCase  ,    **_lowerCamelCase       )			->							Dict:




										'''simple docstring'''
										return self.tokenizer.decode(*_lowerCamelCase  ,    **_lowerCamelCase       )





							@contextmanager
							def   SCREAMING_SNAKE_CASE						(     self       )			->							str:




										'''simple docstring'''
										warnings.warn(
										    "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
										    "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
										    "your audio inputs, or in a separate call."       )
										__lowercase       =       True
										__lowercase       =       self.tokenizer
										yield
										__lowercase       =       self.feature_extractor
										__lowercase       =       False





