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

        >>> # Available models: nvidia/ChronoEdit-14B-Diffusers
        >>> model_id = "nvidia/ChronoEdit-14B-Diffusers"
        >>> image_encoder = CLIPVisionModel.from_pretrained(
        ...     model_id, subfolder="image_encoder", torch_dtype=torch.float32
        ... )
        >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
        >>> transformer = ChronoEditTransformer3DModel.from_pretrained(
        ...     model_id, subfolder="transformer", torch_dtype=torch.bfloat16
        ... )
        >>> pipe = ChronoEditPipeline.from_pretrained(
        ...     model_id, vae=vae, image_encoder=image_encoder, transformer=transformer, torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")

        >>> image = load_image("https://huggingface.co/spaces/nvidia/ChronoEdit/resolve/main/examples/3.png")
        >>> max_area = 720 * 1280
        >>> aspect_ratio = image.height / image.width
        >>> mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
        >>> height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
        >>> width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
        >>> image = image.resize((width, height))
        >>> prompt = (
        ...     "The user wants to transform the image by adding a small, cute mouse sitting inside the floral teacup, enjoying a spa bath. The mouse should appear relaxed and cheerful, with a tiny white bath towel draped over its head like a turban. It should be positioned comfortably in the cup’s liquid, with gentle steam rising around it to blend with the cozy atmosphere. "
        ...     "The mouse’s pose should be natural—perhaps sitting upright with paws resting lightly on the rim or submerged in the tea. The teacup’s floral design, gold trim, and warm lighting must remain unchanged to preserve the original aesthetic. The steam should softly swirl around the mouse, enhancing the spa-like, whimsical mood."
        ... )

        >>> output = pipe(
        ...     image=image,
        ...     prompt=prompt,
        ...     height=height,
        ...     width=width,
        ...     num_frames=5,
        ...     guidance_scale=5.0,
        ...     enable_temporal_reasoning=False,
        ...     num_temporal_reasoning_steps=0,
        ... ).frames[0]
        >>> export_to_video(output, "output.mp4", fps=16)
        ```
c                     t        j                  |       } t        j                  t        j                  |             } | j	                         S N)ftfyfix_texthtmlunescapestriptexts    |/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/pipelines/chronoedit/pipeline_chronoedit.pybasic_cleanr*   a   s3    ==D==t,-D::<    c                 T    t        j                  dd|       } | j                         } | S )Nz\s+ )resubr&   r'   s    r)   whitespace_cleanr0   g   s$    66&#t$D::<DKr+   c                 .    t        t        |             } | S r!   )r0   r*   r'   s    r)   prompt_cleanr2   m   s    K-.DKr+   encoder_output	generatorsample_modec                     t        | d      r |dk(  r| j                  j                  |      S t        | d      r|dk(  r| j                  j                         S t        | d      r| j                  S t        d      )Nlatent_distsampleargmaxlatentsz3Could not access latents of provided encoder_output)hasattrr7   r8   moder:   AttributeError)r3   r4   r5   s      r)   retrieve_latentsr>   s   st     ~}-+2I))00;;		/K84K))..00		+%%%RSSr+   c            /           e Zd ZdZdZg dZdededede	de
d	ed
ef fdZ	 	 	 	 	 d@deeee   f   dededeej(                     deej*                     f
dZ	 dAdedeej(                     fdZ	 	 	 	 	 	 	 	 dBdeeee   f   deeeee   f      dededeej4                     deej4                     dedeej(                     deej*                     fdZ	 	 	 	 dCdZ	 	 	 	 	 	 	 	 dDded!ed"ed#ed$ed%edeej*                     deej(                     d&eeej:                  eej:                     f      d'eej4                     d(eej4                  ej4                  f   fd)Ze d*        Z!e d+        Z"e d,        Z#e d-        Z$e d.        Z%e d/        Z& ejN                          e(e)      ddddd d0d1ddddddd2dddd'gdd3d4fdedeeee   f   deeee   f   d#ed$ed%ed5ed6e*dee   d&eeej:                  eej:                     f      d'eej4                     deej4                     deej4                     d7eej4                     d8ee   d9ed:ee+ee,f      d;eee-eee+gdf   e.e/f      d<ee   ded=ed>ef,d?              Z0 xZ1S )EChronoEditPipelinea  
    Pipeline for image-to-video generation using Wan.

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

    Args:
        tokenizer ([`T5Tokenizer`]):
            Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
            specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        text_encoder ([`T5EncoderModel`]):
            [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
            the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        image_encoder ([`CLIPVisionModel`]):
            [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModel), specifically
            the
            [clip-vit-huge-patch14](https://github.com/mlfoundations/open_clip/blob/main/docs/PRETRAINED.md#vit-h14-xlm-roberta-large)
            variant.
        transformer ([`WanTransformer3DModel`]):
            Conditional Transformer to denoise the input latents.
        scheduler ([`UniPCMultistepScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKLWan`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
    z-text_encoder->image_encoder->transformer->vae)r:   prompt_embedsnegative_prompt_embeds	tokenizertext_encoderimage_encoderimage_processortransformervae	schedulerc           	      f   t         |           | j                  |||||||       t        | dd       r | j                  j
                  j                  nd| _        t        | dd       r | j                  j
                  j                  nd| _	        t        | j                        | _        || _        y )N)rH   rD   rC   rE   rG   rI   rF   rH         )vae_scale_factor)super__init__register_modulesgetattrrH   configscale_factor_temporalvae_scale_factor_temporalscale_factor_spatialvae_scale_factor_spatialr   video_processorrF   )	selfrC   rD   rE   rF   rG   rH   rI   	__class__s	           r)   rO   zChronoEditPipeline.__init__   s     	%'#+ 	 	
 SZZ^`egkRl)N)Nrs&PWX\^ceiPj(L(Lpq%-t?\?\].r+   Nr      promptnum_videos_per_promptmax_sequence_lengthdevicedtypec                    |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}|D cg c]  }t        |       }}t        |      }| j                  |d|dddd      }|j                  |j                  }
}	|
j                  d      j                  d      j                         }| j                  |	j                  |      |
j                  |            j                  }|j                  ||      }t        ||      D cg c]
  \  }}|d |  }}}t!        j"                  |D cg c]J  }t!        j$                  ||j'                  ||j)                  d      z
  |j)                  d            g      L c}d      }|j*                  \  }}}|j-                  d|d      }|j/                  ||z  |d	      }|S c c}w c c}}w c c}w )
N
max_lengthTpt)paddingra   
truncationadd_special_tokensreturn_attention_maskreturn_tensorsr   r   dim)r_   r^   )_execution_devicerD   r_   
isinstancestrr2   lenrC   	input_idsattention_maskgtsumlongtolast_hidden_stateziptorchstackcat	new_zerossizeshaperepeatview)rX   r[   r\   r]   r^   r_   u
batch_sizetext_inputstext_input_idsmaskseq_lensrA   v_seq_lens                   r)   _get_t5_prompt_embedsz(ChronoEditPipeline._get_t5_prompt_embeds   s    14110**00'4&&+12a,q/22[
nn *#"& % 
  +44k6P6P771:>>a>(--/)).*;*;F*CTWWV_Ugg%((uV(D+.}h+GH41a2AHH^klYZUYY1;;':QVVAY'Fq	RSTlrs

 &++7A%,,Q0EqI%**:8M+MwXZ[7 3" Ils   GGAG!imagec                     |xs | j                   }| j                  |d      j                  |      } | j                  di |ddi}|j                  d   S )Nrb   )imagesrg   output_hidden_statesT )rk   rF   rt   rE   hidden_states)rX   r   r^   image_embedss       r)   encode_imagezChronoEditPipeline.encode_image   s_    
 1411$$E$$GJJ6R)t))MEMM))"--r+   Tnegative_promptdo_classifier_free_guidancerA   rB   c
                    |xs | j                   }t        |t              r|gn|}|t        |      }
n|j                  d   }
|| j                  |||||	      }|r||xs d}t        |t              r|
|gz  n|}|:t        |      t        |      ur$t        dt        |       dt        |       d      |
t        |      k7  r!t        d| dt        |       d	| d|
 d
	      | j                  |||||	      }||fS )a"  
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
                Whether to use classifier free guidance or not.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            device: (`torch.device`, *optional*):
                torch device
            dtype: (`torch.dtype`, *optional*):
                torch dtype
        r   )r[   r\   r]   r^   r_    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`.)	rk   rl   rm   rn   r|   r   type	TypeError
ValueError)rX   r[   r   r   r\   rA   rB   r]   r^   r_   r   s              r)   encode_promptz ChronoEditPipeline.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
           
      F    ||t        d| d| d      ||t        d      |Ut        |t        j                        s;t        |t        j
                  j
                        st        dt        |             |dz  dk7  s|dz  dk7  rt        d| d	| d
      |	Lt         fd|	D              s8t        d j                   d|	D 
cg c]  }
|
 j                  vs|
 c}
       ||t        d| d| d      ||t        d| d| d      ||t        d      |7t        |t              s't        |t              st        dt        |             |9t        |t              s(t        |t              st        dt        |             y y y c c}
w )NzCannot forward both `image`: z and `image_embeds`: z2. Please make sure to only forward one of the two.zbProvide either `image` or `prompt_embeds`. Cannot leave both `image` and `image_embeds` undefined.zE`image` has to be of type `torch.Tensor` or `PIL.Image.Image` but is    r   z8`height` and `width` have to be divisible by 16 but are z and r   c              3   :   K   | ]  }|j                   v   y wr!   )_callback_tensor_inputs).0krX   s     r)   	<genexpr>z2ChronoEditPipeline.check_inputs.<locals>.<genexpr>[  s#      F
23A---F
s   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zCannot forward both `prompt`: z and `prompt_embeds`: z'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is z;`negative_prompt` has to be of type `str` or `list` but is )r   rl   rw   TensorPILImager   allr   rm   list)rX   r[   r   r   heightwidthrA   rB   r   "callback_on_step_end_tensor_inputsr   s   `          r)   check_inputszChronoEditPipeline.check_inputsA  sh    !9/w6KL> Z0 0  =\1t  Zu||%DZX]_b_h_h_n_nModeijoepdqrssB;!urzQWX^W__dejdkklmnn-9# F
7YF
 C
 DTEaEaDbbn  |^  pHvw  bc  ko  kG  kG  bGpq  pH  oI  J  -";08N}o ^0 0  (-C-O9/9JJi  kA  jB B0 0  ^ 5w  FC)@TZ\`IaQRVW]R^Q_`aa(?C0OUY9ZZ[_`o[pZqrss :[0 )' pHs   F!F  @  Q   r   num_channels_latentsr   r   
num_framesr4   r:   returnc           
         |dz
  | j                   z  dz   }|| j                  z  }|| j                  z  }|||||f}t        |	t              r)t	        |	      |k7  rt        dt	        |	       d| d      |
t        ||	||      }
n|
j                  ||      }
|j                  d      }t        j                  ||j                  |j                  d   |j                  d   |dz
  ||      gd	      }|j                  || j                  j                        }t        j                  | j                  j                   j"                        j%                  d| j                  j                   j&                  ddd      j                  |
j(                  |
j                        }d
t        j                  | j                  j                   j*                        j%                  d| j                  j                   j&                  ddd      j                  |
j(                  |
j                        z  }t        |	t              rI|	D cg c](  }t-        | j                  j/                  |      d      * }}t        j                  |      }n;t-        | j                  j/                  |      d      }|j1                  |dddd      }|j                  |      }||z
  |z  }t        j2                  |d|||      }d|d d d d t        t5        d|            f<   |d d d d ddf   }t        j6                  |d| j                         }t        j8                  ||d d d d dd d d f   gd	      }|j%                  |d| j                   ||      }|j;                  dd      }|j                  |j(                        }|
t        j8                  ||gd	      fS c c}w )Nr   z/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.)r4   r^   r_   )r^   r_   r   r   rh         ?r9   )r5   )ri   repeatsrj   )rT   rV   rl   r   rn   r   r   rt   	unsqueezerw   ry   rz   r|   rH   r_   tensorrR   latents_meanr~   z_dimr^   latents_stdr>   encoder}   onesrangerepeat_interleaveconcat	transpose)rX   r   r   r   r   r   r   r_   r^   r4   r:   num_latent_frameslatent_heightlatent_widthr|   video_conditionr   r   r   latent_conditionmask_lat_sizefirst_frame_masks                         r)   prepare_latentsz"ChronoEditPipeline.prepare_latentsx  s{    (!^0N0NNQRR$"?"?? = ==13DmUabi&3y>Z+GA#i.AQ R&<'gi 
 ?"5IfTYZGjjej<G"))EOOEKKNEKKNJQRNTZ\abcij
 *,,F$((..,Q LL556T!TXX__**Aq!4R. 	
 ELL)D)DEJJ1dhhooNcNcefhiklmppNNGMM
 
 i&bk ]^ !AxX     %yy)9:/0P^fg/66z1aAN+..u5,|;{J

:q*m\Z:;aDq*!5667(Aqs3 223CTXTrTrs&6aABPQk8R%SYZ[%**:r4;Y;Y[hjvw%//15%(()9)@)@Am5E%FANNN) s   -Oc                     | j                   S r!   _guidance_scalerX   s    r)   guidance_scalez!ChronoEditPipeline.guidance_scale  s    ###r+   c                      | j                   dkD  S )Nr   r   r   s    r)   r   z.ChronoEditPipeline.do_classifier_free_guidance  s    ##a''r+   c                     | j                   S r!   )_num_timestepsr   s    r)   num_timestepsz ChronoEditPipeline.num_timesteps  s    """r+   c                     | j                   S r!   )_current_timestepr   s    r)   current_timestepz#ChronoEditPipeline.current_timestep      %%%r+   c                     | j                   S r!   )
_interruptr   s    r)   	interruptzChronoEditPipeline.interrupt  s    r+   c                     | j                   S r!   )_attention_kwargsr   s    r)   attention_kwargsz#ChronoEditPipeline.attention_kwargs  r   r+   2   g      @npFr   num_inference_stepsr   r   output_typereturn_dictr   callback_on_step_endr   enable_temporal_reasoningnum_temporal_reasoning_stepsc                    t        |t        t        f      r|j                  }| j	                  |||||||||	       |sdn|}|| j
                  z  dk7  rBt        j                  d| j
                   d       || j
                  z  | j
                  z  dz   }t        |d      }|| _	        || _
        d| _        d| _        | j                  }|t        |t              rd}n-|t        |t              rt!        |      }n|j"                  d   }| j%                  ||| j&                  |	||||      \  }}| j(                  j*                  }|j-                  |      }||j-                  |      }|| j/                  ||      }|j1                  |dd      }|j-                  |      }| j2                  j5                  ||	       | j2                  j6                  }| j8                  j:                  j<                  }| j>                  jA                  |||
      j-                  |tB        jD                        }| jG                  |||	z  ||||tB        jD                  ||
|
      \  }}t!        |      || j2                  jH                  z  z
  }t!        |      | _%        | jM                  |      5 }tO        |      D ]  \  }} | jP                  r|r#||k(  r|ddddddgf   }|ddddddgf   }tS        t!        | j2                  jT                              D ]  }!| j2                  jT                  |!   |j"                  d   | j2                  jT                  |!   j"                  d   k7  sT| j2                  jT                  |!   ddddddgf   | j2                  jT                  |!<    | j2                  jV                  1| j2                  jV                  ddddddgf   | j2                  _+        | | _        tC        jX                  ||gd      j-                  |      }"| j[                  |j"                  d         }#| j)                  |"|#|||d      d   }$| j&                  r%| j)                  |"|#|||d      d   }%|%||$|%z
  z  z   }$| j2                  j]                  |$| |d      d   }|Zi }&|D ]  }'t_               |'   |&|'<     || || |&      }(|(ja                  d|      }|(ja                  d|      }|(ja                  d|      }|t!        |      dz
  k(  s'|dz   |kD  r/|dz   | j2                  jH                  z  dk(  r|jc                          td        stg        jh                           	 ddd       d| _        |dk(  s|j-                  | j8                  j*                        }tC        jj                  | j8                  j:                  jl                        jo                  d| j8                  j:                  j<                  ddd      j-                  |jp                  |j*                        })dtC        jj                  | j8                  j:                  jr                        jo                  d| j8                  j:                  j<                  ddd      j-                  |jp                  |j*                        z  }*||*z  |)z   }|r|j"                  d   dkD  r~| j8                  ju                  |ddddddgf   d      d   }+| j8                  ju                  |ddddddf   d      d   },tC        jX                  |,|+ddddddf   gd      }-n | j8                  ju                  |d      d   }-| j>                  jw                  |-|      }-n|}-| jy                          |s|-fS t{        |-      S # 1 sw Y   JxY w)aF  
        The call function to the pipeline for generation.

        Args:
            image (`PipelineImageInput`):
                The input image to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
                instead.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            height (`int`, defaults to `480`):
                The height of the generated video.
            width (`int`, defaults to `832`):
                The width of the generated video.
            num_frames (`int`, defaults to `81`):
                The number of frames in the generated video.
            num_inference_steps (`int`, defaults to `50`):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, defaults to `5.0`):
                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
                `guidance_scale` is defined as `w` of equation 2. of [Imagen
                Paper](https://arxiv.org/pdf/2205.11487.pdf). 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.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
                A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
                generation deterministic.
            latents (`torch.Tensor`, *optional*):
                Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor is generated by sampling using the supplied random `generator`.
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `prompt` input argument.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `negative_prompt` input argument.
            image_embeds (`torch.Tensor`, *optional*):
                Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
                image embeddings are generated from the `image` input argument.
            output_type (`str`, *optional*, defaults to `"np"`):
                The output format of the generated image. Choose between `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`ChronoEditPipelineOutput`] 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.
            enable_temporal_reasoning (`bool`, *optional*, defaults to `False`):
                Whether to enable temporal reasoning.
            num_temporal_reasoning_steps (`int`, *optional*, defaults to `0`):
                The number of steps to enable temporal reasoning.

        Examples:

        Returns:
            [`~ChronoEditPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`ChronoEditPipelineOutput`] is returned, otherwise a `tuple` is returned
                where the first element is a list with the generated images and the second element is a list of `bool`s
                indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
           r   z(`num_frames - 1` has to be divisible by z!. Rounding to the nearest number.NFr   )r[   r   r   r\   rA   rB   r]   r^   )r^   )r   r   )r_   )totalrj   rh   )r   timestepencoder_hidden_statesencoder_hidden_states_imager   r   )r   r:   rA   rB   latentr   r   )r   )frames)>rl   r   r   tensor_inputsr   rT   loggerwarningmaxr   r   r   r   rk   rm   r   rn   r|   r   r   rG   r_   rt   r   r}   rI   set_timesteps	timestepsrH   rR   r   rW   
preprocessrw   float32r   orderr   progress_bar	enumerater   r   model_outputslast_samplery   expandsteplocalspopupdateXLA_AVAILABLExm	mark_stepr   r   r~   r^   r   decodepostprocess_videomaybe_free_model_hooksr   ).rX   r   r[   r   r   r   r   r   r   r\   r4   r:   rA   rB   r   r   r   r   r   r   r]   r   r   r^   r   transformer_dtyper   r   	conditionnum_warmup_stepsr   itjlatent_model_inputr   
noise_prednoise_uncondcallback_kwargsr   callback_outputsr   r   
video_editvideo_reasonvideos.                                                 r)   __call__zChronoEditPipeline.__call__  s   Z *-=?U,VW1E1S1S. 	".
	
 8QZ
666!;NN:4;Y;Y:ZZ{| $t'E'EEHfHffijjJQ'
-!1!%'' *VS"9JJvt$<VJ&,,Q/J 150B0B+(,(H(H"7'#9 3 1C 	1
-- !,,22%(():;!-%;%>%>?P%Q",,UF;L#**:q!<#'89 	$$%8$HNN,,	  $xx44$$//fE/RUUV\didqdqUr!11.. MM
 y>,?$..BVBV,VV!)n%89 :	#\!), 9#1>>,6R1R%aQGm4G )!QB- 8I"3t~~'C'C#DE q>>77:F&}}R0DNN4P4PQR4S4Y4YZ\4]]BF..B^B^_`BabcefijlnhoboBp < <Q ?q ~~11=59^^5O5OPQSTWXZ\V]P]5^2)*&%*YY/C%K%N%NO`%a"88GMM!$45!--"4%*70<%5 % .  
 33#'#3#3&8!).D4@)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 '') LLNs9#:	#x "&h&jj0GTXX__99:a..1a8GNNGMM2 
 TXX__-H-H I N NqRVRZRZRaRaRgRgijlmop q t t! K +l:G(W]]1-=-A!XX__WQAr7]-CQV_WXYZ
#xxwq!SbSy/AuUVWX		<Aq!"H1E"FANUCAF((::5k:ZEE 	##%8O'u55s:	# :	#s    )B	^536^5*G)^5^55^?)Nr   rZ   NNr!   )NTr   NN   NN)NNNN)r   r   r   r   NNNN)2__name__
__module____qualname____doc__model_cpu_offload_seqr   r
   r   r   r   r   r   r   rO   r	   rm   r   intr   rw   r^   r_   r   r   r   boolr   r   r   	Generatorr   r   propertyr   r   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGfloatr   r   r   r   r   r  __classcell__)rY   s   @r)   r@   r@      s&   4 LT/ / '/ '	/
 ,/ 2/ / 3/< )-%&#&)-'+'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5r #+/4tv %''+)-MQ*.AO!AO AO "	AO
 AO AO AO $AO &AO E%//43H"HIJAO %,,'AO 
u||U\\)	*AOF $ $ ( ( # # & &   & & U]]_12 )-15#% #/0MQ*.049=/3%) 59 9B#&*/,-3[6![6 c49n%[6 sDI~.	[6
 [6 [6 [6 ![6 [6  (}[6 E%//43H"HIJ[6 %,,'[6  -[6 !) 6[6 u||,[6  c]![6" #[6$ #4S>2%[6& '(Cd+T124DF\\]
'[6, -1I-[6. !/[60 $(1[62 '*3[6 3 [6r+   r@   )Nr8   )=r$   typingr   r   r   r   r   r   r	   r   regexr.   rw   transformersr
   r   r   r   	callbacksr   r   rF   r   loadersr   modelsr   r   
schedulersr   utilsr   r   r   r   utils.torch_utilsr   rW   r   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr  r   r"   r  r*   r0   r2   r   r  rm   r>   r@   r   r+   r)   <module>r/     s     D D D 
   ] ] A 1 ) D 9 b b - - . 5 ))MM			H	%/ d ck
TLL
T-5eoo-F
T\_
Tp	6*,> p	6r+   