Upload VINE model - pipeline
Browse files- config.json +10 -0
- vine_pipeline.py +691 -0
config.json
CHANGED
|
@@ -10,6 +10,16 @@
|
|
| 10 |
},
|
| 11 |
"bbox_min_dim": 5,
|
| 12 |
"box_threshold": 0.35,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
"debug_visualizations": false,
|
| 14 |
"hidden_dim": 768,
|
| 15 |
"interested_object_pairs": [],
|
|
|
|
| 10 |
},
|
| 11 |
"bbox_min_dim": 5,
|
| 12 |
"box_threshold": 0.35,
|
| 13 |
+
"custom_pipelines": {
|
| 14 |
+
"vine-video-understanding": {
|
| 15 |
+
"impl": "vine_pipeline.VinePipeline",
|
| 16 |
+
"pt": [
|
| 17 |
+
"VineModel"
|
| 18 |
+
],
|
| 19 |
+
"tf": [],
|
| 20 |
+
"type": "multimodal"
|
| 21 |
+
}
|
| 22 |
+
},
|
| 23 |
"debug_visualizations": false,
|
| 24 |
"hidden_dim": 768,
|
| 25 |
"interested_object_pairs": [],
|
vine_pipeline.py
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
import cv2
|
| 4 |
+
import os
|
| 5 |
+
from typing import Dict, List, Tuple, Optional, Any, Union
|
| 6 |
+
from transformers import Pipeline
|
| 7 |
+
import tempfile
|
| 8 |
+
import uuid
|
| 9 |
+
|
| 10 |
+
from .vine_config import VineConfig
|
| 11 |
+
from .vine_model import VineModel
|
| 12 |
+
from .vis_utils import render_dino_frames, render_sam_frames, render_vine_frame_sets
|
| 13 |
+
from laser.loading import load_video
|
| 14 |
+
from laser.preprocess.mask_generation_grounding_dino import generate_masks_grounding_dino
|
| 15 |
+
|
| 16 |
+
class VinePipeline(Pipeline):
|
| 17 |
+
"""
|
| 18 |
+
Pipeline for VINE model that handles end-to-end video understanding.
|
| 19 |
+
|
| 20 |
+
This pipeline takes a video file or frames, along with segmentation method
|
| 21 |
+
and keyword lists, and returns probability distributions over the keywords.
|
| 22 |
+
|
| 23 |
+
Segmentation Model Configuration:
|
| 24 |
+
The pipeline requires SAM2 and GroundingDINO models for mask generation.
|
| 25 |
+
You can configure custom paths via constructor kwargs:
|
| 26 |
+
|
| 27 |
+
- sam_config_path: Path to SAM2 config (e.g., "configs/sam2.1/sam2.1_hiera_b+.yaml")
|
| 28 |
+
- sam_checkpoint_path: Path to SAM2 checkpoint (e.g., "checkpoints/sam2.1_hiera_base_plus.pt")
|
| 29 |
+
- gd_config_path: Path to GroundingDINO config (e.g., "groundingdino/config/GroundingDINO_SwinT_OGC.py")
|
| 30 |
+
- gd_checkpoint_path: Path to GroundingDINO checkpoint (e.g., "checkpoints/groundingdino_swint_ogc.pth")
|
| 31 |
+
|
| 32 |
+
Old:
|
| 33 |
+
- SAM2: ~/research/sam2/ or /home/asethi04/LASER_NEW/LASER/sam2/
|
| 34 |
+
- GroundingDINO: /home/asethi04/LASER_NEW/LASER/GroundingDINO/
|
| 35 |
+
|
| 36 |
+
Alternative: Use set_segmentation_models() to provide pre-initialized model instances.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
sam_config_path: Optional[str] = None,
|
| 42 |
+
sam_checkpoint_path: Optional[str] = None,
|
| 43 |
+
gd_config_path: Optional[str] = None,
|
| 44 |
+
gd_checkpoint_path: Optional[str] = None,
|
| 45 |
+
**kwargs
|
| 46 |
+
):
|
| 47 |
+
self.grounding_model = None
|
| 48 |
+
self.sam_predictor = None
|
| 49 |
+
self.mask_generator = None
|
| 50 |
+
|
| 51 |
+
self.sam_config_path = sam_config_path
|
| 52 |
+
self.sam_checkpoint_path = sam_checkpoint_path
|
| 53 |
+
self.gd_config_path = gd_config_path
|
| 54 |
+
self.gd_checkpoint_path = gd_checkpoint_path
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
super().__init__(**kwargs)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Set default parameters from config
|
| 61 |
+
self.segmentation_method = getattr(self.model.config, 'segmentation_method', 'grounding_dino_sam2')
|
| 62 |
+
self.box_threshold = getattr(self.model.config, 'box_threshold', 0.35)
|
| 63 |
+
self.text_threshold = getattr(self.model.config, 'text_threshold', 0.25)
|
| 64 |
+
self.target_fps = getattr(self.model.config, 'target_fps', 1)
|
| 65 |
+
self.visualize = getattr(self.model.config, 'visualize', False)
|
| 66 |
+
self.visualization_dir = getattr(self.model.config, 'visualization_dir', None)
|
| 67 |
+
self.debug_visualizations = getattr(self.model.config, 'debug_visualizations', False)
|
| 68 |
+
self._device = getattr(self.model.config, '_device')
|
| 69 |
+
if kwargs.get("device") is not None:
|
| 70 |
+
self._device = kwargs.get("device")
|
| 71 |
+
|
| 72 |
+
def set_segmentation_models(
|
| 73 |
+
self,
|
| 74 |
+
*,
|
| 75 |
+
sam_predictor=None,
|
| 76 |
+
mask_generator=None,
|
| 77 |
+
grounding_model=None
|
| 78 |
+
):
|
| 79 |
+
"""
|
| 80 |
+
Set pre-initialized segmentation models, bypassing automatic initialization/current_values
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
sam_predictor: Pre-built SAM2 video predictor
|
| 84 |
+
mask_generator: Pre-built SAM2 automatic mask generator
|
| 85 |
+
grounding_model: Pre-built GroundingDINO model
|
| 86 |
+
"""
|
| 87 |
+
if sam_predictor is not None:
|
| 88 |
+
self.sam_predictor = sam_predictor
|
| 89 |
+
if mask_generator is not None:
|
| 90 |
+
self.mask_generator = mask_generator
|
| 91 |
+
if grounding_model is not None:
|
| 92 |
+
self.grounding_model = grounding_model
|
| 93 |
+
|
| 94 |
+
def _sanitize_parameters(self, **kwargs):
|
| 95 |
+
"""Sanitize parameters for different pipeline stages."""
|
| 96 |
+
preprocess_kwargs = {}
|
| 97 |
+
forward_kwargs = {}
|
| 98 |
+
postprocess_kwargs = {}
|
| 99 |
+
|
| 100 |
+
# Preprocess parameters
|
| 101 |
+
if "segmentation_method" in kwargs:
|
| 102 |
+
preprocess_kwargs["segmentation_method"] = kwargs["segmentation_method"]
|
| 103 |
+
if "target_fps" in kwargs:
|
| 104 |
+
preprocess_kwargs["target_fps"] = kwargs["target_fps"]
|
| 105 |
+
if "box_threshold" in kwargs:
|
| 106 |
+
preprocess_kwargs["box_threshold"] = kwargs["box_threshold"]
|
| 107 |
+
if "text_threshold" in kwargs:
|
| 108 |
+
preprocess_kwargs["text_threshold"] = kwargs["text_threshold"]
|
| 109 |
+
if "categorical_keywords" in kwargs:
|
| 110 |
+
preprocess_kwargs["categorical_keywords"] = kwargs["categorical_keywords"]
|
| 111 |
+
|
| 112 |
+
# Forward parameters
|
| 113 |
+
if "categorical_keywords" in kwargs:
|
| 114 |
+
forward_kwargs["categorical_keywords"] = kwargs["categorical_keywords"]
|
| 115 |
+
if "unary_keywords" in kwargs:
|
| 116 |
+
forward_kwargs["unary_keywords"] = kwargs["unary_keywords"]
|
| 117 |
+
if "binary_keywords" in kwargs:
|
| 118 |
+
forward_kwargs["binary_keywords"] = kwargs["binary_keywords"]
|
| 119 |
+
if "object_pairs" in kwargs:
|
| 120 |
+
forward_kwargs["object_pairs"] = kwargs["object_pairs"]
|
| 121 |
+
if "return_flattened_segments" in kwargs:
|
| 122 |
+
forward_kwargs["return_flattened_segments"] = kwargs["return_flattened_segments"]
|
| 123 |
+
if "return_valid_pairs" in kwargs:
|
| 124 |
+
forward_kwargs["return_valid_pairs"] = kwargs["return_valid_pairs"]
|
| 125 |
+
if "interested_object_pairs" in kwargs:
|
| 126 |
+
forward_kwargs["interested_object_pairs"] = kwargs["interested_object_pairs"]
|
| 127 |
+
if "debug_visualizations" in kwargs:
|
| 128 |
+
forward_kwargs["debug_visualizations"] = kwargs["debug_visualizations"]
|
| 129 |
+
postprocess_kwargs["debug_visualizations"] = kwargs["debug_visualizations"]
|
| 130 |
+
|
| 131 |
+
# Postprocess parameters
|
| 132 |
+
if "return_top_k" in kwargs:
|
| 133 |
+
postprocess_kwargs["return_top_k"] = kwargs["return_top_k"]
|
| 134 |
+
if "self.visualize" in kwargs:
|
| 135 |
+
postprocess_kwargs["self.visualize"] = kwargs["self.visualize"]
|
| 136 |
+
|
| 137 |
+
return preprocess_kwargs, forward_kwargs, postprocess_kwargs
|
| 138 |
+
|
| 139 |
+
def preprocess(
|
| 140 |
+
self,
|
| 141 |
+
video_input: Union[str, np.ndarray, torch.Tensor],
|
| 142 |
+
segmentation_method: str = None,
|
| 143 |
+
target_fps: int = None,
|
| 144 |
+
box_threshold: float = None,
|
| 145 |
+
text_threshold: float = None,
|
| 146 |
+
categorical_keywords: List[str] = None,
|
| 147 |
+
**kwargs
|
| 148 |
+
) -> Dict[str, Any]:
|
| 149 |
+
"""
|
| 150 |
+
Preprocess video input and generate masks.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
video_input: Path to video file, or video tensor/array
|
| 154 |
+
segmentation_method: "sam2" or "grounding_dino_sam2"
|
| 155 |
+
target_fps: Target FPS for video processing
|
| 156 |
+
box_threshold: Box threshold for Grounding DINO
|
| 157 |
+
text_threshold: Text threshold for Grounding DINO
|
| 158 |
+
categorical_keywords: Keywords for Grounding DINO segmentation
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
Dict containing video frames, masks, and bboxes
|
| 162 |
+
"""
|
| 163 |
+
# Use defaults from config if not provided
|
| 164 |
+
if segmentation_method is None:
|
| 165 |
+
segmentation_method = self.segmentation_method
|
| 166 |
+
if target_fps is None:
|
| 167 |
+
target_fps = self.target_fps
|
| 168 |
+
if box_threshold is None:
|
| 169 |
+
box_threshold = self.box_threshold
|
| 170 |
+
if text_threshold is None:
|
| 171 |
+
text_threshold = self.text_threshold
|
| 172 |
+
if categorical_keywords is None:
|
| 173 |
+
categorical_keywords = ["object"] # Default generic category
|
| 174 |
+
|
| 175 |
+
if isinstance(video_input, str):
|
| 176 |
+
# Video file path
|
| 177 |
+
video_tensor = load_video(video_input, target_fps=target_fps)
|
| 178 |
+
if isinstance(video_tensor, list):
|
| 179 |
+
video_tensor = np.array(video_tensor)
|
| 180 |
+
elif isinstance(video_tensor, torch.Tensor):
|
| 181 |
+
video_tensor = video_tensor.cpu().numpy()
|
| 182 |
+
|
| 183 |
+
elif isinstance(video_input, (np.ndarray, torch.Tensor)):
|
| 184 |
+
# Video tensor/array
|
| 185 |
+
if isinstance(video_input, torch.Tensor):
|
| 186 |
+
video_tensor = video_input.numpy()
|
| 187 |
+
else:
|
| 188 |
+
video_tensor = video_input
|
| 189 |
+
else:
|
| 190 |
+
raise ValueError(f"Unsupported video input type: {type(video_input)}")
|
| 191 |
+
|
| 192 |
+
# Ensure video tensor is numpy array
|
| 193 |
+
if not isinstance(video_tensor, np.ndarray):
|
| 194 |
+
video_tensor = np.array(video_tensor)
|
| 195 |
+
|
| 196 |
+
# Ensure video tensor is in correct format
|
| 197 |
+
if len(video_tensor.shape) != 4:
|
| 198 |
+
raise ValueError(f"Expected video tensor shape (frames, height, width, channels), got {video_tensor.shape}")
|
| 199 |
+
|
| 200 |
+
# Generate masks and bboxes based on segmentation method
|
| 201 |
+
visualization_data: Dict[str, Any] = {}
|
| 202 |
+
print(f"Segmentation method: {segmentation_method}")
|
| 203 |
+
if segmentation_method == "sam2":
|
| 204 |
+
masks, bboxes, vis_data = self._generate_sam2_masks(video_tensor)
|
| 205 |
+
elif segmentation_method == "grounding_dino_sam2":
|
| 206 |
+
masks, bboxes, vis_data = self._generate_grounding_dino_sam2_masks(
|
| 207 |
+
video_tensor, categorical_keywords, box_threshold, text_threshold, video_input
|
| 208 |
+
)
|
| 209 |
+
else:
|
| 210 |
+
raise ValueError(f"Unsupported segmentation method: {segmentation_method}")
|
| 211 |
+
if vis_data:
|
| 212 |
+
visualization_data.update(vis_data)
|
| 213 |
+
visualization_data.setdefault("sam_masks", masks)
|
| 214 |
+
|
| 215 |
+
return {
|
| 216 |
+
"video_frames": torch.tensor(video_tensor),
|
| 217 |
+
"masks": masks,
|
| 218 |
+
"bboxes": bboxes,
|
| 219 |
+
"num_frames": len(video_tensor),
|
| 220 |
+
"visualization_data": visualization_data,
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
def _generate_sam2_masks(self, video_tensor: np.ndarray) -> Tuple[Dict, Dict, Dict[str, Any]]:
|
| 224 |
+
"""Generate masks using SAM2 automatic mask generation."""
|
| 225 |
+
# Initialize SAM2 models if not already done
|
| 226 |
+
print("Generating SAM2 masks...")
|
| 227 |
+
if self.mask_generator is None:
|
| 228 |
+
self._initialize_segmentation_models()
|
| 229 |
+
|
| 230 |
+
if self.mask_generator is None:
|
| 231 |
+
raise ValueError("SAM2 mask generator not available")
|
| 232 |
+
|
| 233 |
+
masks: Dict[int, Dict[int, torch.Tensor]] = {}
|
| 234 |
+
bboxes: Dict[int, Dict[int, List[int]]] = {}
|
| 235 |
+
|
| 236 |
+
for frame_id, frame in enumerate(video_tensor):
|
| 237 |
+
if isinstance(frame, np.ndarray) and frame.dtype != np.uint8:
|
| 238 |
+
frame = (frame * 255).astype(np.uint8) if frame.max() <= 1 else frame.astype(np.uint8)
|
| 239 |
+
|
| 240 |
+
height, width, _ = frame.shape
|
| 241 |
+
frame_masks = self.mask_generator.generate(frame)
|
| 242 |
+
|
| 243 |
+
masks[frame_id] = {}
|
| 244 |
+
bboxes[frame_id] = {}
|
| 245 |
+
|
| 246 |
+
for obj_id, mask_data in enumerate(frame_masks):
|
| 247 |
+
mask = mask_data["segmentation"]
|
| 248 |
+
if isinstance(mask, np.ndarray):
|
| 249 |
+
mask = torch.from_numpy(mask)
|
| 250 |
+
|
| 251 |
+
if len(mask.shape) == 2:
|
| 252 |
+
mask = mask.unsqueeze(-1)
|
| 253 |
+
elif len(mask.shape) == 3 and mask.shape[0] == 1:
|
| 254 |
+
mask = mask.permute(1, 2, 0)
|
| 255 |
+
|
| 256 |
+
wrapped_id = obj_id + 1
|
| 257 |
+
masks[frame_id][wrapped_id] = mask
|
| 258 |
+
|
| 259 |
+
mask_np = mask.squeeze().numpy() if isinstance(mask, torch.Tensor) else mask.squeeze()
|
| 260 |
+
|
| 261 |
+
coords = np.where(mask_np > 0)
|
| 262 |
+
if len(coords[0]) > 0:
|
| 263 |
+
y1, y2 = coords[0].min(), coords[0].max()
|
| 264 |
+
x1, x2 = coords[1].min(), coords[1].max()
|
| 265 |
+
bboxes[frame_id][wrapped_id] = [x1, y1, x2, y2]
|
| 266 |
+
|
| 267 |
+
return masks, bboxes, {"sam_masks": masks}
|
| 268 |
+
|
| 269 |
+
def _generate_grounding_dino_sam2_masks(
|
| 270 |
+
self,
|
| 271 |
+
video_tensor: np.ndarray,
|
| 272 |
+
categorical_keywords: List[str],
|
| 273 |
+
box_threshold: float,
|
| 274 |
+
text_threshold: float,
|
| 275 |
+
video_path: str,
|
| 276 |
+
) -> Tuple[Dict, Dict, Dict[str, Any]]:
|
| 277 |
+
"""Generate masks using Grounding DINO + SAM2."""
|
| 278 |
+
# Initialize models if not already done
|
| 279 |
+
print("Generating Grounding DINO + SAM2 masks...")
|
| 280 |
+
if self.grounding_model is None or self.sam_predictor is None:
|
| 281 |
+
self._initialize_segmentation_models()
|
| 282 |
+
|
| 283 |
+
if self.grounding_model is None or self.sam_predictor is None:
|
| 284 |
+
raise ValueError("GroundingDINO or SAM2 models not available")
|
| 285 |
+
|
| 286 |
+
temp_video_path = None
|
| 287 |
+
if video_path is None or not isinstance(video_path, str):
|
| 288 |
+
temp_video_path = self._create_temp_video(video_tensor)
|
| 289 |
+
video_path = temp_video_path
|
| 290 |
+
|
| 291 |
+
CHUNK = 5
|
| 292 |
+
classes_ls = [categorical_keywords[i:i + CHUNK] for i in range(0, len(categorical_keywords), CHUNK)]
|
| 293 |
+
video_segments, oid_class_pred, _ = generate_masks_grounding_dino(
|
| 294 |
+
self.grounding_model,
|
| 295 |
+
box_threshold,
|
| 296 |
+
text_threshold,
|
| 297 |
+
self.sam_predictor,
|
| 298 |
+
self.mask_generator,
|
| 299 |
+
video_tensor,
|
| 300 |
+
video_path,
|
| 301 |
+
"temp_video",
|
| 302 |
+
out_dir=tempfile.gettempdir(),
|
| 303 |
+
classes_ls=classes_ls,
|
| 304 |
+
target_fps=self.target_fps,
|
| 305 |
+
visualize=self.debug_visualizations,
|
| 306 |
+
frames=None,
|
| 307 |
+
max_prop_time=10
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
masks: Dict[int, Dict[int, torch.Tensor]] = {}
|
| 311 |
+
bboxes: Dict[int, Dict[int, List[int]]] = {}
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
for frame_id, frame_masks in video_segments.items():
|
| 315 |
+
masks[frame_id] = {}
|
| 316 |
+
bboxes[frame_id] = {}
|
| 317 |
+
|
| 318 |
+
for obj_id, mask in frame_masks.items():
|
| 319 |
+
if not isinstance(mask, torch.Tensor):
|
| 320 |
+
mask = torch.tensor(mask)
|
| 321 |
+
masks[frame_id][obj_id] = mask
|
| 322 |
+
mask_np = mask.numpy()
|
| 323 |
+
if mask_np.ndim == 3 and mask_np.shape[0] == 1:
|
| 324 |
+
mask_np = np.squeeze(mask_np, axis=0)
|
| 325 |
+
|
| 326 |
+
coords = np.where(mask_np > 0)
|
| 327 |
+
if len(coords[0]) > 0:
|
| 328 |
+
y1, y2 = coords[0].min(), coords[0].max()
|
| 329 |
+
x1, x2 = coords[1].min(), coords[1].max()
|
| 330 |
+
bboxes[frame_id][obj_id] = [x1, y1, x2, y2]
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
if temp_video_path and os.path.exists(temp_video_path):
|
| 334 |
+
os.remove(temp_video_path)
|
| 335 |
+
|
| 336 |
+
vis_data: Dict[str, Any] = {
|
| 337 |
+
"sam_masks": masks,
|
| 338 |
+
"dino_labels": oid_class_pred,
|
| 339 |
+
}
|
| 340 |
+
return masks, bboxes, vis_data
|
| 341 |
+
|
| 342 |
+
def _initialize_segmentation_models(self):
|
| 343 |
+
"""Initialize segmentation models based on the requested method and configured paths."""
|
| 344 |
+
if (self.sam_predictor is None or self.mask_generator is None):
|
| 345 |
+
self._initialize_sam2_models()
|
| 346 |
+
|
| 347 |
+
if self.grounding_model is None:
|
| 348 |
+
self._initialize_grounding_dino_model()
|
| 349 |
+
|
| 350 |
+
def _initialize_sam2_models(self):
|
| 351 |
+
"""Initialize SAM2 video predictor and mask generator."""
|
| 352 |
+
try:
|
| 353 |
+
from sam2.build_sam import build_sam2_video_predictor, build_sam2
|
| 354 |
+
from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator
|
| 355 |
+
except ImportError as e:
|
| 356 |
+
print(f"Warning: Could not import SAM2: {e}")
|
| 357 |
+
return
|
| 358 |
+
|
| 359 |
+
# Resolve SAM2 paths
|
| 360 |
+
config_path, checkpoint_path = self._resolve_sam2_paths()
|
| 361 |
+
|
| 362 |
+
# Validate paths if custom ones were provided
|
| 363 |
+
if self.sam_config_path is not None and not os.path.exists(config_path):
|
| 364 |
+
raise ValueError(f"SAM2 config path not found: {config_path}")
|
| 365 |
+
if self.sam_checkpoint_path is not None and not os.path.exists(checkpoint_path):
|
| 366 |
+
raise ValueError(f"SAM2 checkpoint path not found: {checkpoint_path}")
|
| 367 |
+
|
| 368 |
+
# Only proceed if we have valid paths
|
| 369 |
+
if not os.path.exists(checkpoint_path):
|
| 370 |
+
print(f"Warning: SAM2 checkpoint not found at {checkpoint_path}")
|
| 371 |
+
print("SAM2 functionality will be unavailable")
|
| 372 |
+
return
|
| 373 |
+
|
| 374 |
+
try:
|
| 375 |
+
device = self._device
|
| 376 |
+
|
| 377 |
+
print(type(device))
|
| 378 |
+
# Video predictor
|
| 379 |
+
self.sam_predictor = build_sam2_video_predictor(
|
| 380 |
+
config_path, checkpoint_path, device=device
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
# Mask generator
|
| 384 |
+
sam2_model = build_sam2(config_path, checkpoint_path, device=device, apply_postprocessing=False)
|
| 385 |
+
self.mask_generator = SAM2AutomaticMaskGenerator(
|
| 386 |
+
model=sam2_model,
|
| 387 |
+
points_per_side=32,
|
| 388 |
+
points_per_batch=32,
|
| 389 |
+
pred_iou_thresh=0.7,
|
| 390 |
+
stability_score_thresh=0.8,
|
| 391 |
+
crop_n_layers=2,
|
| 392 |
+
box_nms_thresh=0.6,
|
| 393 |
+
crop_n_points_downscale_factor=2,
|
| 394 |
+
min_mask_region_area=30.0,
|
| 395 |
+
use_m2m=True,
|
| 396 |
+
)
|
| 397 |
+
print("✓ SAM2 models initialized successfully")
|
| 398 |
+
|
| 399 |
+
except Exception as e:
|
| 400 |
+
raise ValueError(f"Failed to initialize SAM2 with custom paths: {e}")
|
| 401 |
+
|
| 402 |
+
def _initialize_grounding_dino_model(self):
|
| 403 |
+
"""Initialize GroundingDINO model."""
|
| 404 |
+
try:
|
| 405 |
+
from groundingdino.util.inference import Model as gd_Model
|
| 406 |
+
except ImportError as e:
|
| 407 |
+
print(f"Warning: Could not import GroundingDINO: {e}")
|
| 408 |
+
return
|
| 409 |
+
|
| 410 |
+
# Resolve GroundingDINO paths
|
| 411 |
+
config_path, checkpoint_path = self._resolve_grounding_dino_paths()
|
| 412 |
+
|
| 413 |
+
# Validate paths if custom ones were provided
|
| 414 |
+
if self.gd_config_path is not None and not os.path.exists(config_path):
|
| 415 |
+
raise ValueError(f"GroundingDINO config path not found: {config_path}")
|
| 416 |
+
if self.gd_checkpoint_path is not None and not os.path.exists(checkpoint_path):
|
| 417 |
+
raise ValueError(f"GroundingDINO checkpoint path not found: {checkpoint_path}")
|
| 418 |
+
|
| 419 |
+
# Only proceed if we have valid paths
|
| 420 |
+
if not (os.path.exists(config_path) and os.path.exists(checkpoint_path)):
|
| 421 |
+
print(f"Warning: GroundingDINO models not found at {config_path} / {checkpoint_path}")
|
| 422 |
+
print("GroundingDINO functionality will be unavailable")
|
| 423 |
+
return
|
| 424 |
+
|
| 425 |
+
try:
|
| 426 |
+
device = self._device
|
| 427 |
+
print(type(device))
|
| 428 |
+
self.grounding_model = gd_Model(
|
| 429 |
+
model_config_path=config_path,
|
| 430 |
+
model_checkpoint_path=checkpoint_path,
|
| 431 |
+
device=device
|
| 432 |
+
)
|
| 433 |
+
print("✓ GroundingDINO model initialized successfully")
|
| 434 |
+
|
| 435 |
+
except Exception as e:
|
| 436 |
+
raise ValueError(f"Failed to initialize GroundingDINO with custom paths: {e}")
|
| 437 |
+
|
| 438 |
+
def _resolve_sam2_paths(self):
|
| 439 |
+
"""Resolve SAM2 config and checkpoint paths."""
|
| 440 |
+
# Use custom paths if provided
|
| 441 |
+
if self.sam_config_path and self.sam_checkpoint_path:
|
| 442 |
+
return self.sam_config_path, self.sam_checkpoint_path
|
| 443 |
+
|
| 444 |
+
def _resolve_grounding_dino_paths(self):
|
| 445 |
+
"""Resolve GroundingDINO config and checkpoint paths."""
|
| 446 |
+
# Use custom paths if provided
|
| 447 |
+
if self.gd_config_path and self.gd_checkpoint_path:
|
| 448 |
+
return self.gd_config_path, self.gd_checkpoint_path
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def _prepare_visualization_dir(self, name: str, enabled: bool) -> Optional[str]:
|
| 452 |
+
"""
|
| 453 |
+
Ensure a directory exists for visualization artifacts and return it.
|
| 454 |
+
If visualization is disabled, returns None.
|
| 455 |
+
"""
|
| 456 |
+
if not enabled:
|
| 457 |
+
return None
|
| 458 |
+
|
| 459 |
+
if self.visualization_dir:
|
| 460 |
+
target_dir = os.path.join(self.visualization_dir, name) if name else self.visualization_dir
|
| 461 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 462 |
+
return target_dir
|
| 463 |
+
|
| 464 |
+
return tempfile.mkdtemp(prefix=f"vine_{name}_")
|
| 465 |
+
|
| 466 |
+
def _create_temp_video(self, video_tensor: np.ndarray, base_dir: Optional[str] = None, prefix: str = "temp_video") -> str:
|
| 467 |
+
"""Create a temporary video file from video tensor."""
|
| 468 |
+
if base_dir is None:
|
| 469 |
+
base_dir = tempfile.mkdtemp(prefix=f"vine_{prefix}_")
|
| 470 |
+
else:
|
| 471 |
+
os.makedirs(base_dir, exist_ok=True)
|
| 472 |
+
file_name = f"{prefix}_{uuid.uuid4().hex}.mp4"
|
| 473 |
+
temp_path = os.path.join(base_dir, file_name)
|
| 474 |
+
|
| 475 |
+
# Use OpenCV to write video
|
| 476 |
+
height, width = video_tensor.shape[1:3]
|
| 477 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 478 |
+
out = cv2.VideoWriter(temp_path, fourcc, self.target_fps, (width, height))
|
| 479 |
+
|
| 480 |
+
for frame in video_tensor:
|
| 481 |
+
# Convert RGB to BGR for OpenCV
|
| 482 |
+
if len(frame.shape) == 3 and frame.shape[2] == 3:
|
| 483 |
+
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
| 484 |
+
else:
|
| 485 |
+
frame_bgr = frame
|
| 486 |
+
out.write(frame_bgr.astype(np.uint8))
|
| 487 |
+
|
| 488 |
+
out.release()
|
| 489 |
+
return temp_path
|
| 490 |
+
|
| 491 |
+
def _forward(self, model_inputs: Dict[str, Any], **forward_kwargs) -> Dict[str, Any]:
|
| 492 |
+
"""Forward pass through the model."""
|
| 493 |
+
outputs = self.model.predict(
|
| 494 |
+
video_frames=model_inputs["video_frames"],
|
| 495 |
+
masks=model_inputs["masks"],
|
| 496 |
+
bboxes=model_inputs["bboxes"],
|
| 497 |
+
**forward_kwargs
|
| 498 |
+
)
|
| 499 |
+
outputs.setdefault("video_frames", model_inputs.get("video_frames"))
|
| 500 |
+
outputs.setdefault("bboxes", model_inputs.get("bboxes"))
|
| 501 |
+
outputs.setdefault("masks", model_inputs.get("masks"))
|
| 502 |
+
outputs.setdefault("visualization_data", model_inputs.get("visualization_data"))
|
| 503 |
+
return outputs
|
| 504 |
+
|
| 505 |
+
def postprocess(
|
| 506 |
+
self,
|
| 507 |
+
model_outputs: Dict[str, Any],
|
| 508 |
+
return_top_k: int = 3,
|
| 509 |
+
visualize: Optional[bool] = None,
|
| 510 |
+
**kwargs
|
| 511 |
+
) -> Dict[str, Any]:
|
| 512 |
+
"""
|
| 513 |
+
Postprocess model outputs into user-friendly format.
|
| 514 |
+
|
| 515 |
+
Args:
|
| 516 |
+
model_outputs: Raw model outputs
|
| 517 |
+
return_top_k: Number of top predictions to return
|
| 518 |
+
self.visualize: Whether to include visualization data
|
| 519 |
+
|
| 520 |
+
Returns:
|
| 521 |
+
Formatted results
|
| 522 |
+
"""
|
| 523 |
+
results = {
|
| 524 |
+
"categorical_predictions": model_outputs.get("categorical_predictions", {}),
|
| 525 |
+
"unary_predictions": model_outputs.get("unary_predictions", {}),
|
| 526 |
+
"binary_predictions": model_outputs.get("binary_predictions", {}),
|
| 527 |
+
"confidence_scores": model_outputs.get("confidence_scores", {}),
|
| 528 |
+
"summary": self._generate_summary(model_outputs)
|
| 529 |
+
}
|
| 530 |
+
if "flattened_segments" in model_outputs:
|
| 531 |
+
results["flattened_segments"] = model_outputs["flattened_segments"]
|
| 532 |
+
if "valid_pairs" in model_outputs:
|
| 533 |
+
results["valid_pairs"] = model_outputs["valid_pairs"]
|
| 534 |
+
if "valid_pairs_metadata" in model_outputs:
|
| 535 |
+
results["valid_pairs_metadata"] = model_outputs["valid_pairs_metadata"]
|
| 536 |
+
if "visualization_data" in model_outputs:
|
| 537 |
+
results["visualization_data"] = model_outputs["visualization_data"]
|
| 538 |
+
|
| 539 |
+
if self.visualize and "video_frames" in model_outputs and "bboxes" in model_outputs:
|
| 540 |
+
frames_tensor = model_outputs["video_frames"]
|
| 541 |
+
if isinstance(frames_tensor, torch.Tensor):
|
| 542 |
+
frames_np = frames_tensor.detach().cpu().numpy()
|
| 543 |
+
else:
|
| 544 |
+
frames_np = np.asarray(frames_tensor)
|
| 545 |
+
if frames_np.dtype != np.uint8:
|
| 546 |
+
if np.issubdtype(frames_np.dtype, np.floating):
|
| 547 |
+
max_val = frames_np.max() if frames_np.size else 0.0
|
| 548 |
+
scale = 255.0 if max_val <= 1.0 else 1.0
|
| 549 |
+
frames_np = (frames_np * scale).clip(0, 255).astype(np.uint8)
|
| 550 |
+
else:
|
| 551 |
+
frames_np = frames_np.clip(0, 255).astype(np.uint8)
|
| 552 |
+
|
| 553 |
+
cat_label_lookup: Dict[int, Tuple[str, float]] = {}
|
| 554 |
+
for obj_id, preds in model_outputs.get("categorical_predictions", {}).items():
|
| 555 |
+
if preds:
|
| 556 |
+
prob, label = preds[0]
|
| 557 |
+
cat_label_lookup[obj_id] = (label, prob)
|
| 558 |
+
|
| 559 |
+
unary_preds = model_outputs.get("unary_predictions", {})
|
| 560 |
+
unary_lookup: Dict[int, Dict[int, List[Tuple[float, str]]]] = {}
|
| 561 |
+
for (frame_id, obj_id), preds in unary_preds.items():
|
| 562 |
+
if preds:
|
| 563 |
+
unary_lookup.setdefault(frame_id, {})[obj_id] = preds
|
| 564 |
+
|
| 565 |
+
binary_preds = model_outputs.get("binary_predictions", {})
|
| 566 |
+
binary_lookup: Dict[int, List[Tuple[Tuple[int, int], List[Tuple[float, str]]]]] = {}
|
| 567 |
+
for (frame_id, obj_pair), preds in binary_preds.items():
|
| 568 |
+
if preds:
|
| 569 |
+
binary_lookup.setdefault(frame_id, []).append((obj_pair, preds))
|
| 570 |
+
|
| 571 |
+
bboxes = model_outputs["bboxes"]
|
| 572 |
+
visualization_data = model_outputs.get("visualization_data", {})
|
| 573 |
+
visualizations: Dict[str, Dict[str, Any]] = {}
|
| 574 |
+
debug_visualizations = kwargs.get("debug_visualizations")
|
| 575 |
+
if debug_visualizations is None:
|
| 576 |
+
debug_visualizations = self.debug_visualizations
|
| 577 |
+
|
| 578 |
+
vine_frame_sets = render_vine_frame_sets(
|
| 579 |
+
frames_np,
|
| 580 |
+
bboxes,
|
| 581 |
+
cat_label_lookup,
|
| 582 |
+
unary_lookup,
|
| 583 |
+
binary_lookup,
|
| 584 |
+
visualization_data.get("sam_masks"),
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
vine_visuals: Dict[str, Dict[str, Any]] = {}
|
| 588 |
+
final_frames = vine_frame_sets.get("all", [])
|
| 589 |
+
if final_frames:
|
| 590 |
+
final_entry: Dict[str, Any] = {"frames": final_frames, "video_path": None}
|
| 591 |
+
final_dir = self._prepare_visualization_dir("all", enabled=self.visualize)
|
| 592 |
+
final_entry["video_path"] = self._create_temp_video(
|
| 593 |
+
np.stack(final_frames, axis=0),
|
| 594 |
+
base_dir=final_dir,
|
| 595 |
+
prefix="all_visualization"
|
| 596 |
+
)
|
| 597 |
+
vine_visuals["all"] = final_entry
|
| 598 |
+
|
| 599 |
+
if debug_visualizations:
|
| 600 |
+
sam_masks = visualization_data.get("sam_masks")
|
| 601 |
+
if sam_masks:
|
| 602 |
+
sam_frames = render_sam_frames(frames_np, sam_masks, visualization_data.get("dino_labels"))
|
| 603 |
+
sam_entry = {"frames": sam_frames, "video_path": None}
|
| 604 |
+
if sam_frames:
|
| 605 |
+
sam_dir = self._prepare_visualization_dir("sam", enabled=self.visualize)
|
| 606 |
+
sam_entry["video_path"] = self._create_temp_video(
|
| 607 |
+
np.stack(sam_frames, axis=0),
|
| 608 |
+
base_dir=sam_dir,
|
| 609 |
+
prefix="sam_visualization"
|
| 610 |
+
)
|
| 611 |
+
visualizations["sam"] = sam_entry
|
| 612 |
+
|
| 613 |
+
dino_labels = visualization_data.get("dino_labels")
|
| 614 |
+
if dino_labels:
|
| 615 |
+
dino_frames = render_dino_frames(frames_np, bboxes, dino_labels)
|
| 616 |
+
dino_entry = {"frames": dino_frames, "video_path": None}
|
| 617 |
+
if dino_frames:
|
| 618 |
+
dino_dir = self._prepare_visualization_dir("dino", enabled=self.visualize)
|
| 619 |
+
dino_entry["video_path"] = self._create_temp_video(
|
| 620 |
+
np.stack(dino_frames, axis=0),
|
| 621 |
+
base_dir=dino_dir,
|
| 622 |
+
prefix="dino_visualization"
|
| 623 |
+
)
|
| 624 |
+
visualizations["dino"] = dino_entry
|
| 625 |
+
|
| 626 |
+
for name in ("object", "unary", "binary"):
|
| 627 |
+
frames_list = vine_frame_sets.get(name, [])
|
| 628 |
+
entry: Dict[str, Any] = {"frames": frames_list, "video_path": None}
|
| 629 |
+
if frames_list:
|
| 630 |
+
vine_dir = self._prepare_visualization_dir(name, enabled=self.visualize)
|
| 631 |
+
entry["video_path"] = self._create_temp_video(
|
| 632 |
+
np.stack(frames_list, axis=0),
|
| 633 |
+
base_dir=vine_dir,
|
| 634 |
+
prefix=f"{name}_visualization"
|
| 635 |
+
)
|
| 636 |
+
vine_visuals[name] = entry
|
| 637 |
+
|
| 638 |
+
if vine_visuals:
|
| 639 |
+
visualizations["vine"] = vine_visuals
|
| 640 |
+
|
| 641 |
+
if visualizations:
|
| 642 |
+
results["visualizations"] = visualizations
|
| 643 |
+
|
| 644 |
+
return results
|
| 645 |
+
|
| 646 |
+
def _generate_summary(self, model_outputs: Dict[str, Any]) -> Dict[str, Any]:
|
| 647 |
+
"""Generate a summary of the predictions."""
|
| 648 |
+
categorical_preds = model_outputs.get("categorical_predictions", {})
|
| 649 |
+
unary_preds = model_outputs.get("unary_predictions", {})
|
| 650 |
+
binary_preds = model_outputs.get("binary_predictions", {})
|
| 651 |
+
|
| 652 |
+
summary = {
|
| 653 |
+
"num_objects_detected": len(categorical_preds),
|
| 654 |
+
"num_unary_predictions": len(unary_preds),
|
| 655 |
+
"num_binary_predictions": len(binary_preds),
|
| 656 |
+
"top_categories": [],
|
| 657 |
+
"top_actions": [],
|
| 658 |
+
"top_relations": []
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
# Extract top categories
|
| 662 |
+
all_categories = []
|
| 663 |
+
for obj_preds in categorical_preds.values():
|
| 664 |
+
if obj_preds:
|
| 665 |
+
all_categories.extend(obj_preds)
|
| 666 |
+
|
| 667 |
+
if all_categories:
|
| 668 |
+
sorted_categories = sorted(all_categories, reverse=True)
|
| 669 |
+
summary["top_categories"] = [(cat, prob) for prob, cat in sorted_categories[:3]]
|
| 670 |
+
|
| 671 |
+
# Extract top actions
|
| 672 |
+
all_actions = []
|
| 673 |
+
for action_preds in unary_preds.values():
|
| 674 |
+
if action_preds:
|
| 675 |
+
all_actions.extend(action_preds)
|
| 676 |
+
|
| 677 |
+
if all_actions:
|
| 678 |
+
sorted_actions = sorted(all_actions, reverse=True)
|
| 679 |
+
summary["top_actions"] = [(act, prob) for prob, act in sorted_actions[:3]]
|
| 680 |
+
|
| 681 |
+
# Extract top relations
|
| 682 |
+
all_relations = []
|
| 683 |
+
for rel_preds in binary_preds.values():
|
| 684 |
+
if rel_preds:
|
| 685 |
+
all_relations.extend(rel_preds)
|
| 686 |
+
|
| 687 |
+
if all_relations:
|
| 688 |
+
sorted_relations = sorted(all_relations, reverse=True)
|
| 689 |
+
summary["top_relations"] = [(rel, prob) for prob, rel in sorted_relations[:3]]
|
| 690 |
+
|
| 691 |
+
return summary
|