Skip to content

Commit fe89df7

Browse files
Improve Scene Atlas evidence review and duplicate detection
1 parent 559dc3f commit fe89df7

2 files changed

Lines changed: 206 additions & 28 deletions

File tree

‎src/facut/vlog/atlas.py‎

Lines changed: 91 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import hashlib
1212
import json
1313
import os
14+
import re
1415
import tempfile
1516
from pathlib import Path
1617
from typing import Any, Iterable, Literal
@@ -26,6 +27,11 @@
2627
ATLAS_VERSION = "1.1"
2728
DEFAULT_BATCH_SIZE = 12
2829
DEEP_SAMPLE_COUNT = 12
30+
DEEP_EVENT_SAMPLE_LIMIT = 12
31+
NEAR_DUPLICATE_DISTANCE = 4
32+
# Split all 64 bits into five disjoint bands. Any pair within distance four
33+
# must share at least one band exactly; the exact distance is still checked.
34+
_HASH_BANDS = ((0, 13), (13, 13), (26, 13), (39, 13), (52, 12))
2935

3036

3137
def _atlas_root(project_dir: str | Path) -> Path:
@@ -180,25 +186,21 @@ def _stored_observation_index(root: Path) -> dict[str, list[dict[str, Any]]]:
180186
return result
181187

182188

183-
def _current_observed_media(
184-
assets: list[dict[str, Any]],
185-
observations: dict[str, list[dict[str, Any]]],
189+
def _current_observations(
190+
asset: dict[str, Any],
191+
observations: list[dict[str, Any]],
186192
evidence_policy: dict[str, Any],
187-
) -> set[str]:
188-
hashes = {item["media_id"]: item["content_sha256"] for item in assets}
189-
return {
190-
media_id
191-
for media_id, records in observations.items()
192-
if any(
193-
item.get("content_sha256") == hashes.get(media_id)
194-
and isinstance(item.get("evidence_policy"), dict)
195-
and all(
196-
item["evidence_policy"].get(key) == value
197-
for key, value in evidence_policy.items()
198-
)
199-
for item in records
193+
) -> list[dict[str, Any]]:
194+
return [
195+
item
196+
for item in observations
197+
if item.get("content_sha256") == asset["content_sha256"]
198+
and isinstance(item.get("evidence_policy"), dict)
199+
and all(
200+
item["evidence_policy"].get(key) == value
201+
for key, value in evidence_policy.items()
200202
)
201-
}
203+
]
202204

203205

204206
def _deep_review_reasons(observations: list[dict[str, Any]]) -> list[str]:
@@ -225,24 +227,80 @@ def _deep_review_reasons(observations: list[dict[str, Any]]) -> list[str]:
225227
return sorted(reasons)
226228

227229

228-
def _hash_distance(left: str, right: str) -> int:
229-
return (int(left, 16) ^ int(right, 16)).bit_count()
230+
def _event_sample_times(
231+
duration: float | None, observations: list[dict[str, Any]]
232+
) -> list[float]:
233+
"""Suggest bounded extra looks near evidence-backed events, not new claims."""
234+
235+
if duration is None or duration <= 0:
236+
return []
237+
windows: set[tuple[float, float]] = set()
238+
for record in observations:
239+
# Deep review must not feed its own suggested windows.
240+
if not str(record.get("task_id", "")).startswith("atlas_baseline_"):
241+
continue
242+
if not _deep_review_reasons([record]):
243+
continue
244+
interval = record["observation"]["range"]
245+
start = min(duration, max(0.0, interval["start"]))
246+
end = min(duration, max(start, interval["end"]))
247+
windows.add((start, end))
248+
ordered = sorted(windows)
249+
if len(ordered) > DEEP_EVENT_SAMPLE_LIMIT:
250+
# Keep deterministic spread across a clip instead of taking only early events.
251+
last = len(ordered) - 1
252+
ordered = [
253+
ordered[index * last // (DEEP_EVENT_SAMPLE_LIMIT - 1)]
254+
for index in range(DEEP_EVENT_SAMPLE_LIMIT)
255+
]
256+
whole_clip = set(_sample_times(duration, DEEP_SAMPLE_COUNT))
257+
extra: set[float] = set()
258+
# Give each distinct window a midpoint before spending spare slots around it.
259+
for sample in (
260+
lambda start, end: (start + end) / 2,
261+
lambda start, end: start - 1,
262+
lambda start, end: end + 1,
263+
lambda start, end: start,
264+
lambda start, end: end,
265+
):
266+
for start, end in ordered:
267+
# Avoid asking for a frame at the exact (exclusive) end of media.
268+
last_frame = duration - min(0.01, duration / 2)
269+
timestamp = round(min(last_frame, max(0.0, sample(start, end))), 6)
270+
if timestamp not in whole_clip:
271+
extra.add(timestamp)
272+
if len(extra) == DEEP_EVENT_SAMPLE_LIMIT:
273+
return sorted(extra)
274+
return sorted(extra)
230275

231276

232277
def _annotate_near_duplicates(assets: list[dict[str, Any]]) -> None:
233278
"""Record perceptual candidates without excluding either source."""
234279

235-
fingerprints: list[tuple[dict[str, Any], str]] = []
280+
fingerprints: list[tuple[dict[str, Any], int]] = []
281+
bands: dict[tuple[int, int], list[int]] = {}
236282
for asset in assets:
237283
frames = asset.get("representative_frames") or []
238284
middle = frames[len(frames) // 2] if frames else {}
239-
value = middle.get("perceptual_hash")
240-
if isinstance(value, str) and len(value) == 16:
241-
fingerprints.append((asset, value))
285+
value = middle.get("perceptual_hash") if isinstance(middle, dict) else None
286+
if not isinstance(value, str) or not re.fullmatch(r"[0-9A-Fa-f]{16}", value):
287+
continue
288+
index = len(fingerprints)
289+
fingerprint = int(value, 16)
290+
fingerprints.append((asset, fingerprint))
291+
for shift, width in _HASH_BANDS:
292+
key = (shift, (fingerprint >> shift) & ((1 << width) - 1))
293+
bands.setdefault(key, []).append(index)
294+
242295
for index, (left, left_hash) in enumerate(fingerprints):
243-
for right, right_hash in fingerprints[index + 1 :]:
244-
distance = _hash_distance(left_hash, right_hash)
245-
if distance > 4:
296+
possible: set[int] = set()
297+
for shift, width in _HASH_BANDS:
298+
key = (shift, (left_hash >> shift) & ((1 << width) - 1))
299+
possible.update(right_index for right_index in bands[key] if right_index > index)
300+
for right_index in sorted(possible):
301+
right, right_hash = fingerprints[right_index]
302+
distance = (left_hash ^ right_hash).bit_count()
303+
if distance > NEAR_DUPLICATE_DISTANCE:
246304
continue
247305
left.setdefault("near_duplicate_candidates", []).append(
248306
{"media_id": right["media_id"], "hamming_distance": distance}
@@ -311,15 +369,20 @@ def build_scene_atlas(
311369
stored = _stored_observation_index(root)
312370
_annotate_near_duplicates(assets)
313371
evidence_policy = {"sampling": sampling, "max_gap": float(max_gap)}
314-
observed = _current_observed_media(assets, stored, evidence_policy)
372+
observed: set[str] = set()
315373
for asset in assets:
316-
reasons = _deep_review_reasons(stored.get(asset["media_id"], []))
374+
media_id = asset["media_id"]
375+
current = _current_observations(asset, stored.get(media_id, []), evidence_policy)
376+
if current:
377+
observed.add(media_id)
378+
reasons = _deep_review_reasons(current)
317379
if reasons:
318380
asset["deep_review"] = {
319381
"required": True,
320382
"reasons": reasons,
321383
"sample_count": DEEP_SAMPLE_COUNT,
322384
"sample_times": _sample_times(asset["duration"], DEEP_SAMPLE_COUNT),
385+
"event_sample_times": _event_sample_times(asset["duration"], current),
323386
}
324387

325388
old = _read_json(root / "atlas.json", {"tasks": []})

‎tests/test_vlog_atlas.py‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,3 +273,118 @@ def test_adaptive_sampling_bounds_long_clip_blind_regions(tmp_path) -> None:
273273
times = task["assets"][0]["baseline"]["sample_times"]
274274
assert len(times) > 3
275275
assert max(right - left for left, right in zip(times, times[1:])) <= 15.0
276+
277+
278+
@pytest.mark.parametrize("changed", ["content", "sampling_gap"])
279+
def test_stale_observation_does_not_schedule_deep_review(tmp_path, changed) -> None:
280+
manager = _manager(tmp_path, count=1)
281+
build_scene_atlas(manager)
282+
task = next_atlas_inspection_batch(manager.project_dir)
283+
result = ingest_atlas_observations(
284+
manager.require_document(),
285+
manager.project_dir,
286+
{
287+
"task_id": task["task_id"],
288+
"observations": _observations(task, confidence=0.5, actions=["fall"]),
289+
},
290+
)
291+
assert result["deep_pending"] == 1
292+
293+
max_gap = 15.0
294+
if changed == "content":
295+
replacement = tmp_path / "clip-000.mp4"
296+
replacement.write_bytes(b"replacement-video")
297+
manager.document.media[0].sha256 = hashlib_sha256(replacement.read_bytes())
298+
manager.document.media[0].size = replacement.stat().st_size
299+
manager.save(create_snapshot=False)
300+
else:
301+
max_gap = 10.0
302+
303+
rebuilt = build_scene_atlas(manager, max_gap=max_gap)
304+
assert rebuilt["baseline_pending"] == 1
305+
assert rebuilt["deep_pending"] == 0
306+
next_task = next_atlas_inspection_batch(manager.project_dir)
307+
assert next_task["assets"][0]["deep_review"]["reasons"] == []
308+
309+
310+
def test_deep_review_suggests_extra_samples_around_observed_event(tmp_path) -> None:
311+
manager = _manager(tmp_path, count=1)
312+
manager.document.media[0].technical.duration = 1800
313+
manager.save(create_snapshot=False)
314+
build_scene_atlas(manager)
315+
baseline = next_atlas_inspection_batch(manager.project_dir)
316+
records = _observations(baseline, actions=["fall"])
317+
records[0]["range"] = {"start": 723.0, "end": 724.0}
318+
ingest_atlas_observations(
319+
manager.require_document(),
320+
manager.project_dir,
321+
{"task_id": baseline["task_id"], "observations": records},
322+
)
323+
324+
deep = next_atlas_inspection_batch(manager.project_dir)
325+
review = deep["assets"][0]["deep_review"]
326+
assert deep["kind"] == "deep"
327+
assert review["sample_count"] == len(review["sample_times"]) == 12
328+
assert review["event_sample_times"] == [722.0, 723.0, 723.5, 724.0, 725.0]
329+
build_scene_atlas(manager)
330+
assert next_atlas_inspection_batch(manager.project_dir) == deep
331+
332+
333+
def test_event_sample_times_are_bounded_and_use_only_baseline_evidence() -> None:
334+
from facut.vlog.atlas import _event_sample_times
335+
336+
observations = [
337+
{
338+
"task_id": "atlas_baseline_example",
339+
"observation": {
340+
"range": {"start": float(i), "end": i + 0.8},
341+
"actions": ["fall"],
342+
},
343+
}
344+
for i in range(40)
345+
]
346+
observations.append(
347+
{
348+
"task_id": "atlas_deep_example",
349+
"observation": {"range": {"start": 48.0, "end": 49.0}, "actions": ["fall"]},
350+
}
351+
)
352+
times = _event_sample_times(50.0, observations)
353+
assert len(times) == 12
354+
assert times == _event_sample_times(50.0, list(reversed(observations)))
355+
assert times[0] == 0.4 and times[-1] == 39.4
356+
assert _event_sample_times(None, observations) == []
357+
358+
359+
def test_near_duplicate_index_matches_exhaustive_and_ignores_invalid_hashes() -> None:
360+
import random
361+
362+
rng = random.Random(42)
363+
anchors = [rng.getrandbits(64) for _ in range(25)]
364+
values = [
365+
anchor ^ sum(1 << bit for bit in rng.sample(range(64), distance))
366+
for anchor in anchors
367+
for distance in range(6)
368+
]
369+
# Distance four, with flips in four different bands; bit 63 must be covered.
370+
values.extend([0, (1 << 63) | (1 << 51) | (1 << 30) | 2])
371+
assets = [
372+
{"media_id": str(i), "representative_frames": [{"perceptual_hash": f"{value:016x}"}]}
373+
for i, value in enumerate(values)
374+
]
375+
assets.extend(
376+
[
377+
{"media_id": "invalid", "representative_frames": [{"perceptual_hash": "x" * 16}]},
378+
{"media_id": "null-frame", "representative_frames": [None]},
379+
]
380+
)
381+
_annotate_near_duplicates(assets)
382+
383+
for i, left in enumerate(values):
384+
expected = [
385+
{"media_id": str(j), "hamming_distance": distance}
386+
for j, right in enumerate(values)
387+
if i != j and (distance := (left ^ right).bit_count()) <= 4
388+
]
389+
assert assets[i].get("near_duplicate_candidates", []) == expected
390+
assert all("near_duplicate_candidates" not in item for item in assets[-2:])

0 commit comments

Comments
 (0)