
    bi                        d dl Z d dlmZmZmZmZmZmZ d dlZ	d dl
Zd dlZd dlmZmZ ddlmZmZ ddlmZ ddlmZmZ ddlmZ dd	lmZmZmZ dd
lmZ ddl m!Z! ddl"m#Z#  e       rd dl$m%c m&Z' dZ(ndZ( ejR                  e*      Z+dZ,	 d"dejZ                  deej\                     de/fdZ0	 	 	 	 d#de1de1de2de2fdZ3	 	 	 	 d$dee1   deee/ejh                  f      deee1      deee2      fdZ5 G d  d!e!e      Z6y)%    N)AnyCallableDictListOptionalUnion)"Qwen2_5_VLForConditionalGenerationQwen2Tokenizer   )PipelineImageInputVaeImageProcessor)QwenImageLoraLoaderMixin)AutoencoderKLQwenImageQwenImageTransformer2DModel)FlowMatchEulerDiscreteScheduler)is_torch_xla_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipeline   )QwenImagePipelineOutputTFa  
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import QwenImageInpaintPipeline
        >>> from diffusers.utils import load_image

        >>> pipe = QwenImageInpaintPipeline.from_pretrained("Qwen/Qwen-Image", torch_dtype=torch.bfloat16)
        >>> pipe.to("cuda")
        >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
        >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
        >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
        >>> source = load_image(img_url)
        >>> mask = load_image(mask_url)
        >>> image = pipe(prompt=prompt, negative_prompt=" ", image=source, mask_image=mask, strength=0.85).images[0]
        >>> image.save("qwenimage_inpainting.png")
        ```
encoder_output	generatorsample_modec                     t        | d      r |dk(  r| j                  j                  |      S t        | d      r|dk(  r| j                  j                         S t        | d      r| j                  S t        d      )Nlatent_distsampleargmaxlatentsz3Could not access latents of provided encoder_output)hasattrr   r   moder!   AttributeError)r   r   r   s      s/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/qwenimage/pipeline_qwenimage_inpaint.pyretrieve_latentsr&   2   st     ~}-+2I))00;;		/K84K))..00		+%%%RSS    base_seq_lenmax_seq_len
base_shift	max_shiftc                 <    ||z
  ||z
  z  }|||z  z
  }| |z  |z   }|S N )image_seq_lenr(   r)   r*   r+   mbmus           r%   calculate_shiftr3   @   s;     
Z	K,$>?AQ%%A		Q	BIr'   num_inference_stepsdevice	timestepssigmasc                    ||t        d      |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS |dt        t        j                  | j                        j
                  j                               v }|st        d| j                   d       | j                  d
||d| | j                  }t        |      }||fS  | j                  |fd	|i| | j                  }||fS )a  
    Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
    custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.

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

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

ValueErrorsetinspect	signatureset_timesteps
parameterskeys	__class__r6   len)	schedulerr4   r5   r6   r7   kwargsaccepts_timestepsaccept_sigmass           r%   retrieve_timestepsrF   N   s   > !3tuu'3w/@/@AXAX/Y/d/d/i/i/k+ll .y/B/B.C Da b  	 	M)FMfM''	!)n ))) 
	 C(9(9):Q:Q(R(](](b(b(d$ee.y/B/B.C D_ `  	 	GvfGG''	!)n ))) 	 	 3MFMfM''	)))r'   c            7       j    e Zd ZdZdZddgZdededede	d	e
f
 fd
Zdej                  dej                  fdZ	 	 	 dDdeeee   f   deej&                     deej(                     fdZdej                  dej,                  fdZd Z	 	 	 	 	 dEdeeee   f   deej&                     dedeej                     deej                     defdZ	 	 	 	 	 	 	 	 dFdZed        Zed        Zd Zd  Z d! Z!d" Z"	 dGd#Z#d$ Z$e%d%        Z&e%d&        Z'e%d'        Z(e%d(        Z)e%d)        Z* ejV                          e,e-      ddd*ddddddd+d,dd-dddddddd.d/dddgd0fdeeee   f   d1eeee   f   d2e.de/d3e/d4e/d5ee   d6ee   d7ee   d8e.d9ed:eee.      d;e.dedeeej,                  eej,                     f      deej                     deej                     deej                     d<eej                     d=eej                     d>ee   d?e0d@ee1ee2f      dAee3eee1gdf      dBee   def4dC              Z4 xZ5S )HQwenImageInpaintPipelinea  
    The QwenImage pipeline for text-to-image generation.

    Args:
        transformer ([`QwenImageTransformer2DModel`]):
            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 ([`Qwen2.5-VL-7B-Instruct`]):
            [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct), specifically the
            [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) variant.
        tokenizer (`QwenTokenizer`):
            Tokenizer of class
            [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
    ztext_encoder->transformer->vaer!   prompt_embedsrB   vaetext_encoder	tokenizertransformerc                    t         |           | j                  |||||       t        | dd       r"dt	        | j
                  j                        z  nd| _        t        | dd       r | j
                  j                  j                  nd| _
        t        | j                  dz  | j                        | _        t        | j                  dz  | j                  ddd	      | _        d
| _        d| _        d| _        d| _        y )N)rJ   rK   rL   rM   rB   rJ   r         )vae_scale_factorvae_latent_channelsFT)rQ   rR   do_normalizedo_binarizedo_convert_grayscale   z<|im_start|>system
Describe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|im_end|>
<|im_start|>user
{}<|im_end|>
<|im_start|>assistant
"      )super__init__register_modulesgetattrrA   rJ   temperal_downsamplerQ   configz_dimlatent_channelsr   image_processormask_processortokenizer_max_lengthprompt_template_encode prompt_template_encode_start_idxdefault_sample_size)selfrB   rJ   rK   rL   rM   r@   s         r%   rZ   z!QwenImageInpaintPipeline.__init__   s    	%# 	 	
 KRRVX]_cJdS)E)E%F Fjk 9@eT8Rtxx44XZ0!22Q6DL`L` 
 0!22Q6 $ 4 4!%
 %)! 'E#02-#& r'   hidden_statesmaskc                     |j                         }|j                  d      }||   }t        j                  ||j	                         d      }|S )Nr   dimr   )boolsumtorchsplittolist)rg   rh   ri   	bool_maskvalid_lengthsselectedsplit_results          r%   _extract_masked_hiddenz/QwenImageInpaintPipeline._extract_masked_hidden   sH    IIK	!!, +{{8]-A-A-CKr'   Npromptr5   dtypec                    |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}| j
                  }| j                  }|D cg c]  }|j                  |       }}| j                  || j                  |z   ddd      j                  |      }| j                  |j                  |j                  d      }	|	j                  d   }
| j                  |
|j                        }|D cg c]  }||d  	 }}|D cg c]A  }t        j                   |j#                  d      t        j$                  |j&                        C }}t)        |D cg c]  }|j#                  d       c}      }t        j*                  |D cg c]J  }t        j,                  ||j/                  ||j#                  d      z
  |j#                  d            g      L c}      }t        j*                  |D cg c]:  }t        j,                  ||j/                  ||j#                  d      z
        g      < c}      }|j                  ||      }||fS c c}w c c}w c c}w c c}w c c}w c c}w )	NTpt)
max_lengthpadding
truncationreturn_tensors)	input_idsattention_maskoutput_hidden_statesr   )rx   r5   r   )_execution_devicerK   rx   
isinstancestrrd   re   formatrL   rc   tor   r   rh   rv   ro   onessizelongr5   maxstackcat	new_zeros)rg   rw   r5   rx   templatedrop_idxetxt
txt_tokensencoder_hidden_statesrh   split_hidden_statesattn_mask_listr)   urI   encoder_attention_masks                    r%   _get_qwen_prompt_embedsz0QwenImageInpaintPipeline._get_qwen_prompt_embeds   s1    14110**00'4&&..88+12axq!22^^D55@$[_pt $ 

"V* 	 !% 1 1 **%44!% !2 !

 .;;B?"99-IbIbc5HIq|II\opWX%**QVVAYejjRpp.AB166!9BCVijQRUYY1;;{QVVAY'>q	JKLj
 "'KYZaUYY1;;{QVVAY'>?@AZ"
 &((uV(D444/ 3 JpBj [s&   I?IAI$"I)AI.=?I3imager   c                    t        |t              rjt        |j                  d         D cg c]1  }t	        | j
                  j                  |||dz          ||         3 }}t        j                  |d      }n&t	        | j
                  j                  |      |      }t        j                  | j
                  j                  j                        j                  d| j
                  j                  j                  ddd      j                  |j                  |j                         }dt        j                  | j
                  j                  j"                        j                  d| j
                  j                  j                  ddd      j                  |j                  |j                         z  }||z
  |z  }|S c c}w )Nr   r   )r   rk         ?)r   listrangeshaper&   rJ   encodero   r   tensorr^   latents_meanviewr_   r   r5   rx   latents_std)rg   r   r   iimage_latentsr   r   s          r%   _encode_vae_imagez*QwenImageInpaintPipeline._encode_vae_image   sa   i& u{{1~. !q1q51A!BiXYl[M  "IIm;M,TXX__U-CyYM LL556T!TXX__**Aq!4R$$m&9&9: 	
 ELL)D)DEJJ1dhhooNcNcefhiklmpp  -"5"5
 
 '5D's   6F>c                 N   t        ||z  |      }t        t        ||z
  d            }| j                  j                  || j                  j
                  z  d  }t        | j                  d      r2| j                  j                  || j                  j
                  z         |||z
  fS )Nr   set_begin_index)minintr   rB   r6   orderr"   r   )rg   r4   strengthr5   init_timestept_startr6   s          r%   get_timestepsz&QwenImageInpaintPipeline.get_timesteps  s    /(:<OPc-=qABNN,,Wt~~7K7K-K-MN	4>>#45NN**7T^^5I5I+IJ-777r'   r   num_images_per_promptprompt_embeds_maskmax_sequence_lengthc                    |xs | j                   }t        |t              r|gn|}|t        |      n|j                  d   }|| j                  ||      \  }}|ddd|f   }|ddd|f   }|j                  \  }}	}|j                  d|d      }|j                  ||z  |	d      }|j                  d|d      }|j                  ||z  |	      }||fS )a1  

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            device: (`torch.device`):
                torch device
            num_images_per_prompt (`int`):
                number of images that should be generated per prompt
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
        Nr   r   r   )r   r   r   rA   r   r   repeatr   )
rg   rw   r5   r   rI   r   r   
batch_size_seq_lens
             r%   encode_promptz&QwenImageInpaintPipeline.encode_prompt  s   , 1411'4&&$1$9S[}?R?RST?U
 040L0LVU[0\-M-%a)=*=)=&=>/3G4G3G0GH%++7A%,,Q0EqI%**:8M+MwXZ[/66q:OQRS/44ZBW5WY`a000r'   c           
          |dk  s|dkD  rt        d|       | j                  dz  z  dk7  s| j                  dz  z  dk7  r,t        j                  d j                  dz   d| d| d       |Lt	         fd	|D              s8t        d
 j
                   d|D cg c]  }| j
                  vs| c}       ||	t        d| d|	 d      ||	t        d      |7t        |t              s't        |t              st        dt        |             ||
t        d| d|
 d      |	|t        d      |
|t        d      |t        |t        j                  j                        st        dt        |       d      t        |t        j                  j                        st        dt        |       d      |dk7  rt        d| d      ||dkD  rt        d|       y y c c}w )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   :   K   | ]  }|j                   v   y wr-   )_callback_tensor_inputs).0krg   s     r%   	<genexpr>z8QwenImageInpaintPipeline.check_inputs.<locals>.<genexpr>[  s#      F
23A---F
s   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zCannot forward both `prompt`: z and `prompt_embeds`: z2. Please make sure to only forward one of the two.zeProvide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined.z2`prompt` has to be of type `str` or `list` but is z'Cannot forward both `negative_prompt`: z and `negative_prompt_embeds`: zIf `prompt_embeds` are provided, `prompt_embeds_mask` also have to be passed. Make sure to generate `prompt_embeds_mask` from the same text encoder that was used to generate `prompt_embeds`.zIf `negative_prompt_embeds` are provided, `negative_prompt_embeds_mask` also have to be passed. Make sure to generate `negative_prompt_embeds_mask` from the same text encoder that was used to generate `negative_prompt_embeds`.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 rV   z9`max_sequence_length` cannot be greater than 1024 but is )r9   rQ   loggerwarningallr   r   r   r   typePILImage)rg   rw   r   
mask_imager   heightwidthoutput_typenegative_promptrI   negative_prompt_embedsr   negative_prompt_embeds_mask"callback_on_step_end_tensor_inputspadding_mask_cropr   r   s   `                r%   check_inputsz%QwenImageInpaintPipeline.check_inputsA  s   $ a<8a<QRZQ[\]]T**Q./14AVAVYZAZ8[_`8`NN?@U@UXY@Y?ZZcdjckkpqvpw  x`  a .9# F
7YF
 C
 DTEaEaDbbn  |^  pHvw  bc  ko  kG  kG  bGpq  pH  oI  J  -";08N}o ^0 0  ^ 5w  FC)@TZ\`IaQRVW]R^Q_`aa&+A+M9/9J K*++]_ 
 $);)C Q  "-2M2U u  (eSYY__5 `aefkal`mmno  j#))//: Z(),  e# #cdocppq!rss*/BT/IXYlXmnoo 0J*U pHs   G51G5c                     | j                  |||dz  d|dz  d      } | j                  dddddd      } | j                  ||dz  |dz  z  |dz        } | S )Nr   r      r   r      )r   permutereshape)r!   r   num_channels_latentsr   r   s        r%   _pack_latentsz&QwenImageInpaintPipeline._pack_latents  sl     ,,z+?1aQVZ[Q[]^_//!Q1a3//*v{uz.JL`cdLder'   c                    | j                   \  }}}dt        |      |dz  z  z  }dt        |      |dz  z  z  }| j                  ||dz  |dz  |dz  dd      } | j                  dddddd      } | j	                  ||dz  d||      } | S )Nr   r   r   r   r   r   )r   r   r   r   r   )r!   r   r   rQ   r   num_patcheschannelss          r%   _unpack_latentsz(QwenImageInpaintPipeline._unpack_latents  s     -4MM)
K c&k&6&:;<SZ$4q$89:,,z6Q;
HPQMSTVWX//!Q1a3//*h5.A1feTr'   c                 8    | j                   j                          y)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)rJ   enable_slicingrg   s    r%   enable_vae_slicingz+QwenImageInpaintPipeline.enable_vae_slicing      
 	!r'   c                 8    | j                   j                          y)z
        Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
        computing decoding in one step.
        N)rJ   disable_slicingr   s    r%   disable_vae_slicingz,QwenImageInpaintPipeline.disable_vae_slicing  s    
 	  "r'   c                 8    | j                   j                          y)a  
        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)rJ   enable_tilingr   s    r%   enable_vae_tilingz*QwenImageInpaintPipeline.enable_vae_tiling  s     	 r'   c                 8    | j                   j                          y)z
        Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
        computing decoding in one step.
        N)rJ   disable_tilingr   s    r%   disable_vae_tilingz+QwenImageInpaintPipeline.disable_vae_tiling  r   r'   c                    t        |	t              r)t        |	      |k7  rt        dt        |	       d| d      dt	        |      | j
                  dz  z  z  }dt	        |      | j
                  dz  z  z  }|d|||f}|j                         dk(  r|j                  d      }n0|j                         dk7  rt        d|j                          d	      |
|
j                  ||
      S |j                  ||
      }|j                  d   | j                  k7  r| j                  ||	      }n|}||j                  d   kD  rC||j                  d   z  dk(  r.||j                  d   z  }t        j                  |g|z  d      }n^||j                  d   kD  r4||j                  d   z  dk7  rt        d|j                  d    d| d      t        j                  |gd      }|j                  dd      }|
-t        ||	||      }| j                   j#                  |||      }
n|
j                  |      }|}
| j%                  |||||      }| j%                  |||||      }| j%                  |
||||      }
|
||fS )Nz/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.r   r   r   r    Expected image dims 4 or 5, got r   r5   rx   r   r   r   rk   z'Cannot duplicate `image` of batch size z to z text prompts.)r   r5   rx   )r   r   rA   r9   r   rQ   rl   	unsqueezer   r   r`   r   ro   r   	transposer   rB   scale_noiser   )rg   r   timestepr   r   r   r   rx   r5   r   r!   r   r   additional_image_per_promptnoises                  r%   prepare_latentsz(QwenImageInpaintPipeline.prepare_latents  s    i&3y>Z+GA#i.AQ R&<'gi  c&kd&;&;a&?@ASZD$9$9A$=>?Q 4feD 99;!OOA&EYY[A?		}ANOO::V5:99e4;;q>T111 22)2TM!M++A..:@S@STU@V3VZ[3[*48K8KA8N*N'!II}o8S&SYZ[M---a00Z-BUBUVWBX5X\]5]9-:M:Ma:P9QQUV`Uaaop  "II}o1=M%//15? )FRWXEnn00%PGJJv&EG""5*6JFTYZ**=*FZ\bdij$$Wj:NPVX]^},,r'   c                    dt        |      | j                  dz  z  z  }dt        |      | j                  dz  z  z  }t        j                  j                  j                  |||f      }|j                  |	|      }||z  }|j                         dk(  r|j                  d      }n0|j                         dk7  rt        d|j                          d      |j                  |	|      }|j                  d   | j                  k(  r|}n| j                  ||
	      }|j                  d
   |k  rX||j                  d
   z  d
k(  st        d| d|j                  d
    d      |j                  ||j                  d
   z  ddd      }|j                  d
   |k  rY||j                  d
   z  d
k(  st        d| d|j                  d
    d      |j                  ||j                  d
   z  dddd      }|j                  |	|      }| j                  |||||      }| j                  |j                  d|dd      ||||      }||fS )Nr   )r   r   r   r   r   r   r   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   rQ   ro   nn
functionalinterpolater   rl   r   r9   r   r`   r   r   r   )rg   ri   masked_imager   r   r   r   r   rx   r5   r   masked_image_latentss               r%   prepare_mask_latentsz-QwenImageInpaintPipeline.prepare_mask_latents  s    c&kd&;&;a&?@ASZD$9$9A$=>? xx""..t65/.JwwfEw2"77
"'11!4L1$?@P@P@R?SSTUVV#fEBa D$8$88#/ #'#9#9Xa#9#b  ::a=:%

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

1 O^^ 
 ;;zTZZ]:Aq!DD%%a(:5 4 : :1 ==B 11;FCWC]C]^_C`Ba btt 
 $8#>#>zMaMgMghiMj?jlmoprsuv#w   466fE6R#11   
 !!KK/A6 
 )))r'   c                     | j                   S r-   )_guidance_scaler   s    r%   guidance_scalez'QwenImageInpaintPipeline.guidance_scaleO  s    ###r'   c                     | j                   S r-   )_attention_kwargsr   s    r%   attention_kwargsz)QwenImageInpaintPipeline.attention_kwargsS      %%%r'   c                     | j                   S r-   )_num_timestepsr   s    r%   num_timestepsz&QwenImageInpaintPipeline.num_timestepsW  s    """r'   c                     | j                   S r-   )_current_timestepr   s    r%   current_timestepz)QwenImageInpaintPipeline.current_timestep[  r  r'   c                     | j                   S r-   )
_interruptr   s    r%   	interruptz"QwenImageInpaintPipeline.interrupt_  s    r'   g      @g333333?2   r   r   Ti   r   true_cfg_scaler   r   r   r   r   r   r4   r7   r   r   r   r   return_dictr  callback_on_step_endr   c                 \   |xs | j                   | j                  z  }|xs | j                   | j                  z  }| j                  ||||
||||||||||	|       || _        || _        d| _        d| _        |	"| j                  j                  ||||	      }d}nd}d}|}| j                  j                  |||||      }|j                  t        j                        }|t        |t              rd	}n-|t        |t               rt#        |      }n|j$                  d
   }| j&                  } |duxs
 |duxr |du}!|d	kD  xr |!}"| j)                  |||| ||      \  }}|"r| j)                  |||| ||      \  }}|t+        j,                  dd	|z  |      n|}t/        |      | j                  z  dz  t/        |      | j                  z  dz  z  }#t1        |#| j2                  j4                  j7                  dd      | j2                  j4                  j7                  dd      | j2                  j4                  j7                  dd      | j2                  j4                  j7                  dd            }$t9        | j2                  || ||$      \  }%}| j;                  ||
|       \  }%}|d	k  rt=        d|
 d| d      |%dd	 j?                  ||z        }&| j@                  j4                  jB                  dz  }'| jE                  ||&||z  |'|||jF                  | ||
      \  }}(})| j                  j                  |||||      }*|	||*dk  z  }+n|}+| jI                  |*|+||'||||jF                  | |
      \  },}d	|| j                  z  dz  || j                  z  dz  fgg|z  }-tK        t#        |%      || j2                  jL                  z  z
  d
      }.t#        |%      | _'        | j@                  j4                  jP                  rGt        jR                  d	g|| t        j                        }/|/jU                  |j$                  d
         }/nd}/| jV                  i | _        | |jY                  d	      j[                         nd}0| |jY                  d	      j[                         nd}1| j]                  |      5 }2t_        |%      D ]  \  }3}4| j`                  r|4| _        |4jU                  |j$                  d
         j                  |jF                        }5| j@                  jc                  d      5  | jA                  ||5d z  |/|||-|0| jV                  d!	      d
   }6ddd       |"r| j@                  jc                  d"      5  | jA                  ||5d z  |/|||-|1| jV                  d!	      d
   }7ddd       7|6|7z
  z  z   }8t        jd                  |6d#d$%      }9t        jd                  |8d#d$%      }:|8|9|:z  z  }6|jF                  };| j2                  jg                  6|4|d&      d
   }|)}<|,}=|3t#        |%      d	z
  k  r9|%|3d	z      }>| j2                  ji                  |<t        jj                  |>g      |(      }<d	|=z
  |<z  |=|z  z   }|jF                  |;k7  r9t        jl                  jn                  jq                         r|j                  |;      }|Hi }?|D ]  }@ts               |@   |?|@<     || |3|4|?      }A|Aju                  d'|      }|Aju                  d(|      }|3t#        |%      d	z
  k(  s'|3d	z   |.kD  r/|3d	z   | j2                  jL                  z  d
k(  r|2jw                          tx        st{        j|                           	 ddd       d| _        |d)k(  r|}n| j                  |||| j                        }|j                  | j                  jF                        }t        jj                  | j                  j4                  j                        j                  d	| j                  j4                  j                  d	d	d	      j                  |j                  |jF                        }Bdt        jj                  | j                  j4                  j                        j                  d	| j                  j4                  j                  d	d	d	      j                  |j                  |jF                        z  }C||Cz  |Bz   }| j                  j                  |d&      d
   ddddd
f   }| j                  j                  ||*      }|	+|D 3cg c]   }3| j                  j                  |||3|      " }}3| j                          |s|fS t        |+      S # 1 sw Y   ,xY w# 1 sw Y   xY w# 1 sw Y   'xY wc c}3w ),a#  
        Function invoked when calling the pipeline for generation.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
                instead.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
                not greater than `1`).
            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.
            true_cfg_scale (`float`, *optional*, defaults to 1.0):
                When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
            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.
            padding_mask_crop (`int`, *optional*, defaults to `None`):
                The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
                image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
                with the same aspect ration of the image and contains all masked area, and then expand that area based
                on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
                resizing to the original image size for inpainting. This is useful when the masked area is small while
                the image is large and contain information irrelevant for inpainting, such as background.
            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 3.5):
                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.

                This parameter in the pipeline is there to support future guidance-distilled models when they come up.
                Note that passing `guidance_scale` to the pipeline is ineffective. To enable classifier-free guidance,
                please pass `true_cfg_scale` and `negative_prompt` (even an empty negative prompt like " ") should
                enable classifier-free guidance computations.
            num_images_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
                One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
                to make generation deterministic.
            latents (`torch.Tensor`, *optional*):
                Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor will be generated by sampling using the supplied random `generator`.
            prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            negative_prompt_embeds (`torch.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            output_type (`str`, *optional*, defaults to `"pil"`):
                The output format of the generate image. Choose between
                [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~pipelines.qwenimage.QwenImagePipelineOutput`] instead of a plain tuple.
            attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            callback_on_step_end (`Callable`, *optional*):
                A function that calls at the end of each denoising steps during the inference. The function is called
                with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
                callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
                `callback_on_step_end_tensor_inputs`.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
                will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
                `._callback_tensor_inputs` attribute of your pipeline class.
            max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.

        Examples:

        Returns:
            [`~pipelines.qwenimage.QwenImagePipelineOutput`] or `tuple`:
            [`~pipelines.qwenimage.QwenImagePipelineOutput`] if `return_dict` is True, otherwise a `tuple`. When
            returning a tuple, the first element is a list with the generated images.
        )	r   r   rI   r   r   r   r   r   r   NF)padfilldefault)r   r   crops_coordsresize_mode)rx   r   r   )rw   rI   r   r5   r   r   r   r   base_image_seq_len   max_image_seq_len   r*         ?r+   ffffff?)r7   r2   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  r  r   rk   )totalcondi  )	rh   r   guidanceencoder_hidden_states_maskr   
img_shapestxt_seq_lensr  r  uncondr   T)rl   keepdim)r  r!   rI   latent)r   )images)Krf   rQ   r   r   r  r  r  rb   get_crop_regionra   
preprocessr   ro   float32r   r   r   rA   r   r   r   nplinspacer   r3   rB   r^   getrF   r   r9   r   rM   in_channelsr   rx   r   r   r   r  guidance_embedsfullexpandr  rn   rq   progress_bar	enumerater  cache_contextnormstepr   r   backendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   rJ   r   r   r_   r5   r   decodepostprocessapply_overlaymaybe_free_model_hooksr   )Drg   rw   r   r  r   r   r   r   r   r   r   r4   r7   r   r   r   r!   rI   r   r   r   r   r  r  r  r   r   r  r  original_image
init_imager   r5   has_neg_promptdo_true_cfgr/   r2   r6   latent_timestepr   r   r   mask_conditionr   ri   r!  num_warmup_stepsr  r"  negative_txt_seq_lensr1  r   tr   
noise_predneg_noise_pred	comb_pred	cond_norm
noise_normlatents_dtypeinit_latents_proper	init_masknoise_timestepcallback_kwargsr   callback_outputsr   r   sD                                                                       r%   __call__z!QwenImageInpaintPipeline.__call__c  s@
   V K433d6K6KKI11D4I4II 	#+'#91(C/Q/ 3 	 	
$  .!1!% (..>>z5RX^o>pL KL#K))44&LVa 5 

  ]]]7
 *VS"9JJvt$<VJ&,,Q/J''(4 
"$.Z3NVZ3Z 	 %q(;^,0,>,>'1"7 3 -? -
)) BFBTBT&4#>&;$7 CU C?"$? TZSaS!&9"9;NOgmV(=(==Bs5zUYUjUjGjnoGopNN!!%%&:C@NN!!%%&94@NN!!%%lC8NN!!%%k48
 *<NN*
&	& *.););<OQY[a)b&	&"QRZQ[ \/00df  $BQ-..z<Q/QR  $//66BBaG(,(<(<.. )
% ,,77vUZf 8 
  '%#)=>L/L%)%>%> !&
"" 6T%:%::a?$J_J_A_cdAdefgjtt
s9~0CdnnFZFZ0ZZ\]^!)n ""22zz1#~fEMMZHw}}Q'78HH  (%'D"ASA_)--!-4;;=ei?Z?f'+++299;lp 	
 %89 K	#\!), J#1>>)*&88GMM!$4588G%%33F; !%!1!1&-!)D!)3E.;#-%1)-)>)>$) "2 
" 
"J ))77A )-)9)9*1%-_%-7R2H'1)>-1-B-B(- *: 
* 
* !/:P^C^1_ _I %

:2t LI!&I2t!LJ!*i*.D!EJ !(..--j!WRW-XYZ[ '4# 	s9~))%.q1u%5N*...*D*D+U\\>:J-KU+' y=,??)gBUU==M1~~))668")**]";'3&(O? 9-3Xa[*9';D!Q'X$.229gFG$4$8$8-$XM I**A9I/IqSTuX\XfXfXlXlNlpqNq '') LLNUJ#K	#Z "&("E**7FE4CXCXYGjj0GTXX__99:a..1a8GNNGMM2 
 TXX__-H-H I N NqRVRZRZRaRaRgRgijlmop q t t! K +l:GHHOOGO?B1a7KE((44U4TE ,mrhiD((66z>STVbc 
 	##%8O&e44G  -K	# K	#BsJ   4A9f-+f%f=+f(F5ff:%f)fffff&)NNN)Nr   NNrV   )NNNNNNNNr-   )6__name__
__module____qualname____doc__model_cpu_offload_seqr   r   r   r	   r
   r   rZ   ro   Tensorrv   r   r   r   r   r5   rx   r   	Generatorr   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   propertyr   r  r  r	  r  no_gradr   EXAMPLE_DOC_STRINGfloatr   rm   r   r   r   rW  __classcell__)r@   s   @r%   rH   rH      sb   $ =(/:"'2"' $"' 9	"'
 ""' 1"'JELL   )-)-'+	$5c49n%$5 &$5 $	$5Nu||  0	8 *.%&0459#''1c49n%'1 &'1  #	'1
  -'1 %U\\2'1 !'1d #$(+/ !IpV    "#!"$ ?-BI*V $ $ & & # # & &   U]]_12 )-15 #$()-37 $#+/#%(, #%&MQ*.04599=>B%* 59KO9B#&7R5c49n%R5 sDI~.R5 	R5
 "R5 'R5 1R5 R5 }R5 $C=R5 R5 !R5 e%R5 R5  #R5  E%//43H"HIJ!R5" %,,'#R5$  -%R5& %U\\2'R5( !) 6)R5* &.ell%;+R5, c]-R5. /R50 #4S>21R52 'xc40@$0F'GH3R54 -1I5R56 !7R5 3 R5r'   rH   )Nr   )r  r  r  r  )NNNN)7r;   typingr   r   r   r   r   r   numpyr*  	PIL.Imager   ro   transformersr	   r
   ra   r   r   loadersr   modelsr   r   
schedulersr   utilsr   r   r   utils.torch_utilsr   pipeline_utilsr   pipeline_outputr   torch_xla.core.xla_modelcore	xla_modelr=  r<  
get_loggerrX  r   rb  r]  r^  r   r&   r   rc  r3   r5   rF   rH   r.   r'   r%   <module>rt     sL    = =    K D / I 9 O O - . 4 ))MM 
		H	% , ck
TLL
T-5eoo-F
T\_
T  

 
 	

 
  *.15%)$(8*!#8* U3,-.8* S	"	8*
 T%[!8*vn502J n5r'   