
    +h                     N   S SK r S SKrS SKrS SKJr  S SKrS SKJrJ	r	J
r
JrJrJrJr  S SKrS SKJs  Jr  S SKJrJrJr  SSKJrJr  SSKJr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(J)r)J*r*J+r+J,r,J-r-J.r.  SSK/J0r0J1r1J2r2  SSK3J4r4  SSK5J6r6  SSK7J8r8  \*" 5       (       a  S SK9J:s  J;r<  Sr=OSr=\+R|                  " \?5      r@\(" 5       (       a  S SKAJBrB  \)" 5       (       a  S SKCrCSrD    SS\\E   S\\\F\R                  4      S\\\E      S\\\H      4S jjrI " S S\4\5      rJg)    N)AnyCallableDictListOptionalTupleUnion)Gemma2PreTrainedModelGemmaTokenizerGemmaTokenizerFast   )MultiPipelineCallbacksPipelineCallback)PipelineImageInputPixArtImageProcessor)SanaLoraLoaderMixin)AutoencoderDCSanaTransformer2DModel)DPMSolverMultistepScheduler)	BACKENDS_MAPPINGUSE_PEFT_BACKENDis_bs4_availableis_ftfy_availableis_torch_xla_availableloggingreplace_example_docstringscale_lora_layersunscale_lora_layers)
get_deviceis_torch_versionrandn_tensor   )DiffusionPipeline)ASPECT_RATIO_1024_BIN   )SanaPipelineOutputTF)BeautifulSoupa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import SanaSprintImg2ImgPipeline
        >>> from diffusers.utils.loading_utils import load_image

        >>> pipe = SanaSprintImg2ImgPipeline.from_pretrained(
        ...     "Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")

        >>> image = load_image(
        ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/penguin.png"
        ... )


        >>> image = pipe(prompt="a cute pink bear", image=image, strength=0.5, height=832, width=480).images[0]
        >>> image[0].save("output.png")
        ```
num_inference_stepsdevice	timestepssigmasc                    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 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*   len)	schedulerr(   r)   r*   r+   kwargsaccepts_timestepsaccept_sigmass           o/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/pipelines/sana/pipeline_sana_sprint_img2img.pyretrieve_timestepsr<   W   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            9       L  ^  \ rS rSrSr\R                  " S5      rSrSS/r	S\
\\4   S\S	\S
\S\4
U 4S jjrS rS rS rS r   SIS\
\\\   4   S\R2                  S\R4                  S\S\S\\\      4S jjr        SJS\
\\\   4   S\S\\R2                     S\\R>                     S\\R>                     S\S\S\\\      S\\    4S jjr!S  r"S! r#   SKS" jr$SLS# jr%S$ r&S%\'S&\S'\S\R2                  S\R4                  4
S( jr( SMS) jr)\*S* 5       r+\*S+ 5       r,\*S, 5       r-\*S- 5       r.\R^                  " 5       \0" \15      SS.SS/S0S1SS2SS3S3S4SSSSS5S6SS6SSS/S/ S7Q4S\
\\\   4   S8\S9\\   S:\ S;\ S<\ S%\'S=\ S\\   S'\S&\S>\ S?\\
\Rd                  \\Rd                     4      S\\R>                     S\\R>                     S\\R>                     S@\\   SA\S\SB\SC\\3\\44      SD\\5\\\3/S4      SE\\   S\S\\   SF\
\6\74   44SG jj5       5       r8SHr9U =r:$ )NSanaSprintImg2ImgPipeline   zf
Pipeline for text-to-image generation using [SANA-Sprint](https://huggingface.co/papers/2503.09641).
u5   [#®•©™&@·º½¾¿¡§~\)\(\]\[\}\{\|\\/\*]{1,}ztext_encoder->transformer->vaelatentsprompt_embeds	tokenizertext_encodervaetransformerr7   c                   > [         TU ]  5         U R                  XX4US9  [        U S5      (       a<  U R                  b/  S[        U R                  R                  R                  5      S-
  -  OSU l        [        U R                  S9U l
        g )N)rC   rD   rE   rF   r7   rE   r"   r%       )vae_scale_factor)super__init__register_moduleshasattrrE   r6   configencoder_block_out_channelsrI   r   image_processor)selfrC   rD   rE   rF   r7   r5   s         r;   rK   "SanaSprintImg2ImgPipeline.__init__   s     	hq 	 	
 tU##(< #dhhoo@@AAEF 	
  4TEZEZ[r=   c                 8    U R                   R                  5         g)z
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
N)rE   enable_slicingrQ   s    r;   enable_vae_slicing,SanaSprintImg2ImgPipeline.enable_vae_slicing       
 	!r=   c                 8    U R                   R                  5         g)z
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
computing decoding in one step.
N)rE   disable_slicingrU   s    r;   disable_vae_slicing-SanaSprintImg2ImgPipeline.disable_vae_slicing   s    
 	  "r=   c                 8    U R                   R                  5         g)z
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
processing larger images.
N)rE   enable_tilingrU   s    r;   enable_vae_tiling+SanaSprintImg2ImgPipeline.enable_vae_tiling   s     	 r=   c                 8    U R                   R                  5         g)z
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
computing decoding in one step.
N)rE   disable_tilingrU   s    r;   disable_vae_tiling,SanaSprintImg2ImgPipeline.disable_vae_tiling   rX   r=   F,  Npromptr)   dtypeclean_captionmax_sequence_lengthcomplex_human_instructionc           	      2   [        U[        5      (       a  U/OUn[        U SS5      b  SU R                  l        U R                  XS9nU(       d  UnOPSR                  U5      nU V	s/ s H  oU	-   PM	     nn	[        U R                  R                  U5      5      n
X-   S-
  nU R                  USUSSS	S
9nUR                  nUR                  nUR                  U5      nU R                  UR                  U5      US9nUS   R                  X2S9nX4$ s  sn	f )a  
Encodes the prompt into text encoder hidden states.

Args:
    prompt (`str` or `List[str]`, *optional*):
        prompt to be encoded
    device: (`torch.device`, *optional*):
        torch device to place the resulting embeddings on
    clean_caption (`bool`, defaults to `False`):
        If `True`, the function will preprocess and clean the provided caption before encoding.
    max_sequence_length (`int`, defaults to 300): Maximum sequence length to use for the prompt.
    complex_human_instruction (`list[str]`, defaults to `complex_human_instruction`):
        If `complex_human_instruction` is not empty, the function will use the complex Human instruction for
        the prompt.
rC   Nright)rh   
r"   
max_lengthTpt)paddingrn   
truncationadd_special_tokensreturn_tensors)attention_maskr   )rg   r)   )
isinstancestrgetattrrC   padding_side_text_preprocessingjoinr6   encode	input_idsrt   torD   )rQ   rf   r)   rg   rh   ri   rj   max_length_all
chi_promptpnum_chi_prompt_tokenstext_inputstext_input_idsprompt_attention_maskrB   s                  r;   _get_gemma_prompt_embeds2SanaSprintImg2ImgPipeline._get_gemma_prompt_embeds   s3   0 (44&&4d+7*1DNN'))&)N )0N#<=J.45f1nfF5$'(=(=j(I$J!2H1LNnn %# % 
 %.. + : : 5 8 8 @)).*;*;F*CTi)j%a(++%+G33) 6s   (Dr%   num_images_per_promptr   
lora_scalec
           	         Uc  U R                   nU R                  b  U R                  R                  n
OSn
U	bI  [        U [        5      (       a4  Xl        U R                  b!  [        (       a  [        U R                  U	5        [        U SS5      b  SU R                  l
        UnS/[        [        U* S-   S5      5      -   nUc(  U R                  UUU
UUUS9u  pEUSS2U4   nUSS2U4   nUR                  u  pnUR                  SUS5      nUR!                  X-  US5      nUR!                  US5      nUR                  US5      nU R                  b6  [        U [        5      (       a!  [        (       a  [#        U R                  U	5        XE4$ )a#  
Encodes the prompt into text encoder hidden states.

Args:
    prompt (`str` or `List[str]`, *optional*):
        prompt to be encoded

    num_images_per_prompt (`int`, *optional*, defaults to 1):
        number of images that should be generated per prompt
    device: (`torch.device`, *optional*):
        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.
    clean_caption (`bool`, defaults to `False`):
        If `True`, the function will preprocess and clean the provided caption before encoding.
    max_sequence_length (`int`, defaults to 300): Maximum sequence length to use for the prompt.
    complex_human_instruction (`list[str]`, defaults to `complex_human_instruction`):
        If `complex_human_instruction` is not empty, the function will use the complex Human instruction for
        the prompt.
NrC   rl   r   r%   )rf   r)   rg   rh   ri   rj   )_execution_devicerD   rg   ru   r   _lora_scaler   r   rw   rC   rx   listranger   shaperepeatviewr   )rQ   rf   r   r)   rB   r   rh   ri   rj   r   rg   rn   select_indexbs_embedseq_len_s                   r;   encode_prompt'SanaSprintImg2ImgPipeline.encode_prompt  s   D >++F(%%++EE !j7J&K&K)   ,1A1A!$"3"3Z@4d+7*1DNN' )
sT%a";<< 373P3P+$7*C 4Q 40M *!\/:M$9!\/$J!,221%,,Q0EqI%**8+KWVXY 5 : :8R H 5 < <=RTU V($ 3449I9I#D$5$5zB33r=   c                 n   S[        [        R                  " U R                  R                  5      R
                  R                  5       5      ;   n0 nU(       a  X$S'   S[        [        R                  " U R                  R                  5      R
                  R                  5       5      ;   nU(       a  XS'   U$ )Neta	generator)r/   r0   r1   r7   stepr3   r4   )rQ   r   r   accepts_etaextra_step_kwargsaccepts_generators         r;   prepare_extra_step_kwargs3SanaSprintImg2ImgPipeline.prepare_extra_step_kwargsf  s     s7#4#4T^^5H5H#I#T#T#Y#Y#[\\'*e$ (3w/@/@ATAT/U/`/`/e/e/g+hh-6k*  r=   c                 N   [        X-  U5      n[        [        X-
  S5      5      nU R                  R                  XPR                  R
                  -  S  n[        U R                  S5      (       a1  U R                  R                  XPR                  R
                  -  5        XaU-
  4$ )Nr   set_begin_index)minintmaxr7   r*   orderrM   r   )rQ   r(   strengthr)   init_timestept_startr*   s          r;   get_timesteps'SanaSprintImg2ImgPipeline.get_timestepsx  s    /:<OPc-=qABNN,,W~~7K7K-K-MN	4>>#455NN**7^^5I5I+IJ777r=   c           
        ^  US:  d  US:  a  [        SU 35      eUS-  S:w  d	  US-  S:w  a  [        SU SU S35      e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c  [        S5      eUb  [        U5      US-   :w  a  [        S5      eUb  Ub  [        S5      eUc  Uc  [        S5      eUb  US:w  a  [        S5      eg g s  snf )Nr   r%   z2The value of strength should in [0.0, 1.0] but is rH   z8`height` and `width` have to be divisible by 32 but are z and .c              3   @   >#    U  H  oTR                   ;   v   M     g 7fN)_callback_tensor_inputs).0krQ   s     r;   	<genexpr>9SanaSprintImg2ImgPipeline.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 zEMust provide `prompt_attention_mask` when specifying `prompt_embeds`.zWIf providing custom timesteps, `timesteps` must be of length `num_inference_steps + 1`.zFIf providing custom timesteps, `max_timesteps` should not be provided.z5Should provide either `timesteps` or `max_timesteps`.r"   zNIntermediate timesteps for SCM is not supported when num_inference_steps != 2.)r.   allr   ru   rv   r   typer6   )rQ   rf   r   heightwidthr(   r*   max_timestepsintermediate_timesteps"callback_on_step_end_tensor_inputsrB   r   r   s   `            r;   check_inputs&SanaSprintImg2ImgPipeline.check_inputs  s    a<8a<QRZQ[\]]B;!urzQWX^W__dejdkklmnn-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$)>)Fdee S^7JQ7N%Nvww ]%>eff!6TUU!-2E2Jmnn 3K-7 pHs   4E0E0c                   ^ ^ T(       aT  [        5       (       dE  [        R                  [        S   S   R	                  S5      5        [        R                  S5        SmT(       aT  [        5       (       dE  [        R                  [        S   S   R	                  S5      5        [        R                  S5        Sm[        U[        [        45      (       d  U/nS[        4UU 4S jjnU Vs/ s H
  oC" U5      PM     sn$ s  snf )	Nbs4r   zSetting `clean_caption=True`z#Setting `clean_caption` to False...Fftfytextc                    > T(       a$  TR                  U 5      n TR                  U 5      n U $ U R                  5       R                  5       n U $ r   )_clean_captionlowerstrip)r   rh   rQ   s    r;   process>SanaSprintImg2ImgPipeline._text_preprocessing.<locals>.process  sH    **40**40 K zz|))+Kr=   )
r   loggerwarningr   formatr   ru   tupler   rv   )rQ   r   rh   r   ts   ` `  r;   ry   -SanaSprintImg2ImgPipeline._text_preprocessing  s    !1!3!3NN+E226==>\]^NN@A!M!2!4!4NN+F3B7>>?]^_NN@A!M$..6D	# 	 	 %))Dq
D)))s   *C>c                 ^
   [        U5      n[        R                  " U5      nUR                  5       R	                  5       n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[        USS9R                  n[
        R                  " SSU5      n[
        R                  " S	SU5      n[
        R                  " S
SU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " SSU5      n[
        R                  " S SU5      n[
        R                  " S!SU5      n[
        R                  " U R                  SU5      n[
        R                  " S"SU5      n[
        R                  " S#5      n[        [
        R                  " X!5      5      S$:  a  [
        R                  " USU5      n[        R                  " U5      n[        R                   " [        R                   " U5      5      n[
        R                  " S%SU5      n[
        R                  " S&SU5      n[
        R                  " S'SU5      n[
        R                  " S(SU5      n[
        R                  " S)SU5      n[
        R                  " S*SU5      n[
        R                  " S+SU5      n[
        R                  " S,SU5      n[
        R                  " S-SU5      n[
        R                  " S.SU5      n[
        R                  " S/S0U5      n[
        R                  " S1S2U5      n[
        R                  " S3SU5      nUR                  5         [
        R                  " S4S5U5      n[
        R                  " S6SU5      n[
        R                  " S7SU5      n[
        R                  " S8SU5      nUR                  5       $ )9Nz<person>personzk\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@))) zh\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))zhtml.parser)featuresz
@[\w\d]+\bz[\u31c0-\u31ef]+z[\u31f0-\u31ff]+z[\u3200-\u32ff]+z[\u3300-\u33ff]+z[\u3400-\u4dbf]+z[\u4dc0-\u4dff]+z[\u4e00-\u9fff]+z|[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+-u   [`´«»“”¨]"u   [‘’]'z&quot;?z&ampz"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} z\d:\d\d\s+$z\\nz
#\d{1,3}\bz	#\d{5,}\bz
\b\d{6,}\bz0[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)z
[\"\']{2,}z[\.]{2,}z\s+\.\s+z	(?:\-|\_)r   z\b[a-zA-Z]{1,3}\d{3,15}\bz\b[a-zA-Z]+\d+[a-zA-Z]+\bz\b\d+[a-zA-Z]+\d+\bz!(worldwide\s+)?(free\s+)?shippingz(free\s)?download(\sfree)?z\bclick\b\s(?:for|on)\s\w+z9\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?z\bpage\s+\d+\bz*\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\bu   \b\d+\.?\d*[xх×]\d+\.?\d*\bz
\b\s+\:\s+z: z(\D[,\./])\bz\1 z\s+z^[\"\']([\w\W]+)[\"\']$z\1z^[\'\_,\-\:;]z[\'\_,\-\:\-\+]$z^\.\S+$)rv   ulunquote_plusr   r   resubr'   r   bad_punct_regexcompiler6   findallr   fix_texthtmlunescape)rQ   captionregex2s      r;   r   (SanaSprintImg2ImgPipeline._clean_caption  s   g,//'*--/'')&&Xw7&&z

 &&w
  -@EE &&G4 &&,b':&&,b':&&,b':&&,b':&&,b':&&,b':&&,b': && L
 &&-sG<&&c73 &&R1&&"g. &&>WM &&W5 &&g. &&G4&&r73&&G4&&LbRYZ &&g6&&dG4&&--tW=&&dG4 L)rzz&*+a/ffVS'2G--(--g 67&&5r7C&&5r7C&&/W=&&=r7K&&6GD&&6GD&&UWY[bc&&*B8&&FgV&&92wG&&w7&&&':&&g.&&3UGD&&)38&&,c7;&&R1}}r=   imager   r   c                    [        U[        R                  5      (       az  UR                  S:X  a  UR	                  S5      nUR
                  S   U:w  d  UR
                  S   U:w  a  [        R                  " XU4SSS9nU R                  R                  XUS9nOU R                  R                  XUS9nUR                  XES9nU$ )	Nr   r   r"   bilinearF)sizemodealign_corners)r   r   r)   rg   )ru   torchTensorndim	unsqueezer   FinterpolaterP   
preprocessr}   )rQ   r   r   r   r)   rg   s         r;   prepare_image'SanaSprintImg2ImgPipeline.prepare_imageE  s     eU\\**zzQ*{{1~'5;;q>U+Be5/
bgh((33EPU3VE ((33EPU3VE4r=   c                     U
b  U
R                  XS9$ UU[        U5      U R                  -  [        U5      U R                  -  4nUR                  S   U:w  ai  U R                  R                  U5      R                  nXR                  R                  R                  -  U R                  R                  R                  -  nOUnX<R                  S   :  a@  X<R                  S   -  S:X  a+  X<R                  S   -  n[        R                  " U/U-  SS9nO\X<R                  S   :  a4  X<R                  S   -  S:w  a  [        SUR                  S    SU S35      e[        R                  " U/SS9n[        U	[        5      (       a*  [!        U	5      U:w  a  [        S[!        U	5       S	U S
35      e[#        XXS9U R                  R                  R                  -  n[        R$                  " U5      U-  [        R&                  " U5      U-  -   n
U
$ )Nr   r%   r   )dimz'Cannot duplicate `image` of batch size z to z text prompts.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.)r   r)   rg   )r}   r   rI   r   rE   r{   latentrN   scaling_factorr7   
sigma_datar   catr.   ru   r   r6   r!   cossin)rQ   r   timestep
batch_sizenum_channels_latentsr   r   rg   r)   r   rA   r   image_latentsadditional_image_per_promptnoises                  r;   prepare_latents)SanaSprintImg2ImgPipeline.prepare_latents]  s    ::V:99  K4000J$///	
 ;;q>11HHOOE*11E!HHOO$B$BBT^^EZEZEeEeeM!M++A..:@S@STU@V3VZ[3[*48K8KA8N*N'!II}o8S&SYZ[M--a00ZBUBUVWBX5X\]5]9-:M:Ma:P9QQUV`Uaaop  "II}o1=Mi&&3y>Z+GA#i.AQ R&<'gi  UTW[WeWeWlWlWwWww))H%5		(8Ke8SSr=   c                     U R                   $ r   )_guidance_scalerU   s    r;   guidance_scale(SanaSprintImg2ImgPipeline.guidance_scale  s    ###r=   c                     U R                   $ r   )_attention_kwargsrU   s    r;   attention_kwargs*SanaSprintImg2ImgPipeline.attention_kwargs  s    %%%r=   c                     U R                   $ r   )_num_timestepsrU   s    r;   num_timesteps'SanaSprintImg2ImgPipeline.num_timesteps  s    """r=   c                     U R                   $ r   )
_interruptrU   s    r;   	interrupt#SanaSprintImg2ImgPipeline.interrupt  s    r=   r"   gH.!?g?g      @g333333?i   g        pilT)zGiven a user prompt, generate an 'Enhanced prompt' that provides detailed visual descriptions suitable for image generation. Evaluate the level of detail in the user prompt:z- If the prompt is simple, focus on adding specifics about colors, shapes, sizes, textures, and spatial relationships to create vivid and concrete scenes.zo- If the prompt is already detailed, refine and enhance the existing details slightly without overcomplicating.z8Here are examples of how to transform or refine prompts:z- User Prompt: A cat sleeping -> Enhanced: A small, fluffy white cat curled up in a round shape, sleeping peacefully on a warm sunny windowsill, surrounded by pots of blooming red flowers.z- User Prompt: A busy city street -> Enhanced: A bustling city street scene at dusk, featuring glowing street lamps, a diverse crowd of people in colorful clothing, and a double-decker bus passing by towering glass skyscrapers.zPlease generate only the enhanced description for the prompt below and avoid including any additional commentary or evaluations:zUser Prompt: r(   r*   r   r   r  r   r   r   output_typereturn_dictuse_resolution_binningr	  callback_on_step_endr   returnc                    [        U[        [        45      (       a  UR                  nU(       aU  U R                  R
                  R                  S:X  a  [        nO[        S5      eXnnU R                  R                  XUS9u  pU R                  UUU
UUUUUUUUS9  X`l        U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(                  b  U R(                  R+                  S	S5      OSnU R-                  X{U
UU R.                  R0                  5      n U R3                  UU	UUUUUUUS
9	u  nn[5        U R6                  UUUSUUS9u  p2[9        U R6                  S5      (       a  U R6                  R;                  S5        U R=                  X(U5      u  p2US:  a  [        SU SU S35      eUSS n!U R                  R
                  R>                  n"U RA                  U U!UU	-  U"U
U[B        RD                  UUU5
      n[B        RF                  " S/UU[B        RD                  S9n#U#RI                  UR$                  S   5      RK                  UR0                  5      n#U#U R                  R
                  RL                  -  n#U RO                  X5      n$USS n[Q        [#        U5      X R6                  RR                  -  -
  S5      n%[#        U5      U l*        U R                  R0                  n&U RW                  US9 n'[Y        U5       GHh  u  n(n)U RZ                  (       a  M  U)RI                  UR$                  S   5      n*XR6                  R
                  R\                  -  n+[B        R^                  " U*5      [B        R`                  " U*5      [B        R^                  " U*5      -   -  n,U,Rc                  SSSS5      n-U+[B        Rd                  " U-S-  SU--
  S-  -   5      -  n.U R	                  U.RK                  U&S9URK                  U&S9UU#U,SU R(                  S9S   n/SSU--  -
  U.-  SSU--  -
  SU-S-  -  -   U/-  -   [B        Rd                  " U-S-  SU--
  S-  -   5      -  n/U/Rg                  5       U R6                  R
                  R\                  -  n/U R6                  Rh                  " U/U*U40 U$DSS0D6u  nn0UbJ  0 n1U H  n2[k        5       U2   U1U2'   M     U" U U(U)U15      n3U3Rm                  SU5      nU3Rm                  SU5      nU([#        U5      S-
  :X  d)  U(S-   U%:  a0  U(S-   U R6                  RR                  -  S:X  a  U'Ro                  5         [p        (       d  GMS  [r        Rt                  " 5         GMk     SSS5        W0U R6                  R
                  R\                  -  nUS:X  a  UnOURK                  U R.                  R0                  5      n[w        [B        [y        5       [B        Rz                  5      n4[}        SS5      (       a  [B        R~                  OU4R~                  n5 U R.                  R                  XR.                  R
                  R                  -  SS9S   nU(       a  U R                  R                  UWW5      nUS:X  d  U R                  R                  UUS9nU R                  5         U(       d  U4$ [        US9$ ! , (       d  f       GNY= f! U5 a#  n6[        R                  " U6 S35         Sn6A6NSn6A6ff = f) u  
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.
    num_inference_steps (`int`, *optional*, defaults to 20):
        The number of denoising steps. More denoising steps usually lead to a higher quality image at the
        expense of slower inference.
    max_timesteps (`float`, *optional*, defaults to 1.57080):
        The maximum timestep value used in the SCM scheduler.
    intermediate_timesteps (`float`, *optional*, defaults to 1.3):
        The intermediate timestep value used in SCM scheduler (only used when num_inference_steps=2).
    timesteps (`List[int]`, *optional*):
        Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
        in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
        passed will be used. Must be in descending order.
    guidance_scale (`float`, *optional*, defaults to 4.5):
        Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
        `guidance_scale` is defined as `w` of equation 2. of [Imagen
        Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
        1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
        usually at the expense of lower image quality.
    num_images_per_prompt (`int`, *optional*, defaults to 1):
        The number of images to generate per prompt.
    height (`int`, *optional*, defaults to self.unet.config.sample_size):
        The height in pixels of the generated image.
    width (`int`, *optional*, defaults to self.unet.config.sample_size):
        The width in pixels of the generated image.
    eta (`float`, *optional*, defaults to 0.0):
        Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
        [`schedulers.DDIMScheduler`], will be ignored for others.
    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 ge 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_attention_mask (`torch.Tensor`, *optional*): Pre-generated attention mask for text embeddings.
    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.IFPipelineOutput`] instead of a plain tuple.
    attention_kwargs:
        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).
    clean_caption (`bool`, *optional*, defaults to `True`):
        Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
        be installed. If the dependencies are not installed, the embeddings will be created from the raw
        prompt.
    use_resolution_binning (`bool` defaults to `True`):
        If set to `True`, the requested height and width are first mapped to the closest resolutions using
        `ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
        the requested resolution. Useful for generating non-square images.
    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 `300`):
        Maximum sequence length to use with the `prompt`.
    complex_human_instruction (`List[str]`, *optional*):
        Instructions for complex human attention:
        https://github.com/NVlabs/Sana/blob/main/configs/sana_app_config/Sana_1600M_app.yaml#L55.

Examples:

Returns:
    [`~pipelines.sana.pipeline_output.SanaPipelineOutput`] or `tuple`:
        If `return_dict` is `True`, [`~pipelines.sana.pipeline_output.SanaPipelineOutput`] is returned,
        otherwise a `tuple` is returned where the first element is a list with the generated images
rH   zInvalid sample size)ratios)rf   r   r   r   r(   r*   r   r   r   rB   r   FNr%   r   scale)r   r)   rB   r   rh   ri   rj   r   )r+   r   r   r   z?After adjusting the num_inference_steps by strength parameter: z!, the number of pipelinesteps is z4 which is < 1 and not appropriate for this pipeline.r   r   )totalr"   )rg   )encoder_hidden_statesencoder_attention_maskguidancer   r  r	  r  rA   rB   r   z>=z2.5.0)r  z. 
Try to use VAE tiling for large images. For example: 
pipe.vae.enable_tiling(tile_sample_min_width=512, tile_sample_min_height=512))r  )images)Hru   r   r   tensor_inputsrF   rN   sample_sizer$   r.   rP   classify_height_width_binr   r  r  r  rv   r   r6   r   r   r	  getr   rE   rg   r   r<   r7   rM   r   r   in_channelsr  r   float32fullexpandr}   guidance_embeds_scaler   r   r   r  progress_bar	enumerater  r   r   r   r   sqrtfloatr   localspopupdateXLA_AVAILABLExm	mark_steprw   r   cudar    OutOfMemoryErrordecoder   warningswarnresize_and_crop_tensorpostprocessmaybe_free_model_hooksr&   )7rQ   rf   r(   r*   r   r   r  r   r   r   r   r   r   r   rA   rB   r   r  r  rh   r  r	  r  r   ri   rj   aspect_ratio_binorig_height
orig_widthr   r)   r   
init_imagelatent_timesteplatent_channelsr  r   num_warmup_stepstransformer_dtyper*  ir   r   latents_model_inputscm_timestepscm_timestep_expandedlatent_model_input
noise_preddenoisedcallback_kwargsr   callback_outputstorch_accelerator_module	oom_errores7                                                          r;   __call__"SanaSprintImg2ImgPipeline.__call__  sO   v *-=?U,VWW1E1S1S. "&&22b8#8  !677&,K 00JJ6aqJrMF 3'#9/Q'"7 	 	
  .!1 *VS"9"9JJvt$<$<VJ&,,Q/J''AEAVAVAbT**..w=hl
 ''ffdhhnnU
 "7'"7' 3&?!  

	
! *<NN'#9*
&	 4>>#455NN**1-)-););<O[a)b&	"QRZQ[ \/00df  $BQ- **11==&&..MM
  ::qc>&V??7==#34778K8KLd..55KKK !::9J crN	s9~0CnnFZFZ0ZZ\]^!)n ,,22%89\!),1>> 88GMM!$45&-0E0E0P0P&P#$yy2eii6IEIIV^L_6_`(4(9(9"aA(F%%85::)1,4I0Ia/OO< &"
 "--&))0A)B*7*:*:AR*:*S+@%) %%)%:%: .  
 2226HH1444q;PRS;S7SSWaabJJ4a71?T;TYZ:ZZ[\
 (--/$..2G2G2R2RR
 %)NN$7$7'%5F%TY%! (3&(O?-3Xa[* @';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') =LLNg - :l T^^22===("Ejj0G'.ujlEJJ'O$ $D'22 &&->> 
((//2P2P(P^cdefg &,,CCE:Wbch&((44U4TE 	##%8O!//k :9F  c d e s+   >I\	\	%=\ 	
\]!\??])r  r  r  r   r  rP   rI   )Fre   N)r%   NNNFre   NN)NNN)Fr   );__name__
__module____qualname____firstlineno____doc__r   r   r   model_cpu_offload_seqr   r	   r   r   r
   r   r   r   rK   rV   r[   r_   rc   rv   r   r   r)   rg   boolr   r   r   r   r-  r   r   r   r   ry   r   r   r   r  propertyr  r	  r  r  no_gradr   EXAMPLE_DOC_STRING	Generatorr   r   r   r&   r   rP  __static_attributes____classcell__)r5   s   @r;   r?   r?      s   
 jj 	HIO =(/:\);;<\ ,\ 	\
 ,\ /\,"#!" $#&9=84c49n%84 84 {{	84
 84 !84 $,DI#684| &')-048<##&9=&*S4c49n%S4  #S4 &	S4
  -S4  (5S4 S4 !S4 $,DI#6S4 UOS4l!$	8* ,0"4on*2pd!  	
  {{2 sw&P $ $ & & # #   ]]_12 )-#$#&(+ #$(/0MQ*.048<%* #'+59KO9B#&	0
5~0c49n%~0 !~0 9	~0
 ~0 !&~0 ~0 "~0 ~0  (}~0 ~0 ~0 ~0 E%//43H"HIJ~0 %,,'~0   -!~0"  (5#~0$ c]%~0& '~0( )~0* !%+~0, #4S>2-~0. 'xc40@$0F'GH/~00 -1I1~02 !3~04 $(95~0H 
!5(	)I~0 3 ~0r=   r?   )NNNN)Kr   r0   r   urllib.parseparser   r7  typingr   r   r   r   r   r   r	   r   torch.nn.functionalnn
functionalr   transformersr
   r   r   	callbacksr   r   rP   r   r   loadersr   modelsr   r   
schedulersr   utilsr   r   r   r   r   r   r   r   r   utils.torch_utilsr   r    r!   pipeline_utilsr#   "pixart_alpha.pipeline_pixart_alphar$   pipeline_outputr&   torch_xla.core.xla_modelcore	xla_modelr2  r1  
get_loggerrR  r   r   r'   r   r[  r   rv   r)   r-  r<   r?   r-   r=   r;   <module>rs     s     	   D D D    R R A G * ; 5
 
 
 L K . F / ))MM			H	%! 4 *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vC0 13F C0r=   