ó
    qyüifC  ã            
       ó"  • S SK r S SKJr  S SKJr  S SKrS SKJs  Jr	  S SK
Jr  SSKJr  SSKJr  SSKJrJr  SS	KJrJrJrJr  SS
KJr  SSKJrJr  SSKJrJrJ r J!r!   " S S\SS9r"SSS\#\\#   -  S\$S\#S\4
S jr%\ " S S\5      5       r&S/r'g)é    N)ÚIterable)ÚUnion)Ú
functionalé   )ÚTorchvisionBackend)ÚBatchFeature)Úgroup_images_by_shapeÚreorder_images)ÚChannelDimensionÚ
ImageInputÚPILImageResamplingÚSizeDict)ÚDepthEstimatorOutput)ÚImagesKwargsÚUnpack)Ú
TensorTypeÚauto_docstringÚis_torch_availableÚrequires_backendsc                   óB   • \ rS rSr% Sr\\S'   \\S'   \\S'   \\S'   Srg)	ÚCHMv2ImageProcessorKwargsé&   a  
ensure_multiple_of (`int`, *optional*, defaults to 1):
    If `do_resize` is `True`, the image is resized to a size that is a multiple of this value. Can be overridden
    by `ensure_multiple_of` in `preprocess`.
keep_aspect_ratio (`bool`, *optional*, defaults to `False`):
    If `True`, the image is resized to the largest possible size such that the aspect ratio is preserved. Can
    be overridden by `keep_aspect_ratio` in `preprocess`.
do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):
    Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0
    is used for background, and background itself is not included in all classes of a dataset (e.g.
    ADE20k). The background label will be replaced by 255.
Úensure_multiple_ofÚsize_divisorÚkeep_aspect_ratioÚdo_reduce_labels© N)	Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__ÚintÚ__annotations__ÚboolÚ__static_attributes__r   ó    Úm/home/mande/repo/quber/.venv/lib/python3.13/site-packages/transformers/models/chmv2/image_processing_chmv2.pyr   r   &   s!   ‡ ñð ÓØÓØÓØÖr'   r   F)ÚtotalÚinput_imageútorch.TensorÚoutput_sizer   ÚmultipleÚreturnc                 óÐ   • SS jnU R                   SS  u  pVUu  pxXu-  n	X†-  n
U(       a#  [        SU
-
  5      [        SU	-
  5      :  a  U
n	OU	n
U" X•-  US9nU" X¦-  US9n[        X¼S9$ )Nc                 ó¬   • [        X-  5      U-  nUb   XC:”  a  [        R                  " X-  5      U-  nXB:  a  [        R                  " X-  5      U-  nU$ ©N)ÚroundÚmathÚfloorÚceil)Úvalr-   Úmin_valÚmax_valÚxs        r(   Úconstrain_to_multiple_ofÚ>get_resize_output_image_size.<locals>.constrain_to_multiple_of@   sQ   € Ü�#‘.Ó! HÑ,ˆàÑ 1£;Ü—
’
˜3™>Ó*¨XÑ5ˆAà‹;Ü—	’	˜#™.Ó)¨HÑ4ˆAàˆr'   éþÿÿÿé   )r-   ©ÚheightÚwidth)r   N)ÚshapeÚabsr   )r*   r,   r   r-   r:   Úinput_heightÚinput_widthÚoutput_heightÚoutput_widthÚscale_heightÚscale_widthÚ
new_heightÚ	new_widths                r(   Úget_resize_output_image_sizerK   :   sŒ   € ô	ð !,× 1Ñ 1°"°#Ð 6Ñ€LØ"-Ñ€Mð !Ñ/€LØÑ,€Kæäˆq�;‰Ó¤# a¨,Ñ&6Ó"7Ó7à&‰Lð 'ˆKá)¨,Ñ*EÐPXÑY€JÙ(¨Ñ)BÈXÑV€Iä˜:Ñ7Ð7r'   c            $       óš  ^ • \ rS rSrSr\r\R                  r	/ SQr
/ SQrSSS.rSrSrS	rSrSrSrSrSrS
rSrSrSrS\\   4U 4S jjr\ S7S\S\S-  S\\   S\4U 4S jjj5       r S7S\S\S-  S\S\ S\!\"-  S-  S\#\!S4   S-  S\4S jjr$S\%S   S\%S   4S jr&S\%S   S\S\S\'SSS \S!\'S"\S#\(S$\S%\(\%\(   -  S-  S&\(\%\(   -  S-  S'\S(\)S-  S)\S*\)S-  S+\S-  S\4$S, jr*S7S-\%\+   S-  4S. jjr,   S8S/SS\'SSS0\S(\)S-  S'\SS4U 4S1 jjjr- S9S/SS*\)SS4S2 jjr. S7S3S4S-\"\%\+\)\)4      -  S-  S-  S\%\/\!\"4      4S5 jjr0S6r1U =r2$ ):ÚCHMv2ImageProcessoréa   z0PIL backend for CHMV2 with reduce_label support.)gáz®GáÚ?gçû©ñÒMÚ?g‹lçû©ñÒ?)gÝ$�•CË?g+‡ÙÎ÷Ã?gçû©ñÒMÂ?i€  r>   TNFgp?é   Úkwargsc                 ó&   >• [         TU ]  " S0 UD6  g )Nr   )ÚsuperÚ__init__)ÚselfrP   Ú	__class__s     €r(   rS   ÚCHMv2ImageProcessor.__init__y   s   ø€ Ü‰ÒÑ"˜6Ó"r'   ÚimagesÚsegmentation_mapsr.   c                 ó&   >• [         TU ]  " X40 UD6$ )zX
segmentation_maps (`ImageInput`, *optional*):
    The segmentation maps to preprocess.
)rR   Ú
preprocess)rT   rW   rX   rP   rU   s       €r(   rZ   ÚCHMv2ImageProcessor.preprocess|   s   ø€ ô ‰wÒ! &ÑF¸vÑFÐFr'   Údo_convert_rgbÚinput_data_formatÚreturn_tensorsÚdeviceztorch.devicec                 óÒ  • U R                  XXFS9nUR                  5       nSUS'   0 n	U R                  " U40 UD6U	S'   Ubš  U R                  USS[        R                  S9n
UR                  5       nUR                  SSS.5        U R                  " SSU
0UD6n
U
 Vs/ s H1  nUR                  S	5      R                  [        R                  5      PM3     n
nX©S
'   [        X•S9$ s  snf )z"Handle extra inputs beyond images.)rW   r\   r]   r_   Fr   Úpixel_valuesé   )rW   Úexpected_ndimsr\   r]   )Údo_normalizeÚ
do_rescalerW   r   Úlabels)ÚdataÚtensor_typer   )Ú_prepare_image_like_inputsÚcopyÚ_preprocessr   ÚFIRSTÚupdateÚsqueezeÚtoÚtorchÚint64r   )rT   rW   rX   r\   r]   r^   r_   rP   Úimages_kwargsrg   Úprocessed_segmentation_mapsÚsegmentation_maps_kwargsÚprocessed_segmentation_maps                r(   Ú_preprocess_image_like_inputsÚ1CHMv2ImageProcessor._preprocess_image_like_inputs‰   s!  € ð ×0Ñ0ØÐL]ð 1ð 
ˆð Ÿ™›ˆØ,1ˆÐ(Ñ)ØˆØ#×/Ò/°ÑH¸-ÑHˆˆ^Ñð Ñ(Ø*.×*IÑ*IØ(Ø Ø$Ü"2×"8Ñ"8ð	 +Jð +Ð'ð (.§{¡{£}Ð$Ø$×+Ñ+¸UÐRWÑ,XÔYØ*.×*:Ò*:ñ +Ø2ð+Ø6Nñ+Ð'ñ 3Nó+â2MÐ.ð +×2Ñ2°1Ó5×8Ñ8¼¿¹ÖEÙ2Mð (ð +ð 9�‰Nä ÑBÐBùò+s   Â8C$rf   r+   c           
      ób  • [        [        U5      5       H–  nX   n[        R                  " US:H  [        R                  " SUR
                  UR                  S9U5      nUS-
  n[        R                  " US:H  [        R                  " SUR
                  UR                  S9U5      nX1U'   M˜     U$ )z/Reduce label values by 1, replacing 0 with 255.r   éÿ   )Údtyper_   r=   éþ   )ÚrangeÚlenrp   ÚwhereÚtensorrz   r_   )rT   rf   ÚidxÚlabels       r(   Úreduce_labelÚ CHMv2ImageProcessor.reduce_labelµ   s‘   € äœ˜V›Ö%ˆCØ‘KˆEÜ—K’K ¨¡
¬E¯LªL¸ÀEÇKÁKÐX]×XdÑXdÑ,eÐglÓmˆEØ˜A‘IˆEÜ—K’K ¨¡¬e¯lªl¸3ÀeÇkÁkÐZ_×ZfÑZfÑ.gÐinÓoˆEØ�3‹Kñ &ð ˆr'   r   Ú	do_resizeÚsizeÚresamplez7PILImageResampling | tvF.InterpolationMode | int | NoneÚdo_center_cropÚ	crop_sizere   Úrescale_factorrd   Ú
image_meanÚ	image_stdr   r   Údo_padr   Údisable_groupingc           	      óÞ  • U(       a  U R                  U5      n[        UUS9u  nn0 nUR                  5        H%  u  nnU(       a  U R                  UUUUUS9nUUU'   M'     [	        UU5      n[        UUS9u  nn0 nUR                  5        HQ  u  nnU(       a  U R                  UU5      nU R                  UX‰X«U5      nU(       a  U R                  UU5      nUUU'   MS     [	        UU5      nU$ )zCustom preprocessing for CHMV2.)r�   )Úimager…   r†   r   r   )r‚   r	   ÚitemsÚresizer
   Úcenter_cropÚrescale_and_normalizeÚ	pad_image)rT   rW   r   r„   r…   r†   r‡   rˆ   re   r‰   rd   rŠ   r‹   r   r   rŒ   r   r�   rP   Úgrouped_imagesÚgrouped_images_indexÚresized_images_groupedrA   Ústacked_imagesÚresized_imagesÚprocessed_images_groupedÚprocessed_imagess                              r(   rk   ÚCHMv2ImageProcessor._preprocess¿   s'  € ö, Ø×&Ñ& vÓ.ˆFô 0EÀVÐ^nÑ/oÑ,ˆÐ,Ø!#ÐØ%3×%9Ñ%9Ö%;Ñ!ˆE�>ÞØ!%§¡Ø(ØØ%Ø'9Ø&7ð "-ð "�ð -;Ð" 5Ó)ñ &<ô (Ð(>Ð@TÓUˆô 0EÀ^ÐfvÑ/wÑ,ˆÐ,Ø#%Ð Ø%3×%9Ñ%9Ö%;Ñ!ˆE�>ÞØ!%×!1Ñ!1°.À)Ó!L�à!×7Ñ7Ø 
¸LÐV_óˆNö Ø!%§¡°ÀÓ!M�Ø.<Ð$ UÓ+ñ &<ô *Ð*BÐDXÓYÐàÐr'   Útarget_sizesc                 óL  • [        5       (       d  [        S5      eUR                  nUb¼  [        U5      [        U5      :w  a  [	        S5      e[        U[        R                  5      (       a  UR                  5       n/ n[        [        U5      5       HN  n[        R                  " X5   R                  SS9X%   SSS9nUS   R                  SS9nUR                  U5        MP     U$ UR                  SS9n[        UR                  S   5       Vs/ s H  o„U   PM	     nnU$ s  snf )	aÁ  
Converts the output of [`CHMv2ForSemanticSegmentation`] into semantic segmentation maps.

Args:
    outputs ([`CHMv2ForSemanticSegmentation`]):
        Raw outputs of the model.
    target_sizes (`list[Tuple]` of length `batch_size`, *optional*):
        List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
        predictions will not be resized.

Returns:
    semantic_segmentation: `list[torch.Tensor]` of length `batch_size`, where each item is a semantic
    segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
    specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
z:PyTorch is required for post_process_semantic_segmentationzTMake sure that you pass in as many target sizes as the batch dimension of the logitsr   )ÚdimÚbilinearF©r…   ÚmodeÚalign_cornersr=   )r   ÚImportErrorÚlogitsr}   Ú
ValueErrorÚ
isinstancerp   ÚTensorÚnumpyr|   ÚFÚinterpolateÚ	unsqueezeÚargmaxÚappendrA   )	rT   Úoutputsr�   r¥   Úsemantic_segmentationr€   Úresized_logitsÚsemantic_mapÚis	            r(   Ú"post_process_semantic_segmentationÚ6CHMv2ImageProcessor.post_process_semantic_segmentationú   s+  € ô  "×#Ñ#ÜÐZÓ[Ð[à—‘ˆð Ñ#Ü�6‹{œc ,Ó/Ó/Ü Øjóð ô ˜,¬¯©×5Ñ5Ø+×1Ñ1Ó3�à$&Ð!äœS ›[Ö)�Ü!"§¢Ø‘K×)Ñ)¨aÐ)Ð0°|Ñ7HÈzÐinñ"�ð  .¨aÑ0×7Ñ7¸AÐ7Ð>�Ø%×,Ñ,¨\Ö:ñ *ð %Ð$ð %+§M¡M°a MÐ$8Ð!ÜGLÐMb×MhÑMhÐijÑMkÔGlÓ$mÒGlÀ!¸1Ô%=ÑGlÐ!Ð$mà$Ð$ùò %ns   ÄD!r�   Ú	antialiasc                 óà   >• UR                   (       a  UR                  (       d  [        SUR                  5        35      e[	        UUR                   UR                  4UUS9n[
        TU ]  XX4S9$ )a´  
Resize an image to `(size["height"], size["width"])`.

Args:
    image (`torch.Tensor`):
        Image to resize.
    size (`SizeDict`):
        Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
    interpolation (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
        `InterpolationMode` filter to use when resizing the image e.g. `InterpolationMode.BICUBIC`.
    antialias (`bool`, *optional*, defaults to `True`):
        Whether to use antialiasing when resizing the image
    ensure_multiple_of (`int`, *optional*):
        If `do_resize` is `True`, the image is resized to a size that is a multiple of this value
    keep_aspect_ratio (`bool`, *optional*, defaults to `False`):
        If `True`, and `do_resize` is `True`, the image is resized to the largest possible size such that the aspect ratio is preserved.

Returns:
    `torch.Tensor`: The resized image.
zDThe size dictionary must contain the keys 'height' and 'width'. Got )r,   r   r-   )r†   r¶   )r?   r@   r¦   ÚkeysrK   rR   r‘   )	rT   r�   r…   r†   r¶   r   r   r,   rU   s	           €r(   r‘   ÚCHMv2ImageProcessor.resize'  sh   ø€ ð: �{�{ $§*§*ÜÐcÐdh×dmÑdmÓdoÐcpÐqÓrÐrä2ØØŸ™ d§j¡jÐ1Ø/Ø'ñ	
ˆô ‰w‰~˜e¸8ˆ~ÐYÐYr'   c                 ó†   • UR                   SS u  p4S nU" X25      u  pgU" XB5      u  p‰X†X—4n
[        R                  " X5      $ )aL  
Center pad a batch of images to be a multiple of `size_divisor`.

Args:
    image (`torch.Tensor`):
        Image to pad.  Can be a batch of images of dimensions (N, C, H, W) or a single image of dimensions (C, H, W).
    size_divisor (`int`):
        The width and height of the image will be padded to a multiple of this number.
r<   Nc                 óX   • [         R                  " X-  5      U-  nX -
  nUS-  nX4-
  nXE4$ )Nrb   )r3   r5   )r…   r   Únew_sizeÚpad_sizeÚpad_size_leftÚpad_size_rights         r(   Ú_get_padÚ/CHMv2ImageProcessor.pad_image.<locals>._get_pad_  s9   € Ü—y’y Ñ!4Ó5¸ÑDˆHØ‘ˆHØ$¨™MˆMØ%Ñ5ˆNØ Ð0Ð0r'   )rA   ÚtvFÚpad)rT   r�   r   r?   r@   rÀ   Úpad_topÚ
pad_bottomÚpad_leftÚ	pad_rightÚpaddings              r(   r”   ÚCHMv2ImageProcessor.pad_imageO  sP   € ð Ÿ™ B CÐ(‰ˆò	1ñ ' vÓ<ÑˆÙ& uÓ;ÑˆØ iÐ<ˆÜ�wŠw�uÓ&Ð&r'   r¯   r   c                 óx  • [        U S5        UR                  nUb#  [        U5      [        U5      :w  a  [        S5      e/ nUc  S/[        U5      -  OUn[	        X25       HV  u  pVUb;  [
        R                  R                  R                  US   USSS9R                  5       nUR                  SU05        MX     U$ )	aj  
Converts the raw output of [`DepthEstimatorOutput`] into final depth predictions and depth PIL images.
Only supports PyTorch.

Args:
    outputs ([`DepthEstimatorOutput`]):
        Raw outputs of the model.
    target_sizes (`TensorType` or `List[Tuple[int, int]]`, *optional*):
        Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size
        (height, width) of each image in the batch. If left to None, predictions will not be resized.

Returns:
    `List[Dict[str, TensorType]]`: A list of dictionaries of tensors representing the processed depth
    predictions.
rp   Nz]Make sure that you pass in as many target sizes as the batch dimension of the predicted depth)NN.r    Tr¡   Úpredicted_depth)r   rË   r}   r¦   Úziprp   Únnr   r«   rn   r®   )rT   r¯   r�   rË   ÚresultsÚdepthÚtarget_sizes          r(   Úpost_process_depth_estimationÚ1CHMv2ImageProcessor.post_process_depth_estimationk  sÌ   € ô( 	˜$ Ô(à!×1Ñ1ˆàÑ$¬3¨Ó+?Ä3À|ÓCTÓ+TÜØoóð ð ˆØ8DÑ8L˜�v¤ OÓ 4Ò4ÐR^ˆÜ"% oÖ"DÑˆEØÑ&ÜŸ™×+Ñ+×7Ñ7Ø˜/Ñ*°À:Ð]að 8ð ç‘'“)ð ð �N‰NÐ-¨uÐ5Ö6ñ #Eð ˆr'   r   r1   )Tr=   F)r=   )3r   r   r    r!   r"   r   Úvalid_kwargsr   ÚBICUBICr†   rŠ   r‹   r…   Údefault_to_squarerˆ   r„   r‡   re   rd   r   rŒ   r‰   r   r   r   r   rS   r   r   r   rZ   r%   r   Ústrr   r   rv   Úlistr‚   r   Úfloatr#   rk   Útupler´   r‘   r”   ÚdictrÑ   r&   Ú__classcell__)rU   s   @r(   rM   rM   a   sB  ø† á:à,€LØ!×)Ñ)€HÚ&€JÚ%€IØ CÑ(€DØÐð €IØ€IØ€NØ€JØ€LØÐØ€FØ€NØÐØÐØ€Lð# Ð(AÑ!B÷ #ð ð 04ñ
Gàð
Gð &¨Ñ,ð
Gð Ð2Ñ3ð	
Gð
 
÷
Gó ð
Gð& 59ñ*Càð*Cð &¨Ñ,ð*Cð ð	*Cð
 ,ð*Cð ˜jÑ(¨4Ñ/ð*Cð �c˜>Ð)Ñ*¨TÑ1ð*Cð 
õ*CðX 4¨Ñ#7ð ¸DÀÑ<Pô ð9 à�^Ñ$ð9 ð ð9 ð ð	9 ð
 ð9 ð Lð9 ð ð9 ð ð9 ð ð9 ð ð9 ð ð9 ð ˜D ™KÑ'¨$Ñ.ð9 ð ˜4 ™;Ñ&¨Ñ-ð9 ð  ð9 ð   $™Jð9 ð  ð!9 ð" ˜D‘jð#9 ð$  ™+ð%9 ð( 
ô)9 ñv+%ÈÈUÉÐVZÑHZõ +%ðd Ø)*Ø"'ñ&Zàð&Zð ð&Zð Lð	&Zð
 ð&Zð   $™Jð&Zð  ð&Zð 
÷&Zð &ZðV ñ'àð'ð ð'ð 
õ	'ð> JNñ'à'ð'ð ! 4¨¨c°3¨h©Ñ#8Ñ8¸4Ñ?À$ÑFð'ð 
ˆd�3˜
�?Ñ#Ñ	$÷	'ó 'r'   rM   )(r3   Úcollections.abcr   Útypingr   rp   Útorch.nn.functionalrÍ   r   rª   Útorchvision.transforms.v2rÂ   Úimage_processing_backendsr   Úimage_processing_baser   Úimage_transformsr	   r
   Úimage_utilsr   r   r   r   Úmodeling_outputsr   Úprocessing_utilsr   r   Úutilsr   r   r   r   r   r#   r%   rK   rM   Ú__all__r   r'   r(   Ú<module>rè      s¬   ðó* Ý $Ý ã ß Ð Ý 7å ;Ý 1ß Eß UÓ UÝ 4ß 4ß VÓ Vô °Eò ð($8Øð$8à�x ‘}Ñ$ð$8ð ð$8ð ð	$8ð
 ô$8ðN ôpÐ,ó pó ðpðf	 !Ð
!�r'   