
    ^j&                     p   d Z ddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
 ddlmZmZ ddlmZmZmZmZmZ dd	lmZmZ dd
lmZmZ deeef   deeef   defdZ	 ddedeeeef   z  ee   z  ee   z  deeeef   z  ee   z  ee   z  deez  dz  def
dZ G d ded      Z e G d de             Z!dgZ"y)z"Image processor class for Pixtral.    N)
functional   )TorchvisionBackend)BatchFeatureget_size_dict)group_images_by_shapereorder_images)ChannelDimension
ImageInputPILImageResamplingSizeDictget_image_size)ImagesKwargsUnpack)
TensorTypeauto_docstring
image_size
patch_sizereturnc                 ~    | \  }}t        |t        t        f      r|n||f\  }}|dz
  |z  dz   }|dz
  |z  dz   }||fS )aP  
    Calculate the number of image tokens given the image size and patch size.

    Args:
        image_size (`tuple[int, int]`):
            The size of the image as `(height, width)`.
        patch_size (`tuple[int, int]`):
            The patch size as `(height, width)`.

    Returns:
        `int`: The number of image tokens.
       )
isinstancetuplelist)r   r   heightwidthpatch_heightpatch_widthnum_width_tokensnum_height_tokenss           /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/pixtral/image_processing_pixtral.py_num_image_tokensr"      sa     MFE.8eT].S
ZdfpYqL+	k1A5!4q8...    input_imagesizeinput_data_formatc                    t        |t        t        f      r|n||f\  }}t        |t        t        f      r|n||f\  }}t        | |      \  }}	t	        ||z  |	|z        }
|
dkD  rBt        t        j                  ||
z              }t        t        j                  |	|
z              }	t        ||	f||f      \  }}||z  ||z  fS )aN  
    Find the target (height, width) dimension of the output image after resizing given the input image and the desired
    size.

    Args:
        input_image (`ImageInput`):
            The image to resize.
        size (`int` or `tuple[int, int]`):
            Max image size an input image can be. Must be a dictionary with the key "longest_edge".
        patch_size (`int` or `tuple[int, int]`):
            The patch_size as `(height, width)` to use for resizing the image. If patch_size is an integer, `(patch_size, patch_size)`
            will be used
        input_data_format (`ChannelDimension`, *optional*):
            The channel dimension format of the input image. If unset, will use the inferred format from the input.

    Returns:
        `tuple`: The target (height, width) dimension of the output image after resizing.
    r   )	r   r   r   r   maxintmathfloorr"   )r$   r%   r   r&   
max_height	max_widthr   r   r   r   ratior    r   s                r!   get_resize_output_image_sizer/   1   s    0 %/teT]$CD$PTJ	.8eT].S
ZdfpYqL+";0ABMFE#UY%67Eqy TZZ/0DJJuu}-.*;VUOl\gMh*i''|+-=-KKKr#   c                   ,    e Zd ZU dZeeef   ez  ed<   y)PixtralImageProcessorKwargsz
    patch_size (`Union[dict[str, int], int]` *optional*, defaults to `{"height": 16, "width": 16}`):
        Size of the patches in the model, used to calculate the output image size.
    r   N)__name__
__module____qualname____doc__dictstrr)   __annotations__ r#   r!   r1   r1   Y   s    
 S#X$$r#   r1   F)totalc                       e Zd Zej                  Zg dZg dZdddZddiZ	dZ
dZdZdZdZeZdd	gZd
ee   f fdZeded
ee   def fd       Z	 d#dddededdddf
 fdZded   d	eeeef      ddfdZ	 d#ded   dededddedededededeee   z  dz  deee   z  dz  d edz  d!e e!z  dz  de"e ef   ez  dz  defd"Z# xZ$S )$PixtralImageProcessor)g3<4'?gwgM?gy{ ?)gB91?gwt.?g	U?   r   r   longest_edgei   Tpixel_valuesimage_sizeskwargsc                 $    t        |   di | y )Nr9   )super__init__)selfrB   	__class__s     r!   rE   zPixtralImageProcessor.__init__r   s    "6"r#   imagesr   c                 $    t        |   |fi |S N)rD   
preprocess)rF   rH   rB   rG   s      r!   rK   z PixtralImageProcessor.preprocessu   s    w!&3F33r#   Nimageztorch.Tensorr%   r   resamplez7PILImageResampling | tvF.InterpolationMode | int | Nonec                    |j                   r|j                   |j                   f}n<|j                  r%|j                  r|j                  |j                  f}nt        d      |j                  r%|j                  r|j                  |j                  f}nt        d      t	        |||      }t        	|   |ft        |d   |d         |d|S )a  
        Resize an image. The longest edge of the image is resized to size["longest_edge"], with the aspect ratio
        preserved. Output dimensions are aligned to patch_size.

        Args:
            image (`torch.Tensor`):
                Image to resize.
            size (`SizeDict`):
                Dict containing the longest possible edge of the image.
            patch_size (`SizeDict`):
                Patch size used to calculate the size of the output image.
            resample (`PILImageResampling | tvF.InterpolationMode | int | None`, *optional*):
                Resampling filter to use when resizing the image.
        z@size must contain either 'longest_edge' or 'height' and 'width'.z-patch_size must contain 'height' and 'width'.)r%   r   r   r   r>   )r%   rM   )r?   r   r   
ValueErrorr/   rD   resizer   )
rF   rL   r%   r   rM   rB   
size_tuplepatch_size_tupleoutput_sizerG   s
            r!   rP   zPixtralImageProcessor.resizey   s    , ++T->->?J[[TZZ++tzz2J_``!1!1 * 1 1:3C3CDLMM25zVfgw~
 Ak!nMX`
dj
 	
r#   c                 :   t        d |D              t        d |D              f}t        ||      D cg c]F  \  }}t        j                  j                  j                  |d|d   |d   z
  d|d   |d   z
  f      H }}}t        j                  |      S c c}}w )a  
        Pads images to form a batch of same shape.

        Args:
            pixel_values (`list[torch.Tensor]`):
                A list of pixel values, each of shape (channels, height, width).
            image_sizes (`list[tuple[int, int]]`):
                A list of (height, width) for each image.

        Returns:
            `torch.Tensor`: Stacked and padded images.
        c              3   &   K   | ]	  }|d      yw)r   Nr9   .0ss     r!   	<genexpr>z:PixtralImageProcessor._pad_for_batching.<locals>.<genexpr>   s     3!13   c              3   &   K   | ]	  }|d      yw)r   Nr9   rV   s     r!   rY   z:PixtralImageProcessor._pad_for_batching.<locals>.<genexpr>   s     8S!18SrZ   r   r   )pad)r(   ziptorchnnr   r\   stack)rF   r@   rA   	max_shapeimgr%   paddeds          r!   _pad_for_batchingz'PixtralImageProcessor._pad_for_batching   s    " 3{33S8S{8S5ST	 !{;
T HH##Ca1Q1GIVWL[_`a[bLb-c#d
 
 {{6""	
s   AB	do_resizedo_center_crop	crop_size
do_rescalerescale_factordo_normalize
image_mean	image_stddisable_groupingreturn_tensorsc           	      Z   t        |xs | j                  d      }t        di |}t        ||      \  }}i }|j	                         D ]!  \  }}|r| j                  ||||      }|||<   # t        ||      }t        ||      \  }}t        t        |            D cg c]
  }||   d    }}i }|j	                         D ]4  \  }}|r| j                  ||      }| j                  ||||	|
|      }|||<   6 t        ||      }| j                  ||      }t        ||d|      S c c}w )	NT)default_to_square)rm   )rL   r%   r   rM   r   )r@   rA   )datatensor_typer9   )r   r   r   r   itemsrP   r	   rangelencenter_croprescale_and_normalizerd   r   )rF   rH   re   r%   rM   rf   rg   rh   ri   rj   rk   rl   rm   rn   r   rB   patch_size_sdgrouped_imagesgrouped_images_indexresized_images_groupedshapestacked_imagesresized_imagesibatch_image_sizesprocessed_images_groupedprocessed_imagespadded_imagess                               r!   _preprocessz!PixtralImageProcessor._preprocess   s   $ #:#@TXY
 .:./DV^n/o,,!#%3%9%9%; 	;!E>!%(tX` "- " -;"5)	; ((>@TU/D^fv/w,,AFsK_G`AabA1!4Q7bb#% %3%9%9%; 	=!E>!%!1!1.)!L!77
NL*V_N /=$U+	= **BDXY..)) / 

 "/@QR`n
 	
# cs   D(rJ   )%r2   r3   r4   r   BICUBICrM   rk   rl   r   r%   rp   re   rh   rj   do_convert_rgbr1   valid_kwargsmodel_input_namesr   rE   r   r   r   rK   r   rP   r   r   r)   rd   boolfloatr7   r   r6   r   __classcell__)rG   s   @r!   r<   r<   b   s   !))H4J4I,JD!DIJLN.L'7#(C!D # 4 4v>Y7Z 4_k 4 4 OS%
%
 %
 	%

 L%
 
%
N#>*# %S/*# 
	#N 8<3
^$3
 3
 	3

 L3
 3
 3
 3
 3
 3
 DK'$.3
 4;&-3
 +3
 j(4/3
 cNX-43
" 
#3
r#   r<   rJ   )#r5   r*   r^   torchvision.transforms.v2r   tvFimage_processing_backendsr   image_processing_utilsr   r   image_transformsr   r	   image_utilsr
   r   r   r   r   processing_utilsr   r   utilsr   r   r   r)   r"   r   r7   r/   r1   r<   __all__r9   r#   r!   <module>r      s   )   7 ; A E e e 4 //%S/ /uS#X /SV /0 8<	%L%L
c3h
$s)
+eCj
8%L eCHo%S	1E#J>%L --4	%L
 %LP%,e % H
. H
 H
V #
#r#   