
    ^j]*                     >   d dl Z d dlZd dlm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  ej&                  e      Zd	Zd
edededededeeef   fdZdddeddfdZdddddeded   fdZ G d ded      Z ed       G d de             ZdgZy)     N)
functional   )TorchvisionBackend)BatchFeature)
ImageInputPILImageResampling)ImagesKwargsUnpack)
TensorTypeauto_docstringlogging)F        i0  i`  heightwidth
patch_sizemax_patchespooling_kernel_sizereturnc                 p   | |z  }||dz  z  }t        j                  ||z        }|| z  }||z  }	||z  }
t        t        j                  ||
z              |
z  }t        t        j                  |	|
z              |
z  }|dk(  r|dk(  rt	        d||z   d      ||dz  z  |
z  }|dk(  r1|
}t        t        t        j                  || z              |
z  |      }n5|dk(  r0|
}t        t        t        j                  | |z              |
z  |      }||z  |kD  rt	        d|  d| d| d| d| d	|       ||fS )
a  
    Image is resized to preserve aspect ratio so it fits within the patch budget.
    Target dimensions are the largest that:
    1) Produce at most `max_patches` patches when patchified with `patch_size`
    2) Have height and width divisible by `pooling_kernel_size * patch_size`
       r   zpAttempting to resize to a 0 x 0 image. Resized height should be divisible by `pooling_kernel_size * patch_size`=.z
Resizing [xz] to [z] but this exceeds z patches with patch_size )mathsqrtintfloor
ValueErrormin)r   r   r   r   r   total_px	target_pxfactorideal_heightideal_width	side_multtarget_heighttarget_widthmax_side_lengths                 }/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/gemma4/image_processing_gemma4.py get_aspect_ratio_preserving_sizer+   !   s    ~Hz1}-IYYy8+,FF?L5.K#j0I 

<)#;<=	IMtzz+	"9:;iGL la/22E
2R1SSTV
 	

 #&91&<<	IO!

56>*+i7
 
	 

6E>*+i7

 |#i/%}oQ|n M  +},Ej\S
 	

 ,&&    imagetorch.Tensorc                     | j                   \  }}}||z  }||z  }| j                  |||||      }|j                  ddddd      }|j                  ||z  d      }|S )z
    Convert 3D tensor image of shape (num_channels, image_height, image_width) into 2D tensor of patches of shape
    (num_patches_height * num_patches_width, patch_size * patch_size * num_channels).
       r   r      r   )shapereshapepermute)r-   r   num_channelsimage_heightimage_widthnum_patches_heightnum_patches_widthpatched_images           r*   convert_image_to_patchesr<   X   s{    
 /4kk+L,%3#z1MM,0BJPacmnM!))!Q1a8M!))*<?P*PRTUMr,   	positionstarget_length)r.   r.   c                 .   | j                   d   }||z
  }|dkD  ryddg| j                  dz
  z  d|gz   }ddd|f}t        j                  j                  j                  | |dd      } t        j                  j                  j                  ||dd      }| |fS )z3
    Pad the tensor along the first dimension.
    r   r0   constant)modevaluer2   )r3   ndimtorchnnr   pad)r-   r=   r>   current_lengthpadding_lengthpaddingpos_paddings          r*   pad_along_first_dimrK   g   s     [[^N"^3Na&EJJN+q..AA!Q/##''wZq'QHH''++I{[]+^	)r,   c                   0    e Zd ZU dZeed<   eed<   eed<   y)Gemma4ImageProcessorKwargsaY  
    patch_size (`int`, *optional*):
        Size of each image patch in pixels.
    max_soft_tokens (`int`, *optional*):
        Maximum number of soft (vision) tokens per image.
        Must be one of {70, 140, 280, 560, 1120}.
    pooling_kernel_size (`int`, *optional*):
        Spatial pooling kernel size applied after patchification.
    r   max_soft_tokensr   N)__name__
__module____qualname____doc__r   __annotations__ r,   r*   rM   rM   w   s     Or,   rM   F)totalz$Constructs a Gemma4 image processor.)custom_introc                       e Zd Zej                  Zg dZg dZdZdZ	dZ
dZdZdZdZdZdZeZg d	Zd
ee   f fdZ fdZdej0                  dedededej6                  dej0                  fdZded
ee   def fdZ	 	 	 d!de d   de!ddde!de"de!de"e e"   z  dz  de"e e"   z  dz  de#e$z  dz  dedz  dedz  dedz  defd Z% xZ&S )"Gemma4ImageProcessor)        rY   rY   )      ?rZ   rZ   NTF   r   r   pixel_valuesimage_position_idsnum_soft_tokens_per_imagekwargsc                     t        |   di | | j                  t        vr t	        dt         d| j                   d      y )N!`max_soft_tokens` must be one of , got r   rT   )super__init__rN   _SUPPORTED_SOFT_TOKENSr   selfr`   	__class__s     r*   re   zGemma4ImageProcessor.__init__   sN    "6"'==@AW@XX^_c_s_s^ttuvww >r,   c                 .    d|d<   t        |   di | y )NF	do_resizerT   )rd   _validate_preprocess_kwargsrg   s     r*   rl   z0Gemma4ImageProcessor._validate_preprocess_kwargs   s    
 ${+5f5r,   r-   r   r   r   resampler   c                     |j                   d   |j                   d   }}t        |||||      \  }}	||k(  r|	|k(  r|S t        j                  |||	g|d      S )Nr2   )r   r   r   r   r   T)sizeinterpolation	antialias)r3   r+   tvFresize)
rh   r-   r   r   r   rm   r   r   r'   r(   s
             r*   aspect_ratio_preserving_resizez3Gemma4ImageProcessor.aspect_ratio_preserving_resize   ss     BR&F!# 3'
#| F"|u'<Lzz."	
 	
r,   imagesc                 $    t        |   |fi |S )N)rd   
preprocess)rh   rv   r`   ri   s      r*   rx   zGemma4ImageProcessor.preprocess   s    
 w!&3F33r,   r.   rk   z7PILImageResampling | tvF.InterpolationMode | int | None
do_rescalerescale_factordo_normalize
image_mean	image_stdreturn_tensorsrN   c           	      ^   |t         vrt        dt          d| d      ||dz  z  }g }g }g }|D ];  }|r| j                  ||
|||      }| j                  ||||||      }|j                  d   |
z  }|j                  d   |
z  }t        ||
      }|j                  |j                  d   |dz  z         |j                  }t        j                  t        j                  ||	      t        j                  ||	      d
      }t        j                  |d      }|j                  |j                  d   d      }t        |||      \  }}|j                  |       |j                  |       > t        j                  |d      }t        j                  |d      }|||d}t        ||	      S )Nrb   rc   r   r   )r-   r   r   r   rm   ro   r2   r   )devicexy)indexing)dimr\   )datatensor_type)rf   r   ru   rescale_and_normalizer3   r<   appendr   rD   meshgridarangestackr4   rK   r   )rh   rv   rk   rm   ry   rz   r{   r|   r}   r~   r   rN   r   r`   r   r]   position_idsr_   r-   patch_heightpatch_widthpatchesr   
patch_gridstacked_gridreal_positionsr=   r   s                               r*   _preprocessz Gemma4ImageProcessor._preprocess   s     "88@AW@XX^_n^oopqrr &(;Q(>>
 $&! "	+E;;) +(;% <  ..uj.R^`jluvE !;;r?j8L++b/Z7K.ujAG%,,W]]1-=ATVWAW-WX \\F[8\&9J
 !;;zr:L)11'--2BAFN "5Wnk!ZGY(	*E"	+J {{<Q7{{<Q7 )".)B

 >BBr,   )NNN)'rO   rP   rQ   r   BICUBICrm   r|   r}   rp   default_to_squaredo_convert_rgbrk   ry   r{   r   rN   r   rM   valid_kwargsmodel_input_namesr
   re   rl   rD   Tensorr   rs   InterpolationModeru   r   r   rx   listboolfloatstrr   r   __classcell__)ri   s   @r*   rX   rX      s   !))H JIDNIJLJO-L[x(B!C x6
||
 
 	

 !
 ''
 

644 344 
	4$ "&&**.JC^$JC JC L	JC
 JC JC JC DK'$.JC 4;&-JC j(4/JC $JJC tJC !4ZJC 
JCr,   rX   )r   rD   torchvision.transforms.v2r   rs   image_processing_backendsr   image_processing_utilsr   image_utilsr   r   processing_utilsr	   r
   utilsr   r   r   
get_loggerrO   loggerrf   r   tupler+   r<   rK   rM   rX   __all__rT   r,   r*   <module>r      s     7 ; 2 9 4 8 8 
		H	% 3 3'3'3' 3' 	3'
 3' 38_3'nN   &4EH
)* U   CDJC- JC EJCZ "
"r,   