
    i                        d dl Z d dl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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 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$m%c m&Z' dZ(ndZ( ejR                  e*      Z+dZ,de-fdZ.	 	 	 	 ddee/   deee-ej`                  f      deee/      deee1      fdZ2 G d de!      Z3y)    N)AnyCallableDictListOptionalUnion)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")
        ```
promptc                    g }d}d}d}d}t        j                  ||       }t        j                  ||       }t        j                  ||       }t        j                  ||       }	|j                  |       |j                  |       |j                  |       |j                  |	       |r(dj                  |D 
cg c]  }
d|
 d
 c}
      dz   }|S d}|S c c}
w )	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)r   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               /home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/diffusers/pipelines/hunyuan_image/pipeline_hunyuanimage.pyextract_glyph_textr.   >   s     ''#1 #1 ::&:FC::&:FC#%::.JF#S #%::.JF#S 12129:9:#yyGX)YtF4&*:)YZ]aa    $	 *Zs   8C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 valuesr1   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r1   r0   r2   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r2   r0   r0    )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r1   len)	schedulerr/   r0   r1   r2   kwargsaccepts_timestepsaccept_sigmass           r-   retrieve_timestepsrB   c   s   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	 	M)FMfM''	!)n ))) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	 	GvfGG''	!)n ))) 	 	 3MFMfM''	)))    c            3           e Zd ZdZdZddgZddgZ	 	 d;ded	ed
e	de
dedededee   dee   f fdZ	 	 	 	 	 	 	 d<de
d
e	deeee   f   deej*                     deej,                     dedededefdZ	 	 	 d=ded
ededeej*                     deej,                     defdZ	 	 	 	 	 	 	 d>deeee   f   deej*                     dededeej4                     deej4                     deej4                     deej4                     fdZ	 	 	 	 	 	 	 	 	 	 d?d Z	 d@d!Zed"        Zed#        Z ed$        Z!ed%        Z" ejF                          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eee   f   d*eeee   f   d+ee   d,ee   d-ed.ee&   d/eee&      ded0eeejN                  eejN                     f      deej4                     deej4                     deej4                     d1eej4                     d2eej4                     deej4                     deej4                     d3eej4                     d4eej4                     d5ee   d6e(d7ee)ee*f      d8ee+eee)gdf      d9ee   f.d:              Z, xZ-S )AHunyuanImagePipelinea  
    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guiderNr>   vaetext_encoder	tokenizertext_encoder_2tokenizer_2transformerc
                 :   t         
|           | j                  |||||||||		       t        | dd       r | j                  j
                  j                  nd| _        t        | j                        | _	        d| _
        d| _        d| _        d| _        d	| _        y )
N)	rJ   rK   rL   rM   rN   rO   r>   rI   rH   rJ       )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getattrrJ   configspatial_compression_ratiorR   r   image_processortokenizer_max_lengthtokenizer_2_max_lengthprompt_template_encode prompt_template_encode_start_idxdefault_sample_size)selfr>   rJ   rK   rL   rM   rN   rO   rI   rH   r<   s             r-   rY   zHunyuanImagePipeline.__init__   s     	%)##! 	 
	
 NUUY[`bfMg I Imo0$BWBWX$(!&)# 'l#02-#% rC   r   r0   dtyper_   templatedrop_idxhidden_state_skip_layerc
                    |xs | j                   }|xs |j                  }t        |t              r|gn|}|D 
cg c]  }
|j	                  |
       }}
 ||||z   ddd      j                  |      } ||j                  |j                  d      }|j                  |	dz       }|d d |d f   }|j                  d d |d f   }|j                  ||      }|j                  |      }||fS c c}
w )	N
max_lengthTpt)rj   padding
truncationreturn_tensors)	input_idsattention_maskoutput_hidden_statesr   re   r0   r0   )	_execution_devicere   
isinstancestrformattoro   rp   hidden_states)rd   rL   rK   r   r0   re   r_   rf   rg   rh   etxt
txt_tokensencoder_hidden_statesrG   encoder_attention_masks                   r-   _get_qwen_prompt_embedsz,HunyuanImagePipeline._get_qwen_prompt_embeds   s    1411+++'4&&+12axq!2208;\^bsw

"V* 	 !- **%44!%!

 .;;>UXY>Y<Z[%al3!+!:!:1hi<!H%((uV(D!7!:!:&!:!I444% 3s   C.c                    |xs | j                   }|xs |j                  }t        |t              rt	        d      |t	        d       ||d|ddd      j                  |      } ||j                  |j                  j                               d   }|j                  ||	      }|j                  j                  |
      }	||	fS )Nzbyt5 prompt should be a stringzbyt5 prompt should not be Nonerj   Trk   )rl   rj   rm   add_special_tokensrn   )ro   rp   r   rr   rs   )	rt   re   ru   listr5   rx   ro   rp   float)
rd   rL   rK   r   r0   re   r_   r|   rG   r~   s
             r-   _get_byt5_prompt_embedsz,HunyuanImagePipeline._get_byt5_prompt_embeds  s     1411+++fd#=>>^=>> +#
 "V* 	 % **%44::<
 
 &((uV(D!+!:!:!=!=V!=!L444rC   r   
batch_sizenum_images_per_promptprompt_embeds_maskprompt_embeds_2prompt_embeds_mask_2c	           	         |xs | j                   }|dg|z  }t        |t              r|gn|}|M| j                  | j                  | j
                  ||| j                  | j                  | j                        \  }}|!g }	g }
|D cg c]  }t        |       }}|D ]  }|ut        j                  d| j                  | j                  j                  j                  f|      }t        j                  d| j                  f|t        j                         }n7| j#                  | j$                  | j                  ||| j                        \  }}|	j'                  |       |
j'                  |        t        j(                  |	d      }t        j(                  |
d      }|j*                  \  }}}|j-                  d|d      }|j/                  ||z  |d	      }|j-                  d|d      }|j/                  ||z  |      }|j*                  \  }}}|j-                  d|d      }|j/                  ||z  |d	      }|j-                  d|d      }|j/                  ||z  |      }||||fS c c}w )
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.
         )rL   rK   r   r0   r_   rf   rg   r   rs   r0   re   )rL   rK   r   r0   r_   r   )dim)rt   ru   rv   r   rL   rK   r_   ra   rb   r.   torchzerosr`   rM   r\   d_modelint64r   rN   appendcatshaperepeatview)rd   r   r0   r   r   rG   r   r   r   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_promptz"HunyuanImagePipeline.encode_prompt&  s   D 1411>TJ&F'4&& 040L0L..!..%)%>%>44>> 1M 1-M- "#% (*%:@AQ-a0AKA) I
%(-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%I( $ii(<!DO#(99-FA#N %++7A%,,Q0EqI%**:8M+MwXZ[/66q:OQRS/44ZBW5WY`a)//9a)004I1M)..z<Q/QS\^`a3::1>SUVW388F[9[]fg0/CWWWI Bs   I)c           
          | j                   dz  z  dk7  s| j                   dz  z  dk7  r,t        j                  d j                   dz   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      ||t	        d      ||	t	        d      |	|
t	        d      ||t	        d      y y c c}w )Nr   r   z-`height` and `width` have to be divisible by z	 but are z and z(. Dimensions will be resized accordinglyc              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0krd   s     r-   	<genexpr>z4HunyuanImagePipeline.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`: 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`.)
rR   loggerwarningallr5   r   ru   rv   r   type)rd   r   heightwidthnegative_promptrG   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_inputsz!HunyuanImagePipeline.check_inputs  sm     T**Q./14AVAVYZAZ8[_`8`NN?@U@UXY@Y?ZZcdjckkpqvpw  x`  a .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*++]_ 
 $);)C Q  "-2M2U u  >o5{  &+?+G Y  $/4Q4Y }  5Z/O pHs   E'E'c	                 ,   t        |      | j                  z  }t        |      | j                  z  }||||f}	||j                  ||      S t        |t              r)t        |      |k7  rt        dt        |       d| d      t        |	|||      }|S )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.)	generatorr0   re   )intrR   rx   ru   r   r=   r5   r   )
rd   r   num_channels_latentsr   r   re   r0   r   rF   r   s
             r-   prepare_latentsz$HunyuanImagePipeline.prepare_latents  s     V 5 55E
d333165A::V5:99i&3y>Z+GA#i.AQ R&<'gi 
 u	&PUVrC   c                     | j                   S r   )_attention_kwargsrd   s    r-   attention_kwargsz%HunyuanImagePipeline.attention_kwargs      %%%rC   c                     | j                   S r   )_num_timestepsr   s    r-   num_timestepsz"HunyuanImagePipeline.num_timesteps  s    """rC   c                     | j                   S r   )_current_timestepr   s    r-   current_timestepz%HunyuanImagePipeline.current_timestep  r   rC   c                     | j                   S r   )
_interruptr   s    r-   	interruptzHunyuanImagePipeline.interrupt  s    rC   2   g      
@pilTr   r   r   r/   distilled_guidance_scaler2   r   r   r   r   r   output_typereturn_dictr   callback_on_step_endr   c                    |xs | j                   | j                  z  }|xs | j                   | j                  z  }| j                  |||||||||||||       || _        d| _        d| _        |t        |t              rd}n-|t        |t              rt        |      }n|j                  d   }| j                  }| j                  ||||||||      \  }}}}|j                  | j                  j                        }|j                  | j                  j                        }t!        j"                  |dk(        s| j$                  | j$                  }n%| j&                  | j&                  }nt)        d      }|j*                  rw|j,                  dkD  rh| j                  ||||||||      \  }}}}|j                  | j                  j                        }|j                  | j                  j                        }| j                  j.                  j0                  }| j3                  ||z  ||||j                  ||	|
      }
|t5        j6                  d	d
|dz         dd n|}t9        | j:                  |||      \  }}t=        t        |      || j:                  j>                  z  z
  d      }t        |      | _         | j                  j.                  jB                  r|tE        d      | j                  j.                  jB                  rAt!        jF                  |g|
j                  d   z  | j                  j                  |      dz  }nd}| jH                  i | _        | j:                  jK                  d       | jM                  |      5 }tO        |      D ]
  \  } }!| jP                  r|!| _        |!jS                  |
j                  d         j                  |
j                        }"| j                  j.                  jT                  rj| t        |      dz
  k(  rt!        jF                  d
g|      }#n|| dz      }#|#jS                  |
j                  d         j                  |
j                        }#nd}#||f||f||f||fd}$|jW                  | ||!       |jY                  |$      }%|%D ]  }&|j[                  | j                         |$j]                         D 'ci c]  }'|'t_        |&|'       }(}'t_        |&|j`                        })| j                  jc                  |)      5   | j                  d|
|"|#|| jH                  dd|(d   |&_2        ddd       |jg                  | j                           ||%      d   }*|
j                  }+| j:                  ji                  |*|!|
d      d   }
|
j                  |+k7  r9t         jj                  jl                  jo                         r|
j                  |+      }
|Hi },|D ]  }-tq               |-   |,|-<     || | |!|,      }.|.js                  d|
      }
|.js                  d|      }| t        |      dz
  k(  s'| dz   |kD  r/| dz   | j:                  j>                  z  dk(  r|ju                          tv        sty        jz                           	 ddd       d| _        |dk(  r|
}/n|
j                  | j|                  j                        | j|                  j.                  j~                  z  }
| j|                  j                  |
d      d   }/| j                  j                  |/|      }/| j                          |s|/fS t        |/      S c c}'w # 1 sw Y   xY w# 1 sw Y   xY w)ar  
        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   rG   r   r   r   r   r   r   r   r   NFr   r   )r   rG   r   r0   r   r   r   r   )enabled)r   r   r   r   re   r0   r   rF   g      ?g        r   )r2   zD`distilled_guidance_scale` is required for guidance-distilled model.rr   g     @@)totalrs   )r}   r~   encoder_hidden_states_2encoder_attention_mask_2)stepr/   timestep)ry   r   
timestep_rguidancer   r   )r   rF   rG   latent)r   )imagesr4   )Erc   rR   r   r   r   r   ru   rv   r   r=   r   rt   r   rx   rO   re   r   r   rH   rI   r   _enablednum_conditionsr\   in_channelsr   nplinspacerB   r>   maxorderr   guidance_embedsr5   tensorr   set_begin_indexprogress_bar	enumerater   expanduse_meanflow	set_stateprepare_inputsprepare_modelsr;   r[   _identifier_keycache_context
noise_predcleanup_modelsr   backendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_steprJ   scaling_factordecoder^   postprocessmaybe_free_model_hooksr   )0rd   r   r   r   r   r/   r   r2   r   r   rF   rG   r   r   r   r   r   r   r   r   r   r   r   r   r   r0   rI   r   r1   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__zHunyuanImagePipeline.__call__  s   t K433d6K6KKI11D4I4II 	+'#91(C/Q+!5%=*G 	 	
  "2!% *VS"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~0CdnnFZFZ0ZZ\]^!)n ""227O7Wcdd""22-.q1AAIYIYI_I_hn   H  (%'D" 	&&q)%89 j	#\!), i#1>>)*&88GMM!$4588G##**77C	NQ..%*\\3%%G
%.q1u%5
!+!2!27==3C!D!G!G!VJ!%J
 /<=S-T/AC^._0?AY/Z1EGd0e	!   a=P[\ ]  &44]C +7 <&))$*:*:; _l^p^p^r#PZ
G,>
$KK#K #
 $++=v?U?U#VL))77E 
8H8H8H 9*1%-'1%--1-B-B(-9 *9 9*5
 ))$*:*:;/<L $L1!4
 !(..--j!WRW-XYZ[==M1~~))668")**]";'3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNSi#j	#X "&("Ejj0488??3Q3QQGHHOOGO?BE((44U4TE 	##%8O)77W#
 
kj	# j	#s>   E]7]%
33]7&,]*	D>]7]7%]7*]4/]77^ )NN)NNNrS   rU   rV   r   )NNrT   )Nr   r   NNNN)
NNNNNNNNNNr   ).__name__
__module____qualname____doc__model_cpu_offload_seqr   _optional_componentsr   r   r
   r   r   r	   r   r   r   rY   r   rv   r   r   r0   re   r   r   r   Tensorr   r   r   propertyr   r   r   r   no_gradr   EXAMPLE_DOC_STRINGr   	Generatorboolr   r   r   r
  __classcell__)r<   s   @r-   rE   rE      s   0 M(/:((3 :>=A &2 & ' & 9	 &
 " & ' & # & 4 & 56 & 9: &L )-)-'+$( ^'(#5!#5 9#5 c49n%	#5
 &#5 $#5 "#5 #5 #5 "%#5T *.'+$'"5 "5 %"5 	"5
 &"5 $"5 ""5N *.%&0459267;\Xc49n%\X &\X 	\X
  #\X  -\X %U\\2\X "%,,/\X 'u||4\XF #$(!!%&*+/C\ : & & # # & &   U]]_12 )-15 $##%48(,%&MQ*.04599=>B267;;?@D%* 59KO9B1j8c49n%j8 sDI~.j8 	j8
 }j8 !j8 #+5/j8 e%j8  #j8 E%//43H"HIJj8 %,,'j8  -j8 %U\\2j8 !) 6j8 &.ell%;j8  "%,,/!j8" 'u||4#j8$ #+5<<"8%j8& (0'='j8( c])j8* +j8, #4S>2-j8. 'xc40@$0F'GH/j80 -1I1j8 3 j8rC   rE   )NNNN)4r7   r   typingr   r   r   r   r   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  rv   r.   r   r0   r   rB   rE   r4   rC   r-   <module>r&     s     	 = =   j j 3 0 O 9 O O - . 7 ))MM 
		H	% &! s ! N *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vD8, D8rC   