
    bi3                        d dl Z 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mZ d dlmZmZ ddlmZmZ ddlmZ ddlmZ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jZ                  e.      Z/ e       rd dl0Z0dZ1d Z2d Z3d Z4	 	 	 	 d"dee5   deee6ejn                  f      deee5      deee8      fdZ9	 d#dejt                  deejv                     de6fdZ< G d  d!e%e      Z=y)$    N)AnyCallableDictListOptionalUnion)Image)AutoTokenizerUMT5EncoderModel   )MultiPipelineCallbacksPipelineCallback)WanLoraLoaderMixin)AutoencoderKLWanWanTransformer3DModel)FlowMatchEulerDiscreteScheduler)is_ftfy_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DiffusionPipeline   )WanPipelineOutputTFa_  
    Examples:
        ```python
        >>> import torch
        >>> from diffusers.utils import export_to_video
        >>> from diffusers import AutoencoderKLWan, WanVideoToVideoPipeline
        >>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler

        >>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
        >>> model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
        >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
        >>> pipe = WanVideoToVideoPipeline.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 = "A robot standing on a mountain top. The sun is setting in the background"
        >>> 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"
        >>> video = load_video(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
        ... )
        >>> output = pipe(
        ...     video=video,
        ...     prompt=prompt,
        ...     negative_prompt=negative_prompt,
        ...     height=480,
        ...     width=720,
        ...     guidance_scale=5.0,
        ...     strength=0.7,
        ... ).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    k/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/wan/pipeline_wan_video2video.pybasic_cleanr'   S   s3    ==D==t,-D::<    c                 T    t        j                  dd|       } | j                         } | S )Nz\s+ )resubr#   r$   s    r&   whitespace_cleanr-   Y   s$    66&#t$D::<DKr(   c                 .    t        t        |             } | S r   )r-   r'   r$   s    r&   prompt_cleanr/   _   s    K-.DKr(   num_inference_stepsdevice	timestepssigmasc                    ||t        d      |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS  | j                  |fd	|i| | j                  }||fS )a  
    Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
    custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.

    Args:
        scheduler (`SchedulerMixin`):
            The scheduler to get timesteps from.
        num_inference_steps (`int`):
            The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
            must be `None`.
        device (`str` or `torch.device`, *optional*):
            The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
        timesteps (`List[int]`, *optional*):
            Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
            `num_inference_steps` and `sigmas` must be `None`.
        sigmas (`List[float]`, *optional*):
            Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
            `num_inference_steps` and `timesteps` must be `None`.

    Returns:
        `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
        second element is the number of inference steps.
    zYOnly one of `timesteps` or `sigmas` can be passed. Please choose one to set custom valuesr2   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r2   r1   r3   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r3   r1   r1    )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r2   len)	schedulerr0   r1   r2   r3   kwargsaccepts_timestepsaccept_sigmass           r&   retrieve_timestepsrC   e   s   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	 	M)FMfM''	!)n ))) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	 	GvfGG''	!)n ))) 	 	 3MFMfM''	)))r(   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)hasattrrH   rI   moderK   AttributeError)rD   rE   rF   s      r&   retrieve_latentsrO      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
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	 	 	 	 	 d<dZ	 	 	 	 	 	 	 	 	 	 d=deej,                     dededededeej&                     deej$                     d eej2                     d!eej,                     d"eej,                     fd#Zd$ Zed%        Zed&        Zed'        Zed(        Z ed)        Z!ed*        Z" ejF                          e$e%      d
d
d
ddd+d
d,d-dd
d
d
d
d.dd
d
d!gd/fdee&jL                     deeee   f   deeee   f   deded0ed1eee      d2e'd3e'dee   d eeej2                  eej2                     f      d!eej,                     deej,                     deej,                     d4ee   d5ed6ee(ee)f      d7eee*eee(gd
f   e+e,f      d8ee   def(d9              Z- xZ.S )>WanVideoToVideoPipelinea  
    Pipeline for video-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.
        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)rK   prompt_embedsnegative_prompt_embeds	tokenizertext_encodertransformervaer?   c                 \   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)rW   rU   rT   rV   r?   rW   r         )vae_scale_factor)super__init__register_modulesgetattrsumrW   temperal_downsamplevae_scale_factor_temporalr>   vae_scale_factor_spatialr   video_processor)selfrT   rU   rV   rW   r?   r=   s         r&   r]   z WanVideoToVideoPipeline.__init__   s     	%# 	 	
 T[[_afhlSmc$((2N2N.O)Ost&RYZ^`egkRlS1M1M-N(Nrs%-t?\?\]r(   Nr   promptnum_videos_per_promptmax_sequence_lengthr1   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)paddingrk   
truncationadd_special_tokensreturn_attention_maskreturn_tensorsr   r   dim)ri   r1   )_execution_devicerU   ri   
isinstancestrr/   r>   rT   	input_idsattention_maskgtr`   longtolast_hidden_stateziptorchstackcat	new_zerossizeshaperepeatview)re   rf   rg   rh   r1   ri   u
batch_sizetext_inputstext_input_idsmaskseq_lensrR   v_seq_lens                   r&   _get_t5_prompt_embedsz-WanVideoToVideoPipeline._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_guidancerR   rS   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   )rf   rg   rh   r1   ri    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`.)	ru   rv   rw   r>   r   r   type	TypeErrorr6   )re   rf   r   r   rg   rR   rS   rh   r1   ri   r   s              r&   encode_promptz%WanVideoToVideoPipeline.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    |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        d      y y c c}
w )N   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kre   s     r&   	<genexpr>z7WanVideoToVideoPipeline.check_inputs.<locals>.<genexpr>h  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 z3Only one of `video` or `latents` should be provided)r6   allr   rv   rw   listr   )re   rf   r   heightwidthvideorK   rR   rS   "callback_on_step_end_tensor_inputsr   s   `          r&   check_inputsz$WanVideoToVideoPipeline.check_inputsY  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!4RSS "51 pHs   D0%D0  @  r   r   num_channels_latentsr   r   rE   rK   timestepc           
         t        |t              r)t        |      |k7  rt        dt        |       d| d      |	$|j	                  d      dz
  | j
                  z  dz   n|	j	                  d      }||||| j                  z  || j                  z  f}|	|D cg c]7  }t        | j                  j                  |j                  d            d      9 }}t        j                  |d	      j                  |      }t        j                  | j                  j                  j                         j#                  d| j                  j                  j$                  ddd      j                  ||      }d
t        j                  | j                  j                  j&                        j#                  d| j                  j                  j$                  ddd      j                  ||      z  }||z
  |z  }t)        ||||      }t+        | j,                  d      r| j,                  j/                  |||
      }	|	S | j,                  j1                  ||
|      }	|	S |	j                  |      }	|	S c c}w )Nz/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.r   r   r   rJ   )rF   rr         ?)rE   r1   ri   	add_noise)rv   r   r>   r6   r   rb   rc   rO   rW   encode	unsqueezer   r   r|   tensorconfiglatents_meanr   z_dimlatents_stdr   rL   r?   r   scale_noise)re   r   r   r   r   r   ri   r1   rE   rK   r   num_latent_framesr   vidinit_latentsr   r   noises                     r&   prepare_latentsz'WanVideoToVideoPipeline.prepare_latents  sB    i&3y>Z+GA#i.AQ R&<'gi  JQUZZ]Q4#A#AAAE^e^j^jkl^m 	  d333T222
 ?qvwjm,TXX__S]]1=M-N\dewLw 99\q9<<UCL TXX__99:??488??CXCXZ[]^`abeeflnst  TXX__-H-H I N NqRVRZRZRaRaRgRgijlmop q t t! K )<7;FL )FRWXEt~~{3..22<Q 	 ..44\8US  jj(G+ xs   <I&c                     t        t        ||z        |      }t        ||z
  d      }||| j                  j                  z  d  }|||z
  fS )Nr   )minintmaxr?   order)re   r0   r2   strengthr1   init_timestept_starts          r&   get_timestepsz%WanVideoToVideoPipeline.get_timesteps  sY    C 3h >?ATU)M91=g(<(<<>?	-777r(   c                     | j                   S r   _guidance_scalere   s    r&   guidance_scalez&WanVideoToVideoPipeline.guidance_scale  s    ###r(   c                      | j                   dkD  S )Nr   r   r   s    r&   r   z3WanVideoToVideoPipeline.do_classifier_free_guidance  s    ##c))r(   c                     | j                   S r   )_num_timestepsr   s    r&   num_timestepsz%WanVideoToVideoPipeline.num_timesteps  s    """r(   c                     | j                   S r   )_current_timestepr   s    r&   current_timestepz(WanVideoToVideoPipeline.current_timestep      %%%r(   c                     | j                   S r   )
_interruptr   s    r&   	interruptz!WanVideoToVideoPipeline.interrupt  s    r(   c                     | j                   S r   )_attention_kwargsr   s    r&   attention_kwargsz(WanVideoToVideoPipeline.attention_kwargs  r   r(   2   g      @g?npi   r0   r2   r   r   output_typereturn_dictr   callback_on_step_endr   c                    t        |t        t        f      r|j                  }|xs- | j                  j
                  j                  | j                  z  }|xs- | j                  j
                  j                  | j                  z  }d}
| j                  |||||||||	       || _
        || _        d| _        d| _        | j                  }|t        |t              rd}n-|t        |t               rt#        |      }n|j$                  d   }| j'                  ||| j(                  |
||||      \  }}| j                  j*                  }|j-                  |      }||j-                  |      }t/        | j0                  |||      \  }}| j3                  |||	|      \  }}|dd j5                  ||
z        }t#        |      | _        |=| j8                  j;                  |||      j-                  |t<        j>                        }| j                  j
                  j@                  }| jC                  |||
z  |||t<        j>                  ||||
      }t#        |      || j0                  jD                  z  z
  }t#        |      | _        | jG                  |      5 }tI        |      D ]t  \  }}| jJ                  r|| _        |j-                  |      }|jM                  |j$                  d         }| j	                  ||||d	      d   } | j(                  r$| j	                  ||||d	      d   }!|!|| |!z
  z  z   } | j0                  jO                  | ||d
      d   }|Zi }"|D ]  }#tQ               |#   |"|#<     || |||"      }$|$jS                  d|      }|$jS                  d|      }|$jS                  d|      }|t#        |      dz
  k(  s'|dz   |kD  r/|dz   | j0                  jD                  z  dk(  r|jU                          tV        satY        jZ                          w 	 ddd       d| _        |dk(  s~|j-                  | j\                  j*                        }t=        j^                  | j\                  j
                  j`                        jc                  d| j\                  j
                  jd                  ddd      j-                  |jf                  |j*                        }%dt=        j^                  | j\                  j
                  jh                        jc                  d| j\                  j
                  jd                  ddd      j-                  |jf                  |j*                        z  }&||&z  |%z   }| j\                  jk                  |d
      d   }| j8                  jm                  ||      }n|}| jo                          |s|fS tq        |      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.
            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://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.
            strength (`float`, defaults to `0.8`):
                Higher strength leads to more differences between original image and generated video.
            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.
        r   NFr   )rf   r   r   rg   rR   rS   rh   r1   )r   r   )ri   )total)hidden_statesr   encoder_hidden_statesr   r   )r   rK   rR   rS   latentr   )r   )frames)9rv   r   r   tensor_inputsrV   r   sample_heightrc   sample_widthr   r   r   r   r   ru   rw   r   r>   r   r   r   ri   r|   rC   r?   r   r   r   rd   preprocess_videor   float32in_channelsr   r   progress_bar	enumerater   expandsteplocalspopupdateXLA_AVAILABLExm	mark_steprW   r   r   r   r   r1   r   decodepostprocess_videomaybe_free_model_hooksr   )'re   r   rf   r   r   r   r0   r2   r   r   rg   rE   rK   rR   rS   r   r   r   r   r   rh   r1   r   transformer_dtypelatent_timestepr   num_warmup_stepsr   itlatent_model_inputr   
noise_prednoise_uncondcallback_kwargsr   callback_outputsr   r   s'                                          r&   __call__z WanVideoToVideoPipeline.__call__  s   z *-=?U,VW1E1S1S.`4++22@@4C`C``]))00==@]@]] ! 	".
	
  .!1!%'' *VS"9JJvt$<VJ&,,Q/J 150B0B+(,(H(H"7'#9 3 1C 	1
-- !,,22%(():;!-%;%>%>?P%Q" *<DNNL_agir)s&	&)-););<OQZ\dfl)m&	&#BQ-..z<Q/QR!)n?((99%V[9\__emm ` E
  $//66BB&&.. MM
 y>,?$..BVBV,VV!)n%89 -	#\!), ,#1>>)*&%,ZZ0A%B"88GMM!$45!--"4%*7%5 % .  
 33#'#3#3&8!).D)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 '') LLNY,#-	#^ "&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 ..O-	# -	#s   E+WWW)Nr      NN)NTr   NNr   NN)NNNNN)
Nr   r   r   r   NNNNN)/__name__
__module____qualname____doc__model_cpu_offload_seqr   r
   r   r   r   r   r]   r   rw   r   r   r   r   r1   ri   r   boolTensorr   r   	Generatorr   r   propertyr   r   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr	   floatr   r   r   r   r   r   __classcell__)r=   s   @r&   rQ   rQ      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 #+/,T` )-$&'+)-/3*.+/4%4 4 "	4
 4 4 $4 &4 EOO,4 %,,'4 5<<(4n8 $ $ * * # # & &   & & U]]_12 $((,15#%)- #/0MQ*.049=%) 59 9B#&/t/EKK t/ c49n%t/ sDI~.	t/
 t/ t/ !t/ DI&t/ t/ t/  (}t/ E%//43H"HIJt/ %,,'t/  -t/ !) 6t/  c]!t/" #t/$ #4S>2%t/& '(Cd+T124DF\\]
't/, -1I-t/. !/t/ 3 t/r(   rQ   )NNNN)NrI   )>r!   r8   typingr   r   r   r   r   r   regexr+   r   PILr	   transformersr
   r   	callbacksr   r   loadersr   modelsr   r   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   rd   r   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr  loggerr   r  r'   r-   r/   r   rw   r1   r  rC   r  r  rO   rQ   r5   r(   r&   <module>r     s2     = =    8 A ) = 9 b b - - . . ))MM			H	%  F *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*z ck
TLL
T-5eoo-F
T\_
Tg//1C g/r(   