Ë
    ÛÓ^jçH  ã            
       ó2  — d dl Z d dlmZ d dlmZ d dlZd dlmc mZ	 d dl
m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mZmZ ddlmZ ddlmZmZ ddlm Z m!Z!m"Z"m#Z#  G d„ ded¬«      Z$ddde%ee%   z  de&de%def
d„Z'e! G d„ de«      «       Z(dgZ)y)é    N)ÚIterable)ÚUnion)Ú
functionalé   )ÚTorchvisionBackend)ÚBatchFeature)Ú'SemanticSegmentationPostProcessorOutput)Úgroup_images_by_shapeÚreorder_images)ÚChannelDimensionÚ
ImageInputÚPILImageResamplingÚSizeDict)ÚDepthEstimatorOutput)ÚImagesKwargsÚUnpack)Ú
TensorTypeÚauto_docstringÚis_torch_availableÚrequires_backendsc                   ó:   — e Zd ZU dZeed<   eed<   eed<   eed<   y)ÚCHMv2ImageProcessorKwargsa=  
    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_labelsN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚintÚ__annotations__Úbool© ó    ú{/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/chmv2/image_processing_chmv2.pyr   r   '   s!   … ñð ÓØÓØÓØÔr%   r   F)ÚtotalÚinput_imageútorch.TensorÚoutput_sizer   ÚmultipleÚreturnc                 óâ   — dd„}| j                   dd  \  }}|\  }}||z  }	||z  }
|r"t        d|
z
  «      t        d|	z
  «      k  r|
}	n|	}
 ||	|z  |¬«      } ||
|z  |¬«      }t        ||¬«      S )Nc                 ó¬   — t        | |z  «      |z  }|� ||kD  rt        j                  | |z  «      |z  }||k  rt        j                  | |z  «      |z  }|S ©N)ÚroundÚmathÚfloorÚceil)Úvalr+   Úmin_valÚmax_valÚxs        r&   Úconstrain_to_multiple_ofz>get_resize_output_image_size.<locals>.constrain_to_multiple_ofA   s[   € Ü�#˜‘.Ó! HÑ,ˆàÐ 1 w¢;Ü—
‘
˜3 ™>Ó*¨XÑ5ˆAàˆwŠ;Ü—	‘	˜# ™.Ó)¨HÑ4ˆAàˆr%   éþÿÿÿé   )r+   ©ÚheightÚwidth)r   N)ÚshapeÚabsr   )r(   r*   r   r+   r8   Úinput_heightÚinput_widthÚoutput_heightÚoutput_widthÚscale_heightÚscale_widthÚ
new_heightÚ	new_widths                r&   Úget_resize_output_image_sizerH   ;   sš   € ó	ð !,× 1Ñ 1°"°#Ð 6Ñ€L�+Ø"-Ñ€M�<ð ! <Ñ/€LØ Ñ,€Káäˆq�;‰Ó¤# a¨,Ñ&6Ó"7Ò7à&‰Lð 'ˆKá)¨,¸Ñ*EÐPXÔY€JÙ(¨°{Ñ)BÈXÔV€Iä˜:¨YÔ7Ð7r%   c            $       óx  ‡ — e Zd ZdZeZej                  Zg d¢Z	g d¢Z
dddœZdZdZdZdZdZdZdZdZd	Zd
ZdZd
Zdee   fˆ fd„Ze	 d7dededz  dee   defˆ fd„«       Z	 d7dededz  dedede e!z  dz  de"e df   dz  defd„Z#de$d   de$d   fd„Z%de$d   de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'e(dz  d(ed)e(dz  d*edz  def$d+„Z)	 d8d,e$e*   dz  d-edd.fd/„Z+	 	 	 d9d0dde&ddd1ed'e(dz  d&eddfˆ fd2„Z,	 d:d0dd)e(ddfd3„Z-	 d7d4d5d,e!e$e*e(e(f      z  dz  dz  de$e.e e!f      fd6„Z/ˆ xZ0S );ÚCHMv2ImageProcessorz0PIL 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        ‰| �  di |¤Ž y )Nr$   )ÚsuperÚ__init__)ÚselfrL   Ú	__class__s     €r&   rO   zCHMv2ImageProcessor.__init__z   s   ø€ Ü‰ÑÑ"˜6Ó"r%   ÚimagesÚsegmentation_mapsr,   c                 ó&   •— t        ‰| �  ||fi |¤ŽS )zp
        segmentation_maps (`ImageInput`, *optional*):
            The segmentation maps to preprocess.
        )rN   Ú
preprocess)rP   rR   rS   rL   rQ   s       €r&   rU   zCHMv2ImageProcessor.preprocess}   s   ø€ ô ‰wÑ! &Ð*;ÑF¸vÑFÐFr%   Údo_convert_rgbÚinput_data_formatÚreturn_tensorsÚdeviceztorch.devicec                 óä  — | j                  ||||¬«      }|j                  «       }d|d<   i }	 | j                  |fi |¤Ž|	d<   |�›| j                  |ddt        j                  ¬«      }
|j                  «       }|j                  dddœ«        | j                  dd|
i|¤Ž}
|
D �cg c]0  }|j                  d	«      j                  t        j                  «      ‘Œ2 }
}|
|	d
<   t        |	|¬«      S c c}w )z"Handle extra inputs beyond images.)rR   rV   rW   rY   Fr   Úpixel_valuesé   )rR   Úexpected_ndimsrV   rW   )Údo_normalizeÚ
do_rescalerR   r   Úlabels)ÚdataÚtensor_typer$   )Ú_prepare_image_like_inputsÚcopyÚ_preprocessr   ÚFIRSTÚupdateÚsqueezeÚtoÚtorchÚint64r   )rP   rR   rS   rV   rW   rX   rY   rL   Úimages_kwargsra   Úprocessed_segmentation_mapsÚsegmentation_maps_kwargsÚprocessed_segmentation_maps                r&   Ú_preprocess_image_like_inputsz1CHMv2ImageProcessor._preprocess_image_like_inputsŠ   s+  € ð ×0Ñ0Ø¨.ÐL]Ðflð 1ó 
ˆð Ÿ™›ˆØ,1ˆÐ(Ñ)ØˆØ/˜t×/Ñ/°ÑH¸-ÑHˆˆ^Ñð Ð(Ø*.×*IÑ*IØ(Ø Ø$Ü"2×"8Ñ"8ð	 +Jó +Ð'ð (.§{¡{£}Ð$Ø$×+Ñ+¸UÐRWÑ,XÔYØ*:¨$×*:Ñ*:ñ +Ø2ð+Ø6Nñ+Ð'ð 3Nö+à.ð +×2Ñ2°1Ó5×8Ñ8¼¿¹ÕEð+Ð'ð +ð 9ˆD�‰Nä °>ÔBÐBùò+s   Â$5C-r`   r)   c           	      óf  — t        t        |«      «      D ]™  }||   }t        j                  |dk(  t        j                  d|j
                  |j                  ¬«      |«      }|dz
  }t        j                  |dk(  t        j                  d|j
                  |j                  ¬«      |«      }|||<   Œ› |S )z/Reduce label values by 1, replacing 0 with 255.r   éÿ   )ÚdtyperY   r:   éþ   )ÚrangeÚlenrj   ÚwhereÚtensorrs   rY   )rP   r`   ÚidxÚlabels       r&   Úreduce_labelz CHMv2ImageProcessor.reduce_label¶   sš   € äœ˜V›Ó%ò 	 ˆCØ˜3‘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ØˆF�3ŠKð	 ð ˆr%   r   Ú	do_resizeÚsizeÚresamplez7PILImageResampling | tvF.InterpolationMode | int | NoneÚdo_center_cropÚ	crop_sizer_   Úrescale_factorr^   Ú
image_meanÚ	image_stdr   r   Údo_padr   Údisable_groupingc           	      óÄ  — |r| j                  |«      }t        ||¬«      \  }}i }|j                  «       D ]"  \  }}|r| j                  |||||¬«      }|||<   Œ$ t	        ||«      }t        ||¬«      \  }}i }|j                  «       D ]H  \  }}|r| j                  ||«      }| j                  |||	|
||«      }|r| j                  ||«      }|||<   ŒJ t	        ||«      }|S )zCustom preprocessing for CHMV2.)r…   )Úimager}   r~   r   r   )r{   r
   ÚitemsÚresizer   Úcenter_cropÚrescale_and_normalizeÚ	pad_image)rP   rR   r   r|   r}   r~   r   r€   r_   r�   r^   r‚   rƒ   r   r   r„   r   r…   rL   Úgrouped_imagesÚgrouped_images_indexÚresized_images_groupedr>   Ústacked_imagesÚresized_imagesÚprocessed_images_groupedÚprocessed_imagess                              r&   re   zCHMv2ImageProcessor._preprocessÀ   s5  € ñ, Ø×&Ñ& 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Ø 
¨N¸LÈ*ÐV_óˆNñ Ø!%§¡°ÀÓ!M�Ø.<Ð$ UÒ+ð		=ô *Ð*BÐDXÓYÐàÐr%   Útarget_sizesÚreturn_segmentation_scoreszBlist[torch.Tensor] | list[SemanticSegmentationPostProcessorOutput]c                 óÄ  — t        «       st        d«      ‚|j                  }|�Ít        |«      t        |«      k7  rt	        d«      ‚t        |t        j                  «      r|j                  «       }g }t        t        |«      «      D ]g  }t        j                  ||   j                  d¬«      ||   dd¬«      }|d   j                  d¬«      }|j                  t        ||d   dœ¬	«      «       Œi nJ|j                  d
¬«      }	t        |j                   d   «      D �
cg c]  }
t        |	|
   ||
   dœ¬	«      ‘Œ }}
|s|D �cg c]  }|j"                  ‘Œ }}|S c c}
w c c}w )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.
            return_segmentation_scores (`bool`, *optional*, defaults to `False`):
                Whether to return segmentation scores alongside the segmentation map. When `True`, each element of
                the returned list is a [`SemanticSegmentationPostProcessorOutput`] with fields `segmentation`
                (class IDs, shape `(height, width)`) and `segmentation_scores` (shape `(num_classes, height, width)`).

        Returns:
            `list[torch.Tensor]` or `list[SemanticSegmentationPostProcessorOutput]`: When
            `return_segmentation_scores=False` (default), a list of length `batch_size` where each item is a
            segmentation map of shape `(height, width)` with class IDs. When `return_segmentation_scores=True`,
            a list of [`SemanticSegmentationPostProcessorOutput`] with fields `segmentation` (class IDs, shape
            `(height, width)`) and `segmentation_scores` (shape `(num_classes, height, width)`). In both cases,
            `(height, width)` corresponds to the target size (if `target_sizes` is specified).
        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_corners)ÚsegmentationÚsegmentation_scores)ra   r:   )r   ÚImportErrorÚlogitsrv   Ú
ValueErrorÚ
isinstancerj   ÚTensorÚnumpyru   ÚFÚinterpolateÚ	unsqueezeÚargmaxÚappendr	   r>   rœ   )rP   Úoutputsr”   r•   rŸ   Úsemantic_segmentationry   Úresized_logitsÚsemantic_mapÚseg_mapsÚiÚitems               r&   Ú"post_process_semantic_segmentationz6CHMv2ImageProcessor.post_process_semantic_segmentationû   sy  € ô2 "Ô#ÜÐZÓ[Ð[à—‘ˆð Ð#Ü�6‹{œc ,Ó/Ò/Ü Øjóð ô ˜,¬¯©Ô5Ø+×1Ñ1Ó3�à$&Ð!äœS ›[Ó)ò 	�Ü!"§¡Ø˜3‘K×)Ñ)¨aÐ)Ó0°|ÀCÑ7HÈzÐinô"�ð  .¨aÑ0×7Ñ7¸AÐ7Ó>�Ø%×,Ñ,Ü;Ø.:ÐSaÐbcÑSdÑeôõñ	ð —}‘}¨�}Ó+ˆHô
 ˜vŸ|™|¨A™Ó/ö	%ð ô 8Ø*2°1©+ÈfÐUVÉiÑXöð%Ð!ð %ñ *ØCXÖ$Y¸4 T×%6Ó%6Ð$YÐ!Ð$Yà$Ð$ùò%ùò %Zs   ÄEÅEr‡   Ú	antialiasc                 óÜ   •— |j                   r|j                  st        d|j                  «       › �«      ‚t	        ||j                   |j                  f||¬«      }t
        ‰| �  ||||¬«      S )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    ÚkeysrH   rN   r‰   )	rP   r‡   r}   r~   r±   r   r   r*   rQ   s	           €r&   r‰   zCHMv2ImageProcessor.resize=  sl   ø€ ð: �{Š{ $§*¢*ÜÐcÐdh×dmÑdmÓdoÐcpÐqÓrÐrä2ØØŸ™ d§j¡jÐ1Ø/Ø'ô	
ˆô ‰w‰~˜e [¸8Èyˆ~ÓYÐYr%   c                 ó”   — |j                   dd \  }}d„ } |||«      \  }} |||«      \  }}	|||	|f}
t        j                  ||
«      S )a„  
        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.
        r9   Nc                 ó^   — t        j                  | |z  «      |z  }|| z
  }|dz  }||z
  }||fS )Nr\   )r1   r3   )r}   r   Únew_sizeÚpad_sizeÚpad_size_leftÚpad_size_rights         r&   Ú_get_padz/CHMv2ImageProcessor.pad_image.<locals>._get_padu  sA   € Ü—y‘y ¨Ñ!4Ó5¸ÑDˆHØ $‘ˆHØ$¨™MˆMØ%¨Ñ5ˆNØ  .Ð0Ð0r%   )r>   ÚtvFÚpad)rP   r‡   r   r<   r=   rº   Úpad_topÚ
pad_bottomÚpad_leftÚ	pad_rightÚpaddings              r&   rŒ   zCHMv2ImageProcessor.pad_imagee  s`   € ð Ÿ™ B CÐ(‰ˆ�ò	1ñ ' v¨|Ó<Ñˆ�Ù& u¨lÓ;Ñˆ�)Ø˜W i°Ð<ˆÜ�w‰w�u˜gÓ&Ð&r%   r©   r   c                 óv  — t        | d«       |j                  }|�"t        |«      t        |«      k7  rt        d«      ‚g }|€dgt        |«      z  n|}t	        ||«      D ]X  \  }}|�>t
        j                  j                  j                  |d   |dd¬«      j                  «       }|j                  d|i«       ŒZ |S )	aÊ  
        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.
        rj   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Ã   rv   r    Úziprj   Únnr   r¥   rh   r¨   )rP   r©   r”   rÃ   ÚresultsÚdepthÚtarget_sizes          r&   Úpost_process_depth_estimationz1CHMv2ImageProcessor.post_process_depth_estimation�  sÔ   € ô( 	˜$ Ô(à!×1Ñ1ˆàÐ$¬3¨Ó+?Ä3À|ÓCTÒ+TÜØoóð ð ˆØ8DÐ8L˜�v¤ OÓ 4Ò4ÐR^ˆÜ"% o°|Ó"Dò 	7ÑˆE�;ØÐ&ÜŸ™×+Ñ+×7Ñ7Ø˜/Ñ*°À:Ð]að 8ó ç‘'“)ð ð �N‰NÐ-¨uÐ5Õ6ð	7ð ˆr%   r/   )NF)Tr:   F)r:   )1r   r   r   r    r   Úvalid_kwargsr   ÚBICUBICr~   r‚   rƒ   r}   Údefault_to_squarer€   r|   r   r_   r^   r   r„   r�   r   r   r   r   rO   r   r   r   rU   r#   r   Ústrr   r   rp   Úlistr{   r   Úfloatr!   re   Útupler°   r‰   rŒ   ÚdictrÉ   Ú__classcell__)rQ   s   @r&   rJ   rJ   b   sR  ø„ á:à,€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 ðx diñ@%Ø%)¨%¡[°4Ñ%7ð@%Ø\`ð@%à	Mó@%ðN Ø)*Ø"'ñ&Zàð&Zð ð&Zð Lð	&Zð
 ð&Zð   $™Jð&Zð  ð&Zð 
õ&ZðV ñ'àð'ð ð'ð 
ó	'ð> JNñ'à'ð'ð ! 4¨¨c°3¨h©Ñ#8Ñ8¸4Ñ?À$ÑFð'ð 
ˆd�3˜
�?Ñ#Ñ	$÷	'r%   rJ   )*r1   Úcollections.abcr   Útypingr   rj   Útorch.nn.functionalrÅ   r   r¤   Útorchvision.transforms.v2r»   Úimage_processing_backendsr   Úimage_processing_baser   Úimage_processing_outputsr	   Úimage_transformsr
   r   Úimage_utilsr   r   r   r   Úmodeling_outputsr   Úprocessing_utilsr   r   Úutilsr   r   r   r   r   r!   r#   rH   rJ   Ú__all__r$   r%   r&   ú<module>rà      s¯   ðó* Ý $Ý ã ß Ð Ý 7å ;Ý 1Ý Oß Eß UÓ UÝ 4ß 4ß VÓ Vô °Eõ ð($8Øð$8à�x ‘}Ñ$ð$8ð ð$8ð ð	$8ð
 ó$8ðN ôEÐ,ó Eó ðEðP
 !Ð
!�r%   