1111import hashlib
1212import json
1313import os
14+ import re
1415import tempfile
1516from pathlib import Path
1617from typing import Any , Iterable , Literal
2627ATLAS_VERSION = "1.1"
2728DEFAULT_BATCH_SIZE = 12
2829DEEP_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
3137def _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
204206def _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
232277def _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" : []})
0 commit comments