Ë
    ÜÓ^jy@  ã                   ó$  — d Z ddlmZ ddlmZmZmZ ddlmZm	Z	 ddl
mZ  e«       rddlZddlmc mZ 	 	 ddd	d
d	dedededeed	f   fd„Z	 	 	 dd
d	dd	dd	dee   dz  dededeeef   dz  ded	eeeeez  f      f   fd„Z G d„ de«      ZdgZy)z"Video processor class for Videomt.é   )Ú'SemanticSegmentationPostProcessorOutput)ÚIMAGENET_DEFAULT_MEANÚIMAGENET_DEFAULT_STDÚPILImageResampling)Úis_torch_availableÚrequires_backends)ÚBaseVideoProcessoré    NÚmask_labelsútorch.TensorÚ
mask_probsÚ	query_idxÚmask_thresholdÚoverlap_mask_area_thresholdÚreturnc                 óì   — | |k(  }|j                  «       }||   |k\  }|j                  «       }||z  }	|	j                  «       }
|dkD  xr |dkD  xr |
dkD  }|r||z  }|j                  «       |kD  sd}||	fS )a„  
    Checks whether a predicted query produces a valid panoptic segment.

    Args:
        mask_labels (`torch.Tensor`):
            Tensor of shape `(height, width)` containing the winning query index for each pixel.
        mask_probs (`torch.Tensor`):
            Tensor of shape `(num_queries, height, width)` containing per-query mask probabilities.
        query_idx (`int`):
            Index of the query to validate.
        mask_threshold (`float`, *optional*, defaults to 0.5):
            Threshold used to binarize the query mask probabilities.
        overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
            Minimum overlap ratio required between the assigned query area and the original query mask area.

    Returns:
        `tuple[bool, torch.Tensor]`: A tuple containing whether the segment is valid and the final boolean mask for
        that segment.
    r
   F)ÚsumÚitem)r   r   r   r   r   Ú
query_maskÚquery_mask_areaÚoriginal_maskÚoriginal_areaÚ
final_maskÚfinal_mask_areaÚmask_existsÚ
area_ratios                ú/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/videomt/video_processing_videomt.pyÚcheck_segment_validityr      s™   € ð4  	Ñ)€JØ —n‘nÓ&€Oà˜yÑ)¨^Ñ;€MØ!×%Ñ%Ó'€Mà˜mÑ+€JØ —n‘nÓ&€Oà! AÑ%ÒS¨-¸!Ñ*;ÒSÀÐRSÑ@S€KáØ$ }Ñ4ˆ
Ø�‰Ó Ð#>Ò>ØˆKà˜
Ð"Ð"ó    Úpred_scoresÚpred_labelsÚlabel_ids_to_fuseÚtarget_sizec                 ób  — |€| j                   d   n|d   }|€| j                   d   n|d   }t        j                  ||ft        j                  | j                  ¬«      dz
  }	g }
| j                  «       } |dd…ddf   | z  j                  d«      }d}i }t        |j                   d   «      D ]~  }||   j                  «       }t        || |||«      \  }}|sŒ+|r||v r||v r	||   |	|<   Œ>|||<   ||	|<   t        ||   j                  «       d«      }|
j                  |||dœ«       |dz  }Œ€ |	|
fS )aÁ  
    Converts per-query mask predictions into a panoptic segmentation map.

    Args:
        mask_probs (`torch.Tensor`):
            Tensor of shape `(num_queries, height, width)` containing per-query mask logits.
        pred_scores (`torch.Tensor`):
            Tensor of shape `(num_queries,)` containing the confidence score of each predicted query.
        pred_labels (`torch.Tensor`):
            Tensor of shape `(num_queries,)` containing the predicted class ID of each query.
        label_ids_to_fuse (`set[int]`, *optional*):
            Label IDs that should be fused across disconnected regions.
        mask_threshold (`float`, *optional*, defaults to 0.5):
            Threshold used to binarize the query mask probabilities.
        overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
            Minimum overlap ratio required to keep a predicted segment.
        target_size (`tuple[int, int]`, *optional*):
            Final `(height, width)` of the segmentation map. If unset, uses the spatial size of `mask_probs`.

    Returns:
        `tuple[torch.Tensor, list[dict[str, int | float]]]`: The panoptic segmentation map and the metadata for each
        predicted segment.
    Né   r
   é   )ÚdtypeÚdeviceé   ©ÚidÚlabel_idÚscore)ÚshapeÚtorchÚzerosÚlongr(   ÚsigmoidÚargmaxÚranger   r   ÚroundÚappend)r   r    r!   r"   r   r   r#   ÚheightÚwidthÚsegmentationÚsegmentsr   Úcurrent_segment_idÚstuff_memory_listr   Ú
pred_classr   r   Úsegment_scores                      r   Úcompute_segmentsr?   H   s~  € ð@ %0Ð$7ˆZ×Ñ˜aÒ ¸[È¹^€FØ#.Ð#6ˆJ×Ñ˜QÒ¸KÈ¹N€Eä—;‘; ¨˜´e·j±jÈ×IZÑIZÔ[Ð^_Ñ_€LØ€Hà×#Ñ#Ó%€JØšq $¨˜}Ñ-°
Ñ:×BÑBÀ1ÓE€KàÐØ(*Ðä˜;×,Ñ,¨QÑ/Ó0ò  ˆ	Ø  Ñ+×0Ñ0Ó2ˆ
ä"8Ø˜ Y°Ð@[ó#
Ñˆ�Zñ Øá Ð/@Ñ!@ØÐ.Ñ.Ø+<¸ZÑ+H�˜ZÑ(Øà0BÐ! *Ñ-à#5ˆ�ZÑ Ü˜k¨)Ñ4×9Ñ9Ó;¸QÓ?ˆØ�‰à(Ø&Ø&ñô	
ð 	˜aÑÑð5 ð6 ˜Ð!Ð!r   c                   ó$  — e Zd Zej                  ZeZeZ	dddœZ
dZdZdZdZdZdZdZdgZddd	eeeef      d
ed   fd„Z	 dd	eeeef      ded
dfd„Z	 dd	eeeef      ded
ee   fd„Z	 	 	 	 dd	eeeef      dedededee   dz  d
ee   fd„Zy)ÚVideomtVideoProcessori€  )r7   r8   TFgp?Úpixel_values_videosÚmasks_queries_logitsr   Útarget_sizesr   c                 ó–   — g }t        |«      D ]8  \  }}t        j                  ||   d   |dd¬«      d   }|j                  |«       Œ: |S )z=Interpolates mask logits to each frame's original resolution.)N.ÚbilinearF)ÚsizeÚmodeÚalign_cornersr
   )Ú	enumerateÚFÚinterpolater6   )ÚselfrC   rD   ÚresizedÚidxÚoriginal_sizeÚ	upsampleds          r   Ú_resize_mask_logitsz)VideomtVideoProcessor._resize_mask_logits    se   € ð ˆÜ"+¨LÓ"9ò 	&ÑˆC�ÜŸ™Ø$ SÑ)¨)Ñ4Ø"ØØ#ô	ð
 ñˆIð �N‰N˜9Õ%ð	&ð ˆr   Úreturn_segmentation_scoreszBlist[torch.Tensor] | list[SemanticSegmentationPostProcessorOutput]c                 óš  — t        | dg«       |j                  }|j                  }|j                  «       j	                  d¬«      ddd…f   }|j                  «       j                  «       }t        j                  |j                  dd«      |j                  d«      «      }|j                  |j                  d   |j                  d   |j                  d	   |j                  d   «      }| j                  ||«      }	|	D �
cg c]!  }
t        |
j                  d¬«      |
d
œ¬«      ‘Œ# }}
|s|D �cg c]  }|j                  ‘Œ }}|S c c}
w c c}w )aé  
        Converts the output of [`VideomtForUniversalSegmentation`] into semantic segmentation predictions.

        Args:
            outputs ([`VideomtForUniversalSegmentationOutput`]):
                Raw outputs of the model.
            target_sizes (`list[tuple[int, int]]`):
                List of `(height, width)` tuples corresponding to the requested final size of each prediction.
                Length should match the number of frames in the output.
            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.
        r/   éÿÿÿÿ©Údim.Nr%   r&   r
   éþÿÿÿ)r9   Úsegmentation_scores)Údata)r   rC   Úclass_queries_logitsÚfloatÚsoftmaxr2   r/   ÚmatmulÚ	transposeÚflattenÚreshaper.   rR   r   r3   r9   )rM   ÚoutputsrD   rS   rC   r[   Úmasks_classesÚmasks_probsÚsegmentation_logitsÚoutput_logitsÚlogitÚsemantic_segmentationr   s                r   Ú"post_process_semantic_segmentationz8VideomtVideoProcessor.post_process_semantic_segmentation±   s\  € ô8 	˜$  	Ô*à&×;Ñ;ÐØ&×;Ñ;Ðð -×2Ñ2Ó4×<Ñ<ÀÐ<ÓDÀSÈ#È2È#ÀXÑNˆØ*×0Ñ0Ó2×:Ñ:Ó<ˆä#Ÿl™l¨=×+BÑ+BÀ1ÀaÓ+HÈ+×J]ÑJ]Ð^_ÓJ`ÓaÐØ1×9Ñ9Ø×Ñ˜aÑ  -×"5Ñ"5°bÑ"9¸;×;LÑ;LÈRÑ;PÐR]×RcÑRcÐdfÑRgó
Ðð ×0Ñ0Ð1DÀlÓSˆð 'ö	!
ð ô 4Ø&+§l¡l°q lÓ&9ÐRWÑXöð!
Ðð !
ñ *ØCXÖ$Y¸4 T×%6Ó%6Ð$YÐ!Ð$Yà$Ð$ùò!
ùò %Zs   Ã>&EÄ,EÚ	thresholdc           
      óø  — t        | dg«       |j                  }|j                  }| j                  ||«      }|j                  }|j
                  d   }|j
                  d   }	g }
t        |«      D �]‡  }||   }||   }|j                  «       j                  d¬«      ddd…f   }|j                  d«      \  }}|dkD  }|j                  «       j                  «       }|j                  d«      |j                  d«      z  j                  d«      |j                  d«      j                  d«      d	z   z  }||z  }t        j                  ||   dt        j                  |¬
«      }g }d}t        |	«      D ]q  }||   j!                  «       }t        j"                  ||   «      sŒ/||k\  sŒ5||||   <   |j%                  |||   j!                  «       t'        |d«      dœ«       |dz  }Œs |
j%                  ||dœ«       �ŒŠ |
S )a   
        Converts the output of [`VideomtForUniversalSegmentation`] into instance segmentation predictions.

        Args:
            outputs ([`VideomtForUniversalSegmentationOutput`]):
                Raw outputs of the model.
            target_sizes (`list[tuple[int, int]]`):
                List of `(height, width)` tuples corresponding to the requested final size of each prediction.
                Length should match the number of frames in the output.
            threshold (`float`, *optional*, defaults to 0.5):
                Minimum combined score to keep an instance.

        Returns:
            `list[dict]`: A list of dicts (one per frame), each containing:
                - `"segmentation"` -- A `torch.Tensor` of shape `(height, width)` with instance IDs (or -1 for background).
                - `"segments_info"` -- A list of dicts with `"id"`, `"label_id"`, and `"score"` for each instance.
        r/   r
   rX   rU   rV   .Nr%   g�íµ ÷Æ°>©Ú
fill_valuer'   r(   r)   r*   ©r9   Úsegments_info)r   r[   rC   rR   r(   r.   r4   r\   r]   Úmaxr2   r`   r   r/   Úfullr1   r   Úanyr6   r5   )rM   rb   rD   rj   r[   rC   Úmask_probs_batchr(   Ú
num_framesÚnum_queriesÚresultsÚ	frame_idxÚ	mask_predÚ
mask_classÚclass_probsÚscoresÚpred_classesÚ
pred_masksr   Úmask_scoresr    r9   r:   r;   r   r-   s                             r   Ú"post_process_instance_segmentationz8VideomtVideoProcessor.post_process_instance_segmentationé   s  € ô. 	˜$  	Ô*à&×;Ñ;ÐØ&×;Ñ;Ðà×3Ñ3Ð4HÈ,ÓWÐà%×,Ñ,ˆØ)×/Ñ/°Ñ2ˆ
Ø*×0Ñ0°Ñ4ˆàˆä˜zÓ*ó  	VˆIØ(¨Ñ3ˆIØ-¨iÑ8ˆJà$×*Ñ*Ó,×4Ñ4¸Ð4Ó<¸SÀ#À2À#¸XÑFˆKØ#.§?¡?°2Ó#6Ñ ˆF�LØ" Q™ˆJà"Ÿ™Ó*×2Ñ2Ó4ˆJØ%×-Ñ-¨aÓ0°:×3EÑ3EÀaÓ3HÑH×MÑMÈaÓPØ×"Ñ" 1Ó%×)Ñ)¨!Ó,¨tÑ3ñˆKð ! ;Ñ.ˆKä Ÿ:™: l°9Ñ&=È"ÔTY×T^ÑT^ÐgmÔnˆLàˆHØ!"ÐÜ" ;Ó/ò ,�	Ø# IÑ.×3Ñ3Ó5�ä—9‘9˜Z¨	Ñ2Õ3¸ÀÓ8JØ:L�L ¨IÑ!6Ñ7Ø—O‘Oà"4Ø(4°YÑ(?×(DÑ(DÓ(FÜ%*¨5°!£_ñôð '¨!Ñ+Ñ&ð,ð �N‰N¨LÈ8ÑTÖUðA 	VðB ˆr   Nr   r   r"   c                 ó„  — t        | dg«       |j                  }|j                  }|j                  d   }	|j                  d   dz
  }
| j	                  ||«      }|j                  «       j                  d¬«      j                  d«      \  }}g }t        |	«      D �]$  }||   }||   }||   }|j                  d   |j                  d   cxk(  r|j                  d   k(  st        d«      ‚ t        d«      ‚|j                  |
«      ||kD  z  }||   }||   }||   }|j                  d   dk  ra|�||   n|j                  dd \  }}t        j                  ||fdt        j                  |j                  ¬«      }|j                  |g d	œ«       Œõt!        |||||||�||   nd¬
«      \  }}|j                  ||d	œ«       �Œ' |S )a9  
        Converts the output of [`VideomtForUniversalSegmentation`] into panoptic segmentation predictions.

        Args:
            outputs ([`VideomtForUniversalSegmentationOutput`]):
                Raw outputs of the model.
            target_sizes (`list[tuple[int, int]]`):
                List of `(height, width)` tuples corresponding to the requested final size of each prediction.
                Length should match the number of frames in the output.
            threshold (`float`, *optional*, defaults to 0.8):
                Minimum score to keep a predicted segment.
            mask_threshold (`float`, *optional*, defaults to 0.5):
                Threshold for binarizing mask probabilities.
            overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
                Overlap threshold to merge masks into a single segment.
            label_ids_to_fuse (`set[int]`, *optional*):
                Label IDs that should be fused across disconnected regions.

        Returns:
            `list[dict]`: A list of dicts (one per frame), each containing:
                - `"segmentation"` -- A `torch.Tensor` of shape `(height, width)` with segment IDs (or -1 for background).
                - `"segments_info"` -- A list of dicts with `"id"`, `"label_id"`, and `"score"` for each segment.
        r/   r
   rU   r%   rV   z1mask, scores and labels must have the same shape!Nrl   rn   )r   r    r!   r"   r   r   r#   )r   rC   r[   r.   rR   r\   r]   rp   r4   Ú
ValueErrorÚner/   rq   r1   r(   r6   r?   )rM   rb   rD   rj   r   r   r"   rC   r[   rt   Ú
num_labelsrs   Úpred_scores_batchÚpred_labels_batchrv   rw   r   r    r!   Úto_keepr7   r8   r9   r:   s                           r   Ú"post_process_panoptic_segmentationz8VideomtVideoProcessor.post_process_panoptic_segmentation0  s  € ô@ 	˜$  	Ô*à&×;Ñ;ÐØ&×;Ñ;Ðà)×/Ñ/°Ñ2ˆ
Ø)×/Ñ/°Ñ3°aÑ7ˆ
à×3Ñ3Ð4HÈ,ÓWÐØ/C×/IÑ/IÓ/K×/SÑ/SÐXZÐ/SÓ/[×/_Ñ/_Ð`bÓ/cÑ,ÐÐ,àˆä˜zÓ*ó 	VˆIØ)¨)Ñ4ˆJØ+¨IÑ6ˆKØ+¨IÑ6ˆKà×$Ñ$ QÑ'¨;×+<Ñ+<¸QÑ+?ÔWÀ;×CTÑCTÐUVÑCWÒWÜ Ð!TÓUÐUð XÜ Ð!TÓUÐUà!—n‘n ZÓ0°KÀ)Ñ4KÑLˆGØ# GÑ,ˆJØ% gÑ.ˆKØ% gÑ.ˆKà×Ñ Ñ" aÒ'Ø;GÐ;S ¨YÒ 7ÐYc×YiÑYiÐjkÐjlÐYm‘�˜Ü$Ÿz™zØ˜U�O°¼%¿*¹*ÐMa×MhÑMhô �ð —‘°ÈrÑRÔSØä%5Ø%Ø'Ø'Ø"3Ø-Ø,GØ7CÐ7O˜L¨Ò3ÐUYô&Ñ"ˆL˜(ð �N‰N¨LÈ8ÑTÖUð?	Vð@ ˆr   )F)ç      à?)çš™™™™™é?rˆ   r‰   N)Ú__name__Ú
__module__Ú__qualname__r   ÚBILINEARÚresampler   Ú
image_meanr   Ú	image_stdrG   Ú	do_resizeÚdo_center_cropÚ
do_rescaleÚrescale_factorÚdo_normalizeÚdo_convert_rgbÚdo_sample_framesÚmodel_input_namesÚlistÚtupleÚintrR   Úboolri   r\   Údictr   Úsetr‡   © r   r   rA   rA   ’   se  „ Ø!×*Ñ*€HØ&€JØ$€IØ CÑ(€DØ€IØ€NØ€JØ€NØ€LØ€NØÐØ.Ð/Ððà,ðð ˜5  c ™?Ñ+ðð 
ˆnÑ	ó	ð* ,1ñ	6%ð ˜5  c ™?Ñ+ð6%ð %)ð	6%ð
 
Nó6%ðx ñ	Eð ˜5  c ™?Ñ+ðEð ð	Eð
 
ˆd‰óEðV Ø #Ø-0Ø-1ñMð ˜5  c ™?Ñ+ðMð ð	Mð
 ðMð &+ðMð ˜s™8 d™?ðMð 
ˆd‰ôMr   rA   )rˆ   r‰   )rˆ   r‰   N)Ú__doc__Úimage_processing_outputsr   Úimage_utilsr   r   r   Úutilsr   r   Úvideo_processing_utilsr	   r/   Útorch.nn.functionalÚnnÚ
functionalrK   r›   r\   rš   rœ   r   rž   r™   r�   Ústrr?   rA   Ú__all__rŸ   r   r   ú<module>rª      s,  ðñ )å Oß ZÑ Zß :Ý 8ñ ÔÛß#Ð#ð  Ø),ñ*#Øð*#àð*#ð ð*#ð ð	*#ð
 "'ð*#ð ˆ4�ÐÑ ó*#ðd  Ø),Ø*.ñG"ØðG"àðG"ð  ðG"ð ˜3‘x $‘ð	G"ð
 ðG"ð "'ðG"ð �s˜C�x‘ 4Ñ'ðG"ð ˆ>˜4  S¨#°©+Ð%5Ñ 6Ñ7Ð7Ñ8óG"ôTkÐ.ô kð\ #Ð
#�r   