File size: 27,144 Bytes
ef0b17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
#!/usr/bin/env python3
"""SAM3 常驻模型服务:启动时把 SAM3 video model 载入一次,之后跨视频复用。

服务的 op:
  - "masks": 进程内调 qwen_sam3_video_masks.main()(args.argv = 原 step2 CLI 参数列表)
  - "shutdown"

载入一次的模型:SAM3 video model(默认 ckpt 由 step2 传入;Qwen 标签在 masks 模式走 API,
无需常驻本地模型)。跑在 sam3 env:
  python masking/sam3_server.py --queue <dir>
"""
import argparse
import json
import os
import sys
from pathlib import Path

os.environ.setdefault("PYOPENGL_PLATFORM", "egl")

_QWEN_DIR = Path(__file__).resolve().parent
_OVOW_ROOT = _QWEN_DIR.parent
_ENGINE_DIR = Path(os.environ.get("ENGINE_DIR", str(_OVOW_ROOT / "engine")))
_SAM3_DIR = Path(os.environ.get("SAM3_DIR", str(_OVOW_ROOT / "third_party" / "sam3")))
_IPC_DIR = str(_ENGINE_DIR / "tools" / "model_server")
for p in (_IPC_DIR, str(_QWEN_DIR)):
    if p not in sys.path:
        sys.path.insert(0, p)

import ipc  # noqa: E402  (tools/model_server 在 path 上)

_DEFAULT_SAM3_CKPT = os.environ.get("SAM3_CKPT", str(_SAM3_DIR / "checkpoints" / "sam3" / "sam3.pt"))


def _warm_models():
    """一次性加载 SAM3 video model(常驻)。"""
    print("[sam3-server] 加载 SAM3 video model(常驻)...", flush=True)
    import qwen_sam3_video_masks as qsvm  # noqa: F401
    qsvm.load_once(os.environ.get("SAM3_CKPT") or _DEFAULT_SAM3_CKPT)
    print("[sam3-server] SAM3 ckpt 载入完成。", flush=True)


def _handle_masks(args):
    """进程内单视频 mask 生成:复用常驻 SAM3,init_state 按视频新建。"""
    import qwen_sam3_video_masks as qsvm
    argv = args["argv"]
    old = sys.argv
    try:
        sys.argv = ["qwen_sam3_video_masks.py"] + list(argv)
        qsvm.main()
    finally:
        sys.argv = old
    return {"video": args.get("video_name", "")}


def _as_bool_mask(mask):
    import numpy as np

    arr = np.asarray(mask)
    arr = np.squeeze(arr)
    if arr.ndim != 2:
        raise RuntimeError(f"Unexpected SAM3 mask shape: {arr.shape}")
    return arr > 0


def _normalize_points(raw_points, width: int, height: int):
    points = []
    labels = []
    for item in raw_points:
        if isinstance(item, dict):
            x = float(item.get("x", item.get("px", 0.0)))
            y = float(item.get("y", item.get("py", 0.0)))
            label = int(item.get("label", 1))
        else:
            x = float(item[0])
            y = float(item[1])
            label = int(item[2]) if len(item) > 2 else 1
        if x > 1.0 or y > 1.0:
            x = x / max(1, width)
            y = y / max(1, height)
        x = min(1.0, max(0.0, x))
        y = min(1.0, max(0.0, y))
        points.append([x, y])
        labels.append(1 if label else 0)
    if not any(labels):
        raise RuntimeError("manual SAM3 points need at least one positive point")
    return points, labels


def _prime_empty_cached_outputs(inference_state, num_frames: int):
    """Point prompts are tracker refinements; SAM3 expects a per-frame VG cache."""
    cached = inference_state.setdefault("cached_frame_outputs", {})
    for frame_idx in range(max(0, int(num_frames))):
        cached.setdefault(frame_idx, {})


def _collect_obj_masks(masks_by_frame: dict, frame_idx: int, out: dict | None, obj_id: int):
    if out is None:
        return
    for oid, mask in zip(out.get("out_obj_ids", []), out.get("out_binary_masks", [])):
        if int(oid) != obj_id:
            continue
        arr = _as_bool_mask(mask)
        if int(arr.sum()) > 0:
            masks_by_frame[int(frame_idx)] = arr


def _save_sparse_masks(obj_dir: Path, masks_by_frame: dict) -> None:
    obj_dir.mkdir(parents=True, exist_ok=True)
    from PIL import Image  # type: ignore

    for fid, mask in sorted(masks_by_frame.items()):
        out = (_as_bool_mask(mask).astype("uint8") * 255)
        Image.fromarray(out).save(obj_dir / f"frame_{int(fid):06d}.png")


def _click_boxes_from_points(points, point_labels, specs):
    positives = [p for p, label in zip(points, point_labels) if int(label)]
    if not positives:
        raise RuntimeError("manual box prompt needs at least one positive point")
    x, y = positives[-1]
    boxes = []
    for spec in specs or []:
        if isinstance(spec, dict):
            bw = float(spec.get("w", spec.get("width", 0.55)))
            bh = float(spec.get("h", spec.get("height", 0.45)))
        else:
            bw = float(spec[0])
            bh = float(spec[1] if len(spec) > 1 else spec[0])
        bw = min(0.98, max(0.03, bw))
        bh = min(0.98, max(0.03, bh))
        x0 = min(max(float(x) - bw * 0.5, 0.0), 1.0 - bw)
        y0 = min(max(float(y) - bh * 0.5, 0.0), 1.0 - bh)
        boxes.append([x0, y0, bw, bh])
    if not boxes:
        raise RuntimeError("manual box prompt has no valid click box sizes")
    return boxes


def _mask_has_point(mask, points, point_labels, radius: int = 4) -> bool:
    positives = [p for p, label in zip(points, point_labels) if int(label)]
    if not positives:
        return False
    h, w = mask.shape[:2]
    for x_norm, y_norm in positives:
        x = int(round(float(x_norm) * max(1, w - 1)))
        y = int(round(float(y_norm) * max(1, h - 1)))
        x0, x1 = max(0, x - radius), min(w, x + radius + 1)
        y0, y1 = max(0, y - radius), min(h, y + radius + 1)
        if bool(mask[y0:y1, x0:x1].any()):
            return True
    return False


def _select_prompt_object(out: dict | None, points, point_labels):
    if out is None:
        return None, None, 0
    best = None
    for oid, mask in zip(out.get("out_obj_ids", []), out.get("out_binary_masks", [])):
        arr = _as_bool_mask(mask)
        area = int(arr.sum())
        if area <= 0:
            continue
        has_point = _mask_has_point(arr, points, point_labels)
        score = (1 if has_point else 0, area)
        if best is None or score > best[0]:
            best = (score, int(oid), arr, area)
    if best is None:
        return None, None, 0
    return best[1], best[2], best[3]


def _next_object_name(mask_root: Path, label: str) -> str:
    safe = label
    idx = 1
    while (mask_root / f"{safe}_{idx:02d}").exists():
        idx += 1
    return f"{safe}_{idx:02d}"


def _append_unique(items, value):
    if value not in items:
        items.append(value)
    return items


def _labels_per_keyframe_dict(payload: dict) -> dict:
    out = {}
    for key, values in (payload.get("labels_per_keyframe") or {}).items():
        try:
            frame = int(key)
        except (TypeError, ValueError):
            continue
        out[frame] = [str(v) for v in (values or [])]
    return out


def _as_bool(value, default: bool = True) -> bool:
    if value is None:
        return default
    if isinstance(value, bool):
        return value
    text = str(value).strip().lower()
    if text in {"1", "true", "yes", "on"}:
        return True
    if text in {"0", "false", "no", "off"}:
        return False
    return default


def _commit_object_metadata(
    *, output_root, video_path, video_name, num_frames, fps, width, height,
    mask_root, obj_dir, obj_name, label, category, frame_idx, points, point_labels,
    object_summary, args,
):
    """Upsert one manual object into labels_json / mask_summary / pipeline_config.

    Shared by the single-object and batch manual handlers so both emit identical
    metadata (upsert-by-name, same schema the review UI + run_recon consume)."""
    import qwen_sam3_video_masks as qsvm
    meta_dir = output_root / "metadata"
    labels_json = meta_dir / f"{video_name}_labels.json"
    label_norm = qsvm._simple_normalize(label)
    if labels_json.is_file():
        labels_payload = json.loads(labels_json.read_text(encoding="utf-8"))
    else:
        qsvm._write_labels_json(
            labels_json, video_path, num_frames, fps, width, height, [], [], {},
        )
        labels_payload = json.loads(labels_json.read_text(encoding="utf-8"))
    keyframes = [int(x) for x in (labels_payload.get("keyframes") or [])]
    _append_unique(keyframes, int(frame_idx))
    labels = [str(x) for x in (labels_payload.get("labels") or [])]
    _append_unique(labels, label)
    labels_per_keyframe = _labels_per_keyframe_dict(labels_payload)
    labels_per_keyframe.setdefault(int(frame_idx), [])
    _append_unique(labels_per_keyframe[int(frame_idx)], label)
    label_categories = dict(labels_payload.get("label_categories") or {})
    label_categories[label_norm] = category
    labels_payload.update({
        "video": str(video_path),
        "video_name": video_name,
        "num_frames": int(num_frames),
        "fps": float(fps),
        "width": int(width),
        "height": int(height),
        "keyframes": sorted(keyframes),
        "labels": labels,
        "labels_per_keyframe": {str(k): v for k, v in sorted(labels_per_keyframe.items())},
        "label_categories": label_categories,
    })
    labels_payload["label_category_source"] = "manual_click"
    manual_points = list(labels_payload.get("manual_points") or [])
    manual_points.append({
        "object": obj_name,
        "label": label,
        "points": points,
        "point_labels": point_labels,
        "frame_idx": frame_idx,
    })
    labels_payload["manual_points"] = manual_points
    labels_json.write_text(json.dumps(labels_payload, indent=2), encoding="utf-8")

    objects_summary = [object_summary]
    summary_path = meta_dir / f"{video_name}_mask_summary.json"
    meta_dir.mkdir(parents=True, exist_ok=True)
    if summary_path.is_file():
        summary = json.loads(summary_path.read_text(encoding="utf-8"))
    else:
        summary = {
            "video": str(video_path),
            "video_name": video_name,
            "num_frames": int(num_frames),
            "fps": float(fps),
            "width": int(width),
            "height": int(height),
            "keyframes": [],
            "labels": [],
            "labels_per_keyframe": {},
            "moving_labels": [],
            "objects": [],
            "mask_root": str(mask_root),
            "labels_json": str(labels_json),
            "qwen_label_category_mode": "manual_click",
            "label_category_source": "manual_click",
            "label_categories": {},
            "label_category_reasons": {},
            "label_visual_descriptions": {},
            "label_prompt_aliases": {},
        }
    summary.update({
        "video": str(video_path),
        "video_name": video_name,
        "num_frames": int(num_frames),
        "fps": float(fps),
        "width": int(width),
        "height": int(height),
        "mask_root": str(mask_root),
        "labels_json": str(labels_json),
        "qwen_label_category_mode": "manual_click",
        "label_category_source": "manual_click",
    })
    keyframes = [int(x) for x in (summary.get("keyframes") or [])]
    _append_unique(keyframes, int(frame_idx))
    labels = [str(x) for x in (summary.get("labels") or [])]
    _append_unique(labels, label)
    labels_per_keyframe = _labels_per_keyframe_dict(summary)
    labels_per_keyframe.setdefault(int(frame_idx), [])
    _append_unique(labels_per_keyframe[int(frame_idx)], label)
    moving_labels = [str(x) for x in (summary.get("moving_labels") or [])]
    if category in {"rigid", "deform"}:
        _append_unique(moving_labels, label)
    else:
        moving_labels = [x for x in moving_labels if x != label]
    label_categories = dict(summary.get("label_categories") or {})
    label_categories[label_norm] = category
    existing_objects = [
        obj for obj in (summary.get("objects") or [])
        if str(obj.get("name", "")) != obj_name
    ]
    summary["keyframes"] = sorted(keyframes)
    summary["labels"] = labels
    summary["labels_per_keyframe"] = {str(k): v for k, v in sorted(labels_per_keyframe.items())}
    summary["moving_labels"] = moving_labels
    summary["label_categories"] = label_categories
    summary["objects"] = existing_objects + objects_summary
    summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8")

    recon_root = output_root / "recon_ready" / video_name
    recon_root.mkdir(parents=True, exist_ok=True)
    batch_config = args.get("batch_config") or str(_ENGINE_DIR / "config" / "batch_config_example_legacy.json")
    cfg_path = recon_root / "pipeline_config.json"
    if cfg_path.is_file():
        pipeline_cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
    else:
        pipeline_cfg = {
            "batch_config": str(Path(batch_config).resolve()),
            "video_path": str(video_path),
            "output_root": str(output_root),
            "mask_glob": "frame_*.png",
            "tracker_mask_mode": "static",
            "objects": [],
        }
    pipeline_cfg.update({
        "batch_config": str(Path(pipeline_cfg.get("batch_config") or batch_config).resolve()),
        "video_path": str(video_path),
        "output_root": str(output_root),
        "mask_glob": "frame_*.png",
        "tracker_mask_mode": "static",
    })
    existing_cfg_objects = [
        obj for obj in (pipeline_cfg.get("objects") or [])
        if str(obj.get("name", "")) != obj_name
    ]
    existing_cfg_objects.append({
        "name": obj_name,
        "masks_dir": str(obj_dir),
        "category": category,
    })
    pipeline_cfg["objects"] = existing_cfg_objects
    cfg_path.write_text(json.dumps(pipeline_cfg, indent=2), encoding="utf-8")

    return {
        "video": video_name,
        "object": obj_name,
        "category": category,
        "frames_with_mask": int(object_summary.get("frames_with_mask", 0)),
        "summary": str(summary_path),
        "pipeline_config": str(cfg_path),
    }


def _handle_manual_points_batch(args):
    """Segment several manually-clicked objects in ONE video pass.

    A single click only masks one frame; every object still needs its mask propagated
    across the whole video (Motion324 wants every frame; the scene animation gates each
    object's visibility on masked frames). Running one ``manual_points`` request per object
    re-encodes all video frames each time (~50s each) because SAM3 evicts per-frame features
    as it propagates (sliding window). Here we point-prompt every object into ONE
    ``inference_state`` (distinct obj_ids) and propagate once per prompt-frame group, so each
    frame's image features are computed once and shared by every object's tracker at that
    frame → ~N× faster. Instance identity is preserved: each obj_id yields its own binary
    mask written to its own ``masks/<video>/<obj>`` dir; masks are never merged."""
    import numpy as np  # noqa: F401
    import qwen_sam3_video_masks as qsvm

    video_path = Path(args["video_path"]).resolve()
    output_root = Path(args["output_root"]).resolve()
    objects_in = list(args.get("objects") or [])
    if not objects_in:
        raise RuntimeError("manual_points_batch needs a non-empty 'objects' list")
    min_obj_area = int(args.get("min_obj_area", 200))
    num_frames, fps, width, height = qsvm._video_info(video_path)
    video_name = video_path.stem
    mask_root = output_root / "masks" / video_name

    sam3_model, _ = qsvm.load_once(args.get("sam3_ckpt") or os.environ.get("SAM3_CKPT") or _DEFAULT_SAM3_CKPT)
    inference_state = sam3_model.init_state(resource_path=str(video_path))

    specs = []
    for i, obj in enumerate(objects_in, start=1):
        label = str(obj.get("label") or "object").strip() or "object"
        category = str(obj.get("category") or "rigid").strip().lower()
        if category not in {"static", "rigid", "deform"}:
            raise RuntimeError(f"invalid manual category: {category}")
        frame_idx = min(max(0, int(obj.get("frame_idx", 0))), max(0, num_frames - 1))
        pts, plabels = _normalize_points(obj.get("points") or [], width, height)
        name = str(obj.get("object_name") or "").strip() or _next_object_name(mask_root, qsvm._safe_id(label))
        specs.append({
            "obj_id": i, "label": label, "category": category, "frame_idx": frame_idx,
            "points": pts, "point_labels": plabels, "object_name": name,
            "masks_by_frame": {},
        })

    by_id = {s["obj_id"]: s for s in specs}

    frames = sorted({s["frame_idx"] for s in specs})
    for gi, gframe in enumerate(frames):
        group = [s for s in specs if s["frame_idx"] == gframe]
        if gi > 0:
            sam3_model.reset_state(inference_state)
        _prime_empty_cached_outputs(inference_state, num_frames)
        for s in group:
            _, prompt_out = sam3_model.add_prompt(
                inference_state,
                frame_idx=gframe,
                points=s["points"],
                point_labels=s["point_labels"],
                obj_id=s["obj_id"],
            )
            _collect_obj_masks(s["masks_by_frame"], gframe, prompt_out, s["obj_id"])
        group_ids = {s["obj_id"] for s in group}
        directions = [False] + ([True] if gframe > 0 else [])
        for reverse in directions:
            for fid, out in sam3_model.propagate_in_video(
                inference_state,
                start_frame_idx=gframe,
                max_frame_num_to_track=num_frames,
                reverse=reverse,
            ):
                if out is None:
                    continue
                for oid in group_ids:
                    _collect_obj_masks(by_id[oid]["masks_by_frame"], fid, out, oid)

    results = []
    for s in specs:
        masks_by_frame = s["masks_by_frame"]
        if not masks_by_frame:
            results.append({"object": s["object_name"], "error": "no mask; refine click points"})
            continue
        max_area = max(int(m.sum()) for m in masks_by_frame.values())
        if max_area < min_obj_area:
            results.append({"object": s["object_name"],
                            "error": f"mask too small: {max_area} < {min_obj_area}"})
            continue
        obj_dir = mask_root / s["object_name"]
        qsvm._save_masks(obj_dir, num_frames, masks_by_frame)
        is_static, med_iou, med_motion, valid_frames, occluded_frames, area_med = qsvm._classify_static(
            masks_by_frame,
            static_iou_thresh=float(args.get("static_iou_thresh", 0.6)),
            static_motion_px=float(args.get("static_motion_px", 10.0)),
            occlusion_area_ratio=float(args.get("occlusion_area_ratio", 0.6)),
            min_valid_frames=int(args.get("min_valid_frames", 10)),
            high_iou_thresh=float(args.get("high_iou_static", 0.8)),
            high_iou_motion_mult=float(args.get("high_iou_motion_mult", 3.0)),
        )
        category = s["category"]
        object_summary = {
            "name": s["object_name"],
            "label": s["label"],
            "sam3_obj_id": s["obj_id"],
            "frames_with_mask": len(masks_by_frame),
            "max_area": int(max_area),
            "median_area": float(area_med),
            "valid_frames": int(valid_frames),
            "occluded_frames": int(occluded_frames),
            "median_iou": float(med_iou),
            "median_motion_px": float(med_motion),
            "is_static": category == "static" or bool(is_static and category == "static"),
            "category": category,
            "category_source": "manual_click",
            "force_static": category == "static",
            "force_dynamic": category in {"rigid", "deform"},
            "prompt_frame": int(s["frame_idx"]),
            "prompt_mode": "points",
            "prompt_box_xywh": None,
            "manual_points": s["points"],
            "manual_point_labels": s["point_labels"],
        }
        res = _commit_object_metadata(
            output_root=output_root, video_path=video_path, video_name=video_name,
            num_frames=num_frames, fps=fps, width=width, height=height,
            mask_root=mask_root, obj_dir=obj_dir, obj_name=s["object_name"],
            label=s["label"], category=category, frame_idx=s["frame_idx"],
            points=s["points"], point_labels=s["point_labels"],
            object_summary=object_summary, args=args,
        )
        results.append(res)

    return {"video": video_name, "num_frames": int(num_frames), "objects": results}


def _handle_manual_points(args):
    """Point-prompt SAM3 masks for Gradio manual mode; writes OVOW mask summary/config."""
    import numpy as np
    import qwen_sam3_video_masks as qsvm

    video_path = Path(args["video_path"]).resolve()
    output_root = Path(args["output_root"]).resolve()
    label = str(args.get("label") or "object").strip() or "object"
    category = str(args.get("category") or "rigid").strip().lower()
    if category not in {"static", "rigid", "deform"}:
        raise RuntimeError(f"invalid manual category: {category}")
    commit = _as_bool(args.get("commit"), True)

    num_frames, fps, width, height = qsvm._video_info(video_path)
    frame_idx = int(args.get("frame_idx", 0))
    frame_idx = min(max(0, frame_idx), max(0, num_frames - 1))
    min_obj_area = int(args.get("min_obj_area", 200))
    points, point_labels = _normalize_points(args.get("points") or [], width, height)

    sam3_model, _ = qsvm.load_once(args.get("sam3_ckpt") or os.environ.get("SAM3_CKPT") or _DEFAULT_SAM3_CKPT)
    inference_state = None
    requested_mode = str(args.get("prompt_mode") or "points").strip().lower()
    prompt_mode = "box" if requested_mode in {"box", "click_box", "visual_box"} else "points"
    masks_by_frame = {}
    prompt_box = None
    obj_id = int(args.get("obj_id", 1))
    if prompt_mode == "box":
        prompt_out = None
        for prompt_box in _click_boxes_from_points(
            points,
            point_labels,
            args.get("click_boxes") or [[0.55, 0.45], [0.75, 0.60]],
        ):
            inference_state = sam3_model.init_state(resource_path=str(video_path))
            prompt_frame, prompt_out = sam3_model.add_prompt(
                inference_state,
                frame_idx=frame_idx,
                boxes_xywh=[prompt_box],
                box_labels=[1],
            )
            selected_obj_id, selected_mask, selected_area = _select_prompt_object(
                prompt_out,
                points,
                point_labels,
            )
            if selected_obj_id is None:
                continue
            obj_id = int(selected_obj_id)
            masks_by_frame = {int(prompt_frame): selected_mask}
            if int(selected_area) >= min_obj_area:
                break
    else:
        inference_state = sam3_model.init_state(resource_path=str(video_path))
        _prime_empty_cached_outputs(inference_state, num_frames)
        prompt_frame, prompt_out = sam3_model.add_prompt(
            inference_state,
            frame_idx=frame_idx,
            points=points,
            point_labels=point_labels,
            obj_id=obj_id,
        )
        _collect_obj_masks(masks_by_frame, prompt_frame, prompt_out, obj_id)

    if commit:
        directions = [False]
        if frame_idx > 0:
            directions.append(True)
        for reverse in directions:
            for fid, out in sam3_model.propagate_in_video(
                inference_state,
                start_frame_idx=frame_idx,
                max_frame_num_to_track=num_frames,
                reverse=reverse,
            ):
                if out is None:
                    continue
                _collect_obj_masks(masks_by_frame, fid, out, obj_id)

    if not masks_by_frame:
        raise RuntimeError("manual SAM3 produced no mask; add/refine click points")
    max_area = max(int(m.sum()) for m in masks_by_frame.values())
    if max_area < min_obj_area:
        raise RuntimeError(
            f"manual SAM3 mask too small: max_area={max_area}, min_obj_area={min_obj_area}"
        )

    video_name = video_path.stem
    mask_root = output_root / "masks" / video_name
    pending_root = output_root / "_pending" / video_name
    safe_label = qsvm._safe_id(label)
    obj_name = str(args.get("object_name") or "").strip() or _next_object_name(mask_root, safe_label)
    obj_dir = (mask_root if commit else pending_root) / obj_name
    if commit:
        qsvm._save_masks(obj_dir, num_frames, masks_by_frame)
    else:
        _save_sparse_masks(obj_dir, masks_by_frame)

    is_static, med_iou, med_motion, valid_frames, occluded_frames, area_med = qsvm._classify_static(
        masks_by_frame,
        static_iou_thresh=float(args.get("static_iou_thresh", 0.6)),
        static_motion_px=float(args.get("static_motion_px", 10.0)),
        occlusion_area_ratio=float(args.get("occlusion_area_ratio", 0.6)),
        min_valid_frames=int(args.get("min_valid_frames", 10)),
        high_iou_thresh=float(args.get("high_iou_static", 0.8)),
        high_iou_motion_mult=float(args.get("high_iou_motion_mult", 3.0)),
    )
    object_summary = {
        "name": obj_name,
        "label": label,
        "sam3_obj_id": obj_id,
        "frames_with_mask": len(masks_by_frame),
        "max_area": int(max_area),
        "median_area": float(area_med),
        "valid_frames": int(valid_frames),
        "occluded_frames": int(occluded_frames),
        "median_iou": float(med_iou),
        "median_motion_px": float(med_motion),
        "is_static": category == "static" or bool(is_static and category == "static"),
        "category": category,
        "category_source": "manual_click",
        "force_static": category == "static",
        "force_dynamic": category in {"rigid", "deform"},
        "prompt_frame": int(frame_idx),
        "prompt_mode": prompt_mode,
        "prompt_box_xywh": prompt_box,
        "manual_points": points,
        "manual_point_labels": point_labels,
    }

    if not commit:
        return {
            "video": video_name,
            "object": obj_name,
            "label": label,
            "category": category,
            "frames_with_mask": len(masks_by_frame),
            "max_area": int(max_area),
            "masks_dir": str(obj_dir),
            "prompt_frame": int(frame_idx),
            "num_frames": int(num_frames),
            "fps": float(fps),
            "width": int(width),
            "height": int(height),
            "object_summary": object_summary,
        }

    return _commit_object_metadata(
        output_root=output_root,
        video_path=video_path,
        video_name=video_name,
        num_frames=num_frames,
        fps=fps,
        width=width,
        height=height,
        mask_root=mask_root,
        obj_dir=obj_dir,
        obj_name=obj_name,
        label=label,
        category=category,
        frame_idx=frame_idx,
        points=points,
        point_labels=point_labels,
        object_summary=object_summary,
        args=args,
    )


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--queue", required=True, help="请求队列目录")
    args = ap.parse_args()
    handlers = {
        "masks": _handle_masks,
        "manual_points": _handle_manual_points,
        "manual_points_batch": _handle_manual_points_batch,
    }
    ipc.server_loop(args.queue, handlers, on_start=_warm_models)


if __name__ == "__main__":
    main()