@larkup/tool-video-intelligence 0.2.10 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +3 -0
- package/README.md +11 -6
- package/dist/agent.d.ts +50 -0
- package/dist/agent.js +505 -241
- package/dist/contracts.d.ts +57 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +5 -4
- package/package.json +3 -3
- package/runtime/app/config.py +1 -1
- package/runtime/app/main.py +0 -4
- package/runtime/app/services/brain.py +694 -71
- package/runtime/app/services/embedding.py +1 -1
- package/runtime/app/services/pipeline.py +256 -11
- package/runtime/app/services/vision.py +191 -34
- package/runtime/app/utils/timing.py +82 -2
- package/tool.manifest.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Video-clip embeddings for cross-modal search
|
|
1
|
+
"""Video-clip embeddings for cross-modal search "find the clip where this
|
|
2
2
|
happens" from a free-text query. Distinct from vision.py's captions: a
|
|
3
3
|
caption describes a clip in words, which can miss an action a viewer would
|
|
4
4
|
recognize but a VLM never put into text. An embedding catches that by
|
|
@@ -25,7 +25,12 @@ from typing import Any, Callable, Iterator
|
|
|
25
25
|
import cv2
|
|
26
26
|
import numpy as np
|
|
27
27
|
|
|
28
|
-
from app.utils.timing import
|
|
28
|
+
from app.utils.timing import (
|
|
29
|
+
bounded_visual_sampling_intervals,
|
|
30
|
+
normalized_important_ranges,
|
|
31
|
+
ocr_sampling_interval,
|
|
32
|
+
rebase_result_timestamps,
|
|
33
|
+
)
|
|
29
34
|
from app.services.brain import (
|
|
30
35
|
AgentPlanner,
|
|
31
36
|
ExtractionPlan,
|
|
@@ -213,6 +218,7 @@ class VisualOperators:
|
|
|
213
218
|
with self._lock:
|
|
214
219
|
if self._ocr is None:
|
|
215
220
|
try:
|
|
221
|
+
# pyrefly: ignore [missing-import]
|
|
216
222
|
from paddleocr import PaddleOCR
|
|
217
223
|
|
|
218
224
|
self._ocr = (
|
|
@@ -492,9 +498,10 @@ def _intersection_over_union(left: list[float], right: list[float]) -> float:
|
|
|
492
498
|
|
|
493
499
|
|
|
494
500
|
class AnonymousTracker:
|
|
495
|
-
def __init__(self) -> None:
|
|
501
|
+
def __init__(self, max_gap_ms: int = 6_000) -> None:
|
|
496
502
|
self.next_id = 1
|
|
497
503
|
self.tracks: dict[int, dict[str, Any]] = {}
|
|
504
|
+
self.max_gap_ms = max(1, int(max_gap_ms))
|
|
498
505
|
|
|
499
506
|
def update(self, detections: list[dict[str, Any]], time_ms: int) -> None:
|
|
500
507
|
claimed: set[int] = set()
|
|
@@ -504,7 +511,7 @@ class AnonymousTracker:
|
|
|
504
511
|
for track_id, track in self.tracks.items()
|
|
505
512
|
if track_id not in claimed
|
|
506
513
|
and track["label"] == detection["label"]
|
|
507
|
-
and time_ms - track["endMs"] <=
|
|
514
|
+
and time_ms - track["endMs"] <= self.max_gap_ms
|
|
508
515
|
]
|
|
509
516
|
track_id, overlap = max(
|
|
510
517
|
candidates, key=lambda item: item[1], default=(0, 0.0)
|
|
@@ -547,6 +554,176 @@ class AnonymousTracker:
|
|
|
547
554
|
]
|
|
548
555
|
|
|
549
556
|
|
|
557
|
+
def _anonymous_presence_ledger(
|
|
558
|
+
observations: list[dict[str, Any]],
|
|
559
|
+
tracks: list[dict[str, Any]],
|
|
560
|
+
sample_interval_secs: float | None = None,
|
|
561
|
+
) -> dict[str, Any]:
|
|
562
|
+
"""Preserve raw tracked-presence measurements without inventing identity."""
|
|
563
|
+
timestamps_by_track: dict[int, list[int]] = defaultdict(list)
|
|
564
|
+
label_counts_at_time: dict[str, list[tuple[int, int]]] = defaultdict(list)
|
|
565
|
+
for observation in observations:
|
|
566
|
+
time_ms = int(observation.get("timeMs") or 0)
|
|
567
|
+
counts: Counter[str] = Counter()
|
|
568
|
+
for detected in observation.get("objects") or []:
|
|
569
|
+
if not isinstance(detected, dict):
|
|
570
|
+
continue
|
|
571
|
+
label = str(detected.get("label") or "").strip()
|
|
572
|
+
track_id = detected.get("trackId")
|
|
573
|
+
if not label:
|
|
574
|
+
continue
|
|
575
|
+
counts[label] += 1
|
|
576
|
+
if isinstance(track_id, int):
|
|
577
|
+
timestamps_by_track[track_id].append(time_ms)
|
|
578
|
+
for label, count in counts.items():
|
|
579
|
+
label_counts_at_time[label].append((time_ms, count))
|
|
580
|
+
|
|
581
|
+
tracked = []
|
|
582
|
+
for track in tracks:
|
|
583
|
+
track_id = track.get("trackId")
|
|
584
|
+
if not isinstance(track_id, int):
|
|
585
|
+
continue
|
|
586
|
+
tracked.append(
|
|
587
|
+
{
|
|
588
|
+
**track,
|
|
589
|
+
"timestampsMs": sorted(set(timestamps_by_track.get(track_id, [])))[:512],
|
|
590
|
+
}
|
|
591
|
+
)
|
|
592
|
+
labels = []
|
|
593
|
+
for label, readings in sorted(label_counts_at_time.items()):
|
|
594
|
+
maximum = max((count for _, count in readings), default=0)
|
|
595
|
+
labels.append(
|
|
596
|
+
{
|
|
597
|
+
"label": label,
|
|
598
|
+
"distinctTrackCount": sum(
|
|
599
|
+
1 for track in tracked if str(track.get("label") or "") == label
|
|
600
|
+
),
|
|
601
|
+
"maximumSimultaneous": maximum,
|
|
602
|
+
"simultaneousTimestampsMs": [
|
|
603
|
+
time_ms for time_ms, count in readings if count >= 2
|
|
604
|
+
][:512],
|
|
605
|
+
}
|
|
606
|
+
)
|
|
607
|
+
return {
|
|
608
|
+
"method": "object-detection-anonymous-tracking",
|
|
609
|
+
"sampledFrames": len(observations),
|
|
610
|
+
**(
|
|
611
|
+
{"sampleIntervalSecs": round(sample_interval_secs, 3)}
|
|
612
|
+
if sample_interval_secs is not None
|
|
613
|
+
else {}
|
|
614
|
+
),
|
|
615
|
+
"tracks": tracked,
|
|
616
|
+
"labels": labels,
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _reconciled_visible_subjects(
|
|
621
|
+
semantic_observations: list[dict[str, Any]],
|
|
622
|
+
) -> list[dict[str, Any]]:
|
|
623
|
+
"""Aggregate only frame-grounded subject observations from semantic reads.
|
|
624
|
+
|
|
625
|
+
The VLM protocol emits a JSON object for each person it actually sees in a
|
|
626
|
+
numbered source frame. Discussed/off-camera names and detector track IDs
|
|
627
|
+
never enter this ledger, so a source-wide person question cannot turn
|
|
628
|
+
either into a fake visible participant.
|
|
629
|
+
"""
|
|
630
|
+
records: list[tuple[str, str, int, int]] = []
|
|
631
|
+
allowed_basis = {"source-named", "source-described", "unresolved"}
|
|
632
|
+
for observation in semantic_observations:
|
|
633
|
+
observation_start = max(0, int(observation.get("startMs") or 0))
|
|
634
|
+
observation_end = max(
|
|
635
|
+
observation_start,
|
|
636
|
+
int(observation.get("endMs") or observation_start),
|
|
637
|
+
)
|
|
638
|
+
for line in str(observation.get("text") or "").splitlines():
|
|
639
|
+
if not line.startswith("Visible subject: "):
|
|
640
|
+
continue
|
|
641
|
+
try:
|
|
642
|
+
subject = json.loads(line.removeprefix("Visible subject: "))
|
|
643
|
+
except json.JSONDecodeError:
|
|
644
|
+
continue
|
|
645
|
+
if not isinstance(subject, dict):
|
|
646
|
+
continue
|
|
647
|
+
identity = " ".join(str(subject.get("identity") or "").split())[:180]
|
|
648
|
+
basis = str(subject.get("identityBasis") or "").strip()
|
|
649
|
+
try:
|
|
650
|
+
start_ms = int(subject.get("startMs"))
|
|
651
|
+
end_ms = int(subject.get("endMs"))
|
|
652
|
+
except (TypeError, ValueError):
|
|
653
|
+
continue
|
|
654
|
+
if (
|
|
655
|
+
not identity
|
|
656
|
+
or basis not in allowed_basis
|
|
657
|
+
or start_ms > end_ms
|
|
658
|
+
or start_ms < observation_start
|
|
659
|
+
or end_ms > observation_end
|
|
660
|
+
):
|
|
661
|
+
continue
|
|
662
|
+
records.append((identity, basis, start_ms, end_ms))
|
|
663
|
+
|
|
664
|
+
# A reader can emit a source-grounded name followed by a visual reminder in
|
|
665
|
+
# parentheses (for example, ``Name (person in green)``) while conservatively
|
|
666
|
+
# labelling the complete string as a description. The named prefix is not
|
|
667
|
+
# a face-recognition guess: it is already an exact source-named anchor in
|
|
668
|
+
# this ledger. Collapse that representation only when the entire prefix
|
|
669
|
+
# equals an anchored name. Purely similar clothing/role descriptions stay
|
|
670
|
+
# separate, because no source evidence establishes that identity link.
|
|
671
|
+
named_keys = {
|
|
672
|
+
identity.casefold()
|
|
673
|
+
for identity, basis, _start_ms, _end_ms in records
|
|
674
|
+
if basis == "source-named"
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
def identity_key(identity: str) -> str:
|
|
678
|
+
direct = identity.casefold()
|
|
679
|
+
if direct in named_keys:
|
|
680
|
+
return direct
|
|
681
|
+
prefix = identity.split("(", 1)[0].strip().casefold()
|
|
682
|
+
return prefix if prefix in named_keys else direct
|
|
683
|
+
|
|
684
|
+
grouped: dict[str, list[tuple[str, str, int, int]]] = defaultdict(list)
|
|
685
|
+
for record in records:
|
|
686
|
+
grouped[identity_key(record[0])].append(record)
|
|
687
|
+
|
|
688
|
+
subjects: list[dict[str, Any]] = []
|
|
689
|
+
for records in sorted(
|
|
690
|
+
grouped.values(), key=lambda items: (min(item[2] for item in items), items[0][0].casefold())
|
|
691
|
+
):
|
|
692
|
+
named = sorted({identity for identity, basis, _start, _end in records if basis == "source-named"}, key=str.casefold)
|
|
693
|
+
identity = named[0] if named else sorted({item[0] for item in records}, key=str.casefold)[0]
|
|
694
|
+
basis = (
|
|
695
|
+
"source-named"
|
|
696
|
+
if named
|
|
697
|
+
else "source-described"
|
|
698
|
+
if any(item[1] == "source-described" for item in records)
|
|
699
|
+
else "unresolved"
|
|
700
|
+
)
|
|
701
|
+
ranges = [(start_ms, end_ms) for _identity, _basis, start_ms, end_ms in records]
|
|
702
|
+
merged: list[list[int]] = []
|
|
703
|
+
for start_ms, end_ms in sorted(set(ranges)):
|
|
704
|
+
if merged and start_ms <= merged[-1][1]:
|
|
705
|
+
merged[-1][1] = max(merged[-1][1], end_ms)
|
|
706
|
+
else:
|
|
707
|
+
merged.append([start_ms, end_ms])
|
|
708
|
+
subjects.append(
|
|
709
|
+
{
|
|
710
|
+
"identity": identity,
|
|
711
|
+
"identityBasis": basis,
|
|
712
|
+
"appearances": [
|
|
713
|
+
{
|
|
714
|
+
"startMs": start_ms,
|
|
715
|
+
"endMs": end_ms,
|
|
716
|
+
"confidence": "direct",
|
|
717
|
+
}
|
|
718
|
+
for start_ms, end_ms in merged
|
|
719
|
+
],
|
|
720
|
+
"observedDurationMs": sum(end_ms - start_ms for start_ms, end_ms in merged),
|
|
721
|
+
"observationCount": len(ranges),
|
|
722
|
+
}
|
|
723
|
+
)
|
|
724
|
+
return subjects
|
|
725
|
+
|
|
726
|
+
|
|
550
727
|
def _retain_clip_frame(
|
|
551
728
|
sampler: MotionSampler,
|
|
552
729
|
frames: list[tuple[int, np.ndarray]],
|
|
@@ -838,7 +1015,7 @@ def _semantic_clip_budget(mode: str, duration_seconds: float, available: int) ->
|
|
|
838
1015
|
These rates keep chronological coverage while preventing a long source from
|
|
839
1016
|
turning into hundreds of nearly-identical model calls.
|
|
840
1017
|
"""
|
|
841
|
-
clips_per_hour = {"fast": 30, "balanced": 60, "thorough":
|
|
1018
|
+
clips_per_hour = {"fast": 30, "balanced": 60, "thorough": 90}.get(mode, 60)
|
|
842
1019
|
minimum = {"fast": 12, "balanced": 24, "thorough": 48}.get(mode, 24)
|
|
843
1020
|
return min(
|
|
844
1021
|
available, max(minimum, math.ceil(duration_seconds / 3_600 * clips_per_hour))
|
|
@@ -1451,6 +1628,24 @@ def _run_pipeline(
|
|
|
1451
1628
|
plan = replace(plan, use_semantic_vision=False)
|
|
1452
1629
|
elif brief.get("requireSemanticVision"):
|
|
1453
1630
|
plan = replace(plan, use_semantic_vision=True)
|
|
1631
|
+
covers_full_source = (
|
|
1632
|
+
len(important_ranges) == 1
|
|
1633
|
+
and important_ranges[0][0] <= 0.1
|
|
1634
|
+
and important_ranges[0][1] >= probe.duration_seconds - 0.5
|
|
1635
|
+
)
|
|
1636
|
+
if not important_ranges or covers_full_source:
|
|
1637
|
+
sample_interval_secs, priority_sample_interval_secs = bounded_visual_sampling_intervals(
|
|
1638
|
+
plan.mode,
|
|
1639
|
+
probe.duration_seconds,
|
|
1640
|
+
plan.sample_interval_secs,
|
|
1641
|
+
plan.priority_sample_interval_secs,
|
|
1642
|
+
[(item.start_secs, item.end_secs) for item in plan.priority_ranges],
|
|
1643
|
+
)
|
|
1644
|
+
plan = replace(
|
|
1645
|
+
plan,
|
|
1646
|
+
sample_interval_secs=sample_interval_secs,
|
|
1647
|
+
priority_sample_interval_secs=priority_sample_interval_secs,
|
|
1648
|
+
)
|
|
1454
1649
|
plan = replace(
|
|
1455
1650
|
plan,
|
|
1456
1651
|
estimated_seconds=estimate_plan_runtime(plan, probe.duration_seconds),
|
|
@@ -1506,7 +1701,20 @@ def _run_pipeline(
|
|
|
1506
1701
|
if len(text) >= 2 and confidence >= 0.5:
|
|
1507
1702
|
text_occurrences[text].append(int(observation["timeMs"]))
|
|
1508
1703
|
text_confidence_totals[text] += confidence
|
|
1509
|
-
tracker = AnonymousTracker(
|
|
1704
|
+
tracker = AnonymousTracker(
|
|
1705
|
+
max_gap_ms=math.ceil(
|
|
1706
|
+
max(plan.sample_interval_secs, plan.priority_sample_interval_secs) * 1_500
|
|
1707
|
+
)
|
|
1708
|
+
)
|
|
1709
|
+
ocr_interval_ms = round(
|
|
1710
|
+
ocr_sampling_interval(
|
|
1711
|
+
plan.mode,
|
|
1712
|
+
probe.duration_seconds,
|
|
1713
|
+
plan.sample_interval_secs,
|
|
1714
|
+
)
|
|
1715
|
+
* 1_000
|
|
1716
|
+
)
|
|
1717
|
+
next_ocr_sample_ms = -1
|
|
1510
1718
|
clip_plan = scene_detector.plan_clips(
|
|
1511
1719
|
path,
|
|
1512
1720
|
important_ranges or [(0.0, probe.duration_seconds)],
|
|
@@ -1553,7 +1761,10 @@ def _run_pipeline(
|
|
|
1553
1761
|
)
|
|
1554
1762
|
detections = operators.detect(frame) if plan.use_object_detection else []
|
|
1555
1763
|
tracker.update(detections, time_ms)
|
|
1556
|
-
ocr_lines =
|
|
1764
|
+
ocr_lines = []
|
|
1765
|
+
if plan.use_ocr and time_ms >= next_ocr_sample_ms:
|
|
1766
|
+
ocr_lines = operators.read_text(frame)
|
|
1767
|
+
next_ocr_sample_ms = time_ms + max(1, ocr_interval_ms)
|
|
1557
1768
|
if plan.use_semantic_vision and clip_starts_ms:
|
|
1558
1769
|
clip_index = min(
|
|
1559
1770
|
max(bisect.bisect_right(clip_starts_ms, time_ms) - 1, 0),
|
|
@@ -1785,6 +1996,14 @@ def _run_pipeline(
|
|
|
1785
1996
|
"narrative": [],
|
|
1786
1997
|
"context": [],
|
|
1787
1998
|
"sourceItems": [],
|
|
1999
|
+
"sourceActivityStructures": [],
|
|
2000
|
+
"sourceTaskInstances": [],
|
|
2001
|
+
"sourceInventoryCoverage": {
|
|
2002
|
+
"complete": False,
|
|
2003
|
+
"totalWindows": 0,
|
|
2004
|
+
"processedWindows": 0,
|
|
2005
|
+
"reason": "interactive inspection does not run a full source inventory",
|
|
2006
|
+
},
|
|
1788
2007
|
"uncertainties": [],
|
|
1789
2008
|
}
|
|
1790
2009
|
else:
|
|
@@ -1809,8 +2028,31 @@ def _run_pipeline(
|
|
|
1809
2028
|
transcript=transcript,
|
|
1810
2029
|
semantic_observations=semantic_evidence,
|
|
1811
2030
|
overlay_text=recurring_overlay_text,
|
|
2031
|
+
on_progress=lambda completed, total: smooth.step(
|
|
2032
|
+
"synthesize",
|
|
2033
|
+
completed,
|
|
2034
|
+
total,
|
|
2035
|
+
f"Cataloging source units ({completed}/{total})",
|
|
2036
|
+
PHASES["synthesize"],
|
|
2037
|
+
span_seconds=max(12, total * 8),
|
|
2038
|
+
unit="source windows",
|
|
2039
|
+
),
|
|
1812
2040
|
)
|
|
2041
|
+
knowledge_summary["sourceActivityStructures"] = planner.source_activity_structures
|
|
2042
|
+
knowledge_summary["sourceTaskInstances"] = planner.source_task_instances
|
|
2043
|
+
knowledge_summary["sourceInventoryCoverage"] = planner.source_inventory_coverage
|
|
2044
|
+
reconciled_visible_subjects = _reconciled_visible_subjects(semantic_evidence)
|
|
2045
|
+
if reconciled_visible_subjects:
|
|
2046
|
+
# The synthesis model is a compact narrative reader. Its selected
|
|
2047
|
+
# excerpts must not discard the complete frame-grounded presence trail
|
|
2048
|
+
# that the visual reader already produced across the source.
|
|
2049
|
+
knowledge_summary["visibleSubjects"] = reconciled_visible_subjects
|
|
1813
2050
|
elapsed_seconds = round(time.monotonic() - pipeline_started, 3)
|
|
2051
|
+
retained_tracks = [
|
|
2052
|
+
track
|
|
2053
|
+
for track in tracker.summaries()
|
|
2054
|
+
if int(track.get("observations") or 0) >= 2
|
|
2055
|
+
]
|
|
1814
2056
|
result = {
|
|
1815
2057
|
"schemaVersion": 1,
|
|
1816
2058
|
"durationMs": round((source_duration_secs or probe.duration_seconds) * 1_000),
|
|
@@ -1823,11 +2065,12 @@ def _run_pipeline(
|
|
|
1823
2065
|
"transcript": transcript,
|
|
1824
2066
|
"detectedLanguage": detected_language,
|
|
1825
2067
|
"visualObservations": observations,
|
|
1826
|
-
"tracks":
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
2068
|
+
"tracks": retained_tracks,
|
|
2069
|
+
"anonymousPresenceLedger": _anonymous_presence_ledger(
|
|
2070
|
+
observations,
|
|
2071
|
+
retained_tracks,
|
|
2072
|
+
plan.sample_interval_secs,
|
|
2073
|
+
),
|
|
1831
2074
|
"recurringOverlayText": recurring_overlay_text,
|
|
1832
2075
|
# Gateway batches complete out of order. Persisting arrival order
|
|
1833
2076
|
# makes chronological retrieval and timeline answers unnecessarily
|
|
@@ -1881,6 +2124,8 @@ def _run_pipeline(
|
|
|
1881
2124
|
"sourceFrames": source_frames,
|
|
1882
2125
|
"decodedFrames": decoded_frames,
|
|
1883
2126
|
"analyzedFrames": analyzed_frames,
|
|
2127
|
+
"visualSampleIntervalSecs": round(plan.sample_interval_secs, 3),
|
|
2128
|
+
"ocrSampleIntervalSecs": round(ocr_interval_ms / 1_000, 3),
|
|
1884
2129
|
"heavyOperatorsDisabled": skip_heavy_operators,
|
|
1885
2130
|
"priorityRanges": [
|
|
1886
2131
|
{
|
|
@@ -86,6 +86,37 @@ _SCHEMA = {
|
|
|
86
86
|
"required": ["name", "what", "howIdentified"],
|
|
87
87
|
},
|
|
88
88
|
},
|
|
89
|
+
"visibleSubjects": {
|
|
90
|
+
"type": "array",
|
|
91
|
+
"maxItems": 12,
|
|
92
|
+
"items": {
|
|
93
|
+
"type": "object",
|
|
94
|
+
"properties": {
|
|
95
|
+
"identity": {"type": "string", "maxLength": 180},
|
|
96
|
+
"identityBasis": {
|
|
97
|
+
"type": "string",
|
|
98
|
+
"enum": [
|
|
99
|
+
"source-named",
|
|
100
|
+
"source-described",
|
|
101
|
+
"unresolved",
|
|
102
|
+
],
|
|
103
|
+
},
|
|
104
|
+
"appearances": {
|
|
105
|
+
"type": "array",
|
|
106
|
+
"maxItems": 12,
|
|
107
|
+
"items": {
|
|
108
|
+
"type": "object",
|
|
109
|
+
"properties": {
|
|
110
|
+
"startFrame": {"type": "integer", "minimum": 0},
|
|
111
|
+
"endFrame": {"type": "integer", "minimum": 0},
|
|
112
|
+
},
|
|
113
|
+
"required": ["startFrame", "endFrame"],
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
"required": ["identity", "identityBasis", "appearances"],
|
|
118
|
+
},
|
|
119
|
+
},
|
|
89
120
|
"visibleText": {
|
|
90
121
|
"type": "array",
|
|
91
122
|
"maxItems": 12,
|
|
@@ -311,6 +342,14 @@ def _build_prompt(
|
|
|
311
342
|
"source genuinely never names them -- not merely because you are being cautious.\n"
|
|
312
343
|
"- Name a person only where this clip shows a readable name label, synchronized speech binds "
|
|
313
344
|
"the name to them, or the supplied evidence explicitly preserves that identity across the cut.\n"
|
|
345
|
+
"- A continuity candidate is a source-grounded name observed earlier in this same recording. "
|
|
346
|
+
"It can preserve a name across an uninterrupted source track or an explicit source handoff, "
|
|
347
|
+
"but it is never permission to identify a lookalike from facial or clothing resemblance alone.\n"
|
|
348
|
+
"- visibleSubjects is a separate ledger of people who are actually visible in the supplied "
|
|
349
|
+
"frames. Do not put someone there merely because they are heard, discussed, named in a caption, "
|
|
350
|
+
"or inferred to be off camera. For each observed appearance, return inclusive startFrame and "
|
|
351
|
+
"endFrame indexes using the numbered frame markers for that clip. Use source-named only for a "
|
|
352
|
+
"source-bound name; otherwise use a source-described stable descriptor or unresolved.\n"
|
|
314
353
|
"- Note appearance where it distinguishes participants: colours of clothing or livery, and "
|
|
315
354
|
"which group wears what. That is often how a viewer tells two groups apart.\n"
|
|
316
355
|
"- Keep an individual's name distinct from a collective one. A group, organization, role, "
|
|
@@ -346,6 +385,8 @@ def _build_prompt(
|
|
|
346
385
|
"markdown fence, with this exact top-level shape: "
|
|
347
386
|
"{\"clips\":[{\"clipIndex\":0,\"summary\":\"the note\","
|
|
348
387
|
"\"entities\":[{\"name\":\"...\",\"what\":\"...\",\"howIdentified\":\"...\"}],"
|
|
388
|
+
"\"visibleSubjects\":[{\"identity\":\"...\",\"identityBasis\":\"source-named|source-described|unresolved\","
|
|
389
|
+
"\"appearances\":[{\"startFrame\":0,\"endFrame\":0}]}],"
|
|
349
390
|
"\"visibleText\":[{\"text\":\"exact text\",\"means\":\"what it conveys\"}],"
|
|
350
391
|
"\"events\":[{\"what\":\"...\",\"basis\":\"read|inferred\"}],"
|
|
351
392
|
"\"sourceQuestions\":[{\"text\":\"exact source question\",\"answer\":\"\","
|
|
@@ -365,9 +406,11 @@ def _build_prompt(
|
|
|
365
406
|
prompt += " Questions to resolve: " + " | ".join(questions[:4])[:1600] + "."
|
|
366
407
|
if known_entities:
|
|
367
408
|
prompt += (
|
|
368
|
-
"
|
|
409
|
+
" Continuity candidates from earlier clips: "
|
|
369
410
|
+ " | ".join(known_entities[:20])[:1200]
|
|
370
|
-
+ "."
|
|
411
|
+
+ ". These are leads, not proof: only reuse an identity when the current source "
|
|
412
|
+
"evidence or an uninterrupted visible track establishes it; never identify someone by "
|
|
413
|
+
"visual resemblance alone."
|
|
371
414
|
)
|
|
372
415
|
for index, clip in enumerate(batch):
|
|
373
416
|
prompt += f"\n\nCLIP {index} covers {clip.start_ms / 1000:.1f}s-{clip.end_ms / 1000:.1f}s."
|
|
@@ -381,7 +424,14 @@ def _content_for_batch(batch: list[ClipCaptionRequest], urls_by_clip: dict[str,
|
|
|
381
424
|
content: list[dict[str, Any]] = []
|
|
382
425
|
for index, clip in enumerate(batch):
|
|
383
426
|
content.append({"type": "text", "text": f"--- CLIP {index} frames ---"})
|
|
384
|
-
for url in urls_by_clip[clip.clip_id]:
|
|
427
|
+
for frame_index, url in enumerate(urls_by_clip[clip.clip_id]):
|
|
428
|
+
time_ms = clip.frames[frame_index][0]
|
|
429
|
+
content.append(
|
|
430
|
+
{
|
|
431
|
+
"type": "text",
|
|
432
|
+
"text": f"CLIP {index} FRAME {frame_index} at {time_ms / 1000:.3f}s",
|
|
433
|
+
}
|
|
434
|
+
)
|
|
385
435
|
content.append({"type": "image_url", "image_url": {"url": url}})
|
|
386
436
|
return content
|
|
387
437
|
|
|
@@ -479,6 +529,51 @@ def _note_lines(entry: dict[str, Any]) -> list[str]:
|
|
|
479
529
|
return lines
|
|
480
530
|
|
|
481
531
|
|
|
532
|
+
def _visible_subject_lines(entry: dict[str, Any], clip: ClipCaptionRequest) -> list[str]:
|
|
533
|
+
"""Persist source-visible identities in a machine-readable evidence line.
|
|
534
|
+
|
|
535
|
+
The protocol describes the supplied frame indices rather than the user's
|
|
536
|
+
language or a video genre. It allows the later index to aggregate actual
|
|
537
|
+
observations without treating every discussed name as an on-screen person.
|
|
538
|
+
"""
|
|
539
|
+
lines: list[str] = []
|
|
540
|
+
allowed_basis = {"source-named", "source-described", "unresolved"}
|
|
541
|
+
frame_times = [time_ms for time_ms, _frame in clip.frames]
|
|
542
|
+
if not frame_times:
|
|
543
|
+
return lines
|
|
544
|
+
for subject in entry.get("visibleSubjects") or []:
|
|
545
|
+
if not isinstance(subject, dict):
|
|
546
|
+
continue
|
|
547
|
+
identity = " ".join(str(subject.get("identity") or "").split())[:180]
|
|
548
|
+
basis = str(subject.get("identityBasis") or "").strip()
|
|
549
|
+
if not identity or basis not in allowed_basis:
|
|
550
|
+
continue
|
|
551
|
+
for appearance in subject.get("appearances") or []:
|
|
552
|
+
if not isinstance(appearance, dict):
|
|
553
|
+
continue
|
|
554
|
+
try:
|
|
555
|
+
start_index = int(appearance.get("startFrame"))
|
|
556
|
+
end_index = int(appearance.get("endFrame"))
|
|
557
|
+
except (TypeError, ValueError):
|
|
558
|
+
continue
|
|
559
|
+
if not (0 <= start_index <= end_index < len(frame_times)):
|
|
560
|
+
continue
|
|
561
|
+
lines.append(
|
|
562
|
+
"Visible subject: "
|
|
563
|
+
+ json.dumps(
|
|
564
|
+
{
|
|
565
|
+
"identity": identity,
|
|
566
|
+
"identityBasis": basis,
|
|
567
|
+
"startMs": frame_times[start_index],
|
|
568
|
+
"endMs": frame_times[end_index],
|
|
569
|
+
},
|
|
570
|
+
ensure_ascii=False,
|
|
571
|
+
separators=(",", ":"),
|
|
572
|
+
)
|
|
573
|
+
)
|
|
574
|
+
return lines
|
|
575
|
+
|
|
576
|
+
|
|
482
577
|
def _normalized_source_terms(value: str) -> list[str]:
|
|
483
578
|
return re.findall(r"[\w]+", value.casefold(), re.UNICODE)
|
|
484
579
|
|
|
@@ -567,12 +662,7 @@ def _parse_response(
|
|
|
567
662
|
{"subject": subject, "relation": relation, "value": value}
|
|
568
663
|
)
|
|
569
664
|
uncertainty = str(entry.get("uncertainty") or "").strip()
|
|
570
|
-
|
|
571
|
-
"Observed context (not a complete answer): "
|
|
572
|
-
if claim_verdict == "partial" and summary
|
|
573
|
-
else ""
|
|
574
|
-
)
|
|
575
|
-
parts = [summary_prefix + summary]
|
|
665
|
+
parts = [summary]
|
|
576
666
|
# Source-authored questions are an exhaustive retrieval surface,
|
|
577
667
|
# so keep them ahead of optional detail that may fill the note's
|
|
578
668
|
# bounded text budget.
|
|
@@ -597,6 +687,7 @@ def _parse_response(
|
|
|
597
687
|
parts.append(f"Source question ({source_basis}): {source_text}")
|
|
598
688
|
if source_answer:
|
|
599
689
|
parts.append(f"Source answer: {source_answer}")
|
|
690
|
+
parts.extend(_visible_subject_lines(entry, batch[index]))
|
|
600
691
|
parts.extend(note_lines)
|
|
601
692
|
if isinstance(claims, list):
|
|
602
693
|
parts.extend(
|
|
@@ -660,6 +751,12 @@ class GatewayVisionClient:
|
|
|
660
751
|
# parallelism shortens a full-video run without reducing coverage or
|
|
661
752
|
# changing the visual evidence sent to the model.
|
|
662
753
|
self.max_concurrency = max(1, min(24, int(os.getenv("LARKUP_VIDEO_GATEWAY_CONCURRENCY", "24"))))
|
|
754
|
+
# Earlier batches establish source-grounded continuity candidates for
|
|
755
|
+
# later batches. A wave still runs independently in parallel; only the
|
|
756
|
+
# compact, evidence-backed candidates cross its boundary.
|
|
757
|
+
self.continuity_wave_batches = max(
|
|
758
|
+
1, min(24, int(os.getenv("LARKUP_VIDEO_CONTINUITY_WAVE_BATCHES", "4")))
|
|
759
|
+
)
|
|
663
760
|
self.limiter = GatewayRateLimiter(
|
|
664
761
|
int(os.getenv("LARKUP_VIDEO_GATEWAY_REQUESTS_PER_MINUTE", "60"))
|
|
665
762
|
)
|
|
@@ -1011,30 +1108,39 @@ class GatewayVisionClient:
|
|
|
1011
1108
|
batches = self._batches_for(clips)
|
|
1012
1109
|
results: dict[str, tuple[str, float]] = {}
|
|
1013
1110
|
completed = 0
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1111
|
+
continuity_entities = list(known_entities or [])
|
|
1112
|
+
for start in range(0, len(batches), self.continuity_wave_batches):
|
|
1113
|
+
wave = batches[start : start + self.continuity_wave_batches]
|
|
1114
|
+
wave_results: list[tuple[int, dict[str, tuple[str, float]]]] = []
|
|
1115
|
+
with ThreadPoolExecutor(max_workers=min(self.max_concurrency, len(wave))) as pool:
|
|
1116
|
+
futures = {
|
|
1117
|
+
pool.submit(
|
|
1118
|
+
self._describe_batch,
|
|
1119
|
+
batch,
|
|
1120
|
+
goal,
|
|
1121
|
+
questions,
|
|
1122
|
+
spoken_context,
|
|
1123
|
+
continuity_entities,
|
|
1124
|
+
model,
|
|
1125
|
+
max_output_tokens,
|
|
1126
|
+
reasoning_effort,
|
|
1127
|
+
): index
|
|
1128
|
+
for index, batch in enumerate(wave)
|
|
1129
|
+
}
|
|
1130
|
+
for future in as_completed(futures):
|
|
1131
|
+
batch_result = future.result()
|
|
1132
|
+
wave_results.append((futures[future], batch_result))
|
|
1133
|
+
results.update(batch_result)
|
|
1134
|
+
# Report usable evidence, not merely finished HTTP requests.
|
|
1135
|
+
# A rejected batch must not make live progress claim that its
|
|
1136
|
+
# clips were analyzed before the coverage gate fails the job.
|
|
1137
|
+
completed += len(batch_result)
|
|
1138
|
+
if on_progress:
|
|
1139
|
+
on_progress(completed, len(clips))
|
|
1140
|
+
for _, batch_result in sorted(wave_results):
|
|
1141
|
+
continuity_entities = self._merge_continuity_entities(
|
|
1142
|
+
continuity_entities, batch_result
|
|
1143
|
+
)
|
|
1038
1144
|
missing_count = len(clips) - len(results)
|
|
1039
1145
|
if missing_count:
|
|
1040
1146
|
provider_error = (
|
|
@@ -1049,6 +1155,52 @@ class GatewayVisionClient:
|
|
|
1049
1155
|
self.last_error = None
|
|
1050
1156
|
return results
|
|
1051
1157
|
|
|
1158
|
+
@staticmethod
|
|
1159
|
+
def _merge_continuity_entities(
|
|
1160
|
+
existing: list[str], captions: dict[str, tuple[str, float]]
|
|
1161
|
+
) -> list[str]:
|
|
1162
|
+
"""Keep compact source-grounded identity candidates across clip waves.
|
|
1163
|
+
|
|
1164
|
+
The visible-subject protocol is the authoritative identity ledger. The
|
|
1165
|
+
older ``Present:`` prose remains useful for compatibility, but must not
|
|
1166
|
+
be the only way a named subject survives into a later bounded reading.
|
|
1167
|
+
"""
|
|
1168
|
+
merged: list[str] = []
|
|
1169
|
+
seen: set[str] = set()
|
|
1170
|
+
for candidate in existing:
|
|
1171
|
+
value = str(candidate).strip()[:120]
|
|
1172
|
+
key = value.casefold()
|
|
1173
|
+
if value and key not in seen:
|
|
1174
|
+
merged.append(value)
|
|
1175
|
+
seen.add(key)
|
|
1176
|
+
for text, _confidence in captions.values():
|
|
1177
|
+
for line in text.splitlines():
|
|
1178
|
+
if not line.startswith("Visible subject: "):
|
|
1179
|
+
continue
|
|
1180
|
+
try:
|
|
1181
|
+
subject = json.loads(line.removeprefix("Visible subject: "))
|
|
1182
|
+
except json.JSONDecodeError:
|
|
1183
|
+
continue
|
|
1184
|
+
if not isinstance(subject, dict):
|
|
1185
|
+
continue
|
|
1186
|
+
if str(subject.get("identityBasis") or "").strip() != "source-named":
|
|
1187
|
+
continue
|
|
1188
|
+
value = " ".join(str(subject.get("identity") or "").split())[:120]
|
|
1189
|
+
key = value.casefold()
|
|
1190
|
+
if value and key not in seen:
|
|
1191
|
+
merged.append(value)
|
|
1192
|
+
seen.add(key)
|
|
1193
|
+
for line in text.splitlines():
|
|
1194
|
+
if not line.startswith("Present: "):
|
|
1195
|
+
continue
|
|
1196
|
+
value = line.removeprefix("Present: ").split(" —", 1)[0]
|
|
1197
|
+
value = value.split(" (identified by", 1)[0].strip()[:120]
|
|
1198
|
+
key = value.casefold()
|
|
1199
|
+
if value and key not in seen:
|
|
1200
|
+
merged.append(value)
|
|
1201
|
+
seen.add(key)
|
|
1202
|
+
return merged[:40]
|
|
1203
|
+
|
|
1052
1204
|
def _batches_for(self, clips: list[ClipCaptionRequest]) -> list[list[ClipCaptionRequest]]:
|
|
1053
1205
|
batches: list[list[ClipCaptionRequest]] = []
|
|
1054
1206
|
batch: list[ClipCaptionRequest] = []
|
|
@@ -1123,7 +1275,12 @@ class GeminiVisionClient(GatewayVisionClient):
|
|
|
1123
1275
|
parts: list[dict[str, Any]] = []
|
|
1124
1276
|
for index, clip in enumerate(batch):
|
|
1125
1277
|
parts.append({"text": f"--- CLIP {index} frames ---"})
|
|
1126
|
-
for
|
|
1278
|
+
for frame_index, (time_ms, frame) in enumerate(clip.frames):
|
|
1279
|
+
parts.append(
|
|
1280
|
+
{
|
|
1281
|
+
"text": f"CLIP {index} FRAME {frame_index} at {time_ms / 1000:.3f}s",
|
|
1282
|
+
}
|
|
1283
|
+
)
|
|
1127
1284
|
parts.append({"inline_data": _frame_to_inline_data(frame)})
|
|
1128
1285
|
parts.append(
|
|
1129
1286
|
{
|