
    bi                        d dl 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Zd dlZd dlmZmZ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mZ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) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z:m;Z;  e-       rd dl<m=c m>Z? dZ@ndZ@ e.j                  eB      ZCdZDg dg dg dg dg dg dg dg dddgg	ZEdeFd eFd!eFfd"ZGe G d# d$e,             ZH G d% d&e9e:e;eeeee7
      ZIy)'    N)	dataclass)AnyCallableDictListOptionalUnion)CLIPImageProcessorCLIPTextModelCLIPTokenizerCLIPVisionModelWithProjection   )PipelineImageInput)FromSingleFileMixinIPAdapterMixinStableDiffusionLoraLoaderMixinTextualInversionLoaderMixin)AutoencoderKLImageProjectionUNet2DConditionModelUNetMotionModel)adjust_lora_scale_text_encoder)MotionAdapter)DDIMSchedulerDPMSolverMultistepSchedulerEulerAncestralDiscreteSchedulerEulerDiscreteSchedulerLMSDiscreteSchedulerPNDMScheduler)USE_PEFT_BACKEND
BaseOutputis_torch_xla_availableloggingreplace_example_docstringscale_lora_layersunscale_lora_layers)randn_tensor)VideoProcessor   )FreeInitMixin)DeprecatedPipelineMixinDiffusionPipelineStableDiffusionMixinTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import EulerDiscreteScheduler, MotionAdapter, PIAPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> adapter = MotionAdapter.from_pretrained("openmmlab/PIA-condition-adapter")
        >>> pipe = PIAPipeline.from_pretrained(
        ...     "SG161222/Realistic_Vision_V6.0_B1_noVAE", motion_adapter=adapter, torch_dtype=torch.float16
        ... )

        >>> pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
        >>> image = load_image(
        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/pix2pix/cat_6.png?download=true"
        ... )
        >>> image = image.resize((512, 512))
        >>> prompt = "cat in a hat"
        >>> negative_prompt = "wrong white balance, dark, sketches, worst quality, low quality, deformed, distorted"
        >>> generator = torch.Generator("cpu").manual_seed(0)
        >>> output = pipe(image=image, prompt=prompt, negative_prompt=negative_prompt, generator=generator)
        >>> frames = output.frames[0]
        >>> export_to_gif(frames, "pia-animation.gif")
        ```
)      ??333333?r0   r0   皙?)r.   r1   r1   r1   HzG?(\?      ?)r.   r1   ffffff?r5   r5   r5   r5   r5   r5   r5   333333?      ?r7   )r.   r/   r0   r0   r0   r1   r1   r1   r1   r1   r1   r1   r0   r0   r/   r.   )r.   r1   r1   r1   r2   r3   r4   r4   r4   r4   r4   r3   r2   r1   r1   r.   )r.   r1   r5   r5   r5   r5   r6   r7   r7   r6   r5   r5   r5   r5   r1   r.   )r7   皙?r8   r8   ffffff?333333?)	r7   r8   r8   r8   r9   r9   r:   g      ?皙?r7   r;   
num_frames
cond_framemotion_scalec                 F   | dkD  sJ d       | |kD  sJ d       t         }|t        |      k  sJ d| d       ||   }||d   g| t        |      z
  z  z   }t        |       D cg c]  }t        ||z
         }}t        |       D cg c]
  }|||       }}|S c c}w c c}w )Nr   z%video_length should be greater than 0z.video_length should be greater than cond_framezmotion_scale typez not implemented)
RANGE_LISTlenrangeabs)r<   r=   r>   
range_listcoefiorders          _/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/pia/pipeline_pia.pyprepare_mask_coef_by_statisticsrJ   e   s    >BBB>
"T$TT"J#j/)]->|nL\+]])l#DDH:c$i!789D*/
*;<QSZ <E<$)*$56qDqN6D6K =6s   "BBc                       e Zd ZU dZeej                  ej                  e	e	e
j                  j                        f   ed<   y)PIAPipelineOutputa  
    Output class for PIAPipeline.

    Args:
        frames (`torch.Tensor`, `np.ndarray`, or List[List[PIL.Image.Image]]):
            Nested list of length `batch_size` with denoised PIL image sequences of length `num_frames`, NumPy array of
            shape `(batch_size, num_frames, channels, height, width, Torch tensor of shape `(batch_size, num_frames,
            channels, height, width)`.
    framesN)__name__
__module____qualname____doc__r	   torchTensornpndarrayr   PILImage__annotations__     rI   rL   rL   w   s5     %,,

Dciioo1F,GGHHrZ   rL   c            5           e Zd ZdZ	 dZg dZg dZ	 	 	 d@dedede	d	e
eef   d
e
eeeeeef   dee   dedef fdZ	 	 	 	 	 dAdeej2                     deej2                     dee   dee   fdZdBdZd Zd Z	 	 	 	 	 	 dCdZ d Z!	 dBdZ"	 dDdZ#d Z$e%d        Z&e%d        Z'e%d        Z(e%d         Z)e%d!        Z* ejV                          e,e-      dd"d#ddd$d%dd&d'dddddddd(d)dddd*gfd+e.d,e
e/e0e/   f   d-ed.ee   d/ee   d0ee   d1ed2ed3ee
e/e0e/   f      d4ee   d5ed6ee
ejb                  e0ejb                     f      d*eej2                     deej2                     deej2                     d7ee.   d8ee0ej2                        d9ed:ee/   d;e2d<ee3e/e4f      dee   d=ee5eee3gdf      d>e0e/   f0d?              Z6 xZ7S )EPIAPipelinez0.33.1z&text_encoder->image_encoder->unet->vae)feature_extractorimage_encodermotion_adapter)latentsprompt_embedsnegative_prompt_embedsNvaetext_encoder	tokenizerunet	schedulerr_   r]   r^   c	           
      ^   t         	|           t        |t              rt	        j
                  ||      }| j                  ||||||||       t        | dd       r/dt        | j                  j                  j                        dz
  z  nd| _        t        d| j                        | _        y )N)rc   rd   re   rf   r_   rg   r]   r^   rc   r)         F)	do_resizevae_scale_factor)super__init__
isinstancer   r   from_unet2dregister_modulesgetattrrB   rc   configblock_out_channelsrl   r(   video_processor)
selfrc   rd   re   rf   rg   r_   r]   r^   	__class__s
            rI   rn   zPIAPipeline.__init__   s    $ 	d01"..t^DD%)/' 	 		
 W^^bdikoVpc$((//*L*L&MPQ&Q Rvw-PTPePefrZ   ra   rb   
lora_scale	clip_skipc
                 H
   |Jt        | t              r:|| _        t        st	        | j
                  |       nt        | j
                  |       |t        |t              rd}
n-|t        |t              rt        |      }
n|j                  d   }
|t        | t              r| j                  || j                        }| j                  |d| j                  j                  dd      }|j                  }| j                  |dd	      j                  }|j                  d
   |j                  d
   k\  rt!        j"                  ||      sj| j                  j%                  |dd| j                  j                  dz
  d
f         }t&        j)                  d| j                  j                   d|        t+        | j
                  j,                  d      r<| j
                  j,                  j.                  r|j0                  j3                  |      }nd}|	(| j                  |j3                  |      |      }|d   }nT| j                  |j3                  |      |d      }|d
   |	dz       }| j
                  j4                  j7                  |      }| j
                  | j
                  j8                  }n/| j:                  | j:                  j8                  }n|j8                  }|j3                  ||      }|j                  \  }}}|j=                  d|d      }|j?                  ||z  |d
      }|rm|j|dg|
z  }n|:tA        |      tA        |      ur$tC        dtA        |       dtA        |       d      t        |t              r|g}n1|
t        |      k7  r!tE        d| dt        |       d| d|
 d	      |}t        | t              r| j                  || j                        }|j                  d   }| j                  |d|dd      }t+        | j
                  j,                  d      r<| j
                  j,                  j.                  r|j0                  j3                  |      }nd}| j                  |j                  j3                  |      |      }|d   }|rK|j                  d   }|j3                  ||      }|j=                  d|d      }|j?                  |
|z  |d
      }| j
                  ,t        | t              rt        rtG        | j
                  |       ||fS )a  
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            device: (`torch.device`):
                torch device
            num_images_per_prompt (`int`):
                number of images that should be generated per prompt
            do_classifier_free_guidance (`bool`):
                whether to use classifier free guidance or not
            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`).
            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.
            lora_scale (`float`, *optional*):
                A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
            clip_skip (`int`, *optional*):
                Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
                the output of the pre-final layer will be used for computing the prompt embeddings.
        Nri   r   
max_lengthTpt)paddingr{   
truncationreturn_tensorslongest)r}   r   r@   z\The following part of your input was truncated because CLIP can only handle sequences up to z	 tokens: use_attention_mask)attention_mask)r   output_hidden_states)dtypedevice 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`.)$ro   r   _lora_scaler    r   rd   r%   strlistrB   shaper   maybe_convert_promptre   model_max_length	input_idsrR   equalbatch_decodeloggerwarninghasattrrs   r   r   to
text_modelfinal_layer_normr   rf   repeatviewtype	TypeError
ValueErrorr&   )rv   promptr   num_images_per_promptdo_classifier_free_guidancenegative_promptra   rb   rx   ry   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textr   prompt_embeds_dtypebs_embedseq_len_uncond_tokensr{   uncond_inputs                          rI   encode_promptzPIAPipeline.encode_prompt   s6   V !j7U&V)D $.t/@/@*M!$"3"3Z@*VS"9JJvt$<VJ&,,Q/J $ ;<2264>>J..$>>::# ) K )22N"nnVYW[n\ffO$$R(N,@,@,DDU[[N  $~~::#At~~'F'F'JR'O$OP  778	,Q
 t((//1EF4K\K\KcKcKvKv!,!;!;!>!>v!F!%  $ 1 1.2C2CF2K\j 1 k -a 0 $ 1 1"%%f-ncg !2 ! !.b 1IM2B C
 !% 1 1 < < M Mm \("&"3"3"9"9YY""&))//"/"5"5%((/B6(R,22'1%,,Q0EqI%**86K+KWVXY '+A+I&!#z 1#VD<Q(QUVZ[jVkUl mV~Q(  OS1!0 1s?33 )/)::J3K_J` ax/
| <33  !0 $ ;< $ 9 9- X&,,Q/J>>$%# * L t((//1EF4K\K\KcKcKvKv!-!<!<!?!?!G!%%)%6%6&&))&1- &7 &" &<A%>"&,2215G%;%>%>EXag%>%h"%;%B%B1F[]^%_"%;%@%@NcAcelnp%q"($ >?DT#D$5$5zB444rZ   c                 |   t        | j                  j                               j                  }t	        |t
        j                        s| j                  |d      j                  }|j                  ||      }|r}| j                  |d      j                  d   }|j                  |d      }| j                  t        j                  |      d      j                  d   }|j                  |d      }||fS | j                  |      j                  }|j                  |d      }t        j                  |      }	||	fS )	Nr|   )r   r   r   T)r   r   dim)nextr^   
parametersr   ro   rR   rS   r]   pixel_valuesr   hidden_statesrepeat_interleave
zeros_likeimage_embeds)
rv   imager   r   r   r   image_enc_hidden_statesuncond_image_enc_hidden_statesr   uncond_image_embedss
             rI   encode_imagezPIAPipeline.encode_image  sD   T''2245;;%.**5*FSSEe4&*&8&8UY&8&Z&h&hik&l#&=&O&OPekl&O&m#-1-?-?  'd .@ .mB. * .L-]-]%1 .^ .* +,JJJ--e4AAL'99:OUV9WL"'"2"2<"@!444rZ   c                    d| j                   j                  j                  z  |z  }|j                  \  }}}}}|j	                  ddddd      j                  ||z  |||      }| j                   j                  |      j                  }|d d d f   j                  ||df|j                  dd  z         j	                  ddddd      }|j                         }|S )Nri   r   r)   r      r@   )	rc   rs   scaling_factorr   permutereshapedecodesamplefloat)	rv   r`   r   channelsr<   heightwidthr   videos	            rI   decode_latentszPIAPipeline.decode_latents  s    dhhoo444w>:A--7
Hj&%//!Q1a088j9PRZ\bdij(//dAg&&
J'CekkRSRTo'UV^^_`bcefhiklmrZ   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)setinspect	signaturerg   stepr   keys)rv   r   r   accepts_etaextra_step_kwargsaccepts_generators         rI   prepare_extra_step_kwargsz%PIAPipeline.prepare_extra_step_kwargs  s     s7#4#4T^^5H5H#I#T#T#Y#Y#[\\'*e$ (3w/@/@ATAT/U/`/`/e/e/g+hh-6k*  rZ   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      |A|?|j                  |j                  k7  r&t        d|j                   d|j                   d      ||t        d      |Ut        |t
              st        dt        |             |d   j                  dvrt        d|d   j                   d      y y c c}
w )Nrj   r   z7`height` and `width` have to be divisible by 8 but are z and r   c              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0krv   s     rI   	<genexpr>z+PIAPipeline.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'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: zu`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but got: `prompt_embeds` z != `negative_prompt_embeds` zProvide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined.z:`ip_adapter_image_embeds` has to be of type `list` but is )r   r   zF`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is D)	r   allr   ro   r   r   r   r   ndim)rv   r   r   r   r   ra   rb   ip_adapter_imageip_adapter_image_embeds"callback_on_step_end_tensor_inputsr   s   `          rI   check_inputszPIAPipeline.check_inputs  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&+A+M9/9J K*++]_ 
 $)?)K""&<&B&BB --:-@-@,A B.445Q8  ',C,O ^  #.5t< PQUVmQnPop  )+00> \]tuv]w]|]|\}}~  ? /E pHs   F%Fc                    g }|rg }|t        |t              s|g}t        |      t        | j                  j                  j
                        k7  rBt        dt        |       dt        | j                  j                  j
                         d      t        || j                  j                  j
                        D ]`  \  }}	t        |	t               }
| j                  ||d|
      \  }}|j                  |d d d f          |sIj                  |d d d f          b n?|D ]:  }|r%|j                  d      \  }}j                  |       |j                  |       < g }t        |      D ]|  \  }}t        j                  |g|z  d      }|r7t        j                  |   g|z  d      }t        j                  ||gd      }|j                  |      }|j                  |       ~ |S )	NzK`ip_adapter_image` must have same length as the number of IP Adapters. Got z images and z IP Adapters.ri   r)   r   r   r   )ro   r   rB   rf   encoder_hid_projimage_projection_layersr   zipr   r   appendchunk	enumeraterR   catr   )rv   r   r   r   r   r   r   negative_image_embedssingle_ip_adapter_imageimage_proj_layeroutput_hidden_statesingle_image_embedssingle_negative_image_embedsrG   s                 rI   prepare_ip_adapter_image_embedsz+PIAPipeline.prepare_ip_adapter_image_embeds  sY    &$&!"*.5$4#5 #$DII,F,F,^,^(__ abefvbwax  yE  FI  JN  JS  JS  Jd  Jd  J|  J|  F}  E~  ~K  L  >A $))"<"<"T"T> 
X9')9 +55E*W&W#DHDUDU+VQ8KEA#%A ##$7a$@A.)001MdTUg1VW
X (? 9#.H[HaHabcHdE02E)001MN##$78	9 #%&/&= 	@"A""'))-@,ADY,Y_`"a*/4yy:OPQ:R9SVk9kqr/s,&+ii1MOb0cij&k#"5"8"8"8"G#**+>?	@ '&rZ   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   r   )	rl   ro   r   rB   r   r'   r   rg   init_noise_sigma)rv   r   num_channels_latentsr<   r   r   r   r   r   r`   r   s              rI   prepare_latentszPIAPipeline.prepare_latents1  s      d+++T***
 i&3y>Z+GA#i.AQ R&<'gi 
 ?"5IfTYZGjj(G DNN;;;rZ   r   c           	         ||||| j                   z  || j                   z  f}|\  }}}}}| j                  j                  |      }|j                  ||      }t	        |	t
              rkt        |      D cg c]?  }| j                  j                  |||dz          j                  j                  |	|         A }}t        j                  |d      }n4| j                  j                  |      j                  j                  |	      }|j                  ||      }t        j                  j                  j                  |||g      }|j!                         | j                  j"                  j$                  z  }t        j&                  |d|||f      j                  ||      }t)        |d|
      }t        j&                  |d|||      j                  || j*                  j,                        }t        |      D ]7  }||   |d d d d |d d d d f<   |j!                         |d d d d |d d d d f<   9 | j.                  rt        j                  |gdz        n|}| j.                  rt        j                  |gdz        n|}||fS c c}w )Nri   r   r   r   )sizer   r)   )rl   ru   
preprocessr   ro   r   rC   rc   encodelatent_distr   rR   r   nn
functionalinterpolatecloners   r   zerosrJ   rf   r   r   )rv   r   r   r   r<   r   r   r   r   r   r>   r   r   scaled_heightscaled_widthr   image_latentimage_latent_paddingmask	mask_coefmasked_imagefs                         rI   prepare_masked_conditionz$PIAPipeline.prepare_masked_conditionJ  sW     d+++T***
 05,1a$$//6'i&\abl\mWXa!a% 01==DDYq\RL  !99\q9L88??51==DDYOL#fEBxx**66|=ZfJg6h+113dhhoo6T6TT{{J:}lSTWW_emrWs3J<P	{{:q*m\Z]] ^ 
 z" 	GA"+A,DAq!Q*>*D*D*FLAq!Q'	G )-(H(Huyy$!$d8<8X8Xuyy,!!34^j\!!/s   4AJc                 N   t        t        ||z        |      }t        ||z
  d      }| j                  j                  || j                  j
                  z  d  }t        | j                  d      r2| j                  j                  || j                  j
                  z         |||z
  fS )Nr   set_begin_index)minintmaxrg   	timestepsrH   r   r  )rv   num_inference_stepsstrengthr   init_timestept_startr  s          rI   get_timestepszPIAPipeline.get_timesteps~  s    C 3h >?ATU)M91=NN,,Wt~~7K7K-K-MN	4>>#45NN**7T^^5I5I+IJ-777rZ   c                     | j                   S r   _guidance_scalerv   s    rI   guidance_scalezPIAPipeline.guidance_scale  s    ###rZ   c                     | j                   S r   )
_clip_skipr  s    rI   ry   zPIAPipeline.clip_skip  s    rZ   c                      | j                   dkD  S )Nri   r  r  s    rI   r   z'PIAPipeline.do_classifier_free_guidance  s    ##a''rZ   c                     | j                   S r   )_cross_attention_kwargsr  s    rI   cross_attention_kwargsz"PIAPipeline.cross_attention_kwargs  s    +++rZ   c                     | j                   S r   )_num_timestepsr  s    rI   num_timestepszPIAPipeline.num_timesteps  s    """rZ   r.      2   g      @ri   g        pilTr`   r   r   r  r<   r   r   r  r  r   num_videos_per_promptr   r   r   r   r>   output_typereturn_dictr!  callback_on_step_endr   c                 
   |xs- | j                   j                  j                  | j                  z  }|xs- | j                   j                  j                  | j                  z  }d}
| j	                  ||||	|||||	       || _        || _        || _        |t        |t              rd}n-|t        |t              rt        |      }n|j                  d   }| j                  }| j                  | j                  j                  dd      nd}| j!                  |||
| j"                  |	|||| j$                  	      \  }}| j"                  rt'        j(                  ||g      }|j+                  |d      }||"| j-                  |||||
z  | j"                        }| j.                  j1                  ||       | j3                  |||      \  }}|dd j5                  ||
z        }t        |      | _        | j9                  ||
z  d||||j:                  |||		      }| j=                  |||
z  d|||| j                   j:                  |||

      \  }} |dk  rCt?        |j                  |||j:                        }!| j.                  jA                  | d   |!|      }| jC                  ||      }"||dind}#| jD                  r| jF                  nd}$tI        |$      D ]3  }%| jD                  r#| jK                  ||%|||j:                  |      \  }}t        |      | _        t        |      || j.                  jL                  z  z
  }&| jO                  | j6                        5 }'tQ        |      D ]  \  }(})| j"                  rt'        j(                  |gdz        n|}*| j.                  jS                  |*|)      }*t'        j(                  |*|| gd      }*| j                  |*|)|||#      jT                  }+| j"                  r|+jW                  d      \  },}-|,||-|,z
  z  z   }+ | j.                  jX                  |+|)|fi |"jZ                  }|Zi }.|D ]  }/t]               |/   |.|/<     || |(|)|.      }0|0j_                  d|      }|0j_                  d|      }|0j_                  d|      }|(t        |      dz
  k(  s'|(dz   |&kD  r/|(dz   | j.                  jL                  z  dk(  r|'ja                          tb        ste        jf                           	 ddd       6 |dk(  r|}1n.| ji                  |      }2| jj                  jm                  |2|      }1| jo                          |s|1fS tq        |1      S # 1 sw Y   xY w)u5  
        The call function to the pipeline for generation.

        Args:
            image (`PipelineImageInput`):
                The input image to be used for video generation.
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
            strength (`float`, *optional*, defaults to 1.0):
                Indicates extent to transform the reference `image`. Must be between 0 and 1.
            height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
                The height in pixels of the generated video.
            width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
                The width in pixels of the generated video.
            num_frames (`int`, *optional*, defaults to 16):
                The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
                amounts to 2 seconds of video.
            num_inference_steps (`int`, *optional*, defaults to 50):
                The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
                expense of slower inference.
            guidance_scale (`float`, *optional*, defaults to 7.5):
                A higher guidance scale value encourages the model to generate images closely linked to the text
                `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide what to not include in image generation. If not defined, you need to
                pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
            eta (`float`, *optional*, defaults to 0.0):
                Corresponds to parameter eta (η) from the [DDIM](https://huggingface.co/papers/2010.02502) paper. Only
                applies to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
            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 video
                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`. Latents should be of shape
                `(batch_size, num_channel, num_frames, height, width)`.
            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 negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
                not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
            ip_adapter_image: (`PipelineImageInput`, *optional*):
                Optional image input to work with IP Adapters.
            ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
                Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
                IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
                contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
                provided, embeddings are computed from the `ip_adapter_image` input argument.
            motion_scale: (`int`, *optional*, defaults to 0):
                Parameter that controls the amount and type of motion that is added to the image. Increasing the value
                increases the amount of motion, while specific ranges of values control the type of motion that is
                added. Must be between 0 and 8. Set between 0-2 to only increase the amount of motion. Set between 3-5
                to create looping motion. Set between 6-8 to perform motion with image style transfer.
            output_type (`str`, *optional*, defaults to `"pil"`):
                The output format of the generated video. Choose between `torch.Tensor`, `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] instead
                of a plain tuple.
            cross_attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
                [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            clip_skip (`int`, *optional*):
                Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
                the output of the pre-final layer will be used for computing the prompt embeddings.
            callback_on_step_end (`Callable`, *optional*):
                A function that calls at the end of each denoising steps during the inference. The function is called
                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.

        Examples:

        Returns:
            [`~pipelines.pia.pipeline_pia.PIAPipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.pia.pipeline_pia.PIAPipelineOutput`] is returned, otherwise a
                `tuple` is returned where the first element is a list with the generated frames.
        ri   Nr   scale)ra   rb   rx   ry   )repeatsr   r   r   )r`   )r<   r   r   r   r   r   r>   r.   r   r   )totalr)   r   )encoder_hidden_statesr!  added_cond_kwargsr`   ra   rb   latent)r   r)  )rM   )9rf   rs   sample_sizerl   r   r  r  r   ro   r   r   rB   r   _execution_devicer!  getr   r   ry   rR   r   r   r   rg   set_timestepsr  r   r#  r   r   r  r'   	add_noiser   free_init_enabled_free_init_num_itersrC   _apply_free_initrH   progress_barr   scale_model_inputr   r   r   prev_samplelocalspopupdateXLA_AVAILABLExm	mark_stepr   ru   postprocess_videomaybe_free_model_hooksrL   )3rv   r   r   r  r<   r   r   r  r  r   r(  r   r   r`   ra   rb   r   r   r>   r)  r*  r!  ry   r+  r   r   r   text_encoder_lora_scaler   r  latent_timestepr  r	  noiser   r1  num_free_init_itersfree_init_iternum_warmup_stepsr;  rG   tlatent_model_input
noise_prednoise_pred_uncondnoise_pred_textcallback_kwargsr   callback_outputsr   video_tensors3                                                      rI   __call__zPIAPipeline.__call__  s   b O499++77$:O:OOM))558M8MM ! 	"#.
	
  .#'=$ *VS"9JJvt$<VJ&,,Q/J'' ?C>Y>Y>eD''++GT:ko 	  150B0B!,,'#9.nn 1C 
1
-- ++!II'=}&MNM%77
PQ7R'+B+N?? '2200L 	$$%8$H)-););<OQY[a)b&	&#BQ-..z<Q/QR!)n &&.. ' 

 "::..!))//% ; 
l c> )FZaZgZghEnn..|AWG !::9cJ
  +/F/R \* 	 <@;Q;Qd77WX#$78 0	'N%%%)%:%:^-@&'--Yb&" #&i.D"9~0CdnnFZFZ0ZZ"")<)<"= ''%i0 &'DAqEIEeEeG9q=)Akr&)-)I)IJ\^_)`&).4Fl3[ab)c& "&*.;/E*; "+ " f  77=G=M=Ma=P:)?%6?]nKn9o%o
 2dnn11*a^L]^jjG+7*,!C =A17!OA.=+?aO+\("2"6"6y'"J(8(<(<_m(\1A1E1EF^`v1w. C	NQ..AE=M3MSTWXSX\`\j\j\p\pRptuRu$++-$M&''' ''0	'f ("E..w7L((::[f:gE 	##%8O ..m'' ''s   FU%+U%%U/	)NNN)NNNNNr   )NNNNNN)r   )8rN   rO   rP   _last_supported_versionmodel_cpu_offload_seq_optional_componentsr   r   r   r   r	   r   r   r   r   r   r   r   r   r   r   r
   r   rn   rR   rS   r   r  r   r   r   r   r   r   r   r  r  propertyr  ry   r   r!  r$  no_gradr$   EXAMPLE_DOC_STRINGr   r   r   	Generatorboolr   r   r   rT  __classcell__)rw   s   @rI   r\   r\      s    '8 EST  37047;!!g!g $!g !	!g
 (/9:!g  "+')
!g !/!g .!g  5!!gT 049=&*#'t5  -t5 !) 6t5 UOt5 C=t5n52
!, # $+/=@+'^ nrH 1"h	8 $ $   ( ( , , # # U]]_12 )-$& $##% #;?/0MQ*.049=9=@D%* ;?#'KO9B3\/!\/ c49n%\/ 	\/
 SM\/ \/ }\/ !\/ \/ "%T#Y"78\/  (}\/ \/ E%//43H"HIJ\/ %,,'\/  -\/  !) 6!\/" ##56#\/$ "*$u||*<!=%\/& '\/( c])\/* +\/, !)c3h 8-\/. C=/\/0 'xc40@$0F'GH1\/2 -1I3\/ 3 \/rZ   r\   )Jr   dataclassesr   typingr   r   r   r   r   r	   numpyrT   rV   rR   transformersr
   r   r   r   image_processorr   loadersr   r   r   r   modelsr   r   r   r   models.lorar   models.unets.unet_motion_modelr   
schedulersr   r   r   r   r   r   utilsr    r!   r"   r#   r$   r%   r&   utils.torch_utilsr'   ru   r(   free_init_utilsr*   pipeline_utilsr+   r,   r-   torch_xla.core.xla_modelcore	xla_modelrB  rA  
get_loggerrN   r   rZ  rA   r  rJ   rL   r\   rY   rZ   rI   <module>rp     s    ! = =  
  h h 1 w w [ [ 9 ;    . - + ] ] ))MM			H	% 6 &*EY]T#4#J

  TW $ I
 I Ix/"x/rZ   