File size: 12,056 Bytes
94f7dc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
"""Finalize per-file attribution and independently audit the CPU export on K:.

Code bodies are not changed. Publication metadata is finalized separately from
the frozen CPU extraction so original copyright notices are never discarded.
"""
from collections import Counter,defaultdict
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
from pathlib import Path
import shutil
import sys
import zipfile

ROOT=Path(__file__).resolve().parent.parent
sys.path[:0]=[str(ROOT/'scripts/rag-multisource'),str(ROOT/'scripts/runpod-rag')]
from multisource_core import license_header,group_split,sha
from filter_core import inspect_code,template_hash,SECRET,INJECTION


def save(path,d):path.write_text(json.dumps(d,indent=2,ensure_ascii=False)+'\n',encoding='utf-8',newline='\n')


def main():
    import requests
    import pyarrow as pa
    import pyarrow.parquet as pq
    import yaml
    latest_path=ROOT/'reports/rag-multisource-latest.json'
    latest=json.loads(latest_path.read_text(encoding='utf-8'));folder=Path(latest['report_path']);export=Path(latest['export_path'])
    assert export.resolve().is_relative_to(ROOT.resolve())
    original_manifest=json.loads((export/'checksums.json').read_text(encoding='utf-8'))
    for name,h in original_manifest.items():
        with (export/name).open('rb') as f:assert hashlib.file_digest(f,'sha256').hexdigest()==h,name
    cfg=json.loads((export/'processing_multisource/config.json').read_text(encoding='utf-8'));sources={s['id']:s for s in cfg['sources']}
    needed={}
    for source_id in ['aifaultbench','ml_dev_bench']:
        for path in (export/'sources'/source_id/'data').glob('*.parquet'):
            for row in pq.read_table(path).to_pylist():
                if row['code']:needed[(source_id,row['source_path'])]=sources[source_id]
    def read(item):
        (source_id,path),source=item
        url=('https://raw.githubusercontent.com/'+source['repo']+'/'+source['revision']+'/'+path if source['kind'].startswith('github') else
             'https://huggingface.co/datasets/'+source['repo']+'/resolve/'+source['revision']+'/'+path)
        r=requests.get(url,timeout=45);r.raise_for_status();assert len(r.content)<=300000
        verified_git=False
        if source['kind'].startswith('github'):
            expected=next(f['git_blob_sha'] for f in source['files'] if f['path']==path)
            assert hashlib.sha1(('blob '+str(len(r.content))+'\0').encode()+r.content).hexdigest()==expected
            verified_git=True
        declared,notice,evidence=license_header(r.content.decode('utf-8'))
        assert evidence not in {'restricted_or_unsupported_header','unsupported_or_compound_spdx'}
        return (source_id,path),{'declared':declared,'notice':notice,'evidence':evidence,'url':url,
            'source_sha256':hashlib.sha256(r.content).hexdigest(),'git_blob_verified':verified_git}
    with ThreadPoolExecutor(max_workers=6) as pool:headers=dict(pool.map(read,needed.items()))
    changed=Counter();code_before={};code_after={};notices_by_source=defaultdict(dict)
    for source_id in ['monster_pytorch_code_10k','aifaultbench','ml_dev_bench']:
        source=sources[source_id]
        for path in (export/'sources'/source_id/'data').glob('*.parquet'):
            table=pq.read_table(path);rows=table.to_pylist();modified=False
            for row in rows:
                code_before[row['record_id']]=row['code_sha256'];extra=json.loads(row['metadata_json'] or '{}')
                if source_id=='monster_pytorch_code_10k':
                    extra['source_row_scope']='global_stream_ordinal_in_frozen_manifest_order'
                    row['metadata_json']=json.dumps(extra,sort_keys=True,ensure_ascii=False);modified=True;changed['monster_row_scope_declared']+=1
                elif row['code']:
                    head=headers[(source_id,row['source_path'])];effective=head['declared'] or source['license_id']
                    assert effective==row['license_id'],(source_id,row['source_path'],effective,row['license_id'])
                    row['attribution_notice']=head['notice'] or source['attribution']
                    row['license_evidence']=head['evidence'] if head['declared'] else 'upstream_benchmark_packaging_license'
                    extra['metadata_license']=source['license_id'];extra['code_license']=effective
                    row['metadata_json']=json.dumps(extra,sort_keys=True,ensure_ascii=False)
                    key=(row['source_path'],row['source_record_id'],row['license_id'])
                    notices_by_source[source_id][key]={'notice':row['attribution_notice'],'license_evidence':row['license_evidence']}
                    modified=True;changed['benchmark_code_notices_restored']+=1
                code_after[row['record_id']]=row['code_sha256']
            if modified:
                tmp=path.with_suffix('.parquet.tmp');pq.write_table(pa.Table.from_pylist(rows,schema=table.schema),tmp,compression='zstd');tmp.replace(path)
        if notices_by_source[source_id]:
            p=export/'sources'/source_id/'ATTRIBUTIONS.jsonl';attrs=[]
            for line in p.read_text(encoding='utf-8').splitlines():
                a=json.loads(line);key=(a['path'],a.get('source_record_id',''),a['license_id'])
                if key in notices_by_source[source_id]:a.update(notices_by_source[source_id][key])
                attrs.append(a)
            p.write_text(''.join(json.dumps(a,ensure_ascii=False)+'\n' for a in attrs),encoding='utf-8',newline='\n')
    assert code_before==code_after
    note='\n\nPublication metadata note: source_row is a global scan ordinal in the frozen Parquet-file manifest order; source_record_id is the original source_hash and is the preferred row identity.\n'
    p=export/'sources/monster_pytorch_code_10k/README.md';p.write_text(p.read_text(encoding='utf-8')+note,encoding='utf-8',newline='\n')
    for name in ['README.md','LICENSING.md']:
        p=export/name;t=p.read_text(encoding='utf-8')
        t=t.replace('MIT benchmark-authored material; external assets excluded','MIT benchmark metadata/tasks; file-declared Apache-2.0 exceptions preserved')
        t+='\n\nPublication metadata finalization: benchmark code retains original file-header copyright/license notices; metadata licensing is recorded separately. Monster source_row uses the global scan ordinal, while source_record_id is the original file hash. Source code bodies are unchanged from the CPU extraction.\n'
        p.write_text(t,encoding='utf-8',newline='\n')
    p=export/'sources/ml_dev_bench/LICENSING.md'
    p.write_text(p.read_text(encoding='utf-8')+'\nThe upstream repository LICENSE is MIT, while 18 retained code units explicitly declare Apache-2.0. Those units keep their Apache notices and code license; benchmark metadata/tasks retain MIT. See LICENSES/Apache-2.0.txt and ATTRIBUTIONS.jsonl.\n',encoding='utf-8',newline='\n')
    # Independent full-record checks, including declared inline license evidence.
    ids=set();dedup=defaultdict(set);groups=defaultdict(set);counts=Counter();topics=Counter();license_counts=Counter();sizes=[];benchmark_count=0
    for source_id,source in sources.items():
        source_folder=export/'sources'/source_id
        assert (source_folder/'LICENSING.md').exists()
        if source.get('license_text'):assert (source_folder/'LICENSE').read_text(encoding='utf-8')==source['license_text']
        for path in sorted((source_folder/'data').glob('*.parquet')):
            for batch in pq.ParquetFile(path).iter_batches(batch_size=64):
                for row in batch.to_pylist():
                    assert row['record_id'] not in ids;ids.add(row['record_id']);counts[source_id]+=1
                    assert row['source_id']==source_id and row['source_revision']==source['revision']
                    assert row['license_id'] in {'MIT','Apache-2.0','BSD-2-Clause','BSD-3-Clause','CC-BY-4.0'}
                    if source_id=='monster_pytorch_code_10k':
                        declared,_,evidence=license_header(row['attribution_notice']+'\npass\n')
                        assert declared==row['license_id'] and evidence.startswith('inline_')
                        assert json.loads(row['metadata_json'])['source_row_scope'].startswith('global_stream_ordinal')
                    if row['benchmark_content']:
                        benchmark_count+=1;assert row['split']=='test' and row['intended_use']=='evaluation'
                        if row['code']:
                            head=headers[(source_id,row['source_path'])]
                            assert row['attribution_notice']==(head['notice'] or source['attribution'])
                    else:
                        assert row['split']==group_split(source_id+':'+row['source_group'])
                        groups[(source_id,row['source_group'])].add(row['split'])
                    assert not SECRET.search(row['text']) and not INJECTION.search(row['text'])
                    if row['code']:
                        info,reason=inspect_code(row['code']);assert not reason,reason
                        assert sha(row['code'])==row['code_sha256'] and sha(info['canonical'])==row['ast_sha256']
                        assert template_hash(info['tree'])==row['template_ast_sha256']
                    key=(row['record_type'],row['license_id'],row['template_ast_sha256'] or sha(row['text']))
                    assert key not in dedup[source_id];dedup[source_id].add(key)
                    topics.update(row['topics']);license_counts[row['license_id']]+=1;sizes.append(len(row['text']))
    assert all(len(v)==1 for v in groups.values())
    assert counts['vikp_clean_notebooks_filtered']==0
    legacy=export/'sources/jupyter_agent';old=json.loads((legacy/'checksums.json').read_text(encoding='utf-8'))
    for name,h in old.items():
        with (legacy/name).open('rb') as f:assert hashlib.file_digest(f,'sha256').hexdigest()==h,name
    readme=(export/'README.md').read_text(encoding='utf-8');card=yaml.safe_load(readme.split('---',2)[1])
    assert card['license']=='other' and 'LICENSING.md' in card['license_link']
    assert {'rag_chunks','qa_examples'}<={x['config_name'] for x in card['configs']}
    finalization={'metadata_only_changes':True,'source_code_bodies_unchanged':True,'changes':dict(changed),
        'notice_sources':[{'source_id':k[0],'path':k[1],**{n:v[n] for n in ['source_sha256','git_blob_verified','evidence']}} for k,v in sorted(headers.items())]}
    save(export/'publication-finalization.json',finalization)
    shutil.copyfile(Path(__file__),export/'processing_multisource/finalize_audit_rag_multisource.py')
    audit={'passed':True,'records':len(ids),'per_source':dict(counts),'benchmark_records':benchmark_count,
        'license_counts':dict(license_counts),'topics':dict(topics),'legacy_jupyter_files_byte_identical':True,
        'all_code_hashes_and_syntax_verified':True,'benchmark_notices_verified_from_frozen_sources':True,
        'monster_inline_license_evidence_verified':True,'grouped_splits_verified':True,'source_specific_card_verified':True,
        'text_chars_mean':round(sum(sizes)/len(sizes),1),'text_chars_max':max(sizes),'within_5400_chars':sum(x<=5400 for x in sizes),
        'export_path':str(export)}
    save(export/'publication-audit.json',audit);save(folder/'local-audit.json',audit)
    manifest={}
    for path in sorted(export.rglob('*')):
        rel=str(path.relative_to(export)).replace('\\','/')
        if path.is_file() and rel not in {'checksums.json','dataset.zip','publish.json'}:
            with path.open('rb') as f:manifest[rel]=hashlib.file_digest(f,'sha256').hexdigest()
    save(export/'checksums.json',manifest)
    with zipfile.ZipFile(folder/'dataset-final.zip','w',compression=zipfile.ZIP_STORED) as z:
        for path in sorted(export.rglob('*')):
            if path.is_file():z.write(path,str(path.relative_to(export)))
    latest.update(status='finalized_and_audited');save(latest_path,latest)
    print(json.dumps(audit,indent=2))


if __name__=='__main__':main()