
    
3jW                        S SK r S SKJr  S SKrS SKrS SKJr  S SK	J
r
JrJrJr  SSKJrJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJrJrJrJr  SSKJr  SSK J!r!  SSK"J#r#  SSK$J%r%  \" 5       (       a  S SK&J's  J(r)  Sr*OSr*\RV                  " \,5      r-\" 5       (       a  S SK.r.\RV                  " \,5      r-Sr/S r0S r1S r2 " S S\#\5      r3g)    N)Callable)
functional)CLIPTextModelCLIPTokenizer"Qwen2_5_VLForConditionalGenerationQwen2VLProcessor   )MultiPipelineCallbacksPipelineCallback)KandinskyLoraLoaderMixin)AutoencoderKLHunyuanVideo)Kandinsky5Transformer3DModel)FlowMatchEulerDiscreteScheduler)is_ftfy_availableis_torch_xla_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )DiffusionPipeline   )KandinskyPipelineOutputTFa  
    Examples:

        ```python
        >>> import torch
        >>> from diffusers import Kandinsky5T2VPipeline
        >>> from diffusers.utils import export_to_video

        >>> # Available models:
        >>> # kandinskylab/Kandinsky-5.0-T2V-Pro-sft-5s-Diffusers
        >>> # kandinskylab/Kandinsky-5.0-T2V-Lite-sft-5s-Diffusers
        >>> # kandinskylab/Kandinsky-5.0-T2V-Lite-nocfg-5s-Diffusers
        >>> # kandinskylab/Kandinsky-5.0-T2V-Lite-distilled16steps-5s-Diffusers
        >>> # kandinskylab/Kandinsky-5.0-T2V-Lite-pretrain-5s-Diffusers
        >>> # kandinskylab/Kandinsky-5.0-T2V-Lite-sft-10s-Diffusers
        >>> # kandinskylab/Kandinsky-5.0-T2V-Lite-nocfg-10s-Diffusers
        >>> # kandinskylab/Kandinsky-5.0-T2V-Lite-distilled16steps-10s-Diffusers
        >>> # kandinskylab/Kandinsky-5.0-T2V-Lite-pretrain-10s-Diffusers

        >>> model_id = "kandinskylab/Kandinsky-5.0-T2V-Lite-sft-5s-Diffusers"
        >>> pipe = Kandinsky5T2VPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
        >>> pipe = pipe.to("cuda")

        >>> prompt = "A cat and a dog baking a cake together in a kitchen."
        >>> negative_prompt = "Static, 2D cartoon, cartoon, 2d animation, paintings, images, worst quality, low quality, ugly, deformed, walking backwards"

        >>> output = pipe(
        ...     prompt=prompt,
        ...     negative_prompt=negative_prompt,
        ...     height=512,
        ...     width=768,
        ...     num_frames=121,
        ...     num_inference_steps=50,
        ...     guidance_scale=5.0,
        ... ).frames[0]

        >>> export_to_video(output, "output.mp4", fps=24, quality=9)
        ```
c                     [        5       (       a  [        R                  " U 5      n [        R                  " [        R                  " U 5      5      n U R                  5       $ )z
Copied from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan.py

Clean text using ftfy if available and unescape HTML entities.
)r   ftfyfix_texthtmlunescapestriptexts    k/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/pipelines/kandinsky5/pipeline_kandinsky.pybasic_cleanr#   b   s>     }}T"==t,-D::<    c                 V    [         R                  " SSU 5      n U R                  5       n U $ )z
Copied from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan.py

Normalize whitespace in text by replacing multiple spaces with single space.
z\s+ )resubr   r    s    r"   whitespace_cleanr)   n   s&     66&#t$D::<DKr$   c                 .    [        [        U 5      5      n U $ )z
Copied from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/wan/pipeline_wan.py

Apply both basic cleaning and whitespace normalization to prompts.
)r)   r#   r    s    r"   prompt_cleanr+   y   s     K-.DKr$   c            -          ^  \ rS rSrSrSr/ SQrS\S\S\	S\
S	\S
\S\4U 4S jjrS\S\S\4S jr\SCS\S\S\S\S\S\S\R(                  4S jj5       rS r   SDS\\\   -  S\R2                  S-  S\S\R4                  S-  4S jjr  SES\\\   -  S\R2                  S-  S\R4                  S-  4S jjr    SFS\\\   -  S"\S\S\R2                  S-  S\R4                  S-  4
S# jjr        SGS$ jr        SHS%\S&\S\S\S'\S\R4                  S-  S\R2                  S-  S(\R>                  \\R>                     -  S-  S)\R(                  S-  S\R(                  4S* jjr \!S+ 5       r"\!S, 5       r#\!S- 5       r$\RJ                  " 5       \&" \'5      SSS!S.S/S0S1S SSSSSSSSS2S3SS)/S!4S\\\   -  S4\\\   -  S-  S\S\S'\S5\S6\(S"\S-  S(\R>                  \\R>                     -  S-  S)\R(                  S-  S7\R(                  S-  S8\R(                  S-  S9\R(                  S-  S:\R(                  S-  S;\R(                  S-  S<\R(                  S-  S=\S-  S>\)S?\*\\/S4   \+-  \,-  S-  S@\\   S\4*SA jj5       5       r-SBr.U =r/$ )IKandinsky5T2VPipeline   aK  
Pipeline for text-to-video generation using Kandinsky 5.0.

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:
    transformer ([`Kandinsky5Transformer3DModel`]):
        Conditional Transformer to denoise the encoded video latents.
    vae ([`AutoencoderKLHunyuanVideo`]):
        Variational Auto-Encoder Model [hunyuanvideo-community/HunyuanVideo
        (vae)](https://huggingface.co/hunyuanvideo-community/HunyuanVideo) to encode and decode videos to and from
        latent representations.
    text_encoder ([`Qwen2_5_VLForConditionalGeneration`]):
        Frozen text-encoder [Qwen2.5-VL](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct).
    tokenizer ([`AutoProcessor`]):
        Tokenizer for Qwen2.5-VL.
    text_encoder_2 ([`CLIPTextModel`]):
        Frozen [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel),
        specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
    tokenizer_2 ([`CLIPTokenizer`]):
        Tokenizer for CLIP.
    scheduler ([`FlowMatchEulerDiscreteScheduler`]):
        A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
z.text_encoder->text_encoder_2->transformer->vae)latentsprompt_embeds_qwenprompt_embeds_clipnegative_prompt_embeds_qwennegative_prompt_embeds_cliptransformervaetext_encoder	tokenizertext_encoder_2tokenizer_2	schedulerc           
        > [         TU ]  5         U R                  UUUUUUUS9  SR                  / SQ5      U l        SU l        [        U SS 5      (       a   U R                  R                  R                  OSU l
        [        U SS 5      (       a   U R                  R                  R                  OSU l        [        U R                  S9U l        g )	N)r4   r5   r6   r7   r8   r9   r:   
)zJ<|im_start|>system
You are a promt engineer. Describe the video in detail.zjDescribe how the camera moves or shakes, describe the zoom and view angle, whether it follows the objects.zPDescribe the location of the video, main characters or objects and their action.z9Describe the dynamism of the video and presented actions.zName the visual style of the video: whether it is a professional footage, user generated content, some kind of animation, video game or scren content.z_Describe the visual effects, postprocessing and transitions if they are presented in the video.zGPay attention to the order of key actions shown in the scene.<|im_end|>z<|im_start|>user
{}<|im_end|>   r5         )vae_scale_factor)super__init__register_modulesjoinprompt_template prompt_template_encode_start_idxgetattrr5   configtemporal_compression_ratiovae_scale_factor_temporalspatial_compression_ratiovae_scale_factor_spatialr   video_processor)	selfr4   r5   r6   r7   r8   r9   r:   	__class__s	           r"   rB   Kandinsky5T2VPipeline.__init__   s     	#%)# 	 	
  $yy	 
 14- ;B$t:T:TDHHOO66Z[ 	& V]]achjnUoUo(Q(Quv%-t?\?\]r$   heightwidthreturnc                 @    S nU" U5      (       a  U" U5      (       a  gg)z
Calculate the scale factor based on resolution.

Args:
    height (int): Video height
    width (int): Video width

Returns:
    tuple: Scale factor as (temporal_scale, height_scale, width_scale)
c                 ,    SU s=:*  =(       a    S:*  $ s  $ )N  iV   )xs    r"   between_480p=Kandinsky5T2VPipeline._get_scale_factor.<locals>.between_480p   s    !??s?"?"r$   )r   r   r   )r   HzG	@r[   rW   )rN   rQ   rR   rY   s       r"   _get_scale_factor'Kandinsky5T2VPipeline._get_scale_factor   s$    	# L$7$7"r$   THWwTwHwWc                 $   [         R                  " XU/5      R                  5       n[         R                  " SUS[         R                  US9nUR                  S5      UR                  S5      -
  R                  5       n	U	SU 2SU 24   R                  5       U	SU2SU24   R                  5       U	SU2SU24   R                  5       pn
XS-  :*  n
XS-  :*  nXS-  :*  nUR                  S5      UR                  S5      -  R                  XX"5      R                  SS5      R                  5       nU
R                  S5      UR                  S5      -  R                  X X-  X-  5      R                  SS5      nUR                  X-  U-  X-  U-  5      $ )aQ  
Create a sparse temporal attention (STA) mask for efficient video generation.

This method generates a mask that limits attention to nearby frames and spatial positions, reducing
computational complexity for video generation.

Args:
    T (int): Number of temporal frames
    H (int): Height in latent space
    W (int): Width in latent space
    wT (int): Temporal attention window size
    wH (int): Height attention window size
    wW (int): Width attention window size
    device (str): Device to create tensor on

Returns:
    torch.Tensor: Sparse attention mask of shape (T*H*W, T*H*W)
r   r   dtypedeviceNr   )
torchTensoramaxarangeint16	unsqueezeabsflattenreshape	transpose)r^   r_   r`   ra   rb   rc   rg   lrmatsta_tsta_hsta_wsta_hwstas                  r"   fast_sta_nabla$Kandinsky5T2VPipeline.fast_sta_nabla   s{   ( LL!#((*LLAqFC{{1~A.335BQBK!BQBK!BQBK! 
 q q q //!$uq'99BB1NXXYZ\]^ffhq!F$4$4Q$77@@quaeT^^_`bcd{{1519aeai00r$   c                    U R                   R                  R                  S   S:X  d   eUR                  u  p4pVnX@R                   R                  R                  S   -  XPR                   R                  R                  S   -  X`R                   R                  R                  S   -  penU R                   R                  R                  S:X  Gav  U R                  UUS-  US-  U R                   R                  R                  U R                   R                  R                  U R                   R                  R                  US9nUR                  S5      R                  S5      U R                   R                  R                  SU R                   R                  R                  U R                   R                  R                  U R                   R                  R                  U R                   R                  R                  U R                   R                  R                  XEU4U R                   R                  R                  S.
n	U	$ S	n	U	$ )
a  
Generate sparse attention parameters for the transformer based on sample dimensions.

This method computes the sparse attention configuration needed for efficient video processing in the
transformer model.

Args:
    sample (torch.Tensor): Input sample tensor
    device (torch.device): Device to place tensors on

Returns:
    Dict: Dictionary containing sparse attention parameters
r   r   r   nablar?   rg   T)
sta_maskattention_type
to_fractalPra   rc   rb   add_stavisual_shapemethodN)r4   rH   
patch_sizeshaper   rz   attention_wTattention_wHattention_wW
unsqueeze_attention_Pattention_add_staattention_method)
rN   samplerg   Br^   r_   r`   _r   sparse_paramss
             r"   get_sparse_params'Kandinsky5T2VPipeline.get_sparse_params  s    &&11!4999aA!!((33A66!!((33A66!!((33A66 
 ""11W<**QQ  ''44  ''44  ''44 + H %//2==a@"&"2"2"9"9"H"H"%%,,88&&--::&&--::&&--::++22DD!"q	**11BBM  !Mr$   Npromptrg   max_sequence_lengthrf   c           
         U=(       d    U R                   nU=(       d    U R                  R                  nU Vs/ s H  oPR                  R	                  U5      PM     nnU R
                  U-   nU R                  USSSSS9S   nUR                  S   U:  a  [        U5       Hs  u  pX   U R
                  S nU R                  R                  XS-
  S 5      n[        U5      S	:  d  MG  U
S[        U5      *  Xi'   [        R                  S
U SU 35        Mu     U R                  USSUSSSS9R                  U5      nU R                  US   SSS9S   S   SS2U R
                  S24   nUS   SS2U R
                  S24   n[        R                  " UR!                  S5      S	S9n["        R$                  " USS	S9R                  [        R&                  S9nUR                  U5      U4$ s  snf )aL  
Encode prompt using Qwen2.5-VL text encoder.

This method processes the input prompt through the Qwen2.5-VL model to generate text embeddings suitable for
video generation.

Args:
    prompt (str | list[str]): Input prompt or list of prompts
    device (torch.device): Device to run encoding on
    num_videos_per_prompt (int): Number of videos to generate per prompt
    max_sequence_length (int): Maximum sequence length for tokenization
    dtype (torch.dtype): Data type for embeddings

Returns:
    tuple[torch.Tensor, torch.Tensor]: Text embeddings and cumulative sequence lengths
Nptlongest)r!   imagesvideosreturn_tensorspadding	input_idsr   r   zXThe following part of your input was truncated because `max_sequence_length` is set to  z	 tokens: T)r!   r   r   
max_length
truncationr   r   )r   return_dictoutput_hidden_stateshidden_statesattention_maskr   dim)r   r   )value)rf   )_execution_devicer6   rf   rE   formatrF   r7   r   	enumeratedecodelenloggerwarningtorh   cumsumsumFpadint32)rN   r   rg   r   rf   p
full_textsmax_allowed_lenuntruncated_idsir!   tokensremoved_textinputsembedsr   
cu_seqlenss                    r"   _encode_prompt_qwen)Kandinsky5T2VPipeline._encode_prompt_qwen9  s1   . 14110**00>DEf**11!4f
E??BUU.. ) 
    $6$Z0(+D,Q,QTVW#~~44VRS<S<U5VW|$q($()=C,=+=$>JMNN/0	,I 1 &   
 "V* 	 ""[)!% # 
 	 	  !$"G"G"II	K   01!T5Z5Z5\2\]\\."4"4Q"7Q?
UU:vQ7:::M
yy++U Fs   $G*c           	          U=(       d    U R                   nU=(       d    U R                  R                  nU R                  USSSSSS9R	                  U5      nU R                  " S0 UD6S   nUR	                  U5      $ )a  
Encode prompt using CLIP text encoder.

This method processes the input prompt through the CLIP model to generate pooled embeddings that capture
semantic information.

Args:
    prompt (str | list[str]): Input prompt or list of prompts
    device (torch.device): Device to run encoding on
    num_videos_per_prompt (int): Number of videos to generate per prompt
    dtype (torch.dtype): Data type for embeddings

Returns:
    torch.Tensor: Pooled text embeddings from CLIP
M   Tr   r   )r   r   add_special_tokensr   r   pooler_outputrW   )r   r8   rf   r9   r   )rN   r   rg   rf   r   pooled_embeds         r"   _encode_prompt_clip)Kandinsky5T2VPipeline._encode_prompt_clip  s    * 14112,,22!!#  " 
 "V* 	 **4V4_Eu%%r$   r      num_videos_per_promptc                    U=(       d    U R                   nU=(       d    U R                  R                  n[        U[        5      (       d  U/n[        U5      nU Vs/ s H  n[        U5      PM     nnU R                  UUUUS9u  pU R                  UUUS9n
UR                  SUS5      nUR                  Xb-  SUR                  S   5      nU
R                  SUS5      n
U
R                  Xb-  S5      n
U	R                  5       nUR                  U5      n[        R                  " [        R                   " S/U[        R"                  S9UR%                  S5      /5      nXU4$ s  snf )a  
Encodes a single prompt (positive or negative) into text encoder hidden states.

This method combines embeddings from both Qwen2.5-VL and CLIP text encoders to create comprehensive text
representations for video generation.

Args:
    prompt (`str` or `list[str]`):
        Prompt to be encoded.
    num_videos_per_prompt (`int`, *optional*, defaults to 1):
        Number of videos to generate per prompt.
    max_sequence_length (`int`, *optional*, defaults to 512):
        Maximum sequence length for text encoding.
    device (`torch.device`, *optional*):
        Torch device.
    dtype (`torch.dtype`, *optional*):
        Torch dtype.

Returns:
    tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        - Qwen text embeddings of shape (batch_size * num_videos_per_prompt, sequence_length, embedding_dim)
        - CLIP pooled embeddings of shape (batch_size * num_videos_per_prompt, clip_embedding_dim)
        - Cumulative sequence lengths (`cu_seqlens`) for Qwen embeddings of shape (batch_size *
          num_videos_per_prompt + 1,)
)r   rg   r   rf   )r   rg   rf   r   r   r   rg   rf   )r   r6   rf   
isinstancelistr   r+   r   r   repeatviewr   diffrepeat_interleaverh   cattensorr   r   )rN   r   r   r   rg   rf   
batch_sizer   r0   prompt_cu_seqlensr1   original_lengthsrepeated_lengthsrepeated_cu_seqlenss                 r"   encode_prompt#Kandinsky5T2VPipeline.encode_prompt  s   B 14110**00&$''XF[
+126a,q/62 150H0H 3	 1I 1
- "55 6 
 066$a
 044.4F4L4LR4P

 066$a
 044Z5WY[\ -113+==!
 $ii\\1#fEKK@BRBYBYZ[B\]
 "7JJJe 3s   E#c           
        ^  Ub  US:  a  [        S5      eUS-  S:w  d	  US-  S:w  a  [        SU SU S35      eUbW  [        U 4S	 jU 5       5      (       d=  [        S
T R                   SU Vs/ s H  oT R                  ;  d  M  UPM     sn 35      eUc  Uc  U	b  Ub  Ub  U	c  [        S5      eUc  Uc  U
b  Ub  Ub  U
c  [        S5      eUc  Uc  [        S5      eUbA  [        U[        5      (       d,  [        U[
        5      (       d  [        S[        U5       35      eUbC  [        U[        5      (       d-  [        U[
        5      (       d  [        S[        U5       35      egggs  snf )a  
Validate input parameters for the pipeline.

Args:
    prompt: Input prompt
    negative_prompt: Negative prompt for guidance
    height: Video height
    width: Video width
    prompt_embeds_qwen: Pre-computed Qwen prompt embeddings
    prompt_embeds_clip: Pre-computed CLIP prompt embeddings
    negative_prompt_embeds_qwen: Pre-computed Qwen negative prompt embeddings
    negative_prompt_embeds_clip: Pre-computed CLIP negative prompt embeddings
    prompt_cu_seqlens: Pre-computed cumulative sequence lengths for Qwen positive prompt
    negative_prompt_cu_seqlens: Pre-computed cumulative sequence lengths for Qwen negative prompt
    callback_on_step_end_tensor_inputs: Callback tensor inputs

Raises:
    ValueError: If inputs are invalid
Ni   z*max_sequence_length must be less than 1024   r   z8`height` and `width` have to be divisible by 16 but are z and .c              3   @   >#    U  H  oTR                   ;   v   M     g 7f)N)_callback_tensor_inputs).0krN   s     r"   	<genexpr>5Kandinsky5T2VPipeline.check_inputs.<locals>.<genexpr>*  s      F
7Y!---7Ys   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zuIf any of `prompt_embeds_qwen`, `prompt_embeds_clip`, or `prompt_cu_seqlens` is provided, all three must be provided.zIf any of `negative_prompt_embeds_qwen`, `negative_prompt_embeds_clip`, or `negative_prompt_cu_seqlens` is provided, all three must be provided.zProvide either `prompt` or `prompt_embeds_qwen` (and corresponding `prompt_embeds_clip` and `prompt_cu_seqlens`). Cannot leave all 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 )
ValueErrorallr   r   strr   type)rN   r   negative_promptrQ   rR   r0   r1   r2   r3   r   negative_prompt_cu_seqlens"callback_on_step_end_tensor_inputsr   r   s   `             r"   check_inputs"Kandinsky5T2VPipeline.check_inputs  s   F */BT/IIJJB;!urzQWX^W__dejdkklmnn-9# F
7YF
 C
 C
 DTEaEaDbbn  |^  pH  |^vw  ko  kG  kG  bGpq  |^  pH  oI  J 
 )-?-KO`Ol!)-?-GK\Kd 2  (3*6)5 ,3.6-5 2  >08 ` 
 z&#'>'>zRXZ^G_G_QRVW]R^Q_`aa&?C00OUY9Z9ZZ[_`o[pZqrss :[0 'I pHs   .E*E*r   num_channels_latents
num_frames	generatorr/   c
                    U	b  U	R                  XvS9$ US-
  U R                  -  S-   n
UU
[        U5      U R                  -  [        U5      U R                  -  U4n[	        U[
        5      (       a*  [        U5      U:w  a  [        S[        U5       SU S35      e[        XXvS9n	U R                  R                  (       a  [        R                  " U	5      n[        R                  " UU
[        U5      U R                  -  [        U5      U R                  -  S/U	R                  U	R                  S9n[        R                   " XU/SS	9n	U	$ )
a  
Prepare initial latent variables for video generation.

This method creates random noise latents or uses provided latents as starting point for the denoising process.

Args:
    batch_size (int): Number of videos to generate
    num_channels_latents (int): Number of channels in latent space
    height (int): Height of generated video
    width (int): Width of generated video
    num_frames (int): Number of frames in video
    dtype (torch.dtype): Data type for latents
    device (torch.device): Device to create latents on
    generator (torch.Generator): Random number generator
    latents (torch.Tensor): Pre-existing latents to use

Returns:
    torch.Tensor: Prepared latent tensor
r   r   z/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.)r   rg   rf   re   r   r   )r   rJ   intrL   r   r   r   r   r   r4   visual_condrh   
zeros_likezerosrf   rg   r   )rN   r   r   rQ   rR   r   rf   rg   r   r/   num_latent_framesr   r   visual_cond_masks                 r"   prepare_latents%Kandinsky5T2VPipeline.prepare_latentsW  sL   > ::V:99'!^0N0NNQRRK4888J$777 
 i&&3y>Z+GA#i.AQ R&<'gi 
 u&V''**73K${{%K4#@#@@J$"?"?? mm~~
  ii7G HbQGr$   c                     U R                   $ )z%Get the current guidance scale value.)_guidance_scalerN   s    r"   guidance_scale$Kandinsky5T2VPipeline.guidance_scale  s     ###r$   c                     U R                   $ )z&Get the number of denoising timesteps.)_num_timestepsr   s    r"   num_timesteps#Kandinsky5T2VPipeline.num_timesteps  s     """r$   c                     U R                   $ )z)Check if generation has been interrupted.)
_interruptr   s    r"   	interruptKandinsky5T2VPipeline.interrupt  s     r$   i   y   2   g      @pilTr   num_inference_stepsr   r0   r1   r2   r3   r   r   output_typer   callback_on_step_endr   c                    [        U[        [        45      (       a  UR                  nU R	                  UUUUUUUUUUUUS9  XPR
                  -  S:w  aA  [        R                  SU R
                   S35        XPR
                  -  U R
                  -  S-   n[        US5      nXpl	        SU l
        U R                  nU R                  R                  nUb  [        U[        5      (       a  SnU/nO3Ub!  [        U[        5      (       a  [!        U5      nOUR"                  S   nUc  U R%                  UUUUS9u  pnU R&                  S	:  a  Uc  S
n[        U[        5      (       a  Ub  U/[!        U5      -  OU/nO<[!        U5      [!        U5      :w  a$  [)        S[!        U5       S[!        U5       S35      eUc  U R%                  UUUUS9u  pnU R*                  R-                  UUS9  U R*                  R.                  nU R                  R0                  R2                  nU R5                  UU-  UUUUUUU	U
5	      n
US-
  U R
                  -  S-   n[6        R8                  " UUS9[6        R8                  " X0R:                  -  S-  US9[6        R8                  " X@R:                  -  S-  US9/n[6        R8                  " UR=                  5       R                  5       R?                  5       US9nUb?  [6        R8                  " UR=                  5       R                  5       R?                  5       US9OSnU RA                  X45      nU RC                  U
U5      n [!        U5      X`R*                  RD                  -  -
  n![!        U5      U l#        U RI                  US9 n"[K        U5       GHI  u  n#n$U RL                  (       a  M  U$RO                  S5      RQ                  UU-  5      n%U R                  U
RS                  U5      URS                  U5      URS                  U5      U%RS                  U5      UUUU SS9	RT                  n&U R&                  S	:  ak  Ubh  U R                  U
RS                  U5      URS                  U5      URS                  U5      U%RS                  U5      UUUU SS9	RT                  n'U'UU&U'-
  -  -   n&U R*                  RW                  U&U$U
SS2SS2SS2SS2SU24   SS9S   U
SS2SS2SS2SS2SU24'   Ub  0 n(U H  n)[Y        5       U)   U(U)'   M     U" U U#U$U(5      n*U*R[                  SU
5      n
U*R[                  SU5      nU*R[                  SU5      nU*R[                  SU5      nU*R[                  SU5      nU#[!        U5      S-
  :X  d)  U#S-   U!:  a0  U#S-   U R*                  RD                  -  S:X  a  U"R]                  5         [^        (       d  GM4  [`        Rb                  " 5         GML     SSS5        U
SS2SS2SS2SS2SU24   n
US:w  Ga"  U
RS                  U Rd                  R                  5      n
U
Rg                  UUUS-
  U R
                  -  S-   X0R:                  -  X@R:                  -  U5      n+U+Ri                  SSSSSS5      n+U+Rg                  UU-  UUS-
  U R
                  -  S-   X0R:                  -  X@R:                  -  5      n+U+U Rd                  R0                  Rj                  -  n+U Rd                  Rm                  U+5      RT                  n+U Rn                  Rq                  U+US9n+OU
n+U Rs                  5         U(       d  U+4$ [u        U+S9$ ! , (       d  f       GNq= f)a	  
The call function to the pipeline for generation.

Args:
    prompt (`str` or `list[str]`, *optional*):
        The prompt or prompts to guide the video generation. If not defined, pass `prompt_embeds` instead.
    negative_prompt (`str` or `list[str]`, *optional*):
        The prompt or prompts to avoid during video generation. If not defined, pass `negative_prompt_embeds`
        instead. Ignored when not using guidance (`guidance_scale` < `1`).
    height (`int`, defaults to `512`):
        The height in pixels of the generated video.
    width (`int`, defaults to `768`):
        The width in pixels of the generated video.
    num_frames (`int`, defaults to `25`):
        The number of frames in the generated video.
    num_inference_steps (`int`, defaults to `50`):
        The number of denoising steps.
    guidance_scale (`float`, defaults to `5.0`):
        Guidance scale as defined in classifier-free guidance.
    num_videos_per_prompt (`int`, *optional*, defaults to 1):
        The number of videos to generate per prompt.
    generator (`torch.Generator` or `list[torch.Generator]`, *optional*):
        A torch generator to make generation deterministic.
    latents (`torch.Tensor`, *optional*):
        Pre-generated noisy latents.
    prompt_embeds (`torch.Tensor`, *optional*):
        Pre-generated text embeddings.
    negative_prompt_embeds (`torch.Tensor`, *optional*):
        Pre-generated negative text embeddings.
    output_type (`str`, *optional*, defaults to `"pil"`):
        The output format of the generated video.
    return_dict (`bool`, *optional*, defaults to `True`):
        Whether or not to return a [`KandinskyPipelineOutput`].
    callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
        A function that is called at the end of each denoising step.
    callback_on_step_end_tensor_inputs (`list`, *optional*):
        The list of tensor inputs for the `callback_on_step_end` function.
    max_sequence_length (`int`, defaults to `512`):
        The maximum sequence length for text encoding.

Examples:

Returns:
    [`~KandinskyPipelineOutput`] or `tuple`:
        If `return_dict` is `True`, [`KandinskyPipelineOutput`] is returned, otherwise a `tuple` is returned
        where the first element is a list with the generated images.
)r   r   rQ   rR   r0   r1   r2   r3   r   r   r   r   r   z(`num_frames - 1` has to be divisible by z!. Rounding to the nearest number.FNr   )r   r   rg   rf   g      ?z{Static, 2D cartoon, cartoon, 2d animation, paintings, images, worst quality, low quality, ugly, deformed, walking backwardsz9`negative_prompt` must have same length as `prompt`. Got z vs r   r~   r   )totalT)	r   encoder_hidden_statespooled_projectionstimestepvisual_rope_postext_rope_posscale_factorr   r   )r   r/   r0   r1   r2   r3   latent   r	   r>   )r  )frames);r   r   r
   tensor_inputsr   rJ   r   r   maxr   r  r   r4   rf   r   r   r   r   r   r   r   r:   set_timesteps	timestepsrH   in_visual_dimr   rh   rk   rL   r   itemr\   r   orderr  progress_barr   r  rm   r   r   r   steplocalspopupdateXLA_AVAILABLExm	mark_stepr5   rp   permutescaling_factorr   rM   postprocess_videomaybe_free_model_hooksr   ),rN   r   r   rQ   rR   r   r  r   r   r   r/   r0   r1   r2   r3   r   r   r  r   r  r   r   rg   rf   r   r  r   r   r  r  negative_text_rope_posr  r   num_warmup_stepsr   r   tr  pred_velocityuncond_pred_velocitycallback_kwargsr   callback_outputsvideos,                                               r"   __call__Kandinsky5T2VPipeline.__call__  s   R *-=?U,VWW1E1S1S. 	+11(C(C/'A/Q 3 	 	
 666!;NN:4;Y;Y:ZZ{| $'E'EEHfHffijjJQ'
-''  && *VS"9"9JXFJvt$<$<VJ+11!4J %HLHZHZ$7	 I[ IE4E $& #`/3//EKEW?"3c&k"A^m]n_%V4 OPSTcPdOeeijmntjuivvwx  +2&&.,?%#	 '  e+Jd 	$$%8$HNN,,	  $//66DD&&.. 

 (!^0N0NNQRRLL*6:LL#@#@@AEfULL"?"??1DVT
 %6%;%;%=%A%A%C%H%H%JSYZ *5 LL388:>>@EEGPVW 	 --f< ..w? y>,?..BVBV,VV!)n%89\!),1>>;;q>00>S1ST !% 0 0")**U"3*<*?*?*F'9'<'<U'C%[[/$3"/!-"/ $ !1 
! &  &&,1L1X+/+;+;&-jj&7.I.L.LU.S+F+I+I%+P!)U!3(7&<%1&3$( ,< 
, f ) %9>]]qMq;r$rM=A^^=P=P!1gaAq:O;O:O.O&P^c >Q >>1a$9%9$99: (3&(O?-3Xa[* @';D!Q'X$.229gFG)9)=)=>RTf)g&)9)=)=>RTf)g&2B2F2F57R3/ 3C2F2F57R3/ I**A9I/IqSTuX\XfXfXlXlNlpqNq '') =LLNu - :| !Q1&;';&;;< ("jj0GOO%aD$B$BBQF777666$E MM!Q1a3EMM22$aD$B$BBQF777666E DHHOO:::EHHOOE*11E((::5k:ZEE 	##%8O&e44E :9s   H;]]
]&)r   r  r  rE   rF   rL   rJ   rM   )r	   r	   r	   cuda)N   N)NN)r   r   NN)NNNNNNNN)r   rV   i@  Q   NNNN)0__name__
__module____qualname____firstlineno____doc__model_cpu_offload_seqr   r   r   r   r   r   r   r   rB   r   tupler\   staticmethodrh   ri   rz   r   r   r   rg   rf   r   r   r   r   	Generatorr   propertyr   r  r  no_gradr   EXAMPLE_DOC_STRINGfloatboolr   r   r
   r4  __static_attributes____classcell__)rO   s   @r"   r-   r-      s   4 M(^1(^ '(^ 9	(^
 $(^ &(^ #(^ 3(^T# #C #E #(  1#  1#  1#  13  1  1S  1hmhtht  1  1D/h '+#&$(D,d3iD, t#D, !	D,
 {{T!D,R '+$(	#&d3i#& t##& {{T!	#&P &'#&&*$([Kd3i[K  #[K !	[K
 t#[K {{T![KF  $($(#'+/ Ttr %'$(&*DH'+BB "B 	B
 B B {{T!B t#B ??T%//%::TAB $B 
BH $ $ # #   ]]_12 #'26#% #,-DH'+2626;?;?15:>"' nr9B#&-\5d3i\5 tCy4/\5 	\5
 \5 \5 !\5 \5  #Tz\5 ??T%//%::TA\5 $\5 "LL4/\5 "LL4/\5 &+\\D%8\5 &+\\D%8\5  !<<$.!\5" %*LL4$7#\5$ 4Z%\5& '\5( 'Sz4'78;KKNddgkk)\5* -1I+\5, !-\5 3 \5r$   r-   )4r   typingr   regexr'   rh   torch.nnr   r   transformersr   r   r   r   	callbacksr
   r   loadersr   modelsr   models.transformersr   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   rM   r   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr&  r%  
get_loggerr9  r   r   rD  r#   r)   r+   r-   rW   r$   r"   <module>rZ     s        $ k k A / / ? 9  . - . 4 ))MM			H	% 
		H	%& R	E5-/G E5r$   