
    bi                        d dl 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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*  e        rd dl+m,c m-Z. dZ/ndZ/ e!j`                  e1      Z2 e       rd dl3Z3dZ4d Z5d Z6d Z7	 ddejp                  deejr                     de:fdZ; G d de(e      Z<y)    N)AnyCallableDictListOptionalTupleUnion)AutoTokenizerCLIPImageProcessorCLIPVisionModelUMT5EncoderModel   )MultiPipelineCallbacksPipelineCallback)PipelineImageInput)WanLoraLoaderMixin)AutoencoderKLWanWanTransformer3DModel)FlowMatchEulerDiscreteScheduler)is_ftfy_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DiffusionPipeline   )WanPipelineOutputTFa	  
    Examples:
        ```python
        >>> import torch
        >>> import numpy as np
        >>> from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
        >>> from diffusers.utils import export_to_video, load_image
        >>> from transformers import CLIPVisionModel

        >>> # Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers
        >>> model_id = "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers"
        >>> image_encoder = CLIPVisionModel.from_pretrained(
        ...     model_id, subfolder="image_encoder", torch_dtype=torch.float32
        ... )
        >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
        >>> pipe = WanImageToVideoPipeline.from_pretrained(
        ...     model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")

        >>> image = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
        ... )
        >>> max_area = 480 * 832
        >>> aspect_ratio = image.height / image.width
        >>> mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
        >>> height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
        >>> width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
        >>> image = image.resize((width, height))
        >>> 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."
        ... )
        >>> 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"

        >>> output = pipe(
        ...     image=image,
        ...     prompt=prompt,
        ...     negative_prompt=negative_prompt,
        ...     height=height,
        ...     width=width,
        ...     num_frames=81,
        ...     guidance_scale=5.0,
        ... ).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    c/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/wan/pipeline_wan_i2v.pybasic_cleanr*   `   s3    ==D==t,-D::<    c                 T    t        j                  dd|       } | j                         } | S )Nz\s+ )resubr&   r'   s    r)   whitespace_cleanr0   f   s$    66&#t$D::<DKr+   c                 .    t        t        |             } | S r!   )r0   r*   r'   s    r)   prompt_cleanr2   l   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)hasattrr7   r8   moder:   AttributeError)r3   r4   r5   s      r)   retrieve_latentsr>   r   st     ~}-+2I))00;;		/K84K))..00		+%%%RSSr+   c            0       f    e Zd ZdZdZg dZg dZ	 	 	 	 	 	 dBdedede	d	e
d
ededededee   def fdZ	 	 	 	 	 dCdeeee   f   dededeej.                     deej0                     f
dZ	 dDdedeej.                     fdZ	 	 	 	 	 	 	 	 dEdeeee   f   deeeee   f      dededeej8                     deej8                     dedeej.                     deej0                     fd Z	 	 	 	 	 dFd!Z	 	 	 	 	 	 	 	 	 dGded%ed&ed'ed(ed)edeej0                     deej.                     d*eeej>                  eej>                     f      d+eej8                     d,eej8                     d-e ej8                  ej8                  f   fd.Z!e"d/        Z#e"d0        Z$e"d1        Z%e"d2        Z&e"d3        Z'e"d4        Z( ejR                          e*e+      ddd"d#d$d5d6ddddddddd7dddd+gdfdedeeee   f   deeee   f   d'ed(ed)ed8ed9ed:ee   dee   d*eeej>                  eej>                     f      d+eej8                     deej8                     deej8                     d;eej8                     d,eej8                     d<e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,dA              Z1 xZ2S )HWanImageToVideoPipelinea>	  
    Pipeline for image-to-video 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.
        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 ([`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.
        transformer_2 ([`WanTransformer3DModel`], *optional*):
            Conditional Transformer to denoise the input latents during the low-noise stage. In two-stage denoising,
            `transformer` handles high-noise stages and `transformer_2` handles low-noise stages. If not provided, only
            `transformer` is used.
        boundary_ratio (`float`, *optional*, defaults to `None`):
            Ratio of total timesteps to use as the boundary for switching between transformers in two-stage denoising.
            The actual boundary timestep is calculated as `boundary_ratio * num_train_timesteps`. When provided,
            `transformer` handles timesteps >= boundary_timestep and `transformer_2` handles timesteps <
            boundary_timestep. If `None`, only `transformer` is used for the entire denoising process.
    z<text_encoder->image_encoder->transformer->transformer_2->vae)r:   prompt_embedsnegative_prompt_embeds)transformertransformer_2image_encoderimage_processorN	tokenizertext_encodervae	schedulerrF   rE   rC   rD   boundary_ratioexpand_timestepsc           
         t         |           | j                  ||||||||       | j                  |	|
       t	        | dd       r | j
                  j                  j                  nd| _        t	        | dd       r | j
                  j                  j                  nd| _
        t        | j                        | _        || _        y )N)rI   rH   rG   rE   rC   rJ   rF   rD   )rK   rL   rI         )vae_scale_factor)super__init__register_modulesregister_to_configgetattrrI   configscale_factor_temporalvae_scale_factor_temporalscale_factor_spatialvae_scale_factor_spatialr   video_processorrF   )selfrG   rH   rI   rJ   rF   rE   rC   rD   rK   rL   	__class__s              r)   rR   z WanImageToVideoPipeline.__init__   s     	%'#+' 	 		
 	~P`aRYZ^`egkRl)N)Nrs&PWX\^ceiPj(L(Lpq%-t?\?\].r+   r      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)paddingre   
truncationadd_special_tokensreturn_attention_maskreturn_tensorsr   r   dimrc   rb   )_execution_devicerH   rc   
isinstancestrr2   lenrG   	input_idsattention_maskgtsumlongtolast_hidden_stateziptorchstackcat	new_zerossizeshaperepeatview)r\   r_   r`   ra   rb   rc   u
batch_sizetext_inputstext_input_idsmaskseq_lensrA   v_seq_lens                   r)   _get_t5_prompt_embedsz-WanImageToVideoPipeline._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 )Nrf   )imagesrk   output_hidden_statesT )rp   rF   ry   rE   hidden_states)r\   r   rb   image_embedss       r)   encode_imagez$WanImageToVideoPipeline.encode_image   s_    
 1411$$E$$GJJ6R)t))MEMM))"--r+   Tnegative_promptdo_classifier_free_guidancerA   rB   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   )r_   r`   ra   rb   rc    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`.)	rp   rq   rr   rs   r   r   type	TypeError
ValueError)r\   r_   r   r   r`   rA   rB   ra   rb   rc   r   s              r)   encode_promptz%WanImageToVideoPipeline.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           
          ||t        d| d| d      ||t        d      |Ut        |t        j                        s;t        |t        j
                  j
                        st        dt        |             |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        |              j                  j                  |
t        d       j                  j                  |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    r   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kr\   s     r)   	<genexpr>z7WanImageToVideoPipeline.check_inputs.<locals>.<genexpr>g  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 zV`guidance_scale_2` is only supported when the pipeline's `boundary_ratio` is not None.zUCannot forward `image_embeds` when the pipeline's `boundary_ratio` is not configured.)r   rq   r|   TensorPILImager   allr   rr   listrV   rK   )r\   r_   r   r   heightwidthrA   rB   r   "callback_on_step_end_tensor_inputsguidance_scale_2r   s   `           r)   check_inputsz$WanImageToVideoPipeline.check_inputsL  s    !9/w6KL> Z0 0  =\1t  Zu||%DZX]_b_h_h_n_nModeijoepdqrssB;!urzQWX^W__dejdkklmnn-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;;%%-2B2Nuvv;;%%1l6Ntuu 7O17 pHs   G#!G#  @  Q   r   num_channels_latentsr   r   
num_framesr4   r:   
last_imagereturnc                 j	   |dz
  | j                   z  dz   }|| j                  z  }|| j                  z  }|||||f}t        |	t              r)t	        |	      |k7  rt        dt	        |	       d| d      |
t        ||	||      }
n|
j                  ||      }
|j                  d      }| j                  j                  r|}n|Jt        j                  ||j                  |j                  d   |j                  d   |dz
  ||      gd	      }n[|j                  d      }t        j                  ||j                  |j                  d   |j                  d   |dz
  ||      |gd	      }|j                  || 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  }t        |	t              rI|	D cg c](  }t/        | j                  j1                  |      d      * }}t        j                  |      }n;t/        | j                  j1                  |      d      }|j3                  |dddd      }|j                  |      }||z
  |z  }| j                  j                  r-t        j4                  dd|||||      }d|d d d d df<   |
||fS t        j4                  |d|||      }| d|d d d d t        t7        d|            f<   n"d|d d d d t        t7        d|dz
              f<   |d d d d ddf   }t        j8                  |d| j                         }t        j:                  ||d d d d dd d d f   gd	      }|j'                  |d| j                   ||      }|j=                  dd      }|j                  |j*                        }|
t        j:                  ||gd	      fS c c}w )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.)r4   rb   rc   )rb   rc   r   r   rl         ?r9   )r5   rn   )rm   repeatsro   )rX   rZ   rq   r   rs   r   r   ry   	unsqueezerV   rL   r|   r~   r   r   rI   rc   tensorlatents_meanr   z_dimrb   latents_stdr>   encoder   onesrangerepeat_interleaveconcat	transpose)r\   r   r   r   r   r   r   rc   rb   r4   r:   r   num_latent_frameslatent_heightlatent_widthr   video_conditionr   r   r   latent_conditionfirst_frame_maskmask_lat_sizes                          r)   prepare_latentsz'WanImageToVideoPipeline.prepare_latents  s_    (!^0N0NNQRR$"?"?? = ==13DmUabi&3y>Z+GA#i.AQ R&<'gi 
 ?"5IfTYZGjjej<G";;''#O#iiAA
UVX^`efgmnO $--a0J#iiAA
UVX^`efhrsO *,,F$((..,Q LL556T!TXX__**Aq!4R. 	
 ELL)D)DEJJ1dhhooNcNcefhiklmppNNGMM
 
 i&bk ]^ !AxX     %yy)9:/0P^fg/66z1aAN+..u5,|;{J;;''$zz1'EZ`  )*Q1W%,.>>>

:q*m\Z>?M!QU1j%9 ::;BCM!QU1j1n%= >>?(Aqs3 223CTXTrTrs&6aABPQk8R%SYZ[%**:r4;Y;Y[hjvw%//15%(()9)@)@Am5E%FANNN? s   8-R0c                     | j                   S r!   _guidance_scaler\   s    r)   guidance_scalez&WanImageToVideoPipeline.guidance_scale  s    ###r+   c                      | j                   dkD  S )Nr   r   r   s    r)   r   z3WanImageToVideoPipeline.do_classifier_free_guidance  s    ##a''r+   c                     | j                   S r!   )_num_timestepsr   s    r)   num_timestepsz%WanImageToVideoPipeline.num_timesteps  s    """r+   c                     | j                   S r!   )_current_timestepr   s    r)   current_timestepz(WanImageToVideoPipeline.current_timestep      %%%r+   c                     | j                   S r!   )
_interruptr   s    r)   	interruptz!WanImageToVideoPipeline.interrupt  s    r+   c                     | j                   S r!   )_attention_kwargsr   s    r)   attention_kwargsz(WanImageToVideoPipeline.attention_kwargs  r   r+   2   g      @npnum_inference_stepsr   r   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      }| j                  j                  |	|}	|| _        |	| _        || _        d| _        d| _        | j                   }|t        |t"              rd}n-|t        |t$              rt'        |      }n|j(                  d   }| j+                  ||| j,                  |
||||      \  }}| j.                  | j.                  j0                  n| j2                  j0                  }|j5                  |      }||j5                  |      }| j.                  o| j.                  j                  j6                  O|)|| j9                  ||      }n| j9                  ||g|      }|j;                  |dd      }|j5                  |      }| j<                  j?                  ||       | j<                  j@                  }| jB                  j                  jD                  }| jF                  jI                  |||	      j5                  |tJ        jL                  
      }|=| jF                  jI                  |||	      j5                  |tJ        jL                  
      }| jO                  |||
z  ||||tJ        jL                  ||||      }| j                  jP                  r|\  }}}n|\  }}t'        |      || j<                  jR                  z  z
  }t'        |      | _*        | j                  j                  8| j                  j                  | j<                  j                  jV                  z  } nd} | jY                  |      5 }!t[        |      D ]^  \  }"}#| j\                  r|#| _        | |#| k\  r| j.                  }$|}%n| j2                  }$|	}%| j                  jP                  rudz
  |z  ||z  z   }&|&j5                  |      }&|d   d   ddddddddf   |#z  j_                         }'|'ja                  d      jc                  |j(                  d   d      }(nFtK        jd                  ||gd      j5                  |      }&|#jc                  |j(                  d         }(|$jg                  d      5   |$|&|(|||d      d   })ddd       | j,                  r6|$jg                  d      5   |$|&|(|||d      d   }*|*|%)|*z
  z  z   })ddd       | j<                  ji                  )|#|d      d   }|Zi }+|D ]  },tk               |,   |+|,<     || |"|#|+      }-|-jm                  d|      }|-jm                  d|      }|-jm                  d|      }|"t'        |      dz
  k(  s'|"dz   |kD  r/|"dz   | j<                  jR                  z  dk(  r|!jo                          tp        sKts        jt                          a 	 ddd       d| _        | j                  jP                  rdz
  |z  ||z  z   }|dk(  s~|j5                  | jB                  j0                        }tK        jv                  | jB                  j                  jx                        j{                  d| jB                  j                  jD                  ddd      j5                  |j|                  |j0                        }.dtK        jv                  | jB                  j                  j~                        j{                  d| jB                  j                  jD                  ddd      j5                  |j|                  |j0                        z  }/||/z  |.z   }| jB                  j                  |d      d   }0| jF                  j                  |0|      }0n|}0| j                          |s|0fS t        |0      S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w)a  
        The call function to the pipeline for generation.

        Args:
            image (`PipelineImageInput`):
                The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
            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`).
            height (`int`, defaults to `480`):
                The height of the generated video.
            width (`int`, defaults to `832`):
                The width of the generated video.
            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://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.
            guidance_scale_2 (`float`, *optional*, defaults to `None`):
                Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline's
                `boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2`
                and the pipeline's `boundary_ratio` are not None.
            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   z(`num_frames - 1` has to be divisible by z!. Rounding to the nearest number.NFr   )r_   r   r   r`   rA   rB   ra   rb   )rb   )r   r   )rc   )totalr   ro   rl   cond)r   timestepencoder_hidden_statesencoder_hidden_states_imager   r   uncond)r   r:   rA   rB   latentr   )r   )frames)Drq   r   r   tensor_inputsr   rX   loggerwarningmaxrV   rK   r   _guidance_scale_2r   r   r   rp   rr   r   rs   r   r   r   rC   rc   rD   ry   	image_dimr   r   rJ   set_timesteps	timestepsrI   r   r[   
preprocessr|   float32r   rL   orderr   num_train_timestepsprogress_bar	enumerater   flattenr   expandr~   cache_contextsteplocalspopupdateXLA_AVAILABLExm	mark_stepr   r   r   rb   r   decodepostprocess_videomaybe_free_model_hooksr   )1r\   r   r_   r   r   r   r   r   r   r   r`   r4   r:   rA   rB   r   r   r   r   r   r   r   ra   rb   r   transformer_dtyper   r   latents_outputs	conditionr   num_warmup_stepsboundary_timestepr   itcurrent_modelcurrent_guidance_scalelatent_model_inputtemp_tsr   
noise_prednoise_uncondcallback_kwargsr   callback_outputsr   r   videos1                                                    r)   __call__z WanImageToVideoPipeline.__call__  sK   Z *-=?U,VW1E1S1S. 	".	
 666!;NN:4;Y;Y:ZZ{| $t'E'EEHfHffijjJQ'
;;%%16F6N--!1!1!%'' *VS"9JJvt$<VJ&,,Q/J 150B0B+(,(H(H"7'#9 3 1C 	1
-- 7;6F6F6RD,,22X\XjXjXpXp%(():;!-%;%>%>?P%Q" 'D,<,<,C,C,M,M,Y#%#'#4#4UF#CL#'#4#4eZ5H&#QL'..z1a@L'??+<=L 	$$%8$HNN,,	  $xx44$$//fE/RUUV\didqdqUr!--88FZ_8`ccemm d J .... MM
 ;;''3B0GY 0!0GY y>,?$..BVBV,VV!)n;;%%1 $ : :T^^=R=R=f=f f $%89 D	#\!), C#1>>)*&$,5F0F$($4$4M-;* %)$6$6M-=*;;//*+.>*>))KN^ahNh)h&);)>)>?P)Q&  0215a1cckBQFOOQG&003::7==;KRPH).GY3GQ)O)R)RSd)e& xxa(89H"008 !.&8!).;4@)9$)" "J 33&44X> 	i'4*<%-2H8D-=(-( ( &24Jj[gNg4h%h
	i ..--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 '') LLNGC#D	#L "&;;''++y8;Kg;UUGh&jj0G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 ..K 	i 	iOD	# D	#sD   D-`<`"%`<=`/C`<0`<"`,'`</`94`<<a)NNNNNF)Nr   r^   NNr!   )NTr   NN   NN)NNNNN)	r   r   r   r   NNNNN)3__name__
__module____qualname____doc__model_cpu_offload_seqr   _optional_componentsr
   r   r   r   r   r   r   r   floatboolrR   r	   rr   r   intr|   rb   rc   r   r   r   r   r   r   	Generatorr   r   propertyr   r   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   r   r   r   r   r  __classcell__)r]   s   @r)   r@   r@      s   !F [T_ /3)--1/3*.!&/ / '/ 	/
 3/ ,/ '/ +/ -/ !/ /D )-%&#&)-'+'c49n%'  #' !	'
 &' $'X *..!. &. <@,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5p #+/;vB %''+)-MQ*.-1XO!XO XO "	XO
 XO XO XO $XO &XO E%//43H"HIJXO %,,'XO U\\*XO 
u||U\\)	*XOt $ $ ( ( # # & &   & & U]]_12 )-15#% #,0/0MQ*.049=/3-1%) 59 9B#&3{/!{/ c49n%{/ sDI~.	{/
 {/ {/ {/ !{/ {/ #5/{/  (}{/ E%//43H"HIJ{/ %,,'{/  -{/ !) 6{/  u||,!{/" U\\*#{/$ c]%{/& '{/( #4S>2){/* '(Cd+T124DF\\]
+{/0 -1I1{/2 !3{/ 3 {/r+   r@   )Nr8   )=r$   typingr   r   r   r   r   r   r	   r   regexr.   r|   transformersr
   r   r   r   	callbacksr   r   rF   r   loadersr   modelsr   r   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   r[   r   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr  r  
get_loggerr  r   r"   r)  r*   r0   r2   r   r&  rr   r>   r@   r   r+   r)   <module>r:     s     D D D 
   ] ] A 1 ) = 9 b b - - . . ))MM			H	%. b ck
TLL
T-5eoo-F
T\_
Ty
//1C y
/r+   