
    bi                        d dl Z d dlmZmZmZmZmZmZ d dlZ	d dl
Zd dl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d	lmZ dd
lmZmZmZm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(  e       rd dl)m*c m+Z, dZ-ndZ- ej\                  e/      Z0 e       rd dl1Z1dZ2d Z3d Z4d Z5	 ddejl                  deejn                     de8fdZ9 G d de&e      Z:y)    N)AnyCallableDictListOptionalUnion)AutoTokenizerUMT5EncoderModel   )MultiPipelineCallbacksPipelineCallback)PipelineImageInput)WanLoraLoaderMixin)AutoencoderKLWanWanVACETransformer3DModel)FlowMatchEulerDiscreteScheduler)is_ftfy_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DiffusionPipeline   )WanPipelineOutputTFae  
    Examples:
        ```python
        >>> import torch
        >>> import PIL.Image
        >>> from diffusers import AutoencoderKLWan, WanVACEPipeline
        >>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
        >>> from diffusers.utils import export_to_video, load_image
        def prepare_video_and_mask(first_img: PIL.Image.Image, last_img: PIL.Image.Image, height: int, width: int, num_frames: int):
            first_img = first_img.resize((width, height))
            last_img = last_img.resize((width, height))
            frames = []
            frames.append(first_img)
            # Ideally, this should be 127.5 to match original code, but they perform computation on numpy arrays
            # whereas we are passing PIL images. If you choose to pass numpy arrays, you can set it to 127.5 to
            # match the original code.
            frames.extend([PIL.Image.new("RGB", (width, height), (128, 128, 128))] * (num_frames - 2))
            frames.append(last_img)
            mask_black = PIL.Image.new("L", (width, height), 0)
            mask_white = PIL.Image.new("L", (width, height), 255)
            mask = [mask_black, *[mask_white] * (num_frames - 2), mask_black]
            return frames, mask

        >>> # Available checkpoints: Wan-AI/Wan2.1-VACE-1.3B-diffusers, Wan-AI/Wan2.1-VACE-14B-diffusers
        >>> model_id = "Wan-AI/Wan2.1-VACE-1.3B-diffusers"
        >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
        >>> pipe = WanVACEPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
        >>> flow_shift = 3.0  # 5.0 for 720P, 3.0 for 480P
        >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
        >>> pipe.to("cuda")

        >>> prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."
        >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
        >>> first_frame = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png"
        ... )
        >>> last_frame = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png>>> "
        ... )

        >>> height = 512
        >>> width = 512
        >>> num_frames = 81
        >>> video, mask = prepare_video_and_mask(first_frame, last_frame, height, width, num_frames)

        >>> output = pipe(
        ...     video=video,
        ...     mask=mask,
        ...     prompt=prompt,
        ...     negative_prompt=negative_prompt,
        ...     height=height,
        ...     width=width,
        ...     num_frames=num_frames,
        ...     num_inference_steps=30,
        ...     guidance_scale=5.0,
        ...     generator=torch.Generator().manual_seed(42),
        ... ).frames[0]
        >>> export_to_video(output, "output.mp4", fps=16)
        ```
c                     t        j                  |       } t        j                  t        j                  |             } | j	                         S N)ftfyfix_texthtmlunescapestriptexts    d/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/wan/pipeline_wan_vace.pybasic_cleanr'   n   s3    ==D==t,-D::<    c                 T    t        j                  dd|       } | j                         } | S )Nz\s+ )resubr#   r$   s    r&   whitespace_cleanr-   t   s$    66&#t$D::<DKr(   c                 .    t        t        |             } | S r   )r-   r'   r$   s    r&   prompt_cleanr/   z   s    K-.DKr(   encoder_output	generatorsample_modec                     t        | d      r |dk(  r| j                  j                  |      S t        | d      r|dk(  r| j                  j                         S t        | d      r| j                  S t        d      )Nlatent_distsampleargmaxlatentsz3Could not access latents of provided encoder_output)hasattrr4   r5   moder7   AttributeError)r0   r1   r2   s      r&   retrieve_latentsr;      st     ~}-+2I))00;;		/K84K))..00		+%%%RSSr(   c            0           e Zd ZdZdZg dZdededede	de
f
 fd	Z	 	 	 	 	 d?deeee   f   dededeej$                     deej&                     f
dZ	 	 	 	 	 	 	 	 d@deeee   f   deeeee   f      dededeej,                     deej,                     dedeej$                     deej&                     fdZ	 	 	 	 	 	 dAdZ	 	 	 	 	 	 	 	 	 dBdeee      deee      deeej6                  j6                  eej6                  j6                     eeej6                  j6                        f      ded ed!ed"edeej&                     deej$                     fd#Z	 	 	 dCdej,                  dej,                  deeeej,                           d$eeej:                  eej:                     f      deej$                     d%ej,                  fd&Z	 	 dDdej,                  deeej,                        d$eeej:                  eej:                     f      d%ej,                  fd'Z	 	 	 	 	 	 	 	 dEded(ed ed!ed"edeej&                     deej$                     d$eeej:                  eej:                     f      d)eej,                     d%ej,                  fd*Z e!d+        Z"e!d,        Z#e!d-        Z$e!d.        Z%e!d/        Z&e!d0        Z' ejP                          e)e*      d
d
d
d
d
d1dddd2d3dd
d
d
d
d4dd
d
d)gd5fdeeee   f   deeee   f   deee      deee      deee      d6ee+ee+   ej,                  f   d ed!ed"ed7ed8e+dee   d$eeej:                  eej:                     f      d)eej,                     deej,                     deej,                     d9ee   d:ed;ee,ee-f      d<eee.eee,gd
f   e/e0f      d=ee   def,d>              Z1 xZ2S )FWanVACEPipelinea  
    Pipeline for controllable generation using Wan.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
    implemented for all pipelines (downloading, saving, running on a particular device, etc.).

    Args:
        tokenizer ([`T5Tokenizer`]):
            Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
            specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        text_encoder ([`T5EncoderModel`]):
            [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
            the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        transformer ([`WanTransformer3DModel`]):
            Conditional Transformer to denoise the input latents.
        scheduler ([`UniPCMultistepScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKLWan`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
    ztext_encoder->transformer->vae)r7   prompt_embedsnegative_prompt_embeds	tokenizertext_encodertransformervae	schedulerc                 \   t         |           | j                  |||||       t        | dd       r"dt	        | j
                  j                        z  nd| _        t        | dd       r"dt        | j
                  j                        z  nd| _	        t        | j                        | _        y )N)rC   rA   r@   rB   rD   rC   r         )vae_scale_factor)super__init__register_modulesgetattrsumrC   temperal_downsamplevae_scale_factor_temporallenvae_scale_factor_spatialr   video_processor)selfr@   rA   rB   rC   rD   	__class__s         r&   rJ   zWanVACEPipeline.__init__   s     	%# 	 	
 T[[_afhlSmc$((2N2N.O)Ost&RYZ^`egkRlS1M1M-N(Nrs%-t?\?\]r(   Nr   promptnum_videos_per_promptmax_sequence_lengthdevicedtypec                    |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}|D cg c]  }t        |       }}t        |      }| j                  |d|dddd      }|j                  |j                  }
}	|
j                  d      j                  d      j                         }| j                  |	j                  |      |
j                  |            j                  }|j                  ||      }t        ||      D cg c]
  \  }}|d |  }}}t!        j"                  |D cg c]J  }t!        j$                  ||j'                  ||j)                  d      z
  |j)                  d            g      L c}d      }|j*                  \  }}}|j-                  d|d      }|j/                  ||z  |d	      }|S c c}w c c}}w c c}w )
N
max_lengthTpt)paddingr[   
truncationadd_special_tokensreturn_attention_maskreturn_tensorsr   r   dimrY   rX   )_execution_devicerA   rY   
isinstancestrr/   rP   r@   	input_idsattention_maskgtrM   longtolast_hidden_stateziptorchstackcat	new_zerossizeshaperepeatview)rS   rU   rV   rW   rX   rY   u
batch_sizetext_inputstext_input_idsmaskseq_lensr>   v_seq_lens                   r&   _get_t5_prompt_embedsz%WanVACEPipeline._get_t5_prompt_embeds   s    14110**00'4&&+12a,q/22[
nn *#"& % 
  +44k6P6P771:>>a>(--/)).*;*;F*CTWWV_Ugg%((uV(D+.}h+GH41a2AHH^klYZUYY1;;':QVVAY'Fq	RSTlrs

 &++7A%,,Q0EqI%**:8M+MwXZ[7 3" Ils   GGAG!Tnegative_promptdo_classifier_free_guidancer>   r?   c
                    |xs | j                   }t        |t              r|gn|}|t        |      }
n|j                  d   }
|| j                  |||||	      }|r||xs d}t        |t              r|
|gz  n|}|:t        |      t        |      ur$t        dt        |       dt        |       d      |
t        |      k7  r!t        d| dt        |       d	| d|
 d
	      | j                  |||||	      }||fS )a"  
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
                Whether to use classifier free guidance or not.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            device: (`torch.device`, *optional*):
                torch device
            dtype: (`torch.dtype`, *optional*):
                torch dtype
        r   )rU   rV   rW   rX   rY    z?`negative_prompt` should be the same type to `prompt`, but got z != .z`negative_prompt`: z has batch size z, but `prompt`: zT. Please make sure that passed `negative_prompt` matches the batch size of `prompt`.)	rf   rg   rh   rP   ru   r   type	TypeError
ValueError)rS   rU   r   r   rV   r>   r?   rW   rX   rY   ry   s              r&   encode_promptzWanVACEPipeline.encode_prompt   sj   L 1411'4&&VJ&,,Q/J  66&;$7 7 M '+A+I-3O@J?\_@`jO+<<fuO!d6l$:O&OUVZ[jVkUl mV~Q(  s?33 )/)::J3K_J` ax/
| <33  &*%?%?&&;$7 &@ &" 444r(   c           
           j                    j                  j                  j                  d   z  }||z  dk7  s||z  dk7  rt	        d| d| d| d      |Lt         fd|D              s8t	        d j                   d	|D cg c]  }| j                  vs| c}       ||t	        d
| d| d      ||t	        d| d| d      ||t	        d      |7t        |t              s't        |t              st	        dt        |             |7t        |t              s't        |t              st	        dt        |             ||	;t        |      t        |	      k7  r$t	        dt        |       dt        |	       d      |
t        |
t        j                  j                        }t        |
t              xr t        d |
D              }t        |
t              xr t        d |
D              }|s|s|st	        d      |rt        |
      dk7  rt	        d      y y y |	t	        d      y c c}w )Nr   r   z-`height` and `width` have to be divisible by z	 but are  and r   c              3   :   K   | ]  }|j                   v   y wr   )_callback_tensor_inputs).0krS   s     r&   	<genexpr>z/WanVACEPipeline.check_inputs.<locals>.<genexpr>I  s#      F
23A---F
s   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zCannot forward both `prompt`: z and `prompt_embeds`: z2. Please make sure to only forward one of the two.z'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is z;`negative_prompt` has to be of type `str` or `list` but is zLength of `video` z and `mask` z? do not match. Please make sure that they have the same length.c              3   d   K   | ](  }t        |t        j                  j                         * y wr   rg   PILImager   ref_imgs     r&   r   z/WanVACEPipeline.check_inputs.<locals>.<genexpr>n  s&      S=DJw		8S   .0c              3   d   K   | ](  }t        |t              xr t        d  |D               * yw)c              3   d   K   | ](  }t        |t        j                  j                         * y wr   r   )r   ref_img_s     r&   r   z9WanVACEPipeline.check_inputs.<locals>.<genexpr>.<genexpr>r  s      5t`hj399??6[5tr   N)rg   listallr   s     r&   r   z/WanVACEPipeline.check_inputs.<locals>.<genexpr>q  s5      [ w-t#5tls5t2tt[r   `reference_images` has to be of type `PIL.Image.Image` or `list` of `PIL.Image.Image`, or `list` of `list` of `PIL.Image.Image`, but is {type(reference_images)}a[  The pipeline only supports generating one video at a time at the moment. When passing a list of list of reference images, where the outer list corresponds to the batch size and the inner list corresponds to list of conditioning images per video, please make sure to only pass one inner list of reference images (i.e., `[[<image1>, <image2>, ...]]`z7`mask` can only be passed if `video` is passed as well.)rQ   rB   config
patch_sizer   r   r   rg   rh   r   r   rP   r   r   )rS   rU   r   heightwidthr>   r?   "callback_on_step_end_tensor_inputsvideor|   reference_imagesbaser   is_pil_imageis_list_of_pil_imagesis_list_of_list_of_pil_imagess   `               r&   check_inputszWanVACEPipeline.check_inputs8  s    ,,t/?/?/F/F/Q/QRS/TTD=A!2LTFR[\b[cchinhoopqrr-9# F
7YF
 C
 DTEaEaDbbn  |^  pHvw  bc  ko  kG  kG  bGpq  pH  oI  J  -";08N}o ^0 0  (-C-O9/9JJi  kA  jB B0 0  ^ 5w  FC)@TZ\`IaQRVW]R^Q_`aa(?C0OUY9ZZ[_`o[pZqrssu:T*$,SZLSYK P6 6   +)*:CIIOOL(23CT(J )s SHXS P% 1;;KT0R 1WZ [#3[ X- %(=A^$a  1S9I5Ja5O$b  6P0 ,* VWW i pHs   H<H<  @  Q   r   r|   r   ry   r   r   
num_framesc
           	         || j                   | j                  j                  j                  d   z  }
| j                  j                  |d         \  }}||z  ||z  kD  r.t        ||z  ||z        }t        ||z        t        ||z        }}||
z  dk7  s||
z  dk7  r/t        j                  d|
 d| d| d       ||
z  |
z  }||
z  |
z  }||z  ||z  k  sJ | j                  j                  |||      }||f}n t        j                  |d|||||	      }||f}|B| j                  j                  ||d   |d         }t        j                  |dz   d	z  dd
      }nt        j                  |      }|j                  ||	      }|j                  ||	      }|$t!        |t"        j$                  j$                        r't'        |j(                  d         D cg c]  }|g }}nt!        |t*        t,        f      r:t!        t/        t1        |            t"        j$                  j$                        r|g}nt!        |t*        t,        f      r^t!        t/        t1        |            t*              r<t!        t/        t1        |d               t"        j$                  j$                        r|}nt3        d      |j(                  d   t5        |      k7  r(t3        d|j(                  d    dt5        |       d      |D cg c]  }t5        |       c}t7        fdD              rt3        d d      g }t9        |      D ]&  \  }}g }t9        |      D ]  \  }}|	| j                  j;                  |d d       }|j(                  dd  \  }}t        |d   |z  |d   |z        }t        ||z        t        ||z        }}t        j<                  j>                  jA                  |||fdd      jC                  d      }|d   |z
  d	z  }|d   |z
  d	z  }t        jD                  dg||	|d}||d d |||z   |||z   f<   |jG                  |        |jG                  |       ) |||fS c c}w c c}w )Nr   r   z.Video height and width should be divisible by z
, but got r   z. r   rd   r   )minmaxr   Batch size of `video` " and length of `reference_images`  does not match.c              3   .   K   | ]  }|d    k7    yw)r   N )r   lref_images_lengthss     r&   r   z8WanVACEPipeline.preprocess_conditions.<locals>.<genexpr>  s     Faq&q))Fs   zGAll batches of `reference_images` should have the same length, but got z.. Support for this may be added in the future.bilinearF)rt   r9   align_cornersrX   rY   )$rQ   rB   r   r   rR   get_default_height_widthr   intloggerwarningpreprocess_videorp   zerosclamp	ones_likerm   rg   r   r   rangeru   r   tuplenextiterr   rP   any	enumerate
preprocessnn
functionalinterpolatesqueezeonesappend)rS   r   r|   r   ry   r   r   r   rY   rX   r   video_heightvideo_widthscale
image_sizer   reference_images_batchreference_images_preprocessedipreprocessed_imagesjimage
img_height	img_width
new_height	new_widthresized_imagetopleftcanvasr   s                                 @r&   preprocess_conditionsz%WanVACEPipeline.preprocess_conditions  s    0043C3C3J3J3U3UVW3XXD(,(<(<(U(UV[\]V^(_%L+k)FUN:EK/,1FG,/u0D,Es;Y^K^G_kd"a';+=+BDTF*UaTbbghsgttvw !- 4<*d2d:+-%???((99%{[E&4JKK
Az65PU^deE %J''88z!}jYZm\D;;qA~1!<D??5)DuV4wwU6w2 #z2BCIIOO'T<A%++a.<QRq!1 2RR(4-8ZTRbMcHdfifofofufu=v 01'$74%5 67>4%5a%8 9:CIIOOL/Y 
 ;;q>S!122(Q(88Z[^_o[pZq  rB  C  Yii>Tc"89iF3EFFYZlYm n. . 
 )+%)23C)D 	F%A%"$%&<= 35=,,77tTJ(-BC(8%
IJqMJ6
1	8QR(+J,>(?YQVEVAWI
 % 3 3 ? ?Y 7jX] !@ !'!*  "!}z1a7"1	1a7AO
O6OMZq#j 00$	9I2IIJ#**623 *001DE#	F& d999_  S( js   
Q2>Q7r1   returnc           	      |   |xs | j                   }t        |t              rt        d      |'t	        |j
                  d         D cg c]  }d g }}nC|j
                  d   t        |      k7  r(t        d|j
                  d    dt        |       d      |j
                  d   dk7  rt        d      | j                  j                  }|j                  |      }t        j                  | j                  j                  j                  |t        j                  	      j                  d| j                  j                  j                   ddd      }d
t        j                  | j                  j                  j"                  |t        j                  	      j                  d| j                  j                  j                   ddd      z  }	|\t%        | j                  j'                  |      |d      j)                  d      }
|
j+                         |z
  |	z  j                  |      }
nt        j,                  |dkD  d
d      j                  |      }|d|z
  z  }||z  }t%        | j                  j'                  |      |d      }t%        | j                  j'                  |      |d      }|j+                         |z
  |	z  j                  |      }|j+                         |z
  |	z  j                  |      }t        j.                  ||gd      }
g }t1        |
|      D ]  \  }}|D ]  }|j2                  dk(  sJ |j                  |      }|d d d d d d d d f   }t%        | j                  j'                  |      |d      }|j+                         |z
  |	z  j                  |      }|j5                  d      }t        j.                  |t        j6                  |      gd      }t        j.                  |j5                  d      |gd      } |j9                  |        t        j:                  |      S c c}w )NWPassing a list of generators is not yet supported. This may be supported in the future.r   r   r   r   r   ^Generating with more than one video is not yet supported. This may be supported in the future.)rY   r         ?r6   )r2   g      ?g        rb   r   )rf   rg   r   r   r   ru   rP   rC   rY   rm   rp   tensorr   latents_meanfloat32rw   z_dimlatents_stdr;   encodeunbindfloatwhererr   ro   ndimr   
zeros_liker   rq   )rS   r   r|   r   r1   rX   r   	vae_dtyper   r   r7   inactivereactivelatent_listlatentr   reference_imagereference_latents                     r&   prepare_video_latentsz%WanVACEPipeline.prepare_video_latents  s    1411i&vww# 16ekk!n0EF1FF{{1~%5!66 ,U[[^,<<^_bcs_t^u  vF  G  ;;q>Qp  HHNN	y)||DHHOO$@$@W\WdWdejjtxx$$aA
 ELL)D)DV[`[h[hinntxx$$aA
 
 <&txxu'=yV^_ffghiG,6+EII)TG;;tcz3477i7HDD)Ht|H'(A9ZbcH'(A9ZbcH!)L8KGKKIVH!)L8KGKKIVHii8 4!<G.1';K.L 
	'*F*#9 Q&++q000"1"4"49"4"E"1$4A2E"F#3DHHOOO4TV_mu#v %5%;%;%=%LP[$[#_#_`i#j #3#;#;A#> #(99.>@P@PQa@b-cij#k $4$<$<Q$?#HaPQ v&
	' {{;''a  Gs   
P9c           	         t        |t              rt        d      |'t        |j                  d         D cg c]  }d g }}nC|j                  d   t        |      k7  r(t        d|j                  d    dt        |       d      |j                  d   dk7  rt        d      | j                  j                  j                  d   }g }t        ||      D ]h  \  }}|j                  \  }	}
}}|
| j                  z   dz
  | j                  z  }|| j                  |z  z  |z  }|| j                  |z  z  |z  }|dd d d d d d f   }|j                  |
|| j                  || j                        }|j                  dd	ddd
      j                  dd      }t        j                   j"                  j%                  |j'                  d      |||fd      j)                  d      }t        |      }|dkD  r=t        j*                  |d d d |d d d d f         }t        j,                  ||gd      }|j/                  |       k t        j0                  |      S c c}w )Nr   r   zBatch size of `mask` r   r   r   r   r   rF   r   znearest-exact)rt   r9   rb   )rg   r   r   r   ru   rP   rB   r   r   ro   rO   rQ   rw   permuteflattenrp   r   r   r   	unsqueezer   r   rr   r   rq   )rS   r|   r   r1   r   transformer_patch_size	mask_listmask_r   num_channelsr   r   r   new_num_framesr   r   num_ref_imagesmask_paddings                     r&   prepare_maskszWanVACEPipeline.prepare_masks'  sq    i&vww#05djjm0DE1EEzz!}$4 55 +DJJqM?:\]`aq]r\s  tD  E  ::a=Ap  "&!1!1!8!8!C!CA!F	-07G-H 	$)E)6;kk3L*fe(4+I+IIAMRVRpRppND$A$ADZ$Z[^ttJ$"?"?BX"XY\rrI!Q1*%EJJJ(E(EyRVRoRoE MM!Q1a088A>EHH''33".*i)PWf 4 gaj  !!78N!$//a.!Q6N0OP		<"7Q?U##	$$ {{9%%E  Fs   
Inum_channels_latentsr7   c
                 P   |	|	j                  ||      S |dz
  | j                  z  dz   }
|||
t        |      | j                  z  t        |      | j                  z  f}t	        |t
              r)t        |      |k7  rt        dt        |       d| d      t        ||||      }	|	S )Nr   r   z/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.)r1   rX   rY   )	rm   rO   r   rQ   rg   r   rP   r   r   )rS   ry   r	  r   r   r   rY   rX   r1   r7   num_latent_framesru   s               r&   prepare_latentszWanVACEPipeline.prepare_latentsW  s     ::V5:99'!^0N0NNQRR K4888J$777
 i&3y>Z+GA#i.AQ R&<'gi 
 u	&PUVr(   c                     | j                   S r   _guidance_scalerS   s    r&   guidance_scalezWanVACEPipeline.guidance_scalew  s    ###r(   c                      | j                   dkD  S )Nr   r  r  s    r&   r   z+WanVACEPipeline.do_classifier_free_guidance{  s    ##c))r(   c                     | j                   S r   )_num_timestepsr  s    r&   num_timestepszWanVACEPipeline.num_timesteps  s    """r(   c                     | j                   S r   )_current_timestepr  s    r&   current_timestepz WanVACEPipeline.current_timestep      %%%r(   c                     | j                   S r   )
_interruptr  s    r&   	interruptzWanVACEPipeline.interrupt  s    r(   c                     | j                   S r   )_attention_kwargsr  s    r&   attention_kwargsz WanVACEPipeline.attention_kwargs  r  r(   r   2   g      @npi   conditioning_scalenum_inference_stepsr  output_typereturn_dictr  callback_on_step_endr   c                     t        |t        t        f      r|j                  }t        |t              st        d      |dk7  rt        d      | j                  ||||||||||
       |	| j                  z  dk7  rBt        j                  d| j                   d       |	| j                  z  | j                  z  dz   }	t        |	d      }	|| _        || _        d| _        d| _        | j                  }|t        |t              rd}n-|t        |t               rt#        |      }n|j$                  d   }| j&                  j(                  }| j*                  j(                  }t        |t,        t.        f      r-|gt#        | j*                  j0                  j2                        z  }t        |t               rt#        |      t#        | j*                  j0                  j2                        k7  rBt        d	t#        |       d
t#        | j*                  j0                  j2                         d      t5        j6                  |      }t        |t4        j8                        r|j;                  d      t#        | j*                  j0                  j2                        k7  rHt        d	|j;                  d       d
t#        | j*                  j0                  j2                         d      |j=                  ||      }| j?                  ||| j@                  |||||      \  }}|j=                  |      }||j=                  |      }| jB                  jE                  |
|       | jB                  jF                  }| jI                  |||||||	t4        jJ                  |	      \  }}}t#        |d         }| jM                  |||||      }| jO                  |||      }t5        jP                  ||gd      }|j=                  |      }| j*                  j0                  jR                  }| jU                  ||z  ||||	|| j                  z  z   t4        jJ                  |||	      }|j$                  d   |j$                  d   k7  rt        j                  d       t#        |      |
| jB                  jV                  z  z
  }t#        |      | _,        | j[                  |
      5 } t]        |      D ]x  \  }!}"| j^                  r|"| _        |j=                  |      }#|"ja                  |j$                  d         }$| j+                  |#|$||||d      d   }%| j@                  r&| j+                  |#|$||||d      d   }&|&||%|&z
  z  z   }%| jB                  jc                  |%|"|d      d   }|Zi }'|D ]  }(te               |(   |'|(<     || |!|"|'      })|)jg                  d|      }|)jg                  d|      }|)jg                  d|      }|!t#        |      dz
  k(  s'|!dz   |kD  r/|!dz   | jB                  jV                  z  dk(  r| ji                          tj        setm        jn                          { 	 ddd       d| _        |dk(  sx|dddd|df   }|j=                  |      }t5        j6                  | j&                  j0                  jp                        js                  d| j&                  j0                  jt                  ddd      j=                  |jv                  |j(                        }*dt5        j6                  | j&                  j0                  jx                        js                  d| j&                  j0                  jt                  ddd      j=                  |jv                  |j(                        z  }+||+z  |*z   }| j&                  j{                  |d      d   }| j|                  j                  ||      }n|}| j                          |s|fS t        |      S # 1 sw Y   xY w)a   
        The call function to the pipeline for generation.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`
                instead.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            video (`List[PIL.Image.Image]`, *optional*):
                The input video or videos to be used as a starting point for the generation. The video should be a list
                of PIL images, a numpy array, or a torch tensor. Currently, the pipeline only supports generating one
                video at a time.
            mask (`List[PIL.Image.Image]`, *optional*):
                The input mask defines which video regions to condition on and which to generate. Black areas in the
                mask indicate conditioning regions, while white areas indicate regions for generation. The mask should
                be a list of PIL images, a numpy array, or a torch tensor. Currently supports generating a single video
                at a time.
            reference_images (`List[PIL.Image.Image]`, *optional*):
                A list of one or more reference images as extra conditioning for the generation. For example, if you
                are trying to inpaint a video to change the character, you can pass reference images of the new
                character here. Refer to the Diffusers [examples](https://github.com/huggingface/diffusers/pull/11582)
                and original [user
                guide](https://github.com/ali-vilab/VACE/blob/0897c6d055d7d9ea9e191dce763006664d9780f8/UserGuide.md)
                for a full list of supported tasks and use cases.
            conditioning_scale (`float`, `List[float]`, `torch.Tensor`, defaults to `1.0`):
                The conditioning scale to be applied when adding the control conditioning latent stream to the
                denoising latent stream in each control layer of the model. If a float is provided, it will be applied
                uniformly to all layers. If a list or tensor is provided, it should have the same length as the number
                of control layers in the model (`len(transformer.config.vace_layers)`).
            height (`int`, defaults to `480`):
                The height in pixels of the generated image.
            width (`int`, defaults to `832`):
                The width in pixels of the generated image.
            num_frames (`int`, defaults to `81`):
                The number of frames in the generated video.
            num_inference_steps (`int`, defaults to `50`):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, defaults to `5.0`):
                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
                `guidance_scale` is defined as `w` of equation 2. of [Imagen
                Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
                1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
                usually at the expense of lower image quality.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
                A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
                generation deterministic.
            latents (`torch.Tensor`, *optional*):
                Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor is generated by sampling using the supplied random `generator`.
            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.
            output_type (`str`, *optional*, defaults to `"np"`):
                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 [`WanPipelineOutput`] instead of a plain tuple.
            attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
                A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
                each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
                DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
                list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
                will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
                `._callback_tensor_inputs` attribute of your pipeline class.
            max_sequence_length (`int`, defaults to `512`):
                The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
                truncated. If the prompt is shorter, it will be padded to this length.

        Examples:

        Returns:
            [`~WanPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`WanPipelineOutput`] is returned, otherwise a `tuple` is returned where
                the first element is a list with the generated images and the second element is a list of `bool`s
                indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
        zTPassing a list of prompts is not yet supported. This may be supported in the future.r   z`Generating multiple videos per prompt is not yet supported. This may be supported in the future.z(`num_frames - 1` has to be divisible by z!. Rounding to the nearest number.NFr   zLength of `conditioning_scale` z! does not match number of layers r   r   )rU   r   r   rV   r>   r?   rW   rX   )rX   rb   r   zThe number of frames in the conditioning latents does not match the number of frames to be generated. Generation quality may be affected.)total)hidden_statestimestepencoder_hidden_statescontrol_hidden_statescontrol_hidden_states_scaler  r%  )r%  r7   r>   r?   r   r   )r$  )frames)Brg   r   r   tensor_inputsrh   r   r   rO   r   r   r   r  r  r  r  rf   r   rP   ru   rC   rY   rB   r   r   r   vace_layersrp   r   Tensorrt   rm   r   r   rD   set_timesteps	timestepsr   r   r   r  rr   in_channelsr  orderr  progress_barr   r  expandsteplocalspopupdateXLA_AVAILABLExm	mark_stepr   rw   r   rX   r   decoderR   postprocess_videomaybe_free_model_hooksr   ),rS   rU   r   r   r|   r   r"  r   r   r   r#  r  rV   r1   r7   r>   r?   r$  r%  r  r&  r   rW   rX   ry   r   transformer_dtyper3  num_reference_imagesconditioning_latentsr	  num_warmup_stepsr6  r   tlatent_model_inputr*  
noise_prednoise_uncondcallback_kwargsr   callback_outputsr   r   s,                                               r&   __call__zWanVACEPipeline.__call__  sP   l *-=?U,VW1E1S1S. &#&stt A%r 
 	".	
 666!;NN:4;Y;Y:ZZ{| $t'E'EEHfHffijjJQ'
-!1!%'' *VS"9JJvt$<VJ&,,Q/JHHNN	 ,,22(3,7"4!5D<L<L<S<S<_<_8`!`($/%&#d.>.>.E.E.Q.Q*RR 5c:L6M5NNopstx  uE  uE  uL  uL  uX  uX  qY  pZ  Z[  \  "'.@!A(%,,7!&&q)S1A1A1H1H1T1T-UU 56H6M6Ma6P5QQrsvw{  xH  xH  xO  xO  x[  x[  t\  s]  ]^  _  "4!6!6fL]!6!^ 150B0B+(,(H(H"7'#9 3 1C 	1
-- &(():;!-%;%>%>?P%Q" 	$$%8$HNN,,	 )-(B(BMM
)
%t%  ##3A#67#99%GWYbdjk!!$(8)D$yy*>)E1M3667HI#//66BB&&.. -0N0NNNMM

  %%a(GMM!,<<NN \
 y>,?$..BVBV,VV!)n%89 1	#\!), 0#1>>)*&%,ZZ0A%B"88GMM!$45!--"4%*7*>0B%5 % .  
 33#'#3#3&8!).D.B4F)9$) $4 $ $L ".*|B[0\!\J ..--j!WRW-XYZ['3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s* I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNa0#1	#f "&h&a$8$99:Gjj+GTXX__99:a..1a8GNNGMM2 
 TXX__-H-H I N NqRVRZRZRaRaRgRgijlmop q t t! K +l:GHHOOGO?BE((::5k:ZEE 	##%8O ..Y1	# 1	#s   
E/`;``)Nr      NN)NTr   NNrM  NN)NNNNNN)	NNNr   r   r   r   NN)NNN)NN)   r   r   r   NNNN)3__name__
__module____qualname____doc__model_cpu_offload_seqr   r	   r
   r   r   r   rJ   r   rh   r   r   r   rp   rX   rY   r   boolr1  r   r   r   r   r   r   	Generatorr   r  r  propertyr  r   r  r  r  r  no_gradr   EXAMPLE_DOC_STRINGr   r   r   r   r   r   rL  __classcell__)rT   s   @r&   r=   r=      s   * =T^ ^ '^ /	^
 ^ 3^2 )-%&#&)-'+'c49n%'  #' !	'
 &' $'Z <@,0%&049=#&)-'+O5c49n%O5 "%T#Y"78O5 &*	O5
  #O5  -O5 !) 6O5 !O5 &O5 $O5n #+/JX\ 5937qu'+)-^:/01^: t./0^: #5$syy:OQUVZ[^[d[d[j[jVkQl)l#mn	^:
 ^: ^: ^: ^: $^: &^:H @DMQ)-A(||A( llA( #4U\\(:#;<	A(
 E%//43H"HIJA( &A( 
A(L :>MQ	.&ll.& #4#56.& E%//43H"HIJ	.&
 
.&f %''+)-MQ*. " 	
   $ & E%//43H"HIJ %,,' 
@ $ $ * * # # & &   & & U]]_12 )-154837?CFI#% #/0MQ*.049=%) 59 9B#&3~/c49n%~/ sDI~.~/ /01	~/
 t./0~/ #4(:#;<~/ "%eell"BC~/ ~/ ~/ ~/ !~/ ~/  (}~/ E%//43H"HIJ~/ %,,'~/   -!~/" !) 6#~/$ c]%~/& '~/( #4S>2)~/* '(Cd+T124DF\\]
+~/0 -1I1~/2 !3~/ 3 ~/r(   r=   )Nr5   );r!   typingr   r   r   r   r   r   	PIL.Imager   regexr+   rp   transformersr	   r
   	callbacksr   r   image_processorr   loadersr   modelsr   r   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   rR   r   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr=  r<  
get_loggerrO  r   r   rX  r'   r-   r/   r1  rU  rh   r;   r=   r   r(   r&   <module>rk     s     = =    8 A 1 ) A 9 b b - - . . ))MM			H	%; | ck
TLL
T-5eoo-F
T\_
TB/'); B/r(   