
    Z jS                        S SK r S SKJr  S SKJrJr  S SKrS SKrSSK	J
r
  SSKJr  SSKJrJrJr  SSKJrJrJrJrJrJr  SS	KJrJr  SS
KJrJrJr  \" 5       (       a  S SKJ r   S SK!J"r#   " S S\SS9r$\" SS9S\%S\&\'\%\%4      4S j5       r(S\%S\%S\%S\%S\%S\'\%\%4   4S jr)\" SS9S\%S\%S\%S\%S\'\%\%4   4
S j5       r*S\SS4S jr+S  r, S-S!\&\&\'\%\%4         S\%S"\S#   SS$4S% jjr-S&\&\&S$      S\%S\'S$\&\&\%      4   4S' jr. S-S!\&\&\'\%\%4         S\%S"\S#   SS$4S( jjr/S)\S\4S* jr0\ " S+ S,\
5      5       r1S,/r2g).    N)	lru_cache)OptionalUnion   )TorchvisionBackend)BatchFeature)group_images_by_shapereorder_imagessplit_to_tiles)IMAGENET_STANDARD_MEANIMAGENET_STANDARD_STD
ImageInputPILImageResamplingSizeDictmake_nested_list_of_images)ImagesKwargsUnpack)
TensorTypeauto_docstringis_vision_available)Image)
functionalc                   $    \ rS rSr% Sr\\S'   Srg)MllamaImageProcessorKwargs+   zO
max_image_tiles (`int`, *optional*):
    The maximum number of tiles allowed.
max_image_tiles N)__name__
__module____qualname____firstlineno____doc__int__annotations____static_attributes__r       ڃ/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/mllama/image_processing_mllama.pyr   r   +   s    
 r&   r   F)total
   )maxsizer   returnc                     / n[        SU S-   5       H5  n[        SU S-   5       H  nX#-  U ::  d  M  UR                  X#45        M!     M7     U$ )a  
Computes all allowed aspect ratios for a given maximum number of input tiles.

This function calculates all possible arrangements of tiles that can be formed
within the constraint of the maximum number of tiles. Each arrangement is
represented by its aspect ratio (width/height) and the corresponding tile configuration.

Args:
    max_image_tiles (`int`):
        The maximum number of tiles allowed.

Returns:
    `list[tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height)
    configuration in terms of number of tiles.

Example:
    >>> get_all_supported_aspect_ratios(4)
    [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (3, 1), (4, 1)]

   )rangeappend)r   aspect_ratioswidthheights       r'   get_all_supported_aspect_ratiosr3   4   sW    , Mq/A-.A23F~0$$e_5 4 / r&   image_heightimage_widthcanvas_heightcanvas_width	tile_sizec                 8   [         R                  " XU5      n[         R                  " XU5      nX`-  nXQ-  nX:  a0  Un	[        [        R                  " X-  5      =(       d    SU5      n
X4$ Un
[        [        R                  " X-  5      =(       d    SU5      n	X4$ )a  
Calculates the new size of an image to fit within a canvas while maintaining aspect ratio.

This function calculates the optimal size for an image to fit within a canvas defined by
canvas_height and canvas_width, while ensuring that the image dimensions are not smaller than
tile_size. If the image is larger than the canvas, the returned size will fit within the canvas.
If the image already fits within the canvas, the size remains unchanged.
The aspect ratio of the original image is preserved as much as possible.

Args:
    image_height (`int`):
        The height of the original image.
    image_width (`int`):
        The width of the original image.
    canvas_height (`int`):
        The height of the canvas.
    canvas_width (`int`):
        The width of the canvas.
    tile_size (`int`):
        The tile size.

Returns:
    `tuple[int, int]`: A tuple containing the new height and width of the image.

r-   )npclipminmathfloor)r4   r5   r6   r7   r8   target_widthtarget_heightscale_hscale_w	new_width
new_heights              r'   get_image_size_fit_to_canvasrE   R   s    B 77;<@LGGL]CM*G(G 	L$:;@q-P
   	 #


;#89>QM	  r&   d   c                    [        U5      n[        R                  " U5      U-  n[        R                  " U5      R                  u  pgX`-  nXq-  n	[        R                  " X:  X5      n
XS:     n[        U5      S:  a  [        R                  " U5      nOXS:     n[        R                  " U5      nXZU:H     n[        U5      S:  a/  USS2S4   USS2S4   -  n[        R                  " U5      nUU   nOUS   n[        U5      $ )ar  
Determines the best canvas based on image and tile size and maximum number of tiles.

First, calculates possible resolutions based on the maximum number of tiles and tile size.
For each possible resolution, calculates the scaling factors for width and height, and selects
the smallest one. If upscaling is possible, picks the smallest upscaling factor > 1.
If upscaling is not possible, picks the largest scaling factor <= 1.
If there are multiple resolutions with the same max scale, picks the one with the lowest area.

Args:
    image_height (`int`):
        The height of the image.
    image_width (`int`):
        The width of the image.
    max_image_tiles (`int`):
        The maximum number of tiles any image can be split into.
    tile_size (`int`):
        The tile size.

Returns:
    `tuple[int, int]`: The best canvas resolution [height, width] for the given image.
r-   r   N)
r3   r:   arrayTwherelenr<   maxargmintuple)r4   r5   r   r8   possible_tile_arrangementspossible_canvas_sizestarget_heightstarget_widthsrA   rB   scalesupscaling_optionsselected_scaledownscaling_optionschosen_canvasareasoptimal_idxoptimal_canvass                     r'   get_optimal_tiled_canvasr[      s	   : "A!QHH%?@9L$&HH-B$C$E$E!N+G)GXXg':F{+
! 12$aZ0 34)N*BCM
=Aad#mAqD&99ii&&{3&q)  r&   sizec                     U R                   (       a  U R                  (       d  [        SU  35      eU R                   U R                  :w  a  [        SU  35      eg )NzJArgument `size` must be a dictionary with keys 'height' and 'width'. Got: z9Argument `size` must have the same height and width, got )r2   r1   
ValueError)r\   s    r'   _validate_sizer_      sN    KKDJJefjeklmm{{djj TUYTZ[\\ !r&   c                     U(       d  [        S5      eU (       d  [        S5      eUb  US::  a  [        SU S35      e[        U5        g )Nz9MllamaImageProcessor doesn't support `do_pad=False` mode.z<MllamaImageProcessor doesn't support `do_resize=False` mode.r   zGMllamaImageProcessor `max_image_tiles` must be a positive integer, got .)r^   r_   )	do_resizer\   do_padr   s       r'   %_validate_mllama_preprocess_argumentsrd      sM    TUUWXX/Q"6bcrbsstuvv4r&   r0   deviceztorch.devicetorch.Tensorc           	         [        U 5      n[        S U  5       5      n[        R                  " X4U4[        R                  US9nSUSS2SS2S4'   [        U 5       H'  u  pg[        U5       H  u  nu  pSXVUSX-  24'   M     M)     U$ )a  
Builds a mask for the aspect ratios of the images.

Args:
    aspect_ratios (`List[List[Tuple[int, int]]]`):
        A list of lists containing aspect ratios for each image in the batch.
        Each aspect ratio is represented as a tuple of (width, height) in terms of number of tiles.
    max_image_tiles (`int`):
        The maximum number of tiles any image can be split into.
    device (`torch.device`, *optional*):
        The device to create the tensor on. Defaults to CPU.

Returns:
    `torch.Tensor`: A 3D torch.Tensor of shape (batch_size, max_num_images, max_image_tiles).
        The mask contains 1s for valid tiles and 0s for padding.
c              3   8   #    U  H  n[        U5      v   M     g 7fNrK   .0rows     r'   	<genexpr>*build_aspect_ratio_mask.<locals>.<genexpr>        ;]cS]   dtypere   r-   Nr   )rK   rL   torchzeroslong	enumerate)r0   r   re   
batch_sizemax_num_imagesaspect_ratio_maskisample_aspect_ratiosjnum_tiles_wnum_tiles_hs              r'   build_aspect_ratio_maskr      s    * ]#J;];;NZ$QY^YcYclrs
 "#aAg $-]#;-67K-L)A)CD$?k&?$??@ .M $< r&   batch_imagesc                    [        U 5      n[        S U  5       5      nU  VVs/ s H  oD  H  oUR                  PM     M     nnnUS   u  pxp[        R                  " X#XX4[        R
                  U S   S   R                  S9n/ n[        U 5       HT  u  p/ n[        U5       H-  u  pUR                  S   nX[XSU24'   UR                  U5        M/     UR                  U5        MV     X4$ s  snnf )a  
Stack a list of lists of images with variable lengths into a torch.Tensor, applying zero padding as needed.
Each list in the input represents a batch sample, and each image within a list is expected to be
pre-split into tiles. The resulting array will have a shape of
(batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width).

Args:
    batch_images (`List[List[torch.Tensor]]`):
        A list of lists of image tiles. Each inner list represents
        a batch sample containing multiple images, where each image is pre-split into tiles.
        The shape of each tile array is (num_tiles, channels, tile_height, tile_width).
    max_image_tiles (int):
        The maximum number of tiles any image was potantially split.

Returns:
    `Tuple[torch.Tensor, List[List[int]]]`: A tuple containing:
        - stacked_images (`torch.Tensor`):
            A numpy array of stacked images with shape
            (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width).
        - all_num_tiles (`List[List[int]]`):
            A list of lists containing the number of tiles
            for each image in each batch sample.
c              3   8   #    U  H  n[        U5      v   M     g 7fri   rj   )rl   imagess     r'   rn   (pad_batches_and_tiles.<locals>.<genexpr>  s     @<V<rq   r   rr   N)	rK   rL   shapert   ru   float32re   rw   r/   )r   r   rx   ry   r   imageshapes_channelstile_height
tile_widthstacked_imagesall_num_tilesr{   num_sample_tilesr}   	num_tiless                    r'   pad_batches_and_tilesr      s    8 \"J@<@@N(4If&kk&kFI+1!9(A [[	_XmmAq!((N M|,	!&)HAAI/41)+,##I. * 	-. - (() Js   C+c                 (   [        U 5      n[        S U  5       5      n[        U5      n[        R                  " X44[        R
                  US9n[        U 5       H5  u  px[        U5       H!  u  n	u  pUR                  X45      S-   XgU	4'   M#     M7     U$ )a1  
Convert aspect ratio tuples to unique ids.

For batch padding we use 0, because there might be different number of images in each batch.
The aspect ratio ids start from 1, with 1 corresponding to the first supported aspect ratio.

Args:
    aspect_ratios (`List[List[Tuple[int, int]]]`):
        A list of aspect ratios for each image in the batch.
    max_image_tiles (`int`):
        The maximum number of tiles any image can be split into.
    device (`torch.device`, *optional*):
        The device to create the tensor on. Defaults to CPU.

Returns:
    `torch.Tensor`:
        The aspect ratios ids as a numpy array with shape (batch_size, max_num_images).
        Each id corresponds to the index of the aspect ratio in the list of supported aspect ratios,
        offset by 1 (so 0 can be used for padding).
c              3   8   #    U  H  n[        U5      v   M     g 7fri   rj   rk   s     r'   rn   /convert_aspect_ratios_to_ids.<locals>.<genexpr>F  rp   rq   rr   r-   )rK   rL   r3   rt   ru   rv   rw   index)r0   r   re   rx   ry   supported_aspect_ratiosaspect_ratios_idsr{   r|   r}   r   r~   s               r'   convert_aspect_ratios_to_idsr   ,  s    2 ]#J;];;N=oNZ$@

[ab#,]#;-67K-L)A)&=&C&C[D^&_bc&cd# .M $< r&   r   c                 >   [        5       (       a  [        U [        R                  5      (       d  U $ U R                  S:X  a  U $ U R	                  S5      n[        R
                  " SUR                  S5      n[        R                  " X!5      nUR	                  S5      nU$ )z|
Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image
as is.
RGBRGBA)   r   r   )r   
isinstancer   modeconvertnewr\   alpha_composite)r   
image_rgba
backgroundr   s       r'   convert_to_rgbr   Q  s}    
   
5%++(F(FzzUv&J6:??ODJ++JCO%--e4Or&   c                     ^  \ rS rSr\R
                  r\r\	r
SSS.rSrSrSrSrSrSr\r/ SQrS\\   4U 4S jjrU 4S	 jr\S
\S\\   S\4U 4S jj5       rS%S
\S\S\4S jjrS\S\4S jrSSS\S\ \\4   SS4S jr!  S&SSS\S\S\"S   S\#S\$S\ \\4   4   4U 4S jjjr%S
\&\&S      S\SSS\#S\'S\#S\'\&\'   -  S-  S \'\&\'   -  S-  S\S-  S!\(\)-  S-  S"\#S-  S\4S# jr*S$r+U =r,$ )'MllamaImageProcessoric     r2   r1   T   )pixel_valuesr   aspect_ratio_idsrz   kwargsc                    > [         TU ]  " S0 UD6  [        U R                  U R                  U R
                  U R                  5        g Nr   )super__init__rd   rb   r\   rc   r   selfr   	__class__s     r'   r   MllamaImageProcessor.__init__r  s4    "6"-dnndiiVZVjVjkr&   c                    > [         TU ]  " S0 UD6  [        U R                  U R                  U R
                  U R                  5        g r   )r   _validate_preprocess_kwargsrd   rb   r\   rc   r   r   s     r'   r   0MllamaImageProcessor._validate_preprocess_kwargsv  s4    +5f5-dnndiiVZVjVjkr&   r   r+   c                 &   > [         TU ]  " U40 UD6$ ri   )r   
preprocess)r   r   r   r   s      r'   r   MllamaImageProcessor.preprocessz  s    w!&3F33r&   expected_ndimsc                 6    U R                  U5      n[        XS9$ )z1Prepare a nested images structure for processing.)r   )fetch_imagesr   )r   r   r   s      r'   _prepare_images_structure.MllamaImageProcessor._prepare_images_structure~  s    ""6*)&PPr&   r   c                     [        U5      $ )z Converts an image to RGB format.)r   )r   r   s     r'   r   #MllamaImageProcessor.convert_to_rgb  s    e$$r&   rf   r\   aspect_ratioc                     UR                   SS u  pEUu  pgXbR                  -  nXrR                  -  n	SSX-
  X-
  4n
[        R                  " XSS9nU$ )a  
Pad an image to the `size` x `aspect_ratio`. For example, if size is {height: 224, width: 224} and aspect ratio is
(1, 2), the image will be padded to 224x448.

Args:
    image (`torch.Tensor`):
        Image to pad.
    size (`Dict[str, int]`):
        Size of the output image.
    aspect_ratio (`Tuple[int, int]`):
        The aspect ratio of the image.

Returns:
    `torch.Tensor`: The padded image.
Nr   )fill)r   r2   r1   tvFpad)r   r   r\   r   r4   r5   num_tiles_heightnum_tiles_widthpadded_heightpadded_widthpad_sizes              r'   r   MllamaImageProcessor.pad  sa    * %*KK$4!,8)(;;6&3q,4m6RSa0r&   Nr   resampleztvF.InterpolationMode	antialiasc                    > UR                   SS u  pgUR                  n[        UUUUS9u  pX-  nX-  n[        UUU	U
US9u  p[        TU ]  U[        XS9XES9nXU44$ )a  
Resizes an image to fit within a tiled canvas while maintaining its aspect ratio.
The optimal canvas size is calculated based on the maximum number of tiles and the tile size.

The function first determines the best tile arrangement for the image, then resizes the image
to fit within this canvas. The resized image and the number of tiles along the height and width
dimensions are returned.

Args:
    image (`torch.Tensor`):
        Image to resize.
    size (`Dict[str, int]`):
        Size of the output image.
    max_image_tiles (`int`):
        The maximum number of tiles to split the image into.
    resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
        Resampling filter to use when resizing the image.

Returns:
    `Union[torch.Tensor, Tuple[int, int]]`: The resized image and a tuple containing the number of tiles
    along the height and width dimensions.
r   N)r4   r5   r   r8   )r4   r5   r6   r7   r8   r   )r   r   )r   r2   r[   rE   r   resizer   )r   r   r\   r   r   r   r4   r5   r8   r6   r7   r   r   rD   rC   r   s                  r'   r   MllamaImageProcessor.resize  s    < %*KK$4!KK	&>%#+	'
# )5&3 <%#'%!

 8:?(  
 999r&   z7PILImageResampling | tvF.InterpolationMode | int | None
do_rescalerescale_factordo_normalize
image_mean	image_stdreturn_tensorsdisable_groupingc           	         [        USUS9u  p0 n0 nUR                  5        Hh  u  nnU R                  UX#U	S9u  nnU R                  UUUS9nUu  nnU/[	        U5      -  UU'   [        UUU5      nU R                  UXEXgU5      nUUU'   Mj     [        XSS9n[        UUSS9n[        UU	5      u  nnUR                  n[        UU	US9n[        UU	US9n[        UUUS.U
S9nUUS	'   U$ )
NT)	is_nestedr   )r   r\   r   r   )r   r\   r   )r   )r   re   )r   r   rz   )datatensor_typer   )r	   itemsr   r   rK   r   rescale_and_normalizer
   r   re   r   r   r   )r   r   r\   r   r   r   r   r   r   r   r   r   r   grouped_imagesgrouped_images_indexsplit_images_groupedaspect_ratio_groupedr   r   r   r   r   split_imagesr0   r   pixel_values_devicer   rz   encoded_inputss                                r'   _preprocess MllamaImageProcessor._preprocess  ss     0Ed5E0
,  "!%3%9%9%;!E>+/;;$4Tc ,7 ,(NL "XX$) & N
 1=-o+7.3~;N*N ').:JO\L  55j,T]L +7 '% &<( &&:\`a&';=Q]ab"7o"Vi +117?CV
 4?CV
 & ,$4%6
 '
 '0{#r&   r   )r   )NT)-r   r   r    r!   r   BILINEARr   r   r   r   r   r\   rb   r   r   do_convert_rgbrc   r   r   valid_kwargsmodel_input_namesr   r   r   r   r   r   r   r#   r   r   r   rN   r   r   boolr   r   listfloatstrr   r   r%   __classcell__)r   s   @r'   r   r   c  s'   !**H'J%IC(DIJLNFO-L^l(B!C ll 4 4v>X7Y 4^j 4 4Q
 QC QXb Q
%J %: %  CHo	
 
F 7;6:6: 6: 	6:
 236: 6: 
~uS#X.	/6: 6:pAT.)*A A L	A
 A A A DK'$.A 4;&-A tA j(4/A +A 
A Ar&   r   ri   )3r=   	functoolsr   typingr   r   numpyr:   rt   image_processing_backendsr   image_processing_utilsr   image_transformsr	   r
   r   image_utilsr   r   r   r   r   r   processing_utilsr   r   utilsr   r   r   PILr   torchvision.transforms.v2r   r   r   r#   r   rN   r3   rE   r[   r_   rd   r   r   r   r   r   __all__r   r&   r'   <module>r      s@     "   ; 2 U U  5 D D  7U  2S T%S/=R  :0!0!0! 0! 	0!
 0! 38_0!f 36!6!6! 6! 	6!
 38_6! 6!r] ]d ] (,$U38_-.$$ ^$$ 	$N2)tN+,2)2) >4S	?*+2)p (,!U38_-.!! ^$! 	!J*  $ z- z zz "
"r&   