Upload MEV code
Browse files- README.md +45 -0
- gemini/_gemini_runner.py +829 -0
- gemini/generate_multi_event_annotations.py +180 -0
- qwen/camera_motion.md +16 -0
- qwen/classify_camera_motion_qwen3vl.py +372 -0
- qwen/generate_multi_event_annotations.py +2136 -0
- qwen/segment_events_qwen3vl.py +412 -0
- requirements.txt +5 -0
- scripts/multi-event/run_multi_event_annotations.sh +341 -0
- scripts/multi-event/test_multi_event_annotations_100.sh +25 -0
README.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MEV Annotation Toolkit
|
| 2 |
+
|
| 3 |
+
This directory contains the code used to generate multi-event video annotations.
|
| 4 |
+
|
| 5 |
+
## Layout
|
| 6 |
+
|
| 7 |
+
- `qwen/`: local Qwen3-VL annotation, event segmentation, and camera-motion classification scripts.
|
| 8 |
+
- `gemini/`: Gemini API wrappers that reuse the Qwen annotation pipeline schema and post-processing.
|
| 9 |
+
- `scripts/multi-event/`: shell launchers for batched multi-GPU annotation runs.
|
| 10 |
+
|
| 11 |
+
Generated annotations, logs, checkpoints, and datasets are intentionally not included. Keep them under local runtime directories such as `data/`, `annotations/`, `logs/`, and `checkpoints/`.
|
| 12 |
+
|
| 13 |
+
## Basic Usage
|
| 14 |
+
|
| 15 |
+
Run Qwen annotation on segmented videos:
|
| 16 |
+
|
| 17 |
+
```bash
|
| 18 |
+
bash scripts/multi-event/run_multi_event_annotations.sh data/example_segments annotations/qwen/multi_event/output.json --resume
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
Run Gemini annotation:
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
export GEMINI_API_KEY=your_api_key
|
| 25 |
+
python gemini/generate_multi_event_annotations.py --input data/example_segments --output annotations/gemini/multi_event/output.json --recursive --resume
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
Segment a single video into event intervals:
|
| 29 |
+
|
| 30 |
+
```bash
|
| 31 |
+
python qwen/segment_events_qwen3vl.py data/video.mp4 --output annotations/segments/video_events.json
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
Classify camera motion for a single video:
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
python qwen/classify_camera_motion_qwen3vl.py data/video.mp4 --output annotations/camera/video_camera.json
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
## Notes
|
| 41 |
+
|
| 42 |
+
- The Qwen scripts expect a local model checkpoint via `--model-path` or `MODEL_PATH`.
|
| 43 |
+
- The shell launchers derive all paths from this directory and environment variables.
|
| 44 |
+
- `ffmpeg` and `ffprobe` must be available on `PATH`.
|
| 45 |
+
- Gemini scripts use `GEMINI_API_KEY` or `GOOGLE_API_KEY`.
|
gemini/_gemini_runner.py
ADDED
|
@@ -0,0 +1,829 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import ast
|
| 5 |
+
import importlib.util
|
| 6 |
+
import json
|
| 7 |
+
import logging
|
| 8 |
+
import mimetypes
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import requests
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
ROOT_DIR = Path(__file__).resolve().parent.parent
|
| 21 |
+
DEFAULT_API_BASE_URL = "https://generativelanguage.googleapis.com"
|
| 22 |
+
DEFAULT_MODEL_NAME = "models/gemini-2.5-pro"
|
| 23 |
+
DEFAULT_SYSTEM_INSTRUCTION = (
|
| 24 |
+
"You are a careful video annotation assistant. "
|
| 25 |
+
"Return strict JSON only and prefer high-confidence visual facts."
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class GeminiBlockedContentError(RuntimeError):
|
| 30 |
+
def __init__(self, block_reason: str, response_payload: dict[str, Any]):
|
| 31 |
+
self.block_reason = (block_reason or "").strip() or "UNKNOWN"
|
| 32 |
+
self.response_payload = response_payload
|
| 33 |
+
response_snippet = json.dumps(response_payload, ensure_ascii=False)[:2000]
|
| 34 |
+
super().__init__(
|
| 35 |
+
f"Gemini request blocked by safety filter. "
|
| 36 |
+
f"block_reason={self.block_reason} response={response_snippet}"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def load_repo_module(module_name: str, relative_path: str):
|
| 41 |
+
module_path = ROOT_DIR / relative_path
|
| 42 |
+
spec = importlib.util.spec_from_file_location(module_name, module_path)
|
| 43 |
+
if spec is None or spec.loader is None:
|
| 44 |
+
raise ImportError(f"Failed to load module from {module_path}")
|
| 45 |
+
module = importlib.util.module_from_spec(spec)
|
| 46 |
+
sys.modules[module_name] = module
|
| 47 |
+
spec.loader.exec_module(module)
|
| 48 |
+
return module
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def normalize_model_name(value: str | None) -> str:
|
| 52 |
+
cleaned = (value or "").strip()
|
| 53 |
+
if not cleaned:
|
| 54 |
+
return DEFAULT_MODEL_NAME
|
| 55 |
+
if cleaned.startswith("models/"):
|
| 56 |
+
return cleaned
|
| 57 |
+
return f"models/{cleaned}"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def extract_json_text(raw_text: str) -> str:
|
| 61 |
+
text = raw_text.strip()
|
| 62 |
+
fenced_matches = re.findall(r"```(?:json)?\s*(.*?)```", text, flags=re.DOTALL | re.IGNORECASE)
|
| 63 |
+
candidates = [match.strip() for match in fenced_matches if match.strip()]
|
| 64 |
+
candidates.append(text)
|
| 65 |
+
for candidate in candidates:
|
| 66 |
+
if candidate.startswith("{") or candidate.startswith("["):
|
| 67 |
+
return candidate
|
| 68 |
+
for open_char, close_char in (("{", "}"), ("[", "]")):
|
| 69 |
+
start = text.find(open_char)
|
| 70 |
+
if start == -1:
|
| 71 |
+
continue
|
| 72 |
+
depth = 0
|
| 73 |
+
in_string = False
|
| 74 |
+
escape = False
|
| 75 |
+
for index in range(start, len(text)):
|
| 76 |
+
char = text[index]
|
| 77 |
+
if in_string:
|
| 78 |
+
if escape:
|
| 79 |
+
escape = False
|
| 80 |
+
elif char == "\\":
|
| 81 |
+
escape = True
|
| 82 |
+
elif char == '"':
|
| 83 |
+
in_string = False
|
| 84 |
+
continue
|
| 85 |
+
if char == '"':
|
| 86 |
+
in_string = True
|
| 87 |
+
continue
|
| 88 |
+
if char == open_char:
|
| 89 |
+
depth += 1
|
| 90 |
+
elif char == close_char:
|
| 91 |
+
depth -= 1
|
| 92 |
+
if depth == 0:
|
| 93 |
+
return text[start : index + 1]
|
| 94 |
+
raise ValueError("Failed to extract a JSON object from the model response.")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def parse_json_payload(raw_text: str) -> dict[str, Any]:
|
| 98 |
+
json_text = extract_json_text(raw_text)
|
| 99 |
+
try:
|
| 100 |
+
payload = json.loads(json_text)
|
| 101 |
+
except json.JSONDecodeError:
|
| 102 |
+
try:
|
| 103 |
+
payload = ast.literal_eval(json_text)
|
| 104 |
+
except (SyntaxError, ValueError) as exc:
|
| 105 |
+
snippet = raw_text.strip().replace("\n", " ")[:500]
|
| 106 |
+
raise ValueError(f"Model did not return valid JSON. Snippet: {snippet}") from exc
|
| 107 |
+
if isinstance(payload, list):
|
| 108 |
+
if len(payload) == 1 and isinstance(payload[0], dict):
|
| 109 |
+
return payload[0]
|
| 110 |
+
raise ValueError(f"Expected a JSON object, received list with {len(payload)} items.")
|
| 111 |
+
if not isinstance(payload, dict):
|
| 112 |
+
raise ValueError(f"Expected a JSON object, received {type(payload).__name__}.")
|
| 113 |
+
return payload
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def guess_mime_type(path: Path) -> str:
|
| 117 |
+
mime_type, _ = mimetypes.guess_type(str(path))
|
| 118 |
+
if mime_type:
|
| 119 |
+
return mime_type
|
| 120 |
+
suffix = path.suffix.lower()
|
| 121 |
+
if suffix == ".mp4":
|
| 122 |
+
return "video/mp4"
|
| 123 |
+
if suffix == ".mov":
|
| 124 |
+
return "video/quicktime"
|
| 125 |
+
if suffix == ".mkv":
|
| 126 |
+
return "video/x-matroska"
|
| 127 |
+
if suffix == ".avi":
|
| 128 |
+
return "video/x-msvideo"
|
| 129 |
+
if suffix == ".webm":
|
| 130 |
+
return "video/webm"
|
| 131 |
+
return "application/octet-stream"
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def coerce_file_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
| 135 |
+
if "file" in payload and isinstance(payload["file"], dict):
|
| 136 |
+
return payload["file"]
|
| 137 |
+
return payload
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def extract_response_text(payload: dict[str, Any]) -> str:
|
| 141 |
+
texts: list[str] = []
|
| 142 |
+
for candidate in payload.get("candidates", []):
|
| 143 |
+
content = candidate.get("content", {})
|
| 144 |
+
for part in content.get("parts", []):
|
| 145 |
+
text = part.get("text")
|
| 146 |
+
if text:
|
| 147 |
+
texts.append(str(text).strip())
|
| 148 |
+
return "\n".join(part for part in texts if part)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def extract_finish_reason(payload: dict[str, Any]) -> str:
|
| 152 |
+
candidates = payload.get("candidates", [])
|
| 153 |
+
if not candidates:
|
| 154 |
+
return ""
|
| 155 |
+
return str(candidates[0].get("finishReason", "")).strip()
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def extract_block_reason(payload: dict[str, Any]) -> str:
|
| 159 |
+
prompt_feedback = payload.get("promptFeedback", {})
|
| 160 |
+
if not isinstance(prompt_feedback, dict):
|
| 161 |
+
return ""
|
| 162 |
+
return str(prompt_feedback.get("blockReason", "")).strip()
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def looks_like_detection_output(text: str) -> bool:
|
| 166 |
+
lowered = text.lower()
|
| 167 |
+
detection_markers = (
|
| 168 |
+
"box_2d",
|
| 169 |
+
"\"bbox\"",
|
| 170 |
+
"\"label\"",
|
| 171 |
+
"\"labels\"",
|
| 172 |
+
"\"tracking_id\"",
|
| 173 |
+
"\"polygon\"",
|
| 174 |
+
"\"mask\"",
|
| 175 |
+
"\"score\"",
|
| 176 |
+
)
|
| 177 |
+
return any(marker in lowered for marker in detection_markers)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _string_schema(*, nullable: bool = False) -> dict[str, Any]:
|
| 181 |
+
schema: dict[str, Any] = {"type": "STRING"}
|
| 182 |
+
if nullable:
|
| 183 |
+
schema["nullable"] = True
|
| 184 |
+
return schema
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _boolean_schema(*, nullable: bool = False) -> dict[str, Any]:
|
| 188 |
+
schema: dict[str, Any] = {"type": "BOOLEAN"}
|
| 189 |
+
if nullable:
|
| 190 |
+
schema["nullable"] = True
|
| 191 |
+
return schema
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def _object_schema(
|
| 195 |
+
properties: dict[str, dict[str, Any]],
|
| 196 |
+
*,
|
| 197 |
+
required: list[str] | None = None,
|
| 198 |
+
) -> dict[str, Any]:
|
| 199 |
+
schema: dict[str, Any] = {
|
| 200 |
+
"type": "OBJECT",
|
| 201 |
+
"properties": properties,
|
| 202 |
+
}
|
| 203 |
+
if required:
|
| 204 |
+
schema["required"] = required
|
| 205 |
+
return schema
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _array_schema(items: dict[str, Any]) -> dict[str, Any]:
|
| 209 |
+
return {
|
| 210 |
+
"type": "ARRAY",
|
| 211 |
+
"items": items,
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def build_subject_registry_item_schema() -> dict[str, Any]:
|
| 216 |
+
properties = {
|
| 217 |
+
"subject_id": _string_schema(),
|
| 218 |
+
"category": _string_schema(),
|
| 219 |
+
"term": _string_schema(),
|
| 220 |
+
"profile": _string_schema(),
|
| 221 |
+
}
|
| 222 |
+
return _object_schema(properties, required=list(properties))
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def build_global_context_response_schema() -> dict[str, Any]:
|
| 226 |
+
properties = {
|
| 227 |
+
"is_sports": _boolean_schema(),
|
| 228 |
+
"has_animal": _boolean_schema(),
|
| 229 |
+
"is_cooking": _boolean_schema(),
|
| 230 |
+
"subject_registry": _array_schema(build_subject_registry_item_schema()),
|
| 231 |
+
"stable_scene_summary": _string_schema(),
|
| 232 |
+
"stable_camera_summary": _string_schema(),
|
| 233 |
+
}
|
| 234 |
+
return _object_schema(properties, required=list(properties))
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def build_event_response_schema() -> dict[str, Any]:
|
| 238 |
+
properties = {
|
| 239 |
+
"caption": _string_schema(),
|
| 240 |
+
"has_appearance": _boolean_schema(),
|
| 241 |
+
"has_disappearance": _boolean_schema(),
|
| 242 |
+
"has_camera_motion": _boolean_schema(),
|
| 243 |
+
"has_focus_shift": _boolean_schema(nullable=True),
|
| 244 |
+
"is_multi_person": _boolean_schema(),
|
| 245 |
+
"has_environmental_change": _boolean_schema(),
|
| 246 |
+
"has_occlusion": _boolean_schema(),
|
| 247 |
+
"has_lighting_change": _boolean_schema(),
|
| 248 |
+
"has_animal": _boolean_schema(),
|
| 249 |
+
"is_cooking": _boolean_schema(),
|
| 250 |
+
"focus_object": _string_schema(),
|
| 251 |
+
"camera_motion_label": _string_schema(),
|
| 252 |
+
"camera_motion_desc": _string_schema(),
|
| 253 |
+
}
|
| 254 |
+
return _object_schema(properties, required=list(properties))
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def build_caption_only_response_schema() -> dict[str, Any]:
|
| 258 |
+
properties = {"caption": _string_schema()}
|
| 259 |
+
return _object_schema(properties, required=["caption"])
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def build_event_camera_repair_response_schema() -> dict[str, Any]:
|
| 263 |
+
properties = {
|
| 264 |
+
"has_camera_motion": _boolean_schema(),
|
| 265 |
+
"camera_motion_label": _string_schema(),
|
| 266 |
+
"camera_motion_desc": _string_schema(),
|
| 267 |
+
}
|
| 268 |
+
return _object_schema(properties, required=list(properties))
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def build_camera_desc_only_response_schema() -> dict[str, Any]:
|
| 272 |
+
properties = {"camera_motion_desc": _string_schema()}
|
| 273 |
+
return _object_schema(properties, required=["camera_motion_desc"])
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def build_global_camera_repair_response_schema() -> dict[str, Any]:
|
| 277 |
+
properties = {
|
| 278 |
+
"camera_movement_prefix": _string_schema(),
|
| 279 |
+
"camera_movement_label": _string_schema(),
|
| 280 |
+
"camera_movement_description": _string_schema(),
|
| 281 |
+
}
|
| 282 |
+
return _object_schema(properties, required=list(properties))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def build_subject_profile_repair_response_schema() -> dict[str, Any]:
|
| 286 |
+
properties = {"subject_profile": _string_schema()}
|
| 287 |
+
return _object_schema(properties, required=["subject_profile"])
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def build_global_refine_response_schema(*, include_detailed_caption: bool) -> dict[str, Any]:
|
| 291 |
+
properties = {
|
| 292 |
+
"background": _string_schema(),
|
| 293 |
+
"theme": _string_schema(),
|
| 294 |
+
"style": _string_schema(),
|
| 295 |
+
"shot_type": _string_schema(),
|
| 296 |
+
"camera_movement_prefix": _string_schema(),
|
| 297 |
+
"camera_movement_label": _string_schema(),
|
| 298 |
+
"camera_movement_description": _string_schema(),
|
| 299 |
+
"lighting": _string_schema(),
|
| 300 |
+
"atmosphere": _string_schema(),
|
| 301 |
+
"subject_profile": _string_schema(),
|
| 302 |
+
"short_caption": _string_schema(),
|
| 303 |
+
"middle_caption": _string_schema(),
|
| 304 |
+
"long_caption": _string_schema(),
|
| 305 |
+
}
|
| 306 |
+
required = list(properties)
|
| 307 |
+
if include_detailed_caption:
|
| 308 |
+
properties["detailed_caption"] = _string_schema()
|
| 309 |
+
required.append("detailed_caption")
|
| 310 |
+
return _object_schema(properties, required=required)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def infer_response_schema(prompt: str) -> dict[str, Any] | None:
|
| 314 |
+
lowered = prompt.lower()
|
| 315 |
+
if (
|
| 316 |
+
"writing the global annotation" in lowered
|
| 317 |
+
and '"background"' in prompt
|
| 318 |
+
and '"short_caption"' in prompt
|
| 319 |
+
and '"middle_caption"' in prompt
|
| 320 |
+
and '"long_caption"' in prompt
|
| 321 |
+
):
|
| 322 |
+
return build_global_refine_response_schema(
|
| 323 |
+
include_detailed_caption='"detailed_caption"' in prompt
|
| 324 |
+
)
|
| 325 |
+
if (
|
| 326 |
+
'"subject_registry"' in prompt
|
| 327 |
+
and '"stable_scene_summary"' in prompt
|
| 328 |
+
and '"stable_camera_summary"' in prompt
|
| 329 |
+
and '"is_sports"' in prompt
|
| 330 |
+
):
|
| 331 |
+
return build_global_context_response_schema()
|
| 332 |
+
if (
|
| 333 |
+
'"has_appearance"' in prompt
|
| 334 |
+
and '"has_disappearance"' in prompt
|
| 335 |
+
and '"focus_object"' in prompt
|
| 336 |
+
and '"camera_motion_desc"' in prompt
|
| 337 |
+
):
|
| 338 |
+
return build_event_response_schema()
|
| 339 |
+
if "revising the caption for event" in lowered and '"caption"' in prompt:
|
| 340 |
+
return build_caption_only_response_schema()
|
| 341 |
+
if "repairing the camera motion fields for event" in lowered:
|
| 342 |
+
return build_event_camera_repair_response_schema()
|
| 343 |
+
if "rewriting only the event-level camera_motion_desc" in lowered:
|
| 344 |
+
return build_camera_desc_only_response_schema()
|
| 345 |
+
if "repairing the global camera motion fields" in lowered:
|
| 346 |
+
return build_global_camera_repair_response_schema()
|
| 347 |
+
if "repairing the subject_profile field" in lowered:
|
| 348 |
+
return build_subject_profile_repair_response_schema()
|
| 349 |
+
if "return json in exactly this schema" in lowered:
|
| 350 |
+
return {"type": "OBJECT"}
|
| 351 |
+
return None
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def resolve_thinking_budget(model_name: str, raw_value: str | None) -> int | None:
|
| 355 |
+
if raw_value is not None and raw_value.strip() != "":
|
| 356 |
+
return int(raw_value)
|
| 357 |
+
normalized = normalize_model_name(model_name)
|
| 358 |
+
if normalized == "models/gemini-2.5-pro":
|
| 359 |
+
return 128
|
| 360 |
+
return None
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def parse_cleanup_flag(raw_value: str | None) -> bool:
|
| 364 |
+
if raw_value is None:
|
| 365 |
+
return True
|
| 366 |
+
return raw_value.strip().lower() not in {"0", "false", "no", "off"}
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def extract_file_state_name(value: Any) -> str:
|
| 370 |
+
if isinstance(value, dict):
|
| 371 |
+
name = value.get("name")
|
| 372 |
+
return str(name).upper() if name else ""
|
| 373 |
+
if value is None:
|
| 374 |
+
return ""
|
| 375 |
+
return str(value).upper()
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
@dataclass
|
| 379 |
+
class UploadedFile:
|
| 380 |
+
name: str
|
| 381 |
+
uri: str
|
| 382 |
+
mime_type: str
|
| 383 |
+
state: str
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class GeminiRunner:
|
| 387 |
+
def __init__(
|
| 388 |
+
self,
|
| 389 |
+
model_path: Path,
|
| 390 |
+
device_map: str,
|
| 391 |
+
dtype: str,
|
| 392 |
+
attn_implementation: str,
|
| 393 |
+
trust_remote_code: bool,
|
| 394 |
+
fps: float,
|
| 395 |
+
max_pixels: int | None,
|
| 396 |
+
temperature: float,
|
| 397 |
+
top_p: float,
|
| 398 |
+
top_k: int,
|
| 399 |
+
repetition_penalty: float,
|
| 400 |
+
greedy: bool,
|
| 401 |
+
) -> None:
|
| 402 |
+
del model_path, device_map, dtype, attn_implementation, trust_remote_code, repetition_penalty
|
| 403 |
+
self.session = requests.Session()
|
| 404 |
+
self.api_key = (
|
| 405 |
+
os.environ.get("GEMINI_API_KEY")
|
| 406 |
+
or os.environ.get("GOOGLE_API_KEY")
|
| 407 |
+
or os.environ.get("GEMINI_API_TOKEN")
|
| 408 |
+
or ""
|
| 409 |
+
).strip()
|
| 410 |
+
if not self.api_key:
|
| 411 |
+
raise RuntimeError("Missing Gemini API key. Set GEMINI_API_KEY or GOOGLE_API_KEY.")
|
| 412 |
+
|
| 413 |
+
self.model_name = normalize_model_name(os.environ.get("GEMINI_MODEL"))
|
| 414 |
+
self.api_base_url = os.environ.get("GEMINI_API_BASE_URL", DEFAULT_API_BASE_URL).rstrip("/")
|
| 415 |
+
self.system_instruction = os.environ.get("GEMINI_SYSTEM_INSTRUCTION", DEFAULT_SYSTEM_INSTRUCTION).strip()
|
| 416 |
+
self.temperature = 0.0 if greedy else temperature
|
| 417 |
+
self.top_p = top_p
|
| 418 |
+
self.top_k = top_k
|
| 419 |
+
self.greedy = greedy
|
| 420 |
+
self.fps = fps if fps and fps > 0 else None
|
| 421 |
+
self.max_pixels = max_pixels if max_pixels and max_pixels > 0 else None
|
| 422 |
+
self.http_timeout = float(os.environ.get("GEMINI_HTTP_TIMEOUT", "600"))
|
| 423 |
+
self.file_poll_interval = float(os.environ.get("GEMINI_FILE_POLL_INTERVAL", "5"))
|
| 424 |
+
self.file_poll_timeout = float(os.environ.get("GEMINI_FILE_POLL_TIMEOUT", "1800"))
|
| 425 |
+
self.http_retry_count = max(1, int(os.environ.get("GEMINI_HTTP_RETRY_COUNT", "32")))
|
| 426 |
+
self.http_retry_base_delay = max(0.5, float(os.environ.get("GEMINI_HTTP_RETRY_BASE_DELAY", "10")))
|
| 427 |
+
self.http_retry_max_delay = max(
|
| 428 |
+
self.http_retry_base_delay,
|
| 429 |
+
float(os.environ.get("GEMINI_HTTP_RETRY_MAX_DELAY", "120")),
|
| 430 |
+
)
|
| 431 |
+
self.cleanup_uploaded_files = parse_cleanup_flag(os.environ.get("GEMINI_CLEANUP_FILES"))
|
| 432 |
+
self.thinking_budget = resolve_thinking_budget(self.model_name, os.environ.get("GEMINI_THINKING_BUDGET"))
|
| 433 |
+
self.json_retry_count = max(1, int(os.environ.get("GEMINI_JSON_RETRY_COUNT", "3")))
|
| 434 |
+
self.retry_extra_tokens = max(128, int(os.environ.get("GEMINI_RETRY_EXTRA_TOKENS", "512")))
|
| 435 |
+
self.max_retry_tokens = max(1024, int(os.environ.get("GEMINI_MAX_RETRY_TOKENS", "8192")))
|
| 436 |
+
self.use_response_schema = parse_cleanup_flag(os.environ.get("GEMINI_USE_RESPONSE_SCHEMA"))
|
| 437 |
+
self.upload_cache: dict[Path, UploadedFile] = {}
|
| 438 |
+
|
| 439 |
+
logging.info(
|
| 440 |
+
"Initialized Gemini runner with model=%s api_base=%s cleanup_files=%s json_retries=%d http_retries=%d response_schema=%s",
|
| 441 |
+
self.model_name,
|
| 442 |
+
self.api_base_url,
|
| 443 |
+
self.cleanup_uploaded_files,
|
| 444 |
+
self.json_retry_count,
|
| 445 |
+
self.http_retry_count,
|
| 446 |
+
self.use_response_schema,
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
@staticmethod
|
| 450 |
+
def _is_retryable_status(status_code: int) -> bool:
|
| 451 |
+
return status_code == 429 or status_code in {500, 502, 503, 504}
|
| 452 |
+
|
| 453 |
+
def _retry_delay(self, attempt: int, response: requests.Response | None = None) -> float:
|
| 454 |
+
if response is not None:
|
| 455 |
+
retry_after = response.headers.get("Retry-After", "").strip()
|
| 456 |
+
if retry_after:
|
| 457 |
+
try:
|
| 458 |
+
return min(float(retry_after), self.http_retry_max_delay)
|
| 459 |
+
except ValueError:
|
| 460 |
+
pass
|
| 461 |
+
delay = self.http_retry_base_delay * (2 ** max(attempt - 1, 0))
|
| 462 |
+
return min(delay, self.http_retry_max_delay)
|
| 463 |
+
|
| 464 |
+
def _request(
|
| 465 |
+
self,
|
| 466 |
+
method: str,
|
| 467 |
+
url: str,
|
| 468 |
+
*,
|
| 469 |
+
json_payload: dict[str, Any] | None = None,
|
| 470 |
+
data: Any = None,
|
| 471 |
+
headers: dict[str, str] | None = None,
|
| 472 |
+
timeout: float | None = None,
|
| 473 |
+
expected_status: int | None = None,
|
| 474 |
+
include_api_key: bool = True,
|
| 475 |
+
) -> requests.Response:
|
| 476 |
+
merged_headers = dict(headers or {})
|
| 477 |
+
last_error: Exception | None = None
|
| 478 |
+
for attempt in range(1, self.http_retry_count + 1):
|
| 479 |
+
response: requests.Response | None = None
|
| 480 |
+
try:
|
| 481 |
+
response = self.session.request(
|
| 482 |
+
method=method,
|
| 483 |
+
url=url,
|
| 484 |
+
params={"key": self.api_key} if include_api_key else None,
|
| 485 |
+
json=json_payload,
|
| 486 |
+
data=data,
|
| 487 |
+
headers=merged_headers,
|
| 488 |
+
timeout=timeout or self.http_timeout,
|
| 489 |
+
)
|
| 490 |
+
if expected_status is not None and response.status_code != expected_status:
|
| 491 |
+
if self._is_retryable_status(response.status_code) and attempt < self.http_retry_count:
|
| 492 |
+
delay = self._retry_delay(attempt, response)
|
| 493 |
+
logging.warning(
|
| 494 |
+
"%s %s returned retryable status %d on attempt %d/%d. Retrying in %.1fs.",
|
| 495 |
+
method,
|
| 496 |
+
url,
|
| 497 |
+
response.status_code,
|
| 498 |
+
attempt,
|
| 499 |
+
self.http_retry_count,
|
| 500 |
+
delay,
|
| 501 |
+
)
|
| 502 |
+
time.sleep(delay)
|
| 503 |
+
continue
|
| 504 |
+
raise RuntimeError(
|
| 505 |
+
f"{method} {url} failed with {response.status_code}: {response.text.strip()}"
|
| 506 |
+
)
|
| 507 |
+
try:
|
| 508 |
+
response.raise_for_status()
|
| 509 |
+
except requests.HTTPError as exc:
|
| 510 |
+
if self._is_retryable_status(response.status_code) and attempt < self.http_retry_count:
|
| 511 |
+
delay = self._retry_delay(attempt, response)
|
| 512 |
+
logging.warning(
|
| 513 |
+
"%s %s returned retryable status %d on attempt %d/%d. Retrying in %.1fs.",
|
| 514 |
+
method,
|
| 515 |
+
url,
|
| 516 |
+
response.status_code,
|
| 517 |
+
attempt,
|
| 518 |
+
self.http_retry_count,
|
| 519 |
+
delay,
|
| 520 |
+
)
|
| 521 |
+
time.sleep(delay)
|
| 522 |
+
continue
|
| 523 |
+
raise RuntimeError(
|
| 524 |
+
f"{method} {url} failed with {response.status_code}: {response.text.strip()}"
|
| 525 |
+
) from exc
|
| 526 |
+
return response
|
| 527 |
+
except requests.RequestException as exc:
|
| 528 |
+
last_error = exc
|
| 529 |
+
if attempt < self.http_retry_count:
|
| 530 |
+
delay = self._retry_delay(attempt, response)
|
| 531 |
+
logging.warning(
|
| 532 |
+
"%s %s failed with %s on attempt %d/%d. Retrying in %.1fs.",
|
| 533 |
+
method,
|
| 534 |
+
url,
|
| 535 |
+
exc.__class__.__name__,
|
| 536 |
+
attempt,
|
| 537 |
+
self.http_retry_count,
|
| 538 |
+
delay,
|
| 539 |
+
)
|
| 540 |
+
time.sleep(delay)
|
| 541 |
+
continue
|
| 542 |
+
raise RuntimeError(f"{method} {url} failed after {attempt} attempts: {exc}") from exc
|
| 543 |
+
if last_error is not None:
|
| 544 |
+
raise RuntimeError(f"{method} {url} failed after {self.http_retry_count} attempts: {last_error}") from last_error
|
| 545 |
+
raise RuntimeError(f"{method} {url} failed without a response.")
|
| 546 |
+
|
| 547 |
+
def _request_json(
|
| 548 |
+
self,
|
| 549 |
+
method: str,
|
| 550 |
+
url: str,
|
| 551 |
+
*,
|
| 552 |
+
json_payload: dict[str, Any] | None = None,
|
| 553 |
+
data: Any = None,
|
| 554 |
+
headers: dict[str, str] | None = None,
|
| 555 |
+
timeout: float | None = None,
|
| 556 |
+
expected_status: int | None = None,
|
| 557 |
+
include_api_key: bool = True,
|
| 558 |
+
) -> dict[str, Any]:
|
| 559 |
+
response = self._request(
|
| 560 |
+
method,
|
| 561 |
+
url,
|
| 562 |
+
json_payload=json_payload,
|
| 563 |
+
data=data,
|
| 564 |
+
headers=headers,
|
| 565 |
+
timeout=timeout,
|
| 566 |
+
expected_status=expected_status,
|
| 567 |
+
include_api_key=include_api_key,
|
| 568 |
+
)
|
| 569 |
+
if not response.content:
|
| 570 |
+
return {}
|
| 571 |
+
return response.json()
|
| 572 |
+
|
| 573 |
+
def _upload_file(self, path: Path) -> UploadedFile:
|
| 574 |
+
resolved = path.expanduser().resolve()
|
| 575 |
+
cached = self.upload_cache.get(resolved)
|
| 576 |
+
if cached is not None:
|
| 577 |
+
return cached
|
| 578 |
+
|
| 579 |
+
if not resolved.exists():
|
| 580 |
+
raise FileNotFoundError(f"Video file does not exist: {resolved}")
|
| 581 |
+
|
| 582 |
+
mime_type = guess_mime_type(resolved)
|
| 583 |
+
file_size = resolved.stat().st_size
|
| 584 |
+
start_headers = {
|
| 585 |
+
"X-Goog-Upload-Protocol": "resumable",
|
| 586 |
+
"X-Goog-Upload-Command": "start",
|
| 587 |
+
"X-Goog-Upload-Header-Content-Length": str(file_size),
|
| 588 |
+
"X-Goog-Upload-Header-Content-Type": mime_type,
|
| 589 |
+
"Content-Type": "application/json",
|
| 590 |
+
}
|
| 591 |
+
start_payload = {"file": {"display_name": resolved.name}}
|
| 592 |
+
start_response = self._request(
|
| 593 |
+
"POST",
|
| 594 |
+
f"{self.api_base_url}/upload/v1beta/files",
|
| 595 |
+
json_payload=start_payload,
|
| 596 |
+
headers=start_headers,
|
| 597 |
+
)
|
| 598 |
+
upload_url = (
|
| 599 |
+
start_response.headers.get("X-Goog-Upload-URL")
|
| 600 |
+
or start_response.headers.get("x-goog-upload-url")
|
| 601 |
+
or ""
|
| 602 |
+
).strip()
|
| 603 |
+
if not upload_url:
|
| 604 |
+
raise RuntimeError("Gemini Files API did not return an upload URL.")
|
| 605 |
+
|
| 606 |
+
upload_headers = {
|
| 607 |
+
"Content-Length": str(file_size),
|
| 608 |
+
"X-Goog-Upload-Offset": "0",
|
| 609 |
+
"X-Goog-Upload-Command": "upload, finalize",
|
| 610 |
+
}
|
| 611 |
+
with resolved.open("rb") as handle:
|
| 612 |
+
upload_payload = self._request_json(
|
| 613 |
+
"POST",
|
| 614 |
+
upload_url,
|
| 615 |
+
data=handle,
|
| 616 |
+
headers=upload_headers,
|
| 617 |
+
timeout=self.http_timeout,
|
| 618 |
+
include_api_key=False,
|
| 619 |
+
)
|
| 620 |
+
|
| 621 |
+
uploaded = self._coerce_uploaded_file(upload_payload, fallback_mime_type=mime_type)
|
| 622 |
+
uploaded = self._wait_until_active(uploaded)
|
| 623 |
+
self.upload_cache[resolved] = uploaded
|
| 624 |
+
return uploaded
|
| 625 |
+
|
| 626 |
+
def _coerce_uploaded_file(self, payload: dict[str, Any], fallback_mime_type: str) -> UploadedFile:
|
| 627 |
+
file_payload = coerce_file_payload(payload)
|
| 628 |
+
name = str(file_payload.get("name", "")).strip()
|
| 629 |
+
uri = str(file_payload.get("uri", "")).strip()
|
| 630 |
+
mime_type = str(file_payload.get("mimeType", "") or file_payload.get("mime_type", "")).strip()
|
| 631 |
+
state = extract_file_state_name(file_payload.get("state"))
|
| 632 |
+
if not name:
|
| 633 |
+
raise RuntimeError(f"Gemini file upload/get response did not contain a file name: {payload}")
|
| 634 |
+
return UploadedFile(
|
| 635 |
+
name=name,
|
| 636 |
+
uri=uri,
|
| 637 |
+
mime_type=mime_type or fallback_mime_type,
|
| 638 |
+
state=state,
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
def _get_file(self, file_name: str, fallback_mime_type: str) -> UploadedFile:
|
| 642 |
+
payload = self._request_json(
|
| 643 |
+
"GET",
|
| 644 |
+
f"{self.api_base_url}/v1beta/{file_name}",
|
| 645 |
+
)
|
| 646 |
+
return self._coerce_uploaded_file(payload, fallback_mime_type=fallback_mime_type)
|
| 647 |
+
|
| 648 |
+
def _wait_until_active(self, uploaded: UploadedFile) -> UploadedFile:
|
| 649 |
+
current = uploaded
|
| 650 |
+
deadline = time.time() + self.file_poll_timeout
|
| 651 |
+
while True:
|
| 652 |
+
state = current.state.upper()
|
| 653 |
+
if current.uri and state in {"", "ACTIVE"}:
|
| 654 |
+
return current
|
| 655 |
+
if state not in {"PROCESSING", "UNSPECIFIED", "STATE_UNSPECIFIED", ""}:
|
| 656 |
+
raise RuntimeError(
|
| 657 |
+
f"Gemini file {current.name} entered unexpected state {current.state or '<empty>'}."
|
| 658 |
+
)
|
| 659 |
+
if time.time() >= deadline:
|
| 660 |
+
raise TimeoutError(f"Timed out waiting for Gemini file {current.name} to become ACTIVE.")
|
| 661 |
+
time.sleep(self.file_poll_interval)
|
| 662 |
+
current = self._get_file(current.name, fallback_mime_type=current.mime_type)
|
| 663 |
+
|
| 664 |
+
def _build_contents(self, video_paths: list[Path], prompt: str) -> list[dict[str, Any]]:
|
| 665 |
+
parts: list[dict[str, Any]] = []
|
| 666 |
+
for path in video_paths:
|
| 667 |
+
uploaded = self._upload_file(path)
|
| 668 |
+
parts.append(
|
| 669 |
+
{
|
| 670 |
+
"file_data": {
|
| 671 |
+
"mime_type": uploaded.mime_type,
|
| 672 |
+
"file_uri": uploaded.uri,
|
| 673 |
+
}
|
| 674 |
+
}
|
| 675 |
+
)
|
| 676 |
+
parts.append({"text": prompt})
|
| 677 |
+
return [{"role": "user", "parts": parts}]
|
| 678 |
+
|
| 679 |
+
def _build_generation_config(
|
| 680 |
+
self,
|
| 681 |
+
max_new_tokens: int,
|
| 682 |
+
*,
|
| 683 |
+
force_deterministic: bool = False,
|
| 684 |
+
response_schema: dict[str, Any] | None = None,
|
| 685 |
+
) -> dict[str, Any]:
|
| 686 |
+
config: dict[str, Any] = {
|
| 687 |
+
"temperature": 0.0 if force_deterministic else self.temperature,
|
| 688 |
+
"maxOutputTokens": max_new_tokens,
|
| 689 |
+
"responseMimeType": "application/json",
|
| 690 |
+
}
|
| 691 |
+
if not force_deterministic and self.top_p and self.top_p > 0:
|
| 692 |
+
config["topP"] = self.top_p
|
| 693 |
+
if not force_deterministic and self.top_k and self.top_k > 0:
|
| 694 |
+
config["topK"] = self.top_k
|
| 695 |
+
if self.thinking_budget is not None:
|
| 696 |
+
config["thinkingConfig"] = {"thinkingBudget": self.thinking_budget}
|
| 697 |
+
if response_schema is not None:
|
| 698 |
+
config["responseSchema"] = response_schema
|
| 699 |
+
return config
|
| 700 |
+
|
| 701 |
+
def _build_retry_prompt(self, prompt: str, retry_reason: str, attempt: int) -> str:
|
| 702 |
+
return (
|
| 703 |
+
f"{prompt}\n\n"
|
| 704 |
+
"IMPORTANT RETRY INSTRUCTIONS:\n"
|
| 705 |
+
f"- The previous response was invalid because: {retry_reason}.\n"
|
| 706 |
+
f"- This is retry attempt {attempt}.\n"
|
| 707 |
+
"- Return exactly one complete top-level JSON object matching the requested schema.\n"
|
| 708 |
+
"- Do not return a JSON array or a list of events.\n"
|
| 709 |
+
"- If you previously returned one item per clip or one item per event, merge them into one global object that matches the requested schema.\n"
|
| 710 |
+
"- Do not return object-detection output, boxes, coordinates, labels-only results, OCR blocks, or grounding results.\n"
|
| 711 |
+
"- Never emit keys such as box_2d, bbox, label, labels, score, mask, polygon, or tracking_id unless the requested schema explicitly asks for them.\n"
|
| 712 |
+
"- Do not include markdown fences, explanations, or any extra text.\n"
|
| 713 |
+
"- Make sure every string is closed and the JSON is syntactically complete.\n"
|
| 714 |
+
"- Keep field values concise enough to finish within the token budget.\n"
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
def _generate_once(
|
| 718 |
+
self,
|
| 719 |
+
*,
|
| 720 |
+
video_paths: list[Path],
|
| 721 |
+
prompt: str,
|
| 722 |
+
max_new_tokens: int,
|
| 723 |
+
force_deterministic: bool,
|
| 724 |
+
) -> dict[str, Any]:
|
| 725 |
+
response_schema = infer_response_schema(prompt) if self.use_response_schema else None
|
| 726 |
+
request_payload = {
|
| 727 |
+
"systemInstruction": {
|
| 728 |
+
"parts": [{"text": self.system_instruction}],
|
| 729 |
+
},
|
| 730 |
+
"contents": self._build_contents(video_paths, prompt),
|
| 731 |
+
"generationConfig": self._build_generation_config(
|
| 732 |
+
max_new_tokens,
|
| 733 |
+
force_deterministic=force_deterministic,
|
| 734 |
+
response_schema=response_schema,
|
| 735 |
+
),
|
| 736 |
+
"store": False,
|
| 737 |
+
}
|
| 738 |
+
return self._request_json(
|
| 739 |
+
"POST",
|
| 740 |
+
f"{self.api_base_url}/v1beta/{self.model_name}:generateContent",
|
| 741 |
+
json_payload=request_payload,
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
def generate_json(
|
| 745 |
+
self,
|
| 746 |
+
video_paths: list[Path],
|
| 747 |
+
prompt: str,
|
| 748 |
+
max_new_tokens: int,
|
| 749 |
+
) -> dict[str, Any]:
|
| 750 |
+
current_max_tokens = max_new_tokens
|
| 751 |
+
retry_reason = "initial invalid JSON response"
|
| 752 |
+
last_error: Exception | None = None
|
| 753 |
+
last_response_text = ""
|
| 754 |
+
last_finish_reason = ""
|
| 755 |
+
|
| 756 |
+
for attempt in range(1, self.json_retry_count + 1):
|
| 757 |
+
attempt_prompt = (
|
| 758 |
+
prompt if attempt == 1 else self._build_retry_prompt(prompt, retry_reason, attempt)
|
| 759 |
+
)
|
| 760 |
+
response_payload = self._generate_once(
|
| 761 |
+
video_paths=video_paths,
|
| 762 |
+
prompt=attempt_prompt,
|
| 763 |
+
max_new_tokens=current_max_tokens,
|
| 764 |
+
force_deterministic=attempt > 1,
|
| 765 |
+
)
|
| 766 |
+
finish_reason = extract_finish_reason(response_payload)
|
| 767 |
+
block_reason = extract_block_reason(response_payload)
|
| 768 |
+
output_text = extract_response_text(response_payload)
|
| 769 |
+
last_response_text = output_text
|
| 770 |
+
last_finish_reason = finish_reason
|
| 771 |
+
|
| 772 |
+
if block_reason == "PROHIBITED_CONTENT" or finish_reason == "PROHIBITED_CONTENT":
|
| 773 |
+
raise GeminiBlockedContentError(
|
| 774 |
+
block_reason=block_reason or finish_reason,
|
| 775 |
+
response_payload=response_payload,
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
if not output_text:
|
| 779 |
+
retry_reason = f"empty text response (finishReason={finish_reason or '<empty>'})"
|
| 780 |
+
last_error = RuntimeError(
|
| 781 |
+
"Gemini generateContent did not return a text payload. "
|
| 782 |
+
f"finish_reason={finish_reason or '<empty>'} response={json.dumps(response_payload, ensure_ascii=False)[:2000]}"
|
| 783 |
+
)
|
| 784 |
+
else:
|
| 785 |
+
try:
|
| 786 |
+
return parse_json_payload(output_text)
|
| 787 |
+
except Exception as exc:
|
| 788 |
+
snippet = output_text.strip().replace("\n", " ")[:500]
|
| 789 |
+
logging.warning(
|
| 790 |
+
"Gemini returned invalid JSON on attempt %d/%d (finish_reason=%s, max_tokens=%d). Snippet: %s",
|
| 791 |
+
attempt,
|
| 792 |
+
self.json_retry_count,
|
| 793 |
+
finish_reason or "<empty>",
|
| 794 |
+
current_max_tokens,
|
| 795 |
+
snippet,
|
| 796 |
+
)
|
| 797 |
+
if looks_like_detection_output(output_text):
|
| 798 |
+
retry_reason = (
|
| 799 |
+
"You returned object-detection or grounding JSON with boxes/labels instead of the requested schema."
|
| 800 |
+
)
|
| 801 |
+
else:
|
| 802 |
+
retry_reason = f"{type(exc).__name__}: {exc}"
|
| 803 |
+
last_error = exc
|
| 804 |
+
|
| 805 |
+
if finish_reason == "MAX_TOKENS":
|
| 806 |
+
current_max_tokens = min(self.max_retry_tokens, current_max_tokens + self.retry_extra_tokens)
|
| 807 |
+
|
| 808 |
+
snippet = last_response_text.strip().replace("\n", " ")[:500]
|
| 809 |
+
raise RuntimeError(
|
| 810 |
+
"Gemini failed to return valid JSON after retries. "
|
| 811 |
+
f"finish_reason={last_finish_reason or '<empty>'} "
|
| 812 |
+
f"last_error={last_error} "
|
| 813 |
+
f"last_snippet={snippet}"
|
| 814 |
+
)
|
| 815 |
+
|
| 816 |
+
def close(self) -> None:
|
| 817 |
+
if not self.cleanup_uploaded_files:
|
| 818 |
+
return
|
| 819 |
+
seen_names = {uploaded.name for uploaded in self.upload_cache.values() if uploaded.name}
|
| 820 |
+
for file_name in seen_names:
|
| 821 |
+
try:
|
| 822 |
+
self._request(
|
| 823 |
+
"DELETE",
|
| 824 |
+
f"{self.api_base_url}/v1beta/{file_name}",
|
| 825 |
+
expected_status=200,
|
| 826 |
+
)
|
| 827 |
+
except Exception as exc:
|
| 828 |
+
logging.warning("Failed to delete Gemini file %s: %s", file_name, exc)
|
| 829 |
+
self.upload_cache.clear()
|
gemini/generate_multi_event_annotations.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import re
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from _gemini_runner import GeminiRunner, load_repo_module
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
BASE = load_repo_module("qwen_multi_event_base", "qwen/generate_multi_event_annotations.py")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def strip_detailed_caption_from_global_prompt(prompt: str) -> str:
|
| 17 |
+
cleaned = prompt
|
| 18 |
+
cleaned = cleaned.replace(
|
| 19 |
+
'- The detailed caption should be about 500-800 words.\n',
|
| 20 |
+
"",
|
| 21 |
+
)
|
| 22 |
+
cleaned = cleaned.replace(
|
| 23 |
+
'- The detailed caption may synthesize and reuse the structured fields plus stable recurring evidence from the event summaries, but it must not turn into a segment-by-segment narration.\n',
|
| 24 |
+
"",
|
| 25 |
+
)
|
| 26 |
+
cleaned = re.sub(
|
| 27 |
+
r',\n(\s*)"detailed_caption": "About 500-800 words\."\n',
|
| 28 |
+
"\n",
|
| 29 |
+
cleaned,
|
| 30 |
+
)
|
| 31 |
+
return cleaned
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_ORIGINAL_BUILD_GLOBAL_CONTEXT_PROMPT = BASE.build_global_context_prompt
|
| 35 |
+
_ORIGINAL_BUILD_GLOBAL_REFINE_PROMPT = BASE.build_global_refine_prompt
|
| 36 |
+
_ORIGINAL_COERCE_GLOBAL_PAYLOAD = BASE.coerce_global_payload
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _gemini_build_global_context_prompt(*args, **kwargs):
|
| 40 |
+
prompt = _ORIGINAL_BUILD_GLOBAL_CONTEXT_PROMPT(*args, **kwargs)
|
| 41 |
+
return (
|
| 42 |
+
f"{prompt}\n\n"
|
| 43 |
+
"IMPORTANT FOR GEMINI:\n"
|
| 44 |
+
"- Return one single JSON object for the entire stitched video.\n"
|
| 45 |
+
"- Never return a JSON array.\n"
|
| 46 |
+
"- Never return one object per clip, per segment, or per event.\n"
|
| 47 |
+
"- The stitched video may contain multiple chronological event clips, but this context pass must summarize the whole stitched video into one object only.\n"
|
| 48 |
+
"- Do not return object-detection output, tracking output, grounding output, OCR output, or visual tool output.\n"
|
| 49 |
+
"- Never return keys such as box_2d, bbox, label, labels, mask, polygon, points, score, or tracking_id unless the requested schema explicitly asks for them.\n"
|
| 50 |
+
"- Never return timestamped clip-local records such as event_clip_id, start_time_seconds, or end_time_seconds in this context pass.\n"
|
| 51 |
+
"- If uncertain, still fill the requested schema directly with high-confidence whole-video annotations rather than switching to detection-style results.\n"
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _gemini_build_global_refine_prompt(*args, **kwargs):
|
| 56 |
+
return strip_detailed_caption_from_global_prompt(
|
| 57 |
+
_ORIGINAL_BUILD_GLOBAL_REFINE_PROMPT(*args, **kwargs)
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _gemini_coerce_global_payload(*args, **kwargs):
|
| 62 |
+
payload = _ORIGINAL_COERCE_GLOBAL_PAYLOAD(*args, **kwargs)
|
| 63 |
+
payload.pop("detailed_caption", None)
|
| 64 |
+
return payload
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
BASE.build_global_context_prompt = _gemini_build_global_context_prompt
|
| 68 |
+
BASE.build_global_refine_prompt = _gemini_build_global_refine_prompt
|
| 69 |
+
BASE.coerce_global_payload = _gemini_coerce_global_payload
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def main() -> int:
|
| 73 |
+
args = BASE.parse_args()
|
| 74 |
+
BASE.setup_logging(args.log_level)
|
| 75 |
+
|
| 76 |
+
input_path = Path(args.input).expanduser().resolve()
|
| 77 |
+
output_path = Path(args.output).expanduser().resolve()
|
| 78 |
+
camera_motion_guide_path = Path(args.camera_motion_guide).expanduser().resolve()
|
| 79 |
+
|
| 80 |
+
suffixes = BASE.parse_video_suffixes(args.video_suffixes)
|
| 81 |
+
allow_uuids = BASE.load_uuid_allow_list(args.uuids, args.uuids_file)
|
| 82 |
+
camera_motion_guide = BASE.load_camera_motion_guide(camera_motion_guide_path)
|
| 83 |
+
|
| 84 |
+
groups = BASE.collect_segment_groups(
|
| 85 |
+
input_path=input_path,
|
| 86 |
+
recursive=args.recursive,
|
| 87 |
+
suffixes=suffixes,
|
| 88 |
+
allow_uuids=allow_uuids,
|
| 89 |
+
)
|
| 90 |
+
if not groups:
|
| 91 |
+
raise RuntimeError("No valid segmented videos were found.")
|
| 92 |
+
|
| 93 |
+
uuids = list(groups)
|
| 94 |
+
if args.limit is not None:
|
| 95 |
+
uuids = uuids[: args.limit]
|
| 96 |
+
|
| 97 |
+
pending_for_print = uuids
|
| 98 |
+
if args.resume and output_path.exists():
|
| 99 |
+
existing_videos_for_print = BASE.load_existing_output(
|
| 100 |
+
output_path=output_path,
|
| 101 |
+
overwrite=False,
|
| 102 |
+
resume=True,
|
| 103 |
+
)
|
| 104 |
+
pending_for_print = [uuid for uuid in uuids if uuid not in existing_videos_for_print]
|
| 105 |
+
|
| 106 |
+
if args.print_uuids_json:
|
| 107 |
+
print(json.dumps(pending_for_print, ensure_ascii=False))
|
| 108 |
+
return 0
|
| 109 |
+
|
| 110 |
+
uuids = BASE.apply_uuid_shard(
|
| 111 |
+
uuids=pending_for_print if args.resume else uuids,
|
| 112 |
+
num_shards=args.num_shards,
|
| 113 |
+
shard_index=args.shard_index,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
logging.info("Discovered %d UUID groups.", len(uuids))
|
| 117 |
+
for uuid in uuids:
|
| 118 |
+
logging.info("UUID %s has %d segments.", uuid, len(groups[uuid]))
|
| 119 |
+
|
| 120 |
+
if args.dry_run:
|
| 121 |
+
logging.info("Dry run complete. Gemini model was not called.")
|
| 122 |
+
return 0
|
| 123 |
+
|
| 124 |
+
existing_videos = BASE.load_existing_output(
|
| 125 |
+
output_path=output_path,
|
| 126 |
+
overwrite=args.overwrite,
|
| 127 |
+
resume=args.resume,
|
| 128 |
+
)
|
| 129 |
+
pending_uuids = [uuid for uuid in uuids if uuid not in existing_videos]
|
| 130 |
+
if not pending_uuids:
|
| 131 |
+
logging.info("Nothing to do. All requested UUIDs already exist in %s.", output_path)
|
| 132 |
+
return 0
|
| 133 |
+
|
| 134 |
+
runner = GeminiRunner(
|
| 135 |
+
model_path=Path(args.model_path).expanduser().resolve(),
|
| 136 |
+
device_map=args.device_map,
|
| 137 |
+
dtype=args.dtype,
|
| 138 |
+
attn_implementation=args.attn_implementation,
|
| 139 |
+
trust_remote_code=args.trust_remote_code,
|
| 140 |
+
fps=args.fps,
|
| 141 |
+
max_pixels=args.max_pixels,
|
| 142 |
+
temperature=args.temperature,
|
| 143 |
+
top_p=args.top_p,
|
| 144 |
+
top_k=args.top_k,
|
| 145 |
+
repetition_penalty=args.repetition_penalty,
|
| 146 |
+
greedy=args.greedy,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
try:
|
| 150 |
+
failures: list[str] = []
|
| 151 |
+
for index, uuid in enumerate(pending_uuids, start=1):
|
| 152 |
+
logging.info("Processing UUID %s (%d/%d)", uuid, index, len(pending_uuids))
|
| 153 |
+
try:
|
| 154 |
+
video_payload = BASE.annotate_uuid(
|
| 155 |
+
uuid=uuid,
|
| 156 |
+
segments=groups[uuid],
|
| 157 |
+
runner=runner,
|
| 158 |
+
camera_motion_guide=camera_motion_guide,
|
| 159 |
+
args=args,
|
| 160 |
+
)
|
| 161 |
+
existing_videos[uuid] = video_payload
|
| 162 |
+
BASE.write_output(output_path, existing_videos)
|
| 163 |
+
logging.info("Wrote %s", output_path)
|
| 164 |
+
except Exception as exc:
|
| 165 |
+
if not args.continue_on_error:
|
| 166 |
+
raise
|
| 167 |
+
logging.exception("Failed to process %s: %s", uuid, exc)
|
| 168 |
+
failures.append(uuid)
|
| 169 |
+
|
| 170 |
+
if failures:
|
| 171 |
+
logging.error("Completed with failures: %s", ", ".join(failures))
|
| 172 |
+
return 1
|
| 173 |
+
logging.info("Finished %d UUIDs.", len(pending_uuids))
|
| 174 |
+
return 0
|
| 175 |
+
finally:
|
| 176 |
+
runner.close()
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
sys.exit(main())
|
qwen/camera_motion.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Camera Motion Labels
|
| 2 |
+
|
| 3 |
+
| Camera Motion Label | Explanation |
|
| 4 |
+
|---|---|
|
| 5 |
+
| `dolly-in` | The camera moves forward relative to the ground plane and the initial frame. |
|
| 6 |
+
| `dolly-out` | The camera moves backward relative to the ground plane and the initial frame. |
|
| 7 |
+
| `pedestal-up` | Select this when the camera moves upward clearly and consistently relative to the ground or the orientation of the initial frame. |
|
| 8 |
+
| `pedestal-down` | Select this when the camera moves downward clearly and consistently relative to the ground or the orientation of the initial frame. |
|
| 9 |
+
| `truck-left` | The camera physically moves to the left, changing its position relative to the initial frame. |
|
| 10 |
+
| `truck-right` | The camera physically moves to the right, changing its position relative to the initial frame. |
|
| 11 |
+
| `pan-left` | The camera rotates its angle by pivoting left with respect to the initial frame. |
|
| 12 |
+
| `pan-right` | The camera rotates its angle by pivoting right with respect to the initial frame. |
|
| 13 |
+
| `tilt-up` | The camera rotates its angle upward vertically with respect to the initial frame. |
|
| 14 |
+
| `tilt-down` | The camera rotates its angle downward vertically with respect to the initial frame. |
|
| 15 |
+
| `roll-CW` | The camera performs a clear and consistent clockwise roll by rotating around its own optical center. |
|
| 16 |
+
| `roll-CCW` | The camera performs a clear and consistent counterclockwise roll by rotating around its own optical center. |
|
qwen/classify_camera_motion_qwen3vl.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import ast
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
ROOT = Path(__file__).resolve().parent
|
| 13 |
+
DEFAULT_CAMERA_GUIDE = ROOT / "camera_motion.md"
|
| 14 |
+
|
| 15 |
+
CAMERA_MOTION_LABELS = [
|
| 16 |
+
"static",
|
| 17 |
+
"dolly-in",
|
| 18 |
+
"dolly-out",
|
| 19 |
+
"pedestal-up",
|
| 20 |
+
"pedestal-down",
|
| 21 |
+
"truck-left",
|
| 22 |
+
"truck-right",
|
| 23 |
+
"pan-left",
|
| 24 |
+
"pan-right",
|
| 25 |
+
"tilt-up",
|
| 26 |
+
"tilt-down",
|
| 27 |
+
"roll-CW",
|
| 28 |
+
"roll-CCW",
|
| 29 |
+
]
|
| 30 |
+
LABEL_MAP = {label.lower(): label for label in CAMERA_MOTION_LABELS}
|
| 31 |
+
LABEL_ALIASES = {
|
| 32 |
+
"none": "static",
|
| 33 |
+
"no motion": "static",
|
| 34 |
+
"no-motion": "static",
|
| 35 |
+
"near-static": "static",
|
| 36 |
+
"stationary": "static",
|
| 37 |
+
"clockwise roll": "roll-CW",
|
| 38 |
+
"counterclockwise roll": "roll-CCW",
|
| 39 |
+
"counter-clockwise roll": "roll-CCW",
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def parse_args() -> argparse.Namespace:
|
| 44 |
+
parser = argparse.ArgumentParser(
|
| 45 |
+
description="Classify camera motion for one video with Qwen3-VL."
|
| 46 |
+
)
|
| 47 |
+
parser.add_argument("video", help="Path to the input video.")
|
| 48 |
+
parser.add_argument(
|
| 49 |
+
"--model-path",
|
| 50 |
+
default="Qwen/Qwen3-VL-32B-Instruct",
|
| 51 |
+
help="Local checkpoint path or Hugging Face model id.",
|
| 52 |
+
)
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
"--camera-motion-guide",
|
| 55 |
+
default=str(DEFAULT_CAMERA_GUIDE),
|
| 56 |
+
help="Path to camera_motion.md.",
|
| 57 |
+
)
|
| 58 |
+
parser.add_argument(
|
| 59 |
+
"--output",
|
| 60 |
+
default=None,
|
| 61 |
+
help="Optional JSON output path. If omitted, prints JSON to stdout.",
|
| 62 |
+
)
|
| 63 |
+
parser.add_argument("--fps", type=float, default=1.0, help="Video sampling FPS.")
|
| 64 |
+
parser.add_argument(
|
| 65 |
+
"--max-pixels",
|
| 66 |
+
type=int,
|
| 67 |
+
default=360000,
|
| 68 |
+
help="Optional Qwen video processor max_pixels hint. Use 0 to disable.",
|
| 69 |
+
)
|
| 70 |
+
parser.add_argument(
|
| 71 |
+
"--max-new-tokens",
|
| 72 |
+
type=int,
|
| 73 |
+
default=512,
|
| 74 |
+
help="Max new tokens for the model response.",
|
| 75 |
+
)
|
| 76 |
+
parser.add_argument(
|
| 77 |
+
"--device-map",
|
| 78 |
+
default="auto",
|
| 79 |
+
help="Transformers device_map argument.",
|
| 80 |
+
)
|
| 81 |
+
parser.add_argument(
|
| 82 |
+
"--dtype",
|
| 83 |
+
default="bfloat16",
|
| 84 |
+
choices=["auto", "float16", "bfloat16", "float32"],
|
| 85 |
+
help="Torch dtype for model loading.",
|
| 86 |
+
)
|
| 87 |
+
parser.add_argument(
|
| 88 |
+
"--attn-implementation",
|
| 89 |
+
default="",
|
| 90 |
+
help='Optional attn_implementation, e.g. "flash_attention_2". Empty disables it.',
|
| 91 |
+
)
|
| 92 |
+
parser.add_argument(
|
| 93 |
+
"--temperature",
|
| 94 |
+
type=float,
|
| 95 |
+
default=0.0,
|
| 96 |
+
help="Sampling temperature. 0 uses greedy decoding.",
|
| 97 |
+
)
|
| 98 |
+
parser.set_defaults(trust_remote_code=True)
|
| 99 |
+
parser.add_argument(
|
| 100 |
+
"--no-trust-remote-code",
|
| 101 |
+
dest="trust_remote_code",
|
| 102 |
+
action="store_false",
|
| 103 |
+
help="Disable trust_remote_code for model and processor loading.",
|
| 104 |
+
)
|
| 105 |
+
return parser.parse_args()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def normalize_label(value: Any) -> str:
|
| 109 |
+
text = re.sub(r"\s+", " ", str(value or "")).strip()
|
| 110 |
+
if not text:
|
| 111 |
+
return "static"
|
| 112 |
+
lowered = text.lower()
|
| 113 |
+
if lowered in LABEL_ALIASES:
|
| 114 |
+
return LABEL_ALIASES[lowered]
|
| 115 |
+
return LABEL_MAP.get(lowered, "")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def extract_json_text(raw_text: str) -> str:
|
| 119 |
+
text = raw_text.strip()
|
| 120 |
+
fenced = re.findall(r"```(?:json)?\s*(.*?)```", text, flags=re.DOTALL | re.I)
|
| 121 |
+
candidates = [item.strip() for item in fenced if item.strip()]
|
| 122 |
+
candidates.append(text)
|
| 123 |
+
for candidate in candidates:
|
| 124 |
+
if candidate.startswith("{") and candidate.endswith("}"):
|
| 125 |
+
return candidate
|
| 126 |
+
|
| 127 |
+
start = text.find("{")
|
| 128 |
+
if start < 0:
|
| 129 |
+
raise ValueError(f"No JSON object found in model output: {text[:300]}")
|
| 130 |
+
|
| 131 |
+
depth = 0
|
| 132 |
+
in_string = False
|
| 133 |
+
escape = False
|
| 134 |
+
for index in range(start, len(text)):
|
| 135 |
+
char = text[index]
|
| 136 |
+
if in_string:
|
| 137 |
+
if escape:
|
| 138 |
+
escape = False
|
| 139 |
+
elif char == "\\":
|
| 140 |
+
escape = True
|
| 141 |
+
elif char == '"':
|
| 142 |
+
in_string = False
|
| 143 |
+
continue
|
| 144 |
+
if char == '"':
|
| 145 |
+
in_string = True
|
| 146 |
+
elif char == "{":
|
| 147 |
+
depth += 1
|
| 148 |
+
elif char == "}":
|
| 149 |
+
depth -= 1
|
| 150 |
+
if depth == 0:
|
| 151 |
+
return text[start : index + 1]
|
| 152 |
+
raise ValueError(f"Unclosed JSON object in model output: {text[:300]}")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def parse_json_payload(raw_text: str) -> dict[str, Any]:
|
| 156 |
+
json_text = extract_json_text(raw_text)
|
| 157 |
+
try:
|
| 158 |
+
payload = json.loads(json_text)
|
| 159 |
+
except json.JSONDecodeError:
|
| 160 |
+
payload = ast.literal_eval(json_text)
|
| 161 |
+
if not isinstance(payload, dict):
|
| 162 |
+
raise ValueError(f"Expected a JSON object, got {type(payload).__name__}.")
|
| 163 |
+
return payload
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def load_camera_motion_guide(path: Path) -> str:
|
| 167 |
+
if path.exists():
|
| 168 |
+
return path.read_text(encoding="utf-8").strip()
|
| 169 |
+
labels = "\n".join(f"- {label}" for label in CAMERA_MOTION_LABELS)
|
| 170 |
+
return f"Allowed labels:\n{labels}"
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def build_prompt(camera_motion_guide: str) -> str:
|
| 174 |
+
labels = ", ".join(CAMERA_MOTION_LABELS)
|
| 175 |
+
return f"""
|
| 176 |
+
You are classifying the dominant camera motion in a single video.
|
| 177 |
+
|
| 178 |
+
Camera motion guide:
|
| 179 |
+
{camera_motion_guide}
|
| 180 |
+
|
| 181 |
+
Allowed output labels:
|
| 182 |
+
{labels}
|
| 183 |
+
|
| 184 |
+
Rules:
|
| 185 |
+
- Return strict JSON only. Do not use markdown fences.
|
| 186 |
+
- Choose exactly one label.
|
| 187 |
+
- Use "static" if there is no clear camera motion or the apparent motion is mostly subject/object motion.
|
| 188 |
+
- Prefer rotation labels pan/tilt/roll when the camera pivots in place.
|
| 189 |
+
- Prefer translation labels dolly/truck/pedestal when the camera physically changes position.
|
| 190 |
+
- If multiple motions occur, choose the most visually dominant camera motion.
|
| 191 |
+
- The description must be one concise English sentence explaining the visual evidence.
|
| 192 |
+
|
| 193 |
+
Return JSON in exactly this schema:
|
| 194 |
+
{{
|
| 195 |
+
"label": "pan-left",
|
| 196 |
+
"description": "The camera pans left as the scene shifts horizontally across the frame."
|
| 197 |
+
}}
|
| 198 |
+
""".strip()
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class Qwen3VLRunner:
|
| 202 |
+
def __init__(
|
| 203 |
+
self,
|
| 204 |
+
model_path: str,
|
| 205 |
+
device_map: str,
|
| 206 |
+
dtype: str,
|
| 207 |
+
attn_implementation: str,
|
| 208 |
+
trust_remote_code: bool,
|
| 209 |
+
fps: float,
|
| 210 |
+
max_pixels: int,
|
| 211 |
+
temperature: float,
|
| 212 |
+
) -> None:
|
| 213 |
+
try:
|
| 214 |
+
import torch
|
| 215 |
+
from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
|
| 216 |
+
except ModuleNotFoundError as exc:
|
| 217 |
+
raise RuntimeError(
|
| 218 |
+
"Missing dependencies. Install torch, transformers, and preferably qwen-vl-utils."
|
| 219 |
+
) from exc
|
| 220 |
+
|
| 221 |
+
self.torch = torch
|
| 222 |
+
self.temperature = temperature
|
| 223 |
+
self.fps = fps if fps > 0 else None
|
| 224 |
+
self.max_pixels = max_pixels if max_pixels > 0 else None
|
| 225 |
+
|
| 226 |
+
try:
|
| 227 |
+
from qwen_vl_utils import process_vision_info # type: ignore
|
| 228 |
+
except ModuleNotFoundError:
|
| 229 |
+
process_vision_info = None
|
| 230 |
+
self.process_vision_info = process_vision_info
|
| 231 |
+
|
| 232 |
+
dtype_map = {
|
| 233 |
+
"auto": "auto",
|
| 234 |
+
"float16": torch.float16,
|
| 235 |
+
"bfloat16": torch.bfloat16,
|
| 236 |
+
"float32": torch.float32,
|
| 237 |
+
}
|
| 238 |
+
load_kwargs: dict[str, Any] = {
|
| 239 |
+
"device_map": device_map,
|
| 240 |
+
"torch_dtype": dtype_map[dtype],
|
| 241 |
+
"trust_remote_code": trust_remote_code,
|
| 242 |
+
}
|
| 243 |
+
if attn_implementation:
|
| 244 |
+
load_kwargs["attn_implementation"] = attn_implementation
|
| 245 |
+
|
| 246 |
+
self.model = Qwen3VLForConditionalGeneration.from_pretrained(
|
| 247 |
+
model_path,
|
| 248 |
+
**load_kwargs,
|
| 249 |
+
)
|
| 250 |
+
self.processor = AutoProcessor.from_pretrained(
|
| 251 |
+
model_path,
|
| 252 |
+
trust_remote_code=trust_remote_code,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
def _build_messages(self, video_path: Path, prompt: str) -> list[dict[str, Any]]:
|
| 256 |
+
video_item: dict[str, Any] = {
|
| 257 |
+
"type": "video",
|
| 258 |
+
"video": str(video_path.resolve()),
|
| 259 |
+
}
|
| 260 |
+
if self.fps is not None:
|
| 261 |
+
video_item["fps"] = self.fps
|
| 262 |
+
if self.max_pixels is not None:
|
| 263 |
+
video_item["max_pixels"] = self.max_pixels
|
| 264 |
+
return [
|
| 265 |
+
{
|
| 266 |
+
"role": "system",
|
| 267 |
+
"content": "You are a careful video annotation assistant. Return strict JSON only.",
|
| 268 |
+
},
|
| 269 |
+
{
|
| 270 |
+
"role": "user",
|
| 271 |
+
"content": [video_item, {"type": "text", "text": prompt}],
|
| 272 |
+
},
|
| 273 |
+
]
|
| 274 |
+
|
| 275 |
+
def _prepare_inputs(self, messages: list[dict[str, Any]]):
|
| 276 |
+
if self.process_vision_info is not None:
|
| 277 |
+
text = self.processor.apply_chat_template(
|
| 278 |
+
messages,
|
| 279 |
+
tokenize=False,
|
| 280 |
+
add_generation_prompt=True,
|
| 281 |
+
)
|
| 282 |
+
image_inputs, video_inputs = self.process_vision_info(messages)
|
| 283 |
+
inputs = self.processor(
|
| 284 |
+
text=[text],
|
| 285 |
+
images=image_inputs,
|
| 286 |
+
videos=video_inputs,
|
| 287 |
+
padding=True,
|
| 288 |
+
return_tensors="pt",
|
| 289 |
+
)
|
| 290 |
+
else:
|
| 291 |
+
try:
|
| 292 |
+
inputs = self.processor.apply_chat_template(
|
| 293 |
+
messages,
|
| 294 |
+
tokenize=True,
|
| 295 |
+
add_generation_prompt=True,
|
| 296 |
+
return_dict=True,
|
| 297 |
+
return_tensors="pt",
|
| 298 |
+
)
|
| 299 |
+
except Exception as exc:
|
| 300 |
+
raise RuntimeError(
|
| 301 |
+
"Failed to prepare video inputs. Install qwen-vl-utils or use a transformers build with Qwen3-VL video chat support."
|
| 302 |
+
) from exc
|
| 303 |
+
return inputs.to(self.model.device)
|
| 304 |
+
|
| 305 |
+
def classify(self, video_path: Path, prompt: str, max_new_tokens: int) -> dict[str, str]:
|
| 306 |
+
messages = self._build_messages(video_path, prompt)
|
| 307 |
+
inputs = self._prepare_inputs(messages)
|
| 308 |
+
generate_kwargs: dict[str, Any] = {"max_new_tokens": max_new_tokens}
|
| 309 |
+
if self.temperature and self.temperature > 0:
|
| 310 |
+
generate_kwargs.update({"do_sample": True, "temperature": self.temperature})
|
| 311 |
+
else:
|
| 312 |
+
generate_kwargs["do_sample"] = False
|
| 313 |
+
|
| 314 |
+
with self.torch.inference_mode():
|
| 315 |
+
generated_ids = self.model.generate(**inputs, **generate_kwargs)
|
| 316 |
+
generated_ids_trimmed = [
|
| 317 |
+
out_ids[len(in_ids) :]
|
| 318 |
+
for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 319 |
+
]
|
| 320 |
+
raw_text = self.processor.batch_decode(
|
| 321 |
+
generated_ids_trimmed,
|
| 322 |
+
skip_special_tokens=True,
|
| 323 |
+
clean_up_tokenization_spaces=False,
|
| 324 |
+
)[0]
|
| 325 |
+
payload = parse_json_payload(raw_text)
|
| 326 |
+
label = normalize_label(payload.get("label"))
|
| 327 |
+
if not label:
|
| 328 |
+
raise ValueError(
|
| 329 |
+
f"Model returned unsupported label {payload.get('label')!r}; allowed labels are {CAMERA_MOTION_LABELS}"
|
| 330 |
+
)
|
| 331 |
+
description = re.sub(r"\s+", " ", str(payload.get("description", ""))).strip()
|
| 332 |
+
if not description:
|
| 333 |
+
description = "The video does not provide enough clear evidence for a more specific camera motion."
|
| 334 |
+
return {"label": label, "description": description}
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def main() -> None:
|
| 338 |
+
args = parse_args()
|
| 339 |
+
video_path = Path(args.video).expanduser().resolve()
|
| 340 |
+
if not video_path.is_file():
|
| 341 |
+
raise FileNotFoundError(f"Video not found: {video_path}")
|
| 342 |
+
|
| 343 |
+
camera_guide = load_camera_motion_guide(
|
| 344 |
+
Path(args.camera_motion_guide).expanduser().resolve()
|
| 345 |
+
)
|
| 346 |
+
runner = Qwen3VLRunner(
|
| 347 |
+
model_path=args.model_path,
|
| 348 |
+
device_map=args.device_map,
|
| 349 |
+
dtype=args.dtype,
|
| 350 |
+
attn_implementation=args.attn_implementation,
|
| 351 |
+
trust_remote_code=args.trust_remote_code,
|
| 352 |
+
fps=args.fps,
|
| 353 |
+
max_pixels=args.max_pixels,
|
| 354 |
+
temperature=args.temperature,
|
| 355 |
+
)
|
| 356 |
+
result = runner.classify(
|
| 357 |
+
video_path=video_path,
|
| 358 |
+
prompt=build_prompt(camera_guide),
|
| 359 |
+
max_new_tokens=args.max_new_tokens,
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
output_text = json.dumps(result, ensure_ascii=False, indent=2) + "\n"
|
| 363 |
+
if args.output:
|
| 364 |
+
output_path = Path(args.output).expanduser().resolve()
|
| 365 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 366 |
+
output_path.write_text(output_text, encoding="utf-8")
|
| 367 |
+
else:
|
| 368 |
+
print(output_text, end="")
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
if __name__ == "__main__":
|
| 372 |
+
main()
|
qwen/generate_multi_event_annotations.py
ADDED
|
@@ -0,0 +1,2136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import ast
|
| 6 |
+
import json
|
| 7 |
+
import logging
|
| 8 |
+
import re
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
import tempfile
|
| 12 |
+
import textwrap
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any, Iterable
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
VIDEO_SUFFIXES = {".mp4", ".mov", ".m4v", ".avi", ".mkv", ".webm"}
|
| 19 |
+
SEGMENT_RE = re.compile(
|
| 20 |
+
r"^(?P<uuid>.+)-(?P<start>\d{2}\.\d{2}\.\d{2}\.\d{3})-(?P<end>\d{2}\.\d{2}\.\d{2}\.\d{3})-seg(?P<segid>\d+)\.(?P<ext>[A-Za-z0-9]+)$"
|
| 21 |
+
)
|
| 22 |
+
EVENT_CAMERA_LABELS = [
|
| 23 |
+
"dolly-in",
|
| 24 |
+
"dolly-out",
|
| 25 |
+
"pedestal-up",
|
| 26 |
+
"pedestal-down",
|
| 27 |
+
"truck-left",
|
| 28 |
+
"truck-right",
|
| 29 |
+
"pan-left",
|
| 30 |
+
"pan-right",
|
| 31 |
+
"tilt-up",
|
| 32 |
+
"tilt-down",
|
| 33 |
+
"roll-CW",
|
| 34 |
+
"roll-CCW",
|
| 35 |
+
]
|
| 36 |
+
EVENT_CAMERA_LABEL_MAP = {label.lower(): label for label in EVENT_CAMERA_LABELS}
|
| 37 |
+
SUBJECT_CATEGORIES = {"human", "animal", "body_part", "object", "unknown"}
|
| 38 |
+
GLOBAL_CAMERA_PREFIXES = {
|
| 39 |
+
"static",
|
| 40 |
+
"moving-throughout",
|
| 41 |
+
"intermittent",
|
| 42 |
+
"motion-changes",
|
| 43 |
+
"mixed",
|
| 44 |
+
"near-static",
|
| 45 |
+
}
|
| 46 |
+
GLOBAL_CAMERA_PREFIX_MAP = {prefix.lower(): prefix for prefix in GLOBAL_CAMERA_PREFIXES}
|
| 47 |
+
DEFAULT_ROOT = Path(__file__).resolve().parent
|
| 48 |
+
DEFAULT_CAMERA_GUIDE = DEFAULT_ROOT / "camera_motion.md"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@dataclass(frozen=True)
|
| 52 |
+
class SegmentInfo:
|
| 53 |
+
uuid: str
|
| 54 |
+
path: Path
|
| 55 |
+
start_time: float
|
| 56 |
+
end_time: float
|
| 57 |
+
duration: float
|
| 58 |
+
seg_id: int
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def parse_args() -> argparse.Namespace:
|
| 62 |
+
parser = argparse.ArgumentParser(
|
| 63 |
+
description="Generate multi-event annotations with a local Qwen3-VL checkpoint."
|
| 64 |
+
)
|
| 65 |
+
parser.add_argument(
|
| 66 |
+
"--input",
|
| 67 |
+
required=True,
|
| 68 |
+
help="Path to a directory of segmented videos or a single segmented video file.",
|
| 69 |
+
)
|
| 70 |
+
parser.add_argument(
|
| 71 |
+
"--output",
|
| 72 |
+
required=True,
|
| 73 |
+
help="Output JSON path.",
|
| 74 |
+
)
|
| 75 |
+
parser.add_argument(
|
| 76 |
+
"--model-path",
|
| 77 |
+
default=str(DEFAULT_ROOT / "checkpoints"),
|
| 78 |
+
help="Local Qwen3-VL checkpoint directory.",
|
| 79 |
+
)
|
| 80 |
+
parser.add_argument(
|
| 81 |
+
"--camera-motion-guide",
|
| 82 |
+
default=str(DEFAULT_CAMERA_GUIDE),
|
| 83 |
+
help="Path to camera_motion.md used to prime the prompts.",
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--recursive",
|
| 87 |
+
action="store_true",
|
| 88 |
+
help="Recursively search for segment videos when the input is a directory.",
|
| 89 |
+
)
|
| 90 |
+
parser.add_argument(
|
| 91 |
+
"--uuids",
|
| 92 |
+
nargs="*",
|
| 93 |
+
default=None,
|
| 94 |
+
help="Optional UUID allow-list.",
|
| 95 |
+
)
|
| 96 |
+
parser.add_argument(
|
| 97 |
+
"--uuids-file",
|
| 98 |
+
default=None,
|
| 99 |
+
help="Optional text file containing one UUID per line.",
|
| 100 |
+
)
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--limit",
|
| 103 |
+
type=int,
|
| 104 |
+
default=None,
|
| 105 |
+
help="Only process the first N UUIDs after sorting and filtering.",
|
| 106 |
+
)
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
"--num-shards",
|
| 109 |
+
type=int,
|
| 110 |
+
default=1,
|
| 111 |
+
help="Deterministically split the UUID list into N shards and only process one shard in this process.",
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument(
|
| 114 |
+
"--shard-index",
|
| 115 |
+
type=int,
|
| 116 |
+
default=0,
|
| 117 |
+
help="0-based shard index used together with --num-shards.",
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--print-uuids-json",
|
| 121 |
+
action="store_true",
|
| 122 |
+
help="Print the discovered UUID list as JSON and exit. Useful for external multi-GPU launchers.",
|
| 123 |
+
)
|
| 124 |
+
parser.add_argument(
|
| 125 |
+
"--overwrite",
|
| 126 |
+
action="store_true",
|
| 127 |
+
help="Overwrite an existing output JSON instead of failing.",
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument(
|
| 130 |
+
"--resume",
|
| 131 |
+
action="store_true",
|
| 132 |
+
help="Merge into an existing output JSON and skip UUIDs that are already present.",
|
| 133 |
+
)
|
| 134 |
+
parser.add_argument(
|
| 135 |
+
"--continue-on-error",
|
| 136 |
+
action="store_true",
|
| 137 |
+
help="Log UUID failures and continue instead of stopping immediately.",
|
| 138 |
+
)
|
| 139 |
+
parser.add_argument(
|
| 140 |
+
"--dry-run",
|
| 141 |
+
action="store_true",
|
| 142 |
+
help="Only validate file grouping and print the discovered UUIDs.",
|
| 143 |
+
)
|
| 144 |
+
parser.add_argument(
|
| 145 |
+
"--keep-temp",
|
| 146 |
+
action="store_true",
|
| 147 |
+
help="Keep temporary stitched videos for inspection.",
|
| 148 |
+
)
|
| 149 |
+
parser.add_argument(
|
| 150 |
+
"--temp-dir",
|
| 151 |
+
default=None,
|
| 152 |
+
help="Optional temp directory root for stitched videos.",
|
| 153 |
+
)
|
| 154 |
+
parser.add_argument(
|
| 155 |
+
"--video-suffixes",
|
| 156 |
+
default=",".join(sorted(VIDEO_SUFFIXES)),
|
| 157 |
+
help="Comma-separated video suffixes to include.",
|
| 158 |
+
)
|
| 159 |
+
parser.add_argument(
|
| 160 |
+
"--fps",
|
| 161 |
+
type=float,
|
| 162 |
+
default=1.0,
|
| 163 |
+
help="Sampling FPS passed to the Qwen video processor.",
|
| 164 |
+
)
|
| 165 |
+
parser.add_argument(
|
| 166 |
+
"--max-pixels",
|
| 167 |
+
type=int,
|
| 168 |
+
default=360000,
|
| 169 |
+
help="Optional max_pixels hint passed to the Qwen video processor.",
|
| 170 |
+
)
|
| 171 |
+
parser.add_argument(
|
| 172 |
+
"--context-max-new-tokens",
|
| 173 |
+
type=int,
|
| 174 |
+
default=1024,
|
| 175 |
+
help="Max new tokens for the global context pass.",
|
| 176 |
+
)
|
| 177 |
+
parser.add_argument(
|
| 178 |
+
"--event-max-new-tokens",
|
| 179 |
+
type=int,
|
| 180 |
+
default=1024,
|
| 181 |
+
help="Max new tokens for each event pass.",
|
| 182 |
+
)
|
| 183 |
+
parser.add_argument(
|
| 184 |
+
"--global-max-new-tokens",
|
| 185 |
+
type=int,
|
| 186 |
+
default=4096,
|
| 187 |
+
help="Max new tokens for the final global prompt pass.",
|
| 188 |
+
)
|
| 189 |
+
parser.add_argument(
|
| 190 |
+
"--temperature",
|
| 191 |
+
type=float,
|
| 192 |
+
default=0.2,
|
| 193 |
+
help="Sampling temperature.",
|
| 194 |
+
)
|
| 195 |
+
parser.add_argument(
|
| 196 |
+
"--top-p",
|
| 197 |
+
type=float,
|
| 198 |
+
default=0.9,
|
| 199 |
+
help="Sampling top-p.",
|
| 200 |
+
)
|
| 201 |
+
parser.add_argument(
|
| 202 |
+
"--top-k",
|
| 203 |
+
type=int,
|
| 204 |
+
default=20,
|
| 205 |
+
help="Sampling top-k.",
|
| 206 |
+
)
|
| 207 |
+
parser.add_argument(
|
| 208 |
+
"--repetition-penalty",
|
| 209 |
+
type=float,
|
| 210 |
+
default=1.05,
|
| 211 |
+
help="Generation repetition penalty.",
|
| 212 |
+
)
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--greedy",
|
| 215 |
+
action="store_true",
|
| 216 |
+
help="Disable sampling and use greedy decoding.",
|
| 217 |
+
)
|
| 218 |
+
parser.add_argument(
|
| 219 |
+
"--device-map",
|
| 220 |
+
default="auto",
|
| 221 |
+
help="Transformers device_map argument.",
|
| 222 |
+
)
|
| 223 |
+
parser.add_argument(
|
| 224 |
+
"--dtype",
|
| 225 |
+
default="bfloat16",
|
| 226 |
+
choices=["auto", "float16", "bfloat16", "float32"],
|
| 227 |
+
help="Torch dtype for model loading.",
|
| 228 |
+
)
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
"--attn-implementation",
|
| 231 |
+
default="flash_attention_2",
|
| 232 |
+
help="Optional attn_implementation passed to from_pretrained. Use an empty string to disable.",
|
| 233 |
+
)
|
| 234 |
+
parser.add_argument(
|
| 235 |
+
"--ffmpeg-bin",
|
| 236 |
+
default="ffmpeg",
|
| 237 |
+
help="ffmpeg executable used to stitch per-UUID segments.",
|
| 238 |
+
)
|
| 239 |
+
parser.add_argument(
|
| 240 |
+
"--log-level",
|
| 241 |
+
default="INFO",
|
| 242 |
+
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
|
| 243 |
+
help="Python log level.",
|
| 244 |
+
)
|
| 245 |
+
parser.set_defaults(trust_remote_code=True)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--no-trust-remote-code",
|
| 248 |
+
dest="trust_remote_code",
|
| 249 |
+
action="store_false",
|
| 250 |
+
help="Disable trust_remote_code when loading the model and processor.",
|
| 251 |
+
)
|
| 252 |
+
return parser.parse_args()
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def setup_logging(level: str) -> None:
|
| 256 |
+
logging.basicConfig(
|
| 257 |
+
level=getattr(logging, level),
|
| 258 |
+
format="%(asctime)s | %(levelname)s | %(message)s",
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def parse_video_suffixes(raw: str) -> set[str]:
|
| 263 |
+
suffixes: set[str] = set()
|
| 264 |
+
for item in raw.split(","):
|
| 265 |
+
token = item.strip().lower()
|
| 266 |
+
if not token:
|
| 267 |
+
continue
|
| 268 |
+
suffixes.add(token if token.startswith(".") else f".{token}")
|
| 269 |
+
return suffixes or set(VIDEO_SUFFIXES)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def timecode_to_seconds(value: str) -> float:
|
| 273 |
+
hours, minutes, seconds, millis = value.split(".")
|
| 274 |
+
total = (
|
| 275 |
+
int(hours) * 3600
|
| 276 |
+
+ int(minutes) * 60
|
| 277 |
+
+ int(seconds)
|
| 278 |
+
+ int(millis) / 1000.0
|
| 279 |
+
)
|
| 280 |
+
return round(total, 3)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def parse_segment_filename(path: Path) -> SegmentInfo:
|
| 284 |
+
match = SEGMENT_RE.match(path.name)
|
| 285 |
+
if not match:
|
| 286 |
+
raise ValueError(
|
| 287 |
+
f"Unsupported segment filename: {path.name}. Expected uuid-start-end-segN.ext."
|
| 288 |
+
)
|
| 289 |
+
start_time = timecode_to_seconds(match.group("start"))
|
| 290 |
+
end_time = timecode_to_seconds(match.group("end"))
|
| 291 |
+
duration = round(max(end_time - start_time, 0.0), 3)
|
| 292 |
+
return SegmentInfo(
|
| 293 |
+
uuid=match.group("uuid"),
|
| 294 |
+
path=path.resolve(),
|
| 295 |
+
start_time=start_time,
|
| 296 |
+
end_time=end_time,
|
| 297 |
+
duration=duration,
|
| 298 |
+
seg_id=int(match.group("segid")),
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def discover_segment_files(
|
| 303 |
+
input_path: Path,
|
| 304 |
+
recursive: bool,
|
| 305 |
+
suffixes: set[str],
|
| 306 |
+
) -> list[Path]:
|
| 307 |
+
if input_path.is_file():
|
| 308 |
+
return [input_path.resolve()]
|
| 309 |
+
if not input_path.is_dir():
|
| 310 |
+
raise FileNotFoundError(f"Input path does not exist: {input_path}")
|
| 311 |
+
iterator = input_path.rglob("*") if recursive else input_path.iterdir()
|
| 312 |
+
return sorted(
|
| 313 |
+
path.resolve()
|
| 314 |
+
for path in iterator
|
| 315 |
+
if path.is_file() and path.suffix.lower() in suffixes
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def collect_segment_groups(
|
| 320 |
+
input_path: Path,
|
| 321 |
+
recursive: bool,
|
| 322 |
+
suffixes: set[str],
|
| 323 |
+
allow_uuids: set[str] | None,
|
| 324 |
+
) -> dict[str, list[SegmentInfo]]:
|
| 325 |
+
groups: dict[str, list[SegmentInfo]] = {}
|
| 326 |
+
skipped = 0
|
| 327 |
+
for path in discover_segment_files(input_path, recursive, suffixes):
|
| 328 |
+
try:
|
| 329 |
+
segment = parse_segment_filename(path)
|
| 330 |
+
except ValueError as exc:
|
| 331 |
+
logging.warning("%s", exc)
|
| 332 |
+
skipped += 1
|
| 333 |
+
continue
|
| 334 |
+
if allow_uuids and segment.uuid not in allow_uuids:
|
| 335 |
+
continue
|
| 336 |
+
groups.setdefault(segment.uuid, []).append(segment)
|
| 337 |
+
for uuid, segments in groups.items():
|
| 338 |
+
groups[uuid] = sorted(
|
| 339 |
+
segments,
|
| 340 |
+
key=lambda item: (item.start_time, item.seg_id, item.path.name),
|
| 341 |
+
)
|
| 342 |
+
if skipped:
|
| 343 |
+
logging.info("Skipped %d non-matching files.", skipped)
|
| 344 |
+
return dict(sorted(groups.items(), key=lambda item: item[0]))
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def load_camera_motion_guide(path: Path) -> str:
|
| 348 |
+
if path.exists():
|
| 349 |
+
return path.read_text(encoding="utf-8").strip()
|
| 350 |
+
fallback_lines = [
|
| 351 |
+
"# Camera Motion Labels",
|
| 352 |
+
"",
|
| 353 |
+
"| Camera Motion Label | Explanation |",
|
| 354 |
+
"|---|---|",
|
| 355 |
+
]
|
| 356 |
+
explanations = {
|
| 357 |
+
"dolly-in": "The camera moves forward relative to the ground plane and the initial frame.",
|
| 358 |
+
"dolly-out": "The camera moves backward relative to the ground plane and the initial frame.",
|
| 359 |
+
"pedestal-up": "Select this when the camera moves upward clearly and consistently relative to the ground or the orientation of the initial frame.",
|
| 360 |
+
"pedestal-down": "Select this when the camera moves downward clearly and consistently relative to the ground or the orientation of the initial frame.",
|
| 361 |
+
"truck-left": "The camera physically moves to the left, changing its position relative to the initial frame.",
|
| 362 |
+
"truck-right": "The camera physically moves to the right, changing its position relative to the initial frame.",
|
| 363 |
+
"pan-left": "The camera rotates its angle by pivoting left with respect to the initial frame.",
|
| 364 |
+
"pan-right": "The camera rotates its angle by pivoting right with respect to the initial frame.",
|
| 365 |
+
"tilt-up": "The camera rotates its angle upward vertically with respect to the initial frame.",
|
| 366 |
+
"tilt-down": "The camera rotates its angle downward vertically with respect to the initial frame.",
|
| 367 |
+
"roll-CW": "The camera performs a clear and consistent clockwise roll by rotating around its own optical center.",
|
| 368 |
+
"roll-CCW": "The camera performs a clear and consistent counterclockwise roll by rotating around its own optical center.",
|
| 369 |
+
}
|
| 370 |
+
for label in EVENT_CAMERA_LABELS:
|
| 371 |
+
fallback_lines.append(f"| `{label}` | {explanations[label]} |")
|
| 372 |
+
return "\n".join(fallback_lines)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def apply_uuid_shard(uuids: list[str], num_shards: int, shard_index: int) -> list[str]:
|
| 376 |
+
if num_shards < 1:
|
| 377 |
+
raise ValueError(f"--num-shards must be >= 1, got {num_shards}")
|
| 378 |
+
if shard_index < 0 or shard_index >= num_shards:
|
| 379 |
+
raise ValueError(
|
| 380 |
+
f"--shard-index must be in [0, {num_shards - 1}], got {shard_index}"
|
| 381 |
+
)
|
| 382 |
+
if num_shards == 1:
|
| 383 |
+
return list(uuids)
|
| 384 |
+
return [uuid for idx, uuid in enumerate(uuids) if idx % num_shards == shard_index]
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def load_uuid_allow_list(raw_uuids: list[str] | None, uuids_file: str | None) -> set[str] | None:
|
| 388 |
+
values: list[str] = []
|
| 389 |
+
if raw_uuids:
|
| 390 |
+
values.extend(raw_uuids)
|
| 391 |
+
if uuids_file:
|
| 392 |
+
path = Path(uuids_file).expanduser().resolve()
|
| 393 |
+
for line in path.read_text(encoding="utf-8").splitlines():
|
| 394 |
+
token = line.strip()
|
| 395 |
+
if token:
|
| 396 |
+
values.append(token)
|
| 397 |
+
if not values:
|
| 398 |
+
return None
|
| 399 |
+
return set(values)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def normalize_whitespace(value: Any) -> str:
|
| 403 |
+
if value is None:
|
| 404 |
+
return ""
|
| 405 |
+
return re.sub(r"\s+", " ", str(value)).strip()
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def normalize_subject_category(value: Any) -> str:
|
| 409 |
+
category = normalize_whitespace(value).lower().replace("-", "_").replace(" ", "_")
|
| 410 |
+
if category in SUBJECT_CATEGORIES:
|
| 411 |
+
return category
|
| 412 |
+
return "unknown"
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def coerce_bool(value: Any, default: bool = False) -> bool:
|
| 416 |
+
if value is None:
|
| 417 |
+
return default
|
| 418 |
+
if isinstance(value, bool):
|
| 419 |
+
return value
|
| 420 |
+
if isinstance(value, (int, float)):
|
| 421 |
+
return bool(value)
|
| 422 |
+
if isinstance(value, str):
|
| 423 |
+
lowered = value.strip().lower()
|
| 424 |
+
if lowered in {"true", "yes", "y", "1"}:
|
| 425 |
+
return True
|
| 426 |
+
if lowered in {"false", "no", "n", "0"}:
|
| 427 |
+
return False
|
| 428 |
+
return default
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def coerce_optional_bool(value: Any) -> bool | None:
|
| 432 |
+
if value is None:
|
| 433 |
+
return None
|
| 434 |
+
if isinstance(value, str) and value.strip().lower() in {"none", "null", ""}:
|
| 435 |
+
return None
|
| 436 |
+
return coerce_bool(value)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def normalize_camera_motion_label(value: Any) -> str:
|
| 440 |
+
label = normalize_whitespace(value)
|
| 441 |
+
if not label:
|
| 442 |
+
return ""
|
| 443 |
+
lowered = label.lower()
|
| 444 |
+
if lowered in {"static", "none", "no-motion", "no motion", "n/a", "na"}:
|
| 445 |
+
return ""
|
| 446 |
+
return EVENT_CAMERA_LABEL_MAP.get(lowered, "")
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def normalize_global_camera_prefix(value: Any) -> str:
|
| 450 |
+
prefix = normalize_whitespace(value)
|
| 451 |
+
if not prefix:
|
| 452 |
+
return ""
|
| 453 |
+
lowered = prefix.lower()
|
| 454 |
+
if lowered in GLOBAL_CAMERA_PREFIX_MAP:
|
| 455 |
+
return GLOBAL_CAMERA_PREFIX_MAP[lowered]
|
| 456 |
+
return ""
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def word_count(text: str) -> int:
|
| 460 |
+
if not text:
|
| 461 |
+
return 0
|
| 462 |
+
return len(re.findall(r"\b\S+\b", text))
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def normalize_camera_motion_surface_text(value: Any) -> str:
|
| 466 |
+
cleaned = normalize_whitespace(value)
|
| 467 |
+
if not cleaned:
|
| 468 |
+
return ""
|
| 469 |
+
cleaned = re.sub(r"\bdollys\b", "dollies", cleaned, flags=re.IGNORECASE)
|
| 470 |
+
cleaned = re.sub(r"\bdolly-ins\b", "dollies in", cleaned, flags=re.IGNORECASE)
|
| 471 |
+
cleaned = re.sub(r"\bdolly-outs\b", "dollies out", cleaned, flags=re.IGNORECASE)
|
| 472 |
+
cleaned = re.sub(
|
| 473 |
+
r"\b(as|while|when)\s+(the camera|camera|it)\s+dolly[\s-]*(in|out)\b",
|
| 474 |
+
lambda match: f"{match.group(1)} {match.group(2)} dollies {match.group(3).lower()}",
|
| 475 |
+
cleaned,
|
| 476 |
+
flags=re.IGNORECASE,
|
| 477 |
+
)
|
| 478 |
+
cleaned = re.sub(
|
| 479 |
+
r"\b(the camera|camera|it)\s+dolly[\s-]*(in|out)\b",
|
| 480 |
+
lambda match: f"{match.group(1)} dollies {match.group(2).lower()}",
|
| 481 |
+
cleaned,
|
| 482 |
+
flags=re.IGNORECASE,
|
| 483 |
+
)
|
| 484 |
+
return cleaned
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def describe_camera_motion(label: str, scope: str = "event") -> str:
|
| 488 |
+
fragments = {
|
| 489 |
+
"dolly-in": "dollies in",
|
| 490 |
+
"dolly-out": "dollies out",
|
| 491 |
+
"pedestal-up": "pedestals up",
|
| 492 |
+
"pedestal-down": "pedestals down",
|
| 493 |
+
"truck-left": "trucks left",
|
| 494 |
+
"truck-right": "trucks right",
|
| 495 |
+
"pan-left": "pans left",
|
| 496 |
+
"pan-right": "pans right",
|
| 497 |
+
"tilt-up": "tilts up",
|
| 498 |
+
"tilt-down": "tilts down",
|
| 499 |
+
"roll-CW": "rolls clockwise",
|
| 500 |
+
"roll-CCW": "rolls counterclockwise",
|
| 501 |
+
}
|
| 502 |
+
if label not in fragments:
|
| 503 |
+
return ""
|
| 504 |
+
if scope == "global":
|
| 505 |
+
return f"The camera {fragments[label]} through most of the video."
|
| 506 |
+
return f"The camera {fragments[label]}."
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def is_following_camera_description(text: str) -> bool:
|
| 510 |
+
lowered = normalize_whitespace(text).lower()
|
| 511 |
+
if not lowered:
|
| 512 |
+
return False
|
| 513 |
+
keywords = ("follow", "follows", "following", "track", "tracking", "tracked", "keeps pace")
|
| 514 |
+
return any(keyword in lowered for keyword in keywords)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def camera_motion_fragment(label: str) -> str:
|
| 518 |
+
sentence = describe_camera_motion(label)
|
| 519 |
+
if not sentence:
|
| 520 |
+
return ""
|
| 521 |
+
fragment = sentence.removeprefix("The camera ").strip()
|
| 522 |
+
return fragment[:-1] if fragment.endswith(".") else fragment
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def derive_global_camera_from_events(
|
| 526 |
+
events: list[dict[str, Any]],
|
| 527 |
+
) -> tuple[str, str, str]:
|
| 528 |
+
sequence_description = summarize_global_camera_sequence(events)
|
| 529 |
+
moving_events = [event for event in events if coerce_bool(event.get("has_camera_motion"))]
|
| 530 |
+
labels = [event.get("camera_motion_label", "") for event in moving_events if event.get("camera_motion_label")]
|
| 531 |
+
unlabeled_descs = [
|
| 532 |
+
normalize_whitespace(event.get("camera_motion_desc"))
|
| 533 |
+
for event in moving_events
|
| 534 |
+
if not event.get("camera_motion_label") and normalize_whitespace(event.get("camera_motion_desc"))
|
| 535 |
+
]
|
| 536 |
+
if not moving_events:
|
| 537 |
+
return (
|
| 538 |
+
"static",
|
| 539 |
+
"",
|
| 540 |
+
sequence_description,
|
| 541 |
+
)
|
| 542 |
+
if len(moving_events) == len(events):
|
| 543 |
+
unique_labels = {label for label in labels if label}
|
| 544 |
+
if len(unique_labels) == 1:
|
| 545 |
+
label = next(iter(unique_labels))
|
| 546 |
+
return ("moving-throughout", label, sequence_description)
|
| 547 |
+
if unlabeled_descs and all(is_following_camera_description(desc) for desc in unlabeled_descs):
|
| 548 |
+
return (
|
| 549 |
+
"moving-throughout",
|
| 550 |
+
"",
|
| 551 |
+
sequence_description,
|
| 552 |
+
)
|
| 553 |
+
return (
|
| 554 |
+
"motion-changes",
|
| 555 |
+
"",
|
| 556 |
+
sequence_description,
|
| 557 |
+
)
|
| 558 |
+
unique_labels = {label for label in labels if label}
|
| 559 |
+
if len(unique_labels) == 1:
|
| 560 |
+
label = next(iter(unique_labels))
|
| 561 |
+
return (
|
| 562 |
+
"intermittent",
|
| 563 |
+
label,
|
| 564 |
+
sequence_description,
|
| 565 |
+
)
|
| 566 |
+
if unlabeled_descs and all(is_following_camera_description(desc) for desc in unlabeled_descs):
|
| 567 |
+
return (
|
| 568 |
+
"intermittent",
|
| 569 |
+
"",
|
| 570 |
+
sequence_description,
|
| 571 |
+
)
|
| 572 |
+
return (
|
| 573 |
+
"motion-changes",
|
| 574 |
+
"",
|
| 575 |
+
sequence_description,
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def global_camera_conflicts_with_events(
|
| 580 |
+
prefix: str,
|
| 581 |
+
label: str,
|
| 582 |
+
events: list[dict[str, Any]],
|
| 583 |
+
) -> bool:
|
| 584 |
+
moving_events = [event for event in events if coerce_bool(event.get("has_camera_motion"))]
|
| 585 |
+
total_events = len(events)
|
| 586 |
+
labeled_events = [event for event in moving_events if event.get("camera_motion_label")]
|
| 587 |
+
unique_labels = {event.get("camera_motion_label", "") for event in labeled_events if event.get("camera_motion_label")}
|
| 588 |
+
|
| 589 |
+
if prefix in {"static", "near-static"}:
|
| 590 |
+
return bool(moving_events)
|
| 591 |
+
|
| 592 |
+
if prefix == "moving-throughout":
|
| 593 |
+
if total_events == 0 or len(moving_events) != total_events:
|
| 594 |
+
return True
|
| 595 |
+
if label and unique_labels and unique_labels != {label}:
|
| 596 |
+
return True
|
| 597 |
+
return False
|
| 598 |
+
|
| 599 |
+
if prefix == "intermittent":
|
| 600 |
+
if total_events == 0 or len(moving_events) == 0 or len(moving_events) == total_events:
|
| 601 |
+
return True
|
| 602 |
+
if label and unique_labels and label not in unique_labels:
|
| 603 |
+
return True
|
| 604 |
+
return False
|
| 605 |
+
|
| 606 |
+
if prefix == "motion-changes":
|
| 607 |
+
return not moving_events
|
| 608 |
+
|
| 609 |
+
if prefix in {"mixed"}:
|
| 610 |
+
return not moving_events
|
| 611 |
+
|
| 612 |
+
return False
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def camera_motion_description_to_phrase(text: str) -> str:
|
| 616 |
+
sentence = normalize_whitespace(text).rstrip(".")
|
| 617 |
+
if not sentence:
|
| 618 |
+
return ""
|
| 619 |
+
lowered = sentence.lower()
|
| 620 |
+
for prefix in ("the camera ", "camera "):
|
| 621 |
+
if lowered.startswith(prefix):
|
| 622 |
+
sentence = sentence[len(prefix):]
|
| 623 |
+
break
|
| 624 |
+
return sentence_to_clause(sentence)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def event_camera_phase(event: dict[str, Any]) -> tuple[str, str]:
|
| 628 |
+
if not coerce_bool(event.get("has_camera_motion")):
|
| 629 |
+
return ("static", "the camera holds a static framing")
|
| 630 |
+
label = normalize_camera_motion_label(event.get("camera_motion_label"))
|
| 631 |
+
if label:
|
| 632 |
+
return (label, f"the camera {camera_motion_fragment(label)}")
|
| 633 |
+
description = normalize_whitespace(event.get("camera_motion_desc"))
|
| 634 |
+
if is_following_camera_description(description):
|
| 635 |
+
return (
|
| 636 |
+
"following",
|
| 637 |
+
"the camera remains relatively stable in framing while following the subject",
|
| 638 |
+
)
|
| 639 |
+
if description:
|
| 640 |
+
phrase = camera_motion_description_to_phrase(description)
|
| 641 |
+
if phrase.startswith("the "):
|
| 642 |
+
return (f"desc:{normalized_caption_key(description)}", phrase)
|
| 643 |
+
return (f"desc:{normalized_caption_key(description)}", f"the camera {phrase}")
|
| 644 |
+
return ("moving", "the camera moves relative to the scene")
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def summarize_global_camera_sequence(events: list[dict[str, Any]]) -> str:
|
| 648 |
+
if not events:
|
| 649 |
+
return "The camera remains static or near-static throughout the video."
|
| 650 |
+
|
| 651 |
+
phases: list[tuple[str, str]] = []
|
| 652 |
+
for event in events:
|
| 653 |
+
key, phrase = event_camera_phase(event)
|
| 654 |
+
if phases and phases[-1][0] == key:
|
| 655 |
+
continue
|
| 656 |
+
phases.append((key, phrase))
|
| 657 |
+
|
| 658 |
+
if not phases:
|
| 659 |
+
return "The camera remains static or near-static throughout the video."
|
| 660 |
+
|
| 661 |
+
if len(phases) == 1:
|
| 662 |
+
key, phrase = phases[0]
|
| 663 |
+
if key == "static":
|
| 664 |
+
return "The camera remains static or near-static throughout the video."
|
| 665 |
+
return f"{phrase[0].upper() + phrase[1:]} throughout the video."
|
| 666 |
+
|
| 667 |
+
clauses = [phrase for _, phrase in phases[:4]]
|
| 668 |
+
if len(phases) == 2:
|
| 669 |
+
return f"{clauses[0][0].upper() + clauses[0][1:]} at first, then {clauses[1]}."
|
| 670 |
+
if len(phases) == 3:
|
| 671 |
+
return f"{clauses[0][0].upper() + clauses[0][1:]} at first, then {clauses[1]}, and later {clauses[2]}."
|
| 672 |
+
return (
|
| 673 |
+
f"{clauses[0][0].upper() + clauses[0][1:]} at first, then {clauses[1]}, "
|
| 674 |
+
f"later {clauses[2]}, and eventually {clauses[3]}."
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def compose_global_camera_movement(prefix: str, label: str, description: str) -> str:
|
| 679 |
+
cleaned = normalize_camera_motion_surface_text(description)
|
| 680 |
+
if "|" in cleaned:
|
| 681 |
+
parts = [normalize_whitespace(part) for part in cleaned.split("|") if normalize_whitespace(part)]
|
| 682 |
+
filtered = [
|
| 683 |
+
part
|
| 684 |
+
for part in parts
|
| 685 |
+
if not normalize_global_camera_prefix(part) and not normalize_camera_motion_label(part)
|
| 686 |
+
]
|
| 687 |
+
cleaned = " ".join(filtered) if filtered else " ".join(parts)
|
| 688 |
+
if cleaned:
|
| 689 |
+
return cleaned
|
| 690 |
+
if prefix in {"static", "near-static"}:
|
| 691 |
+
return "The camera remains static or near-static throughout the video."
|
| 692 |
+
if label:
|
| 693 |
+
return describe_camera_motion(label, scope="global")
|
| 694 |
+
if prefix == "moving-throughout":
|
| 695 |
+
return "The camera keeps moving throughout the video."
|
| 696 |
+
if prefix == "intermittent":
|
| 697 |
+
return "The camera alternates between static framing and periods of movement."
|
| 698 |
+
if prefix == "motion-changes":
|
| 699 |
+
return "The camera motion changes across the video."
|
| 700 |
+
return "The camera behavior remains visually consistent across the video."
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
def normalize_camera_movement_description_output(value: Any) -> str:
|
| 704 |
+
cleaned = normalize_camera_motion_surface_text(value)
|
| 705 |
+
if not cleaned:
|
| 706 |
+
return ""
|
| 707 |
+
if "|" in cleaned:
|
| 708 |
+
parts = [normalize_whitespace(part) for part in cleaned.split("|") if normalize_whitespace(part)]
|
| 709 |
+
non_meta = [
|
| 710 |
+
part
|
| 711 |
+
for part in parts
|
| 712 |
+
if not normalize_global_camera_prefix(part) and not normalize_camera_motion_label(part)
|
| 713 |
+
]
|
| 714 |
+
cleaned = " ".join(non_meta) if non_meta else ""
|
| 715 |
+
if normalize_global_camera_prefix(cleaned) or normalize_camera_motion_label(cleaned):
|
| 716 |
+
return ""
|
| 717 |
+
return cleaned
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
def fallback_subject_profile(subject_registry: list[dict[str, str]]) -> str:
|
| 721 |
+
if not subject_registry:
|
| 722 |
+
return ""
|
| 723 |
+
if len(subject_registry) == 1:
|
| 724 |
+
subject = subject_registry[0]
|
| 725 |
+
term = subject.get("term", "subject")
|
| 726 |
+
profile = subject.get("profile", "")
|
| 727 |
+
category = subject.get("category", "unknown")
|
| 728 |
+
if category == "animal":
|
| 729 |
+
prefix = f"A {term} is the main subject of the video, and no human is visibly established."
|
| 730 |
+
elif category in {"body_part", "object"}:
|
| 731 |
+
prefix = f"A {term} is the main visible subject of the video, and no full human subject is clearly established."
|
| 732 |
+
else:
|
| 733 |
+
prefix = f"A {term} is the main subject of the video."
|
| 734 |
+
if profile:
|
| 735 |
+
return f"{prefix} {profile}"
|
| 736 |
+
return prefix
|
| 737 |
+
chunks = []
|
| 738 |
+
for subject in subject_registry:
|
| 739 |
+
term = subject.get("term", "subject")
|
| 740 |
+
profile = subject.get("profile", "")
|
| 741 |
+
category = subject.get("category", "unknown")
|
| 742 |
+
prefix = f"{term} ({category})" if category != "unknown" else term
|
| 743 |
+
chunks.append(f"{prefix}: {profile}" if profile else prefix)
|
| 744 |
+
return "Multiple recurring subjects appear across the video. " + "; ".join(chunks)
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
def normalize_focus_object(value: Any, subject_registry: list[dict[str, str]]) -> str:
|
| 748 |
+
focus = normalize_whitespace(value)
|
| 749 |
+
if focus:
|
| 750 |
+
return focus
|
| 751 |
+
if subject_registry:
|
| 752 |
+
return subject_registry[0].get("term", "main subject")
|
| 753 |
+
return "main subject"
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def normalized_caption_key(text: str) -> str:
|
| 757 |
+
lowered = normalize_whitespace(text).lower()
|
| 758 |
+
return re.sub(r"[^a-z0-9]+", " ", lowered).strip()
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
def sentence_to_clause(text: str) -> str:
|
| 762 |
+
sentence = normalize_whitespace(text).rstrip(".")
|
| 763 |
+
if not sentence:
|
| 764 |
+
return ""
|
| 765 |
+
if sentence[0].isupper():
|
| 766 |
+
return sentence[0].lower() + sentence[1:]
|
| 767 |
+
return sentence
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
def join_clauses(clauses: list[str]) -> str:
|
| 771 |
+
items = [item.strip() for item in clauses if item and item.strip()]
|
| 772 |
+
if not items:
|
| 773 |
+
return ""
|
| 774 |
+
if len(items) == 1:
|
| 775 |
+
return items[0]
|
| 776 |
+
if len(items) == 2:
|
| 777 |
+
return f"{items[0]} and {items[1]}"
|
| 778 |
+
return f"{', '.join(items[:-1])}, and {items[-1]}"
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
def disambiguate_repeated_caption(
|
| 782 |
+
current_caption: str,
|
| 783 |
+
previous_caption: str,
|
| 784 |
+
event: dict[str, Any],
|
| 785 |
+
) -> str:
|
| 786 |
+
if normalized_caption_key(current_caption) != normalized_caption_key(previous_caption):
|
| 787 |
+
return current_caption
|
| 788 |
+
additions = []
|
| 789 |
+
if event.get("has_appearance"):
|
| 790 |
+
additions.append("with a new subject entering view")
|
| 791 |
+
if event.get("has_disappearance"):
|
| 792 |
+
additions.append("with a subject leaving view")
|
| 793 |
+
if event.get("focus_object"):
|
| 794 |
+
additions.append(f"with attention settling on the {event['focus_object']}")
|
| 795 |
+
if event.get("camera_motion_desc"):
|
| 796 |
+
additions.append(f"as {sentence_to_clause(event['camera_motion_desc'])}")
|
| 797 |
+
if event.get("has_lighting_change"):
|
| 798 |
+
additions.append("under a noticeable lighting shift")
|
| 799 |
+
if event.get("has_environmental_change") and event.get("focus_object"):
|
| 800 |
+
additions.append(f"with further visible change around the {event['focus_object']}")
|
| 801 |
+
elif event.get("has_environmental_change"):
|
| 802 |
+
additions.append("with further visible change in the scene detail")
|
| 803 |
+
if not additions:
|
| 804 |
+
additions.append("with a subtle visible shift from the previous segment")
|
| 805 |
+
base = current_caption.rstrip().rstrip(".")
|
| 806 |
+
return f"{base}, {join_clauses(additions)}."
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def extract_json_text(raw_text: str) -> str:
|
| 810 |
+
text = raw_text.strip()
|
| 811 |
+
fenced_matches = re.findall(r"```(?:json)?\s*(.*?)```", text, flags=re.DOTALL | re.IGNORECASE)
|
| 812 |
+
candidates = [match.strip() for match in fenced_matches if match.strip()]
|
| 813 |
+
candidates.append(text)
|
| 814 |
+
for candidate in candidates:
|
| 815 |
+
if candidate.startswith("{") or candidate.startswith("["):
|
| 816 |
+
return candidate
|
| 817 |
+
for open_char, close_char in (("{", "}"), ("[", "]")):
|
| 818 |
+
start = text.find(open_char)
|
| 819 |
+
if start == -1:
|
| 820 |
+
continue
|
| 821 |
+
depth = 0
|
| 822 |
+
in_string = False
|
| 823 |
+
escape = False
|
| 824 |
+
for index in range(start, len(text)):
|
| 825 |
+
char = text[index]
|
| 826 |
+
if in_string:
|
| 827 |
+
if escape:
|
| 828 |
+
escape = False
|
| 829 |
+
elif char == "\\":
|
| 830 |
+
escape = True
|
| 831 |
+
elif char == '"':
|
| 832 |
+
in_string = False
|
| 833 |
+
continue
|
| 834 |
+
if char == '"':
|
| 835 |
+
in_string = True
|
| 836 |
+
continue
|
| 837 |
+
if char == open_char:
|
| 838 |
+
depth += 1
|
| 839 |
+
elif char == close_char:
|
| 840 |
+
depth -= 1
|
| 841 |
+
if depth == 0:
|
| 842 |
+
return text[start : index + 1]
|
| 843 |
+
raise ValueError("Failed to extract a JSON object from the model response.")
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def parse_json_payload(raw_text: str) -> dict[str, Any]:
|
| 847 |
+
json_text = extract_json_text(raw_text)
|
| 848 |
+
try:
|
| 849 |
+
payload = json.loads(json_text)
|
| 850 |
+
except json.JSONDecodeError:
|
| 851 |
+
try:
|
| 852 |
+
payload = ast.literal_eval(json_text)
|
| 853 |
+
except (SyntaxError, ValueError) as exc:
|
| 854 |
+
snippet = raw_text.strip().replace("\n", " ")[:500]
|
| 855 |
+
raise ValueError(f"Model output is not valid JSON: {snippet}") from exc
|
| 856 |
+
if not isinstance(payload, dict):
|
| 857 |
+
raise ValueError(f"Expected a JSON object, got {type(payload).__name__}.")
|
| 858 |
+
return payload
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
def load_existing_output(
|
| 862 |
+
output_path: Path,
|
| 863 |
+
overwrite: bool,
|
| 864 |
+
resume: bool,
|
| 865 |
+
) -> dict[str, dict[str, Any]]:
|
| 866 |
+
if not output_path.exists():
|
| 867 |
+
return {}
|
| 868 |
+
if overwrite:
|
| 869 |
+
return {}
|
| 870 |
+
if not resume:
|
| 871 |
+
raise FileExistsError(
|
| 872 |
+
f"Output already exists: {output_path}. Use --overwrite or --resume."
|
| 873 |
+
)
|
| 874 |
+
payload = json.loads(output_path.read_text(encoding="utf-8"))
|
| 875 |
+
videos = payload.get("videos", [])
|
| 876 |
+
if not isinstance(videos, list):
|
| 877 |
+
raise ValueError(f"Existing output has no valid videos list: {output_path}")
|
| 878 |
+
return {
|
| 879 |
+
item["uuid"]: item
|
| 880 |
+
for item in videos
|
| 881 |
+
if isinstance(item, dict) and "uuid" in item
|
| 882 |
+
}
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
def write_output(output_path: Path, videos_by_uuid: dict[str, dict[str, Any]]) -> None:
|
| 886 |
+
ordered_videos = [videos_by_uuid[uuid] for uuid in sorted(videos_by_uuid)]
|
| 887 |
+
payload = {
|
| 888 |
+
"total_videos": len(ordered_videos),
|
| 889 |
+
"videos": ordered_videos,
|
| 890 |
+
}
|
| 891 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 892 |
+
output_path.write_text(
|
| 893 |
+
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
|
| 894 |
+
encoding="utf-8",
|
| 895 |
+
)
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def format_subject_registry(subject_registry: list[dict[str, str]]) -> str:
|
| 899 |
+
if not subject_registry:
|
| 900 |
+
return "[]"
|
| 901 |
+
return json.dumps(subject_registry, ensure_ascii=False, indent=2)
|
| 902 |
+
|
| 903 |
+
|
| 904 |
+
def build_global_context_prompt(
|
| 905 |
+
uuid: str,
|
| 906 |
+
total_events: int,
|
| 907 |
+
camera_motion_guide: str,
|
| 908 |
+
) -> str:
|
| 909 |
+
return textwrap.dedent(
|
| 910 |
+
f"""
|
| 911 |
+
You are annotating a stitched multi-event video composed of {total_events} chronologically ordered event clips from the same original video.
|
| 912 |
+
|
| 913 |
+
UUID: {uuid}
|
| 914 |
+
|
| 915 |
+
Return strict JSON only. Do not use markdown fences. Use double-quoted JSON strings and JSON booleans/null.
|
| 916 |
+
|
| 917 |
+
Goals:
|
| 918 |
+
1. Identify whether the content is sports footage. Sports videos are the only exception to the "adjacent event captions should not repeat" rule.
|
| 919 |
+
2. Build a stable subject registry that will be reused in every event caption and in the global prompt.
|
| 920 |
+
3. Prefer specific human nouns such as man, woman, boy, girl, delivery man, worker, bride, groom, or chef instead of person when the subject is visually clear.
|
| 921 |
+
4. If the primary subject is an animal and no human is clearly visible, use a specific animal noun such as dog, cat, horse, bird, or duck instead of person-like wording.
|
| 922 |
+
5. If only a body part or non-human visible subject is central, such as a hand, paw, brush, or vehicle, record that faithfully instead of inventing a full person.
|
| 923 |
+
6. The term field in subject_registry is the canonical noun for that recurring subject, and the category field must distinguish whether it is human, animal, body_part, object, or unknown.
|
| 924 |
+
7. Example: if the chosen term is woman, that exact noun should be reused everywhere. Global captions may introduce the subject as a woman and later refer to the woman, but the noun itself must stay woman rather than lady, person, female, or individual.
|
| 925 |
+
8. Avoid sensitive or racial labels in subject descriptions. If skin tone is visually reliable and helpful, use neutral phrasing like light-to-medium skin tone.
|
| 926 |
+
9. Only state visually high-confidence facts.
|
| 927 |
+
|
| 928 |
+
Camera motion guide:
|
| 929 |
+
{camera_motion_guide}
|
| 930 |
+
|
| 931 |
+
Return JSON in exactly this schema:
|
| 932 |
+
{{
|
| 933 |
+
"is_sports": false,
|
| 934 |
+
"has_animal": false,
|
| 935 |
+
"is_cooking": false,
|
| 936 |
+
"subject_registry": [
|
| 937 |
+
{{
|
| 938 |
+
"subject_id": "subject_1",
|
| 939 |
+
"category": "human",
|
| 940 |
+
"term": "woman",
|
| 941 |
+
"profile": "young adult woman with very long light brown hair, a rust-colored top, and blue jeans"
|
| 942 |
+
}}
|
| 943 |
+
],
|
| 944 |
+
"stable_scene_summary": "One or two concise sentences about globally stable environment and framing.",
|
| 945 |
+
"stable_camera_summary": "One concise sentence about globally stable filming behavior."
|
| 946 |
+
}}
|
| 947 |
+
"""
|
| 948 |
+
).strip()
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
def build_event_prompt(
|
| 952 |
+
uuid: str,
|
| 953 |
+
event_index: int,
|
| 954 |
+
total_events: int,
|
| 955 |
+
previous_caption: str | None,
|
| 956 |
+
previous_focus_object: str | None,
|
| 957 |
+
context: dict[str, Any],
|
| 958 |
+
camera_motion_guide: str,
|
| 959 |
+
) -> str:
|
| 960 |
+
subject_registry = format_subject_registry(context.get("subject_registry", []))
|
| 961 |
+
prev_caption = previous_caption or "<none>"
|
| 962 |
+
prev_focus = previous_focus_object or "<none>"
|
| 963 |
+
is_first_event = event_index == 1
|
| 964 |
+
return textwrap.dedent(
|
| 965 |
+
f"""
|
| 966 |
+
You are annotating event {event_index} of {total_events} for UUID {uuid}.
|
| 967 |
+
|
| 968 |
+
Return strict JSON only. Do not use markdown fences. Use double-quoted JSON strings and JSON booleans/null.
|
| 969 |
+
|
| 970 |
+
Stable context from the full stitched video:
|
| 971 |
+
- is_sports: {json.dumps(context.get("is_sports", False))}
|
| 972 |
+
- has_animal: {json.dumps(context.get("has_animal", False))}
|
| 973 |
+
- is_cooking: {json.dumps(context.get("is_cooking", False))}
|
| 974 |
+
- subject_registry: {subject_registry}
|
| 975 |
+
- stable_scene_summary: {json.dumps(context.get("stable_scene_summary", ""))}
|
| 976 |
+
- stable_camera_summary: {json.dumps(context.get("stable_camera_summary", ""))}
|
| 977 |
+
|
| 978 |
+
Previous event caption: {json.dumps(prev_caption)}
|
| 979 |
+
Previous focus object: {json.dumps(prev_focus)}
|
| 980 |
+
|
| 981 |
+
Rules:
|
| 982 |
+
- Caption only this event clip, not the whole stitched video.
|
| 983 |
+
- The caption should focus on the event-specific action, motion, interaction, or state change that makes this segment distinct.
|
| 984 |
+
- Do not spend words restating stable global information unless that information is needed to make the event action clear and complete.
|
| 985 |
+
- There is no hard word limit for the event caption. Keep it as concise as possible, but long enough to express the action completely and unambiguously.
|
| 986 |
+
- The rules below define what information must be clear, not a fixed sentence template.
|
| 987 |
+
- Write in natural, varied English. Avoid repetitive stock openings or boilerplate phrasing across events when the content differs.
|
| 988 |
+
- Distinguish subtle but visible differences from the previous event when they are present. Fine-grained changes are meaningful and should be described instead of collapsing them into the same generic action.
|
| 989 |
+
- Examples of meaningful distinctions include closed-mouth smiling versus smiling with teeth visible, looking down versus looking toward the frame's left, a slight head lift versus a head turn, a hand resting versus a hand lifting, or maintaining contact with an object versus releasing it.
|
| 990 |
+
- If two adjacent events share the same broad action, describe the most reliable fine-grained difference that makes this event specific.
|
| 991 |
+
- If the repeated action visibly changes an object, material, or scene over time, distinguish the event through that evolving state. Examples include more ingredients being added, fewer petals remaining, a surface becoming more covered, a container becoming fuller or emptier, or another clear cumulative visual change.
|
| 992 |
+
- If the subject keeps moving in a similar way across adjacent events, distinguish the event through what the subject passes, approaches, leaves behind, enters, or moves alongside. Examples include passing a large tree, moving beside a wall, approaching a doorway, or walking beyond parked cars.
|
| 993 |
+
- Prefer these concrete scene-detail or object-state differences over repeating a generic caption such as the man walks or the hand adds ingredients.
|
| 994 |
+
- Unless this is sports footage, the caption must not be textually identical to the previous event caption.
|
| 995 |
+
- The subject_registry provides the canonical subject nouns for this UUID. Reuse those exact nouns in the caption instead of synonyms.
|
| 996 |
+
- subject_registry may include humans, animals, body parts, or non-human objects. Reuse those established noun categories faithfully and do not hallucinate a human subject when the main visible subject is an animal or non-human entity.
|
| 997 |
+
- Any recurring subject already established in subject_registry is globally known for this UUID, so event captions should use definite reference such as the woman or the man, even in event 1.
|
| 998 |
+
- Example: if subject_registry uses woman, write the woman when referring to that established subject in event captions, including the first event. Do not switch to lady, person, female, or individual.
|
| 999 |
+
- Likewise, if subject_registry uses bird, cat, dog, horse, hand, or brush, keep using the bird, the cat, the dog, the horse, the hand, or the brush rather than introducing a person who is not clearly visible.
|
| 1000 |
+
- Only use A/An for a truly new subject that is not already established in subject_registry.
|
| 1001 |
+
- Keep subject nouns strictly consistent with the subject_registry across all events whenever the same subject is being referenced.
|
| 1002 |
+
- If a new human, animal, object, hand, or body part enters the frame, explicitly indicate appearance with wording like appears, enters the frame, or comes into view.
|
| 1003 |
+
- If a human, animal, object, hand, or body part leaves the frame, explicitly indicate disappearance with wording like disappears, leaves the frame, or goes out of view.
|
| 1004 |
+
- The directional, turn, hand, and camera examples below are semantic guidance. Do not copy them mechanically when a more natural wording can express the same meaning with equal precision.
|
| 1005 |
+
- Use frame-aware direction wording when relevant: toward the frame's left, toward the frame's right, into the background, toward the camera.
|
| 1006 |
+
- For turns, describe the final orientation, such as turns to face the frame's left, turns away from the camera to face the background, or turns toward the camera to face the viewer.
|
| 1007 |
+
- If a subject uses a hand, specify his/her/their left hand or right hand.
|
| 1008 |
+
- If a subject is holding a camera inside the scene, call it the man's camera, the woman's camera, or an equivalent possessive phrase so it is not confused with the filming camera.
|
| 1009 |
+
- Camera motion must capture only the dominant major motion. Ignore tiny shifts and ordinary shake.
|
| 1010 |
+
- If the camera is truly static or near-static, set camera_motion_label to "" and camera_motion_desc to "".
|
| 1011 |
+
- If the camera is moving to follow a subject but the subject stays relatively stable in the frame, and you cannot assign a high-confidence major motion label, set camera_motion_label to "" but keep has_camera_motion as true and write camera_motion_desc to explicitly say that the framing remains relatively stable while the camera follows the subject.
|
| 1012 |
+
- Use standard English camera-motion verb forms when writing camera_motion_desc. Write dollies in/out, pedestals up/down, trucks left/right, pans left/right, tilts up/down, rolls clockwise/counterclockwise, and zooms in/out. Never write malformed forms such as dollys out or as it dolly-in.
|
| 1013 |
+
- has_focus_shift is relative to the previous event and only applies when the filming camera does not move. The first event must use null.
|
| 1014 |
+
- If has_camera_motion is true, has_environmental_change must also be true.
|
| 1015 |
+
- is_multi_person means multiple human subjects are visible in this event clip.
|
| 1016 |
+
- has_occlusion is true only when a newly introduced or newly moved subject/object meaningfully blocks a previously visible subject in a changed way, not for ordinary partial overlap.
|
| 1017 |
+
|
| 1018 |
+
Camera motion guide:
|
| 1019 |
+
{camera_motion_guide}
|
| 1020 |
+
|
| 1021 |
+
Return JSON in exactly this schema:
|
| 1022 |
+
{{
|
| 1023 |
+
"caption": "A complete event-specific caption with no fixed word limit. Prioritize the distinctive action in this event, including subtle differences, evolving object or scene state, or passed landmarks when relevant, and avoid unnecessary repetition of stable global context.",
|
| 1024 |
+
"has_appearance": false,
|
| 1025 |
+
"has_disappearance": false,
|
| 1026 |
+
"has_camera_motion": false,
|
| 1027 |
+
"has_focus_shift": {json.dumps(None) if is_first_event else "false"},
|
| 1028 |
+
"is_multi_person": false,
|
| 1029 |
+
"has_environmental_change": false,
|
| 1030 |
+
"has_occlusion": false,
|
| 1031 |
+
"has_lighting_change": false,
|
| 1032 |
+
"has_animal": false,
|
| 1033 |
+
"is_cooking": false,
|
| 1034 |
+
"focus_object": "brief noun phrase",
|
| 1035 |
+
"camera_motion_label": "",
|
| 1036 |
+
"camera_motion_desc": ""
|
| 1037 |
+
}}
|
| 1038 |
+
"""
|
| 1039 |
+
).strip()
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
def build_event_caption_refine_prompt(
|
| 1043 |
+
uuid: str,
|
| 1044 |
+
event_index: int,
|
| 1045 |
+
total_events: int,
|
| 1046 |
+
previous_caption: str,
|
| 1047 |
+
draft_caption: str,
|
| 1048 |
+
context: dict[str, Any],
|
| 1049 |
+
attempt: int = 1,
|
| 1050 |
+
) -> str:
|
| 1051 |
+
subject_registry = format_subject_registry(context.get("subject_registry", []))
|
| 1052 |
+
extra_rules = ""
|
| 1053 |
+
if attempt >= 2:
|
| 1054 |
+
extra_rules = textwrap.dedent(
|
| 1055 |
+
"""
|
| 1056 |
+
- This is a second rewrite attempt because the caption still sounds too close to the previous one.
|
| 1057 |
+
- Change the sentence structure as well as the distinguishing detail so the result does not feel like a lightly edited template.
|
| 1058 |
+
"""
|
| 1059 |
+
).strip()
|
| 1060 |
+
return textwrap.dedent(
|
| 1061 |
+
f"""
|
| 1062 |
+
You are revising the caption for event {event_index} of {total_events} for UUID {uuid}.
|
| 1063 |
+
|
| 1064 |
+
Return strict JSON only. Do not use markdown fences. Use double-quoted JSON strings and JSON booleans/null.
|
| 1065 |
+
|
| 1066 |
+
Stable context:
|
| 1067 |
+
- is_sports: {json.dumps(context.get("is_sports", False))}
|
| 1068 |
+
- subject_registry: {subject_registry}
|
| 1069 |
+
|
| 1070 |
+
Previous event caption: {json.dumps(previous_caption)}
|
| 1071 |
+
Current draft caption: {json.dumps(draft_caption)}
|
| 1072 |
+
|
| 1073 |
+
The draft caption is too similar to the previous event caption. Rewrite it so the current event is distinguished by the finest reliable visible difference.
|
| 1074 |
+
|
| 1075 |
+
Rules:
|
| 1076 |
+
- Reuse the exact canonical subject nouns from subject_registry.
|
| 1077 |
+
- Keep the caption focused on this event only.
|
| 1078 |
+
- Write in natural, non-formulaic English. Do not merely append generic boilerplate to the draft.
|
| 1079 |
+
- If the broad action stays similar, describe the subtle but visible difference, such as mouth open versus mouth closed while smiling, teeth becoming visible, a shift in gaze direction, a head lift, a hand movement, a small pose change, a change in object contact, or another reliable fine-grained state change.
|
| 1080 |
+
- If the repeated action changes the scene or object over time, use that evolving detail to distinguish the event, such as more ingredients accumulating, fewer petals remaining, a surface becoming more covered, or another cumulative visible change.
|
| 1081 |
+
- If the subject keeps moving in a similar way, distinguish the event through what the subject passes, approaches, leaves behind, or enters, such as a tree, wall, doorway, vehicle, table, or other reliable landmark.
|
| 1082 |
+
- Do not invent details that are not visually reliable.
|
| 1083 |
+
- Do not restate stable global context unless needed for clarity.
|
| 1084 |
+
- The rewritten caption must not be textually identical to the previous event caption.
|
| 1085 |
+
- The earlier examples are semantic guidance only. Prefer natural phrasing over rigid reuse of example wording.
|
| 1086 |
+
{extra_rules}
|
| 1087 |
+
|
| 1088 |
+
Return JSON in exactly this schema:
|
| 1089 |
+
{{
|
| 1090 |
+
"caption": "A refined event-specific caption that explicitly distinguishes this event from the previous one."
|
| 1091 |
+
}}
|
| 1092 |
+
"""
|
| 1093 |
+
).strip()
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
def build_event_camera_motion_repair_prompt(
|
| 1097 |
+
uuid: str,
|
| 1098 |
+
event_index: int,
|
| 1099 |
+
total_events: int,
|
| 1100 |
+
draft_payload: dict[str, Any],
|
| 1101 |
+
context: dict[str, Any],
|
| 1102 |
+
camera_motion_guide: str,
|
| 1103 |
+
attempt: int = 1,
|
| 1104 |
+
) -> str:
|
| 1105 |
+
subject_registry = format_subject_registry(context.get("subject_registry", []))
|
| 1106 |
+
extra_rules = ""
|
| 1107 |
+
if attempt >= 2:
|
| 1108 |
+
extra_rules = textwrap.dedent(
|
| 1109 |
+
"""
|
| 1110 |
+
- This is a second repair attempt because the camera fields are still incomplete.
|
| 1111 |
+
- Rewrite the description more concretely and naturally instead of falling back to vague stock wording.
|
| 1112 |
+
"""
|
| 1113 |
+
).strip()
|
| 1114 |
+
return textwrap.dedent(
|
| 1115 |
+
f"""
|
| 1116 |
+
You are repairing the camera motion fields for event {event_index} of {total_events} for UUID {uuid}.
|
| 1117 |
+
|
| 1118 |
+
Return strict JSON only. Do not use markdown fences. Use double-quoted JSON strings and JSON booleans/null.
|
| 1119 |
+
|
| 1120 |
+
Stable context:
|
| 1121 |
+
- subject_registry: {subject_registry}
|
| 1122 |
+
- current_caption: {json.dumps(normalize_whitespace(draft_payload.get("caption")))}
|
| 1123 |
+
- draft_has_camera_motion: {json.dumps(coerce_bool(draft_payload.get("has_camera_motion")))}
|
| 1124 |
+
- draft_camera_motion_label: {json.dumps(normalize_camera_motion_label(draft_payload.get("camera_motion_label")))}
|
| 1125 |
+
- draft_camera_motion_desc: {json.dumps(normalize_whitespace(draft_payload.get("camera_motion_desc")))}
|
| 1126 |
+
|
| 1127 |
+
Rules:
|
| 1128 |
+
- Repair only the camera motion fields.
|
| 1129 |
+
- Use a major motion label only when it is high-confidence.
|
| 1130 |
+
- If the camera is truly static or near-static, set has_camera_motion to false and leave both camera_motion_label and camera_motion_desc empty.
|
| 1131 |
+
- If the camera is moving to follow a subject but the subject remains relatively stable in the frame and no major motion label is high-confidence, set has_camera_motion to true, leave camera_motion_label empty, and write a natural camera_motion_desc explaining that the framing stays relatively stable while the camera follows the subject.
|
| 1132 |
+
- Write natural prose. Do not use shorthand such as static | pan-right | ...
|
| 1133 |
+
- Use standard English camera-motion verb forms. Write dollies in/out, pedestals up/down, trucks left/right, pans left/right, tilts up/down, rolls clockwise/counterclockwise, and zooms in/out. Never write malformed forms such as dollys out or as it dolly-in.
|
| 1134 |
+
- Do not invent camera motion that is not visually reliable.
|
| 1135 |
+
{extra_rules}
|
| 1136 |
+
|
| 1137 |
+
Camera motion guide:
|
| 1138 |
+
{camera_motion_guide}
|
| 1139 |
+
|
| 1140 |
+
Return JSON in exactly this schema:
|
| 1141 |
+
{{
|
| 1142 |
+
"has_camera_motion": false,
|
| 1143 |
+
"camera_motion_label": "",
|
| 1144 |
+
"camera_motion_desc": ""
|
| 1145 |
+
}}
|
| 1146 |
+
"""
|
| 1147 |
+
).strip()
|
| 1148 |
+
|
| 1149 |
+
|
| 1150 |
+
def build_global_camera_repair_prompt(
|
| 1151 |
+
uuid: str,
|
| 1152 |
+
context: dict[str, Any],
|
| 1153 |
+
events: list[dict[str, Any]],
|
| 1154 |
+
draft_payload: dict[str, Any],
|
| 1155 |
+
derived_prefix: str,
|
| 1156 |
+
derived_label: str,
|
| 1157 |
+
derived_description: str,
|
| 1158 |
+
attempt: int = 1,
|
| 1159 |
+
) -> str:
|
| 1160 |
+
event_camera_summary = [
|
| 1161 |
+
{
|
| 1162 |
+
"event_id": event["event_id"],
|
| 1163 |
+
"has_camera_motion": event["has_camera_motion"],
|
| 1164 |
+
"camera_motion_label": event["camera_motion_label"],
|
| 1165 |
+
"camera_motion_desc": event["camera_motion_desc"],
|
| 1166 |
+
}
|
| 1167 |
+
for event in events
|
| 1168 |
+
]
|
| 1169 |
+
extra_rules = ""
|
| 1170 |
+
if attempt >= 2:
|
| 1171 |
+
extra_rules = textwrap.dedent(
|
| 1172 |
+
"""
|
| 1173 |
+
- This is a second repair attempt because the previous global camera description was still unusable or inconsistent.
|
| 1174 |
+
- Rewrite it in more specific natural language while staying fully consistent with the event-level camera evidence.
|
| 1175 |
+
"""
|
| 1176 |
+
).strip()
|
| 1177 |
+
return textwrap.dedent(
|
| 1178 |
+
f"""
|
| 1179 |
+
You are repairing the global camera motion fields for UUID {uuid}.
|
| 1180 |
+
|
| 1181 |
+
Return strict JSON only. Do not use markdown fences. Use double-quoted JSON strings and JSON booleans/null.
|
| 1182 |
+
|
| 1183 |
+
Stable context:
|
| 1184 |
+
- subject_registry: {format_subject_registry(context.get("subject_registry", []))}
|
| 1185 |
+
- stable_camera_summary: {json.dumps(context.get("stable_camera_summary", ""))}
|
| 1186 |
+
- event_camera_summary:
|
| 1187 |
+
{json.dumps(event_camera_summary, ensure_ascii=False, indent=2)}
|
| 1188 |
+
- current_draft_prefix: {json.dumps(normalize_global_camera_prefix(draft_payload.get("camera_movement_prefix")))}
|
| 1189 |
+
- current_draft_label: {json.dumps(normalize_camera_motion_label(draft_payload.get("camera_movement_label")))}
|
| 1190 |
+
- current_draft_description: {json.dumps(normalize_whitespace(draft_payload.get("camera_movement_description")))}
|
| 1191 |
+
- event_derived_prefix: {json.dumps(derived_prefix)}
|
| 1192 |
+
- event_derived_label: {json.dumps(derived_label)}
|
| 1193 |
+
- event_derived_description: {json.dumps(derived_description)}
|
| 1194 |
+
|
| 1195 |
+
Rules:
|
| 1196 |
+
- The result must stay consistent with the event-level camera evidence.
|
| 1197 |
+
- camera_movement_description must be natural prose. Do not use shorthand such as static | pan-right | ...
|
| 1198 |
+
- Use standard English camera-motion verb forms. Write dollies in/out, pedestals up/down, trucks left/right, pans left/right, tilts up/down, rolls clockwise/counterclockwise, and zooms in/out. Never write malformed forms such as dollys out or as it dolly-in.
|
| 1199 |
+
- If the camera behavior changes across the video, describe the sequence directly in natural language.
|
| 1200 |
+
- If the camera is globally static, say so directly in a sentence.
|
| 1201 |
+
- If the camera often follows the subject while keeping the framing relatively stable, you may leave camera_movement_label empty and describe that behavior in natural language.
|
| 1202 |
+
- Prefer specific, UUID-appropriate wording over generic stock sentences when the evidence supports it.
|
| 1203 |
+
{extra_rules}
|
| 1204 |
+
|
| 1205 |
+
Return JSON in exactly this schema:
|
| 1206 |
+
{{
|
| 1207 |
+
"camera_movement_prefix": "static",
|
| 1208 |
+
"camera_movement_label": "",
|
| 1209 |
+
"camera_movement_description": "A natural-language sentence or paragraph."
|
| 1210 |
+
}}
|
| 1211 |
+
"""
|
| 1212 |
+
).strip()
|
| 1213 |
+
|
| 1214 |
+
|
| 1215 |
+
def build_subject_profile_repair_prompt(
|
| 1216 |
+
uuid: str,
|
| 1217 |
+
context: dict[str, Any],
|
| 1218 |
+
events: list[dict[str, Any]],
|
| 1219 |
+
draft_payload: dict[str, Any],
|
| 1220 |
+
attempt: int = 1,
|
| 1221 |
+
) -> str:
|
| 1222 |
+
event_subject_summary = [
|
| 1223 |
+
{
|
| 1224 |
+
"event_id": event["event_id"],
|
| 1225 |
+
"caption": event["caption"],
|
| 1226 |
+
"is_multi_person": event["is_multi_person"],
|
| 1227 |
+
"has_animal": event["has_animal"],
|
| 1228 |
+
"focus_object": event["focus_object"],
|
| 1229 |
+
}
|
| 1230 |
+
for event in events
|
| 1231 |
+
]
|
| 1232 |
+
extra_rules = ""
|
| 1233 |
+
if attempt >= 2:
|
| 1234 |
+
extra_rules = textwrap.dedent(
|
| 1235 |
+
"""
|
| 1236 |
+
- This is a second repair attempt because subject_profile is still missing or unusable.
|
| 1237 |
+
- Rewrite it as a natural paragraph rather than a stock formula.
|
| 1238 |
+
"""
|
| 1239 |
+
).strip()
|
| 1240 |
+
return textwrap.dedent(
|
| 1241 |
+
f"""
|
| 1242 |
+
You are repairing the subject_profile field for UUID {uuid}.
|
| 1243 |
+
|
| 1244 |
+
Return strict JSON only. Do not use markdown fences. Use double-quoted JSON strings and JSON booleans/null.
|
| 1245 |
+
|
| 1246 |
+
Stable context:
|
| 1247 |
+
- subject_registry: {format_subject_registry(context.get("subject_registry", []))}
|
| 1248 |
+
- current_draft_subject_profile: {json.dumps(normalize_whitespace(draft_payload.get("subject_profile")))}
|
| 1249 |
+
- event_subject_summary:
|
| 1250 |
+
{json.dumps(event_subject_summary, ensure_ascii=False, indent=2)}
|
| 1251 |
+
|
| 1252 |
+
Rules:
|
| 1253 |
+
- Reuse the canonical nouns from subject_registry.
|
| 1254 |
+
- Explicitly distinguish whether the recurring subjects are human-only, animal-only, mixed human-animal, or non-human-only.
|
| 1255 |
+
- If no human is clearly visible, do not imply one.
|
| 1256 |
+
- Write a natural paragraph, not a stock formula.
|
| 1257 |
+
- Avoid sensitive racial labels. If skin tone is visually reliable and useful, use neutral phrasing.
|
| 1258 |
+
- Do not narrate event order.
|
| 1259 |
+
{extra_rules}
|
| 1260 |
+
|
| 1261 |
+
Return JSON in exactly this schema:
|
| 1262 |
+
{{
|
| 1263 |
+
"subject_profile": "A natural paragraph describing the recurring main subject or subjects."
|
| 1264 |
+
}}
|
| 1265 |
+
"""
|
| 1266 |
+
).strip()
|
| 1267 |
+
|
| 1268 |
+
|
| 1269 |
+
def build_global_refine_prompt(
|
| 1270 |
+
uuid: str,
|
| 1271 |
+
context: dict[str, Any],
|
| 1272 |
+
events: list[dict[str, Any]],
|
| 1273 |
+
) -> str:
|
| 1274 |
+
event_summary = [
|
| 1275 |
+
{
|
| 1276 |
+
"event_id": event["event_id"],
|
| 1277 |
+
"caption": event["caption"],
|
| 1278 |
+
"focus_object": event["focus_object"],
|
| 1279 |
+
"camera_motion_label": event["camera_motion_label"],
|
| 1280 |
+
"camera_motion_desc": event["camera_motion_desc"],
|
| 1281 |
+
"has_appearance": event["has_appearance"],
|
| 1282 |
+
"has_disappearance": event["has_disappearance"],
|
| 1283 |
+
"has_environmental_change": event["has_environmental_change"],
|
| 1284 |
+
"has_occlusion": event["has_occlusion"],
|
| 1285 |
+
"has_lighting_change": event["has_lighting_change"],
|
| 1286 |
+
}
|
| 1287 |
+
for event in events
|
| 1288 |
+
]
|
| 1289 |
+
return textwrap.dedent(
|
| 1290 |
+
f"""
|
| 1291 |
+
You are writing the global annotation for UUID {uuid} using the full stitched video as primary evidence and the event summaries as supporting evidence.
|
| 1292 |
+
|
| 1293 |
+
Return strict JSON only. Do not use markdown fences. Use double-quoted JSON strings and JSON booleans/null.
|
| 1294 |
+
|
| 1295 |
+
Stable context:
|
| 1296 |
+
- is_sports: {json.dumps(context.get("is_sports", False))}
|
| 1297 |
+
- subject_registry: {format_subject_registry(context.get("subject_registry", []))}
|
| 1298 |
+
- stable_scene_summary: {json.dumps(context.get("stable_scene_summary", ""))}
|
| 1299 |
+
- stable_camera_summary: {json.dumps(context.get("stable_camera_summary", ""))}
|
| 1300 |
+
- event_summaries:
|
| 1301 |
+
{json.dumps(event_summary, ensure_ascii=False, indent=2)}
|
| 1302 |
+
|
| 1303 |
+
Rules:
|
| 1304 |
+
- The global prompt must describe stable, high-confidence information from the stitched whole video.
|
| 1305 |
+
- Do not narrate event order. Do not use first, then, next, afterwards, before, after, event 1, or event 2.
|
| 1306 |
+
- The structured fields do not have fixed sentence-count or word-count limits. Make them as short or as detailed as needed, but only include visually high-confidence and globally stable information.
|
| 1307 |
+
- The field descriptions define coverage, not canned wording. Avoid making every field sound like the same stock template.
|
| 1308 |
+
- Write the structured fields in the style of compact descriptive paragraphs rather than short labels.
|
| 1309 |
+
- Use natural prose and vary sentence openings across fields when appropriate instead of repeatedly starting with the same formula such as "The video shows" or "The scene is set".
|
| 1310 |
+
- background should describe the stable physical setting in concrete visual detail: scene type, layout, major surfaces, furniture, props, vegetation, architecture, visible depth layers, and other recurring environmental elements.
|
| 1311 |
+
- theme should function like a theme description rather than an abstract keyword. It should explain the stable situation, the recurring human or animal roles, the likely activity domain, and the central visual focus without narrating event order.
|
| 1312 |
+
- style should describe the overall visual presentation and footage character, such as documentary, candid, cinematic, stock-footage-like, surveillance-like, tutorial-like, vlog-like, observational, staged, polished, raw, or naturalistic.
|
| 1313 |
+
- shot_type should describe the dominant framing and composition: shot scale, camera angle, viewpoint height, subject placement, depth of field, whether the framing isolates the subject or includes the environment, and any stable compositional pattern.
|
| 1314 |
+
- camera_movement_description should read like a natural standalone sentence or paragraph, summarizing the overall filming behavior, what motion is dominant, whether motion is sustained or intermittent, and whether the framing stays fixed or follows the subject.
|
| 1315 |
+
- Do not write camera_movement_description in shorthand such as static | pan-right | ... . The final text should be natural prose.
|
| 1316 |
+
- Use standard English camera-motion verb forms. Write dollies in/out, pedestals up/down, trucks left/right, pans left/right, tilts up/down, rolls clockwise/counterclockwise, and zooms in/out. Never write malformed forms such as dollys out or as it dolly-in.
|
| 1317 |
+
- If the camera behavior changes across the video, you may describe that sequence directly in natural language, such as static at first, then following the subject, and later panning right.
|
| 1318 |
+
- Avoid generic stock camera descriptions when a more specific, high-confidence description can be written for this UUID.
|
| 1319 |
+
- lighting should describe stable lighting source and quality in concrete terms, such as natural sunlight, indoor ambient light, overhead fixtures, warm or cool tones, contrast level, shadows, highlights, diffusion, and visibility.
|
| 1320 |
+
- atmosphere should describe the stable mood and experiential tone suggested by the visual evidence, such as calm, tense, playful, intimate, energetic, routine, joyful, solemn, tranquil, busy, or contemplative.
|
| 1321 |
+
- subject_profile should read like a compact profile of the recurring main subject or subjects, covering consistent identity terms, apparent age group, visible build or posture when reliable, hair, clothing, accessories, recurring carried objects, and stable appearance cues.
|
| 1322 |
+
- subject_profile must explicitly distinguish whether the stable primary subjects are human-only, animal-only, mixed human-animal, or non-human-only.
|
| 1323 |
+
- If no human is clearly visible, do not imply one. For animal-only videos, describe the animal as the primary subject using species or animal-type details, markings, fur, feathers, or body shape when reliable. For body-part-led or object-led videos, state that the visible hand, tool, object, or other non-human subject is the primary visible subject.
|
| 1324 |
+
- The short caption should be about 20 words.
|
| 1325 |
+
- The middle caption should be about 80 words.
|
| 1326 |
+
- The long caption should be about 200 words.
|
| 1327 |
+
- The detailed caption should be about 500-800 words.
|
| 1328 |
+
- The detailed caption may synthesize and reuse the structured fields plus stable recurring evidence from the event summaries, but it must not turn into a segment-by-segment narration.
|
| 1329 |
+
- The subject_registry defines the canonical subject nouns for the UUID. Reuse those same nouns across subject_profile and all global captions instead of switching to synonyms.
|
| 1330 |
+
- Example: if subject_registry uses woman, the global descriptions may introduce her as a woman and later refer to the woman, but should not switch to lady, person, female, or individual.
|
| 1331 |
+
- The subject_profile should avoid sensitive racial labels and should reuse the same subject nouns chosen in the subject_registry.
|
| 1332 |
+
- The global camera_movement should summarize only the overall stable filming pattern using:
|
| 1333 |
+
- static
|
| 1334 |
+
- moving-throughout
|
| 1335 |
+
- intermittent
|
| 1336 |
+
- motion-changes
|
| 1337 |
+
- mixed
|
| 1338 |
+
- near-static
|
| 1339 |
+
- For static or near-static global motion, camera_movement_label can be empty.
|
| 1340 |
+
|
| 1341 |
+
Return JSON in exactly this schema:
|
| 1342 |
+
{{
|
| 1343 |
+
"background": "A paragraph-style description of the stable physical environment: scene type, layout, major surfaces, props, furniture, architecture, vegetation, and recurring depth layers. No fixed length. Use only high-confidence information.",
|
| 1344 |
+
"theme": "A paragraph-style theme description of the stable situation, recurring roles, and central visual focus. Do not narrate event order. No fixed length. Use only high-confidence information.",
|
| 1345 |
+
"style": "A paragraph-style description of the overall visual style or footage character, such as documentary, candid, cinematic, naturalistic, stock-footage-like, tutorial-like, or observational. No fixed length. Use only high-confidence information.",
|
| 1346 |
+
"shot_type": "A paragraph-style description of dominant shot scale, camera angle, viewpoint height, framing, composition, subject placement, and depth-of-field behavior. No fixed length. Use only high-confidence information.",
|
| 1347 |
+
"camera_movement_prefix": "static",
|
| 1348 |
+
"camera_movement_label": "",
|
| 1349 |
+
"camera_movement_description": "A natural-language sentence or paragraph describing the global filming behavior, without any pipe-delimited shorthand. If motion changes over time, describe the sequence directly in prose. No fixed length. Use only high-confidence information.",
|
| 1350 |
+
"lighting": "A paragraph-style description of stable lighting source, quality, color temperature, contrast, shadows, highlights, and overall visibility. No fixed length. Use only high-confidence information.",
|
| 1351 |
+
"atmosphere": "A paragraph-style description of the stable mood and experiential tone created by the scene, subjects, pacing, and visual presentation. No fixed length. Use only high-confidence information.",
|
| 1352 |
+
"subject_profile": "A paragraph-style profile of the recurring main subject or subjects, explicitly distinguishing human-only, animal-only, mixed human-animal, or non-human-only setups. Reuse the canonical nouns from subject_registry, and if no human is clearly visible, do not imply one. No fixed length. Use only high-confidence information.",
|
| 1353 |
+
"short_caption": "About 20 words.",
|
| 1354 |
+
"middle_caption": "About 80 words.",
|
| 1355 |
+
"long_caption": "About 200 words.",
|
| 1356 |
+
"detailed_caption": "About 500-800 words."
|
| 1357 |
+
}}
|
| 1358 |
+
"""
|
| 1359 |
+
).strip()
|
| 1360 |
+
|
| 1361 |
+
|
| 1362 |
+
class Qwen3VLRunner:
|
| 1363 |
+
def __init__(
|
| 1364 |
+
self,
|
| 1365 |
+
model_path: Path,
|
| 1366 |
+
device_map: str,
|
| 1367 |
+
dtype: str,
|
| 1368 |
+
attn_implementation: str,
|
| 1369 |
+
trust_remote_code: bool,
|
| 1370 |
+
fps: float,
|
| 1371 |
+
max_pixels: int | None,
|
| 1372 |
+
temperature: float,
|
| 1373 |
+
top_p: float,
|
| 1374 |
+
top_k: int,
|
| 1375 |
+
repetition_penalty: float,
|
| 1376 |
+
greedy: bool,
|
| 1377 |
+
) -> None:
|
| 1378 |
+
try:
|
| 1379 |
+
import torch
|
| 1380 |
+
from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
|
| 1381 |
+
except ModuleNotFoundError as exc:
|
| 1382 |
+
raise RuntimeError(
|
| 1383 |
+
"Missing runtime dependencies. Install torch and transformers in the inference environment."
|
| 1384 |
+
) from exc
|
| 1385 |
+
|
| 1386 |
+
self.torch = torch
|
| 1387 |
+
self.temperature = temperature
|
| 1388 |
+
self.top_p = top_p
|
| 1389 |
+
self.top_k = top_k
|
| 1390 |
+
self.repetition_penalty = repetition_penalty
|
| 1391 |
+
self.greedy = greedy
|
| 1392 |
+
self.fps = fps if fps and fps > 0 else None
|
| 1393 |
+
self.max_pixels = max_pixels if max_pixels and max_pixels > 0 else None
|
| 1394 |
+
self.process_vision_info = None
|
| 1395 |
+
|
| 1396 |
+
try:
|
| 1397 |
+
from qwen_vl_utils import process_vision_info # type: ignore
|
| 1398 |
+
except ModuleNotFoundError:
|
| 1399 |
+
process_vision_info = None
|
| 1400 |
+
self.process_vision_info = process_vision_info
|
| 1401 |
+
|
| 1402 |
+
dtype_map = {
|
| 1403 |
+
"auto": "auto",
|
| 1404 |
+
"float16": torch.float16,
|
| 1405 |
+
"bfloat16": torch.bfloat16,
|
| 1406 |
+
"float32": torch.float32,
|
| 1407 |
+
}
|
| 1408 |
+
load_kwargs: dict[str, Any] = {
|
| 1409 |
+
"device_map": device_map,
|
| 1410 |
+
"torch_dtype": dtype_map[dtype],
|
| 1411 |
+
"trust_remote_code": trust_remote_code,
|
| 1412 |
+
}
|
| 1413 |
+
if attn_implementation:
|
| 1414 |
+
load_kwargs["attn_implementation"] = attn_implementation
|
| 1415 |
+
|
| 1416 |
+
self.model = Qwen3VLForConditionalGeneration.from_pretrained(
|
| 1417 |
+
str(model_path),
|
| 1418 |
+
**load_kwargs,
|
| 1419 |
+
)
|
| 1420 |
+
self.processor = AutoProcessor.from_pretrained(
|
| 1421 |
+
str(model_path),
|
| 1422 |
+
trust_remote_code=trust_remote_code,
|
| 1423 |
+
)
|
| 1424 |
+
|
| 1425 |
+
def _build_messages(self, video_paths: list[Path], prompt: str) -> list[dict[str, Any]]:
|
| 1426 |
+
user_content: list[dict[str, Any]] = []
|
| 1427 |
+
for path in video_paths:
|
| 1428 |
+
video_item: dict[str, Any] = {
|
| 1429 |
+
"type": "video",
|
| 1430 |
+
"video": str(path.resolve()),
|
| 1431 |
+
}
|
| 1432 |
+
if self.fps is not None:
|
| 1433 |
+
video_item["fps"] = self.fps
|
| 1434 |
+
if self.max_pixels is not None:
|
| 1435 |
+
video_item["max_pixels"] = self.max_pixels
|
| 1436 |
+
user_content.append(video_item)
|
| 1437 |
+
user_content.append({"type": "text", "text": prompt})
|
| 1438 |
+
return [
|
| 1439 |
+
{
|
| 1440 |
+
"role": "system",
|
| 1441 |
+
"content": (
|
| 1442 |
+
"You are a careful video annotation assistant. "
|
| 1443 |
+
"Return strict JSON only and prefer high-confidence visual facts."
|
| 1444 |
+
),
|
| 1445 |
+
},
|
| 1446 |
+
{
|
| 1447 |
+
"role": "user",
|
| 1448 |
+
"content": user_content,
|
| 1449 |
+
},
|
| 1450 |
+
]
|
| 1451 |
+
|
| 1452 |
+
def _prepare_inputs(self, messages: list[dict[str, Any]]):
|
| 1453 |
+
if self.process_vision_info is not None:
|
| 1454 |
+
text = self.processor.apply_chat_template(
|
| 1455 |
+
messages,
|
| 1456 |
+
tokenize=False,
|
| 1457 |
+
add_generation_prompt=True,
|
| 1458 |
+
)
|
| 1459 |
+
image_inputs, video_inputs = self.process_vision_info(messages)
|
| 1460 |
+
inputs = self.processor(
|
| 1461 |
+
text=[text],
|
| 1462 |
+
images=image_inputs,
|
| 1463 |
+
videos=video_inputs,
|
| 1464 |
+
padding=True,
|
| 1465 |
+
return_tensors="pt",
|
| 1466 |
+
)
|
| 1467 |
+
else:
|
| 1468 |
+
try:
|
| 1469 |
+
inputs = self.processor.apply_chat_template(
|
| 1470 |
+
messages,
|
| 1471 |
+
tokenize=True,
|
| 1472 |
+
add_generation_prompt=True,
|
| 1473 |
+
return_dict=True,
|
| 1474 |
+
return_tensors="pt",
|
| 1475 |
+
)
|
| 1476 |
+
except Exception as exc:
|
| 1477 |
+
raise RuntimeError(
|
| 1478 |
+
"Failed to prepare Qwen video inputs. Install qwen-vl-utils or use a transformers build that supports direct multimodal chat templating."
|
| 1479 |
+
) from exc
|
| 1480 |
+
return inputs.to(self.model.device)
|
| 1481 |
+
|
| 1482 |
+
def generate_json(
|
| 1483 |
+
self,
|
| 1484 |
+
video_paths: list[Path],
|
| 1485 |
+
prompt: str,
|
| 1486 |
+
max_new_tokens: int,
|
| 1487 |
+
) -> dict[str, Any]:
|
| 1488 |
+
messages = self._build_messages(video_paths, prompt)
|
| 1489 |
+
inputs = self._prepare_inputs(messages)
|
| 1490 |
+
|
| 1491 |
+
generate_kwargs: dict[str, Any] = {
|
| 1492 |
+
"max_new_tokens": max_new_tokens,
|
| 1493 |
+
"repetition_penalty": self.repetition_penalty,
|
| 1494 |
+
}
|
| 1495 |
+
if self.greedy:
|
| 1496 |
+
generate_kwargs["do_sample"] = False
|
| 1497 |
+
else:
|
| 1498 |
+
generate_kwargs.update(
|
| 1499 |
+
{
|
| 1500 |
+
"do_sample": True,
|
| 1501 |
+
"temperature": self.temperature,
|
| 1502 |
+
"top_p": self.top_p,
|
| 1503 |
+
"top_k": self.top_k,
|
| 1504 |
+
}
|
| 1505 |
+
)
|
| 1506 |
+
|
| 1507 |
+
with self.torch.inference_mode():
|
| 1508 |
+
generated_ids = self.model.generate(**inputs, **generate_kwargs)
|
| 1509 |
+
generated_ids_trimmed = [
|
| 1510 |
+
out_ids[len(in_ids) :]
|
| 1511 |
+
for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 1512 |
+
]
|
| 1513 |
+
output_text = self.processor.batch_decode(
|
| 1514 |
+
generated_ids_trimmed,
|
| 1515 |
+
skip_special_tokens=True,
|
| 1516 |
+
clean_up_tokenization_spaces=False,
|
| 1517 |
+
)[0]
|
| 1518 |
+
if self.torch.cuda.is_available():
|
| 1519 |
+
self.torch.cuda.empty_cache()
|
| 1520 |
+
return parse_json_payload(output_text)
|
| 1521 |
+
|
| 1522 |
+
|
| 1523 |
+
def create_uuid_temp_dir(
|
| 1524 |
+
uuid: str,
|
| 1525 |
+
temp_root: str | None,
|
| 1526 |
+
keep_temp: bool,
|
| 1527 |
+
) -> tuple[Path, tempfile.TemporaryDirectory[str] | None]:
|
| 1528 |
+
if keep_temp:
|
| 1529 |
+
path = Path(tempfile.mkdtemp(prefix=f"multi_event_{uuid}_", dir=temp_root))
|
| 1530 |
+
logging.info("Keeping temp files for %s in %s", uuid, path)
|
| 1531 |
+
return path, None
|
| 1532 |
+
manager = tempfile.TemporaryDirectory(prefix=f"multi_event_{uuid}_", dir=temp_root)
|
| 1533 |
+
return Path(manager.name), manager
|
| 1534 |
+
|
| 1535 |
+
|
| 1536 |
+
def write_ffmpeg_concat_list(list_path: Path, segments: Iterable[SegmentInfo]) -> None:
|
| 1537 |
+
lines = []
|
| 1538 |
+
for segment in segments:
|
| 1539 |
+
escaped = str(segment.path).replace("\\", "\\\\").replace("'", r"'\''")
|
| 1540 |
+
lines.append(f"file '{escaped}'")
|
| 1541 |
+
list_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
| 1542 |
+
|
| 1543 |
+
|
| 1544 |
+
def stitch_segments(
|
| 1545 |
+
uuid: str,
|
| 1546 |
+
segments: list[SegmentInfo],
|
| 1547 |
+
temp_dir: Path,
|
| 1548 |
+
ffmpeg_bin: str,
|
| 1549 |
+
) -> Path:
|
| 1550 |
+
concat_list = temp_dir / f"{uuid}_concat.txt"
|
| 1551 |
+
stitched_video = temp_dir / f"{uuid}_stitched.mp4"
|
| 1552 |
+
write_ffmpeg_concat_list(concat_list, segments)
|
| 1553 |
+
|
| 1554 |
+
copy_cmd = [
|
| 1555 |
+
ffmpeg_bin,
|
| 1556 |
+
"-hide_banner",
|
| 1557 |
+
"-loglevel",
|
| 1558 |
+
"error",
|
| 1559 |
+
"-y",
|
| 1560 |
+
"-f",
|
| 1561 |
+
"concat",
|
| 1562 |
+
"-safe",
|
| 1563 |
+
"0",
|
| 1564 |
+
"-i",
|
| 1565 |
+
str(concat_list),
|
| 1566 |
+
"-c",
|
| 1567 |
+
"copy",
|
| 1568 |
+
str(stitched_video),
|
| 1569 |
+
]
|
| 1570 |
+
copy_result = subprocess.run(copy_cmd, capture_output=True, text=True)
|
| 1571 |
+
if copy_result.returncode == 0 and stitched_video.exists():
|
| 1572 |
+
return stitched_video
|
| 1573 |
+
|
| 1574 |
+
reencode_cmd = [
|
| 1575 |
+
ffmpeg_bin,
|
| 1576 |
+
"-hide_banner",
|
| 1577 |
+
"-loglevel",
|
| 1578 |
+
"error",
|
| 1579 |
+
"-y",
|
| 1580 |
+
"-f",
|
| 1581 |
+
"concat",
|
| 1582 |
+
"-safe",
|
| 1583 |
+
"0",
|
| 1584 |
+
"-i",
|
| 1585 |
+
str(concat_list),
|
| 1586 |
+
"-an",
|
| 1587 |
+
"-c:v",
|
| 1588 |
+
"libx264",
|
| 1589 |
+
"-pix_fmt",
|
| 1590 |
+
"yuv420p",
|
| 1591 |
+
str(stitched_video),
|
| 1592 |
+
]
|
| 1593 |
+
reencode_result = subprocess.run(reencode_cmd, capture_output=True, text=True)
|
| 1594 |
+
if reencode_result.returncode == 0 and stitched_video.exists():
|
| 1595 |
+
return stitched_video
|
| 1596 |
+
|
| 1597 |
+
raise RuntimeError(
|
| 1598 |
+
"ffmpeg failed to stitch the segments.\n"
|
| 1599 |
+
f"copy stderr: {copy_result.stderr.strip()}\n"
|
| 1600 |
+
f"reencode stderr: {reencode_result.stderr.strip()}"
|
| 1601 |
+
)
|
| 1602 |
+
|
| 1603 |
+
|
| 1604 |
+
def build_global_video_inputs(
|
| 1605 |
+
uuid: str,
|
| 1606 |
+
segments: list[SegmentInfo],
|
| 1607 |
+
temp_dir: Path,
|
| 1608 |
+
ffmpeg_bin: str,
|
| 1609 |
+
) -> list[Path]:
|
| 1610 |
+
if len(segments) == 1:
|
| 1611 |
+
return [segments[0].path]
|
| 1612 |
+
try:
|
| 1613 |
+
return [stitch_segments(uuid, segments, temp_dir, ffmpeg_bin)]
|
| 1614 |
+
except Exception as exc:
|
| 1615 |
+
logging.warning(
|
| 1616 |
+
"Falling back to ordered segment inputs for %s because stitching failed: %s",
|
| 1617 |
+
uuid,
|
| 1618 |
+
exc,
|
| 1619 |
+
)
|
| 1620 |
+
return [segment.path for segment in segments]
|
| 1621 |
+
|
| 1622 |
+
|
| 1623 |
+
def coerce_context_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
| 1624 |
+
subject_registry = []
|
| 1625 |
+
for item in payload.get("subject_registry", []):
|
| 1626 |
+
if not isinstance(item, dict):
|
| 1627 |
+
continue
|
| 1628 |
+
term = normalize_whitespace(item.get("term"))
|
| 1629 |
+
if not term:
|
| 1630 |
+
continue
|
| 1631 |
+
subject_registry.append(
|
| 1632 |
+
{
|
| 1633 |
+
"subject_id": normalize_whitespace(item.get("subject_id")) or f"subject_{len(subject_registry) + 1}",
|
| 1634 |
+
"category": normalize_subject_category(item.get("category")),
|
| 1635 |
+
"term": term,
|
| 1636 |
+
"profile": normalize_whitespace(item.get("profile")),
|
| 1637 |
+
}
|
| 1638 |
+
)
|
| 1639 |
+
return {
|
| 1640 |
+
"is_sports": coerce_bool(payload.get("is_sports")),
|
| 1641 |
+
"has_animal": coerce_bool(payload.get("has_animal")),
|
| 1642 |
+
"is_cooking": coerce_bool(payload.get("is_cooking")),
|
| 1643 |
+
"subject_registry": subject_registry,
|
| 1644 |
+
"stable_scene_summary": normalize_whitespace(payload.get("stable_scene_summary")),
|
| 1645 |
+
"stable_camera_summary": normalize_whitespace(payload.get("stable_camera_summary")),
|
| 1646 |
+
}
|
| 1647 |
+
|
| 1648 |
+
|
| 1649 |
+
def event_camera_output_needs_repair(payload: dict[str, Any]) -> bool:
|
| 1650 |
+
has_camera_motion = coerce_bool(payload.get("has_camera_motion"))
|
| 1651 |
+
camera_motion_desc = normalize_camera_motion_surface_text(payload.get("camera_motion_desc"))
|
| 1652 |
+
return has_camera_motion and not camera_motion_desc
|
| 1653 |
+
|
| 1654 |
+
|
| 1655 |
+
def coerce_event_payload(
|
| 1656 |
+
payload: dict[str, Any],
|
| 1657 |
+
segment: SegmentInfo,
|
| 1658 |
+
event_index: int,
|
| 1659 |
+
context: dict[str, Any],
|
| 1660 |
+
) -> dict[str, Any]:
|
| 1661 |
+
camera_motion_label = normalize_camera_motion_label(payload.get("camera_motion_label"))
|
| 1662 |
+
camera_motion_desc = normalize_camera_motion_surface_text(payload.get("camera_motion_desc"))
|
| 1663 |
+
has_camera_motion = coerce_bool(payload.get("has_camera_motion"))
|
| 1664 |
+
if camera_motion_label:
|
| 1665 |
+
if not camera_motion_desc:
|
| 1666 |
+
camera_motion_desc = describe_camera_motion(camera_motion_label)
|
| 1667 |
+
has_camera_motion = True
|
| 1668 |
+
elif has_camera_motion and camera_motion_desc:
|
| 1669 |
+
pass
|
| 1670 |
+
elif has_camera_motion:
|
| 1671 |
+
camera_motion_desc = "The framing remains relatively stable while the camera follows the subject."
|
| 1672 |
+
else:
|
| 1673 |
+
camera_motion_desc = ""
|
| 1674 |
+
has_camera_motion = False
|
| 1675 |
+
|
| 1676 |
+
has_focus_shift = None if event_index == 1 else coerce_optional_bool(payload.get("has_focus_shift"))
|
| 1677 |
+
if event_index != 1 and has_camera_motion:
|
| 1678 |
+
has_focus_shift = False
|
| 1679 |
+
if event_index != 1 and has_focus_shift is None:
|
| 1680 |
+
has_focus_shift = False
|
| 1681 |
+
|
| 1682 |
+
event = {
|
| 1683 |
+
"event_id": event_index,
|
| 1684 |
+
"start_time": round(segment.start_time, 3),
|
| 1685 |
+
"end_time": round(segment.end_time, 3),
|
| 1686 |
+
"duration": round(segment.duration, 3),
|
| 1687 |
+
"caption": normalize_whitespace(payload.get("caption")),
|
| 1688 |
+
"filename": segment.path.name,
|
| 1689 |
+
"has_appearance": coerce_bool(payload.get("has_appearance")),
|
| 1690 |
+
"has_disappearance": coerce_bool(payload.get("has_disappearance")),
|
| 1691 |
+
"has_camera_motion": has_camera_motion,
|
| 1692 |
+
"has_focus_shift": has_focus_shift,
|
| 1693 |
+
"is_multi_person": coerce_bool(payload.get("is_multi_person")),
|
| 1694 |
+
"has_environmental_change": coerce_bool(payload.get("has_environmental_change")),
|
| 1695 |
+
"has_occlusion": coerce_bool(payload.get("has_occlusion")),
|
| 1696 |
+
"has_lighting_change": coerce_bool(payload.get("has_lighting_change")),
|
| 1697 |
+
"has_animal": coerce_bool(payload.get("has_animal"), default=context.get("has_animal", False)),
|
| 1698 |
+
"is_cooking": coerce_bool(payload.get("is_cooking"), default=context.get("is_cooking", False)),
|
| 1699 |
+
"focus_object": normalize_focus_object(payload.get("focus_object"), context.get("subject_registry", [])),
|
| 1700 |
+
"camera_motion_desc": camera_motion_desc,
|
| 1701 |
+
"camera_motion_label": camera_motion_label,
|
| 1702 |
+
}
|
| 1703 |
+
|
| 1704 |
+
if not event["caption"]:
|
| 1705 |
+
raise ValueError(f"Model returned an empty caption for {segment.path.name}")
|
| 1706 |
+
if event["has_camera_motion"]:
|
| 1707 |
+
event["has_environmental_change"] = True
|
| 1708 |
+
return event
|
| 1709 |
+
|
| 1710 |
+
|
| 1711 |
+
def global_camera_output_needs_repair(payload: dict[str, Any], events: list[dict[str, Any]]) -> bool:
|
| 1712 |
+
prefix = normalize_global_camera_prefix(payload.get("camera_movement_prefix"))
|
| 1713 |
+
label = normalize_camera_motion_label(payload.get("camera_movement_label"))
|
| 1714 |
+
description = normalize_camera_movement_description_output(
|
| 1715 |
+
payload.get("camera_movement_description")
|
| 1716 |
+
)
|
| 1717 |
+
if not description:
|
| 1718 |
+
return True
|
| 1719 |
+
if prefix and global_camera_conflicts_with_events(prefix, label, events):
|
| 1720 |
+
return True
|
| 1721 |
+
return False
|
| 1722 |
+
|
| 1723 |
+
|
| 1724 |
+
def subject_profile_needs_repair(payload: dict[str, Any]) -> bool:
|
| 1725 |
+
return not normalize_whitespace(payload.get("subject_profile"))
|
| 1726 |
+
|
| 1727 |
+
|
| 1728 |
+
def coerce_global_payload(
|
| 1729 |
+
payload: dict[str, Any],
|
| 1730 |
+
context: dict[str, Any],
|
| 1731 |
+
events: list[dict[str, Any]],
|
| 1732 |
+
) -> dict[str, Any]:
|
| 1733 |
+
derived_prefix, derived_label, derived_description = derive_global_camera_from_events(events)
|
| 1734 |
+
prefix = normalize_global_camera_prefix(payload.get("camera_movement_prefix"))
|
| 1735 |
+
label = normalize_camera_motion_label(payload.get("camera_movement_label"))
|
| 1736 |
+
model_description = normalize_camera_movement_description_output(
|
| 1737 |
+
payload.get("camera_movement_description")
|
| 1738 |
+
)
|
| 1739 |
+
if not prefix:
|
| 1740 |
+
prefix, label = derived_prefix, derived_label
|
| 1741 |
+
elif global_camera_conflicts_with_events(prefix, label, events):
|
| 1742 |
+
prefix, label = derived_prefix, derived_label
|
| 1743 |
+
elif prefix in {"static", "near-static"}:
|
| 1744 |
+
label = ""
|
| 1745 |
+
description = model_description or derived_description
|
| 1746 |
+
if not description:
|
| 1747 |
+
if prefix in {"static", "near-static"}:
|
| 1748 |
+
description = "The camera remains essentially static throughout the video."
|
| 1749 |
+
elif label:
|
| 1750 |
+
description = describe_camera_motion(label, scope="global")
|
| 1751 |
+
else:
|
| 1752 |
+
description = "The camera behavior remains visually consistent across the video."
|
| 1753 |
+
|
| 1754 |
+
global_prompt = {
|
| 1755 |
+
"background": normalize_whitespace(payload.get("background")),
|
| 1756 |
+
"theme": normalize_whitespace(payload.get("theme")),
|
| 1757 |
+
"style": normalize_whitespace(payload.get("style")),
|
| 1758 |
+
"shot_type": normalize_whitespace(payload.get("shot_type")),
|
| 1759 |
+
"camera_movement": compose_global_camera_movement(prefix, label, description),
|
| 1760 |
+
"lighting": normalize_whitespace(payload.get("lighting")),
|
| 1761 |
+
"atmosphere": normalize_whitespace(payload.get("atmosphere")),
|
| 1762 |
+
"subject_profile": normalize_whitespace(payload.get("subject_profile")),
|
| 1763 |
+
"short_caption": normalize_whitespace(payload.get("short_caption")),
|
| 1764 |
+
"middle_caption": normalize_whitespace(payload.get("middle_caption")),
|
| 1765 |
+
"long_caption": normalize_whitespace(payload.get("long_caption")),
|
| 1766 |
+
"detailed_caption": normalize_whitespace(payload.get("detailed_caption")),
|
| 1767 |
+
}
|
| 1768 |
+
if not global_prompt["subject_profile"]:
|
| 1769 |
+
global_prompt["subject_profile"] = fallback_subject_profile(context.get("subject_registry", []))
|
| 1770 |
+
return global_prompt
|
| 1771 |
+
|
| 1772 |
+
|
| 1773 |
+
def validate_caption_lengths(uuid: str, global_prompt: dict[str, Any]) -> None:
|
| 1774 |
+
ranges = {
|
| 1775 |
+
"short_caption": (10, 35),
|
| 1776 |
+
"middle_caption": (55, 120),
|
| 1777 |
+
"long_caption": (140, 260),
|
| 1778 |
+
"detailed_caption": (450, 900),
|
| 1779 |
+
}
|
| 1780 |
+
for key, (low, high) in ranges.items():
|
| 1781 |
+
count = word_count(global_prompt.get(key, ""))
|
| 1782 |
+
if count and not (low <= count <= high):
|
| 1783 |
+
logging.warning(
|
| 1784 |
+
"%s %s has %d words, outside the expected range %d-%d.",
|
| 1785 |
+
uuid,
|
| 1786 |
+
key,
|
| 1787 |
+
count,
|
| 1788 |
+
low,
|
| 1789 |
+
high,
|
| 1790 |
+
)
|
| 1791 |
+
|
| 1792 |
+
|
| 1793 |
+
def annotate_uuid(
|
| 1794 |
+
uuid: str,
|
| 1795 |
+
segments: list[SegmentInfo],
|
| 1796 |
+
runner: Qwen3VLRunner,
|
| 1797 |
+
camera_motion_guide: str,
|
| 1798 |
+
args: argparse.Namespace,
|
| 1799 |
+
) -> dict[str, Any]:
|
| 1800 |
+
temp_dir, temp_manager = create_uuid_temp_dir(uuid, args.temp_dir, args.keep_temp)
|
| 1801 |
+
try:
|
| 1802 |
+
global_video_inputs = build_global_video_inputs(
|
| 1803 |
+
uuid=uuid,
|
| 1804 |
+
segments=segments,
|
| 1805 |
+
temp_dir=temp_dir,
|
| 1806 |
+
ffmpeg_bin=args.ffmpeg_bin,
|
| 1807 |
+
)
|
| 1808 |
+
|
| 1809 |
+
logging.info("Running global context pass for %s", uuid)
|
| 1810 |
+
context_payload = runner.generate_json(
|
| 1811 |
+
video_paths=global_video_inputs,
|
| 1812 |
+
prompt=build_global_context_prompt(
|
| 1813 |
+
uuid=uuid,
|
| 1814 |
+
total_events=len(segments),
|
| 1815 |
+
camera_motion_guide=camera_motion_guide,
|
| 1816 |
+
),
|
| 1817 |
+
max_new_tokens=args.context_max_new_tokens,
|
| 1818 |
+
)
|
| 1819 |
+
context = coerce_context_payload(context_payload)
|
| 1820 |
+
|
| 1821 |
+
events: list[dict[str, Any]] = []
|
| 1822 |
+
previous_caption: str | None = None
|
| 1823 |
+
previous_focus_object: str | None = None
|
| 1824 |
+
for event_index, segment in enumerate(segments, start=1):
|
| 1825 |
+
logging.info(
|
| 1826 |
+
"Running event pass for %s (%d/%d): %s",
|
| 1827 |
+
uuid,
|
| 1828 |
+
event_index,
|
| 1829 |
+
len(segments),
|
| 1830 |
+
segment.path.name,
|
| 1831 |
+
)
|
| 1832 |
+
event_payload = runner.generate_json(
|
| 1833 |
+
video_paths=[segment.path],
|
| 1834 |
+
prompt=build_event_prompt(
|
| 1835 |
+
uuid=uuid,
|
| 1836 |
+
event_index=event_index,
|
| 1837 |
+
total_events=len(segments),
|
| 1838 |
+
previous_caption=previous_caption,
|
| 1839 |
+
previous_focus_object=previous_focus_object,
|
| 1840 |
+
context=context,
|
| 1841 |
+
camera_motion_guide=camera_motion_guide,
|
| 1842 |
+
),
|
| 1843 |
+
max_new_tokens=args.event_max_new_tokens,
|
| 1844 |
+
)
|
| 1845 |
+
if event_camera_output_needs_repair(event_payload):
|
| 1846 |
+
for attempt in (1, 2):
|
| 1847 |
+
logging.info(
|
| 1848 |
+
"Repairing event camera fields for %s event %d (attempt %d)",
|
| 1849 |
+
uuid,
|
| 1850 |
+
event_index,
|
| 1851 |
+
attempt,
|
| 1852 |
+
)
|
| 1853 |
+
try:
|
| 1854 |
+
repaired_camera_payload = runner.generate_json(
|
| 1855 |
+
video_paths=[segment.path],
|
| 1856 |
+
prompt=build_event_camera_motion_repair_prompt(
|
| 1857 |
+
uuid=uuid,
|
| 1858 |
+
event_index=event_index,
|
| 1859 |
+
total_events=len(segments),
|
| 1860 |
+
draft_payload=event_payload,
|
| 1861 |
+
context=context,
|
| 1862 |
+
camera_motion_guide=camera_motion_guide,
|
| 1863 |
+
attempt=attempt,
|
| 1864 |
+
),
|
| 1865 |
+
max_new_tokens=min(args.event_max_new_tokens, 512),
|
| 1866 |
+
)
|
| 1867 |
+
for key in ("has_camera_motion", "camera_motion_label", "camera_motion_desc"):
|
| 1868 |
+
if key in repaired_camera_payload:
|
| 1869 |
+
event_payload[key] = repaired_camera_payload[key]
|
| 1870 |
+
if not event_camera_output_needs_repair(event_payload):
|
| 1871 |
+
break
|
| 1872 |
+
except Exception as exc:
|
| 1873 |
+
logging.warning(
|
| 1874 |
+
"Event camera repair failed for %s event %d on attempt %d: %s",
|
| 1875 |
+
uuid,
|
| 1876 |
+
event_index,
|
| 1877 |
+
attempt,
|
| 1878 |
+
exc,
|
| 1879 |
+
)
|
| 1880 |
+
event = coerce_event_payload(
|
| 1881 |
+
payload=event_payload,
|
| 1882 |
+
segment=segment,
|
| 1883 |
+
event_index=event_index,
|
| 1884 |
+
context=context,
|
| 1885 |
+
)
|
| 1886 |
+
if previous_caption and not context.get("is_sports", False):
|
| 1887 |
+
if normalized_caption_key(event["caption"]) == normalized_caption_key(previous_caption):
|
| 1888 |
+
for attempt in (1, 2):
|
| 1889 |
+
logging.info(
|
| 1890 |
+
"Refining near-duplicate event caption for %s event %d (attempt %d)",
|
| 1891 |
+
uuid,
|
| 1892 |
+
event_index,
|
| 1893 |
+
attempt,
|
| 1894 |
+
)
|
| 1895 |
+
try:
|
| 1896 |
+
refined_payload = runner.generate_json(
|
| 1897 |
+
video_paths=[segment.path],
|
| 1898 |
+
prompt=build_event_caption_refine_prompt(
|
| 1899 |
+
uuid=uuid,
|
| 1900 |
+
event_index=event_index,
|
| 1901 |
+
total_events=len(segments),
|
| 1902 |
+
previous_caption=previous_caption,
|
| 1903 |
+
draft_caption=event["caption"],
|
| 1904 |
+
context=context,
|
| 1905 |
+
attempt=attempt,
|
| 1906 |
+
),
|
| 1907 |
+
max_new_tokens=min(args.event_max_new_tokens, 768),
|
| 1908 |
+
)
|
| 1909 |
+
refined_caption = normalize_whitespace(refined_payload.get("caption"))
|
| 1910 |
+
if refined_caption:
|
| 1911 |
+
event["caption"] = refined_caption
|
| 1912 |
+
if normalized_caption_key(event["caption"]) != normalized_caption_key(previous_caption):
|
| 1913 |
+
break
|
| 1914 |
+
except Exception as exc:
|
| 1915 |
+
logging.warning(
|
| 1916 |
+
"Caption refinement failed for %s event %d on attempt %d: %s",
|
| 1917 |
+
uuid,
|
| 1918 |
+
event_index,
|
| 1919 |
+
attempt,
|
| 1920 |
+
exc,
|
| 1921 |
+
)
|
| 1922 |
+
event["caption"] = disambiguate_repeated_caption(
|
| 1923 |
+
current_caption=event["caption"],
|
| 1924 |
+
previous_caption=previous_caption,
|
| 1925 |
+
event=event,
|
| 1926 |
+
)
|
| 1927 |
+
events.append(event)
|
| 1928 |
+
previous_caption = event["caption"]
|
| 1929 |
+
previous_focus_object = event["focus_object"]
|
| 1930 |
+
|
| 1931 |
+
logging.info("Running final global prompt pass for %s", uuid)
|
| 1932 |
+
global_payload = runner.generate_json(
|
| 1933 |
+
video_paths=global_video_inputs,
|
| 1934 |
+
prompt=build_global_refine_prompt(
|
| 1935 |
+
uuid=uuid,
|
| 1936 |
+
context=context,
|
| 1937 |
+
events=events,
|
| 1938 |
+
),
|
| 1939 |
+
max_new_tokens=args.global_max_new_tokens,
|
| 1940 |
+
)
|
| 1941 |
+
derived_prefix, derived_label, derived_description = derive_global_camera_from_events(events)
|
| 1942 |
+
if global_camera_output_needs_repair(global_payload, events):
|
| 1943 |
+
for attempt in (1, 2):
|
| 1944 |
+
logging.info(
|
| 1945 |
+
"Repairing global camera fields for %s (attempt %d)",
|
| 1946 |
+
uuid,
|
| 1947 |
+
attempt,
|
| 1948 |
+
)
|
| 1949 |
+
try:
|
| 1950 |
+
repaired_global_camera_payload = runner.generate_json(
|
| 1951 |
+
video_paths=global_video_inputs,
|
| 1952 |
+
prompt=build_global_camera_repair_prompt(
|
| 1953 |
+
uuid=uuid,
|
| 1954 |
+
context=context,
|
| 1955 |
+
events=events,
|
| 1956 |
+
draft_payload=global_payload,
|
| 1957 |
+
derived_prefix=derived_prefix,
|
| 1958 |
+
derived_label=derived_label,
|
| 1959 |
+
derived_description=derived_description,
|
| 1960 |
+
attempt=attempt,
|
| 1961 |
+
),
|
| 1962 |
+
max_new_tokens=min(args.global_max_new_tokens, 768),
|
| 1963 |
+
)
|
| 1964 |
+
for key in (
|
| 1965 |
+
"camera_movement_prefix",
|
| 1966 |
+
"camera_movement_label",
|
| 1967 |
+
"camera_movement_description",
|
| 1968 |
+
):
|
| 1969 |
+
if key in repaired_global_camera_payload:
|
| 1970 |
+
global_payload[key] = repaired_global_camera_payload[key]
|
| 1971 |
+
if not global_camera_output_needs_repair(global_payload, events):
|
| 1972 |
+
break
|
| 1973 |
+
except Exception as exc:
|
| 1974 |
+
logging.warning(
|
| 1975 |
+
"Global camera repair failed for %s on attempt %d: %s",
|
| 1976 |
+
uuid,
|
| 1977 |
+
attempt,
|
| 1978 |
+
exc,
|
| 1979 |
+
)
|
| 1980 |
+
if subject_profile_needs_repair(global_payload):
|
| 1981 |
+
for attempt in (1, 2):
|
| 1982 |
+
logging.info(
|
| 1983 |
+
"Repairing subject_profile for %s (attempt %d)",
|
| 1984 |
+
uuid,
|
| 1985 |
+
attempt,
|
| 1986 |
+
)
|
| 1987 |
+
try:
|
| 1988 |
+
repaired_subject_profile_payload = runner.generate_json(
|
| 1989 |
+
video_paths=global_video_inputs,
|
| 1990 |
+
prompt=build_subject_profile_repair_prompt(
|
| 1991 |
+
uuid=uuid,
|
| 1992 |
+
context=context,
|
| 1993 |
+
events=events,
|
| 1994 |
+
draft_payload=global_payload,
|
| 1995 |
+
attempt=attempt,
|
| 1996 |
+
),
|
| 1997 |
+
max_new_tokens=min(args.global_max_new_tokens, 768),
|
| 1998 |
+
)
|
| 1999 |
+
if "subject_profile" in repaired_subject_profile_payload:
|
| 2000 |
+
global_payload["subject_profile"] = repaired_subject_profile_payload["subject_profile"]
|
| 2001 |
+
if not subject_profile_needs_repair(global_payload):
|
| 2002 |
+
break
|
| 2003 |
+
except Exception as exc:
|
| 2004 |
+
logging.warning(
|
| 2005 |
+
"subject_profile repair failed for %s on attempt %d: %s",
|
| 2006 |
+
uuid,
|
| 2007 |
+
attempt,
|
| 2008 |
+
exc,
|
| 2009 |
+
)
|
| 2010 |
+
global_prompt = coerce_global_payload(global_payload, context=context, events=events)
|
| 2011 |
+
validate_caption_lengths(uuid, global_prompt)
|
| 2012 |
+
|
| 2013 |
+
return {
|
| 2014 |
+
"uuid": uuid,
|
| 2015 |
+
"total_events": len(events),
|
| 2016 |
+
"global_prompt": global_prompt,
|
| 2017 |
+
"events": events,
|
| 2018 |
+
}
|
| 2019 |
+
finally:
|
| 2020 |
+
if temp_manager is not None:
|
| 2021 |
+
temp_manager.cleanup()
|
| 2022 |
+
|
| 2023 |
+
|
| 2024 |
+
def main() -> int:
|
| 2025 |
+
args = parse_args()
|
| 2026 |
+
setup_logging(args.log_level)
|
| 2027 |
+
|
| 2028 |
+
input_path = Path(args.input).expanduser().resolve()
|
| 2029 |
+
output_path = Path(args.output).expanduser().resolve()
|
| 2030 |
+
model_path = Path(args.model_path).expanduser().resolve()
|
| 2031 |
+
camera_motion_guide_path = Path(args.camera_motion_guide).expanduser().resolve()
|
| 2032 |
+
|
| 2033 |
+
suffixes = parse_video_suffixes(args.video_suffixes)
|
| 2034 |
+
allow_uuids = load_uuid_allow_list(args.uuids, args.uuids_file)
|
| 2035 |
+
camera_motion_guide = load_camera_motion_guide(camera_motion_guide_path)
|
| 2036 |
+
|
| 2037 |
+
groups = collect_segment_groups(
|
| 2038 |
+
input_path=input_path,
|
| 2039 |
+
recursive=args.recursive,
|
| 2040 |
+
suffixes=suffixes,
|
| 2041 |
+
allow_uuids=allow_uuids,
|
| 2042 |
+
)
|
| 2043 |
+
if not groups:
|
| 2044 |
+
raise RuntimeError("No valid segmented videos were found.")
|
| 2045 |
+
|
| 2046 |
+
uuids = list(groups)
|
| 2047 |
+
if args.limit is not None:
|
| 2048 |
+
uuids = uuids[: args.limit]
|
| 2049 |
+
|
| 2050 |
+
pending_for_print = uuids
|
| 2051 |
+
if args.resume and output_path.exists():
|
| 2052 |
+
existing_videos_for_print = load_existing_output(
|
| 2053 |
+
output_path=output_path,
|
| 2054 |
+
overwrite=False,
|
| 2055 |
+
resume=True,
|
| 2056 |
+
)
|
| 2057 |
+
pending_for_print = [uuid for uuid in uuids if uuid not in existing_videos_for_print]
|
| 2058 |
+
|
| 2059 |
+
if args.print_uuids_json:
|
| 2060 |
+
print(json.dumps(pending_for_print, ensure_ascii=False))
|
| 2061 |
+
return 0
|
| 2062 |
+
|
| 2063 |
+
uuids = apply_uuid_shard(
|
| 2064 |
+
uuids=pending_for_print if args.resume else uuids,
|
| 2065 |
+
num_shards=args.num_shards,
|
| 2066 |
+
shard_index=args.shard_index,
|
| 2067 |
+
)
|
| 2068 |
+
|
| 2069 |
+
logging.info("Discovered %d UUID groups.", len(uuids))
|
| 2070 |
+
for uuid in uuids:
|
| 2071 |
+
logging.info("UUID %s has %d segments.", uuid, len(groups[uuid]))
|
| 2072 |
+
|
| 2073 |
+
if args.dry_run:
|
| 2074 |
+
logging.info("Dry run complete. No model was loaded.")
|
| 2075 |
+
return 0
|
| 2076 |
+
|
| 2077 |
+
existing_videos = load_existing_output(
|
| 2078 |
+
output_path=output_path,
|
| 2079 |
+
overwrite=args.overwrite,
|
| 2080 |
+
resume=args.resume,
|
| 2081 |
+
)
|
| 2082 |
+
pending_uuids = [uuid for uuid in uuids if uuid not in existing_videos]
|
| 2083 |
+
if not pending_uuids:
|
| 2084 |
+
logging.info("Nothing to do. All requested UUIDs already exist in %s.", output_path)
|
| 2085 |
+
return 0
|
| 2086 |
+
|
| 2087 |
+
if not model_path.exists():
|
| 2088 |
+
raise FileNotFoundError(
|
| 2089 |
+
f"Model path does not exist: {model_path}. Point --model-path to the local Qwen3-VL checkpoint directory."
|
| 2090 |
+
)
|
| 2091 |
+
|
| 2092 |
+
logging.info("Loading model from %s", model_path)
|
| 2093 |
+
runner = Qwen3VLRunner(
|
| 2094 |
+
model_path=model_path,
|
| 2095 |
+
device_map=args.device_map,
|
| 2096 |
+
dtype=args.dtype,
|
| 2097 |
+
attn_implementation=args.attn_implementation,
|
| 2098 |
+
trust_remote_code=args.trust_remote_code,
|
| 2099 |
+
fps=args.fps,
|
| 2100 |
+
max_pixels=args.max_pixels,
|
| 2101 |
+
temperature=args.temperature,
|
| 2102 |
+
top_p=args.top_p,
|
| 2103 |
+
top_k=args.top_k,
|
| 2104 |
+
repetition_penalty=args.repetition_penalty,
|
| 2105 |
+
greedy=args.greedy,
|
| 2106 |
+
)
|
| 2107 |
+
|
| 2108 |
+
failures: list[str] = []
|
| 2109 |
+
for index, uuid in enumerate(pending_uuids, start=1):
|
| 2110 |
+
logging.info("Processing UUID %s (%d/%d)", uuid, index, len(pending_uuids))
|
| 2111 |
+
try:
|
| 2112 |
+
video_payload = annotate_uuid(
|
| 2113 |
+
uuid=uuid,
|
| 2114 |
+
segments=groups[uuid],
|
| 2115 |
+
runner=runner,
|
| 2116 |
+
camera_motion_guide=camera_motion_guide,
|
| 2117 |
+
args=args,
|
| 2118 |
+
)
|
| 2119 |
+
existing_videos[uuid] = video_payload
|
| 2120 |
+
write_output(output_path, existing_videos)
|
| 2121 |
+
logging.info("Wrote %s", output_path)
|
| 2122 |
+
except Exception as exc:
|
| 2123 |
+
if not args.continue_on_error:
|
| 2124 |
+
raise
|
| 2125 |
+
logging.exception("Failed to process %s: %s", uuid, exc)
|
| 2126 |
+
failures.append(uuid)
|
| 2127 |
+
|
| 2128 |
+
if failures:
|
| 2129 |
+
logging.error("Completed with failures: %s", ", ".join(failures))
|
| 2130 |
+
return 1
|
| 2131 |
+
logging.info("Finished %d UUIDs.", len(pending_uuids))
|
| 2132 |
+
return 0
|
| 2133 |
+
|
| 2134 |
+
|
| 2135 |
+
if __name__ == "__main__":
|
| 2136 |
+
sys.exit(main())
|
qwen/segment_events_qwen3vl.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import ast
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
import subprocess
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def parse_args() -> argparse.Namespace:
|
| 14 |
+
parser = argparse.ArgumentParser(
|
| 15 |
+
description="Use Qwen3-VL to segment one video into consecutive events."
|
| 16 |
+
)
|
| 17 |
+
parser.add_argument("video", help="Path to the input video.")
|
| 18 |
+
parser.add_argument(
|
| 19 |
+
"--model-path",
|
| 20 |
+
default="Qwen/Qwen3-VL-32B-Instruct",
|
| 21 |
+
help="Local checkpoint path or Hugging Face model id.",
|
| 22 |
+
)
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
"--output",
|
| 25 |
+
default=None,
|
| 26 |
+
help="Optional JSON output path. If omitted, prints JSON to stdout.",
|
| 27 |
+
)
|
| 28 |
+
parser.add_argument("--fps", type=float, default=1.0, help="Video sampling FPS.")
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"--max-pixels",
|
| 31 |
+
type=int,
|
| 32 |
+
default=360000,
|
| 33 |
+
help="Optional Qwen video processor max_pixels hint. Use 0 to disable.",
|
| 34 |
+
)
|
| 35 |
+
parser.add_argument(
|
| 36 |
+
"--max-new-tokens",
|
| 37 |
+
type=int,
|
| 38 |
+
default=1024,
|
| 39 |
+
help="Max new tokens for the model response.",
|
| 40 |
+
)
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
"--device-map",
|
| 43 |
+
default="auto",
|
| 44 |
+
help="Transformers device_map argument.",
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--dtype",
|
| 48 |
+
default="bfloat16",
|
| 49 |
+
choices=["auto", "float16", "bfloat16", "float32"],
|
| 50 |
+
help="Torch dtype for model loading.",
|
| 51 |
+
)
|
| 52 |
+
parser.add_argument(
|
| 53 |
+
"--attn-implementation",
|
| 54 |
+
default="",
|
| 55 |
+
help='Optional attn_implementation, e.g. "flash_attention_2". Empty disables it.',
|
| 56 |
+
)
|
| 57 |
+
parser.add_argument(
|
| 58 |
+
"--temperature",
|
| 59 |
+
type=float,
|
| 60 |
+
default=0.0,
|
| 61 |
+
help="Sampling temperature. 0 uses greedy decoding.",
|
| 62 |
+
)
|
| 63 |
+
parser.add_argument(
|
| 64 |
+
"--ffprobe-bin",
|
| 65 |
+
default="ffprobe",
|
| 66 |
+
help="ffprobe executable used to read video duration.",
|
| 67 |
+
)
|
| 68 |
+
parser.set_defaults(trust_remote_code=True)
|
| 69 |
+
parser.add_argument(
|
| 70 |
+
"--no-trust-remote-code",
|
| 71 |
+
dest="trust_remote_code",
|
| 72 |
+
action="store_false",
|
| 73 |
+
help="Disable trust_remote_code for model and processor loading.",
|
| 74 |
+
)
|
| 75 |
+
return parser.parse_args()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def probe_duration(video_path: Path, ffprobe_bin: str) -> float | None:
|
| 79 |
+
try:
|
| 80 |
+
result = subprocess.run(
|
| 81 |
+
[
|
| 82 |
+
ffprobe_bin,
|
| 83 |
+
"-v",
|
| 84 |
+
"error",
|
| 85 |
+
"-show_entries",
|
| 86 |
+
"format=duration",
|
| 87 |
+
"-of",
|
| 88 |
+
"default=noprint_wrappers=1:nokey=1",
|
| 89 |
+
str(video_path),
|
| 90 |
+
],
|
| 91 |
+
check=True,
|
| 92 |
+
capture_output=True,
|
| 93 |
+
text=True,
|
| 94 |
+
)
|
| 95 |
+
except (FileNotFoundError, subprocess.CalledProcessError):
|
| 96 |
+
return None
|
| 97 |
+
try:
|
| 98 |
+
duration = float(result.stdout.strip())
|
| 99 |
+
except ValueError:
|
| 100 |
+
return None
|
| 101 |
+
return round(duration, 3) if duration > 0 else None
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def extract_json_text(raw_text: str) -> str:
|
| 105 |
+
text = raw_text.strip()
|
| 106 |
+
fenced = re.findall(r"```(?:json)?\s*(.*?)```", text, flags=re.DOTALL | re.I)
|
| 107 |
+
candidates = [item.strip() for item in fenced if item.strip()]
|
| 108 |
+
candidates.append(text)
|
| 109 |
+
for candidate in candidates:
|
| 110 |
+
if candidate.startswith("{") and candidate.endswith("}"):
|
| 111 |
+
return candidate
|
| 112 |
+
|
| 113 |
+
start = text.find("{")
|
| 114 |
+
if start < 0:
|
| 115 |
+
raise ValueError(f"No JSON object found in model output: {text[:300]}")
|
| 116 |
+
|
| 117 |
+
depth = 0
|
| 118 |
+
in_string = False
|
| 119 |
+
escape = False
|
| 120 |
+
for index in range(start, len(text)):
|
| 121 |
+
char = text[index]
|
| 122 |
+
if in_string:
|
| 123 |
+
if escape:
|
| 124 |
+
escape = False
|
| 125 |
+
elif char == "\\":
|
| 126 |
+
escape = True
|
| 127 |
+
elif char == '"':
|
| 128 |
+
in_string = False
|
| 129 |
+
continue
|
| 130 |
+
if char == '"':
|
| 131 |
+
in_string = True
|
| 132 |
+
elif char == "{":
|
| 133 |
+
depth += 1
|
| 134 |
+
elif char == "}":
|
| 135 |
+
depth -= 1
|
| 136 |
+
if depth == 0:
|
| 137 |
+
return text[start : index + 1]
|
| 138 |
+
raise ValueError(f"Unclosed JSON object in model output: {text[:300]}")
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def parse_json_payload(raw_text: str) -> dict[str, Any]:
|
| 142 |
+
json_text = extract_json_text(raw_text)
|
| 143 |
+
try:
|
| 144 |
+
payload = json.loads(json_text)
|
| 145 |
+
except json.JSONDecodeError:
|
| 146 |
+
payload = ast.literal_eval(json_text)
|
| 147 |
+
if not isinstance(payload, dict):
|
| 148 |
+
raise ValueError(f"Expected a JSON object, got {type(payload).__name__}.")
|
| 149 |
+
return payload
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def coerce_float(value: Any, field_name: str) -> float:
|
| 153 |
+
if isinstance(value, str):
|
| 154 |
+
value = value.strip().rstrip("s")
|
| 155 |
+
try:
|
| 156 |
+
return round(float(value), 3)
|
| 157 |
+
except (TypeError, ValueError) as exc:
|
| 158 |
+
raise ValueError(f"Invalid {field_name}: {value!r}") from exc
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def build_prompt(duration: float | None) -> str:
|
| 162 |
+
duration_line = (
|
| 163 |
+
f"The video duration is approximately {duration:.3f} seconds."
|
| 164 |
+
if duration is not None
|
| 165 |
+
else "The video duration is not provided; infer timestamps in seconds from the video timeline."
|
| 166 |
+
)
|
| 167 |
+
return f"""
|
| 168 |
+
You are segmenting a single video into consecutive semantic events.
|
| 169 |
+
|
| 170 |
+
{duration_line}
|
| 171 |
+
|
| 172 |
+
Definition of an event:
|
| 173 |
+
- An event is a continuous temporal interval with one dominant visible action, interaction, camera-framing state, or meaningful scene/object state.
|
| 174 |
+
- Split when the dominant action changes, a new subject/object appears or disappears, the focus changes materially, or the scene state changes enough that a separate event caption would be needed.
|
| 175 |
+
- Do not over-segment tiny pose changes, ordinary motion within the same action, or brief camera shake.
|
| 176 |
+
- Do not leave gaps between events.
|
| 177 |
+
- Events must be chronological and non-overlapping.
|
| 178 |
+
- The first event should begin at 0.0 seconds.
|
| 179 |
+
- If the duration is known, the last event should end at the video duration.
|
| 180 |
+
- Use seconds as numbers, not strings.
|
| 181 |
+
- Include a short description for each event so the boundary decision is inspectable.
|
| 182 |
+
|
| 183 |
+
Return strict JSON only. Do not use markdown fences.
|
| 184 |
+
|
| 185 |
+
Return JSON in exactly this schema:
|
| 186 |
+
{{
|
| 187 |
+
"event_count": 3,
|
| 188 |
+
"events": [
|
| 189 |
+
{{
|
| 190 |
+
"event_id": 1,
|
| 191 |
+
"begin_time": 0.0,
|
| 192 |
+
"end_time": 2.5,
|
| 193 |
+
"description": "The first visible event in one concise sentence."
|
| 194 |
+
}},
|
| 195 |
+
{{
|
| 196 |
+
"event_id": 2,
|
| 197 |
+
"begin_time": 2.5,
|
| 198 |
+
"end_time": 5.0,
|
| 199 |
+
"description": "The second visible event in one concise sentence."
|
| 200 |
+
}}
|
| 201 |
+
]
|
| 202 |
+
}}
|
| 203 |
+
""".strip()
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def normalize_events(payload: dict[str, Any], duration: float | None) -> dict[str, Any]:
|
| 207 |
+
raw_events = payload.get("events")
|
| 208 |
+
if not isinstance(raw_events, list) or not raw_events:
|
| 209 |
+
raise ValueError("Model output must contain a non-empty events list.")
|
| 210 |
+
|
| 211 |
+
events: list[dict[str, Any]] = []
|
| 212 |
+
for index, item in enumerate(raw_events, start=1):
|
| 213 |
+
if not isinstance(item, dict):
|
| 214 |
+
raise ValueError(f"Event {index} is not an object.")
|
| 215 |
+
begin_time = coerce_float(item.get("begin_time"), "begin_time")
|
| 216 |
+
end_time = coerce_float(item.get("end_time"), "end_time")
|
| 217 |
+
if duration is not None:
|
| 218 |
+
begin_time = min(max(begin_time, 0.0), duration)
|
| 219 |
+
end_time = min(max(end_time, 0.0), duration)
|
| 220 |
+
if end_time <= begin_time:
|
| 221 |
+
raise ValueError(
|
| 222 |
+
f"Event {index} has non-positive duration: {begin_time} to {end_time}"
|
| 223 |
+
)
|
| 224 |
+
description = re.sub(
|
| 225 |
+
r"\s+", " ", str(item.get("description", "")).strip()
|
| 226 |
+
)
|
| 227 |
+
events.append(
|
| 228 |
+
{
|
| 229 |
+
"event_id": index,
|
| 230 |
+
"begin_time": begin_time,
|
| 231 |
+
"end_time": end_time,
|
| 232 |
+
"description": description,
|
| 233 |
+
}
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
events.sort(key=lambda item: (item["begin_time"], item["end_time"]))
|
| 237 |
+
for index, event in enumerate(events, start=1):
|
| 238 |
+
event["event_id"] = index
|
| 239 |
+
|
| 240 |
+
if events[0]["begin_time"] != 0.0:
|
| 241 |
+
events[0]["begin_time"] = 0.0
|
| 242 |
+
if duration is not None:
|
| 243 |
+
events[-1]["end_time"] = duration
|
| 244 |
+
|
| 245 |
+
return {
|
| 246 |
+
"event_count": len(events),
|
| 247 |
+
"events": events,
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class Qwen3VLRunner:
|
| 252 |
+
def __init__(
|
| 253 |
+
self,
|
| 254 |
+
model_path: str,
|
| 255 |
+
device_map: str,
|
| 256 |
+
dtype: str,
|
| 257 |
+
attn_implementation: str,
|
| 258 |
+
trust_remote_code: bool,
|
| 259 |
+
fps: float,
|
| 260 |
+
max_pixels: int,
|
| 261 |
+
temperature: float,
|
| 262 |
+
) -> None:
|
| 263 |
+
try:
|
| 264 |
+
import torch
|
| 265 |
+
from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
|
| 266 |
+
except ModuleNotFoundError as exc:
|
| 267 |
+
raise RuntimeError(
|
| 268 |
+
"Missing dependencies. Install torch, transformers, and preferably qwen-vl-utils."
|
| 269 |
+
) from exc
|
| 270 |
+
|
| 271 |
+
self.torch = torch
|
| 272 |
+
self.temperature = temperature
|
| 273 |
+
self.fps = fps if fps > 0 else None
|
| 274 |
+
self.max_pixels = max_pixels if max_pixels > 0 else None
|
| 275 |
+
|
| 276 |
+
try:
|
| 277 |
+
from qwen_vl_utils import process_vision_info # type: ignore
|
| 278 |
+
except ModuleNotFoundError:
|
| 279 |
+
process_vision_info = None
|
| 280 |
+
self.process_vision_info = process_vision_info
|
| 281 |
+
|
| 282 |
+
dtype_map = {
|
| 283 |
+
"auto": "auto",
|
| 284 |
+
"float16": torch.float16,
|
| 285 |
+
"bfloat16": torch.bfloat16,
|
| 286 |
+
"float32": torch.float32,
|
| 287 |
+
}
|
| 288 |
+
load_kwargs: dict[str, Any] = {
|
| 289 |
+
"device_map": device_map,
|
| 290 |
+
"torch_dtype": dtype_map[dtype],
|
| 291 |
+
"trust_remote_code": trust_remote_code,
|
| 292 |
+
}
|
| 293 |
+
if attn_implementation:
|
| 294 |
+
load_kwargs["attn_implementation"] = attn_implementation
|
| 295 |
+
|
| 296 |
+
self.model = Qwen3VLForConditionalGeneration.from_pretrained(
|
| 297 |
+
model_path,
|
| 298 |
+
**load_kwargs,
|
| 299 |
+
)
|
| 300 |
+
self.processor = AutoProcessor.from_pretrained(
|
| 301 |
+
model_path,
|
| 302 |
+
trust_remote_code=trust_remote_code,
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
def _build_messages(self, video_path: Path, prompt: str) -> list[dict[str, Any]]:
|
| 306 |
+
video_item: dict[str, Any] = {
|
| 307 |
+
"type": "video",
|
| 308 |
+
"video": str(video_path.resolve()),
|
| 309 |
+
}
|
| 310 |
+
if self.fps is not None:
|
| 311 |
+
video_item["fps"] = self.fps
|
| 312 |
+
if self.max_pixels is not None:
|
| 313 |
+
video_item["max_pixels"] = self.max_pixels
|
| 314 |
+
return [
|
| 315 |
+
{
|
| 316 |
+
"role": "system",
|
| 317 |
+
"content": "You are a careful video event segmentation assistant. Return strict JSON only.",
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"role": "user",
|
| 321 |
+
"content": [video_item, {"type": "text", "text": prompt}],
|
| 322 |
+
},
|
| 323 |
+
]
|
| 324 |
+
|
| 325 |
+
def _prepare_inputs(self, messages: list[dict[str, Any]]):
|
| 326 |
+
if self.process_vision_info is not None:
|
| 327 |
+
text = self.processor.apply_chat_template(
|
| 328 |
+
messages,
|
| 329 |
+
tokenize=False,
|
| 330 |
+
add_generation_prompt=True,
|
| 331 |
+
)
|
| 332 |
+
image_inputs, video_inputs = self.process_vision_info(messages)
|
| 333 |
+
inputs = self.processor(
|
| 334 |
+
text=[text],
|
| 335 |
+
images=image_inputs,
|
| 336 |
+
videos=video_inputs,
|
| 337 |
+
padding=True,
|
| 338 |
+
return_tensors="pt",
|
| 339 |
+
)
|
| 340 |
+
else:
|
| 341 |
+
try:
|
| 342 |
+
inputs = self.processor.apply_chat_template(
|
| 343 |
+
messages,
|
| 344 |
+
tokenize=True,
|
| 345 |
+
add_generation_prompt=True,
|
| 346 |
+
return_dict=True,
|
| 347 |
+
return_tensors="pt",
|
| 348 |
+
)
|
| 349 |
+
except Exception as exc:
|
| 350 |
+
raise RuntimeError(
|
| 351 |
+
"Failed to prepare video inputs. Install qwen-vl-utils or use a transformers build with Qwen3-VL video chat support."
|
| 352 |
+
) from exc
|
| 353 |
+
return inputs.to(self.model.device)
|
| 354 |
+
|
| 355 |
+
def segment(self, video_path: Path, prompt: str, max_new_tokens: int) -> dict[str, Any]:
|
| 356 |
+
messages = self._build_messages(video_path, prompt)
|
| 357 |
+
inputs = self._prepare_inputs(messages)
|
| 358 |
+
generate_kwargs: dict[str, Any] = {"max_new_tokens": max_new_tokens}
|
| 359 |
+
if self.temperature and self.temperature > 0:
|
| 360 |
+
generate_kwargs.update({"do_sample": True, "temperature": self.temperature})
|
| 361 |
+
else:
|
| 362 |
+
generate_kwargs["do_sample"] = False
|
| 363 |
+
|
| 364 |
+
with self.torch.inference_mode():
|
| 365 |
+
generated_ids = self.model.generate(**inputs, **generate_kwargs)
|
| 366 |
+
generated_ids_trimmed = [
|
| 367 |
+
out_ids[len(in_ids) :]
|
| 368 |
+
for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 369 |
+
]
|
| 370 |
+
raw_text = self.processor.batch_decode(
|
| 371 |
+
generated_ids_trimmed,
|
| 372 |
+
skip_special_tokens=True,
|
| 373 |
+
clean_up_tokenization_spaces=False,
|
| 374 |
+
)[0]
|
| 375 |
+
return parse_json_payload(raw_text)
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def main() -> None:
|
| 379 |
+
args = parse_args()
|
| 380 |
+
video_path = Path(args.video).expanduser().resolve()
|
| 381 |
+
if not video_path.is_file():
|
| 382 |
+
raise FileNotFoundError(f"Video not found: {video_path}")
|
| 383 |
+
|
| 384 |
+
duration = probe_duration(video_path, args.ffprobe_bin)
|
| 385 |
+
runner = Qwen3VLRunner(
|
| 386 |
+
model_path=args.model_path,
|
| 387 |
+
device_map=args.device_map,
|
| 388 |
+
dtype=args.dtype,
|
| 389 |
+
attn_implementation=args.attn_implementation,
|
| 390 |
+
trust_remote_code=args.trust_remote_code,
|
| 391 |
+
fps=args.fps,
|
| 392 |
+
max_pixels=args.max_pixels,
|
| 393 |
+
temperature=args.temperature,
|
| 394 |
+
)
|
| 395 |
+
payload = runner.segment(
|
| 396 |
+
video_path=video_path,
|
| 397 |
+
prompt=build_prompt(duration),
|
| 398 |
+
max_new_tokens=args.max_new_tokens,
|
| 399 |
+
)
|
| 400 |
+
result = normalize_events(payload, duration)
|
| 401 |
+
|
| 402 |
+
output_text = json.dumps(result, ensure_ascii=False, indent=2) + "\n"
|
| 403 |
+
if args.output:
|
| 404 |
+
output_path = Path(args.output).expanduser().resolve()
|
| 405 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 406 |
+
output_path.write_text(output_text, encoding="utf-8")
|
| 407 |
+
else:
|
| 408 |
+
print(output_text, end="")
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
if __name__ == "__main__":
|
| 412 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
requests>=2.31
|
| 2 |
+
torch
|
| 3 |
+
transformers
|
| 4 |
+
accelerate
|
| 5 |
+
qwen-vl-utils
|
scripts/multi-event/run_multi_event_annotations.sh
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 5 |
+
SCRIPT_PATH="$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]}")"
|
| 6 |
+
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
|
| 7 |
+
ANNOTATION_SCRIPT="${ANNOTATION_SCRIPT:-$ROOT_DIR/qwen/generate_multi_event_annotations.py}"
|
| 8 |
+
PYTHON_BIN="${PYTHON_BIN:-python}"
|
| 9 |
+
INPUT_PATH="${1:-$ROOT_DIR/examples}"
|
| 10 |
+
OUTPUT_PATH="${2:-$ROOT_DIR/annotations/qwen/multi_event/generated_multi_event.json}"
|
| 11 |
+
MODEL_PATH="${MODEL_PATH:-$ROOT_DIR/checkpoints}"
|
| 12 |
+
MAX_PARALLEL_GPUS="${MAX_PARALLEL_GPUS:-8}"
|
| 13 |
+
ANNOTATION_WORKERS="${ANNOTATION_WORKERS:-auto}"
|
| 14 |
+
KEEP_PARTIAL_OUTPUTS="${KEEP_PARTIAL_OUTPUTS:-0}"
|
| 15 |
+
RUN_IN_BACKGROUND="${RUN_IN_BACKGROUND:-1}"
|
| 16 |
+
LOG_ROOT="${LOG_ROOT:-$ROOT_DIR/logs/qwen/multi_event}"
|
| 17 |
+
RUN_ID="${RUN_ID:-}"
|
| 18 |
+
RUN_DIR="${RUN_DIR:-}"
|
| 19 |
+
MAIN_LOG="${MAIN_LOG:-}"
|
| 20 |
+
|
| 21 |
+
EXTRA_ARGS=()
|
| 22 |
+
if [ "$#" -gt 2 ]; then
|
| 23 |
+
EXTRA_ARGS=("${@:3}")
|
| 24 |
+
fi
|
| 25 |
+
|
| 26 |
+
contains_arg() {
|
| 27 |
+
local needle="$1"
|
| 28 |
+
shift
|
| 29 |
+
local arg
|
| 30 |
+
for arg in "$@"; do
|
| 31 |
+
if [ "$arg" = "$needle" ]; then
|
| 32 |
+
return 0
|
| 33 |
+
fi
|
| 34 |
+
done
|
| 35 |
+
return 1
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
require_integer() {
|
| 39 |
+
local name="$1"
|
| 40 |
+
local value="$2"
|
| 41 |
+
if [[ ! "$value" =~ ^[0-9]+$ ]]; then
|
| 42 |
+
echo "$name must be a non-negative integer, got: $value" >&2
|
| 43 |
+
exit 1
|
| 44 |
+
fi
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
init_run_dir() {
|
| 48 |
+
mkdir -p "$LOG_ROOT"
|
| 49 |
+
if [ -z "$RUN_ID" ]; then
|
| 50 |
+
RUN_ID="$(date '+%Y%m%d_%H%M%S')_$$"
|
| 51 |
+
fi
|
| 52 |
+
if [ -z "$RUN_DIR" ]; then
|
| 53 |
+
RUN_DIR="$LOG_ROOT/$RUN_ID"
|
| 54 |
+
fi
|
| 55 |
+
mkdir -p "$RUN_DIR"
|
| 56 |
+
if [ -z "$MAIN_LOG" ]; then
|
| 57 |
+
MAIN_LOG="$RUN_DIR/main.log"
|
| 58 |
+
fi
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
if [ -z "${ANNOTATION_BACKGROUND_CHILD:-}" ] \
|
| 62 |
+
&& [ "$RUN_IN_BACKGROUND" = "1" ] \
|
| 63 |
+
&& ! contains_arg --dry-run "${EXTRA_ARGS[@]}" \
|
| 64 |
+
&& ! contains_arg --print-uuids-json "${EXTRA_ARGS[@]}"; then
|
| 65 |
+
init_run_dir
|
| 66 |
+
export ANNOTATION_BACKGROUND_CHILD=1
|
| 67 |
+
export RUN_ID
|
| 68 |
+
export RUN_DIR
|
| 69 |
+
export MAIN_LOG
|
| 70 |
+
nohup bash "$SCRIPT_PATH" "$@" >>"$MAIN_LOG" 2>&1 &
|
| 71 |
+
PID="$!"
|
| 72 |
+
printf '%s\n' "$PID" >"$RUN_DIR/pid"
|
| 73 |
+
printf 'Started background annotation job.\nPID: %s\nRun dir: %s\nMain log: %s\nOutput: %s\n' \
|
| 74 |
+
"$PID" "$RUN_DIR" "$MAIN_LOG" "$OUTPUT_PATH"
|
| 75 |
+
exit 0
|
| 76 |
+
fi
|
| 77 |
+
|
| 78 |
+
init_run_dir
|
| 79 |
+
|
| 80 |
+
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting multi-event annotation run"
|
| 81 |
+
echo "run_dir=$RUN_DIR"
|
| 82 |
+
echo "output_path=$OUTPUT_PATH"
|
| 83 |
+
echo "input_path=$INPUT_PATH"
|
| 84 |
+
echo "model_path=$MODEL_PATH"
|
| 85 |
+
|
| 86 |
+
discover_gpu_ids() {
|
| 87 |
+
if [ -n "${GPU_IDS:-}" ]; then
|
| 88 |
+
printf '%s\n' "$GPU_IDS"
|
| 89 |
+
return 0
|
| 90 |
+
fi
|
| 91 |
+
if [ -n "${CUDA_VISIBLE_DEVICES:-}" ]; then
|
| 92 |
+
printf '%s\n' "$CUDA_VISIBLE_DEVICES"
|
| 93 |
+
return 0
|
| 94 |
+
fi
|
| 95 |
+
if command -v nvidia-smi >/dev/null 2>&1; then
|
| 96 |
+
nvidia-smi --query-gpu=index --format=csv,noheader
|
| 97 |
+
return 0
|
| 98 |
+
fi
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
normalize_gpu_ids() {
|
| 102 |
+
"$PYTHON_BIN" - "$@" <<'PY'
|
| 103 |
+
import re
|
| 104 |
+
import sys
|
| 105 |
+
|
| 106 |
+
tokens = []
|
| 107 |
+
for raw in sys.argv[1:]:
|
| 108 |
+
parts = re.split(r"[\s,]+", raw.strip())
|
| 109 |
+
for part in parts:
|
| 110 |
+
part = part.strip()
|
| 111 |
+
if part:
|
| 112 |
+
tokens.append(part)
|
| 113 |
+
for token in tokens:
|
| 114 |
+
print(token)
|
| 115 |
+
PY
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
readarray -t GPU_IDS_ARRAY < <(normalize_gpu_ids "$(discover_gpu_ids)")
|
| 119 |
+
GPU_COUNT="${#GPU_IDS_ARRAY[@]}"
|
| 120 |
+
|
| 121 |
+
require_integer "MAX_PARALLEL_GPUS" "$MAX_PARALLEL_GPUS"
|
| 122 |
+
if [ "$ANNOTATION_WORKERS" != "auto" ]; then
|
| 123 |
+
require_integer "ANNOTATION_WORKERS" "$ANNOTATION_WORKERS"
|
| 124 |
+
fi
|
| 125 |
+
|
| 126 |
+
if [ ! -f "$ANNOTATION_SCRIPT" ]; then
|
| 127 |
+
echo "Annotation script not found: $ANNOTATION_SCRIPT" >&2
|
| 128 |
+
exit 1
|
| 129 |
+
fi
|
| 130 |
+
|
| 131 |
+
if contains_arg --dry-run "${EXTRA_ARGS[@]}" || contains_arg --print-uuids-json "${EXTRA_ARGS[@]}"; then
|
| 132 |
+
exec "$PYTHON_BIN" "$ANNOTATION_SCRIPT" \
|
| 133 |
+
--input "$INPUT_PATH" \
|
| 134 |
+
--output "$OUTPUT_PATH" \
|
| 135 |
+
--model-path "$MODEL_PATH" \
|
| 136 |
+
--recursive \
|
| 137 |
+
"${EXTRA_ARGS[@]}"
|
| 138 |
+
fi
|
| 139 |
+
|
| 140 |
+
UUID_JSON="$("$PYTHON_BIN" "$ANNOTATION_SCRIPT" \
|
| 141 |
+
--input "$INPUT_PATH" \
|
| 142 |
+
--output "$OUTPUT_PATH" \
|
| 143 |
+
--model-path "$MODEL_PATH" \
|
| 144 |
+
--recursive \
|
| 145 |
+
--print-uuids-json \
|
| 146 |
+
"${EXTRA_ARGS[@]}")"
|
| 147 |
+
|
| 148 |
+
UUID_COUNT="$(printf '%s' "$UUID_JSON" | "$PYTHON_BIN" -c 'import json,sys; print(len(json.load(sys.stdin)))')"
|
| 149 |
+
|
| 150 |
+
if [ "$UUID_COUNT" -eq 0 ]; then
|
| 151 |
+
echo "No pending UUIDs to annotate."
|
| 152 |
+
exit 0
|
| 153 |
+
fi
|
| 154 |
+
|
| 155 |
+
if [ "$ANNOTATION_WORKERS" = "auto" ]; then
|
| 156 |
+
if [ "$GPU_COUNT" -gt 0 ]; then
|
| 157 |
+
WORKER_COUNT="$GPU_COUNT"
|
| 158 |
+
else
|
| 159 |
+
WORKER_COUNT=1
|
| 160 |
+
fi
|
| 161 |
+
else
|
| 162 |
+
WORKER_COUNT="$ANNOTATION_WORKERS"
|
| 163 |
+
fi
|
| 164 |
+
|
| 165 |
+
if [ "$WORKER_COUNT" -gt "$MAX_PARALLEL_GPUS" ]; then
|
| 166 |
+
WORKER_COUNT="$MAX_PARALLEL_GPUS"
|
| 167 |
+
fi
|
| 168 |
+
if [ "$GPU_COUNT" -gt 0 ] && [ "$WORKER_COUNT" -gt "$GPU_COUNT" ]; then
|
| 169 |
+
WORKER_COUNT="$GPU_COUNT"
|
| 170 |
+
fi
|
| 171 |
+
if [ "$WORKER_COUNT" -gt "$UUID_COUNT" ]; then
|
| 172 |
+
WORKER_COUNT="$UUID_COUNT"
|
| 173 |
+
fi
|
| 174 |
+
if [ "$WORKER_COUNT" -lt 1 ]; then
|
| 175 |
+
WORKER_COUNT=1
|
| 176 |
+
fi
|
| 177 |
+
|
| 178 |
+
if [ "$WORKER_COUNT" -le 1 ]; then
|
| 179 |
+
exec "$PYTHON_BIN" "$ANNOTATION_SCRIPT" \
|
| 180 |
+
--input "$INPUT_PATH" \
|
| 181 |
+
--output "$OUTPUT_PATH" \
|
| 182 |
+
--model-path "$MODEL_PATH" \
|
| 183 |
+
--recursive \
|
| 184 |
+
"${EXTRA_ARGS[@]}"
|
| 185 |
+
fi
|
| 186 |
+
|
| 187 |
+
HAS_OVERWRITE=0
|
| 188 |
+
HAS_RESUME=0
|
| 189 |
+
if contains_arg --overwrite "${EXTRA_ARGS[@]}"; then
|
| 190 |
+
HAS_OVERWRITE=1
|
| 191 |
+
fi
|
| 192 |
+
if contains_arg --resume "${EXTRA_ARGS[@]}"; then
|
| 193 |
+
HAS_RESUME=1
|
| 194 |
+
fi
|
| 195 |
+
|
| 196 |
+
if [ -e "$OUTPUT_PATH" ] && [ "$HAS_OVERWRITE" -eq 0 ] && [ "$HAS_RESUME" -eq 0 ]; then
|
| 197 |
+
echo "Output already exists: $OUTPUT_PATH. Use --overwrite or --resume." >&2
|
| 198 |
+
exit 1
|
| 199 |
+
fi
|
| 200 |
+
|
| 201 |
+
PARTIAL_DIR="$RUN_DIR/partials"
|
| 202 |
+
mkdir -p "$PARTIAL_DIR"
|
| 203 |
+
cleanup() {
|
| 204 |
+
if [ "${KEEP_PARTIAL_OUTPUTS}" != "1" ] && [ -d "$PARTIAL_DIR" ]; then
|
| 205 |
+
rm -rf "$PARTIAL_DIR"
|
| 206 |
+
fi
|
| 207 |
+
}
|
| 208 |
+
trap cleanup EXIT
|
| 209 |
+
|
| 210 |
+
UUID_JSON_PATH="$PARTIAL_DIR/uuids.json"
|
| 211 |
+
printf '%s\n' "$UUID_JSON" >"$UUID_JSON_PATH"
|
| 212 |
+
|
| 213 |
+
"$PYTHON_BIN" - "$UUID_JSON_PATH" "$PARTIAL_DIR" "$WORKER_COUNT" <<'PY'
|
| 214 |
+
import json
|
| 215 |
+
import sys
|
| 216 |
+
from pathlib import Path
|
| 217 |
+
|
| 218 |
+
uuid_path = Path(sys.argv[1])
|
| 219 |
+
out_dir = Path(sys.argv[2])
|
| 220 |
+
num_workers = int(sys.argv[3])
|
| 221 |
+
uuids = json.loads(uuid_path.read_text(encoding="utf-8"))
|
| 222 |
+
buckets = [[] for _ in range(num_workers)]
|
| 223 |
+
for idx, uuid in enumerate(uuids):
|
| 224 |
+
buckets[idx % num_workers].append(uuid)
|
| 225 |
+
for idx, bucket in enumerate(buckets):
|
| 226 |
+
worker_file = out_dir / f"worker_{idx}.txt"
|
| 227 |
+
worker_file.write_text(
|
| 228 |
+
("\n".join(bucket) + "\n") if bucket else "",
|
| 229 |
+
encoding="utf-8",
|
| 230 |
+
)
|
| 231 |
+
PY
|
| 232 |
+
|
| 233 |
+
PIDS=()
|
| 234 |
+
LOGS=()
|
| 235 |
+
PARTIAL_OUTPUTS=()
|
| 236 |
+
|
| 237 |
+
for ((worker_idx = 0; worker_idx < WORKER_COUNT; worker_idx++)); do
|
| 238 |
+
UUID_FILE="$PARTIAL_DIR/worker_${worker_idx}.txt"
|
| 239 |
+
if [ ! -s "$UUID_FILE" ]; then
|
| 240 |
+
continue
|
| 241 |
+
fi
|
| 242 |
+
PARTIAL_OUTPUT="$PARTIAL_DIR/part_${worker_idx}.json"
|
| 243 |
+
LOG_PATH="$PARTIAL_DIR/worker_${worker_idx}.log"
|
| 244 |
+
PARTIAL_OUTPUTS+=("$PARTIAL_OUTPUT")
|
| 245 |
+
LOGS+=("$LOG_PATH")
|
| 246 |
+
|
| 247 |
+
(
|
| 248 |
+
if [ "$GPU_COUNT" -gt 0 ]; then
|
| 249 |
+
export CUDA_VISIBLE_DEVICES="${GPU_IDS_ARRAY[$worker_idx]}"
|
| 250 |
+
fi
|
| 251 |
+
exec "$PYTHON_BIN" "$ANNOTATION_SCRIPT" \
|
| 252 |
+
--input "$INPUT_PATH" \
|
| 253 |
+
--output "$PARTIAL_OUTPUT" \
|
| 254 |
+
--model-path "$MODEL_PATH" \
|
| 255 |
+
--recursive \
|
| 256 |
+
--uuids-file "$UUID_FILE" \
|
| 257 |
+
--overwrite \
|
| 258 |
+
"${EXTRA_ARGS[@]}"
|
| 259 |
+
) >"$LOG_PATH" 2>&1 &
|
| 260 |
+
PIDS+=("$!")
|
| 261 |
+
done
|
| 262 |
+
|
| 263 |
+
STATUS=0
|
| 264 |
+
for pid in "${PIDS[@]}"; do
|
| 265 |
+
if ! wait "$pid"; then
|
| 266 |
+
STATUS=1
|
| 267 |
+
fi
|
| 268 |
+
done
|
| 269 |
+
|
| 270 |
+
if [ "$STATUS" -ne 0 ]; then
|
| 271 |
+
echo "One or more annotation workers failed. Logs are in $RUN_DIR" >&2
|
| 272 |
+
for log_path in "${LOGS[@]}"; do
|
| 273 |
+
if [ -f "$log_path" ]; then
|
| 274 |
+
echo "===== $log_path =====" >&2
|
| 275 |
+
tail -n 40 "$log_path" >&2 || true
|
| 276 |
+
fi
|
| 277 |
+
done
|
| 278 |
+
exit "$STATUS"
|
| 279 |
+
fi
|
| 280 |
+
|
| 281 |
+
"$PYTHON_BIN" - "$OUTPUT_PATH" "$HAS_RESUME" "${PARTIAL_OUTPUTS[@]}" <<'PY'
|
| 282 |
+
import json
|
| 283 |
+
import sys
|
| 284 |
+
from pathlib import Path
|
| 285 |
+
|
| 286 |
+
output_path = Path(sys.argv[1])
|
| 287 |
+
resume = bool(int(sys.argv[2]))
|
| 288 |
+
partial_paths = [Path(arg) for arg in sys.argv[3:]]
|
| 289 |
+
|
| 290 |
+
videos_by_uuid = {}
|
| 291 |
+
if resume and output_path.exists():
|
| 292 |
+
payload = json.loads(output_path.read_text(encoding="utf-8"))
|
| 293 |
+
for item in payload.get("videos", []):
|
| 294 |
+
if isinstance(item, dict) and "uuid" in item:
|
| 295 |
+
videos_by_uuid[item["uuid"]] = item
|
| 296 |
+
|
| 297 |
+
for path in partial_paths:
|
| 298 |
+
if not path.exists():
|
| 299 |
+
continue
|
| 300 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 301 |
+
for item in payload.get("videos", []):
|
| 302 |
+
if isinstance(item, dict) and "uuid" in item:
|
| 303 |
+
videos_by_uuid[item["uuid"]] = item
|
| 304 |
+
|
| 305 |
+
ordered = [videos_by_uuid[uuid] for uuid in sorted(videos_by_uuid)]
|
| 306 |
+
merged = {
|
| 307 |
+
"total_videos": len(ordered),
|
| 308 |
+
"videos": ordered,
|
| 309 |
+
}
|
| 310 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 311 |
+
output_path.write_text(
|
| 312 |
+
json.dumps(merged, ensure_ascii=False, indent=2) + "\n",
|
| 313 |
+
encoding="utf-8",
|
| 314 |
+
)
|
| 315 |
+
PY
|
| 316 |
+
|
| 317 |
+
"$PYTHON_BIN" - "$OUTPUT_PATH" "$PARTIAL_DIR" <<'PY'
|
| 318 |
+
import sys
|
| 319 |
+
from pathlib import Path
|
| 320 |
+
|
| 321 |
+
output_path = Path(sys.argv[1])
|
| 322 |
+
partial_dir = Path(sys.argv[2])
|
| 323 |
+
partial_logs = sorted(partial_dir.glob("part_*.manual_camera_desc_mismatches.txt"))
|
| 324 |
+
if not partial_logs:
|
| 325 |
+
raise SystemExit(0)
|
| 326 |
+
|
| 327 |
+
merged_path = output_path.with_name(f"{output_path.stem}.manual_camera_desc_mismatches.txt")
|
| 328 |
+
chunks = []
|
| 329 |
+
for path in partial_logs:
|
| 330 |
+
text = path.read_text(encoding="utf-8").strip()
|
| 331 |
+
if text:
|
| 332 |
+
chunks.append(text)
|
| 333 |
+
if chunks:
|
| 334 |
+
merged_path.write_text("\n\n".join(chunks) + "\n", encoding="utf-8")
|
| 335 |
+
print(f"Wrote manual camera mismatch log to {merged_path}")
|
| 336 |
+
PY
|
| 337 |
+
|
| 338 |
+
if [ "${KEEP_PARTIAL_OUTPUTS}" = "1" ]; then
|
| 339 |
+
echo "Partial worker outputs kept in $PARTIAL_DIR"
|
| 340 |
+
fi
|
| 341 |
+
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Completed multi-event annotation run"
|
scripts/multi-event/test_multi_event_annotations_100.sh
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
| 5 |
+
RUN_SCRIPT="$ROOT_DIR/scripts/multi-event/run_multi_event_annotations.sh"
|
| 6 |
+
|
| 7 |
+
INPUT_PATH="${1:-$ROOT_DIR/data/mev_video}"
|
| 8 |
+
OUTPUT_PATH="${2:-$ROOT_DIR/annotations/qwen/multi_event/test_mev_video_100.json}"
|
| 9 |
+
UUID_LIMIT="${UUID_LIMIT:-100}"
|
| 10 |
+
|
| 11 |
+
EXTRA_ARGS=()
|
| 12 |
+
if [ "$#" -gt 2 ]; then
|
| 13 |
+
EXTRA_ARGS=("${@:3}")
|
| 14 |
+
fi
|
| 15 |
+
|
| 16 |
+
if [[ ! "$UUID_LIMIT" =~ ^[0-9]+$ ]] || [ "$UUID_LIMIT" -lt 1 ]; then
|
| 17 |
+
echo "UUID_LIMIT must be a positive integer, got: $UUID_LIMIT" >&2
|
| 18 |
+
exit 1
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
exec bash "$RUN_SCRIPT" \
|
| 22 |
+
"$INPUT_PATH" \
|
| 23 |
+
"$OUTPUT_PATH" \
|
| 24 |
+
--limit "$UUID_LIMIT" \
|
| 25 |
+
"${EXTRA_ARGS[@]}"
|