
    bi]                     (   d dl mZmZmZmZmZmZ d dlZd dlm	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 ddlmZ ddl m!Z! ddl"m#Z# ddl$m%Z%  e       rdZ&ndZ& ejN                  e(      Z)dZ* G d de#eee      Z+y)    )AnyCallableDictListOptionalUnionN)Image)CLIPTextModelCLIPTokenizerT5EncoderModelT5TokenizerFast   )FluxLoraLoaderMixinFromSingleFileMixinTextualInversionLoaderMixin)AutoencoderKL)FluxTransformer2DModel)FlowMatchEulerDiscreteScheduler)is_torch_xla_availableloggingreplace_example_docstring   )FluxFillPipeline)FluxPipelineOutput)DiffusionPipeline   )VisualClozeGenerationPipelineTFa
  
    Examples:
        ```python
        >>> import torch
        >>> from diffusers import VisualClozePipeline
        >>> from diffusers.utils import load_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 = VisualClozePipeline.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,
        ...     upsampling_width=1344,
        ...     upsampling_height=768,
        ...     upsampling_strength=0.4,
        ...     guidance_scale=30,
        ...     num_inference_steps=30,
        ...     max_sequence_length=512,
        ...     generator=torch.Generator("cpu").manual_seed(0),
        ... ).images[0][0]
        >>> image.save("visualcloze.png")
        ```
c            +       @    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Z ej$                          ee      ddddddddddddddddddgddfdeeee   f   deeee   f   deej2                     dee   dee   dedeee      dedee   d eeej6                  eej6                     f      deej2                     deej2                     d!eej2                     d"ee   d#ed$eeeef      d%eeeeegdf      d&ee   d'ed(ef(d)              Z  xZ!S ),VisualClozePipelinea  
    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        ||||||||      | _        t        |||||||      | _        y )N)r#   r$   r&   r%   r'   r(   r"   )r#   r$   r&   r%   r'   r(   r"   r)   )super__init__register_modulesr   generation_pipeVisualClozeUpsamplingPipelineupsampling_pipe)
selfr"   r#   r$   r%   r&   r'   r(   r)   	__class__s
            x/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/visualcloze/pipeline_visualcloze_combined.pyr,   zVisualClozePipeline.__init__   s     	%)## 	 	
  =%)##!	 
  =%)## 
    Nc           
          |dk  s|dkD  rt        d|       |>| j                  dz  z  dk7  r)t        j                  d j                  dz   d| d       |>| j                  dz  z  dk7  r)t        j                  d j                  dz   d| d       |	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 )Nr   r   z2The value of strength should in [0.0, 1.0] but is r   z*`upsampling_height`has to be divisible by z	 but are z(. Dimensions will be resized accordinglyz+`upsampling_width` have to be divisible by c              3   :   K   | ]  }|j                   v   y wN)_callback_tensor_inputs).0kr1   s     r3   	<genexpr>z3VisualClozePipeline.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.z7Each sample in the batch must have a 2D list of images.zKEach in-context example and query should contain the same number of images.c              3   $   K   | ]  }|d u  
 y wr7    r9   imgs     r3   r;   z3VisualClozePipeline.check_inputs.<locals>.<genexpr>   s     =33$;=   zGThere are no targets in the query, which should be represented as None.c              3   $   K   | ]  }|d u  
 y wr7   r=   r>   s     r3   r;   z3VisualClozePipeline.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`.   z+max_sequence_length cannot exceed 512, got )
ValueErrorvae_scale_factorloggerwarningallr8   
isinstancestrlisttypelenany)r1   imagetask_promptcontent_promptupsampling_heightupsampling_widthstrengthr!   pooled_prompt_embeds"callback_on_step_end_tensor_inputsmax_sequence_lengthr:   samplerows   `             r3   check_inputsz VisualClozePipeline.check_inputs   s    a<8a<QRZQ[\]](->$BWBWZ[B[-\`a-aNN<T=R=RUV=V<WW`ar`s  t\  ] ',<@U@UXY@Y,Z^_,_NN=d>S>SVW>W=XXabras  t\  ] .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   KK7K
2   g      >@r   pilTrC   g      ?rP   rQ   rO   rR   rS   num_inference_stepssigmasguidance_scalenum_images_per_prompt	generatorrU   output_typereturn_dictjoint_attention_kwargscallback_on_step_endrV   rW   upsampling_strengthc                    | j                  |||||||	|
||||||||dk(  r|nd      }|dk(  r|s|fS t        |      S t        |t              s|g}g }g }g }g }t        |
t        j
                  f      r|
ng }t        t        |j                              D ]  }|j                  t        |j                  |                |j                  |   D ]  }|j                  |       |j                  t        j                  d|j                  d             |j                  ||t        |      z     r||t        |      z     nd       t        |
t        j
                  f      r|j                  |
|t        |      z              | j                  |||||||||||||||      }|j                  }g }|dk(  r(g }d}|D ]  }|j                  ||||z           ||z  }  n|}|s|fS t        |      S )	aW  
        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)`.
            upsampling_height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
                The height in pixels of the generated image (i.e., output image) after upsampling via SDEdit. By
                default, the image is upsampled by a factor of three, and the base resolution is determined by the
                resolution parameter of the pipeline. When only one of `upsampling_height` or `upsampling_width` is
                specified, the other will be automatically set based on the aspect ratio.
            upsampling_width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
                The width in pixels of the generated image (i.e., output image) after upsampling via SDEdit. By
                default, the image is upsampled by a factor of three, and the base resolution is determined by the
                resolution parameter of the pipeline. When only one of `upsampling_height` or `upsampling_width` is
                specified, the other will be automatically set based on the aspect ratio.
            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`.
            upsampling_strength (`float`, *optional*, defaults to 1.0):
                Indicates extent to transform the reference `image` when upsampling the results. Must be between 0 and
                1. The generated image is used as a starting point and more noise is added the higher the
                `upsampling_strength`. The number of denoising steps depends on the amount of noise initially added.
                When `upsampling_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 0 skips the upsampling step and
                output the results at the resolution of `self.resolution`.

        Examples:

        Returns:
            [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
            is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
            images.
        r   r\   )rP   rQ   rO   r]   r^   r_   r`   ra   r    r!   rU   rd   re   rV   rW   rb   )imagesRGB)   rj   rj    )promptrO   
mask_imageheightwidthrT   r]   r^   r_   ra   rb   rd   re   rV   rW   )r.   r   rI   rK   torch	GeneratorrangerM   rh   appendr	   newsizer0   ) r1   rP   rQ   rO   rR   rS   r]   r^   r_   r`   ra   r    r!   rU   rb   rc   rd   re   rV   rW   rf   generation_outputn_target_per_sampleupsampling_imageupsampling_maskupsampling_promptupsampling_generatoriupsampling_outputoutputstartns                                    r3   __call__zVisualClozePipeline.__call__   sa   ^ !00#) 3)"7'!5#9!5/Q 3':a'?U! 1 
$ !#)++%->?? .41,-N ,6y5??BT,Uy[]s,3345 		TA&&s+<+C+CA+F'GH*11!4 T ''.&&uyy

O'TU!((?MaRUVdReNe?fN1s>':#:;ln ")eoo-?@(//	!c.>Q:Q0RST		T !00$"&$"( 3)*##9!5/Q 3 1 
" "((% FE( eEEAI67
 F9!00r4   )i  )NNNN)"__name__
__module____qualname____doc__model_cpu_offload_seq_optional_componentsr8   r   r   r
   r   r   r   r   intr,   rZ   rp   no_gradr   EXAMPLE_DOC_STRINGr   rJ   r   r   FloatTensorfloatrq   boolr   r   r   r   __classcell__)r2   s   @r3   r   r   ]   sy   8 M(/: )
2)
 )
 $	)

 !)
 ')
 %)
 ,)
 )
f !+/ Mb^ U]]_12 .204-1+/*.#%(, $/0MQ/359<@%* ;?KO9B#&%(+}13S	>*}1 c49n-}1 ))*	}1
 $C=}1 #3-}1 !}1 e%}1 }1  (}}1 E%//43H"HIJ}1 %++,}1   1 12}1 'u'8'89}1 c]}1  !}1" !)c3h 8#}1$ 'xc40@$0F'GH%}1& -1I'}1( !)}1* #+}1 3 }1r4   r   ),typingr   r   r   r   r   r   rp   PILr	   transformersr
   r   r   r   loadersr   r   r   models.autoencodersr   models.transformersr   
schedulersr   utilsr   r   r   flux.pipeline_flux_fillr   r/   flux.pipeline_outputr   pipeline_utilsr   pipeline_visualcloze_generationr   XLA_AVAILABLE
get_loggerr   rF   r   r   r=   r4   r3   <module>r      s    > =   V V \ \ 0 9 9 
 X 5 . J MM 
		H	%. b_1	_1r4   