File size: 5,486 Bytes
4ad9219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""核查真实重复媒体及可证实的评测父视频ID;不把匿名来源编造成已知URL。"""
import collections
import concurrent.futures
import json
from pathlib import Path
import sys
import time
import urllib.parse
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
from download_assets import atomic,sha
from prepare_online_manifest import identity


def audit():
    started=time.perf_counter();inventory_path=ROOT/'provenance/eval_media_inventory.json'
    inventory=json.loads(inventory_path.read_text());by_sha=collections.defaultdict(list);known={}
    for key,row in inventory.items():
        by_sha[row['sha256']].append(key)
        if key.startswith('ovo/'):
            canonical=identity(key.removeprefix('ovo/'))
            if canonical.startswith('youtube:'):known[key]=canonical
    recovery_path=ROOT/'configs/media_recovery.frozen.json'
    if recovery_path.exists():
        for video,item in json.loads(recovery_path.read_text())['recoveries'].items():
            proof_path=ROOT/item['proof_path'];proof=json.loads(proof_path.read_text())
            if sha(proof_path)!=item['proof_sha256'] or not proof['passed'] or proof['public_source']!=item['public_source']:
                raise ValueError('恢复父URL与实际身份核查证据不符')
            url=urllib.parse.urlparse(item['public_source']);video_id=None
            if url.hostname in ('www.youtube.com','youtube.com'):
                video_id=urllib.parse.parse_qs(url.query).get('v',[None])[0]
            elif url.hostname=='youtu.be':video_id=url.path.strip('/')
            if video_id:known[('streaming/' if item['benchmark']=='streamingbench' else 'ovo/')+video]='youtube:'+video_id
    duplicates=[dict(sha256=digest,sources=sorted(keys)) for digest,keys in sorted(by_sha.items()) if len(keys)>1]
    def check(key):
        row=inventory[key];path=ROOT/row['path'];digest=sha(path)
        return dict(source_video=key,path=row['path'],bytes=path.stat().st_size,actual_sha256=digest,
                    declared_sha256=row['sha256'],passed=digest==row['sha256'])
    with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
        checks=list(pool.map(check,[key for group in duplicates for key in group['sources']]))
    known_ids=set(known.values());hits=[];candidate_counts={};candidate_hashes={}
    for split,manifest in [('train','online_pilot20k.candidate.jsonl'),('dev','online_dev.candidate.jsonl')]:
        candidate_counts[split]=0;candidate_hashes[split]=sha(ROOT/'manifests'/manifest)
        for line in (ROOT/'manifests'/manifest).open():
            row=json.loads(line)
            candidate_counts[split]+=1
            if row['canonical_source'] in known_ids:
                hits.append(dict(split=split,id=row['id'],source_video=row['source_video'],canonical_source=row['canonical_source']))
    expected=json.loads((ROOT/'manifests/eval_media_expected.json').read_text())
    expected_keys={'ovo/'+key for key in expected['ovo']}|{'streaming/'+key for key in expected['streaming']}
    result=dict(passed=set(inventory)==expected_keys and all(row['passed'] for row in checks),
        scope='all_actual_extracted_media_SHA_metadata; duplicate_files_physically_rehashed; known_public_parent_IDs_only; no_model_predictions_read',
        sources=len(inventory),exact_identical_media_groups=duplicates,duplicate_source_files=sum(len(group['sources']) for group in duplicates),
        actual_duplicate_file_hashes_rechecked=checks,known_public_parent_by_eval_source=known,
        known_public_parent_count=len(known_ids),candidate_train_dev_same_parent_hits=hits,
        candidate_QA_counts_checked=candidate_counts,candidate_QA_manifest_sha256=candidate_hashes,
        parent_ID_evidence=dict(OVO='published_source_filename_normalization_with_documented_11_character_YouTube_ID_heuristic_not_all_URLs_fetched',
            Streaming='verified_publisher_URL_from_registered_media_recovery_only'),
        known_parent_conflict_videos=sorted({row['source_video'] for row in hits}),
        eval_media_inventory_sha256=sha(inventory_path),wall_seconds=time.perf_counter()-started,
        boundary='unknown_URLs_and_reencoded_or_nonoverlapping_parent_segments_need_separate_content_audit')
    target=ROOT/'provenance/eval_exact_media_duplicates.json'
    previous=json.loads(target.read_text()) if target.exists() else None
    stable=lambda row:{key:value for key,value in row.items() if key!='wall_seconds'}
    # 相同事实的再次只读核查不改冻结证据hash;每次真实检查耗时仍单独留档。
    if previous is not None and stable(previous)==stable(result):result=previous
    else:atomic(target,result)
    with (ROOT/'logs/eval_identity_checks.jsonl').open('a') as log:
        log.write(json.dumps(dict(timestamp=time.time(),wall_seconds=time.perf_counter()-started,
            duplicate_files_rehashed=len(checks),actual_bytes_rehashed=sum(row['bytes'] for row in checks),
            passed=result['passed'],proof_sha256=sha(target)))+'\n')
    print(json.dumps(dict(passed=result['passed'],sources=len(inventory),duplicate_groups=len(duplicates),
        duplicate_files=result['duplicate_source_files'],known_parent_IDs=len(known_ids),candidate_train_dev_parent_hits=len(hits))),flush=True)
    if not result['passed']:raise ValueError('实际评测重复媒体hash或源覆盖核查失败')
    return target,result


if __name__=='__main__':audit()