
    bi{                        d dl Z 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 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 ddlm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z*  e"       rd dl+Z+ e#jX                  e-      Z.dZ/g dfdZ0d Z1	 	 	 	 d dee2   dee	e3ejh                  f      deee2      deee5      fdZ6	 d!dejn                  deejp                     de3fdZ9 G d dee      Z:y)"    N)AnyCallableDictListOptionalTupleUnion)T5EncoderModelT5Tokenizer   )MultiPipelineCallbacksPipelineCallback)PipelineImageInput)CogVideoXLoraLoaderMixin)AutoencoderKLCogVideoXConsisIDTransformer3DModel)get_3d_rotary_pos_embed)DiffusionPipeline)CogVideoXDPMScheduler)is_opencv_availableloggingreplace_example_docstring)randn_tensor)VideoProcessor   )ConsisIDPipelineOutputa|  
    Examples:
        ```python
        >>> import torch
        >>> from diffusers import ConsisIDPipeline
        >>> from diffusers.pipelines.consisid.consisid_utils import prepare_face_models, process_face_embeddings_infer
        >>> from diffusers.utils import export_to_video
        >>> from huggingface_hub import snapshot_download

        >>> snapshot_download(repo_id="BestWishYsh/ConsisID-preview", local_dir="BestWishYsh/ConsisID-preview")
        >>> (
        ...     face_helper_1,
        ...     face_helper_2,
        ...     face_clip_model,
        ...     face_main_model,
        ...     eva_transform_mean,
        ...     eva_transform_std,
        ... ) = prepare_face_models("BestWishYsh/ConsisID-preview", device="cuda", dtype=torch.bfloat16)
        >>> pipe = ConsisIDPipeline.from_pretrained("BestWishYsh/ConsisID-preview", torch_dtype=torch.bfloat16)
        >>> pipe.to("cuda")

        >>> # ConsisID works well with long and well-described prompts. Make sure the face in the image is clearly visible (e.g., preferably half-body or full-body).
        >>> prompt = "The video captures a boy walking along a city street, filmed in black and white on a classic 35mm camera. His expression is thoughtful, his brow slightly furrowed as if he's lost in contemplation. The film grain adds a textured, timeless quality to the image, evoking a sense of nostalgia. Around him, the cityscape is filled with vintage buildings, cobblestone sidewalks, and softly blurred figures passing by, their outlines faint and indistinct. Streetlights cast a gentle glow, while shadows play across the boy's path, adding depth to the scene. The lighting highlights the boy's subtle smile, hinting at a fleeting moment of curiosity. The overall cinematic atmosphere, complete with classic film still aesthetics and dramatic contrasts, gives the scene an evocative and introspective feel."
        >>> image = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/consisid/consisid_input.png?download=true"

        >>> id_cond, id_vit_hidden, image, face_kps = process_face_embeddings_infer(
        ...     face_helper_1,
        ...     face_clip_model,
        ...     face_helper_2,
        ...     eva_transform_mean,
        ...     eva_transform_std,
        ...     face_main_model,
        ...     "cuda",
        ...     torch.bfloat16,
        ...     image,
        ...     is_align_face=True,
        ... )

        >>> video = pipe(
        ...     image=image,
        ...     prompt=prompt,
        ...     num_inference_steps=50,
        ...     guidance_scale=6.0,
        ...     use_dynamic_cfg=False,
        ...     id_vit_hidden=id_vit_hidden,
        ...     id_cond=id_cond,
        ...     kps_cond=face_kps,
        ...     generator=torch.Generator("cuda").manual_seed(42),
        ... )
        >>> export_to_video(video.frames[0], "output.mp4", fps=8)
        ```
))   r   r   )r   r   r   )r   r   r   )r   r   r   )r   r   r   c           	         d}t        j                  ddgddgddgddgg      }t        j                  |      }| j                  \  }}t        j                  ||dg      }t	        t        |            D ]  }||   }	||	d      }
||	   dddf   }||	   dddf   }|d   |d   z
  dz  |d   |d   z
  dz  z   dz  }t        j                  t        j                  |d   |d   z
  |d   |d   z
              }t        j                  t        t        j                  |            t        t        j                  |            ft        |dz        |ft        |      ddd      }t        j                  |j                         ||
      } |d	z  j                  t         j                         }t#        |      D ]J  \  }}||   }
|\  }}t        j$                  |j                         t        |      t        |      fd
|
d      }L t&        j(                  j+                  |j                  t         j                               }|S )a  
    This function draws keypoints and the limbs connecting them on an image.

    Parameters:
    - image_pil (PIL.Image): Input image as a PIL object.
    - kps (list of tuples): A list of keypoints where each keypoint is a tuple of (x, y) coordinates.
    - color_list (list of tuples, optional): List of colors (in RGB format) for each keypoint. Default is a set of five
      colors.

    Returns:
    - PIL.Image: Image with the keypoints and limbs drawn.
       r      r   r   Ng      ?ih  g333333?
   )nparraysizezerosrangelenmathdegreesatan2cv2ellipse2PolyintmeanfillConvexPolycopyastypeuint8	enumeratecirclePILImage	fromarray)	image_pilkps
color_list
stickwidthlimbSeqwhout_imgiindexcolorxylengthanglepolygonidx_kpkpout_img_pils                      i/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/consisid/pipeline_consisid.pydraw_kpsrM   b   s    JhhAAAA78G
((3-C>>DAqhh1ay!G3w<  E
58$Jq!tJq!tQ4!A$;1$!qt'99cATZZ!qtQqTAaD[AB""_c"''!*o.VaZ*0MsSXz[\^acd
 $$W\\^WeDE }$$RXX.Gn N
6"1**W\\^c!fc!f-=r5"MN
 ))%%gnnRXX&>?K    c                 $   |}|}| \  }}||z  }|||z  kD  r|}t        t        ||z  |z              }	n|}	t        t        ||z  |z              }t        t        ||z
  dz              }
t        t        ||	z
  dz              }|
|f|
|z   ||	z   ffS )a*  
    This function calculates the resize and crop region for an image to fit a target width and height while preserving
    the aspect ratio.

    Parameters:
    - src (tuple): A tuple containing the source image's height (h) and width (w).
    - tgt_width (int): The target width to resize the image.
    - tgt_height (int): The target height to resize the image.

    Returns:
    - tuple: Two tuples representing the crop region:
        1. The top-left coordinates of the crop region.
        2. The bottom-right coordinates of the crop region.
    g       @)r.   round)src	tgt_width
tgt_heighttwthr?   r>   rresize_heightresize_widthcrop_top	crop_lefts               rL   get_resize_crop_region_for_gridr[      s      
B	BDAq	AABG}5a!,-E"q&1*-.5"},345HE2,345Ii 8m#;Y=U"VVVrN   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^   r(   )	schedulerr\   r]   r^   r_   kwargsaccepts_timestepsaccept_sigmass           rL   retrieve_timestepsrn      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''	)))rN   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)hasattrrs   rt   moderv   AttributeError)ro   rp   rq   s      rL   retrieve_latentsrz      st     ~}-+2I))00;;		/K84K))..00		+%%%RSSrN   c            7       x    e Zd ZdZg ZdZg dZdedede	de
def
 fd	Z	 	 	 	 	 dAdeeee   f   dededeej&                     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j.                     deej.                     dedeej&                     deej(                     fdZ	 	 	 	 	 	 	 	 	 	 dCdej.                  dedededededeej(                     deej&                     deej2                     d eej.                     d!eej.                     fd"Zd ej.                  d#ej.                  fd$Zd% Zd& Z	 	 	 dDd'Zdedededej&                  d#eej.                  ej.                  f   f
d(Z e!d)        Z"e!d*        Z#e!d+        Z$e!d,        Z% ejL                          e'e(      d
d
d-d.d/d0d1d2dd3d
d
d
d
d4dd
d
d gdd
d
d
fde)deeeee   f      deeeee   f      dededed5ed6e*d7eded8e*deeej2                  eej2                     f      d eejV                     deejV                     deejV                     d9ed:ed;ee,ee-f      d<eee.eee,gd
f   e/e0f      d=ee   ded>eej.                     d?eej.                     d!eej.                     d#ee1ef   f2d@              Z2 xZ3S )EConsisIDPipelinea  
    Pipeline for image-to-video generation using ConsisID.

    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. ConsisID 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 ([`ConsisIDTransformer3DModel`]):
            A text conditioned `ConsisIDTransformer3DModel` to denoise the encoded video latents.
        scheduler ([`SchedulerMixin`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
    ztext_encoder->transformer->vae)rv   prompt_embedsnegative_prompt_embeds	tokenizertext_encodervaetransformerrj   c                    t         |           | j                  |||||       t        | d      r;| j                  /dt        | j                  j                  j                        dz
  z  nd| _        t        | d      r,| j                   | j                  j                  j                  nd| _
        t        | d      r,| j                   | j                  j                  j                  nd| _        t        | j                        | _        y )	N)r   r   r   r   rj   r   r    r      r   gffffff?)vae_scale_factor)super__init__register_modulesrw   r   r(   configblock_out_channelsvae_scale_factor_spatialtemporal_compression_ratiovae_scale_factor_temporalscaling_factorvae_scaling_factor_imager   video_processor)selfr   r   r   r   rj   ri   s         rL   r   zConsisIDPipeline.__init__  s     	%# 	 	
 CJ$PUBV[_[c[c[oA#dhhoo889A=>uv 	% ;B$:NSWS[S[SgDHHOO66mn 	& /6dE.BtxxG[DHHOO**ad 	%  .t?\?\]rN   Nr      promptnum_videos_per_promptmax_sequence_lengthr]   dtypec                    |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}t        |      }| j                  |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                  |            d   }|j                  ||      }|j                  \  }}}|j                  d|d      }|j!                  ||z  |d      }|S )N
max_lengthTpt)paddingr   
truncationadd_special_tokensreturn_tensorslongest)r   r   r"   r   zXThe following part of your input was truncated because `max_sequence_length` is set to  z	 tokens: r   )r   r]   )_execution_devicer   r   
isinstancestrr(   r   	input_idsshapetorchequalbatch_decodeloggerwarningtorepeatview)r   r   r   r   r]   r   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textr}   _seq_lens                 rL   _get_t5_prompt_embedsz&ConsisIDPipeline._get_t5_prompt_embeds8  s    14110**00'4&&[
nn *# % 
 %....SW.Xbb  $(<(<R(@@UcetIu>>66qJ]`aJadfJfGf7ghLNN'(	,A
 )).*;*;F*CDQG%((uV(D &++7A%,,Q0EqI%**:8M+MwXZ[rN   Tnegative_promptdo_classifier_free_guidancer}   r~   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`.)	r   r   r   r(   r   r   type	TypeErrorrb   )r   r   r   r   r   r}   r~   r   r]   r   r   s              rL   encode_promptzConsisIDPipeline.encode_promptc  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4rN   imager   num_channels_latents
num_framesheightwidthrp   rv   kps_condc           
         t        |	t              r)t        |	      |k7  rt        dt        |	       d| d      |dz
  | j                  z  dz   }||||| j
                  z  || j
                  z  f}|j                  d      }t        |	t              rt        |      D cg c]<  }t        | j                  j                  ||   j                  d            |	|         > }}||j                  d      }t        |      D cg c]<  }t        | j                  j                  ||   j                  d            |	|         > }}n|D cg c]6  }t        | j                  j                  |j                  d            |	      8 }}|R|j                  d      }|D cg c]6  }t        | j                  j                  |j                  d            |	      8 }}t        j                  |d      j                  |      j                  ddddd	      }| j                  |z  }|mt        j                  d      j                  |      j                  ddddd	      }| j                  |z  }||dz
  ||| j
                  z  || j
                  z  f}n$||dz
  ||| j
                  z  || j
                  z  f}t        j                   |||
      }|t        j                  ||gd      }nt        j                  ||gd      }|
t#        ||	||      }
n|
j                  |      }
|
| j$                  j&                  z  }
|
|fS c c}w c c}w c c}w c c}w )Nz/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.r   r    r   dimr   r   )r]   r   )rp   r]   r   )r   listr(   rb   r   r   	unsqueezer'   rz   r   encoder   catr   permuter   r&   r   rj   init_noise_sigma)r   r   r   r   r   r   r   r   r]   rp   rv   r   r   rA   image_latentskps_cond_latentsimgpadding_shapelatent_paddings                      rL   prepare_latentsz ConsisIDPipeline.prepare_latents  so    i&3y>Z+GA#i.AQ R&<'gi 
 !1n)G)GG!K
 d333T222
 "i&`efp`q[\ q1C1CA1F!GSTVM  ##--a0 #:.$ %TXX__Xa[5J5J15M%NPYZ[P\]$  $
 hmm`c-dhhoocmmA>N.OQZ[mMm##--a0nv#wgj$4TXX__S]]STEU5VXa$b#w #w		-Q7::5AII!QPQSTVWX55E$yy)9qADDUKSSTUWXZ[]^`ab#<<?OO Q$$777666M Q$$777666M ]6O!II}6F&W]^_M!II}n&E1MM?"5IfTYZGjj(G DNN;;;%%g
$
 n $xs   AMAM	;M;Mreturnc                     |j                  ddddd      }d| j                  z  |z  }| j                  j                  |      j                  }|S )Nr   r    r   r   r   )r   r   r   decodert   )r   rv   framess      rL   decode_latentszConsisIDPipeline.decode_latents
  sJ    //!Q1a0d333g=)00rN   c                     t        t        ||z        |      }t        ||z
  d      }||| j                  j                  z  d  }|||z
  fS )Nr   )minr.   maxrj   order)r   r\   r^   strengthr]   init_timestept_starts          rL   get_timestepszConsisIDPipeline.get_timesteps  sY    C 3h >?ATU)M91=g(<(<<>?	-777rN   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etarp   )rc   rd   re   rj   steprg   rh   )r   rp   r   accepts_etaextra_step_kwargsaccepts_generators         rL   prepare_extra_step_kwargsz*ConsisIDPipeline.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*  rN   c
           
      X    t        |t        j                        sKt        |t        j                  j                        s't        |t
              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      |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 )Nz``image` has to be of type `torch.Tensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is r   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kr   s     rL   	<genexpr>z0ConsisIDPipeline.check_inputs.<locals>.<genexpr>F  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   r   Tensorr6   r7   r   rb   r   allr   r   r   )r   r   r   r   r   r   "callback_on_step_end_tensor_inputsrv   r}   r~   r   s   `          rL   check_inputszConsisIDPipeline.check_inputs-  sr    5%,,/uciioo6ud+K=" 
 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   6F'
F'c                 R   || j                   | j                  j                  j                  z  z  }|| j                   | j                  j                  j                  z  z  }| j                  j                  j                  | j                  j                  j                  z  }| j                  j                  j
                  | j                  j                  j                  z  }t        ||f||      }	t        | j                  j                  j                  |	||f||      \  }
}|
|fS )N)	embed_dimcrops_coords	grid_sizetemporal_sizer]   )	r   r   r   
patch_sizesample_widthsample_heightr[   r   attention_head_dim)r   r   r   r   r]   grid_height
grid_widthbase_size_widthbase_size_heightgrid_crops_coords	freqs_cos	freqs_sins               rL   %_prepare_rotary_positional_embeddingsz6ConsisIDPipeline._prepare_rotary_positional_embeddingsl  s    !>!>AQAQAXAXAcAc!cdt<<t?O?O?V?V?a?aab
**11>>$BRBRBYBYBdBdd++22@@DDTDTD[D[DfDff;*%8H
  7&&--@@*"J/$ 
	9 )##rN   c                     | j                   S r   )_guidance_scaler   s    rL   guidance_scalezConsisIDPipeline.guidance_scale  s    ###rN   c                     | j                   S r   )_num_timestepsr  s    rL   num_timestepszConsisIDPipeline.num_timesteps  s    """rN   c                     | j                   S r   )_attention_kwargsr  s    rL   attention_kwargsz!ConsisIDPipeline.attention_kwargs  s    %%%rN   c                     | j                   S r   )
_interruptr  s    rL   	interruptzConsisIDPipeline.interrupt  s    rN   i  i  1   2   g      @Fg        pilr\   r  use_dynamic_cfgr   output_typereturn_dictr
  callback_on_step_endr   id_vit_hiddenid_condc                 X   t        |t        t        f      r|j                  }|xs- | j                  j
                  j                  | j                  z  }|xs- | j                  j
                  j                  | j                  z  }|xs  | j                  j
                  j                  }d}
| j                  |||||||||	       || _        || _        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!        |      | _        t3        | j                  j
                  d	d      }|r|nd}|Et5        ||      }| j6                  j9                  |||
      j;                  ||j<                        }| j6                  j9                  |||
      j;                  ||j<                        }| j                  j
                  j>                  dz  }| jA                  |||
z  |||||j<                  ||||      \  }}| jC                  ||      } | j                  j
                  jD                  r#| jG                  |||jI                  d      |      nd}!tK        t!        |      || j.                  jL                  z  z
  d      }"| jO                  |      5 }#d}$|jQ                         }%tS        |      D ]  \  }&}'| jT                  r|rt)        j*                  |gdz        n|}(| j.                  jW                  |(|'      }(|rt)        j*                  |gdz        n|})t)        j*                  |(|)gd      }(|'jY                  |(j"                  d         }*| j	                  |(||*|!|d||      d   }+|+j[                         }+|	rQd|dt]        j^                  t\        j`                  ||%|&   jc                         z
  |z  dz  z        z
  dz  z  z   | _        |r)|+je                  d      \  },}-|,| jf                  |-|,z
  z  z   }+t        | j.                  th              s' | j.                  jj                  |+|'|fi | ddid   }n5 | j.                  jj                  |+|$|'|&dkD  r||&dz
     nd|fi | ddi\  }}$|j;                  |j<                        }|Zi }.|D ]  }/tm               |/   |.|/<     || |&|'|.      }0|0jo                  d|      }|0jo                  d|      }|0jo                  d|      }|&t!        |      dz
  k(  s+|&dz   |"kD  sS|&dz   | j.                  jL                  z  dk(  st|#jq                           	 ddd       |dk(  s/| js                  |      }1| j6                  ju                  |1|      }1n|}1| jw                          |s|1fS ty        |1      S # 1 sw Y   `xY w)a  
        Function invoked when calling 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`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
                The height in pixels of the generated image. This is set to 480 by default for the best results.
            width (`int`, *optional*, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial):
                The width in pixels of the generated image. This is set to 720 by default for the best results.
            num_frames (`int`, defaults to `49`):
                Number of frames to generate. Must be divisible by self.vae_scale_factor_temporal. Generated video will
                contain 1 extra frame because ConsisID is conditioned with (num_seconds * fps + 1) frames where
                num_seconds is 6 and fps is 4. However, since videos can be saved at any fps, the only condition that
                needs to be satisfied is that of divisibility mentioned above.
            num_inference_steps (`int`, *optional*, 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`, *optional*, defaults to 6):
                Guidance scale as defined in [Classifier-Free Diffusion
                Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
                of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
                `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
                the text `prompt`, usually at the expense of lower image quality.
            use_dynamic_cfg (`bool`, *optional*, defaults to `False`):
                If True, dynamically adjusts the guidance scale during inference. This allows the model to use a
                progressive guidance scale, improving the balance between text-guided generation and image quality over
                the course of the inference steps. Typically, early inference steps use a higher guidance scale for
                more faithful image generation, while later steps reduce it for more diverse and natural results.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of videos to generate per prompt.
            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
                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 image
                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. 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.
            output_type (`str`, *optional*, defaults to `"pil"`):
                The output format of the generate image. 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_xl.StableDiffusionXLPipelineOutput`] 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`, *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.
            max_sequence_length (`int`, defaults to `226`):
                Maximum sequence length in encoded prompt. Must be consistent with
                `self.transformer.config.max_text_seq_length` otherwise may lead to poor results.
            id_vit_hidden (`Optional[torch.Tensor]`, *optional*):
                The tensor representing the hidden features extracted from the face model, which are used to condition
                the local facial extractor. This is crucial for the model to obtain high-frequency information of the
                face. If not provided, the local facial extractor will not run normally.
            id_cond (`Optional[torch.Tensor]`, *optional*):
                The tensor representing the hidden features extracted from the clip model, which are used to condition
                the local facial extractor. This is crucial for the model to edit facial features If not provided, the
                local facial extractor will not run normally.
            kps_cond (`Optional[torch.Tensor]`, *optional*):
                A tensor that determines whether the global facial extractor use keypoint information for conditioning.
                If provided, this tensor controls whether facial keypoints such as eyes, nose, and mouth landmarks are
                used during the generation process. This helps ensure the model retains more facial low-frequency
                information.

        Examples:

        Returns:
            [`~pipelines.consisid.pipeline_output.ConsisIDPipelineOutput`] or `tuple`:
            [`~pipelines.consisid.pipeline_output.ConsisIDPipelineOutput`] if `return_dict` is True, otherwise a
            `tuple`. When returning a tuple, the first element is a list with the generated images.
        r   )	r   r   r   r   r   r   rv   r}   r~   FNr   g      ?)r   r   r   r   r}   r~   r   r]   r   is_kps)r   r   )r   r    )total)hidden_statesencoder_hidden_statestimestepimage_rotary_embr
  r  r  r  g      @r  rv   r}   r~   latent)videor  )r   )=r   r   r   tensor_inputsr   r   r   r   r   sample_framesr   r  r	  r  r   r   r(   r   r   r   r   r   rn   rj   r  getattrrM   r   
preprocessr   r   in_channelsr   r    use_rotary_positional_embeddingsr   r%   r   r   progress_barcpur4   r  scale_model_inputexpandfloatr)   cospiitemchunkr  r   r   localspopupdater   postprocess_videomaybe_free_model_hooksr   )2r   r   r   r   r   r   r   r\   r  r  r   r   rp   rv   r}   r~   r  r  r
  r  r   r   r  r  r   r   r]   r   r^   r  latent_channelsr   r   r  num_warmup_stepsr&  old_pred_original_sampletimesteps_cpurA   tlatent_model_inputlatent_image_inputr  
noise_prednoise_pred_uncondnoise_pred_textcallback_kwargsr   callback_outputsr  s2                                                     rL   __call__zConsisIDPipeline.__call__  s   ~ *-=?U,VW1E1S1S.`4++22@@4C`C``]))00==@]@]]H4#3#3#:#:#H#H
 ! 	+/Q'#9 	 
	
  .!1 *VS"9JJvt$<VJ&,,Q/J''
 '5s&:# 150B0B+(C"7'#9 3 1C 	1
-- '!II'=}&MSTUM *<DNNL_ag)h&	&!)n ))00(EB%84x0H++66xV[6\__m11 ` H $$//fE/RUU--- V 
 **11==B!%!5!5.."
 !::9cJ
 &&GG 66vugllSToW]^ 	 s9~0CdnnFZFZ0ZZ\]^%89 I	*\'+$%MMOM!), E*1>>A\UYYy1}%=bi"%)^^%E%EFXZ[%\"GbUYY/B%Chu"%*YY0BDV/W]^%_" 88$6$<$<Q$?@ "--"4*7%%5%5 %"/# . 	 	
 (--/
 #+,~"hh $$7-:J:O:O:Q$QUh#hmp"p!q 	0 	,D( /9C9I9I!9L6%!2T5H5HO^oLo5p!pJ "$..2GH1dnn11*aqL]qkpqrstG8K8K8K"0,-E	!a%(t9 ,9 %*95G5 "**]%8%89 (3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM-=-A-ABZ\r-s*I**A9I/IqSTuX\XfXfXlXlNlpqNq '')KE*	I	*V h&''0E((::T_:`EE 	##%8O%U33oI	* I	*s   I/X X -X  X))Nr   r   NN)NTr   NNr   NN)
r         <   Z   NNNNN)NNN)4__name__
__module____qualname____doc___optional_componentsmodel_cpu_offload_seqr   r   r
   r   r   r   r   r	   r   r   r.   r   r   r]   r   r   boolr   r   	Generatorr   r   r   r   r   r   r   propertyr  r  r
  r  no_gradr   EXAMPLE_DOC_STRINGr   r*  FloatTensorr   r   r   r   r   r   r@  __classcell__)ri   s   @rL   r|   r|      sm   , <^^ %^ $	^
 0^ )^@ )-%&#&)-'+(c49n%(  #( !	(
 &( $(\ <@,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5h $&'+)-/3*.+/S&||S& S& "	S&
 S& S& S& $S& &S& EOO,S& %,,'S& 5<<(S&lell u|| 8!2 #=~$$ $ 	$
 $ 
u||U\\)	*$2 $ $ # # & &   U]]_12 37;?#% # %%&MQ/359>B  59 9B#&04*.+/7w4!w4 sDI~./w4 "%T#Y"78	w4
 w4 w4 w4 !w4 w4 w4  #w4 w4 E%//43H"HIJw4 %++,w4   1 12w4  !)):): ;!w4" #w4$ %w4& #4S>2'w4( '(Cd+T124DF\\]
)w4. -1I/w40 !1w42  -3w44 %,,'5w46 5<<(7w48 
%u,	-9w4 3 w4rN   r|   )NNNN)Nrt   );rd   r)   typingr   r   r   r   r   r   r	   numpyr#   r6   r   transformersr
   r   	callbacksr   r   image_processorr   loadersr   modelsr   r   models.embeddingsr   pipelines.pipeline_utilsr   
schedulersr   utilsr   r   r   utils.torch_utilsr   r   r   pipeline_outputr   r,   
get_loggerrE  r   rO  rM   r[   r.   r   r]   r*  rn   r   rL  rz   r|   ra   rN   rL   <module>r`     s+     D D D  
  4 A 1 / H 8 9 / L L - - 3  
		H	%3 l )n )ZWH *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*z ck
TLL
T-5eoo-F
T\_
TT4(*B T4rN   