
    +hp*                     V    S SK JrJrJrJrJr  S SKrS SKJr  SSK	J
r
   " S S\
5      rg)    )DictListOptionalTupleUnionN)Image   )VaeImageProcessorc                   ~  ^  \ rS rSrSrSS.S\4U 4S jjjrS\\\\	R                           S\S	\
\\\R                        \\\\         \\   4   4S
 jrS\\\	R                        S\\   S	\\\R                        4S jrS\\\	R                        S\S\S	\
\\\	R                        \\\\         4   4S jrS\\\	R                        S	\\\R                        4S jrS\
\\4   S	\4S jr     SS\\\\   4   S\\\\   4   S\\\\\\               S\\   S\\   S\S\S	\4S jjrSrU =r$ )VisualClozeProcessor   a7  
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U ]  " U0 UD6  Xl        g )N)super__init__r   )selfr   argskwargs	__class__s       k/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/pipelines/visualcloze/visualcloze_utils.pyr   VisualClozeProcessor.__init__&   s    $)&)$    input_imagesvae_scale_factorreturnc                    [        U5      [        US   5      pCSU-  n[        U5       Vs/ s H  n/ PM     nn[        U5       Vs/ s H  nSPM     nn/ n	[        U5       GHs  n
[        U5       H  nX   U   c  M  X   U   R                  X   U   R                  -  nU R                  U R                  -  n[        X-  S-  5      n[        X-  5      n[        X-  S5      U-  n[        X-  S5      U-  nX4X'     O   [        U5       H  nX   U   bR  U R                  X   U   X   S   X   S   5      nXz   R                  U5        XS-
  :X  a  U	R                  S5        M[  M]  [        R                  " SX   =(       d    U R                  U R                  4S5      nXz   R                  U5        XS-
  :X  d  M  U	R                  S5        M     GMv     [        U	5      S:  a  [        U	5      S:  a  XS-
     S   =(       d    Sn[        [        U5      5       H  n
[        [        Xz   5      5       Hz  nXz   U   c  M  [        Xz   U   R                  XU
   U   R                  -  -  5      n[        US	-  5      S	-  n[        US	-  5      S	-  nU R                  Xz   U   X5      Xz   U'   M|     M     / n[        [        U5      5       H  n
UR                  Xz    Vs/ s H  nUR                  UR                  /PM     sn5        [        Xz   5       H@  u  nnU R                  U5      nU R                  U5      nU R                  U5      nUXz   U'   MB     M     UUU	4$ s  snf s  snf s  snf )
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_image%VisualClozeProcessor.preprocess_image*   s   6 $'|#4c,q/6J=((	AFyAQ4RAQARAQ4RFKIFV7WFVFV7W%' y!A=)?1%1#/?1#5#;#;loa>P>W>W#WL"&//DOO"CK!; CDE 45E 2A6BE 2A6BE&+^KN * =)?1%1!22<?13E{~VWGXZeZhijZklF$'..v6M)'..q1 * "IIe[^-aQUQ`Q`?aclmE$'..u5M)'..q1 * "8 !#O(<q(@A.q18SE3/01s#3#678A'*1-9 #$4$7$:$A$AU^_M`abMcMiMiEi$j k #EBJ" 4 #EBJ" 415=M=PQR=SUZ1b(+A. 9 2 s+,-ACSCVWCVCSYY 7CVWX%&6&9:5))%0((/u-). #A&	 ; .  o==k 5S7WZ  Xs   M&M+#"M0
r6   c                    / n[        U5       H  u  pEU[        U5      S-
  :X  aJ  U Vs/ s H<  n[        R                  " SSUS   R                  S   US   R                  S   4US9PM>     nnOIU Vs/ s H<  n[        R                  " SSUS   R                  S   US   R                  S   4SS9PM>     nnUR                  U5        M     U$ s  snf s  snf )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   r6   maskr7   rowm	row_masksr3   s	            r   preprocess_mask$VisualClozeProcessor.preprocess_mask   s      -FAC%))`o`o[\EJJ1c!fll1os1v||AGTUV`o  	
 ap`o[\EJJ1c!fll1os1v||AGTUV`o   KK	" . s   AC3ACr%   r$   c                     U R                  US   S   X#5      nU R                  U5      nU R                  U5      nU R                  U5      nXAS   S'   X#///nX4$ )zProcess 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$   rA   r?   s         r   preprocess_image_upsampling0VisualClozeProcessor.preprocess_image_upsampling   sm      LOA.>!!%(  'u%"Q()((r   c                     [         R                  " SSUS   S   R                  S   US   S   R                  S   45      //$ )Nr   r   r   r	   )rF   onesrH   )r   r   s     r   preprocess_mask_upsampling/VisualClozeProcessor.preprocess_mask_upsampling   sJ    Q<?1#5#;#;A#>QPQ@R@X@XYZ@[\]^__r   sizec                 >    SUS    SUS    SUS   US   -   S34nU$ )NzA grid layout with r   z
 rows and r   z columns, displaying z images arranged side by side. )r   rW   layout_instructions      r   get_layout_prompt&VisualClozeProcessor.get_layout_prompt   sO    !$q'*T!WI=RSWXYSZ]abc]dSdRe  fD  E
 "!r   task_promptcontent_prompt
upsamplingc                    [        U[        5      (       a	  U/nU/nU/n/ / U(       d  UO$[        [        U5      5       Vs/ s H  nSPM     snU/ / / S.n	[        [        U5      5       H  n
U(       a  SnO,U R	                  [        X:   5      [        X:   S   5      45      nU(       a&  U R                  X:   XES9u  pU R                  U5      nO:U R                  X:   US9u  pnU R                  X5      nU	S   R                  U5        U	S   R                  U5        U	S   R                  U5        U	S	   R                  U5        U	S
   R                  U5        M     U	$ s  snf )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_imagerI   r]   r^   layout_promptr6   
image_sizer   )r%   r$   )r   r6   rc   ra   rI   rb   )

isinstancestrr#   r"   r[   rQ   rU   rB   rM   r)   )r   r]   r^   r   r%   r$   r_   r   r3   outputr7   rb   cur_processed_imagescur_image_sizecur_maskcur_target_positions                   r   
preprocessVisualClozeProcessor.preprocess   s   . k3''&-K,-N(>L .8;USVWbScMd>eMdtMd>e,!
 s;'(A $ $ 6 6LO8LcR^RabcRdNe7f g7;7W7W OF 8X 84$  ::;OPLPLaLa O6F Mb MI$6I  //0DZ()001DE< ''7< ''(<=6N!!(+?#**=9- )0 = ?fs    E)NNNFr!   )__name__
__module____qualname____firstlineno____doc__r&   r   r   r   r   r   rF   TensorrB   rM   rQ   rU   re   r[   r   boolr   rk   __static_attributes____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   rF   PILr   image_processorr
   r   rY   r   r   <module>ry      s%    6 5   0d, dr   