CGVM-R2.6-Qwen3VL-8B-step600 / src /scripts /audit_content_overlap.py
XiangnanW's picture
Upload CGVM R2.6 step-000600 checkpoint, R2.6 source bundle (cgvm-r26-src-v1.tar.gz), and 4-round audit report
4ad9219 verified
Raw History Blame Contribute Delete
7.34 kB
#!/usr/bin/env python3
"""元数据规范化之外的跨剪辑内容匹配;完整覆盖前只报告partial审计。"""
from array import array
import argparse
import collections
import fcntl
import itertools
import json
import os
from pathlib import Path
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
from download_assets import atomic, safe_flock, sha
def main():
parser=argparse.ArgumentParser();parser.add_argument('--allow-partial',action='store_true');args=parser.parse_args()
cfg=json.loads((ROOT/'configs/content_overlap_protocol.json').read_text());started=time.perf_counter()
manifest=json.loads((ROOT/'manifests/training_videos.candidate.json').read_text())
training_inventory=json.loads((ROOT/'provenance/training_media_inventory.json').read_text())
eval_inventory=json.loads((ROOT/'provenance/eval_media_inventory.json').read_text())
videos=[];stale=[];inputs={}
for path in sorted((ROOT/'provenance/fingerprints').glob('*.json')):
value=json.loads(path.read_text())
if value['status']!='completed':continue
key=value['source_video']
if value['kind']=='training':
valid=key in manifest and key in training_inventory and value.get('media_frames')==training_inventory[key]['files']
else:valid=key in eval_inventory and value.get('media_sha256')==eval_inventory[key]['sha256']
if not valid:
stale.append(dict(kind=value['kind'],source_video=key,file=str(path.relative_to(ROOT))));continue
# 媒体恢复/候选重选后的旧指纹不计覆盖;旧文件保留供来源追溯。
inputs[str(path.relative_to(ROOT))]=sha(path)
value['fingerprint_file']=str(path);value['split']=manifest[value['source_video']]['splits'][0] if value['kind']=='training' else 'evaluation'
videos.append(value)
present={(v['kind'],v['source_video']) for v in videos}
expected={('training',v) for v in manifest}
media=json.loads((ROOT/'manifests/eval_media_expected.json').read_text())
expected.update(('evaluation','ovo/'+v) for v in media['ovo']);expected.update(('evaluation','streaming/'+v) for v in media['streaming'])
missing=sorted(expected-present)
if missing and not args.allow_partial:raise RuntimeError('指纹覆盖未完整,不能出最终去重结论')
common=collections.defaultdict(set)
for vid,video in enumerate(videos):
for frame in video['fingerprints']:
if frame['std']>=cfg['minimum_gray_standard_deviation']:common[int(frame['phash'],16)].add(vid)
ignored={h for h,ids in common.items() if len(ids)>cfg['common_hash_distinct_videos_skip_above']}
bandpairs=list(itertools.combinations(range(8),2));buckets={};frames=[]
for vid,video in enumerate(videos):
for frame in video['fingerprints']:
h=int(frame['phash'],16)
if frame['std']<cfg['minimum_gray_standard_deviation'] or h in ignored:continue
index=len(frames);frames.append((vid,frame['timestamp'],h,int(frame['dhash'],16),frame['width']/frame['height']))
parts=[(h>>(8*i))&255 for i in range(8)]
for pair,(a,b) in enumerate(bandpairs):
key=(pair<<16)|(parts[a]<<8)|parts[b]
if key not in buckets:buckets[key]=array('I')
buckets[key].append(index)
matches={};checked=0
for index,(vid,t,h,dhash,aspect) in enumerate(frames):
parts=[(h>>(8*i))&255 for i in range(8)];candidates=set()
for pair,(a,b) in enumerate(bandpairs):candidates.update(buckets[(pair<<16)|(parts[a]<<8)|parts[b]])
for other in candidates:
if other>=index:continue
other_vid,other_t,other_h,other_dhash,other_aspect=frames[other]
if other_vid==vid:continue
if abs(aspect/other_aspect-1)>cfg['aspect_ratio_relative_tolerance']:continue
checked+=1
if (h^other_h).bit_count()>cfg['phash_hamming_cap'] or (dhash^other_dhash).bit_count()>cfg['dhash_hamming_cap']:continue
left,right=(other_vid,vid) if other_vid<vid else (vid,other_vid)
lt,rt=(other_t,t) if other_vid<vid else (t,other_t)
offset=round((rt-lt)/cfg['offset_bin_seconds'])
key=(left,right,offset)
# 最多留128个实际支持,防止静态长片重复帧占用无界内存。
examples=matches.setdefault(key,[])
if len(examples)<128:examples.append((lt,rt,h,other_h))
if index%50000==0:print(json.dumps(dict(frames_checked=index,total=len(frames),candidate_temporal_groups=len(matches))),flush=True)
edges=[]
for (left,right,offset),examples in matches.items():
distinct=len({row[2] for row in examples})
if distinct<cfg['minimum_distinct_phashes']:continue
span_left=max(row[0] for row in examples)-min(row[0] for row in examples)
span_right=max(row[1] for row in examples)-min(row[1] for row in examples)
if min(span_left,span_right)<cfg['minimum_matched_span_seconds']:continue
a,b=videos[left],videos[right]
edge=dict(left=dict(kind=a['kind'],source_video=a['source_video'],split=a['split']),
right=dict(kind=b['kind'],source_video=b['source_video'],split=b['split']),
offset_bin=offset,distinct_phashes=distinct,support_span_seconds=[span_left,span_right],
support=[dict(left_time=x[0],right_time=x[1],left_phash=f'{x[3]:016x}',right_phash=f'{x[2]:016x}') for x in examples[:16]])
edges.append(edge)
excluded=set();cross_dev=[]
for edge in edges:
pair=[edge['left'],edge['right']]
if any(v['kind']=='evaluation' for v in pair):
excluded.update(v['source_video'] for v in pair if v['kind']=='training')
elif {v['split'] for v in pair}=={'train','dev'}:cross_dev.append(edge)
result=dict(status='partial' if missing else 'full_coverage_matching_complete',full_required_coverage=not missing,
protocol_sha256=sha(ROOT/'configs/content_overlap_protocol.json'),videos=len(videos),
fingerprint_input_sha256=inputs,stale_or_removed_fingerprints_excluded=stale,
training_candidate_manifest_sha256=sha(ROOT/'manifests/training_videos.candidate.json'),
eval_media_inventory_sha256=sha(ROOT/'provenance/eval_media_inventory.json'),
expected_videos=len(expected),missing=missing,nontrivial_frames=len(frames),candidate_pairs_checked=checked,
common_hashes_ignored=len(ignored),overlap_edges=edges,training_eval_conflict_videos=sorted(excluded),
train_dev_conflicts=cross_dev,wall_cpu_seconds=time.perf_counter()-started,
false_negative_boundary='does_not_prove_identity_of_nonoverlapping_parent_video_segments_or_all_large_crop_transformations')
atomic(ROOT/'provenance/content_overlap_audit.json',result)
print(json.dumps(dict(status=result['status'],videos=len(videos),edges=len(edges),train_eval_conflicts=len(excluded),train_dev_conflicts=len(cross_dev))),flush=True)
if __name__=='__main__':
with (ROOT/'coordination/content_overlap.lock').open('w') as lock:
safe_flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB);lock.write(str(os.getpid()));lock.flush();main()