
    i                        d dl Z d dlmZ d dlmZ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c mZ d dlmZmZ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/ ddl0m1Z1  e&       rd dl2m3c m4Z5 dZ6ndZ6 e'jn                  e8      Z9 e%       rd dl:Z:dZ;d Z<d Z=d Z>	 ddej~                  deej                     deAfdZB G d de.e      ZCy)     N)deepcopy)AnyCallableDictListOptionalTupleUnion)AutoTokenizerCLIPImageProcessorCLIPVisionModelUMT5EncoderModel   )MultiPipelineCallbacksPipelineCallback)PipelineImageInput)WanLoraLoaderMixin)AutoencoderKLWanWanAnimateTransformer3DModel)UniPCMultistepScheduler)is_ftfy_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DiffusionPipeline   )WanAnimateImageProcessor)WanPipelineOutputTFa  
    Examples:
        ```python
        >>> import torch
        >>> import numpy as np
        >>> from diffusers import WanAnimatePipeline
        >>> from diffusers.utils import export_to_video, load_image, load_video

        >>> model_id = "Wan-AI/Wan2.2-Animate-14B-Diffusers"
        >>> pipe = WanAnimatePipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
        >>> # Optionally upcast the Wan VAE to FP32
        >>> pipe.vae.to(torch.float32)
        >>> pipe.to("cuda")

        >>> # Load the reference character image
        >>> image = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
        ... )

        >>> # Load pose and face videos (preprocessed from reference video)
        >>> # Note: Videos should be preprocessed to extract pose keypoints and face features
        >>> # Refer to the Wan-Animate preprocessing documentation for details
        >>> pose_video = load_video("path/to/pose_video.mp4")
        >>> face_video = load_video("path/to/face_video.mp4")

        >>> # CFG is generally not used for Wan Animate
        >>> prompt = (
        ...     "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
        ...     "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
        ... )

        >>> # Animation mode: Animate the character with the motion from pose/face videos
        >>> output = pipe(
        ...     image=image,
        ...     pose_video=pose_video,
        ...     face_video=face_video,
        ...     prompt=prompt,
        ...     height=height,
        ...     width=width,
        ...     segment_frame_length=77,  # Frame length of each inference segment
        ...     guidance_scale=1.0,
        ...     num_inference_steps=20,
        ...     mode="animate",
        ... ).frames[0]
        >>> export_to_video(output, "output_animation.mp4", fps=30)

        >>> # Replacement mode: Replace a character in the background video
        >>> # Requires additional background_video and mask_video inputs
        >>> background_video = load_video("path/to/background_video.mp4")
        >>> mask_video = load_video("path/to/mask_video.mp4")  # Black areas preserved, white areas generated
        >>> output = pipe(
        ...     image=image,
        ...     pose_video=pose_video,
        ...     face_video=face_video,
        ...     background_video=background_video,
        ...     mask_video=mask_video,
        ...     prompt=prompt,
        ...     height=height,
        ...     width=width,
        ...     segment_frame_length=77,  # Frame length of each inference segment
        ...     guidance_scale=1.0,
        ...     num_inference_steps=20,
        ...     mode="replace",
        ... ).frames[0]
        >>> export_to_video(output, "output_replacement.mp4", fps=30)
        ```
c                     t        j                  |       } t        j                  t        j                  |             } | j	                         S N)ftfyfix_texthtmlunescapestriptexts    v/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/pipelines/wan/pipeline_wan_animate.pybasic_cleanr,   w   s3    ==D==t,-D::<    c                 T    t        j                  dd|       } | j                         } | S )Nz\s+ )resubr(   r)   s    r+   whitespace_cleanr2   }   s$    66&#t$D::<DKr-   c                 .    t        t        |             } | S r#   )r2   r,   r)   s    r+   prompt_cleanr4      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)hasattrr9   r:   moder<   AttributeError)r5   r6   r7   s      r+   retrieve_latentsr@      st     ~}-+2I))00;;		/K84K))..00		+%%%RSSr-   c            :       	    e Zd ZdZdZg dZdededede	de
d	ed
ef fdZ	 	 	 	 	 dWdeeee   f   dededeej(                     deej*                     f
dZ	 dXdedeej(                     fdZ	 	 	 	 	 	 	 	 dYdeeee   f   deeeee   f      dededeej4                     deej4                     dedeej(                     deej*                     fdZ	 	 	 	 	 	 dZdZ	 	 	 	 d[deded ed!ed"ed#eej4                     deej*                     deeej(                  f   d$ej4                  fd%Z	 	 	 	 	 d\dej4                  ded&ed'eeej<                  eej<                     f      deej*                     deej(                     d$ej4                  fd(Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d]d-eej4                     d.eej4                     d/eej4                     ded0ed1ed2ed3ed4ed5ed6ed&ed'eeej<                  eej<                     f      deej*                     deej(                     d$ej4                  f d7Z 	 	 	 	 	 d\d8ej4                  ded&ed'eeej<                  eej<                     f      deej*                     deej(                     d$ej4                  fd9Z!	 	 	 	 	 	 	 	 d^ded:ed2ed3ed;edeej*                     deej(                     d'eeej<                  eej<                     f      d<eej4                     d$e"ej4                  ej4                  ej4                  f   fd=Z#d>ee$   d?ed$ee$   fd@Z%e&dA        Z'e&dB        Z(e&dC        Z)e&dD        Z*e&dE        Z+e&dF        Z, ejZ                          e.e/      ddddd*d+d)dGd,dddHdddddddIdddd<gdfded8ee0jb                  jb                     dJee0jb                  jb                     d.eee0jb                  jb                        d/eee0jb                  jb                        deeee   f   deeee   f   d2ed3ed0edKedLedMedNee   dOe2dee   d'eeej<                  eej<                     f      d<eej4                     deej4                     deej4                     dPeej4                     dQee   dRedSee3ee$f      dTeee4eee3gdf   e5e6f      dUee   def6dV              Z7 xZ8S )_WanAnimatePipelineaM
  
    Pipeline for unified character animation and replacement using Wan-Animate.

    WanAnimatePipeline takes a character image, pose video, and face video as input, and generates a video in two
    modes:

    1. **Animation mode**: The model generates a video of the character image that mimics the human motion in the input
       pose and face videos. The character is animated based on the provided motion controls, creating a new animated
       video of the character.

    2. **Replacement mode**: The model replaces a character in a background video with the provided character image,
       using the pose and face videos for motion control. This mode requires additional `background_video` and
       `mask_video` inputs. The mask video should have black regions where the original content should be preserved and
       white regions where the new character should be generated.

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

    The pipeline also inherits the following loading methods:
        - [`~loaders.WanLoraLoaderMixin.load_lora_weights`] for loading LoRA weights

    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.
        image_encoder ([`CLIPVisionModel`]):
            [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModel), specifically
            the
            [clip-vit-huge-patch14](https://github.com/mlfoundations/open_clip/blob/main/docs/PRETRAINED.md#vit-h14-xlm-roberta-large)
            variant.
        transformer ([`WanAnimateTransformer3DModel`]):
            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.
        image_processor ([`CLIPImageProcessor`]):
            Image processor for preprocessing images before encoding.
    z-text_encoder->image_encoder->transformer->vae)r<   prompt_embedsnegative_prompt_embeds	tokenizertext_encodervae	schedulerimage_processorimage_encodertransformerc           	      >   t         	|           | j                  |||||||       t        | dd       r | j                  j
                  j                  nd| _        t        | dd       r | j                  j
                  j                  nd| _	        t        | j                        | _        t        | j                  dd      | _        | j                  #| j                  j
                  j                  d	d  nd
}t        | j                  |dd      | _        || _        y )N)rG   rF   rE   rJ   rK   rH   rI   rG         )vae_scale_factorFT)rO   do_normalizedo_convert_grayscale)r   r   bilinearr   )rO   spatial_patch_sizeresample
fill_color)super__init__register_modulesgetattrrG   configscale_factor_temporalvae_scale_factor_temporalscale_factor_spatialvae_scale_factor_spatialr   video_processorvideo_processor_for_maskrK   
patch_sizer    vae_image_processorrI   )
selfrE   rF   rG   rH   rI   rJ   rK   rT   	__class__s
            r+   rX   zWanAnimatePipeline.__init__   s    	%'#+ 	 	
 SZZ^`egkRl)N)Nrs&PWX\^ceiPj(L(Lpq%-t?\?\](6!::ei)
% IMHXHXHdT--44??Djp#;!::1	$
   /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)paddingrm   
truncationadd_special_tokensreturn_attention_maskreturn_tensorsr   r   dimrk   rj   )_execution_devicerF   rk   
isinstancestrr4   lenrE   	input_idsattention_maskgtsumlongtolast_hidden_stateziptorchstackcat	new_zerossizeshaperepeatview)rd   rg   rh   ri   rj   rk   u
batch_sizetext_inputstext_input_idsmaskseq_lensrC   v_seq_lens                   r+   _get_t5_prompt_embedsz(WanAnimatePipeline._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!imagec                     |xs | j                   }| j                  |d      j                  |      } | j                  di |ddi}|j                  d   S )Nrn   )imagesrs   output_hidden_statesTrR    )rx   rI   r   rJ   hidden_states)rd   r   rj   image_embedss       r+   encode_imagezWanAnimatePipeline.encode_image  s_    
 1411$$E$$GJJ6R)t))MEMM))"--r-   Tnegative_promptdo_classifier_free_guidancerC   rD   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   )rg   rh   ri   rj   rk    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`.)	rx   ry   rz   r{   r   r   type	TypeError
ValueError)rd   rg   r   r   rh   rC   rD   ri   rj   rk   r   s              r+   encode_promptz WanAnimatePipeline.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           
      d    ||t        d| d| d      ||t        d      |Ut        |t        j                        s;t        |t        j
                  j
                        st        dt        |             |t        d      |t        d      t        |t              rt        |t              st        d      t        |      d	k(  st        |      d	k(  rt        d
      |dk(  r||t        d      |dk(  r+t        |t              rt        |t              st        d      |dz  d	k7  s|	dz  d	k7  rt        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              r|dvrt        dt        |       d|       |/t        |t              r|dvrt        d t        |       d|       y y c c}w )!NzCannot forward both `image`: z and `image_embeds`: z2. Please make sure to only forward one of the two.zbProvide either `image` or `prompt_embeds`. Cannot leave both `image` and `image_embeds` undefined.zE`image` has to be of type `torch.Tensor` or `PIL.Image.Image` but is z:Provide `pose_video`. Cannot leave `pose_video` undefined.z:Provide `face_video`. Cannot leave `face_video` undefined.z:`pose_video` and `face_video` must be lists of PIL images.r   z>`pose_video` and `face_video` must contain at least one frame.replacezProvide `background_video` and `mask_video`. Cannot leave both `background_video` and `mask_video` undefined when mode is `replace`.zW`background_video` and `mask_video` must be lists of PIL images when mode is `replace`.   z8`height` and `width` have to be divisible by 16 but are z and r   c              3   :   K   | ]  }|j                   v   y wr#   )_callback_tensor_inputs).0krd   s     r+   	<genexpr>z2WanAnimatePipeline.check_inputs.<locals>.<genexpr>  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`: 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 )animater   zM`mode` has to be of type `str` and in ('animate', 'replace') but its type is z and value is )r      zV`prev_segment_conditioning_frames` has to be of type `int` and 1 or 5 but its type is )r   ry   r   TensorPILImager   listr{   allr   rz   int)rd   rg   r   r   
pose_video
face_videobackground_video
mask_videoheightwidthrC   rD   r   "callback_on_step_end_tensor_inputsr>    prev_segment_conditioning_framesr   s   `                r+   check_inputszWanAnimatePipeline.check_inputsq  s   $ !9/w6KL> Z0 0  =\1t  Zu||%DZX]_b_h_h_n_nModeijoepdqrssYZZYZZ*d+:j$3OYZZz?a3z?a#7]^^9"2":j>P5  9j1A4&HPZ[egkPlvwwB;!urzQWX^W__dejdkklmnn-9# F
7YF
 C
 DTEaEaDb c Bl1atOkOkFkQlmo 
 -";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Zc%:dJ`>`_`dei`j_kkyz~y  A  ,7;SAEemsEs9:;>JjIkm  Ft 8; ms   =J-J-r   latent_tlatent_hlatent_wmask_lenmask_pixel_valuesreturnc	           	         |&t        j                  |d|dz
  dz  dz   ||||      }	n!|j                         j                  ||      }	d|	d d d d d |f<   |	d d d d ddf   }
t        j                  |
d| j
                        }
t        j                  |
|	d d d d dd f   gd      }	|	j                  |d	| j
                  ||      j                  dd      }	|	S )
Nr   rM   rv   rj   rk   r   r   )ru   repeatsrt   rw   )	r   zeroscloner   repeat_interleaver]   concatr   	transpose)rd   r   r   r   r   r   r   rk   rj   mask_lat_sizefirst_frame_masks              r+   get_i2v_maskzWanAnimatePipeline.get_i2v_mask  s     $!KKA11A5xQV_eM .33588e8TM)*aIXIo&(Aqs3 223CTXTrTrs&6aABh8O%PVWX%**D::Hh

)Aq/ 	 r-   r7   r6   c           
         |xs | j                   j                  }|j                  dk(  r|j                  d      }|j                  \  }}}}}	|| j
                  z  }
|	| j
                  z  }|j                  ||      }t        |t              rJ|D cg c])  }t        | j                   j                  |      ||      + }}t        j                  |      }n&t        | j                   j                  |      ||      }t        j                  | j                   j                  j                        j!                  d| j                   j                  j"                  ddd      j                  |j$                  |j                        }dt        j                  | j                   j                  j&                        j!                  d| j                   j                  j"                  ddd      j                  |j$                  |j                        z  }||z
  |z  }|j                  d   dk(  r|dkD  r|j)                  |dddd      }| j+                  |d|
|dd ||      }t        j                  ||gd	      }|S c c}w )
NrM   r   r   r6   r7   r         ?r   rw   rt   )rG   rk   ndim	unsqueezer   r_   r   ry   r   r@   encoder   r   tensorr[   latents_meanr   z_dimrj   latents_stdexpandr   )rd   r   r   r7   r6   rk   rj   r   r   r   latent_heightlatent_widthgref_image_latentsr   latents_recip_stdreference_image_maskreference_image_latentss                     r+   prepare_reference_image_latentsz2WanAnimatePipeline.prepare_reference_image_latents  s@    '::?OOA&E!&1a$"?"?? = == e4i& ir!cd !71R]^! ! !&		*; < 01GT_ ` LL556T!TXX__**Aq!4R!((*;*A*AB 	
  %,,txx/J/J"K"P"PQRTXT\T\TcTcTiTiklnoqr"s"v"v$$&7&=&=#
 
 /=ARR ""1%*zA~ 1 8 8RRQS T  $00Q|]^`dfkmst"'))-ACT,U[\"]&&3!s   .I8M        r   prev_segment_cond_videor   r   segment_frame_lengthstart_framer   r   prev_segment_cond_framestaskinterpolation_modec                    |xs | j                   j                  }|B|
dk(  r|d d d d d |	f   j                  |      }n|d|	||f}t        j                  |||      }|j
                  \  }}}}}|dz
  | j                  z  dz   }|| j                  z  }|| j                  z  }||k7  s||k7  rxt        d| d| d| d| d	       |j                  dd	      j                  d
d      }t        j                  |||f|      }|j                  d
|df      j                  dd	      }|
dk(  r|d d d d |	d f   j                  |      }n!||	z
  }t        j                  |||||||      }|j                  |      }t        j                  ||gd	      }t        |t               r|t#        |      k(  rTt%        |      D cg c]=  \  }}t'        | j                   j)                  ||   j+                  d
            ||      ? }}}nS|dk(  r4|D cg c](  }t'        | j                   j)                  |      ||      * }}nt-        dt#        |       d|       t        j                  |      }n&t'        | j                   j)                  |      ||      }t        j.                  | j                   j0                  j2                        j5                  d| j                   j0                  j6                  ddd      j                  |j8                  |j                        }dt        j.                  | j                   j0                  j:                        j5                  d| j                   j0                  j6                  ddd      j                  |j8                  |j                        z  } ||z
  | z  }|
dk(  rpd|z
  }|j=                  d
d	ddd      }|j                  d
d      }t        j                  |||fd      }|j                  d
|df      }!|!j=                  d
d	ddd      }!nd }!| j?                  |||||d
kD  r|	nd
|!||      }"t        j                  |"|gd      }|S c c}}w c c}w )Nr   r   rv   r   z,Interpolating prev segment cond video from (, ) to ()r   r   )r   r>   rw   rk   rt   z:The batch size of the prev segment video should be either z or 1 but is r   rM   nearest)r   r   rk   rj   ) rG   rk   r   r   r   r   r]   r_   printr   flattenFinterpolate	unflattenr   ry   r   r{   	enumerater@   r   r   r   r   r[   r   r   r   rj   r   permuter   )#rd   r   r   r   r   r   r   r   r   r   r   r   r7   r6   rk   rj   cond_frames_shapedata_batch_sizechannelsr   segment_heightsegment_widthnum_latent_framesr   r   remaining_segmentremaining_segment_framesfull_segment_cond_videoir   prev_segment_cond_latentsr   r   r   prev_segment_cond_masks#                                      r+   !prepare_prev_segment_cond_latentsz4WanAnimatePipeline.prepare_prev_segment_cond_latents  s   * '"*y *:1aAZBZAZ;Z*[*^*^_d*e'%/4LfV[$\!*/++6Gu]c*d'F]FcFcC1nm1A5$:X:XX[\\$"?"?? = ==V#}'=>}oRP^O__efkellnounvvwx '>&G&G1&M&U&UVWYZ&[#&'mm'vuoDV'# '>&G&GJXZK[&\&f&fghjk&l# 9 0A7O7P1P Q T TUZ [';>V'V$ %H&>UZci!
 #:"<"<5"<"I"'))-DFW,X^_"`i&#i.0 !*) 4-1 %TXX__5LQ5O5Y5YZ[5\%]_`bmn-) - !A% ir-cd$TXX__5L%MqR]^-) - !PQTU^Q_P` a'(*  ).		2K(L%(8 78)[)%
 LL556T!TXX__**Aq!4R)002K2Q2QR 	
  %,,txx/J/J"K"P"PQRTXT\T\TcTcTiTiklnoqr"s"v"v%,,.G.M.M#
 
 &?%MQb$b! 9ZJ#++Aq!Q:J#++Aq1Jz8U\efJ * 4 4QR8H I 1 9 9!Q1a H $!%!2!21<q-a/ "3 	"
 %*II/EG`.agh$i!((k--s   AQ#-Q)r   c                    |j                  |||n| j                  j                        }t        |t              rJ|D cg c])  }t        | j                  j                  |      ||      + }}t        j                  |      }n&t        | j                  j                  |      ||      }t        j                  | j                  j                  j                        j                  d| j                  j                  j                  ddd      j                  |j                  |j                        }	dt        j                  | j                  j                  j                        j                  d| j                  j                  j                  ddd      j                  |j                  |j                        z  }
||	z
  |
z  }|j                   d   dk(  r|dkD  r|j#                  |dddd      }|S c c}w )Nr   r   r   r   r   rw   )r   rG   rk   ry   r   r@   r   r   r   r   r[   r   r   r   rj   r   r   r   )rd   r   r   r7   r6   rk   rj   r   pose_latentsr   r   s              r+   prepare_pose_latentsz'WanAnimatePipeline.prepare_pose_latents  s     ]]&ARX\X`X`XfXf]g
i&mvhi !<WbcL  !99\2L+DHHOOJ,GT_`L LL556T!TXX__**Aq!4R##\%7%78 	
  %,,txx/J/J"K"P"PQRTXT\T\TcTcTiTiklnoqr"s"v"v!3!3#
 
 %|37HHa A%*q.'..z2r2rJL%s    .G5num_channels_latents
num_framesr<   c
                 >   |dz
  | j                   z  dz   }
|| j                  z  }|| j                  z  }|||
dz   ||f}t        |t              r)t	        |      |k7  rt        dt	        |       d| d      |	t        ||||      }	|	S |	j                  ||      }	|	S )Nr   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.)r6   rj   rk   r   )r]   r_   ry   r   r{   r   r   r   )rd   r   r
  r   r   r  rk   rj   r6   r<   r   r   r   r   s                 r+   prepare_latentsz"WanAnimatePipeline.prepare_latents  s     (!^0N0NNQRR$"?"?? = ==13Dq3H-Yefi&3y>Z+GA#i.AQ R&<'gi 
 ?"5IfTYZG  jjej<Gr-   framesnum_target_framesc                     d}d}g }t        |      |k  rR|j                  t        ||                |r|dz  }n|dz  }|dk(  s|t        |      dz
  k(  r| }t        |      |k  rR|S )a9  
        Pads an array-like video `frames` to `num_target_frames` using a "reflect"-like strategy. The frame dimension
        is assumed to be the first dimension. In the 1D case, we can visualize this strategy as follows:

        pad_video_frames([1, 2, 3, 4, 5], 10) -> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2]
        r   Fr   )r{   appendr   )rd   r  r  idxfliptarget_framess         r+   pad_video_framesz#WanAnimatePipeline.pad_video_frames  s     - #44  &+!67qqax3#f+/1x - #44 r-   c                     | j                   S r#   _guidance_scalerd   s    r+   guidance_scalez!WanAnimatePipeline.guidance_scale  s    ###r-   c                      | j                   dkD  S )Nr   r  r  s    r+   r   z.WanAnimatePipeline.do_classifier_free_guidance  s    ##a''r-   c                     | j                   S r#   )_num_timestepsr  s    r+   num_timestepsz WanAnimatePipeline.num_timesteps  s    """r-   c                     | j                   S r#   )_current_timestepr  s    r+   current_timestepz#WanAnimatePipeline.current_timestep      %%%r-   c                     | j                   S r#   )
_interruptr  s    r+   	interruptzWanAnimatePipeline.interrupt  s    r-   c                     | j                   S r#   )_attention_kwargsr  s    r+   attention_kwargsz#WanAnimatePipeline.attention_kwargs  r"  r-      r   npr   num_inference_stepsr>   r   motion_encode_batch_sizer  r   output_typereturn_dictr(  callback_on_step_endr   c                    t        |t        t        f      r|j                  }| 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   }t!        |      }|
|z
  }||z
  |z  } | dk(  rd}!n|| z
  }!||!z   }"|"|z  }#| j%                  ||| j&                  |||||      \  }}| j(                  j*                  }$|j-                  |$      }||j-                  |$      }| j.                  j1                  |      \  }%}&|%|k7  s|&|	k7  r"t        j                  d|& d	|% d
|	 d	| d	       | j2                  j5                  |||	d      j-                  |t6        j8                        }'|| j;                  ||      }|j=                  ||z  dd      }|j-                  |$      }| j?                  ||"      }| j?                  ||"      }|d   j@                  \  }(})|)|k7  s|(|	k7  r"t        j                  d|( d	|) d
|	 d	| d	       | j.                  jC                  |||	      j-                  |t6        j8                        }|d   j@                  \  }*}+| j(                  jD                  jF                  },|*|,k7  s|+|,k7  r"t        j                  d|* d	|+ d
|, d	|, d	       | j.                  jC                  ||,|,      j-                  |t6        j8                        }|dk(  r| j?                  ||"      }| j?                  ||"      }| j.                  jC                  |||	      j-                  |t6        j8                        }| jH                  jC                  |||	      j-                  |t6        j8                        }| jJ                  jM                  ||       | jJ                  jN                  }-| jP                  jD                  jR                  }.| jU                  |'||z  ||      }/d}0|
}1g }2d}3tW        |#      D ]  }4|0|z   |k  sJ | jY                  ||z  |.||	|
t6        j8                  |||0dk(  r|nd	      }|dddd|0|1f   }5|dddd|0|1f   }6|6j[                  ||z  dddd      }6|6j-                  |$      }6|0dkD  r,|3dddd| df   j]                         j_                         }7nd}7|dk(  rM|dddd|0|1f   }8|dddd|0|1f   }9|8j[                  ||z  dddd      }8|9j[                  ||z  dddd      }9nd}8d}9| ja                  |5||z  ||      }:|:j-                  |$      }:| jc                  |7|8|9||z  |
|0||	||||      };t7        jd                  |/|;gd      }<t!        |-      || jJ                  jf                  z  z
  }=t!        |-      | _4        | jk                  |      5 }>tm        |-      D ]  \  }?}@| jn                  r@| _        t7        jd                  ||<gd      j-                  |$      }A|@j[                  |j"                  d         }B| j(                  jq                  d      5  | j)                  AB|||:|6||d	      d   }Cddd       | j&                  rT|6dz  dz
  }D| j(                  jq                  d      5  | j)                  AB|||:D||d	      d   }E|E|C|Ez
  z  z   }Cddd       | jJ                  js                  C@|d      d   }|Zi }F|D ]  }Gtu               |G   F|G<     || |?@F      }H|Hjw                  d|      }|Hjw                  d |      }|Hjw                  d!|      }|?t!        |-      dz
  k(  s'|?dz   |=kD  r/|?dz   | jJ                  jf                  z  dk(  r|>jy                          tz        st}        j~                           	 ddd       |j-                  | jP                  j*                        }t7        j                  | jP                  jD                  j                        j                  d| jP                  jD                  jR                  ddd      j-                  |j                  |j*                        }Id"t7        j                  | jP                  jD                  j                        j                  d| jP                  jD                  jR                  ddd      j-                  |j                  |j*                        z  }J||Jz  |Iz   }| jP                  j                  |ddddddf   d      d   }3|0dkD  r|3dddd|df   }3|2j                  |3       |0|z  }0|1|z  }1| jJ                  jM                  ||       | jJ                  jN                  }- d| _        |0|z   |k\  sJ |d#k(  sAt7        jd                  |2d      ddddd|f   }K| j.                  j                  |K|$      }Kn|}K| j                          |sKfS t        K%      S # 1 sw Y   xY w# 1 sw Y   OxY w# 1 sw Y   nxY w)&au  
        The call function to the pipeline for generation.

        Args:
            image (`PipelineImageInput`):
                The input character image to condition the generation on. Must be an image, a list of images or a
                `torch.Tensor`.
            pose_video (`List[PIL.Image.Image]`):
                The input pose video to condition the generation on. Must be a list of PIL images.
            face_video (`List[PIL.Image.Image]`):
                The input face video to condition the generation on. Must be a list of PIL images.
            background_video (`List[PIL.Image.Image]`, *optional*):
                When mode is `"replace"`, the input background video to condition the generation on. Must be a list of
                PIL images.
            mask_video (`List[PIL.Image.Image]`, *optional*):
                When mode is `"replace"`, the input mask video to condition the generation on. Must be a list of PIL
                images.
            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`).
            mode (`str`, defaults to `"animation"`):
                The mode of the generation. Choose between `"animate"` and `"replace"`.
            prev_segment_conditioning_frames (`int`, defaults to `1`):
                The number of frames from the previous video segment to be used for temporal guidance. Recommended to
                be 1 or 5. In general, should be 4N + 1, where N is a non-negative integer.
            motion_encode_batch_size (`int`, *optional*):
                The batch size for batched encoding of the face video via the motion encoder. This allows trading off
                inference speed for lower memory usage by setting a smaller batch size. Will default to
                `self.transformer.config.motion_encoder_batch_size` if not set.
            height (`int`, defaults to `720`):
                The height of the generated video.
            width (`int`, defaults to `1280`):
                The width of the generated video.
            segment_frame_length (`int`, defaults to `77`):
                The number of frames in each generated video segment. The total frames of video generated will be equal
                to the number of frames in `pose_video`; we will generate the video in segments until we have hit this
                length. In general, should be 4N + 1, where N is a non-negative integer.
            num_inference_steps (`int`, defaults to `20`):
                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 `1.0`):
                Guidance scale as defined in [Classifier-Free Diffusion
                Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
                of [Imagen Paper](https://huggingface.co/papers/2205.11487). 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. By default, CFG is not used in Wan
                Animate inference.
            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.
            negative_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 `negative_prompt` input argument.
            image_embeds (`torch.Tensor`, *optional*):
                Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
                image embeddings are generated from the `image` 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.
        r   z2`segment_frame_length - 1` has to be divisible by z!. Rounding to the nearest number.NFr   )rg   r   r   rh   rC   rD   ri   rj   z Reshaping reference image from (r   r   r   fill)r   r   resize_moder   zReshaping pose video from ()r   r   zReshaping face video from (r   )rj   )r6   rj   )r
  r   r   r  rk   rj   r6   r<   rw   )r   r   r   r   r   r   r   r   r   r6   rj   r   rt   )totalcond)	r   timestepencoder_hidden_statesencoder_hidden_states_imagepose_hidden_statesface_pixel_valuesr,  r(  r.  uncond)r.  r<   rC   rD   r   latent)r-  )r  )Jry   r   r   tensor_inputsr   r]   loggerwarningmaxr  r'  r   r$  rx   rz   r   r{   r   r   r   rK   rk   r   r`   get_default_height_widthrc   
preprocessr   float32r   r   r  r   preprocess_videor[   motion_encoder_sizera   rH   set_timesteps	timestepsrG   r   r   ranger  r   r   detachr	  r  r   orderr  progress_barr   r%  cache_contextsteplocalspopupdateXLA_AVAILABLExm	mark_stepr   r   r   rj   r   decoder  postprocess_videomaybe_free_model_hooksr!   )Lrd   r   r   r   r   r   rg   r   r   r   r   r+  r>   r   r,  r  rh   r6   r<   rC   rD   r   r-  r.  r(  r/  r   ri   rj   r   cond_video_frameseffective_segment_lengthlast_segment_framesnum_padding_framesr  num_segmentstransformer_dtypeimage_heightimage_widthimage_pixelspose_video_widthpose_video_heightface_video_widthface_video_heightexpected_face_sizerF  r
  r   startendall_out_frames
out_framesr   pose_video_segmentface_video_segmentr   background_video_segmentmask_video_segmentr  r  reference_latentsnum_warmup_stepsrJ  r  tlatent_model_inputr5  
noise_predface_pixel_values_uncondnoise_uncondcallback_kwargsr   callback_outputsr   r   videosL                                                                               r+   __call__zWanAnimatePipeline.__call__  sR   J *-=?U,VW1E1S1S. 	".,	
$  $"@"@@AENNDTEcEcDd e# $
 %(F(FFIgIggjkk !  ##7;-!1!%'' *VS"9JJvt$<VJ&,,Q/J  
O#7:Z#Z 03SSWoo!#!"!9<O!O-0BB(,DD 150B0B+(,(H(H"7'#9 3 1C 	1
-- !,,22%(():;!-%;%>%>?P%Q" %)$8$8$Q$QRW$X!k6![E%9NN=k]"\NZ`af`ggijpiqqrst//::5W\jp:qtt%-- u 

 ,,UF;L#**:8M+MqRST#'89 **:7HI
**:7HI
 /9m.@.@++&*:e*CNN-.>-?rBSATTZ[`Zaacdjckklm )):::f\a:bee%-- f 

 /9m.@.@++!--44HH115FJ\5\NN-.>-?rBSATTZ[mZn o&'q* ))::19K ; 

"V5=="
) 	 9#445EGXY..z;LMJ#33DDEU^dlqDruuemm  v   66GG
[ainGorremm s J
 	$$%8$HNN,,	  $xx44 #'"F"F*'<<	Z` #G #

 "
|$ V	1A;;>OOOO **22%9/mm##(A:4 + 
G ",Aq%)O!<!+Aq%)O!<!3!:!::H];]_acegikm!n!3!6!6=N!6!Oqy*4Q<\;\;]5]*^*d*d*f*m*m*o'*.'y +;Aq%)O+L(%/1eCi%@"+C+J+J!66BB,( &8%>%>zLa?acegikmoq%r"+/(%)"44"J1F$FR[dj 5 L (??1B?CL(,(N(N'!9-%(==%9!)I# )O )%  !&		+BD]*^de f  #9~0CdnnFZFZ0ZZ"%i.D"")<"= ;'%i0 :'DAq~~ -.D* */G=N3OUV)W)Z)Z[l)m& xxa(89H))77? %)%5%5*<%-2?8D/;.@5M-=(- &6 
& 
&
 773E3IA3M0!--;;HE e+/+;+;.@)16L<H3?2J9Q1A,1 ,< 
,  
,!L *6*WcJc8d)dJe #nn11*aV[1\]^_G+7*,!C =A17!OA.=+?aO+\("2"6"6y'"J(8(<(<_m(\1A1E1EF^`v1w. C	NQ..AE=M3MSTWXSX\`\j\j\p\pRptuRu$++-$u:';'z jj0G TXX__99:a..1a8GNNGMM2 
 !$ell488??3N3N&O&T&T488??((!Q'b/!0  11L@GAqr):NqQJqy'1.N.O(OP
!!*---E++C NN(()<V(L00ImV	1p "&77;LLLLh&IIn!4Q;M<M;M5MNE((::5k:ZEE 	##%8O ..u  e e7;' ;'sD   2Bk:j8	7k)k	8Ckk8k=kk
kk	)Nr   rf   NNr#   )NTr   NN   NN)NNNNNN)r   NNcuda)r   r;   NNN)NNNr   r   r   r   r   r   r   bicubicr;   NNN)r   r   r   r   NNNN)9__name__
__module____qualname____doc__model_cpu_offload_seqr   r   r   r   r   r   r   r   rX   r
   rz   r   r   r   r   rj   rk   r   r   r   boolr   r   r   r   	Generatorr   r  r	  r	   r  r   r  propertyr  r   r  r!  r%  r(  no_gradr   EXAMPLE_DOC_STRINGr   r   floatr   r   r   r   rv  __classcell__)re   s   @r+   rB   rB      s   )V LT$/ $/ '$/ 	$/
 +$/ ,$/ '$/ 2$/P )-%&#&)-'+'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5x #+/)-!X@ 48'++1  	
   $ELL1 $ c5<<'( 
@ #MQ'+)-0'||0' 0' 	0'
 E%//43H"HIJ0' $0' &0' 
0'h ;?37-1$&()"+#MQ'+)-!q)!)%,,!7q) #5<<0q) U\\*	q)
 q) "q) q) q) q) #&q) q)  q) q) E%//43H"HIJq) $q)  &!q)" 
#q)l #MQ'+)-LL  	
 E%//43H"HIJ $ & 
F %''+)-MQ*. " 	
   $ & E%//43H"HIJ %,,' 
u||U\\5<<7	8<tCy S TRUY * $ $ ( ( # # & &   & & U]]_12 =A6:(,15$&#%0126 #/0MQ*.049=/3%) 59 9B#&=z/!z/ )z/ )	z/
 #4		#89z/ T#))//23z/ c49n%z/ sDI~.z/ z/ z/ "z/ !z/ z/ +.z/ #+3-z/  !z/"  (}#z/$ E%//43H"HIJ%z/& %,,''z/(  -)z/* !) 6+z/, u||,-z/. c]/z/0 1z/2 #4S>23z/4 '(Cd+T124DF\\]
5z/: -1I;z/< !=z/ 3 z/r-   rB   )Nr:   )Dr&   copyr   typingr   r   r   r   r   r	   r
   r   regexr0   r   torch.nn.functionalnn
functionalr   transformersr   r   r   r   	callbacksr   r   rI   r   loadersr   modelsr   r   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   r`   r   pipeline_utilsr   r    pipeline_outputr!   torch_xla.core.xla_modelcore	xla_modelrQ  rP  
get_loggerrz  r=  r$   r  r,   r2   r4   r   r  rz   r@   rB   r   r-   r+   <module>r     s      D D D 
     ] ] A 1 ) D 1 b b - - . 5 . ))MM			H	%B J ck
TLL
T-5eoo-F
T\_
T^/*,> ^/r-   