
    ^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 nn&Oy)^;M!%%'Mm+J nn&O!A%S-!*;SRS@SK$}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$7Za [^F#.#6JQKNE;;ejjIZIZ[^__LH##%Jq$}-
:BB1EK(*;,,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 NN9%	& 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<<<DS#2#XN*002::<#ll=+B+B1a+H+J]J]^_J`a199a -"5"5b"9;;L;LR;PR]RcRcdfRg
 001DlS '	!
  4&+llql&9RWX!
 !
 *CX$Y4T%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34H,W%,,)//2
*004z*  	VI(3I-i8J$**,444<S#2#XFK#.??2#6 FL"QJ"*224J%--a0:3E3Ea3HHMMaP""1%))!,t3K !;.K ::l9&="TYT^T^gmnLH!"";/ ,	#I.33599Z	238J:LLI!67OO"4(4Y(?(D(D(F%*5!_ '!+&, NNL8TUA 	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
)//3a7
334H,W/C/I/I/K/S/SXZ/S/[/_/_`b/c,,z* 	VI))4J+I6K+I6K$$Q';+<+<Q+?W;CTCTUVCWW !TUU X !TUU!nnZ0K)4KLG#G,J%g.K%g.K"a';G;SY 7YcYiYijkjlYm$zzUO%**MaMhMh  rRS%5%''"3-,G7C7OL3UY&"L( NNL8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 s8d?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" 3x$	G"
 G" "'G" sCx4'G" >4S#+%5 6778G"Tk. k\ #
#r   