o
    pidI                     @   s   d dl mZmZmZmZmZmZmZ d dlZd dl	m
Z
mZ ddlmZmZ ddlmZmZ ddlmZ ddlmZ d	d
lmZmZ dZG dd deZdS )    )AnyCallableDictListOptionalTupleUnionN)CLIPTextModelWithProjectionCLIPTokenizer   )PipelineImageInputVaeImageProcessor)UVit2DModelVQModel)AmusedScheduler)replace_example_docstring   )DiffusionPipelineImagePipelineOutputa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import AmusedInpaintPipeline
        >>> from diffusers.utils import load_image

        >>> pipe = AmusedInpaintPipeline.from_pretrained(
        ...     "amused/amused-512", variant="fp16", torch_dtype=torch.float16
        ... )
        >>> pipe = pipe.to("cuda")

        >>> prompt = "fall mountains"
        >>> input_image = (
        ...     load_image(
        ...         "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1.jpg"
        ...     )
        ...     .resize((512, 512))
        ...     .convert("RGB")
        ... )
        >>> mask = (
        ...     load_image(
        ...         "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1_mask.png"
        ...     )
        ...     .resize((512, 512))
        ...     .convert("L")
        ... )
        >>> pipe(prompt, input_image, mask).images[0].save("out.png")
        ```
c                /       s  e Zd ZU eed< eed< eed< eed< eed< e	ed< dZ
dgZdedededede	f
 fdd	Ze ee	
	
	
				
		
	
	
	
	
			
		
			d*deeee ef  dedededededeeeee f  dee deej deej deej deej d eej d!ed"eeeeejgd
f  d#ed$eeeef  d%ed&eeef d'eeeeef ee f f(d(d)Z  Z S )+AmusedInpaintPipelineimage_processorvqvae	tokenizertext_encodertransformer	schedulerz text_encoder->transformer->vqvaec                    sn   t    | j|||||d dt| jjjd  | _t| jdd| _	t| jddddd| _
| jjdd	 d S )
N)r   r   r   r   r   r      F)vae_scale_factordo_normalizeT)r   r   do_binarizedo_convert_grayscale	do_resizelinear)masking_schedule)super__init__register_moduleslenr   configblock_out_channelsr   r   r   mask_processorr   register_to_config)selfr   r   r   r   r   	__class__ p/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/diffusers/pipelines/amused/pipeline_amused_inpaint.pyr%   K   s$   
zAmusedInpaintPipeline.__init__N      ?         $@r   pilT   r   r   r   r   promptimage
mask_imagestrengthnum_inference_stepsguidance_scalenegative_promptnum_images_per_prompt	generatorprompt_embedsencoder_hidden_statesnegative_prompt_embedsnegative_encoder_hidden_statesreturn_dictcallbackcallback_stepscross_attention_kwargs"micro_conditioning_aesthetic_scoremicro_conditioning_crop_coordtemperaturec           .   	   C   s  |
dur|du s|
du r|durt d|dur|du s$|du r(|dur(t d|du r0|
du s8|dur<|
dur<t dt|trD|g}|durMt|}n|
jd }|| }|
du r{| j|ddd| jjd	j| j	}| j
|ddd
}|j}
|jd }|
|d}
||dd}|dkr|du r|du rdgt| }t|tr|g}| j|ddd| jjd	j| j	}| j
|ddd
}|j}|jd }||d}||dd}t||
g}
t||g}| j|}|jdd \}}tj|||d |d |g| j	|jd}|d}||dkrd| n|d}| j||| j	 tt| jj| }t| jj| }| jjtjko<| jjj}|rE| j  | j|j| jj| j	dj }|j\}} }!}"| j!|d d "||!|"}| j#||| j$ || j$ }#|#"|#jd |!|"% |j&}#| jjj'||#< |#( |)  }$||dd}| j*|d}%t+|t| jjD ]x}&| jj|& }'|dkrt,|gd }(n|}(| j-|(||
||d})|dkr|).d\}*}+|*||+|*   })| jj/|)|'||	|$dj0}|&t| jjd ks|&d | jj1 dkr%|%2  |dur%|&| dkr%|&t3| jdd },||,|'| qW d   n	1 s2w   Y  |dkr?|}-n*| jj4|d||| j$ || j$ | jjj5fdj67dd}-| j8|-|}-|ri| j9  | :  |ss|-fS t;|-S )a  
        The call function to the pipeline for generation.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
            image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
                `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
                numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
                or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
                list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
                latents as `image`, but if passing latents directly it is not encoded again.
            mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
                `Image`, numpy array or tensor representing an image batch to mask `image`. White pixels in the mask
                are repainted while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a
                single channel (luminance) before use. If it's a numpy array or pytorch tensor, it should contain one
                color channel (L) instead of 3, so the expected shape for pytorch tensor would be `(B, 1, H, W)`, `(B,
                H, W)`, `(1, H, W)`, `(H, W)`. And for numpy array would be for `(B, H, W, 1)`, `(B, H, W)`, `(H, W,
                1)`, or `(H, W)`.
            strength (`float`, *optional*, defaults to 1.0):
                Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
                starting point and more noise is added the higher the `strength`. The number of denoising steps depends
                on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
                process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
                essentially ignores `image`.
            num_inference_steps (`int`, *optional*, defaults to 16):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, *optional*, defaults to 10.0):
                A higher guidance scale value encourages the model to generate images closely linked to the text
                `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide what to not include in image generation. If not defined, you need to
                pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`torch.Generator`, *optional*):
                A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
                generation deterministic.
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `prompt` input argument. A single vector from the
                pooled and projected final hidden states.
            encoder_hidden_states (`torch.Tensor`, *optional*):
                Pre-generated penultimate hidden states from the text encoder providing additional text conditioning.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
                not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
            negative_encoder_hidden_states (`torch.Tensor`, *optional*):
                Analogous to `encoder_hidden_states` for the positive prompt.
            output_type (`str`, *optional*, defaults to `"pil"`):
                The output format of the generated image. Choose between `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
                plain tuple.
            callback (`Callable`, *optional*):
                A function that calls every `callback_steps` steps during inference. The function is called with the
                following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
            callback_steps (`int`, *optional*, defaults to 1):
                The frequency at which the `callback` function is called. If not specified, the callback is called at
                every step.
            cross_attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
                [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            micro_conditioning_aesthetic_score (`int`, *optional*, defaults to 6):
                The targeted aesthetic score according to the laion aesthetic classifier. See
                https://laion.ai/blog/laion-aesthetics/ and the micro-conditioning section of
                https://arxiv.org/abs/2307.01952.
            micro_conditioning_crop_coord (`Tuple[int]`, *optional*, defaults to (0, 0)):
                The targeted height, width crop coordinates. See the micro-conditioning section of
                https://arxiv.org/abs/2307.01952.
            temperature (`Union[int, Tuple[int, int], List[int]]`, *optional*, defaults to (2, 0)):
                Configures the temperature scheduler on `self.scheduler` see `AmusedScheduler#set_timesteps`.

        Examples:

        Returns:
            [`~pipelines.pipeline_utils.ImagePipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.pipeline_utils.ImagePipelineOutput`] is returned, otherwise a
                `tuple` is returned where the first element is a list with the generated images.
        NzGpass either both `prompt_embeds` and `encoder_hidden_states` or neitherzXpass either both `negatve_prompt_embeds` and `negative_encoder_hidden_states` or neitherz,pass only one of `prompt` or `prompt_embeds`r   pt
max_lengthT)return_tensorspadding
truncationrM   )rE   output_hidden_statesr   r1    )devicedtyper   )rU   rT   )total)micro_condspooled_text_embrB   rH   )model_outputtimestepsampler@   starting_mask_ratioorderlatent)force_not_quantizeshape)<
ValueError
isinstancestrr'   ra   r   model_max_length	input_idsto_execution_devicer   text_embedshidden_statesrepeattorchconcatr   
preprocesstensorrU   	unsqueezeexpandr   set_timestepsint	timestepsr   float16r(   force_upcastfloatencodelatentsquantizereshaper*   r   boolrT   mask_token_idsumnumelprogress_barrangecatr   chunkstepprev_sampler^   updategetattrdecodelatent_channelsr\   clippostprocesshalfmaybe_free_model_hooksr   ).r,   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   output_typerE   rF   rG   rH   rI   rJ   rK   
batch_sizerf   outputsheightwidthrX   start_timestep_idxneeds_upcastingry   latents_bszchannelslatents_heightlatents_widthmaskr]   r   ir[   model_inputrZ   uncond_logitscond_logitsstep_idxoutputr/   r/   r0   __call__g   s  l 









 

,
#
	

zAmusedInpaintPipeline.__call__)NNNr1   r2   r3   Nr   NNNNNr4   TNr   Nr5   r6   r7   )!__name__
__module____qualname__r   __annotations__r   r
   r	   r   r   model_cpu_offload_seq_exclude_from_cpu_offloadr%   rl   no_gradr   EXAMPLE_DOC_STRINGr   r   r   rd   r   rw   rs   	GeneratorTensorr|   r   r   r   r   r   __classcell__r/   r/   r-   r0   r   <   s   
 	

r   )typingr   r   r   r   r   r   r   rl   transformersr	   r
   r   r   r   modelsr   r   
schedulersr   utilsr   pipeline_utilsr   r   r   r   r/   r/   r/   r0   <module>   s   $ 