
    +h                     J   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rS SKrS SKJrJrJrJr  SSKJrJr  SSKJr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!  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/J0s  J1r2  Sr3OSr3\%Rh                  " \55      r6Sr7    S$S\8S\8S\9S\94S jjr: S%S\Rv                  S\\Rx                     S\=4S jjr>    S&S\\8   S\\\=\R~                  4      S\\\8      S \\\9      4S! jjr@ " S" S#\,\\5      rAg)'    N)AnyCallableDictListOptionalTupleUnion)CLIPTextModelCLIPTokenizerT5EncoderModelT5TokenizerFast   )PipelineImageInputVaeImageProcessor)FluxLoraLoaderMixinFromSingleFileMixinTextualInversionLoaderMixin)AutoencoderKL)FluxControlNetModelFluxMultiControlNetModel)FluxTransformer2DModel)FlowMatchEulerDiscreteScheduler)USE_PEFT_BACKENDis_torch_xla_availableloggingreplace_example_docstringscale_lora_layersunscale_lora_layers)randn_tensor   )DiffusionPipeline   )FluxPipelineOutputTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import FluxControlNetInpaintPipeline
        >>> from diffusers.models import FluxControlNetModel
        >>> from diffusers.utils import load_image

        >>> controlnet = FluxControlNetModel.from_pretrained(
        ...     "InstantX/FLUX.1-dev-controlnet-canny", torch_dtype=torch.float16
        ... )
        >>> pipe = FluxControlNetInpaintPipeline.from_pretrained(
        ...     "black-forest-labs/FLUX.1-schnell", controlnet=controlnet, torch_dtype=torch.float16
        ... )
        >>> pipe.to("cuda")

        >>> control_image = load_image(
        ...     "https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Canny-alpha/resolve/main/canny.jpg"
        ... )
        >>> init_image = load_image(
        ...     "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
        ... )
        >>> mask_image = load_image(
        ...     "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
        ... )

        >>> prompt = "A girl holding a sign that says InstantX"
        >>> image = pipe(
        ...     prompt,
        ...     image=init_image,
        ...     mask_image=mask_image,
        ...     control_image=control_image,
        ...     control_guidance_start=0.2,
        ...     control_guidance_end=0.8,
        ...     controlnet_conditioning_scale=0.7,
        ...     strength=0.7,
        ...     num_inference_steps=28,
        ...     guidance_scale=3.5,
        ... ).images[0]
        >>> image.save("flux_controlnet_inpaint.png")
        ```
base_seq_lenmax_seq_len
base_shift	max_shiftc                 4    XC-
  X!-
  -  nX5U-  -
  nX-  U-   nU$ N )image_seq_lenr$   r%   r&   r'   mbmus           v/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.pycalculate_shiftr0   W   s3     
	K$>?A%%A		Q	BI    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)hasattrr6   r7   moder9   AttributeError)r2   r3   r4   s      r/   retrieve_latentsr=   e   s}     ~}--+2I))00;;		/	/K84K))..00		+	+%%%RSSr1   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?   rA   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)rA   r?   r?   r*   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r@   len)	schedulerr>   r?   r@   rA   kwargsaccepts_timestepsaccept_sigmass           r/   retrieve_timestepsrP   s   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''	))r1   c            ;         ^  \ rS rSrSrSr/ r/ SQrS\S\	S\
S\S	\S
\S\S\\\\   \\   \4   4U 4S jjr     SIS\\\\   4   S\S\S\\R2                     S\\R4                     4
S jjr  SJS\\\\   4   S\S\\R2                     4S jjr       SKS\\\\   4   S\\\\\   4      S\\R2                     S\S\\R:                     S\\R:                     S\S\\   4S jjrS\R@                  S\RB                  4S jr"S  r#     SLS! jr$\%S" 5       r&\%S# 5       r'\%S$ 5       r( SMS% jr)S& r*  SNS' jr+\,S( 5       r-\,S) 5       r.\,S* 5       r/\,S+ 5       r0\Rb                  " 5       \2" \35      SSSSSSSSS,SSS-S.S/S0SS0SSSSSS1S2SSS3/S4S\\\\   4   S\\\\\   4      S\4S4\4S5\4S6\4S7\\   S8\\   S9\S:\\   S;\\\      S<\S=\S>\\\\   4   S?\\\\   4   S@\\\\\   4      SA\\\\   4   S\\   S\\\RB                  \\RB                     4      S3\\R:                     S\\R:                     S\\R:                     SB\\   SC\5SD\\6\\74      SE\\8\\\6/S4      SF\\   S\48SG jj5       5       r9SHr:U =r;$ )OFluxControlNetInpaintPipeline   ax  
The Flux controlnet pipeline for inpainting.

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->transformer->vae)r9   prompt_embedscontrol_imagemaskmasked_image_latentsrL   vaetext_encoder	tokenizertext_encoder_2tokenizer_2transformer
controlnetc	                   > [         T
U ]  5         [        U[        [        45      (       a  [        U5      nU R                  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 R                  S-  S9U l        [        U SS 5      (       a   U R                  R                  R                  OSn	[        U R                  S-  U	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)rL   rX   rY   rZ   r[   r\   r]   r^   rX   r    r"      )vae_scale_factor   FT)ra   vae_latent_channelsdo_normalizedo_binarizedo_convert_grayscalerZ   M      )super__init__
isinstancelisttupler   register_modulesgetattrrK   rX   configblock_out_channelsra   r   image_processorlatent_channelsmask_processorr:   rZ   model_max_lengthtokenizer_max_lengthdefault_sample_size)selfrL   rX   rY   rZ   r[   r\   r]   r^   rs   rJ   s             r/   rj   &FluxControlNetInpaintPipeline.__init__   s4    	j4-001*=J%)##! 	 		
 W^^bdikoVpVpc$((//*L*L&MPQ&Q Rvw  1$BWBWZ[B[\=DT5RV=W=W$((//99]_/!22Q6 /!%
 07t[/I/IdnnNhDNN++np 	! $' r1   Nr"      promptnum_images_per_promptmax_sequence_lengthr?   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~   r?   )_execution_devicerY   r~   rk   strrK   r   maybe_convert_promptr\   	input_idsshapetorchequalbatch_decoderv   loggerwarningr[   torepeatview)rx   r{   r|   r}   r?   r~   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textrT   _seq_lens                 r/   _get_t5_prompt_embeds3FluxControlNetInpaintPipeline._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[r1   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   rk   r   rK   r   r   rZ   rv   r   r   r   r   r   r   r   rY   r   pooler_outputr~   r   r   )
rx   r{   r|   r?   r   r   r   r   r   rT   s
             r/   _get_clip_prompt_embeds5FluxControlNetInpaintPipeline._get_clip_prompt_embeds-  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r1   prompt_2rT   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{   r?   r|   )r{   r|   r}   r?   r"   r   r?   r~   )r   rk   r   _lora_scalerY   r   r   r[   r   r   r   r   r~   r]   r   zerosr   r   )rx   r{   r   r?   r|   rT   r   r}   r   r~   text_idss              r/   encode_prompt+FluxControlNetInpaintPipeline.encode_promptZ  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<<r1   imager3   c                    [        U[        5      (       af  [        UR                  S   5       Vs/ s H-  n[	        U R
                  R                  XUS-    5      X#   S9PM/     nn[        R                  " USS9nO#[	        U R
                  R                  U5      US9nX@R
                  R                  R                  -
  U R
                  R                  R                  -  nU$ s  snf )Nr   r"   r3   dim)rk   rl   ranger   r=   rX   encoder   catrp   shift_factorscaling_factor)rx   r   r3   iimage_latentss        r/   _encode_vae_image/FluxControlNetInpaintPipeline._encode_vae_image  s    i&& u{{1~..A !1q51A!Bil[.   "IIm;M,TXX__U-CyYM&)E)EEIgIggs   4C$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maxrL   r@   orderr:   r   )rx   r>   strengthr?   init_timestept_startr@   s          r/   get_timesteps+FluxControlNetInpaintPipeline.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7r1   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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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
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 z and z(. Dimensions will be resized accordinglyc              3   @   >#    U  H  oTR                   ;   v   M     g 7fr)   )_callback_tensor_inputs).0krx   s     r/   	<genexpr>=FluxControlNetInpaintPipeline.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.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 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`.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 rz   z8`max_sequence_length` cannot be greater than 512 but is )rC   ra   r   r   allr   rk   r   rl   typePILImage)rx   r{   r   r   
mask_imager   heightwidthoutput_typerT   r   "callback_on_step_end_tensor_inputspadding_mask_cropr}   r   s   `              r/   check_inputs*FluxControlNetInpaintPipeline.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  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$)=)E U  (eSYY__55 `aefkal`mmno  j#))//:: Z(),  e# #cdocppq!rss*/BS/HWXkWlmnn 0I*Q pHs   (I?I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   r?   r~   latent_image_idslatent_image_id_heightlatent_image_id_widthlatent_image_id_channelss	            r/   _prepare_latent_image_ids7FluxControlNetInpaintPipeline._prepare_latent_image_ids  s     !;;va8#3F#;ell6>RSTVZSZ>[#[ #3F#;ell5>QRVXYRY>Z#Z RbRhRhO7O+33":<T
  ""&">>r1   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   )r9   r   num_channels_latentsr   r   s        r/   _pack_latents+FluxControlNetInpaintPipeline._pack_latents  sg     ,,z1aQVZ[Q[]^_//!Q1a3//*{uz.JL`cdLder1   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   )r9   r   r   ra   r   num_patcheschannelss          r/   _unpack_latents-FluxControlNetInpaintPipeline._unpack_latents#  s     -4MM)
 c&k&6&:;<SZ$4q$89:,,zQ;
HPQMSTVWX//!Q1a3//*5.A6Qr1   c                    [        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U R                  X5S-  US-  X5      nUR                  XS9nU R                  XS9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
c'  [        XXS9nU R                  R                  XU5      n
OU
R                  U5      nUn
U R                  XXEU5      nU R                  XXEU5      nU R                  XXEU5      n
XX4$ )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   r3   r   r   z'Cannot duplicate `image` of batch size z to z text prompts.)r3   r?   r~   )rk   rl   rK   rC   r   ra   r   r   r   r   r   r   r   rL   scale_noiser   )rx   r   timestepr   r   r   r   r~   r?   r3   r9   r   r   r   additional_image_per_promptnoises                   r/   prepare_latents-FluxControlNetInpaintPipeline.prepare_latents4  s    i&&3y>Z+GA#i.AQ R&<'gi  c&kd&;&;a&?@ASZD$9$9A$=>?6A99*PQkSX\]S]_em4..U.P++A..:@S@STU@V3VZ[3[*48K8KA8N*N'!II}o8S&SYZ[M--a00ZBUBUVWBX5X\]5]9-:M:Ma:P9QQUV`Uaaop  "II}o1=M? FXEnn00%PGJJv&EG""56JTYZ**=FZdij$$W:NX]^}>>r1   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O#[        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"   rb   r   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   ra   r   nn
functionalinterpolater   r   r=   rX   r   rp   r   r   rC   r   r   )rx   rV   masked_imager   r   r|   r   r   r~   r?   r3   rW   s               r/   prepare_mask_latents2FluxControlNetInpaintPipeline.prepare_mask_latentsh  sd    c&kd&;&;a&?@ASZD$9$9A$=>? xx""..t5/.Jwwfw27
#fBa B&#/ #3DHHOOL4Q]f#g  4xx7S7S SW[W_W_WfWfWuWuu ::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 
 ))r1   c
                 <   [        U[        R                  5      (       a  OU R                  R	                  XUS9nUR
                  S   n
U
S:X  a  UnOUnUR                  USS9nUR                  XgS9nU(       a!  U	(       d  [        R                  " U/S-  5      nU$ )N)r   r   r   r"   r   r   r    )	rk   r   Tensorrr   
preprocessr   repeat_interleaver   r   )rx   r   r   r   r   r|   r?   r~   do_classifier_free_guidance
guess_modeimage_batch_size	repeat_bys               r/   prepare_image+FluxControlNetInpaintPipeline.prepare_image  s     eU\\**((33EPU3VE ;;q>q "I .I''	q'94&zIIugk*Er1   c                     U R                   $ r)   )_guidance_scalerx   s    r/   guidance_scale,FluxControlNetInpaintPipeline.guidance_scale  s    ###r1   c                     U R                   $ r)   )_joint_attention_kwargsr  s    r/   joint_attention_kwargs4FluxControlNetInpaintPipeline.joint_attention_kwargs  s    +++r1   c                     U R                   $ r)   )_num_timestepsr  s    r/   num_timesteps+FluxControlNetInpaintPipeline.num_timesteps  s    """r1   c                     U R                   $ r)   )
_interruptr  s    r/   	interrupt'FluxControlNetInpaintPipeline.interrupt  s    r1   g333333?   g      @g              ?r   Tr9   r   rW   rU   r   r   r   r   rA   r>   r  control_guidance_startcontrol_guidance_endcontrol_modecontrolnet_conditioning_scaler   return_dictr  callback_on_step_endr   c                 `   U=(       d    U R                   U R                  -  nU=(       d    U R                   U R                  -  nUnUn[        U[        5      (       d%  [        U[        5      (       a  [	        U5      U/-  nO[        U[        5      (       d%  [        U[        5      (       a  [	        U5      U/-  nOu[        U[        5      (       d`  [        U[        5      (       dK  [        U R
                  [        5      (       a  [	        U R
                  R                  5      OSnUU/-  UU/-  pU R                  UUUUU	UUUUUUU
US9  Xl	        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                  R                   n"U R"                  b  U R"                  R%                  SS5      OSn#U R'                  UUUUU!UUU#S9u  nnn$U
b  U R(                  R+                  UUUU
S9n%S	n&OSn%S
n&Un'U R,                  R/                  UUUU%U&S9n(U(R1                  [2        R4                  S9n(U R                  R6                  R8                  S-  n)[        U R
                  [:        5      (       GaI  U R=                  UUUU U-  UU!U R>                  R                   S9nUR                  SS u  pxU R
                  R@                  c  SOSn*U R
                  R@                  c  [C        U R>                  RE                  U5      US9nX`R>                  R6                  RF                  -
  U R>                  R6                  RH                  -  nUR                  SS u  n+n,U RK                  UU U-  U)U+U,5      nUbE  [2        RL                  " U5      R1                  U![2        RN                  S9nURQ                  SS/5      nGO[        U R
                  [        5      (       Ga  / n-U R
                  R                  S   R@                  c  SOSn*[S        U5       GH
  u  n.n/U R=                  U/UUU U-  UU!U R>                  R                   S9n/U/R                  SS u  pxU R
                  R                  S   R@                  c  [C        U R>                  RE                  U/5      US9n/U/U R>                  R6                  RF                  -
  U R>                  R6                  RH                  -  n/U/R                  SS u  n+n,U RK                  U/U U-  U)U+U,5      n/U-RU                  U/5        GM     U-n/ n0[        U[        5      (       a0  U H*  n1U1c  U0RU                  S5        M  U0RU                  U15        M,     [2        RL                  " U05      R1                  U![2        RN                  S9nURQ                  SS/5      nUc  [V        RX                  " SSU-  U5      OUn[[        U5      U R                  -  S-  [[        U5      U R                  -  S-  -  n2[]        U2U R^                  R6                  R%                  SS5      U R^                  R6                  R%                  SS5      U R^                  R6                  R%                  SS5      U R^                  R6                  R%                  SS5      5      n3[a        U R^                  UU!UU3S9u  n4nU Rc                  XU!5      u  n4nUS:  a  [e        SU	 SU S 35      eU4SS Rg                  U U-  5      n5U Ri                  U(U5U U-  U)UUUR                   U!UU5
      u  nn6n7n8U R(                  R/                  UUUU&U%S!9n9Uc	  U(U9S:  -  n:OUn:U Rk                  U9U:U U)UUUUR                   U!U5
      u  n;n/ n<[m        [	        U45      5       H  n.[o        X5       V=V>s/ s H>  u  n=n>S[q        U.[	        U45      -  U=:  =(       d    U.S-   [	        U45      -  U>:  5      -
  PM@     n?n=n>U<RU                  [        U R
                  [:        5      (       a  U?S   OU?5        M     [s        [	        U45      XR^                  Rt                  -  -
  S5      n@[	        U45      U l;        U Ry                  US"9 nA[S        U45       GH  u  n.nBU Rz                  (       a  M  WBR}                  UR                  S   5      R1                  UR                   5      nC[        U R
                  [        5      (       a.  U R
                  R                  S   R6                  R~                  nDO U R
                  R6                  R~                  nDWD(       aE  [2        R                  " S/UU![2        R4                  S#9nEUER}                  UR                  S   5      nEOSnE[        U<U.   [        5      (       a(  [o        UU<U.   5       VFV=s/ s H  u  nFn=UFU=-  PM     nGnFn=O$UnH[        UH[        5      (       a  WHS   nHWHU<U.   -  nGU R                  UUUWGWCS$-  WEUUU$U8U R"                  SS%9u  nInJU R                  R6                  R~                  (       aE  [2        R                  " S/UU![2        R4                  S#9nEUER}                  UR                  S   5      nEOSnEU R                  UWCS$-  WEUUWIWJU$U8U R"                  SW*S&9S   nKUR                   nLU R^                  R                  UKWBUSS'9S   nU7nMU;nNU.[	        U45      S-
  :  a:  U4U.S-      nOU R^                  R                  WM[2        RL                  " UO/5      U65      nMSWN-
  WM-  UNU-  -   nUR                   WL:w  a>  [2        R                  R                  R                  5       (       a  UR1                  WL5      nUb  0 nPU H  nQ[        5       UQ   WPUQ'   M     U" U U.WBWP5      nRURR                  S(U5      nURR                  S)U5      nURR                  S*U5      nURR                  S+U;5      n;URR                  S,U5      nU.[	        U45      S-
  :X  d)  U.S-   W@:  a0  U.S-   U R^                  Rt                  -  S:X  a  WAR                  5         [        (       d  GM  [        R                  " 5         GM     SSS5        US-:X  a  UnOU R                  UUUU R                  5      nUU R>                  R6                  RH                  -  U R>                  R6                  RF                  -   nU R>                  R                  USS'9S   nU R,                  R                  UUS.9nU R                  5         U(       d  U4$ [        US/9$ s  sn>n=f s  sn=nFf ! , (       d  f       N= f)0a  
Function invoked when calling the pipeline for generation.

Args:
    prompt (`str` or `List[str]`, *optional*):
        The prompt or prompts to guide the image generation.
    prompt_2 (`str` or `List[str]`, *optional*):
        The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`.
    image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
        The image(s) to inpaint.
    mask_image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
        The mask image(s) to use for inpainting. White pixels in the mask will be repainted, while black pixels
        will be preserved.
    masked_image_latents (`torch.FloatTensor`, *optional*):
        Pre-generated masked image latents.
    control_image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
        The ControlNet input condition. Image to control the generation.
    height (`int`, *optional*, defaults to self.default_sample_size * self.vae_scale_factor):
        The height in pixels of the generated image.
    width (`int`, *optional*, defaults to self.default_sample_size * self.vae_scale_factor):
        The width in pixels of the generated image.
    strength (`float`, *optional*, defaults to 0.6):
        Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1.
    padding_mask_crop (`int`, *optional*):
        The size of the padding to use when cropping the mask.
    num_inference_steps (`int`, *optional*, defaults to 28):
        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 7.0):
        Guidance scale as defined in [Classifier-Free Diffusion
        Guidance](https://huggingface.co/papers/2207.12598).
    control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
        The percentage of total steps at which the ControlNet starts applying.
    control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
        The percentage of total steps at which the ControlNet stops applying.
    control_mode (`int` or `List[int]`, *optional*):
        The mode for the ControlNet. If multiple ControlNets are used, this should be a list.
    controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
        The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
        to the residual in the original transformer.
    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 more [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.
    prompt_embeds (`torch.FloatTensor`, *optional*):
        Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
    pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
        Pre-generated pooled text embeddings.
    output_type (`str`, *optional*, defaults to `"pil"`):
        The output format of the generate image. Choose between `PIL.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*):
        Additional keyword arguments to be passed to the joint attention mechanism.
    callback_on_step_end (`Callable`, *optional*):
        A function that calls at the end of each denoising step during the inference.
    callback_on_step_end_tensor_inputs (`List[str]`, *optional*):
        The list of tensor inputs for the `callback_on_step_end` function.
    max_sequence_length (`int`, *optional*, defaults to 512):
        The maximum length of the sequence to be generated.

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"   )r   rT   r   r   r   r}   FNr   scale)r{   r   rT   r   r?   r|   r}   r   )padfilldefault)r   r   crops_coordsresize_mode)r~   r   )r   r   r   r   r|   r?   r~   Tr   r    r   r   base_image_seq_len   max_image_seq_len   r&         ?r'   ffffff?)rA   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   r-  r,  )totalr   i  )hidden_statescontrolnet_condcontrolnet_modeconditioning_scaler   guidancepooled_projectionsencoder_hidden_statestxt_idsimg_idsr  r%  )r6  r   r:  r;  r<  controlnet_block_samplescontrolnet_single_block_samplesr=  r>  r  r%  controlnet_blocks_repeat)r%  r9   rT   rU   rV   rW   latent)r   )images)Qrw   ra   rk   rl   rK   r^   r   netsr   r  r  r  r   r   r   r]   r~   r  getr   rt   get_crop_regionrr   r  r   r   float32rp   in_channelsr   r  rX   input_hint_blockr=   r   r   r   r   tensorlongr   	enumerateappendnplinspacer   r0   rL   rP   r   rC   r   r   r  r   zipfloatr   r   r  progress_barr  expandguidance_embedsfullstepr   backendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   decodepostprocessmaybe_free_model_hooksr#   )Srx   r{   r   r   r   rW   rU   r   r   r   r   rA   r>   r  r!  r"  r#  r$  r|   r3   r9   rT   r   r   r%  r  r&  r   r}   global_heightglobal_widthmultr   r?   r~   r   r   r,  r-  original_image
init_imager   rA  height_control_imagewidth_control_imagecontrol_imagesr   control_image_control_mode_cmoder+   r.   r@   latent_timestepr   r   r   mask_conditionr  rV   controlnet_keepsekeepsnum_warmup_stepsrR  tr   use_guidancer:  c
cond_scalecontrolnet_cond_scaler?  r@  
noise_predlatents_dtypeinit_latents_proper	init_masknoise_timestepcallback_kwargsr   callback_outputssS                                                                                      r/   __call__&FluxControlNetInpaintPipeline.__call__  s   Z K433d6K6KKI11D4I4II0$77JG[]a<b<b%()=%>BXAY%Y"0$77JG]_c<d<d#&'=#>BVAW#W 2D99*MacgBhBh0:4??Ld0e0e3t++,klD.//,-- %9 	#'!5/Q/ 3 	 	
   .'=$ *VS"9"9JJvt$<$<VJ&,,Q/J''  && ?C>Y>Y>eD''++GT:ko 	 9=8J8J'!5"7 3! 9K 	9
5+X (..>>L-=N ? L !KL#K))44-|,do 5 

  ]]]7
  $//66BBaGdoo':;; ..#%(==&;hhnn / M *//4MF 150P0P0Xu^b$//7 01O[d e!.1M1M!MQUQYQYQ`Q`QoQo o =J<O<OPQPR<S9$&9 $ 2 2!!66(('! '$||L9<<V5::<V+33RG<)ABBN 150D0DQ0G0X0X0`ufj$%.}%=!>!%!3!3(!),AA*?!((.. "4 " !/ 4 4RS 9??''*;;C%5dhhoon6Uaj%kN&4txx7S7S&SW[W_W_WfWfWuWu%uN AO@T@TUVUW@X=(*=%)%7%7&"%::,,+&N %%n57 &>: +M M,--)E}%,,R0%,,U3	 *
 !<<699&

9SL'//Q8L TZSaS!&9"9;NOgm]+t/D/DDI!6!66!;
 NN!!%%&:C@NN!!%%&94@NN!!%%lC8NN!!%%k48
 *<NN*
&	& *.););<O[a)b&	&"QRZQ[ \/00df  $BQ-..z<Q/QR ;?:N:N.. ;
7'7 ,,77}Lkht 8 
  '%#)=>L/L%)%>%> !&
"" s9~&A   6MMDAq eAI.2Rq1uI6NQR6RSSM   ""z$//K^/_/_58ejk ' s9~0CnnFZFZ0ZZ\]^!)n%89\!),1>>88GMM!$4588G doo/GHH#'??#7#7#:#A#A#Q#QL#'??#9#9#I#IL$zz1#~fTYTaTabH'w}}Q/?@H#Hoa0$77478UWfghWi4j!k4jDAq!a%4jJ!kJ,I)!"7>>0Ea0H-!69K!KJLPOO")$1$0'1%_%';*7$,+/+F+F % M\ MI(*I ##**::$zz1#~fTYTaTabH'w}}Q/?@H#H!--")%_%';*7-E4S$,+/+F+F %-E .  
  !(..--j!WRW-XYZ[ '4# 	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$4$8$8-$XM+//=D+;+?+?@VXl+m(I**A9I/IqSTuX\XfXfXlXlNlpqNq '') =LLNG - :N ("E**7M<QUQfQfgG!?!??488??C_C__GHHOOGO?BE((44U4TE 	##%8O!//: "l' :9s-   /Av=Ev?v
Jv,vv
v-)
r  r  r  r   r  rw   rr   rt   rv   ra   )Nr"   rz   NN)r"   N)NNr"   NNrz   N)NNNNNr)   )FF)<__name__
__module____qualname____firstlineno____doc__model_cpu_offload_seq_optional_componentsr   r   r   r
   r   r   r   r   r	   r   r   r   r   rj   r   r   r   r   r?   r~   r   r   FloatTensorrQ  r   r  	Generatorr   r   r   staticmethodr   r   r   r   r  r  propertyr  r  r  r  no_gradr   EXAMPLE_DOC_STRINGr   boolr   r   r   r  __static_attributes____classcell__)rJ   s   @r/   rR   rR      s`   4 Mk+'2+' +' $	+'
 !+' '+' %+' ,+' &9!:EBU<VXpp
+'` )-%&#&)-'+/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=`u||  	8* !+/ EoN ? ?    4 2?hE*b %* D $ $ , , # #   ]]_12 )-48$()-37,0 $#+/(,#% #<?:=8<CF/0MQ/359<@%* ;?KO9B#&;Q0c49n%Q0 5d3i01Q0 "	Q0
 'Q0 1Q0 *Q0 Q0 }Q0 Q0 $C=Q0 e%Q0 !Q0 Q0 !&eT%[&8 9Q0  $E4;$67!Q0" uS$s)^45#Q0$ (-UDK-?'@%Q0&  (}'Q0( E%//43H"HIJ)Q0* %++,+Q0,   1 12-Q0. 'u'8'89/Q00 c]1Q02 3Q04 !)c3h 85Q06 'xc40@$0F'GH7Q08 -1I9Q0: !;Q0 3 Q0r1   rR   )r0  r2  r3  r4  )Nr7   )NNNN)BrE   typingr   r   r   r   r   r   r	   numpyrN  r   r   transformersr
   r   r   r   rr   r   r   loadersr   r   r   models.autoencodersr   "models.controlnets.controlnet_fluxr   r   models.transformersr   
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   rQ  r0   r  r  r   r=   r?   rP   rR   r*   r1   r/   <module>r     sk    D D D  
   E \ \ 0 _ 9 9  . . / ))MM			H	%) ^ 

 
 	

 
 ck
TLL
T-5eoo-F
T\_
T  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vG0$57JL_ G0r1   