
    bi                        d dl Z d dlZd dlZd dlmZ d dlmZ d dlm	Z	m
Z
mZmZmZmZ d dlZd dlmZ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 dd
lmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z'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l3m4Z4  e"       rd dl5Z5dZ6	 	 	 	 ddee7   deee8ejr                  f      deee7      deee:      fdZ;e G d de             Z< G d de      Z=y)    N)	dataclass)CallableDictListOptionalTupleUnion)T5EncoderModelT5Tokenizer   )MultiPipelineCallbacksPipelineCallback)AutoencoderKLLatteTransformer3DModel)DiffusionPipeline)KarrasDiffusionSchedulers)BACKENDS_MAPPING
BaseOutput	deprecateis_bs4_availableis_ftfy_availableis_torch_xla_availableloggingreplace_example_docstring)is_compiled_modulerandn_tensor)VideoProcessorTF)BeautifulSoupaW  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import LattePipeline
        >>> from diffusers.utils import export_to_gif

        >>> # You can replace the checkpoint id with "maxin-cn/Latte-1" too.
        >>> pipe = LattePipeline.from_pretrained("maxin-cn/Latte-1", torch_dtype=torch.float16)
        >>> # Enable memory optimizations.
        >>> pipe.enable_model_cpu_offload()

        >>> prompt = "A small cactus with a happy face in the Sahara desert."
        >>> videos = pipe(prompt).frames[0]
        >>> export_to_gif(videos, "latte.gif")
        ```
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 valuesr!   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r!   r    r"   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r"   r    r     )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r!   len)	schedulerr   r    r!   r"   kwargsaccepts_timestepsaccept_sigmass           c/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/latte/pipeline_latte.pyretrieve_timestepsr3   Q   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''	)))    c                   ,    e Zd ZU ej                  ed<   y)LattePipelineOutputframesN)__name__
__module____qualname__torchTensor__annotations__r$   r4   r2   r6   r6      s    LLr4   r6   c            3       d    e Zd ZdZ ej
                  d      ZddgZdZg dZ	de
dededed	ef
 fd
Zd Z	 	 	 	 	 	 	 	 	 d=deeee   f   dedededeej0                     deej2                     deej2                     dedefdZd Z	 	 d>dZd?dZd Z	 d@dZe d        Z!e d         Z"e d!        Z#e d"        Z$e d#        Z% ejL                          e'e(      ddd$dd%dd&d'd'd(ddddd)ddd*gdddd+fdeeee   f   ded,ed-eee      d.e)ded/ed0ed1ed2e)d3eeejT                  eejT                     f      d*eej2                     deej2                     deej2                     d4ed5ed6eee+eee,gdf   e-e.f      d7ee   deded8ed9ed:ee/e0f   f.d;              Z1dAd*ejd                  d/ed9efd<Z3 xZ4S )BLattePipelinea  
    Pipeline for text-to-video generation using Latte.

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

    Args:
        vae ([`AutoencoderKL`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
        text_encoder ([`T5EncoderModel`]):
            Frozen text-encoder. Latte uses
            [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
            [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
        tokenizer (`T5Tokenizer`):
            Tokenizer of class
            [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
        transformer ([`LatteTransformer3DModel`]):
            A text conditioned `LatteTransformer3DModel` to denoise the encoded video latents.
        scheduler ([`SchedulerMixin`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
    u6   [#®•©™&@·º½¾¿¡§~\)\(\]\[\}\{\|\\/\\*]{1,}	tokenizertext_encoderztext_encoder->transformer->vae)latentsprompt_embedsnegative_prompt_embedsvaetransformerr.   c                 
   t         |           | j                  |||||       t        | dd       r/dt	        | j
                  j                  j                        dz
  z  nd| _        t        | j                        | _
        y )N)r@   rA   rE   rF   r.   rE            )vae_scale_factor)super__init__register_modulesgetattrr-   rE   configblock_out_channelsrK   r   video_processor)selfr@   rA   rE   rF   r.   r,   s         r2   rM   zLattePipeline.__init__   s~     	lQ\hq 	 	
 W^^bdikoVpc$((//*L*L&MPQ&Q Rvw-t?T?TUr4   c                     |j                   d   dk(  r1|j                         j                         }|d d d d d |d d f   |fS ||d d d d d d f   z  }||j                   d   fS )Nr   rI   rH   )shapesumitem)rS   embmask
keep_indexmasked_features        r2   mask_text_embeddingsz"LattePipeline.mask_text_embeddings   sl    99Q<1*Jq![j[!+,j88 44D(8#99N!399Q<//r4   T rI   Npromptdo_classifier_free_guidancenegative_promptnum_images_per_promptr    rC   rD   clean_captionmask_featurec           	      
   |duxr |du}|| j                   }|t        |t              rd}n-|t        |t              rt	        |      }n|j
                  d   }d}|| j                  ||      }| j                  |d|dddd	      }|j                  }| j                  |d
d      j                  }|j
                  d   |j
                  d   k\  rXt        j                  ||      sB| j                  j                  |dd|dz
  df         }t        j                  d| d|        |j                  j                  |      }|}| j!                  |j                  |      |      }|d   }nt        j"                  |      }| j                   | j                   j$                  }
n%| j&                  | j&                  j$                  }
nd}
|j                  |
|      }|j
                  \  }}}|j)                  d|d      }|j+                  ||z  |d      }|j+                  |d      }|j)                  |d      }|r|t        |t              r|g|z  n|}| j                  ||      }|j
                  d   }| j                  |d|dddd	      }|j                  j                  |      }| j!                  |j                  j                  |      |      }|d   }|rL|j
                  d   }|j                  |
|      }|j)                  d|d      }|j+                  ||z  |d      }nd}|	rO|sM|j-                  d      }| j/                  ||      \  }}|j1                  d      }||ddd|ddf   nd}||fS ||fS )aw  
        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 not to guide the video 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`). For
                Latte, this should be "".
            do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
                whether to use classifier free guidance or not
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                number of video that should be generated per prompt
            device: (`torch.device`, *optional*):
                torch device to place the resulting embeddings on
            prompt_embeds (`torch.FloatTensor`, *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.FloatTensor`, *optional*):
                Pre-generated negative text embeddings. For Latte, it's should be the embeddings of the "" string.
            clean_caption (bool, defaults to `False`):
                If `True`, the function will preprocess and clean the provided caption before encoding.
            mask_feature: (bool, defaults to `True`):
                If `True`, the function will mask the text embeddings.
        NrI   r   x   )rb   
max_lengthTpt)paddingrf   
truncationreturn_attention_maskadd_special_tokensreturn_tensorslongest)rh   rl   z\The following part of your input was truncated because CLIP can only handle sequences up to z	 tokens: )attention_maskdtyper    )_execution_device
isinstancestrlistr-   rU   _text_preprocessingr@   	input_idsr;   equalbatch_decodeloggerwarningro   torA   	ones_likerq   rF   repeatview	unsqueezer\   squeeze)rS   r^   r_   r`   ra   r    rC   rD   rb   rc   rq   embeds_initially_provided
batch_sizerf   text_inputstext_input_idsuntruncated_idsremoved_textro   prompt_embeds_attention_maskbs_embedseq_len_uncond_tokensuncond_inputmasked_prompt_embedskeep_indicesmasked_negative_prompt_embedss                               r2   encode_promptzLattePipeline.encode_prompt   s   N %2$=$dBX`dBd!>++F*VS"9JJvt$<VJ&,,Q/J
 --fM-RF..$%&*#'# ) K )22N"nnVYW[n\ffO$$R(N,@,@,DDU[[N  $~~::?1j[\n_aNaKa;bc"|9\N<
 )77::6BN+9( --n.?.?.GXf-gM)!,M+0??=+I((%%++E)$$**EE%((uV(D,22'1%,,Q0EqI%**86K+KWVXY'C'H'HSU'V$'C'J'JK`bc'd$ '+A+I>HZ]>^_-
:dsM 44]R_4`M&,,Q/J>>$%&*#'# * L *88;;FCN%)%6%6&&))&1- &7 &" &<A%>"&,2215G%;%>%>USY%>%Z"%;%B%B1F[]^%_"%;%@%@NcAcelnp%q" &*"  9)33A6M151J1J=Zv1w. ,#7#?#?#B ?U?a&q-<-':;gk * ()FFF444r4   c                 V   dt        t        j                  | j                  j                        j
                  j                               v }i }|r||d<   dt        t        j                  | j                  j                        j
                  j                               v }|r||d<   |S )Neta	generator)r&   r'   r(   r.   stepr*   r+   )rS   r   r   accepts_etaextra_step_kwargsaccepts_generators         r2   prepare_extra_step_kwargsz'LattePipeline.prepare_extra_step_kwargsd  s     s7#4#4T^^5H5H#I#T#T#Y#Y#[\\'*e$ (3w/@/@ATAT/U/`/`/e/e/g+hh-6k*  r4   c           
          |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      |7t        |t              s't        |t
              st        dt        |             ||t        d	| d| d      ||t        d| d| d      |C|@|j                  |j                  k7  r&t        d|j                   d|j                   d      y y y c c}w )NrJ   r   z7`height` and `width` have to be divisible by 8 but are z and .c              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0krS   s     r2   	<genexpr>z-LattePipeline.check_inputs.<locals>.<genexpr>  s#      F
23A---F
s   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zCannot forward both `prompt`: z and `prompt_embeds`: z2. Please make sure to only forward one of the two.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 and `negative_prompt_embeds`: z'Cannot forward both `negative_prompt`: zu`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but got: `prompt_embeds` z != `negative_prompt_embeds` )r%   allr   rs   rt   ru   typerU   )	rS   r^   heightwidthr`   "callback_on_step_end_tensor_inputsrC   rD   r   s	   `        r2   check_inputszLattePipeline.check_inputsu  s&    A:?eai1nVW]V^^cdicjjklmm-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  ^ 5w  FC)@TZ\`IaQRVW]R^Q_`aa"8"D0 9*++]_ 
 &+A+M9/9J K*++]_ 
 $)?)K""&<&B&BB --:-@-@,A B.445Q8  C *L$5 pHs   E%Ec                     rOt               sEt        j                  t        d   d   j	                  d             t        j                  d       drOt               sEt        j                  t        d   d   j	                  d             t        j                  d       dt        |t        t        f      s|g}dt        f fd}|D cg c]
  } ||       c}S c c}w )	Nbs4rn   zSetting `clean_caption=True`z#Setting `clean_caption` to False...Fftfytextc                     r$j                  |       } j                  |       } | S | j                         j                         } | S r   )_clean_captionlowerstrip)r   rb   rS   s    r2   processz2LattePipeline._text_preprocessing.<locals>.process  sH    **40**40 K zz|))+Kr4   )
r   rz   r{   r   formatr   rs   tupleru   rt   )rS   r   rb   r   ts   ` `  r2   rv   z!LattePipeline._text_preprocessing  s    !1!3NN+E226==>\]^NN@A!M!2!4NN+F3B7>>?]^_NN@A!M$.6D	# 	 %))q
)))s   C!c                 	   t        |      }t        j                  |      }|j                         j	                         }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        |d      j                  }t        j                  dd|      }t        j                  d	d|      }t        j                  d
d|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  d d|      }t        j                  d!d|      }t        j                  | j                  d|      }t        j                  d"d|      }t        j                  d#      }t        t        j                  ||            d$kD  rt        j                  |d|      }t        j                  |      }t        j                   t        j                   |            }t        j                  d%d|      }t        j                  d&d|      }t        j                  d'd|      }t        j                  d(d|      }t        j                  d)d|      }t        j                  d*d|      }t        j                  d+d|      }t        j                  d,d|      }t        j                  d-d|      }t        j                  d.d|      }t        j                  d/d0|      }t        j                  d1d2|      }t        j                  d3d|      }|j                          t        j                  d4d5|      }t        j                  d6d|      }t        j                  d7d|      }t        j                  d8d|      }|j                         S )9Nz<person>personzk\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))r]   zh\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))zhtml.parser)featuresz
@[\w\d]+\bz[\u31c0-\u31ef]+z[\u31f0-\u31ff]+z[\u3200-\u32ff]+z[\u3300-\u33ff]+z[\u3400-\u4dbf]+z[\u4dc0-\u4dff]+z[\u4e00-\u9fff]+z|[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+-u   [`´«»“”¨]"u   [‘’]'z&quot;?z&ampz"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} z\d:\d\d\s+$z\\nz
#\d{1,3}\bz	#\d{5,}\bz
\b\d{6,}\bz0[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)z
[\"\']{2,}z[\.]{2,}z\s+\.\s+z	(?:\-|\_)r   z\b[a-zA-Z]{1,3}\d{3,15}\bz\b[a-zA-Z]+\d+[a-zA-Z]+\bz\b\d+[a-zA-Z]+\d+\bz!(worldwide\s+)?(free\s+)?shippingz(free\s)?download(\sfree)?z\bclick\b\s(?:for|on)\s\w+z9\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?z\bpage\s+\d+\bz*\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\bu   \b\d+\.?\d*[xх×]\d+\.?\d*\bz
\b\s+\:\s+z: z(\D[,\./])\bz\1 z\s+z^[\"\']([\w\W]+)[\"\']$z\1z^[\'\_,\-\:;]z[\'\_,\-\:\-\+]$z^\.\S+$)rt   ulunquote_plusr   r   resubr   r   bad_punct_regexcompiler-   findallr   fix_texthtmlunescape)rS   captionregex2s      r2   r   zLattePipeline._clean_caption  s   g,//'*--/'')&&Xw7&&z

 &&w
  -@EE &&G4 &&,b':&&,b':&&,b':&&,b':&&,b':&&,b':&&,b': && L
 &&-sG<&&c73 &&R1&&"g. &&>WM &&W5 &&g. &&G4&&r73&&G4&&LbRYZ &&g6&&dG4&&--tW=&&dG4 L)rzz&'*+a/ffVS'2G--(--g 67&&5r7C&&5r7C&&/W=&&=r7K&&6GD&&6GD&&UWY[bc&&*B8&&FgV&&92wG&&w7&&&':&&g.&&3UGD&&)38&&,c7;&&R1}}r4   c
                 2   ||||| j                   z  || j                   z  f}
t        |t              r)t        |      |k7  rt	        dt        |       d| d      |	t        |
|||      }	n|	j                  |      }	|	| j                  j                  z  }	|	S )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    rq   )	rK   rs   ru   r-   r%   r   r|   r.   init_noise_sigma)rS   r   num_channels_latents
num_framesr   r   rq   r    r   rB   rU   s              r2   prepare_latentszLattePipeline.prepare_latents5  s      d+++T***
 i&3y>Z+GA#i.AQ R&<'gi 
 ?"5IfTYZGjj(G DNN;;;r4   c                     | j                   S r   _guidance_scalerS   s    r2   guidance_scalezLattePipeline.guidance_scaleN  s    ###r4   c                      | j                   dkD  S )NrI   r   r   s    r2   r_   z)LattePipeline.do_classifier_free_guidanceU  s    ##a''r4   c                     | j                   S r   )_num_timestepsr   s    r2   num_timestepszLattePipeline.num_timestepsY  s    """r4   c                     | j                   S r   )_current_timestepr   s    r2   current_timestepzLattePipeline.current_timestep]  s    %%%r4   c                     | j                   S r   )
_interruptr   s    r2   	interruptzLattePipeline.interrupta  s    r4   2   g      @   i   g        pilrB      r   r!   r   video_lengthr   r   r   r   output_typereturn_dictcallback_on_step_endr   enable_temporal_attentionsdecode_chunk_sizereturnc                    t        |t        t        f      r|j                  }||n|}|xs- | j                  j
                  j                  | j                  z  }|	xs- | j                  j
                  j                  | j                  z  }	| j                  |||	||||       || _	        d| _
        d| _        |t        |t              rd}n-|t        |t              rt        |      }n|j                  d   }| j                   }|dkD  }| j#                  |||||||||	      \  }}|rt%        j&                  ||gd      }t)        | j*                  |||      \  }}t        |      | _        | j                  j
                  j.                  }| j1                  ||z  ||||	|j2                  |||	      }| j5                  ||
      }t7        t        |      || j*                  j8                  z  z
  d      }| j;                  |      5 }t=        |      D ]  \  }}| j>                  r|| _
        |rt%        j&                  |gd	z        n|} | j*                  jA                  | |      } |}!t%        jB                  |!      s| jD                  jF                  d
k(  }"| jD                  jF                  dk(  }#t        |!tH              r%|"s|#rt$        jJ                  nt$        jL                  }$n$|"s|#rt$        jN                  nt$        jP                  }$t%        jR                  |!g|$| jD                        }!n6t        |!j                        dk(  r|!d   jU                  | jD                        }!|!jW                  | j                  d         }!| j	                  | ||!|d      d   }%|r|%jY                  d	      \  }&}'|&||'|&z
  z  z   }%t[        | j*                  j
                  d      r"| j*                  j
                  j\                  dv s|%jY                  d	d      d   }% | j*                  j^                  |%||fi |ddid   }|Zi }(|D ]  })ta               |)   |(|)<     || |||(      }*|*jc                  d|      }|*jc                  d|      }|*jc                  d|      }|t        |      dz
  k(  s'|dz   |kD  r/|dz   | j*                  j8                  z  dk(  r|je                          tf        sti        jj                           	 ddd       d| _
        |dk(  rd}+tm        dd|+d       d}|dk(  s2| jo                  |||      },| jp                  js                  |,|      },n|},| ju                          |s|,fS tw        |,      S # 1 sw Y   xY w)u  
        Function invoked when calling the pipeline for generation.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the video 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 video 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`).
            num_inference_steps (`int`, *optional*, defaults to 100):
                The number of denoising steps. More denoising steps usually lead to a higher quality video at the
                expense of slower inference.
            timesteps (`List[int]`, *optional*):
                Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
                timesteps are used. Must be in descending order.
            guidance_scale (`float`, *optional*, defaults to 7.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 videos that are closely linked to
                the text `prompt`, usually at the expense of lower video quality.
            video_length (`int`, *optional*, defaults to 16):
                The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                The number of videos to generate per prompt.
            height (`int`, *optional*, defaults to self.unet.config.sample_size):
                The height in pixels of the generated video.
            width (`int`, *optional*, defaults to self.unet.config.sample_size):
                The width in pixels of the generated video.
            eta (`float`, *optional*, defaults to 0.0):
                Corresponds to parameter eta (η) in the DDIM paper: https://huggingface.co/papers/2010.02502. Only
                applies to [`schedulers.DDIMScheduler`], will be ignored for others.
            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
                One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
                to make generation deterministic.
            latents (`torch.FloatTensor`, *optional*):
                Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for video
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor will ge generated by sampling using the supplied random `generator`.
            prompt_embeds (`torch.FloatTensor`, *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.FloatTensor`, *optional*):
                Pre-generated negative text embeddings. For Latte this negative prompt should be "". If not provided,
                negative_prompt_embeds will be generated from `negative_prompt` input argument.
            output_type (`str`, *optional*, defaults to `"pil"`):
                The output format of the generate video. Choose between
                [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
            callback_on_step_end (`Callable[[int, int, Dict], None]`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
                A callback function or a list of callback functions to be called at the end of each denoising step.
            callback_on_step_end_tensor_inputs (`List[str]`, *optional*):
                A list of tensor inputs that should be passed to the callback function. If not defined, all tensor
                inputs will be passed.
            clean_caption (`bool`, *optional*, defaults to `True`):
                Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
                be installed. If the dependencies are not installed, the embeddings will be created from the raw
                prompt.
            mask_feature (`bool` defaults to `True`): If set to `True`, the text embeddings will be masked.
            enable_temporal_attentions (`bool`, *optional*, defaults to `True`): Whether to enable temporal attentions
            decode_chunk_size (`int`, *optional*):
                The number of frames to decode at a time. Higher chunk size leads to better temporal consistency at the
                expense of more memory usage. By default, the decoder decodes all frames at once for maximal quality.
                For lower memory usage, reduce `decode_chunk_size`.

        Examples:

        Returns:
            [`~pipelines.latte.pipeline_latte.LattePipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.latte.pipeline_latte.LattePipelineOutput`] is returned,
                otherwise a `tuple` is returned where the first element is a list with the generated images
        NFrI   r   g      ?)r`   ra   r    rC   rD   rb   rc   dim)totalrH   mpsnpurp   )hidden_statesencoder_hidden_statestimestepr   r   variance_type)learnedlearned_ranger   rB   rC   rD   zZPassing `output_type='latents'` is deprecated. Please pass `output_type='latent'` instead.output_type_latentsz1.0.0)standard_warnlatent)r   )videor   )r7   )<rs   r   r   tensor_inputsrF   rP   sample_sizerK   r   r   r   r   rt   ru   r-   rU   rr   r   r;   catr3   r.   r   in_channelsr   rq   r   maxorderprogress_bar	enumerater   scale_model_input	is_tensorr    r   floatfloat32float64int32int64tensorr|   expandchunkhasattrr   r   localspopupdateXLA_AVAILABLExm	mark_stepr   decode_latentsrR   postprocess_videomaybe_free_model_hooksr6   )-rS   r^   r`   r   r!   r   ra   r   r   r   r   r   rB   rC   rD   r   r   r   r   rb   rc   r   r   r   r    r_   latent_channelsr   num_warmup_stepsr   ir   latent_model_inputr   is_mpsis_npurq   
noise_prednoise_pred_uncondnoise_pred_textcallback_kwargsr   callback_outputsdeprecation_messager   s-                                                r2   __call__zLattePipeline.__call__e  s   P *-=?U,VW1E1S1S. 2C1N-T` V4++22>>AVAVVT))00<<t?T?TT."	
  .!% *VS"9JJvt$<VJ&,,Q/J''
 '5s&:# 150B0B'+"7'#9'% 1C 
1
-- '!II'=}&MSTUM *<DNNL_agir)s&	&!)n **11==&&..

 !::9cJ s9~0CdnnFZFZ0ZZ\]^%89 @	#\!), ?#1>>)*&A\UYYy1}%=bi"%)^^%E%EFXZ[%\"#$ '78 066;;uDF/66;;uDF!"2E:28F06&u{{',||5E4Fe\n\u\u'v$)//0A5'7'='@'@ASAZAZ'[$#3#:#:;M;S;STU;V#W  "--"4*7-/I % .  
 /9C9I9I!9L6%!2^YjGj5k!kJ DNN11?C--;;?[[!+!1!1!!1!;A!>J .$..--j!WmHYmglmnop (3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s*I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLN?#@	#D "&)#l   +W6IY^_"Kh&''Qb'cE((::T_:`EE 	##%8O"%00o@	# @	#s   KU=$U==Vc                 R   |j                  ddddd      j                  dd      }d| j                  j                  j                  z  |z  }t        | j                        r | j                  j                  j                  n| j                  j                  }dt        t        j                  |      j                  j                               v }g }t        d|j                  d   |      D ]^  }||||z    j                  d   }i }	|r||	d<    | j                  j                  ||||z    fi |	j                   }
|j#                  |
       ` t%        j&                  |d      } |j(                  d|g|j                  dd   j                  ddddd      }|j+                         }|S )	Nr   rH   rI   r      r   r   rn   )permuteflattenrE   rP   scaling_factorr   	_orig_modforwardr&   r'   r(   r*   r+   rangerU   decodesampleappendr;   r   reshaper   )rS   rB   r   r   forward_vae_fnaccepts_num_framesr7   r  num_frames_indecode_kwargsframes              r2   r  zLattePipeline.decode_latentss  s   //!Q1a088A>dhhoo444w>7I$((7S++33Y]YaYaYiYi)S1B1B>1R1]1]1b1b1d-ee q'--*,=> 	!A#A,=(=>DDQGMM!.;l+#DHHOOGA4E0E$FX-X__EMM% 	! 6q)  LD6<<3CDLLQPQSTVWYZ[ r4   )	Tr]   rI   NNNFTN)NN)Fr   )r   )5r8   r9   r:   __doc__r   r   r   _optional_componentsmodel_cpu_offload_seqr   r   r
   r   r   r   rM   r\   r	   rt   r   boolintr   r;   r    FloatTensorr   r   r   rv   r   r   propertyr   r_   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   	Generatorr   r   r   r   r6   r   r  r<   r  __classcell__)r,   s   @r2   r?   r?      s   , !bjj!Z[O'8<VV %V 	V
 -V -V$0 -1!%&)-59>B#!S5c49n%S5 &*S5 	S5
  #S5 &S5   1 12S5 !)):): ;S5 S5 S5l!0 #1h*2ph nr2 $ $ ( ( # # & &   U]]_12 )-!#%)- #%&MQ/359>B   9B"!+/!#3I1c49n%I1 I1 !	I1
 DI&I1 I1  #I1 I1 I1 I1 I1 E%//43H"HIJI1 %++,I1   1 12I1 !)):): ;I1  !I1" #I1$ '(Cd+T124DF\\]
%I1* -1I+I1, -I1. /I10 %)1I12 3I14 
"E)	*5I1 3 I1Xell # Z] r4   r?   )NNNN)>r   r'   r   urllib.parseparser   dataclassesr   typingr   r   r   r   r   r	   r;   transformersr
   r   	callbacksr   r   modelsr   r   pipelines.pipeline_utilsr   
schedulersr   utilsr   r   r   r   r   r   r   r   utils.torch_utilsr   r   rR   r   torch_xla.core.xla_modelcore	xla_modelr  r  
get_loggerr8   rz   r   r   r   r8  r4  rt   r    r   r3   r6   r?   r$   r4   r2   <module>rJ     s      	  ! ? ?  4 A < 9 3	 	 	 B - ))MM			H	% ! , *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*v *  }% }r4   