
    +h                     0   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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  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  J,r-  Sr.OSr.\ R^                  " \05      r1Sr2    S#S\3S\3S\4S\44S jjr5 S$S\
Rl                  S\\
Rn                     S\84S jjr9    S%S\\3   S\\\8\
Rt                  4      S\\\3      S\\\4      4S  jjr; " S! S"\'\\\5      r<g)&    N)AnyCallableDictListOptionalUnion)CLIPTextModelCLIPTokenizerT5EncoderModelT5TokenizerFast   )PipelineImageInputVaeImageProcessor)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:
        ```py
        import torch
        from diffusers import FluxControlInpaintPipeline
        from diffusers.models.transformers import FluxTransformer2DModel
        from transformers import T5EncoderModel
        from diffusers.utils import load_image, make_image_grid
        from image_gen_aux import DepthPreprocessor  # https://github.com/huggingface/image_gen_aux
        from PIL import Image
        import numpy as np

        pipe = FluxControlInpaintPipeline.from_pretrained(
            "black-forest-labs/FLUX.1-Depth-dev",
            torch_dtype=torch.bfloat16,
        )
        # use following lines if you have GPU constraints
        # ---------------------------------------------------------------
        transformer = FluxTransformer2DModel.from_pretrained(
            "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="transformer", torch_dtype=torch.bfloat16
        )
        text_encoder_2 = T5EncoderModel.from_pretrained(
            "sayakpaul/FLUX.1-Depth-dev-nf4", subfolder="text_encoder_2", torch_dtype=torch.bfloat16
        )
        pipe.transformer = transformer
        pipe.text_encoder_2 = text_encoder_2
        pipe.enable_model_cpu_offload()
        # ---------------------------------------------------------------
        pipe.to("cuda")

        prompt = "a blue robot singing opera with human-like expressions"
        image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/robot.png")

        head_mask = np.zeros_like(image)
        head_mask[65:580, 300:642] = 255
        mask_image = Image.fromarray(head_mask)

        processor = DepthPreprocessor.from_pretrained("LiheYoung/depth-anything-large-hf")
        control_image = processor(image)[0].convert("RGB")

        output = pipe(
            prompt=prompt,
            image=image,
            control_image=control_image,
            mask_image=mask_image,
            num_inference_steps=30,
            strength=0.9,
            guidance_scale=10.0,
            generator=torch.Generator().manual_seed(42),
        ).images[0]
        make_image_grid([image, control_image, mask_image, output.resize(image.size)], rows=1, cols=4).save(
            "output.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           p/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/pipelines/flux/pipeline_flux_control_inpaint.pycalculate_shiftr-   u   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)hasattrr3   r4   moder6   AttributeError)r/   r0   r1   s      r,   retrieve_latentsr:      s}     ~}--+2I))00;;		/	/K84K))..00		+	+%%%RSSr.   num_inference_stepsdevice	timestepssigmasc                    Ub  Ub  [        S5      eUb  S[        [        R                  " U R                  5      R
                  R                  5       5      ;   nU(       d  [        SU R                   S35      eU R                  " S
X2S.UD6  U R                  n[        U5      nX14$ Ub  S[        [        R                  " U R                  5      R
                  R                  5       5      ;   nU(       d  [        SU R                   S35      eU R                  " S
XBS.UD6  U R                  n[        U5      nX14$ U R                  " U4S	U0UD6  U R                  nX14$ )a  
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.

Args:
    scheduler (`SchedulerMixin`):
        The scheduler to get timesteps from.
    num_inference_steps (`int`):
        The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
        must be `None`.
    device (`str` or `torch.device`, *optional*):
        The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
    timesteps (`List[int]`, *optional*):
        Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
        `num_inference_steps` and `sigmas` must be `None`.
    sigmas (`List[float]`, *optional*):
        Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
        `num_inference_steps` and `timesteps` must be `None`.

Returns:
    `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
    second element is the number of inference steps.
zYOnly one of `timesteps` or `sigmas` can be passed. Please choose one to set custom valuesr=   zThe current scheduler class zx's `set_timesteps` does not support custom timestep schedules. Please check whether you are using the correct scheduler.)r=   r<   r>   zv's `set_timesteps` does not support custom sigmas schedules. Please check whether you are using the correct scheduler.)r>   r<   r<   r'   )

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r=   len)	schedulerr;   r<   r=   r>   kwargsaccepts_timestepsaccept_sigmass           r,   retrieve_timestepsrM      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''	))r.   c            1         ^  \ rS rSrSrSr/ rSS/rS\S\	S\
S	\S
\S\S\4U 4S jjr     SDS\\\\   4   S\S\S\\R,                     S\\R.                     4
S jjr  SES\\\\   4   S\S\\R,                     4S jjr       SFS\\\\   4   S\\\\\   4      S\\R,                     S\S\\R4                     S\\R4                     S\S\\   4S jjrS\R:                  S\R<                  4S jrS r     SGS  jr!\"S! 5       r#\"S" 5       r$\"S# 5       r%S$ r&S% r'S& r(S' r) SHS( jr*  SIS) jr+S* r,\-S+ 5       r.\-S, 5       r/\-S- 5       r0\-S. 5       r1\Rd                  " 5       \3" \45      SSSSSSSSS/S0SS1SSSSSS2S3SSS/S4S\\\\   4   S\\\\\   4      S\5S4\5S5\5S6\5S7\\   S8\\   S9\S:\S;\\\      S<\S\\   S\\\R<                  \\R<                     4      S\\R4                     S\\R4                     S\\R4                     S=\\   S>\6S?\\7\\84      S@\\9\\\7/S4      SA\\   S\4.SB jj5       5       r:SCr;U =r<$ )JFluxControlInpaintPipeline   a  
The Flux pipeline for image inpainting using Flux-dev-Depth/Canny.

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->vaer6   prompt_embedsrI   vaetext_encoder	tokenizertext_encoder_2tokenizer_2transformerc           
      <  > [         T	U ]  5         U R                  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)rR   rS   rU   rT   rV   rW   rI   rR   r   r      )vae_scale_factor   FT)rZ   vae_latent_channelsdo_normalizedo_binarizedo_convert_grayscalerT   M      )super__init__register_modulesgetattrrH   rR   configblock_out_channelsrZ   r   image_processorlatent_channelsmask_processorr7   rT   model_max_lengthtokenizer_max_lengthdefault_sample_size)
selfrI   rR   rS   rT   rU   rV   rW   ri   rG   s
            r,   rc   #FluxControlInpaintPipeline.__init__   s    	%)## 	 	
 W^^bdikoVpVpc$((//*L*L&MPQ&Q Rvw  1$BWBWZ[B[\=DT5RV=W=W$((//99]_/!22Q6 /!%
 07t[/I/IdnnNhDNN++np 	! $' r.   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)paddingrv   
truncationreturn_lengthreturn_overflowing_tokensreturn_tensorslongestrx   r|   r   zXThe following part of your input was truncated because `max_sequence_length` is set to  	 tokens: output_hidden_statesr   rt   r<   )_execution_devicerS   rt   
isinstancestrrH   r   maybe_convert_promptrV   	input_idsshapetorchequalbatch_decoderl   loggerwarningrU   torepeatview)rn   rq   rr   rs   r<   rt   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textrQ   _seq_lens                 r,   _get_t5_prompt_embeds0FluxControlInpaintPipeline._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[r.   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	$ )Nrv   TFrw   )rx   rv   ry   r{   rz   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   rH   r   r   rT   rl   r   r   r   r   r   r   r   rS   r   pooler_outputrt   r   r   )
rn   rq   rr   r<   r   r   r   r   r   rQ   s
             r,   _get_clip_prompt_embeds2FluxControlInpaintPipeline._get_clip_prompt_embedsI  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r.   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.
)rq   r<   rr   )rq   rr   rs   r<   r   r   r<   rt   )r   r   r   _lora_scalerS   r   r   rU   r   r   r   r   rt   rW   r   zerosr   r   )rn   rq   r   r<   rr   rQ   r   rs   r   rt   text_idss              r,   encode_prompt(FluxControlInpaintPipeline.encode_promptv  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<<r.   imager0   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   r0   dim)r   listranger   r:   rR   encoder   catrf   shift_factorscaling_factor)rn   r   r0   iimage_latentss        r,   _encode_vae_image,FluxControlInpaintPipeline._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maxrI   r=   orderr7   r   )rn   r;   strengthr<   init_timestept_startr=   s          r,   get_timesteps(FluxControlInpaintPipeline.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7r.   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	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krn   s     r,   	<genexpr>:FluxControlInpaintPipeline.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`.rp   z8`max_sequence_length` cannot be greater than 512 but is )
r@   rZ   r   r   allr   r   r   r   type)rn   rq   r   r   heightwidthrQ   r   "callback_on_step_end_tensor_inputsrs   r   s   `          r,   check_inputs'FluxControlInpaintPipeline.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  */BS/HWXkWlmnn 0I*7 pHs   (G?G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<   rt   latent_image_idslatent_image_id_heightlatent_image_id_widthlatent_image_id_channelss	            r,   _prepare_latent_image_ids4FluxControlInpaintPipeline._prepare_latent_image_ids  s     !;;va8#3F#;ell6>RSTVZSZ>[#[ #3F#;ell5>QRVXYRY>Z#Z RbRhRhO7O+33":<T
  ""&">>r.   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   )r6   r   num_channels_latentsr   r   s        r,   _pack_latents(FluxControlInpaintPipeline._pack_latents%  sg     ,,z1aQVZ[Q[]^_//!Q1a3//*{uz.JL`cdLder.   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   )r6   r   r   rZ   r   num_patcheschannelss          r,   _unpack_latents*FluxControlInpaintPipeline._unpack_latents.  s     -4MM)
 c&k&6&:;<SZ$4q$89:,,zQ;
HPQMSTVWX//!Q1a3//*5.A6Qr.   c                 8    U R                   R                  5         g)z
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
N)rR   enable_slicingrn   s    r,   enable_vae_slicing-FluxControlInpaintPipeline.enable_vae_slicing?      
 	!r.   c                 8    U R                   R                  5         g)z
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
computing decoding in one step.
N)rR   disable_slicingr   s    r,   disable_vae_slicing.FluxControlInpaintPipeline.disable_vae_slicingF  s    
 	  "r.   c                 8    U R                   R                  5         g)z
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
processing larger images.
N)rR   enable_tilingr   s    r,   enable_vae_tiling,FluxControlInpaintPipeline.enable_vae_tilingM  s     	 r.   c                 8    U R                   R                  5         g)z
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
computing decoding in one step.
N)rR   disable_tilingr   s    r,   disable_vae_tiling-FluxControlInpaintPipeline.disable_vae_tilingU  r   r.   c                 l   [        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
b  U
R                  XS9U4$ 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[        XXS9nU R                  R                  XU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   r0   r   r   z'Cannot duplicate `image` of batch size z to z text prompts.)r0   r<   rt   )r   r   rH   r@   r   rZ   r   r   r   r   r   r   r   rI   scale_noiser   )rn   r   timestepr   r   r   r   rt   r<   r0   r6   r   r   r   additional_image_per_promptnoises                   r,   prepare_latents*FluxControlInpaintPipeline.prepare_latents\  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::V:9;KKK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UT..,,]eL$$W:NX]^}>>r.   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   )	r   r   Tensorrh   
preprocessr   repeat_interleaver   r   )rn   r   r   r   r   rr   r<   rt   do_classifier_free_guidance
guess_modeimage_batch_size	repeat_bys               r,   prepare_image(FluxControlInpaintPipeline.prepare_image  s     eU\\**((33EPU3VE ;;q>q "I .I''	q'94&zIIugk*Er.   c                    U R                   R                  XUS9nU R                  R                  X&US9nUSU-
  -  nUR                  XS9n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   U: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  X2R                  S   -  S:X  d  [#        SU S	UR                  S    S
35      eUR%                  X2R                  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[        R(                  " X4SS9nX,4$ )Nr   r   r   r   )sizer   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 zt mask_image 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   r   )rh   r  rj   r   r   rZ   r   nn
functionalinterpolater   r:   rR   r   rf   r   r   r@   r   r   r   )rn   r   
mask_imager   r   rr   r   r   rt   r<   r0   masked_imagemasked_image_latentss                r,   prepare_mask_latents/FluxControlInpaintPipeline.prepare_mask_latents  s    $$//E/R((33JUZ3[
J/#fBc&kd&;&;a&?@ASZD$9$9A$=>? XX((44Zuo4V
]]&]>
7
#fBa $88#/ #3DHHOOL4Q]f#g  4xx7S7S SW[W_W_WfWfWuWuu A+ 0 0 33q8 ..8\
@P@PQR@S?T U^^ 
 $**:9I9I!9L+LaQRTUVJ%%a(:5 : :1 ==B 11;FCWC]C]^_C`Ba btt 
 $8#>#>zMgMghiMj?jlmoprs#t   466f6R#11   
 ''a!5q!< 

  %yy*>)KQST//r.   c                     U R                   $ r&   )_guidance_scaler   s    r,   guidance_scale)FluxControlInpaintPipeline.guidance_scale  s    ###r.   c                     U R                   $ r&   )_joint_attention_kwargsr   s    r,   joint_attention_kwargs1FluxControlInpaintPipeline.joint_attention_kwargs   s    +++r.   c                     U R                   $ r&   )_num_timestepsr   s    r,   num_timesteps(FluxControlInpaintPipeline.num_timesteps  s    """r.   c                     U R                   $ r&   )
_interruptr   s    r,   	interrupt$FluxControlInpaintPipeline.interrupt  s    r.   g333333?   g      @pilTcontrol_imager  r  r   r   r   r;   r>   r  output_typereturn_dictr  callback_on_step_endr   c                    U=(       d    U R                   U R                  -  nU=(       d    U R                   U R                  -  nU R                  UUU	UUUUUUS9	  Xl        UU l        SU l        U R                  nUb  [        U[        5      (       a  SnO3Ub!  [        U[        5      (       a  [        U5      nOUR                  S   nU R                  nU R                  b  U R                  R                  SS5      OSnU R                  UUUUUUUUS9u  nnnU R                  R                   R"                  nUb7  UR%                  UR&                  5      nUR%                  UR&                  5      nO'U R)                  UUUUUUUUR*                  UU5
      u  nnU R,                  R/                  X7US9nUR%                  [0        R2                  S	9nUc  [4        R6                  " S
SU
-  U
5      OUn[9        U5      U R                  -  S-  [9        U5      U R                  -  S-  -  n[;        UU R<                  R                   R                  SS5      U R<                  R                   R                  SS5      U R<                  R                   R                  SS5      U R<                  R                   R                  SS5      5      n [?        U R<                  U
UUU S9u  n!n
U RA                  XU5      u  n!n
U
S:  a  [C        SU	 SU
 S35      eU!SS RE                  UU-  5      n"U RF                  R                   RH                  S-  nU RK                  UUUUU-  UUU R                  R*                  S9nURL                  S:X  a  U R                  RO                  U5      RP                  RS                  US9nX@R                  R                   RT                  -
  U R                  R                   RV                  -  nUR                  SS u  n#n$U RY                  UUU-  UU#U$5      nU R[                  UU"UU-  UUUUR*                  UUU5
      u  nn%n&n'S[9        U5      U R                  S-  -  -  n(S[9        U5      U R                  S-  -  -  n)[]        [        U!5      XR<                  R^                  -  -
  S5      n*[        U!5      U l0        U RF                  R                   Rb                  (       aE  [0        Rd                  " S/UU[0        R2                  S9n+U+Rg                  UR                  S   5      n+OSn+U Ri                  U
S9 n,[k        U!5       GH9  u  n-n.U Rl                  (       a  M  [0        Rn                  " X/SS9n/U.Rg                  UR                  S   5      R%                  UR*                  5      n0U RG                  U/U0S-  U+UUUU'U R                  SS 9	S   n1UR*                  n2U R<                  Rq                  U1U.USS!9S   nUn3U-[        U!5      S-
  :  a;  U!U-S-      n4U R<                  Rs                  U&[0        Rt                  " U4/5      U%5      n5OU&n5U RY                  U5UU-  UU(U)5      n5SU3-
  U5-  U3U-  -   nUR*                  U2:w  a>  [0        Rv                  Rx                  R{                  5       (       a  UR%                  U25      nUbJ  0 n6U H  n7[}        5       U7   U6U7'   M     U" U U-U.U65      n8U8R                  S"U5      nU8R                  S#U5      nU-[        U!5      S-
  :X  d)  U-S-   U*:  a0  U-S-   U R<                  R^                  -  S:X  a  U,R                  5         [        (       d  GM$  [        R                  " 5         GM<     SSS5        US$:X  a  UnOU R                  XXR                  5      nXR                  R                   RV                  -  U R                  R                   RT                  -   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)'af  
Function invoked when calling the pipeline for generation.

Args:
    prompt (`str` or `List[str]`, *optional*):
        The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
        instead.
    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
    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 used as the starting point. 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.
    control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
            `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
        The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
        specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
        as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
        width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
        images must be passed as a list such that each element of the list can be correctly batched for input
        to a single ControlNet.
    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)`.
    mask_image_latent (`torch.Tensor`, `List[torch.Tensor]`):
        `Tensor` representing an image batch to mask `image` generated by VAE. If not provided, the mask
        latents tensor will ge generated by `mask_image`.
    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`.
    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 7.0):
        Guidance scale as defined in [Classifier-Free Diffusion
        Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
        of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
        `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
        the text `prompt`, usually at the expense of lower image quality.
    num_images_per_prompt (`int`, *optional*, defaults to 1):
        The number of images to generate per prompt.
    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.
    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`.

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.
)rQ   r   r   rs   FNr   r   scale)rq   r   rQ   r   r<   rr   rs   r   r   )rt   g      ?r   base_image_seq_len   max_image_seq_len   r#         ?r$   ffffff?)r>   r+   z?After adjusting the num_inference_steps by strength parameter: z!, the number of pipelinesteps is z4 which is < 1 and not appropriate for this pipeline.rY   )r   r   r   r   rr   r<   rt   r   r   r   )totalr   i  )	hidden_statesr   guidancepooled_projectionsencoder_hidden_statestxt_idsimg_idsr  r(  )r(  r6   rQ   latent)r'  )images)Irm   rZ   r   r  r  r!  r   r   r   r   rH   r   r  getr   rR   rf   ri   r   r<   r  rt   rh   r  r   float32nplinspacer   r-   rI   rM   r   r@   r   rW   in_channelsr  ndimr   r3   r4   r   r   r   r   r   r   r  guidance_embedsfullexpandprogress_bar	enumerater"  r   stepr   tensorbackendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   decodepostprocessmaybe_free_model_hooksr    )9rn   rq   r   r   r&  r  r  r   r   r   r;   r>   r  rr   r0   r6   rQ   r   r'  r(  r  r)  r   rs   r<   r   r   r   r   mask
init_imager(   r+   r=   latent_timestepheight_control_imagewidth_control_imager   r   r   height_8width_8num_warmup_stepsr4  rD  r   tlatent_model_inputr   
noise_predlatents_dtype	init_masknoise_timestepinit_latents_propercallback_kwargsr   callback_outputss9                                                            r,   __call__#FluxControlInpaintPipeline.__call__  se   @ K433d6K6KKI11D4I4II 	'!5/Q 3 	 
	
  .'=$'' *VS"9"9JJvt$<$<VJ&,,Q/J'' ?C>Y>Y>eD''++GT:ko 	 '!5"7 3!  	
		
   $xx>>+#7#:#:7>>#J ==0D)-)B)B$%##*&D& ))44UQV4W
]]]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  $//66BBaG**!$99"7((.. + 
 " HHOOM:FFMMXaMbM*XX__-I-IITXX__MkMkkM8E8K8KAB8O5 "5 ..22$$#M ;?:N:N.. ;
7'7 F(=(=(ABCs5zd&;&;a&?@As9~0CnnFZFZ0ZZ\]^!)n ""22zz1#~fEMMZHw}}Q'78HH %89\!),1>>%*YY/GQ%O" 88GMM!$4588G!--"4%_%';*7$,+/+F+F % . 
 

 !(..--j!WRW-XYZ[ !	s9~))%.q1u%5N*...*D*D%u||^4D'Eu+' +8'&*&8&8'6K)KMackmt'# 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 '') =LLNw - :| ("E **7ECXCXYG!?!??488??C_C__GHHOOGO?BE((44U4TE 	##%8O!//[ :9s   H+a6a
a()
r  r!  r  r   r  rm   rh   rj   rl   rZ   )Nr   rp   NN)r   N)NNr   NNrp   NNNNNr&   )FF)=__name__
__module____qualname____firstlineno____doc__model_cpu_offload_seq_optional_componentsr   r   r   r	   r
   r   r   r   rc   r   r   r   r   r   r   r<   rt   r   r   FloatTensorfloatr   r  	Generatorr   r   r   staticmethodr   r   r   r   r   r   r   r   r  r  propertyr  r  r  r"  no_gradr   EXAMPLE_DOC_STRINGr   boolr   r   r   re  __static_attributes____classcell__)rG   s   @r,   rO   rO      s   4 M(/:$'2$' $' $	$'
 !$' '$' %$' ,$'R )-%&#&)-'+/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$ !+/ 4ol ? ?    "#!"$ -?r %* DL0\ $ $ , , # #   ]]_12 )-48$(,0)-37 $##%(, #/0MQ/359<@%* ;?KO9B#&1e0c49n%e0 5d3i01e0 "	e0
 *e0 'e0 1e0 e0 }e0 e0 !e0 e%e0 e0  (}e0 E%//43H"HIJe0  %++,!e0"   1 12#e0$ 'u'8'89%e0& c]'e0( )e0* !)c3h 8+e0, 'xc40@$0F'GH-e0. -1I/e00 !1e0 3 e0r.   rO   )r-  r/  r0  r1  )Nr4   rg  )=rB   typingr   r   r   r   r   r   numpyr=  r   transformersr	   r
   r   r   rh   r   r   loadersr   r   r   models.autoencodersr   models.transformersr   
schedulersr   utilsr   r   r   r   r   r   utils.torch_utilsr   pipeline_utilsr   pipeline_outputr    torch_xla.core.xla_modelcore	xla_modelrO  rN  
get_loggerrh  r   ru  r   rp  r-   r  rq  r   r:   r<   rM   rO   r'   r.   r,   <module>r     so    = =    E 
 1 9 9  . . / ))MM 
		H	%6 x 

 
 	

 
 ck
TLL
T-5eoo-F
T\_
T  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vg0	g0r.   