File size: 32,107 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
"""CPU-only multi-source curation. Source code is parsed, never executed."""
from collections import Counter,defaultdict
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime,timezone
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import socket
import sys
import time
import zipfile

import requests
from multisource_core import code_records,doc_records,evaluation_record,license_header,VERSION,sha
from filter_core import inspect_code,template_hash,SECRET,INJECTION

ROOT=Path(__file__).resolve().parent;OUT=ROOT/'output'
CONFIG=json.loads((ROOT/'config.json').read_text(encoding='utf-8'))


def save(path,data):
    path.parent.mkdir(parents=True,exist_ok=True)
    temporary=path.with_suffix(path.suffix+'.tmp')
    temporary.write_text(json.dumps(data,indent=2,ensure_ascii=False)+'\n',encoding='utf-8');temporary.replace(path)


def fetch(url,max_bytes=300000):
    for attempt in range(3):
        try:
            r=requests.get(url,headers={'User-Agent':'offline-rag-source-curation'},timeout=(15,45))
            if r.status_code in (429,500,502,503,504) and attempt<2:time.sleep(2+attempt*3);continue
            r.raise_for_status()
            if len(r.content)>max_bytes:raise ValueError('Source file exceeds byte budget')
            return r.text
        except requests.RequestException:
            if attempt==2:raise
            time.sleep(2)
    raise RuntimeError('Fetch retry budget exceeded')


def metadata(source,path,row=-1,group=None):
    url=('https://github.com/'+source['repo']+'/blob/'+source['revision']+'/'+path if source['kind'].startswith('github') else
         'https://huggingface.co/datasets/'+source['repo']+'/blob/'+source['revision']+'/'+path)
    return {'source_id':source['id'],'source_repo':source['repo'],'source_revision':source['revision'],
        'source_path':path,'source_url':url,'source_group':group or path,'source_row':row,
        'source_record_id':'','upstream_track':source.get('track','frozen'),'authority':source.get('authority','community')}


class Sink:
    def __init__(self,source):
        import pyarrow as pa
        self.source=source;self.buffers=defaultdict(list);self.writers={};self.counts=Counter();self.topics=Counter();self.licenses=Counter()
        self.seen=set();self.samples=[];self.attributions={};self.code_lengths=[]
        strings=['record_id','source_id','source_repo','source_revision','source_path','source_url','source_group',
            'source_record_id','upstream_track','authority','record_type','intended_use','split','symbol',
            'code','code_sha256','ast_sha256','template_ast_sha256','license_id','license_evidence',
            'attribution_notice','validated_here','curation_version','text','metadata_json']
        lists=['topics','packages','unresolved_names','compatibility_flags']
        self.schema=pa.schema([pa.field(x,pa.string()) for x in strings]+[pa.field(x,pa.list_(pa.string())) for x in lists]+
            [pa.field(x,pa.int64()) for x in ['source_row','line_start','line_end']]+
            [pa.field(x,pa.bool_()) for x in ['external_data_required','benchmark_content']])
    def add(self,row,counters):
        if not row:return
        attr=(row['source_path'],row.get('source_record_id',''),row['license_id'])
        self.attributions[attr]={'source_repo':row['source_repo'],'revision':row['source_revision'],'path':row['source_path'],
            'source_record_id':row.get('source_record_id',''),'license_id':row['license_id'],
            'license_evidence':row['license_evidence'],'notice':row['attribution_notice'],'url':row['source_url']}
        key=(row['record_type'],row['license_id'],row.get('template_ast_sha256') or sha(row['text']))
        if key in self.seen:counters['duplicate_units_within_source']+=1;return
        self.seen.add(key)
        names=set(self.schema.names);extra={k:v for k,v in row.items() if k not in names}
        normalized={f.name:row.get(f.name) for f in self.schema}
        for f in self.schema:
            if f.name=='metadata_json':normalized[f.name]=json.dumps(extra,sort_keys=True,ensure_ascii=False)
            elif normalized[f.name] is None:
                if str(f.type).startswith('list'):normalized[f.name]=[]
                elif str(f.type)=='string':normalized[f.name]=''
                elif str(f.type)=='bool':normalized[f.name]=False
                else:normalized[f.name]=-1
        split=row['split'];self.buffers[split].append(normalized);self.counts[split]+=1;self.topics.update(row['topics']);self.licenses[row['license_id']]+=1
        self.code_lengths.append(len(row['text']))
        if len(self.samples)<8:self.samples.append(normalized)
        if len(self.buffers[split])>=128:self.flush(split)
    def flush(self,split):
        import pyarrow as pa
        import pyarrow.parquet as pq
        if not self.buffers[split]:return
        if split not in self.writers:
            p=OUT/'sources'/self.source['id']/'data'/(split+'-00000.parquet');p.parent.mkdir(parents=True,exist_ok=True)
            self.writers[split]=pq.ParquetWriter(p,self.schema,compression='zstd')
        self.writers[split].write_table(pa.Table.from_pylist(self.buffers[split],schema=self.schema));self.buffers[split]=[]
    def close(self):
        for split in list(self.buffers):self.flush(split)
        for writer in self.writers.values():writer.close()
        folder=OUT/'sources'/self.source['id'];folder.mkdir(parents=True,exist_ok=True)
        with (folder/'ATTRIBUTIONS.jsonl').open('w',encoding='utf-8') as f:
            for value in self.attributions.values():f.write(json.dumps(value,ensure_ascii=False)+'\n')


def source_scaffolding(source):
    folder=OUT/'sources'/source['id'];folder.mkdir(parents=True,exist_ok=True)
    if source.get('license_text'):(folder/'LICENSE').write_text(source['license_text'],encoding='utf-8')
    if source.get('upstream_card'):(folder/'UPSTREAM_CARD.md').write_text(source['upstream_card'],encoding='utf-8')
    if source.get('citation'):(folder/'CITATION.cff').write_text(source['citation'],encoding='utf-8')
    if source['kind']!='metadata_only':
        for license_id,text in CONFIG['standard_licenses'].items():
            p=folder/'LICENSES'/(license_id+'.txt');p.parent.mkdir(exist_ok=True);p.write_text(text,encoding='utf-8')
    if not source.get('license_text'):
        (folder/'LICENSE_STATUS.md').write_text('# Upstream license status\n\n'+source['licensing_note']+'\n',encoding='utf-8')
    save(folder/'PROVENANCE.json',{k:v for k,v in source.items() if k not in ['upstream_card','license_text','citation','files','index']})
    notice=(source.get('attribution','')+'\nSource: '+source['repo']+'@'+source['revision']+'\n'
        +'Changes: selected text/code units, bounded imports, source-specific AST deduplication and grouped splits. '
        +'The content was not run or ported to the local runtime.\n'
        +'File-specific notices are preserved in ATTRIBUTIONS.jsonl. See license_id and license_evidence on every record.\n')
    (folder/'NOTICE').write_text(notice,encoding='utf-8')
    licensing=('# Licensing: '+source['id']+'\n\n'+source['licensing_note']+'\n\n'
        +'The source revision and URLs are frozen in PROVENANCE.json. LICENSE is the actual upstream source/packaging license when available. '
        +'LICENSES contains reference license texts; these do not themselves grant rights or replace file-specific notices. '
        +'ATTRIBUTIONS.jsonl and record metadata identify original license evidence. No blanket repository-wide relicensing is claimed.\n')
    (folder/'LICENSING.md').write_text(licensing,encoding='utf-8')


def github_source(source,sink,counters):
    files=source['files'];counters['source_files_selected']=len(files)
    def read(spec):
        path=spec['path'];url='https://raw.githubusercontent.com/'+source['repo']+'/'+source['revision']+'/'+path
        try:return path,fetch(url,max_bytes=250000),None
        except Exception as e:return path,None,type(e).__name__
    with ThreadPoolExecutor(max_workers=6) as pool:
        for path,text,error in pool.map(read,files):
            counters['source_files_scanned']+=1
            if error:counters['fetch_or_size_'+error]+=1;continue
            meta=metadata(source,path,group=path.split('/')[0] if source['id']=='pytorch_examples' else path)
            if path.endswith('.py'):
                for row in code_records(text,meta,counters,default_license=source['license_id']):sink.add(row,counters)
                # Gallery tutorial prose is independently licensed documentation.
                if source['id']=='pytorch_tutorials':
                    try:
                        import ast
                        prose=ast.get_docstring(ast.parse(text)) or ''
                        for row in doc_records(prose,meta,source['license_id'],counters):sink.add(row,counters)
                    except (SyntaxError,ValueError,RecursionError):pass
            elif path.endswith(('.md','.rst')):
                for row in doc_records(text,meta,source['license_id'],counters):sink.add(row,counters)
            if counters['source_files_scanned']%40==0:progress(source,counters,sink)


def monster_source(source,sink,counters):
    from huggingface_hub import HfFileSystem
    import pyarrow.parquet as pq
    fs=HfFileSystem(token=False);seen=set()
    for i,spec in enumerate(source['files']):
        path='datasets/'+source['repo']+'@'+source['revision']+'/'+spec['path']
        with fs.open(path,'rb',block_size=131072,cache_type='readahead') as handle:
            pf=pq.ParquetFile(handle)
            for batch in pf.iter_batches(batch_size=32,columns=['code','source_hash']):
                for j,row in enumerate(batch.to_pylist()):
                    counters['rows_scanned']+=1
                    key=str(row.get('source_hash') or sha(str(row.get('code'))))
                    if key in seen:counters['duplicate_source_hash']+=1;continue
                    seen.add(key);meta=metadata(source,spec['path'],row=counters['rows_scanned']-1,group=key)
                    meta['source_record_id']=key
                    for item in code_records(row.get('code'),meta,counters,require_inline=True):sink.add(item,counters)
        counters['parquet_shards_scanned']=i+1
        if i%10==0:progress(source,counters,sink)


def aifault_source(source,sink,counters):
    rows=source['index'];counters['index_rows_scanned']=len(rows)
    selected=[x for x in rows if x.get('reproducible') and any(t in str(x.get('repository','')).lower() for t in
        ['pytorch/','scikit-learn/','numpy/','scipy/','pandas-dev/','xgboost','lightgbm','catboost','huggingface/transformers','scikit-image/','opencv/'])]
    counters['unsupported_or_unreproduced_cases']=len(rows)-len(selected)
    def read(case):
        case_id=str(case['bug_id']).zfill(3);base='https://huggingface.co/datasets/'+source['repo']+'/resolve/'+source['revision']+'/bugs/'+case_id+'/'
        try:
            code=fetch(base+'repro.py',max_bytes=100000)
            reproduction=json.loads(fetch(base+'reproduction.json',max_bytes=50000))
            return case_id,case,code,reproduction,None
        except Exception as e:return case_id,case,'',{},type(e).__name__
    with ThreadPoolExecutor(max_workers=6) as pool:
        for case_id,case,code,reproduction,error in pool.map(read,selected):
            counters['cases_scanned']+=1
            if error:counters['fetch_'+error]+=1;continue
            facts={k:case.get(k) for k in ['bug_id','library','repository','domain','issue_url','commit','reproducible','blocking_reason']}
            # Original issue bodies/comments and copied source repos are excluded.
            text='Case metadata: '+json.dumps(facts,ensure_ascii=False)+'\nUpstream reproduction evidence: '+str(reproduction.get('evidence',''))[:900]
            meta=metadata(source,'bugs/'+case_id+'/repro.py',group=case_id);meta['source_record_id']=case_id
            base=evaluation_record(meta,case_id,text,'CC-BY-4.0',extra={'benchmark_facts':facts,'code_status':'intentionally_failing_or_case_specific'})
            sink.add(base,counters)
            for candidate in code_records(code,meta,counters,default_license='CC-BY-4.0'):
                evaluation=evaluation_record(meta,case_id+'-'+candidate['symbol'],text,candidate['license_id'],candidate['code'],
                    extra={'benchmark_facts':facts,'metadata_license':'CC-BY-4.0','code_status':'intentionally_failing_or_case_specific'})
                sink.add(evaluation,counters)
            if counters['cases_scanned']%40==0:progress(source,counters,sink)


def ml_dev_source(source,sink,counters):
    files=source['files']
    def read(spec):
        try:return spec['path'],fetch('https://raw.githubusercontent.com/'+source['repo']+'/'+source['revision']+'/'+spec['path'],max_bytes=100000),None
        except Exception as e:return spec['path'],'',type(e).__name__
    with ThreadPoolExecutor(max_workers=6) as pool:
        for path,text,error in pool.map(read,files):
            counters['source_files_scanned']+=1
            if error:counters['fetch_'+error]+=1;continue
            meta=metadata(source,path,group=str(Path(path).parent));case_id=str(Path(path).parent)
            if path.endswith('task.txt'):
                sink.add(evaluation_record(meta,case_id,text,'MIT',extra={'task_instructions_are_historical':True}),counters)
            elif path.endswith('.py') and 'setup_workspace/' in path:
                for candidate in code_records(text,meta,counters,default_license='MIT'):
                    sink.add(evaluation_record(meta,case_id+'-'+candidate['symbol'],
                        'Original ML-Dev-Bench debugging workspace fixture. It may intentionally contain a bug; not a reference solution.',
                        candidate['license_id'],candidate['code'],extra={'task_instructions_are_historical':True}),counters)
            if counters['source_files_scanned']%40==0:progress(source,counters,sink)


def progress(source,counters,sink):
    save(OUT/'progress.json',{'source':source['id'],'counts':dict(counters),'retained':sum(sink.counts.values())})
    print(json.dumps({'source':source['id'],'scanned':sum(v for k,v in counters.items() if k.endswith('scanned')),'retained':sum(sink.counts.values())}),flush=True)


def preserve_jupyter():
    from huggingface_hub import HfApi
    info=HfApi(token=False).dataset_info(CONFIG['target_repo'],revision=CONFIG['target_parent_commit'],files_metadata=True)
    files=[f.rfilename for f in info.siblings if f.rfilename!='.gitattributes']
    target=OUT/'sources/jupyter_agent';target.mkdir(parents=True)
    hashes={}
    def copy(name):
        url='https://huggingface.co/datasets/'+CONFIG['target_repo']+'/resolve/'+CONFIG['target_parent_commit']+'/'+name
        r=requests.get(url,timeout=60);r.raise_for_status();p=target/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(r.content)
        return name,hashlib.sha256(r.content).hexdigest()
    with ThreadPoolExecutor(max_workers=4) as pool:
        for name,h in pool.map(copy,files):hashes[name]=h
    original=json.loads((target/'checksums.json').read_text(encoding='utf-8'))
    for name,h in original.items():assert hashes.get(name)==h,(name,'Original Jupyter file changed')
    (target/'LICENSING.md').write_text('# Jupyter Agent licensing\n\nApache-2.0 derived artifacts; original Kaggle assets retain their terms. LICENSE and NOTICE are preserved byte-for-byte from the previous dataset commit. The existing Parquet files are unchanged.\n',encoding='utf-8')
    return {'source_id':'jupyter_agent','previous_commit':CONFIG['target_parent_commit'],'preserved_files':hashes,
        'chunks':12292,'qa':9305,'license':'Apache-2.0','content_unchanged':True}


def validate(summaries):
    import pyarrow.parquet as pq
    from multisource_core import group_split
    ids=set();totals=Counter();source_groups=defaultdict(set);samples={};licenses=Counter();code_count=0
    for source in CONFIG['sources']:
        source_id=source['id'];folder=OUT/'sources'/source_id
        assert (folder/'LICENSING.md').exists() and (folder/'PROVENANCE.json').exists()
        if source.get('license_text'):assert (folder/'LICENSE').read_text(encoding='utf-8')==source['license_text']
        samples[source_id]=[]
        for path in sorted((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']);totals[source_id]+=1
                    assert row['source_revision']==source['revision'] and row['source_id']==source_id
                    assert row['license_id'] and row['license_evidence']
                    if source_id=='monster_pytorch_code_10k':assert row['license_evidence'].startswith('inline_')
                    assert not SECRET.search(row['text']) and not INJECTION.search(row['text'])
                    if row['benchmark_content']:assert row['split']=='test' and row['intended_use']=='evaluation'
                    else:
                        assert row['split']==group_split(source_id+':'+row['source_group'])
                        source_groups[(source_id,row['source_group'])].add(row['split'])
                    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'];code_count+=1
                    licenses[row['license_id']]+=1
                    if len(samples[source_id])<4:samples[source_id].append(row)
        assert totals[source_id]==summaries[source_id]['records']
    assert all(len(x)==1 for x in source_groups.values())
    save(OUT/'sample.json',samples)
    result={'passed':True,'records':sum(totals.values()),'per_source':dict(totals),'code_records':code_count,
        'unique_record_ids':len(ids),'license_counts':dict(licenses),'grouped_splits_verified':True,
        'benchmark_material_evaluation_only':True,'all_code_hashes_and_syntax_verified':True,
        'monster_original_license_evidence_required':True,'vikp_contents_not_redistributed':not list((OUT/'sources/vikp_clean_notebooks_filtered').glob('data/*.parquet'))}
    save(OUT/'validation.json',result);return result


def root_cards(summaries,legacy):
    import yaml
    configs=[]
    for name,kind in [('rag_chunks','chunks'),('qa_examples','qa')]:
        configs.append({'config_name':name,'data_files':[{'split':split,'path':'sources/jupyter_agent/data/'+kind+'/'+split+'-*.parquet'} for split in ['train','validation','test']]})
    for source in CONFIG['sources']:
        splits=summaries[source['id']]['splits']
        if splits:configs.append({'config_name':source['id'],'data_files':[{'split':split,'path':'sources/'+source['id']+'/data/'+split+'-*.parquet'} for split in ['train','validation','test'] if splits.get(split)]})
    card={'license':'other','license_name':'source-specific-licenses','license_link':'https://huggingface.co/datasets/'+CONFIG['target_repo']+'/blob/main/LICENSING.md',
        'language':['en','code'],'task_categories':['text-retrieval','question-answering'],
        'tags':['pytorch','data-science','rag','source-specific-licensing','benchmark-study'],'configs':configs}
    lines=['---',yaml.safe_dump(card,sort_keys=False,allow_unicode=True).strip(),'---','','# Offline ML/DL evidence with source-specific licenses','',
        'Each source has its own folder, license information, attribution, frozen revision and provenance. This repository has no blanket Apache/MIT license over all data. Read [LICENSING.md](LICENSING.md) and each record license_id before reuse.','',
        'The existing Jupyter Agent artifacts are unchanged and now live under `sources/jupyter_agent/`. The original `rag_chunks` and `qa_examples` config names still load those exact data files.','',
        '## Sources and output','', '| Source folder / HF config | Retained records | License scope | Intended use |','|---|---:|---|---|',
        '| [jupyter_agent](sources/jupyter_agent) | 12,292 code chunks + 9,305 QA | Apache-2.0 derived artifacts; Kaggle terms remain | RAG / dataset-grounded QA |']
    for source in CONFIG['sources']:
        r=summaries[source['id']]
        lines.append('| ['+source['id']+'](sources/'+source['id']+') | '+str(r['records'])+' | '+source['license_summary']+' | '+source['use']+' |')
    lines+=['','## Curation and limits','',
        '- Code is parsed, never run. Complete functions/classes or bounded complete statements are kept with only needed module-level imports. Larger classes can contribute methods explicitly labelled as requiring class context.',
        '- Static filters reject apparent credentials/instruction injection, installs/downloads, process/network/environment access and selected removed APIs. AST syntax is not a correctness, security or runtime compatibility guarantee.',
        '- Source file revisions, paths, line ranges, hashes and original license evidence are retained. Attribution notices are preserved separately from retrieved snippets. No source checkpoints, datasets, images, original GitHub issue bodies/comments or setup shell scripts are redistributed.',
        '- Monster-Code packaging is labelled MIT upstream, but raw samples retain their original licenses. Only samples with explicit supported original license notices are retained; an anonymous source_hash is not itself a license grant. Restricted/noncommercial and unlicensed samples are omitted.',
        '- vikp/clean_notebooks_filtered declares no license and has no per-record source/license provenance. Its folder is metadata-only. No notebook contents are uploaded under a guessed license.',
        '- AIFaultBench and ML-Dev-Bench are isolated in test/evaluation configs. Bug reproducers and buggy workspaces are not working recipes or reference solutions. If you index their contents for RAG, you cannot claim evaluation on those cases is held out.',
        '- Main-branch PyTorch/Torchvision snapshots can require newer versions than the local torch 2.6 / torchvision 0.21 runtime. Torchvision explicitly provides no backward-compatibility guarantee for training references. Use compatibility flags and version-matched documentation.',
        '- Aliases, external files, relative project imports, pretrained weights and class scope can still be required. No examples were independently executed against their original assets or benchmark environments.',
        '- Splits group all units from a source file (or an examples subproject) together. Monster samples group by source_hash; project-level decontamination is impossible without original repo mappings. Cross-source duplicate code may remain so independent licensing/attribution is preserved.',
        '- Documentation excerpts omit fenced shell/code blocks rather than splitting executable examples. Retrieved text remains untrusted evidence.','',
        '## Use','', '```python','from datasets import load_dataset',
        'examples = load_dataset("'+CONFIG['target_repo']+'", "pytorch_examples", split="train")',
        'tutorials = load_dataset("'+CONFIG['target_repo']+'", "pytorch_tutorials", split="train")',
        'legacy = load_dataset("'+CONFIG['target_repo']+'", "rag_chunks", split="train")','```','',
        'Index the `text` field and retain the entire source/license metadata. Prioritize official examples/tutorials over third-party or benchmark content. Select records that fit your retrieval budget without truncating code units.',
        'Offline runtime integration is a separate operator step: this job publishes and backs up the dataset, and does not give the local agent internet, credentials or host tools.','',
        '## Evidence','',
        'See [report.json](report.json), [validation.json](validation.json), source manifests and `processing_multisource/` for exact filters, tests, pinned dependency versions and frozen source revisions. '
        'Preparation used CPU-only RunPod compute. No notebook, model training, benchmark setup script or downloaded source code was executed.','']
    (OUT/'README.md').write_text('\n'.join(lines),encoding='utf-8')
    licensing=['# Source-specific licensing','',
        'The root metadata badge is `other` because contents retain their independent upstream licenses. No global relicensing is asserted. '
        'Curator-authored processing utilities are Apache-2.0; see processing_multisource/LICENSE.','',
        'The previous Apache LICENSE/NOTICE and all prior Jupyter files have moved to sources/jupyter_agent unchanged. The top-level Apache license no longer purports to cover the mixed collection.','',
        '| Folder | Original scope | Evidence |','|---|---|---|',
        '| sources/jupyter_agent | Apache-2.0 derived Jupyter Agent artifacts | LICENSE, NOTICE, previous frozen manifest |']
    for source in CONFIG['sources']:
        licensing.append('| sources/'+source['id']+' | '+source['license_summary']+' | [LICENSING.md](sources/'+source['id']+'/LICENSING.md), upstream card/license and per-record evidence |')
    licensing+=['','Source-specific notices are in each ATTRIBUTIONS.jsonl. Reference license texts under LICENSES do not replace original attribution and do not license omitted or unknown material. '
        'Linked Kaggle data, model weights, GitHub issue reports and third-party repositories retain their original terms and are not included by this collection.','']
    (OUT/'LICENSING.md').write_text('\n'.join(licensing),encoding='utf-8')


def filter_all():
    started=time.monotonic();OUT.mkdir(exist_ok=True)
    legacy=preserve_jupyter();summaries={}
    for source in CONFIG['sources']:
        source_scaffolding(source);counters=Counter();sink=Sink(source)
        try:
            if source['kind']=='metadata_only':counters['excluded_no_license_declared']=source['declared_rows']
            elif source['kind']=='github_code':github_source(source,sink,counters)
            elif source['kind']=='hf_monster':monster_source(source,sink,counters)
            elif source['kind']=='hf_aifault':aifault_source(source,sink,counters)
            elif source['kind']=='github_benchmark':ml_dev_source(source,sink,counters)
        finally:sink.close()
        summary={'records':sum(sink.counts.values()),'splits':dict(sink.counts),'topics':dict(sink.topics),'licenses':dict(sink.licenses),
            'counters':dict(counters),'text_chars_mean':round(sum(sink.code_lengths)/max(1,len(sink.code_lengths)),1),
            'text_chars_max':max(sink.code_lengths,default=0)}
        summaries[source['id']]=summary
        save(OUT/'sources'/source['id']/'curation_report.json',summary)
        (OUT/'sources'/source['id']/'README.md').write_text('# '+source['id']+'\n\n'+source['licensing_note']+'\n\n'
            +'Retained records: '+str(summary['records'])+'. Intended use: '+source['use']+'.\n'
            +'See LICENSING.md, PROVENANCE.json and curation_report.json. All source content was treated as inert data.\n',encoding='utf-8')
        progress(source,counters,sink)
    validation=validate(summaries);root_cards(summaries,legacy)
    report={'run_id':CONFIG['run_id'],'created_utc':datetime.now(timezone.utc).isoformat(),'curation_version':VERSION,
        'sources':summaries,'legacy_jupyter':legacy,'validation':validation,'seconds':round(time.monotonic()-started,3),
        'machine':{'pod_id':os.environ.get('RUNPOD_POD_ID'),'hostname':socket.gethostname(),'uid':os.getuid(),
            'docker_socket_present':Path('/var/run/docker.sock').exists(),'nvidia_device_present':Path('/dev/nvidia0').exists(),
            'boundaries':[x for x in Path('/proc/self/status').read_text().splitlines() if x.startswith(('CapEff:','NoNewPrivs:'))]},
        'no_source_code_executed':True}
    save(OUT/'report.json',report)
    save(OUT/'source-files.json',{s['id']:{'repo':s['repo'],'revision':s['revision'],'files':s.get('files',[])} for s in CONFIG['sources']})
    processing=OUT/'processing_multisource';processing.mkdir()
    for name in ['worker.py','multisource_core.py','filter_core.py','test_filter.py','test_multisource.py','requirements.lock','config.json','LICENSE']:
        shutil.copyfile(ROOT/name,processing/name)
    checksums={}
    for p in sorted(OUT.rglob('*')):
        if p.is_file() and p.name not in {'checksums.json','dataset.zip','progress.json','publish.json'}:
            with p.open('rb') as f:checksums[str(p.relative_to(OUT))]=hashlib.file_digest(f,'sha256').hexdigest()
    # The nested legacy manifest remains a separately preserved artifact.
    legacy_manifest=OUT/'sources/jupyter_agent/checksums.json'
    checksums['sources/jupyter_agent/checksums.json']=hashlib.sha256(legacy_manifest.read_bytes()).hexdigest()
    save(OUT/'checksums.json',checksums)
    with zipfile.ZipFile(OUT/'dataset.zip','w',compression=zipfile.ZIP_STORED) as z:
        for path in sorted(OUT.rglob('*')):
            if path.is_file() and path.name not in {'dataset.zip','progress.json','publish.json'}:z.write(path,str(path.relative_to(OUT)))
    print(json.dumps({'complete':True,'records':validation['records'],'sources':{k:v['records'] for k,v in summaries.items()},'seconds':report['seconds']}),flush=True)


def publish():
    from huggingface_hub import HfApi,CommitOperationAdd,CommitOperationDelete
    token=os.environ['HF_TOKEN'];api=HfApi(token=token);assert api.whoami()['name']=='shiowo'
    report=json.loads((OUT/'report.json').read_text(encoding='utf-8'));assert report['validation']['passed']
    assert api.dataset_info(CONFIG['target_repo']).sha==CONFIG['target_parent_commit'],'Destination changed; refusing concurrent overwrite'
    manifest=json.loads((OUT/'checksums.json').read_text(encoding='utf-8'))
    for name,h in manifest.items():
        with (OUT/name).open('rb') as f:assert hashlib.file_digest(f,'sha256').hexdigest()==h,name
    operations=[]
    for name in CONFIG['previous_root_files']:
        if name not in {'.gitattributes','README.md'}:operations.append(CommitOperationDelete(path_in_repo=name))
    for path in sorted(OUT.rglob('*')):
        if path.is_file() and path.name not in {'dataset.zip','progress.json','publish.json'}:
            operations.append(CommitOperationAdd(path_in_repo=str(path.relative_to(OUT)),path_or_fileobj=str(path)))
    result=api.create_commit(repo_id=CONFIG['target_repo'],repo_type='dataset',operations=operations,parent_commit=CONFIG['target_parent_commit'],
        commit_message='Add source-separated licensed PyTorch evidence and benchmark study records',
        commit_description='Preserve prior Jupyter artifacts unchanged in a source folder; source-specific licenses and attribution; no blanket MIT/Apache data license; unlicensed notebooks omitted; benchmark content evaluation-only.')
    info=api.dataset_info(CONFIG['target_repo'],revision=result.oid,files_metadata=True);files={x.rfilename:x for x in info.siblings}
    assert all(name in files for name in manifest)
    for name,h in manifest.items():
        if files[name].lfs:assert files[name].lfs.sha256==h,name
    url='https://huggingface.co/datasets/'+CONFIG['target_repo']+'/resolve/'+result.oid+'/checksums.json'
    r=requests.get(url,headers={'Authorization':'Bearer '+token},timeout=60);r.raise_for_status();assert r.content==(OUT/'checksums.json').read_bytes()
    payload={'repo':CONFIG['target_repo'],'commit':result.oid,'commit_url':str(result.commit_url),'files_verified':len(manifest),
        'manifest_verified':True,'source_records':{k:v['records'] for k,v in report['sources'].items()},'legacy_jupyter_unchanged':True}
    save(OUT/'publish.json',payload);print(json.dumps(payload),flush=True)


if __name__=='__main__':
    if sys.argv[1]=='filter':filter_all()
    elif sys.argv[1]=='publish':publish()
    else:raise SystemExit('Expected filter or publish')