
    bip*                     V    d dl mZmZmZmZmZ d dlZd dlmZ ddl	m
Z
  G d de
      Zy)    )DictListOptionalTupleUnionN)Image   )VaeImageProcessorc                   b    e Zd ZdZdddef fdZdeeeej                           dede	eee
j                        eeee         ee   f   fd	Zdeeej                        d
ee   deee
j                        fdZdeeej                        dedede	eeej                        eeee         f   fdZdeeej                        deee
j                        fdZde	eef   defdZ	 	 	 	 	 ddeeee   f   deeee   f   deeeeee               dee   dee   dededefdZ xZS )VisualClozeProcessora_  
    Image processor for the VisualCloze pipeline.

    This processor handles the preprocessing of images for visual cloze tasks, including resizing, normalization, and
    mask generation.

    Args:
        resolution (int, optional):
            Target resolution for processing images. Each image will be resized to this resolution before being
            concatenated to avoid the out-of-memory error. Defaults to 384.
        *args: Additional arguments passed to [~image_processor.VaeImageProcessor]
        **kwargs: Additional keyword arguments passed to [~image_processor.VaeImageProcessor]
      )
resolutionr   c                2    t        |   |i | || _        y )N)super__init__r   )selfr   argskwargs	__class__s       l/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/visualcloze/visualcloze_utils.pyr   zVisualClozeProcessor.__init__&   s    $)&)$    input_imagesvae_scale_factorreturnc                    t        |      t        |d         }}d|z  }t        |      D cg c]  }g  }}t        |      D cg c]  }d }}g }	t        |      D ]s  }
t        |      D ]  }||
   |   ||
   |   j                  ||
   |   j                  z  }| j                  | j                  z  }t        ||z  dz        }t        ||z        }t        ||z  d      |z  }t        ||z  d      |z  }||f||
<    n t        |      D ]  }||
   |   T| j                  ||
   |   ||
   d   ||
   d         }||
   j                  |       |
|dz
  k(  sM|	j                  d       _t        j                  d||
   xs | j                  | j                  fd      }||
   j                  |       |
|dz
  k(  s|	j                  d        v t        |	      dkD  rt        |	      dkD  r||dz
     d   xs d}t        t        |            D ]  }
t        t        ||
               D ]}  }||
   |   t        ||
   |   j                  |||
   |   j                  z  z        }t        |d	z        d	z  }t        |d	z        d	z  }| j                  ||
   |   ||      ||
   |<     g }t        t        |            D ]  }
|j                  ||
   D cg c]  }|j                  |j                  g c}       t        ||
         D ]@  \  }}| j                  |      }| j                  |      }| j                  |      }|||
   |<   B  |||	fS c c}w c c}w c c}w )
a  
        Preprocesses input images for the VisualCloze pipeline.

        This function handles the preprocessing of input images by:
        1. Resizing and cropping images to maintain consistent dimensions
        2. Converting images to the Tensor format for the VAE
        3. Normalizing pixel values
        4. Tracking image sizes and positions of target images

        Args:
            input_images (List[List[Optional[Image.Image]]]):
                A nested list of PIL Images where:
                - Outer list represents different samples, including in-context examples and the query
                - Inner list contains images for the task
                - In the last row, condition images are provided and the target images are placed as None
            vae_scale_factor (int):
                The scale factor used by the VAE for resizing images

        Returns:
            Tuple containing:
            - List[List[torch.Tensor]]: Preprocessed images in tensor format
            - List[List[List[int]]]: Dimensions of each processed image [height, width]
            - List[int]: Target positions indicating which images are to be generated
        r      Ng      ?   RGB)r   r   r   r      )lenrangewidthheightr   intmax_resize_and_cropappendr   newsum	enumeratepil_to_numpynumpy_to_pt	normalize)r   r   r   	n_samplesn_task_images	divisible_processed_imagesresize_sizetarget_positionijaspect_ratiotarget_areanew_hnew_wtargetblankimage_sizesimgimages                        r   preprocess_imagez%VisualClozeProcessor.preprocess_image*   s   6 $'|#4c,q/6J=	((	AFyAQ4RAR4R4RFKIFV7W7W7W%' y! 	2A=) 
?1%1#/?1#5#;#;l1oa>P>W>W#WL"&//DOO"CK|!; CDE 45E 2A6BE 2A6BE&+U^KN
 =) 
2?1%1!22<?13E{ST~VWGXZefgZhijZklF$Q'..v6IM)'..q1!IIe[^-aQUQ`Q`?aclmE$Q'..u5IM)'..q1
2	28 !#O(<q(@	A.q18SE3/01 cs#3A#678 cA'*1-9 #$4Q$7$:$A$AUM]^_M`abMcMiMiEi$j k #EBJ" 4 #EBJ" 415=Ma=PQR=SUZ\a1b(+A.cc s+,- 	/ACSTUCVWCSYY 7WX%&6q&9: /5))%0((/u-). #A&	/	/  o==k 5S7WZ  Xs   	M	MM!
r4   c                    g }t        |      D ]  \  }}|t        |      dz
  k(  rI|D cg c]=  }t        j                  dd|d   j                  d   |d   j                  d   f|      ? }}nH|D cg c]=  }t        j                  dd|d   j                  d   |d   j                  d   fd      ? }}|j                  |        |S c c}w c c}w )a  
        Generate masks for the VisualCloze pipeline.

        Args:
            input_images (List[List[Image.Image]]):
                Processed images from preprocess_image
            target_position (List[int]):
                Binary list marking the positions of target images (1 for target, 0 for condition)

        Returns:
            List[List[torch.Tensor]]:
                A nested list of mask tensors (1 for target positions, 0 for condition images)
        r   r   r   r	   )
fill_value)r*   r    torchfullshaper'   )	r   r   r4   maskr5   rowm	row_masksr1   s	            r   preprocess_maskz$VisualClozeProcessor.preprocess_mask   s      - 		#FAsC%))`o[\EJJ1c!fll1os1v||AGTUV	 
 ap[\EJJ1c!fll1os1v||AGTUV	  KK	"		# s   AC2ACr#   r"   c                     | j                  |d   d   ||      }| j                  |      }| j                  |      }| j                  |      }||d   d<   ||ggg}||fS )a  Process images for the upsampling stage in the VisualCloze pipeline.

        Args:
            input_images: Input image to process
            height: Target height
            width: Target width

        Returns:
            Tuple of processed image and its size
        r   )resizer+   r,   r-   )r   r   r#   r"   r?   r=   s         r   preprocess_image_upsamplingz0VisualClozeProcessor.preprocess_image_upsampling   su      LOA.>!!%(  'u%"Q()[((r   c                     t        j                  dd|d   d   j                  d   |d   d   j                  d   f      ggS )Nr   r   r   r	   )rC   onesrE   )r   r   s     r   preprocess_mask_upsamplingz/VisualClozeProcessor.preprocess_mask_upsampling   sJ    Q<?1#5#;#;A#>QPQ@R@X@XYZ@[\]^__r   sizec                 >    d|d    d|d    d|d   |d   z   df}|S )NzA grid layout with r   z
 rows and r   z columns, displaying z images arranged side by side. )r   rQ   layout_instructions      r   get_layout_promptz&VisualClozeProcessor.get_layout_prompt   sO    !$q'*T!WI=RSWXYSZ]abc]dSdRe  fD  E
 "!r   task_promptcontent_prompt
upsamplingc                    t        |t              r	|g}|g}|g}g g |s|n!t        t        |            D cg c]  }d c}|g g g d}	t        t        |            D ]  }
|rd}n.| j	                  t        ||
         t        ||
   d         f      }|r,| j                  ||
   ||      \  }}| j                  |      }n@| j                  ||
   |      \  }}}| j                  ||      }|	d   j                  |       |	d   j                  |       |	d   j                  |       |	d	   j                  |       |	d
   j                  |        |	S c c}w )a  Process visual cloze inputs.

        Args:
            task_prompt: Task description(s)
            content_prompt: Content description(s)
            input_images: List of images or None for the target images
            height: Optional target height for upsampling stage
            width: Optional target width for upsampling stage
            upsampling: Whether this is in the upsampling processing stage

        Returns:
            Dictionary containing processed images, masks, prompts and metadata
        N)
init_imagerF   rV   rW   layout_promptr4   
image_sizer   )r#   r"   )r   r4   r\   rZ   rF   r[   )

isinstancestrr!   r    rU   rM   rP   r@   rJ   r'   )r   rV   rW   r   r#   r"   rX   r   r1   outputr5   r[   cur_processed_imagescur_image_sizecur_maskcur_target_positions                   r   
preprocesszVisualClozeProcessor.preprocess   s   . k3'&-K,-N(>L .8;USVWbScMd>et>e,!
 s;'( 	:A $ $ 6 6LO8LcR^_`RabcRdNe7f g7;7W7W OF% 8X 84$n  ::;OPLPLaLa O6F Mb MI$n6I  //0DFYZ()001DE< ''7< ''(<=6N!!(+?#**=9-	:0 = ?fs   	E)NNNFr   )__name__
__module____qualname____doc__r$   r   r   r   r   r   rC   Tensorr@   rJ   rM   rP   r^   rU   r   boolr   rd   __classcell__)r   s   @r   r   r      s    14 %# %S> hu{{&;!<=S>QTS>	tD&'d49o)>S	I	JS>j ekk!23FJ3i	d5<< 	!:)4,-) ) 	)
 
tD%&T$s)_(==	>)2`tD<M7N `SWX\]b]i]iXjSk `"eCHo "# " CG $#  "=3S	>*= c49n-= tDhsm)<$=>?	=
 = }= = = 
=r   r   )typingr   r   r   r   r   rC   PILr   image_processorr
   r   rS   r   r   <module>ro      s%    6 5   0d, dr   