
    +h                    F   S SK r S SKJrJrJrJrJrJr  S SKr	S SK
rS SKrS SKJrJrJrJrJrJr  SSKJrJr  SSKJrJrJr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'  SS
K(J)r)  SSK*J+r+  SSK,J-r-  \#" 5       (       a  S SK.J/s  J0r1  Sr2OSr2\$Rf                  " \45      r5Sr6/ SQr7    S#S\8S\8S\9S\94S jjr:    S$S\\8   S\\\;\Rx                  4      S\\\8      S\\\9      4S jjr= S%S\R|                  S\\R~                     S\;4S  jjr@ " S! S"\+\\\\5      rAg)&    N)AnyCallableDictListOptionalUnion)CLIPImageProcessorCLIPTextModelCLIPTokenizerCLIPVisionModelWithProjectionT5EncoderModelT5TokenizerFast   )PipelineImageInputVaeImageProcessor)FluxIPAdapterMixinFluxLoraLoaderMixinFromSingleFileMixinTextualInversionLoaderMixin)AutoencoderKLFluxTransformer2DModel)FlowMatchEulerDiscreteScheduler)USE_PEFT_BACKENDis_torch_xla_availableloggingreplace_example_docstringscale_lora_layersunscale_lora_layers)randn_tensor   )DiffusionPipeline   )FluxPipelineOutputTFa$	  
    Examples:
        # Inpainting with text only
        ```py
        >>> import torch
        >>> from diffusers import FluxKontextInpaintPipeline
        >>> from diffusers.utils import load_image

        >>> prompt = "Change the yellow dinosaur to green one"
        >>> img_url = (
        ...     "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/dinosaur_input.jpeg?raw=true"
        ... )
        >>> mask_url = (
        ...     "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/dinosaur_mask.png?raw=true"
        ... )

        >>> source = load_image(img_url)
        >>> mask = load_image(mask_url)

        >>> pipe = FluxKontextInpaintPipeline.from_pretrained(
        ...     "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")

        >>> image = pipe(prompt=prompt, image=source, mask_image=mask, strength=1.0).images[0]
        >>> image.save("kontext_inpainting_normal.png")
        ```

        # Inpainting with image conditioning
        ```py
        >>> import torch
        >>> from diffusers import FluxKontextInpaintPipeline
        >>> from diffusers.utils import load_image

        >>> pipe = FluxKontextInpaintPipeline.from_pretrained(
        ...     "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")

        >>> prompt = "Replace this ball"
        >>> img_url = "https://images.pexels.com/photos/39362/the-ball-stadion-football-the-pitch-39362.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"
        >>> mask_url = (
        ...     "https://github.com/ZenAI-Vietnam/Flux-Kontext-pipelines/blob/main/assets/ball_mask.png?raw=true"
        ... )
        >>> image_reference_url = (
        ...     "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTah3x6OL_ECMBaZ5ZlJJhNsyC-OSMLWAI-xw&s"
        ... )

        >>> source = load_image(img_url)
        >>> mask = load_image(mask_url)
        >>> image_reference = load_image(image_reference_url)

        >>> mask = pipe.mask_processor.blur(mask, blur_factor=12)
        >>> image = pipe(
        ...     prompt=prompt, image=source, mask_image=mask, image_reference=image_reference, strength=1.0
        ... ).images[0]
        >>> image.save("kontext_inpainting_ref.png")
        ```
))     )    )    )  p  )   0  )@    )p    )  P  )   r4   )r3   r2   )r1   r0   )r/   r.   )r-   r,   )r+   r*   )r)   r(   )r'   r&   )r%   r$   base_seq_lenmax_seq_len
base_shift	max_shiftc                 4    XC-
  X!-
  -  nX5U-  -
  nX-  U-   nU$ N )image_seq_lenr5   r6   r7   r8   mbmus           p/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/pipelines/flux/pipeline_flux_kontext_inpaint.pycalculate_shiftrA      s3     
	K$>?A%%A		Q	BI    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 valuesrE   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)rE   rD   rF   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)rF   rD   rD   r;   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__rE   len)	schedulerrC   rD   rE   rF   kwargsaccepts_timestepsaccept_sigmass           r@   retrieve_timestepsrU      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''	))rB   encoder_output	generatorsample_modec                    [        U S5      (       a!  US:X  a  U R                  R                  U5      $ [        U S5      (       a   US:X  a  U R                  R                  5       $ [        U S5      (       a  U R                  $ [        S5      e)Nlatent_distsampleargmaxlatentsz3Could not access latents of provided encoder_output)hasattrrZ   r[   moder]   AttributeError)rV   rW   rX   s      r@   retrieve_latentsra      s}     ~}--+2I))00;;		/	/K84K))..00		+	+%%%RSSrB   c            G         ^  \ rS rSrSrSrSS/rSS/r  SWS	\S
\	S\
S\S\S\S\S\S\4U 4S jjjr     SXS\\\\   4   S\S\S\\R0                     S\\R2                     4
S jjr  SYS\\\\   4   S\S\\R0                     4S jjr       SZS\\\\   4   S\\\\\   4      S\\R0                     S\S\\R8                     S\\R8                     S\S\\   4S jjrS rS r S  r!         S[S! jr"\#S" 5       r$\#S# 5       r%\#S$ 5       r&S%\RN                  S&\RP                  4S' jr)S( r*S) r+S* r,S+ r-   S\S%\\RN                     S,\S-\S.\S/\S0\S\R2                  S\R0                  S&\\\RP                  \\RP                     4      S\\RN                     S1\\RN                     4S2 jjr.S3 r/\0S4 5       r1\0S5 5       r2\0S6 5       r3\0S7 5       r4\0S8 5       r5\Rl                  " 5       \7" \85      SSSSSSSS9SSS9SS:SS;SSSSSSSSSSSS<S=SSS/SS>S=4"S%\\9   S1\\9   S?\9S\\\\   4   S\\\\\   4      S@\\\\   4   SA\\\\\   4      SB\S/\\   S0\\   SC\SD\\   SE\SF\\\      SG\S\\   S&\\\RP                  \\RP                     4      S\\R8                     S\\R8                     S\\R8                     SH\\9   SI\\\RN                        SJ\\9   SK\\\RN                        SL\\R8                     SM\\R8                     SN\\   SO\:SP\\;\\<4      SQ\\=\\\;/S4      SR\\   S\SS\ST\:4DSU jj5       5       r>SVr?U =r@$ )]FluxKontextInpaintPipeline   a  
The Flux Kontext pipeline for text-to-image generation.

Reference: https://blackforestlabs.ai/announcing-black-forest-labs/

Args:
    transformer ([`FluxTransformer2DModel`]):
        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 ([`AutoencoderKL`]):
        Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
    text_encoder ([`CLIPTextModel`]):
        [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
        the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
    text_encoder_2 ([`T5EncoderModel`]):
        [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
        the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
    tokenizer (`CLIPTokenizer`):
        Tokenizer of class
        [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
    tokenizer_2 (`T5TokenizerFast`):
        Second Tokenizer of class
        [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
z=text_encoder->text_encoder_2->image_encoder->transformer->vaeimage_encoderfeature_extractorr]   prompt_embedsNrQ   vaetext_encoder	tokenizertext_encoder_2tokenizer_2transformerc
                 ^  > [         T
U ]  5         U R                  UUUUUUUUU	S9	  [        U SS 5      (       a/  S[	        U R
                  R                  R                  5      S-
  -  OSU l        [        U SS 5      (       a   U R
                  R                  R                  OSU l	        [        U R                  S-  S9U l        [        U R                  S-  U R                  SS	S	S
9U l        [        U S5      (       a#  U R                  b  U R                  R                  OSU l        SU l        g )N)	rh   ri   rk   rj   rl   rm   rQ   re   rf   rh   r    r"         )vae_scale_factorFT)rq   vae_latent_channelsdo_normalizedo_binarizedo_convert_grayscalerj   M      )super__init__register_modulesgetattrrP   rh   configblock_out_channelsrq   latent_channelsr   image_processormask_processorr^   rj   model_max_lengthtokenizer_max_lengthdefault_sample_size)selfrQ   rh   ri   rj   rk   rl   rm   re   rf   rO   s             r@   ry   #FluxKontextInpaintPipeline.__init__   s(    	%)##'/ 	 
	
 W^^bdikoVpVpc$((//*L*L&MPQ&Q Rvw CJ$PUW[B\B\txx>>bd0$BWBWZ[B[\/!22Q6 $ 4 4!%
 07t[/I/IdnnNhDNN++np 	! $' rB   r"      promptnum_images_per_promptmax_sequence_lengthrD   dtypec           
         U=(       d    U R                   nU=(       d    U R                  R                  n[        U[        5      (       a  U/OUn[        U5      n[        U [        5      (       a  U R                  XR                  5      nU R                  USUSSSSS9nUR                  nU R                  USSS9R                  n	U	R                  S   UR                  S   :  ag  [        R                  " X5      (       dL  U R                  R                  U	S S 2U R                  S	-
  S24   5      n
[        R!                  S
U SU
 35        U R#                  UR%                  U5      SS9S   nU R"                  R                  nUR%                  XTS9nUR                  u  pnUR'                  S	US	5      nUR)                  Xb-  US5      nU$ )N
max_lengthTFpt)paddingr   
truncationreturn_lengthreturn_overflowing_tokensreturn_tensorslongestr   r   r"   zXThe following part of your input was truncated because `max_sequence_length` is set to  	 tokens: output_hidden_statesr   r   rD   )_execution_deviceri   r   
isinstancestrrP   r   maybe_convert_promptrl   	input_idsshapetorchequalbatch_decoder   loggerwarningrk   torepeatview)r   r   r   r   rD   r   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textrg   _seq_lens                 r@   _get_t5_prompt_embeds0FluxKontextInpaintPipeline._get_t5_prompt_embeds(  s    14110**00'44&&[
d788..v7G7GHF&& *&+ ' 
 %..**69UY*Zdd  $(<(<R(@@UcIuIu++88DLeLehiLilnLnIn9opLNN'(	,A
 ++N,=,=f,E\a+bcde##))%((u(D%++A &,,Q0EqI%**:+MwXZ[rB   c           
      r   U=(       d    U R                   n[        U[        5      (       a  U/OUn[        U5      n[        U [        5      (       a  U R                  XR                  5      nU R                  USU R                  SSSSS9nUR                  nU R                  USSS9R                  nUR                  S   UR                  S   :  aq  [        R                  " Xg5      (       dV  U R                  R                  US S 2U R                  S	-
  S24   5      n[        R                  S
U R                   SU 35        U R                  UR!                  U5      SS9n	U	R"                  n	U	R!                  U R                  R$                  US9n	U	R'                  S	U5      n	U	R)                  XB-  S5      n	U	$ )Nr   TFr   )r   r   r   r   r   r   r   r   r   r"   z\The following part of your input was truncated because CLIP can only handle sequences up to r   r   r   )r   r   r   rP   r   r   rj   r   r   r   r   r   r   r   r   ri   r   pooler_outputr   r   r   )
r   r   r   rD   r   r   r   r   r   rg   s
             r@   _get_clip_prompt_embeds2FluxKontextInpaintPipeline._get_clip_prompt_embedsZ  s    1411'44&&[
d788..v~~FFnn 00&+ % 
 %....SW.Xbb  $(<(<R(@@UcIuIu>>66q$JcJcfgJgjlJlGl7mnLNN--.i~G )).*;*;F*CZ_)` &33%((t/@/@/F/Fv(V &,,Q0EF%**:+MrRrB   prompt_2pooled_prompt_embeds
lora_scalec	                    U=(       d    U R                   nUbw  [        U [        5      (       ab  Xl        U R                  b!  [
        (       a  [        U R                  U5        U R                  b!  [
        (       a  [        U R                  U5        [        U[        5      (       a  U/OUnUcH  U=(       d    Un[        U[        5      (       a  U/OUnU R                  UUUS9nU R                  UUUUS9nU R                  b6  [        U [        5      (       a!  [
        (       a  [        U R                  U5        U R                  b6  [        U [        5      (       a!  [
        (       a  [        U R                  U5        U R                  b  U R                  R                  OU R                  R                  n	[        R                  " UR                   S   S5      R#                  X9S9n
XVU
4$ )a?  

Args:
    prompt (`str` or `List[str]`, *optional*):
        prompt to be encoded
    prompt_2 (`str` or `List[str]`, *optional*):
        The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
        used in all text-encoders
    device: (`torch.device`):
        torch device
    num_images_per_prompt (`int`):
        number of images that should be generated per prompt
    prompt_embeds (`torch.FloatTensor`, *optional*):
        Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
        provided, text embeddings will be generated from `prompt` input argument.
    pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
        Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
        If not provided, pooled text embeddings will be generated from `prompt` input argument.
    lora_scale (`float`, *optional*):
        A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
)r   rD   r   )r   r   r   rD   r"   r   rD   r   )r   r   r   _lora_scaleri   r   r   rk   r   r   r   r   r   rm   r   zerosr   r   )r   r   r   rD   r   rg   r   r   r   r   text_idss              r@   encode_prompt(FluxKontextInpaintPipeline.encode_prompt  s   @ 1411 !j7J&K&K)   ,1A1A!$"3"3Z@"".3C3C!$"5"5zB'44&& )6H%/#%>%>zHH $(#?#?&; $@ $ 
 !66&;$7	 7 M ($ 3449I9I#D$5$5zB*$ 3449I9I#D$7$7D+/+<+<+H!!''dN^N^NdNd;;}2215q9<<F<XH<<rB   c                 F   [        U R                  R                  5       5      R                  n[	        U[
        R                  5      (       d  U R                  USS9R                  nUR                  X$S9nU R                  U5      R                  nUR                  USS9nU$ )Nr   )r   r   r   dim)nextre   rM   r   r   r   Tensorrf   pixel_valuesr   image_embedsrepeat_interleave)r   imagerD   r   r   r   s         r@   encode_image'FluxKontextInpaintPipeline.encode_image  s    T''2245;;%..**5*FSSE4))%0==#556KQR5SrB   c                 ,   / nUc  [        U[        5      (       d  U/n[        U5      U R                  R                  R
                  :w  a9  [        S[        U5       SU R                  R                  R
                   S35      eU H-  nU R                  XcS5      nUR                  US S S 24   5        M/     O[        U[        5      (       d  U/n[        U5      U R                  R                  R
                  :w  a9  [        S[        U5       SU R                  R                  R
                   S35      eU H  nUR                  U5        M     / nU H<  n[        R                  " U/U-  SS9nUR                  US	9nUR                  U5        M>     U$ )
NzK`ip_adapter_image` must have same length as the number of IP Adapters. Got z images and z IP Adapters.r"   zR`ip_adapter_image_embeds` must have same length as the number of IP Adapters. Got z image embeds and r   r   )rD   )r   listrP   rm   encoder_hid_projnum_ip_adaptersrH   r   appendr   catr   )r   ip_adapter_imageip_adapter_image_embedsrD   r   r   single_ip_adapter_imagesingle_image_embedss           r@   prepare_ip_adapter_image_embeds:FluxKontextInpaintPipeline.prepare_ip_adapter_image_embeds  s    "*.55$4#5 #$(8(8(I(I(Y(YY abefvbwax  yE  FJ  FV  FV  Fg  Fg  Fw  Fw  Ex  xE  F  ,<'&*&7&78OYZ&[###$7a$@A ,< 5t<<+B*C'*+t/?/?/P/P/`/`` hil  nE  jF  iG  GY  Z^  Zj  Zj  Z{  Z{  ZK  ZK  YL  LY  Z  (?###$78 (? #%#/"'))-@,ADY,Y_`"a"5"8"8"8"G#**+>? $0
 '&rB   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maxrQ   rE   orderr^   r   )r   rC   strengthrD   init_timestept_startrE   s          r@   get_timesteps(FluxKontextInpaintPipeline.get_timesteps  s    /:<OPc-=qABNN,,W~~7K7K-K-MN	4>>#455NN**7^^5I5I+IJ777rB   c           
        ^  US:  d  US:  a  [        SU 35      e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bX  [	        U 4S	 jU 5       5      (       d>  [        S
T R
                   SU Vs/ s H  nUT R
                  ;  d  M  UPM     sn 35      eUb  Ub  [        SU SU S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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b  [        SU
 SU S35      eUbC  Ub@  UR                  UR                  :w  a&  [        SUR                   SUR                   S35      eUb  Uc  [        S5      eUb  Uc  [        S5      eUb  [        U[        R                  R                  5      (       d  [        S[        U5       S35      e[        U[        R                  R                  5      (       d  [        S[        U5       S35      eUS:w  a  [        SU S35      eUb  US:  a  [        S U 35      eg g s  snf )!Nr   r"   z2The value of strength should in [0.0, 1.0] but is r    z-`height` and `width` have to be divisible by z	 but are  and z(. Dimensions will be resized accordinglyc              3   @   >#    U  H  oTR                   ;   v   M     g 7fr:   )_callback_tensor_inputs).0kr   s     r@   	<genexpr>:FluxKontextInpaintPipeline.check_inputs.<locals>.<genexpr>0  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.z Cannot forward both `prompt_2`: 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 z4`prompt_2` has to be of type `str` or `list` but is z'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: z)Cannot forward both `negative_prompt_2`: zu`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but got: `prompt_embeds` z != `negative_prompt_embeds` .zIf `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`.zIf `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`.zJThe image should be a PIL image when inpainting mask crop, but is of type zOThe mask image should be a PIL image when inpainting mask crop, but is of type pilz@The output type should be PIL when inpainting mask crop, but is r   z8`max_sequence_length` cannot be greater than 512 but is )rH   rq   r   r   allr   r   r   r   typer   PILImage)r   r   r   r   
mask_imager   heightwidthoutput_typenegative_promptnegative_prompt_2rg   negative_prompt_embedsr   negative_pooled_prompt_embeds"callback_on_step_end_tensor_inputspadding_mask_cropr   r   s   `                  r@   check_inputs'FluxKontextInpaintPipeline.check_inputs  s   ( a<8a<QRZQ[\]]T**Q./14AVAVYZAZ8[_`8`NN?@U@UXY@Y?ZZcdjckkpqvpw  x`  a .9# F
7YF
 C
 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  !m&?28*<RS`Ra b0 0  ^ 5w  FC)@)@TZ\`IaIaQRVW]R^Q_`aa!:h+D+DZX`bfMgMgSTXYaTbScdee&+A+M9/9J K*++]_  */E/Q;<M;N O*++]_ 
 $)?)K""&<&B&BB --:-@-@,A B.445Q8  $)=)E U  "-2O2W y  (eSYY__55 `aefkal`mmno  j#))//:: Z(),  e# #cdocppq!rss*/BS/HWXkWlmnn 0I* pHs   (K# K#c                 ,   [         R                  " XS5      nUS   [         R                  " U5      S S 2S 4   -   US'   US   [         R                  " U5      S S S 24   -   US'   UR                  u  pgnUR	                  Xg-  U5      nUR                  X4S9$ )Nr   ).r"   ).r    r   )r   r   aranger   reshaper   )	r   r   r   rD   r   latent_image_idslatent_image_id_heightlatent_image_id_widthlatent_image_id_channelss	            r@   _prepare_latent_image_ids4FluxKontextInpaintPipeline._prepare_latent_image_idsv  s     !;;va8#3F#;ell6>RSTVZSZ>[#[ #3F#;ell5>QRVXYRY>Z#Z RbRhRhO7O+33":<T
  ""&">>rB   c                     U R                  XUS-  SUS-  S5      n U R                  SSSSSS5      n U R                  XS-  US-  -  US-  5      n U $ )Nr    r      r"   r      )r   permuter   )r]   r   num_channels_latentsr   r   s        r@   _pack_latents(FluxKontextInpaintPipeline._pack_latents  sg     ,,z1aQVZ[Q[]^_//!Q1a3//*{uz.JL`cdLderB   c                    U R                   u  pEnS[        U5      US-  -  -  nS[        U5      US-  -  -  nU R                  XAS-  US-  US-  SS5      n U R                  SSSSSS5      n U R	                  XFS-  X5      n U $ )Nr    r  r   r   r"   r  )r   r   r   r  r   )r]   r   r   rq   r   num_patcheschannelss          r@   _unpack_latents*FluxKontextInpaintPipeline._unpack_latents  s     -4MM)
 c&k&6&:;<SZ$4q$89:,,zQ;
HPQMSTVWX//!Q1a3//*5.A6QrB   r   rW   c                    [        U[        5      (       ag  [        UR                  S   5       Vs/ s H.  n[	        U R
                  R                  XUS-    5      X#   SS9PM0     nn[        R                  " USS9nO$[	        U R
                  R                  U5      USS9nX@R
                  R                  R                  -
  U R
                  R                  R                  -  nU$ s  snf )Nr   r"   r\   )rW   rX   r   )r   r   ranger   ra   rh   encoder   r   r|   shift_factorscaling_factor)r   r   rW   iimage_latentss        r@   _encode_vae_image,FluxKontextInpaintPipeline._encode_vae_image  s    i&& u{{1~..A !1q51A!Bilhpq.   "IIm;M,TXX__U-CyfnoM&)E)EEIgIggs   5C&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)rh   enable_slicingr   s    r@   enable_vae_slicing-FluxKontextInpaintPipeline.enable_vae_slicing      
 	!rB   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)rh   disable_slicingr  s    r@   disable_vae_slicing.FluxKontextInpaintPipeline.disable_vae_slicing  s    
 	  "rB   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)rh   enable_tilingr  s    r@   enable_vae_tiling,FluxKontextInpaintPipeline.enable_vae_tiling  s     	 rB   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)rh   disable_tilingr  s    r@   disable_vae_tiling-FluxKontextInpaintPipeline.disable_vae_tiling  r  rB   timestepr   r  r   r   image_referencec                    [        U	[        5      (       a*  [        U	5      U:w  a  [        S[        U	5       SU S35      eS[	        U5      U R
                  S-  -  -  nS[	        U5      U R
                  S-  -  -  nX4XV4nS =pUb  UR                  XS9nUR                  S   U R                  :w  a  U R                  XS9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S =nnUb  UR                  XS9nUR                  S   U R                  :w  a  U R                  XS9nOUnUUR                  S   :  aB  UUR                  S   -  S:X  a,  UUR                  S   -  n[        R                  " U/U-  SS	9nO^UUR                  S   :  a5  UUR                  S   -  S:w  a  [        SUR                  S    SU S35      e[        R                  " U/SS	9nU R                  X5S-  US-  X5      nU
c'  [        XXS9nU R                  R                  XU5      n
OU
R                  XS9nUn
UR                  SS  u  nnU R!                  XUUU5      nU R                  UUS-  US-  X5      nSUS'   UbF  UR                  SS  u  nnU R!                  UUUUU5      nU R                  UUS-  US-  X5      nSUS'   U R!                  UX4XV5      nU R!                  XXEU5      n
XUUUUU4$ )Nz/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.r    r   r"   )r   rW   r   r   z'Cannot duplicate `image` of batch size z to z text prompts.z1Cannot duplicate `image_reference` of batch size )rW   rD   r   ).r   )r   r   rP   rH   r   rq   r   r   r~   r  r   r   r  r   rQ   scale_noiser	  )r   r   r+  r   r  r   r   r   rD   rW   r]   r,  r   r  	image_idsadditional_image_per_promptimage_reference_latentsimage_reference_ids
latent_idsnoiseimage_latent_heightimage_latent_widthimage_reference_latent_heightimage_reference_latent_widths                           r@   prepare_latents*FluxKontextInpaintPipeline.prepare_latents  sU    i&&3y>Z+GA#i.AQ R&<'gi  c&kd&;&;a&?@ASZD$9$9A$=>?6A %)(HHFH8E{{1~!5!55 $ 6 6U 6 X %//22zDWDWXYDZ7Z^_7_.8<O<OPQ<R.R+ %		=/<W*W]^ _11!44FYFYZ[F\9\`a9a =m>Q>QRS>T=UUYZdYeest  !&		=/q A 9=<"5&-000LO$$Q'4+?+??*.*@*@*@*l'*9'399!<<NeNkNklmNnAnrsAs.8<S<Y<YZ[<\.\+*/))5L4MPk4kqr*s'5;;A>>:PgPmPmnoPpCptuCu GH_HeHefgHhGiimnxmy  zH  I  +0))5L4MST*U'33J!UVWZY_g
? FXEnn00%PGJJfJ:EG2?2E2Eab2I//**';=PRd
 22+q02D2I6
	 	&".JaJgJghihjJkG)+G&*&8&8'$-,'# #'"@"@9Q>@\`a@aci# +,'""5*FZ$$W:NX]^'>
IWjlqqqrB   c                 L   S[        U5      U R                  S-  -  -  nS[        U5      U R                  S-  -  -  n[        R                  R                  R                  XU4S9nUR                  XS9nX5-  nUR                  XS9nUR                  S   S:X  a  UnOf[        U R                  R                  U5      U
S9nXR                  R                  R                  -
  U R                  R                  R                  -  nUR                  S   U:  aW  X1R                  S   -  S:X  d  [        SU S	UR                  S    S
35      eUR                  X1R                  S   -  SSS5      nUR                  S   U:  aW  X;R                  S   -  S:X  d  [        SU S	UR                  S    S35      eUR                  X;R                  S   -  SSS5      nUR                  XS9nU R!                  UUUUU5      nU R!                  UR                  SUSS5      UUUU5      nX4$ )Nr    )sizer   r"   rp   )rW   r   zvThe passed mask and the required batch size don't match. Masks are supposed to be duplicated to a total batch size of z, but zo masks were passed. Make sure the number of masks that you pass is divisible by the total requested batch size.zyThe passed images and the required batch size don't match. Images are supposed to be duplicated to a total batch size of zq images were passed. Make sure the number of images that you pass is divisible by the total requested batch size.)r   rq   r   nn
functionalinterpolater   r   ra   rh   r  r|   r  r  rH   r   r	  )r   maskmasked_imager   r  r   r   r   r   rD   rW   masked_image_latentss               r@   prepare_mask_latents/FluxKontextInpaintPipeline.prepare_mask_latents6  sd    c&kd&;&;a&?@ASZD$9$9A$=>? xx""..t5/.Jwwfw27
#fBa B&#/ #3DHHOOL4Q]f#g  %xx'C'CC..$/ 
 ::a=:%

1-2 ..8\

1 O^^ 
 ;;zZZ]:Aq!DD%%a(:5 : :1 ==B 11;FCWC]C]^_C`Ba btt 
 $8#>#>zMgMghiMj?jlmoprs#t   466f6R#11   
 !!KK/A6 
 ))rB   c                     U R                   $ r:   )_guidance_scaler  s    r@   guidance_scale)FluxKontextInpaintPipeline.guidance_scale  s    ###rB   c                     U R                   $ r:   )_joint_attention_kwargsr  s    r@   joint_attention_kwargs1FluxKontextInpaintPipeline.joint_attention_kwargs  s    +++rB   c                     U R                   $ r:   )_num_timestepsr  s    r@   num_timesteps(FluxKontextInpaintPipeline.num_timesteps  s    """rB   c                     U R                   $ r:   )_current_timestepr  s    r@   current_timestep+FluxKontextInpaintPipeline.current_timestep  s    %%%rB   c                     U R                   $ r:   )
_interruptr  s    r@   	interrupt$FluxKontextInpaintPipeline.interrupt  s    rB         ?   g      @r   Ti   r   r   r   true_cfg_scaler   r   rC   rF   rG  r   r   negative_ip_adapter_image negative_ip_adapter_image_embedsr   r   r   return_dictrK  callback_on_step_endr   max_area_auto_resizec#                   ^W U	=(       d    U R                   U R                  -  n	U
=(       d    U R                   U R                  -  n
Xn$n#X-  mW[        U!TW-  S-  5      n
[        U!TW-  S-  5      n	U R                  S-  n%U
U%-  U%-  n
U	U%-  U%-  n	U	U#:w  d  U
U$:w  a  [        R	                  SU	 SU
 S35        U R                  UUUUUU	U
UUUUUUUUUU S9  Xl        UU l        SU l        SU l	        UGbt  [        U[        R                  5      (       a   UR                  S	5      U R                  :X  Gd5  [        U[        5      (       aJ  [        US
   [        R                  5      (       a(  US
   R                   S:X  a  [        R"                  " US
S9n[        U[        5      (       a  US
   OUn&U R$                  R'                  U&5      u  n'n(U(U'-  mWU"(       a  [)        UW4S j[*         5       5      u  n)n(n'U(U%-  U%-  n(U'U%-  U%-  n'U R$                  R-                  UU'U(5      nU(n
U'n	Ub  U R.                  R1                  X:XS9n*Sn+OSn*Sn+U R$                  R3                  UU'U(U*U+S9nO[5        S5      eUR7                  [        R8                  S9n,UGbL  [        U[        R                  5      (       a   UR                  S	5      U R                  :X  Gd  [        U[        5      (       aJ  [        US
   [        R                  5      (       a(  US
   R                   S:X  a  [        R"                  " US
S9n[        U[        5      (       a  US
   OUn-U R$                  R'                  U-5      u  n.n/U/U.-  mWU"(       a  [)        UW4S j[*         5       5      u  n)n/n.U/U%-  U%-  n/U.U%-  U%-  n.U R$                  R-                  UU.U/5      nU R$                  R3                  UU.U/U*U+S9nOSnUb  [        U[:        5      (       a  S	n0O3Ub!  [        U[        5      (       a  [=        U5      n0OUR>                  S
   n0U R@                  n1U RB                  b  U RB                  RE                  SS5      OSn2USL=(       d    USL=(       a    USLn3US	:  =(       a    U3n4U RG                  UUUUU1UU U2S9u  nnn5U4(       a  U RG                  UUUUU1UU U2S9u  nnn6Uc  [H        RJ                  " SS	U-  U5      OUn[M        U	5      U R                  -  S-  [M        U
5      U R                  -  S-  -  n7[O        U7U RP                  RR                  RE                  SS5      U RP                  RR                  RE                  SS5      U RP                  RR                  RE                  SS5      U RP                  RR                  RE                  SS5      5      n8[U        U RP                  UU1UU8S9u  n9nU RW                  XU15      u  n9nUS	:  a  [5        S U S!U S"35      eU9SS	 RY                  U0U-  5      n:[[        [=        U95      XRP                  R\                  -  -
  S
5      n;[=        U95      U l/        U R`                  RR                  Rb                  S-  n<U Re                  U,U:U0U-  U<U	U
URf                  U1UUU5      u  nn=n>n?n@nAnBUAb  [        R"                  " U?WA/S
S9n?OW@b  [        R"                  " U?W@/S
S9n?U R.                  R3                  X9U
U+U*S#9nCU,UCS:  -  nDU Ri                  UCUDU0U<UU	U
URf                  U1U5
      u  nEn)U R`                  RR                  Rj                  (       aE  [        Rl                  " S	/UU1[        R8                  S$9nFUFRo                  UR>                  S
   5      nFOSnFUc  UbP  UcM  UcJ  [H        Rp                  " XS%4[H        Rr                  S9nU/U R`                  Rt                  Rv                  -  nOUUcR  UcO  Uc  UbI  [H        Rp                  " XS%4[H        Rr                  S9nU/U R`                  Rt                  Rv                  -  nU RB                  c  0 U l        SnGSnHUc  Ub  U Ry                  UUU1U0U-  5      nGUc  Ub  U Ry                  UUU1U0U-  5      nHU R{                  US&9 nI[}        U95       GH  u  nJnKU R~                  (       a  M  WKU l        WGb  WGU R                  S''   UnLU>b  [        R"                  " UU>/S	S9nLOU=b  [        R"                  " UU=/S	S9nLWKRo                  UR>                  S
   5      R7                  URf                  5      nMU Ra                  WLUMS(-  WFUUU5U?U RB                  SS)9	S
   nNUNSS2SUR                  S	5      24   nNU4(       a^  WHb  WHU R                  S''   U Ra                  WLWMS(-  WFUUW6U?U RB                  SS)9	S
   nOUOSS2SUR                  S	5      24   nOUOUWNUO-
  -  -   nNURf                  nPU RP                  R                  WNWKUSS*9S
   nU=nQWEnRWJ[=        U95      S	-
  :  a:  U9WJS	-      nSU RP                  R                  WQ[        R                  " US/5      WB5      nQS	WR-
  WQ-  URU-  -   nURf                  WP:w  a>  [        R                  R                  R                  5       (       a  UR7                  WP5      nUbJ  0 nTU H  nU[        5       UU   WTUU'   M     U" U WJWKWT5      nVUVR                  S+U5      nUVR                  S,U5      nWJ[=        U95      S	-
  :X  d)  WJS	-   U;:  a0  WJS	-   U RP                  R\                  -  S
:X  a  WIR                  5         [        (       d  GM  [        R                  " 5         GM     SSS5        SU l        US-:X  a  UnOU R                  UXU R                  5      nUU R                  RR                  R                  -  U R                  RR                  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$ ! , (       d  f       N= f)0a)  
Function invoked when calling the pipeline for generation.

Args:
    image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
        `Image`, numpy array or tensor representing an image batch to be be inpainted (which parts of the image
        to be masked out with `mask_image` and repainted according to `prompt` and `image_reference`). For both
        numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
        or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
        list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
        latents as `image`, but if passing latents directly it is not encoded again.
    image_reference (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
        `Image`, numpy array or tensor representing an image batch to be used as the starting point for the
        masked area. For both numpy array and pytorch tensor, the expected value range is between `[0, 1]` If
        it's a tensor or a list or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)` If it is
        a numpy array or a list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can
        also accept image latents as `image`, but if passing latents directly it is not encoded again.
    mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
        `Image`, numpy array or tensor representing an image batch to mask `image`. White pixels in the mask
        are repainted while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a
        single channel (luminance) before use. If it's a numpy array or pytorch tensor, it should contain one
        color channel (L) instead of 3, so the expected shape for pytorch tensor would be `(B, 1, H, W)`, `(B,
        H, W)`, `(1, H, W)`, `(H, W)`. And for numpy array would be for `(B, H, W, 1)`, `(B, H, W)`, `(H, W,
        1)`, or `(H, W)`.
    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.
    prompt_2 (`str` or `List[str]`, *optional*):
        The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
        will be used instead.
    negative_prompt (`str` or `List[str]`, *optional*):
        The prompt or prompts not to guide the image generation. If not defined, one has to pass
        `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
        not greater than `1`).
    negative_prompt_2 (`str` or `List[str]`, *optional*):
        The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
        `text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
    true_cfg_scale (`float`, *optional*, defaults to 1.0):
        True classifier-free guidance (guidance scale) is enabled when `true_cfg_scale` > 1 and
        `negative_prompt` is provided.
    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.
    strength (`float`, *optional*, defaults to 1.0):
        Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
        starting point and more noise is added the higher the `strength`. The number of denoising steps depends
        on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
        process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
        essentially ignores `image`.
    padding_mask_crop (`int`, *optional*, defaults to `None`):
        The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
        image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
        with the same aspect ration of the image and contains all masked area, and then expand that area based
        on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
        resizing to the original image size for inpainting. This is useful when the masked area is small while
        the image is large and contain information irrelevant for inpainting, such as background.
    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.
    guidance_scale (`float`, *optional*, defaults to 3.5):
        Embedded guidance scale is enabled by setting `guidance_scale` > 1. Higher `guidance_scale` encourages
        a model to generate images more aligned with `prompt` at the expense of lower image quality.

        Guidance-distilled models approximates true classifier-free guidance for `guidance_scale` > 1. Refer to
        the [paper](https://huggingface.co/papers/2210.03142) to learn more.
    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.FloatTensor`, *optional*):
        Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
        generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
        tensor will ge generated by sampling using the supplied random `generator`.
    prompt_embeds (`torch.FloatTensor`, *optional*):
        Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
        provided, text embeddings will be generated from `prompt` input argument.
    pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
        Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
        If not provided, pooled text embeddings will be generated from `prompt` input argument.
    ip_adapter_image: (`PipelineImageInput`, *optional*):
        Optional image input to work with IP Adapters.
    ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
        Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
        IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not
        provided, embeddings are computed from the `ip_adapter_image` input argument.
    negative_ip_adapter_image:
        (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
    negative_ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
        Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
        IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. If not
        provided, embeddings are computed from the `ip_adapter_image` input argument.
    negative_prompt_embeds (`torch.FloatTensor`, *optional*):
        Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
        weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
        argument.
    negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
        Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
        weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
        input argument.
    output_type (`str`, *optional*, defaults to `"pil"`):
        The output format of the generate image. Choose between
        [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
    return_dict (`bool`, *optional*, defaults to `True`):
        Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
    joint_attention_kwargs (`dict`, *optional*):
        A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
        `self.processor` in
        [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
    callback_on_step_end (`Callable`, *optional*):
        A function that calls at the end of each denoising steps during the inference. The function is called
        with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
        callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
        `callback_on_step_end_tensor_inputs`.
    callback_on_step_end_tensor_inputs (`List`, *optional*):
        The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
        will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
        `._callback_tensor_inputs` attribute of your pipeline class.
    max_sequence_length (`int` defaults to 512):
        Maximum sequence length to use with the `prompt`.
    max_area (`int`, defaults to `1024 ** 2`):
        The maximum area of the generated image in pixels. The height and width will be adjusted to fit this
        area while maintaining the aspect ratio.

Examples:

Returns:
    [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
    is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
    images.
      ?r    z6Generation `height` and `width` have been adjusted to r   z to fit the model requirements.)
r   r   r   rg   r   r   r   r   r   r   NFr"   r   r  r   c              3   L   >#    U  H  u  p[        TX-  -
  5      X4v   M     g 7fr:   absr   whaspect_ratios      r@   r   6FluxKontextInpaintPipeline.__call__.<locals>.<genexpr>w  s(      3B_$!S-.5B_   !$)padfilldefault)crops_coordsresize_modez/image must be provided correctly for inpainting)r   c              3   L   >#    U  H  u  p[        TX-  -
  5      X4v   M     g 7fr:   re  rg  s      r@   r   rk    s)      GB_$!S-.5B_rl  scale)r   r   rg   r   rD   r   r   r   rY  base_image_seq_len   max_image_seq_len   r7   r8   ffffff?)rF   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   rq  rp  r   r   )totalr   i  )	hidden_statesr+  guidancepooled_projectionsencoder_hidden_statestxt_idsimg_idsrK  r^  )r^  r]   rg   latent)r   )images)Tr   rq   roundr   r   r   rF  rJ  rR  rV  r   r   r   r<  r~   r   ndimr   r   get_default_height_widthr   PREFERRED_KONTEXT_RESOLUTIONSresizer   get_crop_region
preprocessrH   r   float32r   rP   r   r   rK  getr   nplinspacer   rA   rQ   r|   rU   r   r   r   r   rN  rm   in_channelsr9  r   rC  guidance_embedsfullexpandr   uint8r   r   r   progress_bar	enumeraterW  stepr.  tensorbackendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr  rh   r  r  decodepostprocessmaybe_free_model_hooksr#   )Xr   r   r,  r   r   r   r   r   r[  r   r   r   r   rC   rF   rG  r   rW   r]   rg   r   r   r   r\  r]  r   r   r   r^  rK  r_  r   r   r`  ra  original_heightoriginal_widthmultiple_ofimgimage_heightimage_widthr   rp  rq  
init_imageimg_referenceimage_reference_heightimage_reference_widthr   rD   r   has_neg_promptdo_true_cfgr   negative_text_idsr<   r?   rE   latent_timestepnum_warmup_stepsr  r  r1  r3  r/  r2  r4  mask_conditionrA  r@  r{  r   negative_image_embedsr  r  tlatent_model_inputr+  
noise_predneg_noise_predlatents_dtypeinit_latents_proper	init_masknoise_timestepcallback_kwargsr   callback_outputsrj  sX                                                                                          @r@   __call__#FluxKontextInpaintPipeline.__call__  sf   ` K433d6K6KKI11D4I4II*0~x,.367</C78++a/${2;&4_$(?NNHPUV[U\\{|
 	#+/'#9!5*G/Q/ 3# 	 	
(  .'=$!% j&E&E%**UV-[_[o[oJo%&&:eAh+M+MRWXYRZR_R_cdRd		%Q/(55%(5C(,(<(<(U(UVY(Z%L+&5L/2 3B_3 0,; &4{BK';6DL((//|[QE  E!F !,#22BB:V\Bt$#'((33|[|Yd 4 E NOOXXEMMX2
 &55/:N:Nq:QUYUiUi:i ?D11q15<<@@#A&++q0"'))O"C2<_d2S2SOA.YhM<@<P<P<i<i=9"$9 13IILCF GB_G D@(*@ %:[$H;$V!%;{%J[%X""2299!79NO #22==&%)' > O #O *VS"9"9JJvt$<$<VJ&,,Q/J'' ?C>Y>Y>eD''++GT:ko 	 )4 
"$.\3PX\3\ 	 %q(;^
 '!5"7 3!  	
		
  
 ""&*4%B&;$7% # 		&-! TZSaS!&9"9;NOgmV(=(==Bs5zUYUjUjGjnoGopNN!!%%&:C@NN!!%%&94@NN!!%%lC8NN!!%%k48
 *<NN*
&	& *.););<O[a)b&	&"QRZQ[ \/00df  $BQ-..z<Q/QRs9~0CnnFZFZ0ZZ\]^!)n  $//66BBaG  22$## 	k 7YPcej  *J0C#D!LJ"J	#:BJ,,77UZf 8 
 "^c%9:++ !
a ""22zz1#~fEMMZHw}}Q'78HH(,C,O%-2R2Z(*%1C288(T%)B(CdFVFVFgFgFwFw(w%&+B+J%15U5a!xx(:"((K 01D4D4D4U4U4e4ee&&.+-D( $'+B+N?? '22	L %04T4`$($H$H)022	%! %89\!),1>>)*&+NZD001JK%,"*6).G=T3U[\)]&".).G]3KQR)S&88GMM!$4588G!--"4%_%';*7$&+/+F+F % . 
 

 (+<W\\!_+<(<=
,8Rg445NO%)%5%5&8!)D!)+H.D 1 */3/J/J$) &6 
& 
&N &4A7Ha7H4H%IN!/.JQ_D_2`!`J !(..--j!WRW-XYZ[&3# 	s9~))%.q1u%5N*...*D*D+U\\>:J-KU+' y=,??)gBUU==M1~~))6688")**]";'3&(O?-3Xa[* @';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') =LLN_ - :d "&("E**7F4CXCXYG!?!??488??C_C__GHHOOGO?BE((44U4TE 	##%8O!//E :9s   'Kq$7q$$
q2)rR  rF  rV  rJ  r   rN  r   r   r~   r   r   rq   )NN)Nr"   r   NN)r"   N)NNr"   NNr   N)	NNNNNNNNN)NNN)A__name__
__module____qualname____firstlineno____doc__model_cpu_offload_seq_optional_componentsr   r   r   r
   r   r   r   r   r   r	   ry   r   r   r   r   r   r   rD   r   r   r   FloatTensorfloatr   r   r   r   r   staticmethodr  r	  r  r   	Generatorr  r  r!  r%  r)  r9  rC  propertyrG  rK  rO  rS  rW  no_gradr   EXAMPLE_DOC_STRINGr   boolr   r   r   r  __static_attributes____classcell__)rO   s   @r@   rc   rc      s   4 \+-@A(/: 8<04*'2*' *' $	*'
 !*' '*' %*' ,*' 5*' .*' *'^ )-%&#&)-'+/c49n%/  #/ !	/
 &/ $/j &')-	*c49n%*  #* &	*` 59)-%&59<@#&&*M=c49n%M= 5d3i01M= &	M=
  #M=   1 12M= 'u'8'89M= !M= UOM=`	"'J	8, #!&*+/ %`oD ? ?    u||  "#!"" NR*.26er%er er 	er
 "er er er {{er er E%//43H"HIJer %,,'er "%,,/erPG*R $ $ , , # # & &   ]]_12 /38<)-(,4815=A # $#+/#%(, #/0MQ/359<@9=@DBFIM>BEI%* ;?KO9B#&!G_0*+_0 ""45_0 '	_0
 c49n%_0 5d3i01_0 sDI~._0 $E#tCy.$9:_0 _0 _0 }_0 _0 $C=_0 !_0 e%_0  !_0"  (}#_0$ E%//43H"HIJ%_0& %++,'_0(   1 12)_0* 'u'8'89+_0, ##56-_0. "*$u||*<!=/_00 $,,>#?1_02 +343E*F3_04 !)):): ;5_06 (00A0A'B7_08 c]9_0: ;_0< !)c3h 8=_0> 'xc40@$0F'GH?_0@ -1IA_0B !C_0D E_0F G_0 3 _0rB   rc   )ru  rw  rc  rx  )NNNN)Nr[   )BrJ   typingr   r   r   r   r   r   numpyr  	PIL.Imager   r   transformersr	   r
   r   r   r   r   r   r   r   loadersr   r   r   r   modelsr   r   
schedulersr   utilsr   r   r   r   r   r   utils.torch_utilsr   pipeline_utilsr!   pipeline_outputr#   torch_xla.core.xla_modelcore	xla_modelr  r  
get_loggerr  r   r  r  r   r  rA   r   rD   rU   r   r  ra   rc   r;   rB   r@   <module>r     st    = =     E p p ; 9  . . / ))MM 
		H	%: x! . 

 
 	

 
  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*z ck
TLL
T-5eoo-F
T\_
T^0^0rB   