
    
3j                    d   S SK Jr  S SKrS SKrS SKJrJr  S SKrS SK	r	S SK
JrJrJrJr  SSKJr  SSKJr  SSKJrJr  SS	KJr  SS
KJrJrJr  SSKJr  SSKJr  SSK J!r!  \" 5       (       a  S SK"J#s  J$r%  Sr&OSr&\RN                  " \(5      r)Sr*SS jr+    S       SS jjr, " S S\5      r-g)    )annotationsN)AnyCallable)ByT5Tokenizer"Qwen2_5_VLForConditionalGenerationQwen2TokenizerT5EncoderModel   )AdaptiveProjectedMixGuidance)VaeImageProcessor)AutoencoderKLHunyuanImageHunyuanImageTransformer2DModel)FlowMatchEulerDiscreteScheduler)is_torch_xla_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipeline   )HunyuanImagePipelineOutputTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import HunyuanImagePipeline

        >>> pipe = HunyuanImagePipeline.from_pretrained(
        ...     "hunyuanvideo-community/HunyuanImage-2.1-Diffusers", torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")
        >>> prompt = "A cat holding a sign that says hello world"
        >>> # Depending on the variant being used, the pipeline call will slightly vary.
        >>> # Refer to the pipeline documentation for more details.
        >>> image = pipe(prompt, negative_prompt="", num_inference_steps=50).images[0]
        >>> image.save("hunyuanimage.png")
        ```
c                   / nSnSnSnSn[         R                  " X 5      n[         R                  " X05      n[         R                  " X@5      n[         R                  " XP5      n	UR                  U5        UR                  U5        UR                  U5        UR                  U	5        U(       a+  SR                  U V
s/ s H	  n
SU
 S3PM     sn
5      S-   nU$ SnU$ s  sn
f )	a  
Extract text enclosed in quotes for glyph rendering.

Finds text in single quotes, double quotes, and Chinese quotes, then formats it for byT5 processing.

Args:
    prompt: Input text prompt

Returns:
    Formatted glyph text string or None if no quoted text found
z	\'(.*?)\'z	\"(.*?)\"u   ‘(.*?)’u   “(.*?)”z. zText ""N)refindallextendjoin)prompttext_prompt_textspattern_quote_singlepattern_quote_doublepattern_quote_chinese_singlepattern_quote_chinese_doublematches_quote_singlematches_quote_doublematches_quote_chinese_singlematches_quote_chinese_doubletextglyph_text_formatteds               q/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/pipelines/hunyuan_image/pipeline_hunyuanimage.pyextract_glyph_textr+   @   s     ''#1 #1 ::&:C::&:C#%::.J#S #%::.J#S 12129:9:#yyGX)YGXtF4&*:GX)YZ]aa    $	 *Zs   =Cc                   Ub  Ub  [        S5      eUb  S[        [        R                  " U R                  5      R
                  R                  5       5      ;   nU(       d  [        SU R                   S35      eU R                  " S
X2S.UD6  U R                  n[        U5      nX14$ Ub  S[        [        R                  " U R                  5      R
                  R                  5       5      ;   nU(       d  [        SU R                   S35      eU R                  " S
XBS.UD6  U R                  n[        U5      nX14$ U R                  " U4S	U0UD6  U R                  nX14$ )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 values	timestepszThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r-   devicesigmaszv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r/   r.   r.    )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r-   len)	schedulernum_inference_stepsr.   r-   r/   kwargsaccepts_timestepsaccept_sigmass           r*   retrieve_timestepsr?   e   s}   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	M)MfM''	!)n )) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	GvGG''	!)n )) 	 3MFMfM''	))    c                  P  ^  \ rS rSrSrSrSS/rSS/r  S                 SU 4S	 jjjr       S                 SS
 jjr	   S           SS jjr
       S                S!S jjr          S"S jr S#S jr\S 5       r\S 5       r\S 5       r\S 5       r\R(                  " 5       \" \5      SSSSSSSSSSSSSSSSSSSSSSS/4                                             S$S jj5       5       rSrU =r$ )%HunyuanImagePipeline   aZ  
The HunyuanImage pipeline for text-to-image generation.

Args:
    transformer ([`HunyuanImageTransformer2DModel`]):
        Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
    scheduler ([`FlowMatchEulerDiscreteScheduler`]):
        A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
    vae ([`AutoencoderKLHunyuanImage`]):
        Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
    text_encoder ([`Qwen2.5-VL-7B-Instruct`]):
        [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct), specifically the
        [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) variant.
    tokenizer (`Qwen2Tokenizer`): Tokenizer of class [Qwen2Tokenizer].
    text_encoder_2 ([`T5EncoderModel`]):
        [T5EncoderModel](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)
        variant.
    tokenizer_2 (`ByT5Tokenizer`): Tokenizer of class [ByT5Tokenizer]
    guider ([`AdaptiveProjectedMixGuidance`]):
        [AdaptiveProjectedMixGuidance]to be used to guide the image generation.
    ocr_guider ([`AdaptiveProjectedMixGuidance`], *optional*):
        [AdaptiveProjectedMixGuidance] to be used to guide the image generation when text rendering is needed.
z.text_encoder->text_encoder_2->transformer->vaelatentsprompt_embeds
ocr_guiderguiderNc
                8  > [         T
U ]  5         U R                  UUUUUUUUU	S9	  [        U SS 5      (       a   U R                  R
                  R                  OSU l        [        U R                  S9U l	        SU l
        SU l        SU l        SU l        S	U l        g )
N)	vaetext_encoder	tokenizertext_encoder_2tokenizer_2transformerr:   rG   rF   rI       )vae_scale_factor     <|im_start|>system
Describe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>
<|im_start|>user
{}<|im_end|>"   @   )super__init__register_modulesgetattrrI   configspatial_compression_ratiorP   r   image_processortokenizer_max_lengthtokenizer_2_max_lengthprompt_template_encode prompt_template_encode_start_idxdefault_sample_size)selfr:   rI   rJ   rK   rL   rM   rN   rG   rF   r8   s             r*   rW   HunyuanImagePipeline.__init__   s     	%)##! 	 
	
 NUUY[`bfMgMg I Imo0$BWBWX$(!&)# 'l#02-#% r@   c
                   U=(       d    U R                   nU=(       d    UR                  n[        U[        5      (       a  U/OUnU V
s/ s H  oR	                  U
5      PM     nn
U" XU-   SSSS9R                  U5      nU" UR                  UR                  SS9nUR                  U	S-   *    nUS S 2US 24   nUR                  S S 2US 24   nUR                  XTS9nUR                  US9nX4$ s  sn
f )	N
max_lengthTpt)re   padding
truncationreturn_tensors)	input_idsattention_maskoutput_hidden_statesr   dtyper.   r.   )	_execution_devicern   
isinstancestrformattorj   rk   hidden_states)rb   rK   rJ   r   r.   rn   r]   templatedrop_idxhidden_state_skip_layeretxt
txt_tokensencoder_hidden_statesrE   encoder_attention_masks                   r*   _get_qwen_prompt_embeds,HunyuanImagePipeline._get_qwen_prompt_embeds   s    1411+++'44&&+126aq!628;\^bsw

"V* 	 !- **%44!%!

 .;;>UXY>Y<Z[%al3!+!:!:1hi<!H%((u(D!7!:!:&!:!I44% 3s   	C0c           	        U=(       d    U R                   nU=(       d    UR                  n[        U[        5      (       a  [	        S5      eUc  [	        S5      eU" USUSSSS9R                  U5      nU" UR                  UR                  R                  5       S9S   nUR                  XTS	9nUR                  R                  US
9n	X4$ )Nzbyt5 prompt should be a stringzbyt5 prompt should not be Nonere   Trf   )rg   re   rh   add_special_tokensri   )rj   rk   r   rm   ro   )	rp   rn   rq   listr1   rt   rj   rk   float)
rb   rK   rJ   r   r.   rn   r]   r{   rE   r}   s
             r*   _get_byt5_prompt_embeds,HunyuanImagePipeline._get_byt5_prompt_embeds  s     1411+++fd##=>>^=>> +#
 "V* 	 % **%44::<
 
 &((u(D!+!:!:!=!=V!=!L44r@   r   c	           
        U=(       d    U R                   nUc  S/U-  n[        U[        5      (       a  U/OUnUcI  U R                  U R                  U R
                  UUU R                  U R                  U R                  S9u  pVUGc  / n	/ n
U Vs/ s H  n[        U5      PM     nnU H  nUcq  [        R                  " SU R                  U R                  R                  R                  4US9n[        R                  " SU R                  4U[        R                   S9nO3U R#                  U R$                  U R                  UUU R                  S9u  pU	R'                  U5        U
R'                  U5        M     [        R(                  " U	SS9n[        R(                  " U
SS9nUR*                  u  nnnUR-                  SUS5      nUR/                  X4-  US	5      nUR-                  SUS5      nUR/                  X4-  U5      nUR*                  u  nnnUR-                  SUS5      nUR/                  X4-  US	5      nUR-                  SUS5      nUR/                  X4-  U5      nXVXx4$ s  snf )
a>  

Args:
    prompt (`str` or `list[str]`, *optional*):
        prompt to be encoded
    device: (`torch.device`):
        torch device
    batch_size (`int`):
        batch size of prompts, defaults to 1
    num_images_per_prompt (`int`):
        number of images that should be generated per prompt
    prompt_embeds (`torch.Tensor`, *optional*):
        Pre-generated text embeddings. If not provided, text embeddings will be generated from `prompt` input
        argument.
    prompt_embeds_mask (`torch.Tensor`, *optional*):
        Pre-generated text mask. If not provided, text mask will be generated from `prompt` input argument.
    prompt_embeds_2 (`torch.Tensor`, *optional*):
        Pre-generated glyph text embeddings from ByT5. If not provided, will be generated from `prompt` input
        argument using self.tokenizer_2 and self.text_encoder_2.
    prompt_embeds_mask_2 (`torch.Tensor`, *optional*):
        Pre-generated glyph text mask from ByT5. If not provided, will be generated from `prompt` input
        argument using self.tokenizer_2 and self.text_encoder_2.
 )rK   rJ   r   r.   r]   rv   rw   r   ro   r.   rn   )rK   rJ   r   r.   r]   r   )dim)rp   rq   rr   r~   rK   rJ   r]   r_   r`   r+   torchzerosr^   rL   rZ   d_modelint64r   rM   appendcatshaperepeatview)rb   r   r.   
batch_sizenum_images_per_promptrE   prompt_embeds_maskprompt_embeds_2prompt_embeds_mask_2prompt_embeds_2_listprompt_embeds_mask_2_listpglyph_texts
glyph_textglyph_text_embedsglyph_text_embeds_mask_seq_len	seq_len_2s                      r*   encode_prompt"HunyuanImagePipeline.encode_prompt(  s   D 1411>TJ&F'44&& 040L0L..!..%)%>%>44>> 1M 1-M "#% (*%:@A&Q-a0&KA)
%(-D779L9L9S9S9[9[\ek)% .3[[D778u{{.* AE@\@\"&"2"2%)%8%8)%-1-H-H A] A=% %++,=>)001GH% *( $ii(<!DO#(99-FA#N %++7A%,,Q0EqI%**:+MwXZ[/66q:OQRS/44Z5WY`a)//9a)004I1M)..z/QS\^`a3::1>SUVW3889[]fg/WWI Bs   I&c           
     *  ^  UT R                   S-  -  S:w  d  UT R                   S-  -  S:w  a,  [        R                  ST R                   S-   SU SU S35        UbW  [        U 4S jU 5       5      (       d=  [	        ST R
                   S	U Vs/ s H  oT R
                  ;  d  M  UPM     sn 35      eUb  Ub  [	        S
U SU S35      eUc  Uc  [	        S5      eUbA  [        U[        5      (       d,  [        U[        5      (       d  [	        S[        U5       35      eUb  Ub  [	        SU SU S35      eUb  Uc  [	        S5      eUb  Uc  [	        S5      eUc  U	c  [	        S5      eU	b  U
c  [	        S5      eUb  Uc  [	        S5      eg g s  snf )Nr   r   z-`height` and `width` have to be divisible by z	 but are z and z(. Dimensions will be resized accordinglyc              3  @   >#    U  H  oTR                   ;   v   M     g 7fN)_callback_tensor_inputs).0krb   s     r*   	<genexpr>4HunyuanImagePipeline.check_inputs.<locals>.<genexpr>  s      F
7Y!---7Ys   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`: zIf `prompt_embeds` are provided, `prompt_embeds_mask` also have to be passed. Make sure to generate `prompt_embeds_mask` from the same text encoder that was used to generate `prompt_embeds`.zIf `negative_prompt_embeds` are provided, `negative_prompt_embeds_mask` also have to be passed. Make sure to generate `negative_prompt_embeds_mask` from the same text encoder that was used to generate `negative_prompt_embeds`.ziProvide either `prompt` or `prompt_embeds_2`. Cannot leave both `prompt` and `prompt_embeds_2` undefined.zIf `prompt_embeds_2` are provided, `prompt_embeds_mask_2` also have to be passed. Make sure to generate `prompt_embeds_mask_2` from the same text encoder that was used to generate `prompt_embeds_2`.zIf `negative_prompt_embeds_2` are provided, `negative_prompt_embeds_mask_2` also have to be passed. Make sure to generate `negative_prompt_embeds_mask_2` from the same text encoder that was used to generate `negative_prompt_embeds_2`.)
rP   loggerwarningallr1   r   rq   rr   r   type)rb   r   heightwidthnegative_promptrE   negative_prompt_embedsr   negative_prompt_embeds_maskr   r   negative_prompt_embeds_2negative_prompt_embeds_mask_2"callback_on_step_end_tensor_inputsr   s   `              r*   check_inputs!HunyuanImagePipeline.check_inputs  s     T**Q./14AVAVYZAZ8[_`8`NN?@U@UXY@Y?ZZcdjckkpqvpw  x`  a .9# F
7YF
 C
 C
 DTEaEaDbbn  |^  pH  |^vw  ko  kG  kG  bGpq  |^  pH  oI  J  -";08N}o ^0 0  ^ 5w  FC)@)@TZ\`IaIaQRVW]R^Q_`aa&+A+M9/9J K*++]_ 
 $);)C Q  "-2M2U u  >o5{  &+?+G Y  $/4Q4Y }  5Z/O pHs   F%Fc	                $   [        U5      U R                  -  n[        U5      U R                  -  nXX44n	Ub  UR                  XeS9$ [        U[        5      (       a*  [        U5      U:w  a  [        S[        U5       SU S35      e[        XXeS9nU$ )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.)	generatorr.   rn   )intrP   rt   rq   r   r9   r1   r   )
rb   r   num_channels_latentsr   r   rn   r.   r   rD   r   s
             r*   prepare_latents$HunyuanImagePipeline.prepare_latents  s     V 5 55E
d3336A::V:99i&&3y>Z+GA#i.AQ R&<'gi 
 u&Vr@   c                    U R                   $ r   )_attention_kwargsrb   s    r*   attention_kwargs%HunyuanImagePipeline.attention_kwargs      %%%r@   c                    U R                   $ r   )_num_timestepsr   s    r*   num_timesteps"HunyuanImagePipeline.num_timesteps  s    """r@   c                    U R                   $ r   )_current_timestepr   s    r*   current_timestep%HunyuanImagePipeline.current_timestep  r   r@   c                    U R                   $ r   )
_interruptr   s    r*   	interruptHunyuanImagePipeline.interrupt  s    r@   2   g      
@pilTc                |   U=(       d    U R                   U R                  -  nU=(       d    U R                   U R                  -  nU R                  UUUUUUUUUUUUUS9  UU l        SU l        SU l        Ub  [        U[        5      (       a  SnO3Ub!  [        U[        5      (       a  [        U5      nOUR                  S   nU R                  nU R                  UUUUUUUUS9u  pnnUR                  U R                  R                  5      nUR                  U R                  R                  5      n[         R"                  " US:H  5      (       d  U R$                  b  U R$                  nO#U R&                  b  U R&                  nO	[)        SS9nUR*                  (       au  UR,                  S:  ae  U R                  UUUUUUUUS9u  nnnnUR                  U R                  R                  5      nUR                  U R                  R                  5      nU R                  R.                  R0                  nU R3                  UU-  UUUUR                  UU	U
S9n
Uc  [4        R6                  " S	S
US-   5      SS OUn[9        U R:                  UUUS9u  nn[=        [        U5      XPR:                  R>                  -  -
  S5      n[        U5      U l         U R                  R.                  RB                  (       a  Uc  [E        S5      eU R                  R.                  RB                  (       a?  [         RF                  " U/U
R                  S   -  U R                  R                  US9S-  nOSnU RH                  c  0 U l        U R:                  RK                  S5        U RM                  US9 n[O        U5       GH%  u  n n!U RP                  (       a  M  U!U l        U!RS                  U
R                  S   5      R                  U
R                  5      n"U R                  R.                  RT                  (       ai  U [        U5      S-
  :X  a  [         RF                  " S
/US9n#OUU S-      n#U#RS                  U
R                  S   5      R                  U
R                  5      n#OSn#X4X4UU4UU4S.n$URW                  U UU!S9  URY                  U$5      n%U% H  n&UR[                  U R                  5        U$R]                  5        V's0 s H  n'U'[_        U&U'5      _M     n(n'[_        U&UR`                  5      n)U R                  Rc                  U)5         U R                  " SU
U"U#UU RH                  SS.U(D6S   U&l2        SSS5        URg                  U R                  5        M     U" U%5      S   n*U
R                  n+U R:                  Ri                  U*U!U
SS9S   n
U
R                  U+:w  a>  [         Rj                  Rl                  Ro                  5       (       a  U
R                  U+5      n
UbJ  0 n,U H  n-[q        5       U-   U,U-'   M     U" U U U!U,5      n.U.Rs                  SU
5      n
U.Rs                  SU5      nU [        U5      S-
  :X  d)  U S-   U:  a0  U S-   U R:                  R>                  -  S:X  a  URu                  5         [v        (       d  GM  [x        Rz                  " 5         GM(     SSS5        SU l        US:X  a  U
n/O}U
R                  U R|                  R                  5      U R|                  R.                  R~                  -  n
U R|                  R                  U
SS9S   n/U R                  R                  U/US9n/U R                  5         U(       d  U/4$ [        U/S9$ s  sn'f ! , (       d  f       GN/= f! , (       d  f       N= f)a  
Function invoked when calling the pipeline for generation.

Args:
    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 and negative_prompt_embeds is
        not provided, will use an empty negative prompt. Ignored when not using guidance. ).
    height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
        The height in pixels of the generated image. This is set to 1024 by default for the best results.
    width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
        The width in pixels of the generated image. This is set to 1024 by default for the best results.
    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.
    sigmas (`list[float]`, *optional*):
        Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
        their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
        will be used.
    distilled_guidance_scale (`float`, *optional*, defaults to None):
        A guidance scale value for guidance distilled models. Unlike the traditional classifier-free guidance
        where the guidance scale is applied during inference through noise prediction rescaling, guidance
        distilled models take the guidance scale directly as an input parameter during forward pass. Guidance
        is enabled by setting `distilled_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. For
        guidance distilled models, this parameter is required. For non-distilled models, this parameter will be
        ignored.
    num_images_per_prompt (`int`, *optional*, defaults to 1):
        The number of images 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.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 will be 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, *e.g.* prompt weighting. If not
        provided, text embeddings will be generated from `prompt` input argument.
    prompt_embeds_mask (`torch.Tensor`, *optional*):
        Pre-generated text embeddings mask. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
        If not provided, text embeddings mask will be generated from `prompt` input argument.
    prompt_embeds_2 (`torch.Tensor`, *optional*):
        Pre-generated text embeddings for ocr. Can be used to easily tweak text inputs, *e.g.* prompt
        weighting. If not provided, text embeddings for ocr will be generated from `prompt` input argument.
    prompt_embeds_mask_2 (`torch.Tensor`, *optional*):
        Pre-generated text embeddings mask for ocr. Can be used to easily tweak text inputs, *e.g.* prompt
        weighting. If not provided, text embeddings mask for ocr 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.
    negative_prompt_embeds_mask (`torch.Tensor`, *optional*):
        Pre-generated negative text embeddings mask. Can be used to easily tweak text inputs, *e.g.* prompt
        weighting. If not provided, negative text embeddings mask will be generated from `negative_prompt`
        input argument.
    negative_prompt_embeds_2 (`torch.Tensor`, *optional*):
        Pre-generated negative text embeddings for ocr. Can be used to easily tweak text inputs, *e.g.* prompt
        weighting. If not provided, negative text embeddings for ocr will be generated from `negative_prompt`
        input argument.
    negative_prompt_embeds_mask_2 (`torch.Tensor`, *optional*):
        Pre-generated negative text embeddings mask for ocr. Can be used to easily tweak text inputs, *e.g.*
        prompt weighting. If not provided, negative text embeddings mask for ocr 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.qwenimage.QwenImagePipelineOutput`] 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.

Examples:

Returns:
    [`~pipelines.hunyuan_image.HunyuanImagePipelineOutput`] or `tuple`:
    [`~pipelines.hunyuan_image.HunyuanImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When
    returning a tuple, the first element is a list with the generated images.
)
r   rE   r   r   r   r   r   r   r   r   NFr   r   )r   rE   r   r.   r   r   r   r   )enabled)r   r   r   r   rn   r.   r   rD   g      ?g        r   )r/   zD`distilled_guidance_scale` is required for guidance-distilled model.rm   g     @@)totalro   )r|   r}   encoder_hidden_states_2encoder_attention_mask_2)stepr;   timestep)ru   r   
timestep_rguidancer   return_dict)r   rD   rE   latent)output_type)imagesr0   )Era   rP   r   r   r   r   rq   rr   r   r9   r   rp   r   rt   rN   rn   r   r   rF   rG   r   _enablednum_conditionsrZ   in_channelsr   nplinspacer?   r:   maxorderr   guidance_embedsr1   tensorr   set_begin_indexprogress_bar	enumerater   expanduse_meanflow	set_stateprepare_inputsprepare_modelsr7   rY   _identifier_keycache_context
noise_predcleanup_modelsr   backendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_steprI   scaling_factordecoder\   postprocessmaybe_free_model_hooksr   )0rb   r   r   r   r   r;   distilled_guidance_scaler/   r   r   rD   rE   r   r   r   r   r   r   r   r   r   r   callback_on_step_endr   r   r.   rG   r   r-   num_warmup_stepsr   r   itr   r   guider_inputsguider_stateguider_state_batch
input_namecond_kwargscontext_namer   latents_dtypecallback_kwargsr   callback_outputsimages0                                                   r*   __call__HunyuanImagePipeline.__call__  s   t K433d6K6KKI11D4I4II 	+'#91(C/Q+!5%=*G 	 	
  "2!% *VS"9"9JJvt$<$<VJ&,,Q/J'' TXSeSe'1!"7+!5 Tf 	T
P?<P &(()9)9)?)?@),,T-=-=-C-CD yyA-..4??3N__F[[$[[F 2%@F??v44q8 ""&4#>%&; 8%B # 	&+(- &<%>%>t?O?O?U?U%V"'?'B'B4CSCSCYCY'Z$  $//66BB&&!$99!5%% ' 	
 IOS#':Q'>?D\b);DNNL_agpv)w&	&s9~0CnnFZFZ0ZZ\]^!)n ""227O7Wcdd""22-.q1AAIYIYI_I_hn   H  (%'D" 	&&q)%89\!),1>>)*&88GMM!$4588G##**77C	NQ..%*\\3%%G
%.q1u%5
!+!2!27==3C!D!G!G!VJ!%J
 /<-T/A._0?AY/Z1EGd0e	!   a=P[\ ]  &44]C +7&))$*:*:; _l^p^p^r#^rPZ
G,>
$KK^r   #
 $++=v?U?U#VL))77E8<8H8H 9*1%-'1%--1-B-B(-9 *9 9*5 F ))$*:*:;/ +7L $L1!4
 !(..--j!WRW-XYZ[==M1~~))6688")**]";'3&(O?-3Xa[* @';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') =LLNS - :X "&("Ejj0488??3Q3QQGHHOOGO?BE((44U4TE 	##%8O)77W# FEk :9s>   (E^-=^
3^-,^	3E^-^-^-
^*%^--
^;)r   r   r   r   ra   r\   r_   r`   r^   r]   rP   )NN)r:   r   rI   r   rJ   r   rK   r   rL   r	   rM   r   rN   r   rG   #AdaptiveProjectedMixGuidance | NonerF   r  )NNNrQ   rS   rT   r   )rK   r   rJ   r   r   str | list[str]r.   torch.device | Nonern   torch.dtype | Noner]   r   rv   rr   rw   r   rx   r   )NNrR   )rK   r   rJ   r	   r   rr   r.   r  rn   r  r]   r   )Nr   r   NNNN)r   r  r.   r  r   r   r   r   rE   torch.Tensor | Noner   r  r   r  r   r  )
NNNNNNNNNNr   ).r   r  r   r  r   
int | Noner   r  r;   r   r  zfloat | Noner/   list[float] | Noner   r   r   z.torch.Generator | list[torch.Generator] | NonerD   r  rE   r  r   r  r   r  r   r  r   r  r   r  r   r  r   r  r   z
str | Noner   boolr   zdict[str, Any] | Noner  z!Callable[[int, int], None] | Noner   z	list[str])__name__
__module____qualname____firstlineno____doc__model_cpu_offload_seqr   _optional_componentsrW   r~   r   r   r   r   propertyr   r   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr  __static_attributes____classcell__)r8   s   @r*   rB   rB      s   0 M(/:((3 7;:> &2 & ' & 9	 &
 " & ' & # & 4 & 4 & 8 &  &L #'&*$($( ^'(#5!#5 9#5  	#5
 $#5 "#5 "#5 #5 #5 "%#5T '+$($'"5 "5 %"5 	"5
 $"5 ""5 ""5N '+%&-126/348\X\X $\X 	\X
  #\X +\X 0\X -\X 2\XF #$(!!%&*+/C\ : & & # # & &   ]]_12 #'+/! #%15%)%&DH'+-1266:;?/3488<=A"' 26BF9B1j8j8 )j8 	j8
 j8 !j8 #/j8 #j8  #j8 Bj8 %j8 +j8 0j8 !4j8 &9j8  -!j8" 2#j8$ #6%j8& (;'j8(  )j8* +j8, 0-j8. @/j80 -61j8 3 j8r@   rB   )r   rr   )NNNN)r;   r  r.   zstr | torch.device | Noner-   zlist[int] | Noner/   r  ).
__future__r   r3   r   typingr   r   numpyr   r   transformersr   r   r   r	   guidersr   r\   r   modelsr   r   
schedulersr   utilsr   r   r   utils.torch_utilsr   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr   r   
get_loggerr  r   r&  r+   r?   rB   r0   r@   r*   <module>r8     s    #  	     j j 3 0 O 9 O O - . 7 ))MM 
		H	% &! N '+(,"&!%8*#8* &8*  	8*
 8*vD8, D8r@   