
    bi                     V   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
mZmZmZ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 dd	lmZmZmZmZ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Z0ndZ0 ejb                  e2      Z3dZ4 G d de)eee      Z5y)    )AnyCallableDictListOptionalUnionN)CLIPTextModelCLIPTokenizerT5EncoderModelT5TokenizerFast   )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   )calculate_shiftretrieve_latentsretrieve_timesteps)FluxPipelineOutput)DiffusionPipeline   )VisualClozeProcessorTFaD  
    Examples:
        ```python
        >>> import torch
        >>> from diffusers import VisualClozeGenerationPipeline, FluxFillPipeline as VisualClozeUpsamplingPipeline
        >>> from diffusers.utils import load_image
        >>> from PIL import Image

        >>> image_paths = [
        ...     # in-context examples
        ...     [
        ...         load_image(
        ...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_mask.jpg"
        ...         ),
        ...         load_image(
        ...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_incontext-example-1_image.jpg"
        ...         ),
        ...     ],
        ...     # query with the target image
        ...     [
        ...         load_image(
        ...             "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/visualcloze/visualcloze_mask2image_query_mask.jpg"
        ...         ),
        ...         None,  # No image needed for the target image
        ...     ],
        ... ]
        >>> task_prompt = "In each row, a logical task is demonstrated to achieve [IMAGE2] an aesthetically pleasing photograph based on [IMAGE1] sam 2-generated masks with rich color coding."
        >>> content_prompt = "Majestic photo of a golden eagle perched on a rocky outcrop in a mountainous landscape. The eagle is positioned in the right foreground, facing left, with its sharp beak and keen eyes prominently visible. Its plumage is a mix of dark brown and golden hues, with intricate feather details. The background features a soft-focus view of snow-capped mountains under a cloudy sky, creating a serene and grandiose atmosphere. The foreground includes rugged rocks and patches of green moss. Photorealistic, medium depth of field, soft natural lighting, cool color palette, high contrast, sharp focus on the eagle, blurred background, tranquil, majestic, wildlife photography."
        >>> pipe = VisualClozeGenerationPipeline.from_pretrained(
        ...     "VisualCloze/VisualClozePipeline-384", resolution=384, torch_dtype=torch.bfloat16
        ... )
        >>> pipe.to("cuda")

        >>> image = pipe(
        ...     task_prompt=task_prompt,
        ...     content_prompt=content_prompt,
        ...     image=image_paths,
        ...     guidance_scale=30,
        ...     num_inference_steps=30,
        ...     max_sequence_length=512,
        ...     generator=torch.Generator("cpu").manual_seed(0),
        ... ).images[0][0]

        >>> # optional, upsampling the generated image
        >>> pipe_upsample = VisualClozeUpsamplingPipeline.from_pipe(pipe)
        >>> pipe_upsample.to("cuda")

        >>> mask_image = Image.new("RGB", image.size, (255, 255, 255))

        >>> image = pipe_upsample(
        ...     image=image,
        ...     mask_image=mask_image,
        ...     prompt=content_prompt,
        ...     width=1344,
        ...     height=768,
        ...     strength=0.4,
        ...     guidance_scale=30,
        ...     num_inference_steps=30,
        ...     max_sequence_length=512,
        ...     generator=torch.Generator("cpu").manual_seed(0),
        ... ).images[0]

        >>> image.save("visualcloze.png")
        ```
c            %       b    e Zd ZdZdZg ZddgZ	 d=dedede	de
d	ed
ededef fdZ	 	 	 	 	 d>deeee   f   dededeej*                     deej,                     f
dZ	 	 d?deeee   f   dedeej*                     fdZ	 	 	 	 	 	 d@deeee   f   deeee   f   deeee   f   deej*                     dedeej2                     deej2                     dedee   fdZdej8                  dej:                  fd Zd! Z	 	 	 	 dAd"Z e!d#        Z"e!d$        Z#e!d%        Z$d& Z%d' Z&d( Z'd) Z(d* Z)d+ Z*e+d,        Z,e+d-        Z-e+d.        Z.e+d/        Z/ ej`                          e1e2      dddd0dd1dddddd2d3dddgdfdeeee   f   deeee   f   deej2                     d4ed5eee      d6edee   deeej:                  eej:                     f      deej2                     deej2                     deej2                     d7ee   d8e3d9ee4ee5f      d:ee6eee4gdf      d;ee   def"d<              Z7 xZ8S )BVisualClozeGenerationPipelinea  
    The VisualCloze pipeline for image generation with visual context. Reference:
    https://github.com/lzyhha/VisualCloze/tree/main This pipeline is designed to generate images based on visual
    in-context examples.

    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).
        resolution (`int`, *optional*, defaults to 384):
            The resolution of each image when concatenating images from the query and in-context examples.
    z.text_encoder->text_encoder_2->transformer->vaelatentsprompt_embeds	schedulervaetext_encoder	tokenizertext_encoder_2tokenizer_2transformer
resolutionc	           	         t         	|           | j                  |||||||       || _        t	        | dd       r/dt        | j                  j                  j                        dz
  z  nd| _	        t	        | dd       r | j                  j                  j                  nd| _
        t        | j                  dz  | j                  |      | _        t        | d      r"| j                  | j                  j                  nd	| _        d
| _        y )N)r(   r)   r+   r*   r,   r-   r'   r(   r   r!         )vae_scale_factorvae_latent_channelsr.   r*   M      )super__init__register_modulesr.   getattrlenr(   configblock_out_channelsr2   latent_channelsr"   image_processorhasattrr*   model_max_lengthtokenizer_max_lengthdefault_sample_size)
selfr'   r(   r)   r*   r+   r,   r-   r.   	__class__s
            z/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.pyr7   z&VisualClozeGenerationPipeline.__init__   s     	%)## 	 	
 %V]^bdikoVpc$((//*L*L&MPQ&Q Rvw CJ$PUW[B\txx>>bd3!22Q6DL`L`mw 
 07t[/IdnnNhDNN++np 	! $'     Nr!      promptnum_images_per_promptmax_sequence_lengthdevicedtypec           	         |xs | j                   }|xs | j                  j                  }t        |t              r|gn|}t        |      }t        | t              r| j                  || j                        }| j                  |d|dddd      }|j                  }| j                  |dd      j                  }	|	j                  d   |j                  d   k\  rbt        j                  ||	      sL| j                  j                  |	d d | j                  d	z
  df         }
t        j!                  d
| d|
        | j#                  |j%                  |      d      d   }| j"                  j                  }|j%                  ||      }|j                  \  }}}|j'                  d	|d	      }|j)                  ||z  |d      }|S )N
max_lengthTFpt)paddingrN   
truncationreturn_lengthreturn_overflowing_tokensreturn_tensorslongestrP   rT   r!   zXThe following part of your input was truncated because `max_sequence_length` is set to  	 tokens: output_hidden_statesr   rL   rK   )_execution_devicer)   rL   
isinstancestrr:   r   maybe_convert_promptr,   	input_idsshapetorchequalbatch_decoderA   loggerwarningr+   torepeatview)rC   rH   rI   rJ   rK   rL   
batch_sizetext_inputstext_input_idsuntruncated_idsremoved_textr&   _seq_lens                 rE   _get_t5_prompt_embedsz3VisualClozeGenerationPipeline._get_t5_prompt_embeds   s    14110**00'4&&[
d78..vt7G7GHF&& *&+ ' 
 %..**69UY*Zdd  $(<(<R(@@UcetIu++88DLeLehiLilnLnIn9opLNN'(	,A
 ++N,=,=f,E\a+bcde##))%((uV(D%++7A &,,Q0EqI%**:8M+MwXZ[rF   c           	      d   |xs | j                   }t        |t              r|gn|}t        |      }t        | t              r| j                  || j                        }| j                  |d| j                  dddd      }|j                  }| j                  |dd      j                  }|j                  d   |j                  d   k\  rlt        j                  ||      sV| j                  j                  |d d | j                  d	z
  df         }t        j                  d
| j                   d|        | j                  |j!                  |      d      }	|	j"                  }	|	j!                  | j                  j$                  |      }	|	j'                  d	|      }	|	j)                  ||z  d      }	|	S )NrN   TFrO   )rP   rN   rQ   rS   rR   rT   rU   rV   rW   r!   z\The following part of your input was truncated because CLIP can only handle sequences up to rX   rY   r[   )r\   r]   r^   r:   r   r_   r*   rA   r`   ra   rb   rc   rd   re   rf   r)   rg   pooler_outputrL   rh   ri   )
rC   rH   rI   rK   rj   rk   rl   rm   rn   r&   s
             rE   _get_clip_prompt_embedsz5VisualClozeGenerationPipeline._get_clip_prompt_embeds   s    1411'4&&[
d78..vt~~FFnn 00&+ % 
 %....SW.Xbb  $(<(<R(@@UcetIu>>66q$JcJcfgJgjlJlGl7mnLNN--.i~G )).*;*;F*CZ_)` &33%((t/@/@/F/Fv(V &,,Q0EF%**:8M+MrRrF   layout_prompttask_promptcontent_promptpooled_prompt_embeds
lora_scalec
                    |xs | j                   }|	gt        | t              rW|	| _        | j                  t
        rt        | j                  |	       | j                  t
        rt        | j                  |	       t        |t              r	|g}|g}|g}d
d}
t        t        |            D cg c]7  } |
||          d |
||          d |
||   d       j                         9 }}| j                  |||      }| j                  ||||      }| j                  ,t        | t              rt
        rt        | j                  |	       | j                  ,t        | t              rt
        rt        | j                  |	       | j                  | j                  j                  n| j                   j                  }t#        j$                  |j&                  d   d      j)                  ||	      }|||fS c c}w )a  

        Args:
            layout_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to define the number of in-context examples and the number of images involved in
                the task.
            task_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to define the task intention.
            content_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to define the content or caption of the target image to be generated.
            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.
        c                     | 	|rd|  S | S y)Nz(The last image of the last row depicts:   )rH   contents     rE   _preprocessz@VisualClozeGenerationPipeline.encode_prompt.<locals>._preprocessT  s!    !NUA&Ja[aarF    T)r~   )rH   rK   rI   )rH   rI   rJ   rK   r!   r   rK   rL   )F)r\   r]   r   _lora_scaler)   r   r   r+   r^   ranger:   striprt   rq   r   rL   r-   rb   zerosra   rg   )rC   ru   rv   rw   rK   rI   r&   rx   rJ   ry   r   irH   rL   text_idss                  rE   encode_promptz+VisualClozeGenerationPipeline.encode_prompt  s   F 1411 !j7J&K)D   ,1A!$"3"3Z@"".3C!$"5"5zBmS)*OM&-K,-N	 3}-.
 =+,-Q{;q>/J.K1[YghiYjtxMyLz{  B  B  D
 
  $;;"7  <  

 22"7 3	 3 
 ($ 349I#D$5$5zB*$ 349I#D$7$7D+/+<+<+H!!''dN^N^NdNd;;}2215q9<<FRW<X2H<<;
s   -<G5image	generatorc                    t        |t              rjt        |j                  d         D cg c]1  }t	        | j
                  j                  |||dz          ||         3 }}t        j                  |d      }n&t	        | j
                  j                  |      |      }|| j
                  j                  j                  z
  | j
                  j                  j                  z  }|S c c}w )Nr   r!   )r   dim)r]   listr   ra   r   r(   encoderb   catr;   shift_factorscaling_factor)rC   r   r   r   image_latentss        rE   _encode_vae_imagez/VisualClozeGenerationPipeline._encode_vae_imagez  s    i& u{{1~. !q1q51A!BiXYl[M  "IIm;M,TXX__U-CyYM&)E)EEIgIggs   6C'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intmaxr'   	timestepsorderr?   r   )rC   num_inference_stepsstrengthrK   init_timestept_startr   s          rE   get_timestepsz+VisualClozeGenerationPipeline.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7rF   c           
      ~    |Lt         fd|D              s8t        d j                   d|D cg c]  }| j                  vs| c}       |||t        d      |||t        d      |t        d      |-t        |t        t
        f      st        dt        |             |-t        |t        t
        f      st        dt        |             t        |t
              st        |t
              rt        |t
              rt        |t
              s#t        d	t        |       d
t        |             t        |      t        |      k7  rt        d      |D ]  }	t        |	t
              rt        |	d   t
              st        d      t        |	D 
ch c]  }
t        |
       c}
      dk7  rt        d      t        d |	d   D              st        d      |	d d D ]  }
t        d |
D              st        d        ||t        d      ||dkD  rt        d|       y y c c}w c c}
w )Nc              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0krC   s     rE   	<genexpr>z=VisualClozeGenerationPipeline.check_inputs.<locals>.<genexpr>  s#      F
23A---F
s   z2`callback_on_step_end_tensor_inputs` has to be in z, but found zOCannot provide both text `task_prompt` + `content_prompt` and `prompt_embeds`. zVMust provide either `task_prompt` + `content_prompt` or pre-computed `prompt_embeds`. z`task_prompt` is missing.z'`task_prompt` must be str or list, got z*`content_prompt` must be str or list, got z[`task_prompt` and `content_prompt` must both be lists, or both be of type str or None, got z and zP`task_prompt` and `content_prompt` must have the same length whe they are lists.r   z7Each sample in the batch must have a 2D list of images.r!   zKEach in-context example and query should contain the same number of images.c              3   $   K   | ]  }|d u  
 y wr   r}   r   imgs     rE   r   z=VisualClozeGenerationPipeline.check_inputs.<locals>.<genexpr>  s     =33$;=   rW   zGThere are no targets in the query, which should be represented as None.c              3   $   K   | ]  }|d u  
 y wr   r}   r   s     rE   r   z=VisualClozeGenerationPipeline.check_inputs.<locals>.<genexpr>  s     633$;6r   z*Images are missing in in-context examples.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`.rG   z+max_sequence_length cannot exceed 512, got )	all
ValueErrorr   r]   r^   r   typer:   any)rC   r   rv   rw   r&   rx   "callback_on_step_end_tensor_inputsrJ   r   samplerows   `          rE   check_inputsz*VisualClozeGenerationPipeline.check_inputs  s    .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 
 #~'A}G`noo>#9m>Suvv 899":kC;+OFtKGXFYZ[[%j#t.UI$~J^I_`aak4(J~t,Lk40
>SW8X ,-U43G2HJ  >"c+&66 !stt 	W!&$/z&)T7R$%^__F3SC349$%rss=&*==$%noo!#2; WC6#66()UVVW	W $)=)E U 
 */BS/HJK^J_`aa 0I*_ pH@ 4s   H5H5H:
c                    g }t        | d      D ]  \  }}|j                  d      }|j                  \  }}}	||z  dz  }
|	|z  dz  }t        j                  |
|d||      }||d<   t        j
                  |
||      d d d f   |d<   t        j
                  |||      d d d f   |d	<   |j                  d
d      }|j                  |        t        j                  |d      S )Nr!   )startr   r   r   r   ).r   ).r!   ).r   rW   r   )		enumeratesqueezera   rb   r   arangereshapeappendr   )r   r2   rK   rL   latent_image_idsidxr   channelsheightwidthnum_patches_hnum_patches_w	patch_idss                rE   _prepare_latent_image_idsz7VisualClozeGenerationPipeline._prepare_latent_image_ids  s    !%q1 	/HC++a.C&)ii#Hfe"&66!;M!%55:MM=!FZ_`I #If %]6QV WXY[_X_ `If %]6QV WX\^_X_ `If!))"a0I##I.	/ yy)q11rF   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      )ri   permuter   )r%   rj   num_channels_latentsr   r   s        rE   _pack_latentsz+VisualClozeGenerationPipeline._pack_latents  sl     ,,z+?1aQVZ[Q[]^_//!Q1a3//*v{uz.JL`cdLderF   c           	         | j                   \  }}}d}g }t        t        |            D ]  }||   }	|	d   d   |z  }
t        |	D cg c]  }|d   	 c}      |z  }||
|z  dz  z   }| d d ||f   }|j	                  ||
dz  |dz  |dz  dd      }|j                  dddddd      }|j                  ||dz  |
|      }|j                  |       |} |S c c}w )Nr   r!   r   r   r   r   )ra   r   r:   sumri   r   r   r   )r%   sizesr2   rj   num_patchesr   r   unpacked_latentsr   cur_sizer   sizer   endcur_latentss                  rE   _unpack_latentsz-VisualClozeGenerationPipeline._unpack_latents  s   ,3MM)
Ks5z" 	AQxHa[^'77FX6Ta67;KKE6E>a//C!!U3Y,/K%**:v{EQJPX\]P]_`bcdK%--aAq!Q?K%--j(u:MvW\]K##K0E	    7s   C
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)r(   enable_slicingrC   s    rE   enable_vae_slicingz0VisualClozeGenerationPipeline.enable_vae_slicing
      
 	!rF   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)r(   disable_slicingr   s    rE   disable_vae_slicingz1VisualClozeGenerationPipeline.disable_vae_slicing  s    
 	  "rF   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)r(   enable_tilingr   s    rE   enable_vae_tilingz/VisualClozeGenerationPipeline.enable_vae_tiling  s     	 rF   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)r(   disable_tilingr   s    rE   disable_vae_tilingz0VisualClozeGenerationPipeline.disable_vae_tiling   r   rF   c           	      @   |D cg c]*  }t        j                  |d      j                  ||      , }}|D cg c]*  }t        j                  |d      j                  ||      , }}| j                  ||||      }	|D cg c]  }| j	                  ||       }
}|
D cg c]  }|j                          }}t        t        |
            D ]  }|
|   j                  dd \  }}}| j                  |
|   d|||      |
|<   | j                  ||   d|||      ||<   ||   j                  dd \  }}}||   j                  d|||z  |||z  |      ||<   ||   j                  dddddd	      ||<   ||   j                  d||dz  z  ||z  ||z        ||<   | j                  ||   d||dz  z  ||z  ||z        ||<    t        j                  |
d      }
t        j                  |d      }t        j                  |d      }|
|||	fS c c}w c c}w c c}w c c}w )
z6Helper function to prepare latents for a single batch.r   r   r   r!   Nr   r   r   r   )rb   r   rg   r   r   cloner   r:   ra   r   ri   r   r   )rC   r   maskgenr2   rK   rL   r   mr   image_latentmasked_image_latentr   r   r   r   s                   rE   _prepare_latentsz.VisualClozeGenerationPipeline._prepare_latents'  s    RWW#3A&))u)EWWLPQq		!#&&fE&BQQ  99%AQSY[`a EJJS..sC8JJ6BCssyy{CCs<() 	A2>q/2G2G2K/ &%"00a!EY[achiLO%)%7%78KA8NPQSgioqv%w" 37q'--2C/ &%1gll$** )) DG 1gooaAq!Q7DG1goo$(8!(;<**))	DG ((Q$(8!(;<**))DG/	@ yy15#ii(;Cyy1%0$8HHH] XQ KCs   /H/HH"Hc	           	         t        |t              r)t        |      |k7  rt        dt        |       d| d      g }	g }
g }g }t	        t        |            D ]  }| j                  ||   ||   t        |t        j                        r|n||   |||      \  }}}}|	j                  |       |
j                  |       |j                  |       |j                  |        t        j                  |	d      }	t        j                  |
d      }
t        j                  |d      }||	j                  d   kD  r||	j                  d   z  dk(  rd||	j                  d   z  }t        j                  |	g|z  d      }	t        j                  |
g|z  d      }
t        j                  |g|z  d      }nt        d|	j                  d    d| d      t        |
j                  |||	      }| j                  j                  |
||      j                  |
      }t        j                  |	|fd      j                  |
      }	||	|d   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   zCannot expand batch size from z to z.. Batch sizes must be multiples of each other.)r   rK   rL   )rL   rW   )r]   r   r:   r   r   r   rb   	Generatorr   r   ra   r   r'   scale_noiserg   )rC   input_image
input_masktimesteprj   rL   rK   r   r2   masked_image_latentsr   masksr   r   _image_latent_masked_image_latent_mask_latent_image_idsadditional_image_per_promptnoisesr%   s                        rE   prepare_latentsz-VisualClozeGenerationPipeline.prepare_latentsZ  sw    i&3y>Z+GA#i.AQ R&<'gi   "s;'( 	7ALPLaLaA1'	5??C	ST MIM/8I !''(<=  /LL##$56	7  %yy)=1E		-Q7		%Q' ,22155066q99Q>.8<P<V<VWX<Y.Y+',yy2F1GJe1ekl'm$ %		=/<W*W]^ _		5',G"GQO 45I5O5OPQ5R4SSWXbWc dC C  m11Yv]bc..,,]HfMPPW\P]  %yy*>)FBORRY^R_,.>q.AAArF   c                     | j                   S r   )_guidance_scaler   s    rE   guidance_scalez,VisualClozeGenerationPipeline.guidance_scale  s    ###rF   c                     | j                   S r   )_joint_attention_kwargsr   s    rE   joint_attention_kwargsz4VisualClozeGenerationPipeline.joint_attention_kwargs  s    +++rF   c                     | j                   S r   )_num_timestepsr   s    rE   num_timestepsz+VisualClozeGenerationPipeline.num_timesteps  s    """rF   c                     | j                   S r   )
_interruptr   s    rE   	interruptz'VisualClozeGenerationPipeline.interrupt  s    rF   2   g      >@pilTr   sigmasr   output_typereturn_dictr   callback_on_step_endr   c                 ~     j                  ||||
|||       | _        | _        d _         j                  j                  ||| j                        }|d   t        |d   t              rd}n&|d   !t        |d   t              rt        |d         } j                  } j                   j                  j                  dd      nd} j                  |d   |d   |d	   |
|||||
	      \  }
}}t         fd|d   d   D              }t!        | j"                  j$                  j                  dd       j"                  j$                  j                  dd       j"                  j$                  j                  dd       j"                  j$                  j                  dd            }|t'        j(                  dd|z  |      n|}t+         j"                  ||||      \  }} j-                  |d|      \  }}|dd j/                  |z        } j1                  |d   |d   |||z  |
j2                  || j                        \  }	}}t5        t        |      | j"                  j6                  z  z
  d      }t        |       _         j:                  j$                  j<                  rGt?        j@                  dg||t>        jB                        }|jE                  |	jF                  d         }nd} jI                  |      5 }tK        |      D ]  \  } }! jL                  r|!jE                  |	jF                  d         jO                  |	j2                        }"t?        jP                  |	|fd      }# j;                  |#|"dz  |||
|| j                  d	      d   }$|	j2                  }% j"                  jS                  |$|!|	d       d   }	|	j2                  |%k7  r9t>        jT                  jV                  jY                         r|	jO                  |%      }	|Hi }&|D ]  }'t[               |'   |&|'<     | | |!|&      }(|(j]                  d!|	      }	|(j]                  d"|
      }
| t        |      dz
  k(  s'| dz   |kD  r/| dz    j"                  j6                  z  dk(  r|j_                          t`        stc        jd                           	 ddd       g }|d#k(  r|	}ntg        t        |	            D ]]  })|d   |)|z     }*|d$   |)|z     }+ ji                  |	|)   jk                  d      |* j                        d%   },|, jl                  j$                  jn                  z   jl                  j$                  jp                  z   }, jl                  js                  |,d       d   }- j                  ju                  |-|&      d   }-d}.g }/tK        |*d%         D ]h  \  } }0|+|    rV|d'k(  r.|/jw                  |-jy                  |.d|.|0d   z   |0d   f             n#|/jw                  |-d|0d   |.|.|0d   z   f          |.|0d   z  }.j |jw                  |/       ` |d'k7  r1t'        jz                  |D 12cg c]  }1|1D ]  }2|2d   	  c}2}1d(      } j}                          |s|fS t        |)      S # 1 sw Y   xY wc c}2}1w )*a:  
        Function invoked when calling the VisualCloze pipeline for generation.

        Args:
            task_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to define the task intention.
            content_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to define the content or caption of the target image to be generated.
            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)`.
            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 30.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.
        )r&   rx   r   rJ   Fr2   rv   Nr!   scaleru   rw   )	ru   rv   rw   r&   rx   rK   rI   rJ   ry   c              3      K   | ]6  }|D ]/  }|d    j                   z  dz  |d   j                   z  dz  z   1 8 yw)r   r   r!   Nr  )r   r   r   rC   s      rE   r   z9VisualClozeGenerationPipeline.__call__.<locals>.<genexpr>3  s\      

  !W---2tAw$BWBW7W[\7\]
]
s   <?
image_sizer   base_image_seq_len   max_image_seq_leni   
base_shiftg      ?	max_shiftgffffff?g      ?)r  mu
init_imager   r   )totalr   r   i  )	hidden_statesr   guidancepooled_projectionsencoder_hidden_statestxt_idsimg_idsr   r
  )r
  r%   r&   latenttarget_positionrW   )r	  r  )axis)images)@r   r   r   r  r>   
preprocessr2   r]   r^   r   r:   r\   r   getr   r   r   r'   r;   nplinspacer   r   rh   r   rL   r   r   r  r-   guidance_embedsrb   fullfloat32expandra   progress_barr   r  rg   r   stepbackendsmpsis_availablelocalspopupdateXLA_AVAILABLExm	mark_stepr   r   	unsqueezer(   r   r   decodepostprocessr   cropconcatenatemaybe_free_model_hooksr   )3rC   rv   rw   r   r   r  r   rI   r   r%   r&   rx   r	  r
  r   r  r   rJ   processor_outputrj   rK   ry   r   image_seq_lenr  r   latent_timestepr   r   num_warmup_stepsr  r+  r   tr   latent_model_input
noise_predlatents_dtypecallback_kwargsr   callback_outputsbcur_image_sizecur_target_position
cur_latent	cur_imager   croppedr   	sub_imagearrs3   `                                                  rE   __call__z&VisualClozeGenerationPipeline.__call__  s   x 	'!5/Q 3 	 	
  .'=$//::AVAV ; 

 M*6:FVWdFegj;kJm,8ZHXYfHgim=n-m<=J'' ?C>Y>Y>eD''++GT:ko 	 9=8J8J*?;(7+,<='!5"7 3! 9K 
9
5+X  
*<8;
 
 NN!!%%&:C@NN!!%%&94@NN!!%%lC8NN!!%%k48
 TZSaS!&9"9;NOgm);NN*
&	& *.););<OQTV\)]&	& $BQ-..z<Q/QR:>:N:N\*V$..!22 ;O 	;
7%'7 s9~0CdnnFZFZ0ZZ\]^!)n ""22zz1#~fEMMZHw}}Q'78HH %89 -	#\!), ,#1>> 88GMM!$4588G%*YY9M/NTU%V"!--"4%_%';*7$,+/+F+F % . 
 

 !(..--j!WRW-XYZ[==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 '') !LLNY,#-	#f ("E3w<( &!1,!?J!O&67H&I!j.&Y#!11'!*2F2Fq2I>[_[p[pqrtu
(488??+I+IITXX__MiMii
 HHOOJEOJ1M	 00<<YT_<`abc	();< %GAt*1-&%/#NN9>>5!UTRSW_VZ[\V]:^+_`#NN9Qa[%%RVWXRY/BY5Y+Z[T!W$E% W%#&$ e#5'^iT]'^SD	'^	'^efg 	##%8O!//e-	# -	#T (_s   F(Z,5Z,.Z9
,Z6)i  )Nr!   rG   NN)r!   N)Nr!   NNrG   N)NNNN)9__name__
__module____qualname____doc__model_cpu_offload_seq_optional_componentsr   r   r   r	   r
   r   r   r   r   r7   r   r^   r   r   rb   rK   rL   rq   rt   FloatTensorfloatr   Tensorr   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   propertyr   r   r  r  no_gradr   EXAMPLE_DOC_STRINGboolr   r   r   rN  __classcell__)rD   s   @rE   r$   r$   v   s   8 M(/: !'2!' !' $	!'
 !!' '!' %!' ,!' !'L )-%&#&)-'+/c49n%/  #/ !	/
 &/ $/j &')-	*c49n%*  #* &	*d *.%&59<@#&&*X=S$s)^,X= 3S	>*X= c49n-	X=
 &X=  #X=   1 12X= 'u'8'89X= !X= UOX=vu||  	8  !+/ >b@ 2 2(      ."#!"1If?BB $ $ , , # #   U]]_12 .204-1#%(, $/0MQ/359<@%* ;?KO9B#&%K03S	>*K0 c49n-K0 ))*	K0
 !K0 e%K0 K0  (}K0 E%//43H"HIJK0 %++,K0   1 12K0 'u'8'89K0 c]K0 K0 !)c3h 8K0  'xc40@$0F'GH!K0" -1I#K0$ !%K0 3 K0rF   r$   )6typingr   r   r   r   r   r   numpyr%  rb   transformersr	   r
   r   r   loadersr   r   r   models.autoencodersr   models.transformersr   
schedulersr   utilsr   r   r   r   r   r   utils.torch_utilsr   flux.pipeline_flux_fillr   r   r   flux.pipeline_outputr   pipeline_utilsr    visualcloze_utilsr"   torch_xla.core.xla_modelcore	xla_modelr4  r3  
get_loggerrO  re   r[  r$   r}   rF   rE   <module>ro     s    > =   V V \ \ 0 9 9  . [ [ 5 . 3 ))MM 
		H	%@ FB0	B0rF   