File size: 13,081 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
"""License-aware, non-executing extraction for the requested RAG sources."""
import ast
import hashlib
import re

from filter_core import inspect_code,template_hash,SECRET,INJECTION

VERSION='multi-source-v1'
PERMISSIVE={'MIT','Apache-2.0','BSD-2-Clause','BSD-3-Clause'}
HELPER_ROOTS={'os','sys','pathlib','warnings','pkg_resources','platform','logging'}


def sha(text):return hashlib.sha256(text.encode('utf-8')).hexdigest()


def license_header(code):
    """Only declarations before executable code; never infer MIT from a wrapper."""
    head=code[:20000]
    try:
        tree=ast.parse(code)
        first=next((n for n in tree.body if not (isinstance(n,ast.Expr) and isinstance(n.value,ast.Constant) and isinstance(n.value.value,str))),None)
        if first is not None:head='\n'.join(code.splitlines()[:first.lineno-1])[:20000]
    except (SyntaxError,ValueError,RecursionError):pass
    if re.search(r'GNU (?:GENERAL|LESSER|AFFERO)|\b[AL]?GPL[- v]|License-NC|Non.?Commercial|proprietary|all rights reserved.*no permission',head,re.I):
        return None,head,'restricted_or_unsupported_header'
    spdx=re.search(r'SPDX-License-Identifier:\s*([^\r\n]+)',head,re.I)
    if spdx:
        label=spdx.group(1).strip().strip('#*/ ')
        if label in PERMISSIVE:return label,head,'inline_spdx'
        return None,head,'unsupported_or_compound_spdx'
    if re.search(r'Licensed under (?:the )?Apache License[, ]*(?:Version )?2\.0|apache\.org/licenses/LICENSE-2\.0',head,re.I):
        return 'Apache-2.0',head,'inline_apache_notice'
    if re.search(r'Permission is hereby granted,? free of charge|Licensed under (?:the )?MIT License',head,re.I):
        return 'MIT',head,'inline_mit_notice'
    if re.search(r'Redistribution and use in source and binary forms',head,re.I) and re.search(r'THIS SOFTWARE IS PROVIDED',head,re.I):
        return ('BSD-3-Clause' if re.search(r'Neither the name|names? of.*contributors?',head,re.I) else 'BSD-2-Clause'),head,'inline_bsd_notice'
    return None,head,'no_inline_license'


def group_split(group):
    n=int(sha(group)[:8],16)%100
    return 'train' if n<80 else 'validation' if n<90 else 'test'


def import_nodes(tree):
    return [n for n in tree.body if isinstance(n,(ast.Import,ast.ImportFrom))]


def bound_imports(code,tree,unit):
    loaded={n.id for n in ast.walk(unit) if isinstance(n,ast.Name) and isinstance(n.ctx,ast.Load)}
    rows=[]
    for n in import_nodes(tree):
        names={(a.asname or a.name.split('.')[0]) for a in n.names}
        if names&loaded or isinstance(n,ast.ImportFrom) and n.module=='__future__':
            text=ast.get_source_segment(code,n)
            if text not in rows:rows.append(text)
    return '\n'.join(rows)


def raw_segment(code,node):
    start=min([node.lineno]+[x.lineno for x in getattr(node,'decorator_list',[])])
    return '\n'.join(code.splitlines()[start-1:node.end_lineno])


def units(code):
    """Complete AST statements/functions/classes, including decorators."""
    tree=ast.parse(code);items=[];batch=[];chars=0
    def flush():
        nonlocal batch,chars
        if batch:
            a=batch[0];b=batch[-1];segment='\n'.join(code.splitlines()[a.lineno-1:b.end_lineno])
            imports=bound_imports(code,tree,ast.Module(body=batch,type_ignores=[]))
            items.append(('top_level_statements',segment,imports,a.lineno,b.end_lineno,False))
            batch=[];chars=0
    for n in tree.body:
        if isinstance(n,(ast.Import,ast.ImportFrom)):continue
        if isinstance(n,ast.Expr) and isinstance(n.value,ast.Constant) and isinstance(n.value.value,str):continue
        if isinstance(n,(ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef)):
            flush();segment=raw_segment(code,n)
            if len(segment)<=4800:
                items.append((n.name,segment,bound_imports(code,tree,n),n.lineno,n.end_lineno,False))
            elif isinstance(n,ast.ClassDef):
                for m in n.body:
                    if isinstance(m,(ast.FunctionDef,ast.AsyncFunctionDef)):
                        segment=raw_segment(code,m)
                        # Preserve method body while removing only class indentation.
                        import textwrap
                        segment=textwrap.dedent(segment)
                        if len(segment)<=4400:items.append((n.name+'.'+m.name,segment,bound_imports(code,tree,m),m.lineno,m.end_lineno,True))
            continue
        if isinstance(n,ast.If) and '__name__' in ast.unparse(n.test):flush();continue
        text=ast.get_source_segment(code,n)
        if batch and chars+len(text)>2600:flush()
        if len(text)<=4400:batch.append(n);chars+=len(text)
    flush()
    return tree,items


def analyze(code):
    info,reason=inspect_code(code)
    if reason:return None,reason
    calls=[c for c in info['calls'] if c and not c.startswith('.') and c.split('.')[0] not in HELPER_ROOTS]
    torch_calls=[c for c in calls if c.startswith('torch.') and not c.startswith(('torch.cuda.is_available','torch.cuda.device_count','torch.cuda.get_device','torch.backends.','torch.version'))]
    topics=set(info['topics'])
    if torch_calls:topics.add('pytorch')
    if any(c.endswith(('cross_entropy','nll_loss','mse_loss','binary_cross_entropy_with_logits')) for c in calls):topics.add('loss_functions')
    if any(c.endswith(('backward','zero_grad','step')) for c in calls) and (torch_calls or 'torch' in info['packages']):topics.add('training_loop')
    if any(c.endswith(('no_grad','inference_mode','eval')) for c in calls) and (torch_calls or 'torch' in info['packages']):topics.add('evaluation')
    if re.search(r'key_padding_mask|attention_mask|masked_fill|pad_sequence|pack_padded_sequence',code):topics.add('sequence_masking')
    if re.search(r'\.view\(|\.reshape\(|\.flatten\(|\.permute\(|\.transpose\(',code) and (torch_calls or 'torch' in info['packages']):topics.add('tensor_shapes')
    if not topics:return None,'not_useful_ml_operations'
    info['topics']=sorted(topics)
    return info,None


def code_records(code,meta,counters,default_license=None,require_inline=False):
    if not isinstance(code,str) or not 30<=len(code)<=250000:
        counters['code_bounds']+=1;return []
    if SECRET.search(code) or INJECTION.search(code):counters['unsafe_text']+=1;return []
    declared,notice,evidence=license_header(code)
    if evidence in {'restricted_or_unsupported_header','unsupported_or_compound_spdx'}:
        counters[evidence]+=1;return []
    license_id=declared or (None if require_inline else default_license)
    if not license_id:counters['missing_original_license_evidence']+=1;return []
    try:tree,parts=units(code)
    except (SyntaxError,ValueError,RecursionError):counters['syntax_error']+=1;return []
    records=[]
    for symbol,segment,imports,start,end,method in parts:
        full=(imports+'\n\n' if imports else '')+segment
        if len(full)>4800:counters['chunk_bounds']+=1;continue
        info,reason=analyze(full)
        if reason:counters[reason]+=1;continue
        flags=[]
        if method:flags.append('requires_class_context')
        if info['unresolved_names']:flags.append('requires_prior_state_or_project_modules')
        if any(n.startswith('_') for n in info['packages']):flags.append('private_or_project_module')
        if re.search(r'\.cuda\(|[\"\']cuda(?::\d+)?[\"\']',full):flags.append('cuda_referenced')
        if re.search(r'from_pretrained|pretrained\s*=\s*True|weights\s*=\s*(?:[A-Za-z_]+\.)?[A-Za-z_]+\.DEFAULT',full):flags.append('external_weights_required')
        if '.toarray(' in full:flags.append('densifies_sparse_matrix')
        if 'filterwarnings' in full:flags.append('suppresses_warnings')
        if meta.get('upstream_track')=='main':flags.append('main_snapshot_not_runtime_verified')
        ast_hash=sha(info['canonical']);template=template_hash(info['tree'])
        record={**meta,'record_id':meta['source_id']+'-'+sha(meta['source_path']+':'+str(meta.get('source_row',''))+':'+str(start)+':'+ast_hash)[:24],
            'record_type':'python_code','intended_use':'rag','split':group_split(meta['source_id']+':'+meta['source_group']),
            'symbol':symbol,'line_start':start,'line_end':end,'code':full,'code_sha256':sha(full),
            'ast_sha256':ast_hash,'template_ast_sha256':template,'topics':info['topics'],'packages':info['packages'],
            'unresolved_names':info['unresolved_names'],'external_data_required':info['external_data_required'],
            'compatibility_flags':flags,'license_id':license_id,'license_evidence':evidence if declared else 'upstream_repository_license',
            'attribution_notice':notice,'validated_here':'syntax_only_not_executed','benchmark_content':False,'curation_version':VERSION}
        record['text']=('# '+symbol+'\nSource: '+meta['source_url']+'#L'+str(start)+'-L'+str(end)+'\n'
            +'License: '+license_id+'. Syntax checked only; may require original state/files.\n'
            +('Flags: '+', '.join(flags)+'\n' if flags else '')+'\n```python\n'+full+'\n```\n')
        records.append(record)
    return records


def doc_records(text,meta,license_id,counters):
    if not isinstance(text,str) or len(text)>100000:return []
    if SECRET.search(text) or INJECTION.search(text):counters['unsafe_doc']+=1;return []
    text=re.sub(r'(?ms)^```[^\n]*\n.*?^```\s*$','',text)
    text=re.sub(r'(?m)^\.\. (?:code-block|code|literalinclude)::[^\n]*\n(?:\n|[ \t]+[^\n]*\n)*','',text)
    # Full paragraphs; omit shell/install directives rather than executing them.
    paragraphs=re.split(r'\n\s*\n',text);groups=[];parts=[];length=0
    for paragraph in paragraphs:
        if re.search(r'pip install|git clone|curl .*https?://|wget |sudo |\.sh\b',paragraph):continue
        if len(paragraph)>3800:continue
        if parts and length+len(paragraph)>2800:groups.append('\n\n'.join(parts));parts=[];length=0
        parts.append(paragraph);length+=len(paragraph)
    if parts:groups.append('\n\n'.join(parts))
    rows=[]
    for i,body in enumerate(groups):
        if len(body)<120 or not re.search(r'(?i)pytorch|torchvision|convolution|gradient|optim|training|segmentation|classification|tensor|attention|padding|normaliz|backprop',body):continue
        record={**meta,'record_id':meta['source_id']+'-doc-'+sha(meta['source_path']+':'+str(i)+body)[:24],
            'record_type':'documentation','intended_use':'rag','split':group_split(meta['source_id']+':'+meta['source_group']),
            'symbol':'documentation','line_start':0,'line_end':0,'code':'','code_sha256':'','ast_sha256':'','template_ast_sha256':'',
            'topics':['pytorch','documentation'],'packages':[],'unresolved_names':[],'external_data_required':False,
            'compatibility_flags':['not_runtime_verified'],'license_id':license_id,'license_evidence':'upstream_repository_license',
            'attribution_notice':'See the source folder LICENSE and ATTRIBUTIONS.jsonl.',
            'validated_here':'text_only_not_executed','benchmark_content':False,'curation_version':VERSION}
        record['text']='# Documentation excerpt\nSource: '+meta['source_url']+'\nLicense: '+license_id+'\n\n'+body
        rows.append(record)
    return rows


def evaluation_record(meta,case_id,text,license_id,code='',extra=None):
    if SECRET.search(text+'\n'+code) or INJECTION.search(text+'\n'+code):return None
    if len(text)>8000:text=text[:8000]+'\n[Metadata excerpt bounded; use upstream source for full case.]'
    info=None
    if code:
        if len(code)>4800:return None
        info,reason=analyze(code)
        if reason:return None
    row={**meta,'record_id':meta['source_id']+'-case-'+sha(case_id+':'+meta['source_path']+code)[:24],
        'record_type':'benchmark_reproducer' if code else 'benchmark_task','intended_use':'evaluation',
        'split':'test','symbol':case_id,'line_start':1 if code else 0,'line_end':len(code.splitlines()),
        'code':code,'code_sha256':sha(code) if code else '',
        'ast_sha256':sha(info['canonical']) if info else '',
        'template_ast_sha256':template_hash(info['tree']) if info else '',
        'topics':sorted(set((info['topics'] if info else [])+['benchmark','debugging'])),
        'packages':info['packages'] if info else [],'unresolved_names':info['unresolved_names'] if info else [],
        'external_data_required':True,'compatibility_flags':['intentionally_failing_or_task_specific','requires_original_benchmark_environment'],
        'license_id':license_id,'license_evidence':'upstream_benchmark_packaging_license',
        'attribution_notice':'See source LICENSE and NOTICE. Original linked repositories and issue reports retain their own licenses.',
        'validated_here':'syntax_only_not_executed' if code else 'metadata_only_not_executed',
        'benchmark_content':True,'curation_version':VERSION}
    row['text']='# Benchmark study/evaluation evidence — not a working recipe\n'+text+'\n\nSource: '+meta['source_url']+'\nLicense: '+license_id
    if code:row['text']+='\n\n```python\n'+code+'\n```\n'
    if extra:row.update(extra)
    return row