



"""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


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

__A   :							Any										=   '''
    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"""
			UpperCamelCase__			      =	42



class 			_a (					a__):
			"""simple docstring"""



			def __init__(		self     :    Tuple				,   __UpperCamelCase     :    Tuple				,   __UpperCamelCase     :    Any				,   __UpperCamelCase     :    Tuple				,   __UpperCamelCase     :    Optional[Any]				,   __UpperCamelCase     :    Optional[int]				,   )->Optional[int]:
							super().__init__()

							self.register_modules(
							    prior=lowerCAmelCase__				,   image_encoder=lowerCAmelCase__				,   image_processor=lowerCAmelCase__				,   scheduler=lowerCAmelCase__				,   renderer=lowerCAmelCase__				,   )



			def  lowercase__						(		self     :    Any				,   __UpperCamelCase     :    int				,   __UpperCamelCase     :    Any				,   __UpperCamelCase     :    Dict				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    List[str]   )->str:
							if latents is None:
											_UpperCAmelCase					=    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}'   )
											_UpperCAmelCase					=    latents.to(lowerCAmelCase__   )

							_UpperCAmelCase					=    latents * scheduler.init_noise_sigma
							return latents



			def  lowercase__						(		self     :    Optional[int]				,   __UpperCamelCase     :    Tuple=0   )->List[str]:
							if is_accelerate_available():
											from accelerate import cpu_offload
							else:
											raise ImportError('''Please install accelerate via `pip install accelerate`'''   )

							_UpperCAmelCase					=    torch.device(F'cuda:{gpu_id}'   )

							_UpperCAmelCase					=    [self.image_encoder, self.prior]
							for cpu_offloaded_model in models:
											if cpu_offloaded_model is not None:
															cpu_offload(lowerCAmelCase__				,   lowerCAmelCase__   )



			@property
			def  lowercase__						(		self     :    Union[str, Any]   )->int:
							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  lowercase__						(		self     :    str				,   __UpperCamelCase     :    str				,   __UpperCamelCase     :    Any				,   __UpperCamelCase     :    Optional[Any]				,   __UpperCamelCase     :    Optional[int]				,   )->str:
							if isinstance(lowerCAmelCase__				,   lowerCAmelCase__   ) and isinstance(image[0]				,   torch.Tensor   ):
											_UpperCAmelCase					=    torch.cat(lowerCAmelCase__				,   axis=0   ) if image[0].ndim == 4 else torch.stack(lowerCAmelCase__				,   axis=0   )

							if not isinstance(lowerCAmelCase__				,   torch.Tensor   ):
											_UpperCAmelCase					=    self.image_processor(lowerCAmelCase__				,   return_tensors='''pt'''   ).pixel_values[0].unsqueeze(0   )

							_UpperCAmelCase					=    image.to(dtype=self.image_encoder.dtype				,   device=lowerCAmelCase__   )

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

							_UpperCAmelCase					=    image_embeds.repeat_interleave(lowerCAmelCase__				,   dim=0   )

							if do_classifier_free_guidance:
											_UpperCAmelCase					=    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
											_UpperCAmelCase					=    torch.cat([negative_image_embeds, image_embeds]   )

							return image_embeds



			@torch.no_grad()
			@replace_example_docstring(lowerCAmelCase__   )
			def __call__(		self     :    int				,   __UpperCamelCase     :    Tuple				,   __UpperCamelCase     :    int = 1				,   __UpperCamelCase     :    List[Any] = 2_5				,   __UpperCamelCase     :    str = None				,   __UpperCamelCase     :    int = None				,   __UpperCamelCase     :    Tuple = 4.0				,   __UpperCamelCase     :    str = 6_4				,   __UpperCamelCase     :    List[Any] = "pil"				,   __UpperCamelCase     :    Any = True				,   )->List[Any]:

							if isinstance(lowerCAmelCase__				,   PIL.Image.Image   ):
											_UpperCAmelCase					=    1
							elif isinstance(lowerCAmelCase__				,   torch.Tensor   ):
											_UpperCAmelCase					=    image.shape[0]
							elif isinstance(lowerCAmelCase__				,   lowerCAmelCase__   ) and isinstance(image[0]				,   (torch.Tensor, PIL.Image.Image)   ):
											_UpperCAmelCase					=    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__   )}'   )

							_UpperCAmelCase					=    self._execution_device

							_UpperCAmelCase					=    batch_size * num_images_per_prompt

							_UpperCAmelCase					=    guidance_scale > 1.0
							_UpperCAmelCase					=    self._encode_image(lowerCAmelCase__				,   lowerCAmelCase__				,   lowerCAmelCase__				,   lowerCAmelCase__   )

							# prior

							self.scheduler.set_timesteps(lowerCAmelCase__				,   device=lowerCAmelCase__   )
							_UpperCAmelCase					=    self.scheduler.timesteps

							_UpperCAmelCase					=    self.prior.config.num_embeddings
							_UpperCAmelCase					=    self.prior.config.embedding_dim

							_UpperCAmelCase					=    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
							_UpperCAmelCase					=    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
											_UpperCAmelCase					=    torch.cat([latents] * 2   ) if do_classifier_free_guidance else latents
											_UpperCAmelCase					=    self.scheduler.scale_model_input(lowerCAmelCase__				,   lowerCAmelCase__   )

											_UpperCAmelCase					=    self.prior(
											    lowerCAmelCase__				,   timestep=lowerCAmelCase__				,   proj_embedding=lowerCAmelCase__				,   ).predicted_image_embedding

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

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

											_UpperCAmelCase					=    self.scheduler.step(
											    lowerCAmelCase__				,   timestep=lowerCAmelCase__				,   sample=lowerCAmelCase__				,   ).prev_sample

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

							_UpperCAmelCase					=    []
							for i, latent in enumerate(lowerCAmelCase__   ):
											print()
											_UpperCAmelCase					=    self.renderer.decode(
											    latent[None, :]				,   lowerCAmelCase__				,   size=lowerCAmelCase__				,   ray_batch_size=4_0_9_6				,   n_coarse_samples=6_4				,   n_fine_samples=1_2_8				,   )

											images.append(lowerCAmelCase__   )

							_UpperCAmelCase					=    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}'   )

							_UpperCAmelCase					=    images.cpu().numpy()

							if output_type == "pil":
											_UpperCAmelCase					=    [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"""


from collections import UserDict
from typing import Union

import numpy as np
import requests

from ..utils import (
    add_end_docstrings,
    logging,
)
from .audio_classification import ffmpeg_read
from .base import PIPELINE_INIT_ARGS, Pipeline


__A   :							List[str]										=   logging.get_logger(__name__)
@add_end_docstrings(lowerCAmelCase)
class 			_a (					lowerCAmelCase):
			"""simple docstring"""



			def __init__(		self     :    Union[str, Any]				,   **__UpperCamelCase     :    Optional[Any]   )->List[Any]:
							super().__init__(**__UpperCamelCase   )

							if self.framework != "pt":
											raise ValueError(F'The {self.__class__} is only available in PyTorch.'   )
							# No specific FOR_XXX available yet



			def __call__(		self     :    Optional[int]				,   __UpperCamelCase     :    Union[np.ndarray, bytes, str]				,   **__UpperCamelCase     :    Tuple   )->List[str]:
							return super().__call__(__UpperCamelCase				,   **__UpperCamelCase   )



			def  lowercase__						(		self     :    Any				,   **__UpperCamelCase     :    Any   )->Union[str, Any]:
							_UpperCAmelCase					=    {}
							if "candidate_labels" in kwargs:
											_UpperCAmelCase					=    kwargs['''candidate_labels''']
							if "hypothesis_template" in kwargs:
											_UpperCAmelCase					=    kwargs['''hypothesis_template''']

							return preprocess_params, {}, {}



			def  lowercase__						(		self     :    Optional[int]				,   __UpperCamelCase     :    Union[str, Any]				,   __UpperCamelCase     :    List[Any]=None				,   __UpperCamelCase     :    Tuple="This is a sound of {}."   )->int:
							if isinstance(__UpperCamelCase				,   __UpperCamelCase   ):
											if audio.startswith('''http://'''   ) or audio.startswith('''https://'''   ):
															# We need to actually check for a real protocol, otherwise it's impossible to use a local file
															# like http_huggingface_co.png
															_UpperCAmelCase					=    requests.get(__UpperCamelCase   ).content
											else:
															with open(__UpperCamelCase				,   '''rb'''   ) as f:
																			_UpperCAmelCase					=    f.read()

							if isinstance(__UpperCamelCase				,   __UpperCamelCase   ):
											_UpperCAmelCase					=    ffmpeg_read(__UpperCamelCase				,   self.feature_extractor.sampling_rate   )

							if not isinstance(__UpperCamelCase				,   np.ndarray   ):
											raise ValueError('''We expect a numpy ndarray as input'''   )
							if len(audio.shape   ) != 1:
											raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline'''   )

							_UpperCAmelCase					=    self.feature_extractor(
							    [audio]				,   sampling_rate=self.feature_extractor.sampling_rate				,   return_tensors='''pt'''   )
							_UpperCAmelCase					=    candidate_labels
							_UpperCAmelCase					=    [hypothesis_template.format(__UpperCamelCase   ) for x in candidate_labels]
							_UpperCAmelCase					=    self.tokenizer(__UpperCamelCase				,   return_tensors=self.framework				,   padding=__UpperCamelCase   )
							_UpperCAmelCase					=    [text_inputs]
							return inputs



			def  lowercase__						(		self     :    Union[str, Any]				,   __UpperCamelCase     :    Optional[int]   )->Any:
							_UpperCAmelCase					=    model_inputs.pop('''candidate_labels'''   )
							_UpperCAmelCase					=    model_inputs.pop('''text_inputs'''   )
							if isinstance(text_inputs[0]				,   __UpperCamelCase   ):
											_UpperCAmelCase					=    text_inputs[0]
							else:
											# Batching case.
											_UpperCAmelCase					=    text_inputs[0][0]

							_UpperCAmelCase					=    self.model(**__UpperCamelCase				,   **__UpperCamelCase   )

							_UpperCAmelCase					=    {
							    '''candidate_labels''': candidate_labels,
							    '''logits''': outputs.logits_per_audio,
							}
							return model_outputs



			def  lowercase__						(		self     :    List[str]				,   __UpperCamelCase     :    Any   )->List[Any]:
							_UpperCAmelCase					=    model_outputs.pop('''candidate_labels'''   )
							_UpperCAmelCase					=    model_outputs['''logits'''][0]

							if self.framework == "pt":
											_UpperCAmelCase					=    logits.softmax(dim=0   )
											_UpperCAmelCase					=    probs.tolist()
							else:
											raise ValueError('''`tf` framework not supported.'''   )

							_UpperCAmelCase					=    [
							    {'''score''': score, '''label''': candidate_label}
							    for score, candidate_label in sorted(zip(__UpperCamelCase				,   __UpperCamelCase   )				,   key=lambda __UpperCamelCase   : -x[0]   )
							]
							return result



