
    ^jH              
       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,1w;

3>*X5Aw;		#.)H4A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),*EPXYJ({)BXVI: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.)gzG?gM?gl?)g$C?g+?gM?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!&*;Fv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 +' (.{{}$$++URW,XY*:$*:*: +2+6N+' 3N+. +221588E+' + 9D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3KEKK
ELLEKKX]XdXd,eglmEAIEKKell3ekkZ_ZfZf.ginoEF3K	  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
NL*V_N !%!M.<$U+		= **BDX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[) 	!"3K))a)0|C7Hzin"  .a077A7>%,,;.:SabcSde	 }}}+H
 v||A/	%  8*21+fUViX%! % *CX$Y4T%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    : {{$**cdhdmdmdocpqrr2djj1/'	
 w~e[8y~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    yy!45DH$H$MM%5N .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`     BC(	1 'v|<&ul;)Wi<wwug&&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  8D8LvO 44R^"%o|"D 	7E;&++77/*:]a 8 ')  NN-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 " Dj#9 $ +%9 ( 
)9 x di@%%)%[4%7@%\`@%	M@%N )*"'&Z&Z &Z L	&Z
 &Z  $J&Z  &Z 
&ZV '' ' 
	'> JN''' !4c3h#884?$F' 
d3
?#	$	'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
 $8N E, E EP
 !
!r%   