Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
Latest commit
405 lines (324 loc) · 16.2 KB
/
Copy pathapi.py
File metadata and controls
405 lines (324 loc) · 16.2 KB
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
importre
importlogging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO)
logger=logging.getLogger(__name__)
logger.setLevel(logging.INFO)
classGET_API():
def__init__(self, examples, language):
self.examples=examples
self.language=language
defget(self):
examples_api= []
forexampleinself.examples:
ifself.language=='python':
api_info=self._process_python_example(example)
elifself.language=='java':
api_info=self._process_java_example(example)
else:
api_info=""
examples_api.append(api_info)
returnexamples_api
def_process_python_example(self, example):
imported_entities=self._extract_python_imports(example.left_context)
api_descriptions= []
forentity_infoinimported_entities:
entity_name=entity_info['name']
definition_info=self._find_python_definition(entity_name, example.related_files)
ifdefinition_info:
ifdefinition_info['type'] =='class':
api_descriptions.append(definition_info['content'])
elifdefinition_info['type'] =='function':
api_descriptions.append(definition_info['signature'])
return"\n\n".join(api_descriptions)
def_extract_python_imports(self, content):
imported_entities= []
std_libs= {
'abc', 'argparse', 'asyncio', 'collections', 'concurrent', 'contextlib',
'copy', 'csv', 'datetime', 'decimal', 'functools', 'glob', 'io', 'json',
'logging', 'math', 'os', 'pathlib', 're', 'shutil', 'socket', 'subprocess',
'sys', 'tempfile', 'threading', 'time', 'typing', 'unittest', 'uuid',
'xml', 'zipfile'}
third_party_libs= {
'numpy', 'pandas', 'matplotlib', 'scipy', 'sklearn', 'tensorflow',
'torch', 'requests', 'flask', 'django', 'bs4', 'selenium', 'pytest',
'sqlalchemy', 'pydantic', 'fastapi', 'nltk', 'transformers', 'pillow',
'openai', 'websockets', 'aiohttp', 'sentencepiece', 'tqdm', 'torchvision'}
import_lines=re.findall(r'(?:^|\n)(?:import|from)\s+.*?(?:$|\n)', content, re.MULTILINE)
forlineinimport_lines:
line=line.strip()
ifline.startswith('from'):
match=re.match(r'from\s+([a-zA-Z0-9_.]+)\s+import\s+(.*?)$', line)
ifmatch:
module=match.group(1)
base_module=module.split('.')[0]
ifbase_moduleinstd_libsorbase_moduleinthird_party_libs:
continue
items=re.split(r',\s*', match.group(2))
foriteminitems:
item=item.strip()
if' as 'initem:
original, alias=item.split(' as ', 1)
imported_entities.append({'name': original, 'module': module})
else:
imported_entities.append({'name': item, 'module': module})
elifline.startswith('import'):
items=re.split(r',\s*', line[6:].strip())
foriteminitems:
item=item.strip()
base_module=item.split('.')[0].split(' as ')[0]
ifbase_moduleinstd_libsorbase_moduleinthird_party_libs:
continue
if' as 'initem:
original, alias=item.split(' as ', 1)
imported_entities.append({'name': original, 'module': original})
else:
parts=item.split('.')
imported_entities.append({'name': parts[0], 'module': item})
returnimported_entities
def_find_python_definition(self, name, related_files):
forfileinrelated_files:
class_pattern=rf'class\s+{re.escape(name)}\s*(?:\(.*?\))?\s*:'
class_match=re.search(class_pattern, file.code_content, re.DOTALL)
ifclass_match:
class_content=self._parse_class_content(file.code_content, class_match)
return {'type': 'class', 'content': class_content}
func_pattern=rf'def\s+{re.escape(name)}\s*\(.*?\)\s*(?:->\s*.*?)?\s*:'
func_match=re.search(func_pattern, file.code_content, re.MULTILINE)
iffunc_match:
func_sig=self._parse_function_signature(file.code_content, func_match)
return {'type': 'function', 'signature': func_sig}
returnNone
def_parse_class_content(self, code_content, match):
start_pos=match.start()
header_line=code_content[start_pos: code_content.find('\n', start_pos)].strip()
# logging.info(f'header line:\n{header_line}')
lines=code_content[start_pos:].split('\n')
iflen(lines) <2:
returnheader_line
body_lines=lines[1:]
indent=None
forlineinbody_lines:
ifline.strip():
indent_match=re.match(r'^(\s+)', line)
ifindent_match:
indent=indent_match.group(1)
break
ifindentisNone:
returnheader_line
indent_len=len(indent)
method_signatures= []
index=0
whileindex<len(body_lines):
line=body_lines[index]
index+=1
ifline.strip() =='':
continue
line_indent=re.match(r'^\s*', line).group(0)
iflen(line_indent) <indent_len:
break
ifline.lstrip().startswith('class '):
head_line=' '*4+line.strip()
method_signatures_nested= []
whileindex<len(body_lines):
line_temp=body_lines[index]
index+=1
ifline_temp.strip() =='':
continue
line_temp_indent=re.match(r'^\s*', line_temp).group(0)
ifline_temp_indent<=line_indent:
break
ifline_temp.lstrip().startswith('def '):
sig_nested=line_temp.strip()
line_tmp=sig_nested
whileindex<len(body_lines) and (line_tmp.strip() ==''orline_tmp[-1] !=':'):
line_tmp=body_lines[index].strip()
sig_nested+=line_tmp
index+=1
sig_nested=' '*8+sig_nested
method_signatures_nested.append(sig_nested)
nested_class_info='\n'.join([head_line] +method_signatures_nested)
method_signatures.append(nested_class_info)
elifline.lstrip().startswith('def '):
sig=line.strip()
line_temp=sig
whileindex<len(body_lines) and (line_temp.strip() ==''orline_temp[-1] !=':'):
line_temp=body_lines[index].strip()
sig+=line_temp
index+=1
sig=' '*4+sig
method_signatures.append(sig)
class_api_info='\n'.join([header_line] +method_signatures)
returnclass_api_info
def_parse_function_signature(self, code_content, match):
start=match.start()
end=code_content.find('\n', start)
end_1=code_content.find(':', start)
end=max(end, end_1)
ifend==-1:
end=len(code_content)
sig_line=code_content[start:end].strip()
# logging.info(f'sig_line:\n{sig_line}')
returnsig_line
def_parse_java_function_signature(self, code_content, match):
start=match.start()
end=code_content.find('{', start) +1
ifend==0:
end=code_content.find(';', start) +1
ifend==0:
end=len(code_content)
signature=code_content[start:end].strip()
ifsignature.endswith('{'):
signature=signature.rstrip('{').strip()
returnsignature
def_extract_java_imports(self, content):
imported_entities= []
standard_packages= [
'java.',
'javax.',
'javafx.',
'com.sun.',
'com.oracle.',
'sun.',
'jdk.',
'oracle.'
]
import_lines=re.findall(r'(?:^|\n)import\s+.*?;', content, re.MULTILINE)
forlineinimport_lines:
line=line.strip()
ifline.startswith('import'):
package_path=line[6:].strip().rstrip(';').strip()
is_standard_lib=False
forstd_pkginstandard_packages:
ifpackage_path.startswith(std_pkg) or (
package_path.startswith('static ') and
package_path[7:].startswith(std_pkg)
):
is_standard_lib=True
break
ifis_standard_lib:
continue
is_static=False
ifpackage_path.startswith('static '):
is_static=True
package_path=package_path[7:]
ifpackage_path.endswith('.*'):
package=package_path[:-2]
imported_entities.append({
'name': '*',
'original': package_path,
'package': package,
'is_static': is_static
})
else:
parts=package_path.rsplit('.', 1)
iflen(parts) >1:
package, class_name=parts
else:
package, class_name="", parts[0]
imported_entities.append({
'name': class_name,
'original': package_path,
'package': package,
'is_static': is_static
})
returnimported_entities
def_process_java_example(self, example):
processed_entities=set()
imported_entities=self._extract_java_imports(example.left_context)
api_descriptions= []
forentity_infoinimported_entities:
entity_name=entity_info['name']
ifentity_nameinprocessed_entitiesorentity_name=='*':
continue
processed_entities.add(entity_name)
definition_info=self._find_java_definition(entity_name, example.related_files)
ifdefinition_info:
ifdefinition_info['type'] =='class':
api_descriptions.append(definition_info['content'])
elifdefinition_info['type'] =='method':
method_sig=definition_info['signature']
api_descriptions.append(method_sig)
forentity_infoinimported_entities:
ifentity_info['name'] =='*':
package_name=entity_info['package']
package_classes=self._find_classes_in_package(package_name, example.related_files)
forclass_nameinpackage_classes:
ifclass_nameinprocessed_entities:
continue
processed_entities.add(class_name)
definition_info=self._find_java_definition(class_name, example.related_files)
ifdefinition_info:
ifdefinition_info['type'] =='class':
api_descriptions.append(definition_info['content'])
elifdefinition_info['type'] =='method':
method_sig=definition_info['signature']
api_descriptions.append(method_sig)
return"\n\n".join(api_descriptions)
def_find_classes_in_package(self, package_name, related_files):
classes= []
package_pattern=re.compile(rf'package\s+{re.escape(package_name)}\s*;', re.MULTILINE)
class_pattern=re.compile(r'(?:public|private|protected|abstract|final)?\s+(?:class|interface|enum)\s+(\w+)', re.MULTILINE)
forfileinrelated_files:
package_match=package_pattern.search(file.code_content)
ifpackage_match:
class_matches=class_pattern.finditer(file.code_content)
formatchinclass_matches:
class_name=match.group(1)
classes.append(class_name)
returnclasses
def_parse_java_class_content(self, code_content, match):
start_pos=match.start()
header_end=code_content.find('{', start_pos) +1
ifheader_end<=0:
returncode_content[start_pos:].split('\n')[0].strip()
header_line=code_content[start_pos:header_end].strip()
end_pos=self._find_matching_brace_end(code_content, header_end-1)
ifend_pos==-1:
returnheader_line+" ... }"
class_body=code_content[header_end:end_pos]
method_pattern=r'\b(?:public|private|protected|static|final|abstract|synchronized)(?:\s+(?:public|private|protected|static|final|abstract|synchronized))*\s+(?!if|while|for|switch|catch)[\w<>\[\],\s.]+?\s+(\w+)\s*\([^)]*\)\s*(?:throws\s+[\w\s,\.]+)?\s*\{'
method_matches=list(re.finditer(method_pattern, class_body))
method_signatures= []
formethod_matchinmethod_matches:
method_start=method_match.start()
brace_pos=class_body.find('{', method_start)
ifbrace_pos==-1:
continue
method_sig=class_body[method_start:brace_pos].strip()
method_signatures.append(' '*4+method_sig)
class_api_info='\n'.join([header_line] +method_signatures) +'\n}'
returnclass_api_info
def_find_matching_brace_end(self, text, open_brace_pos):
ifopen_brace_pos>=len(text) ortext[open_brace_pos] !='{':
return-1
stack= ['{']
pos=open_brace_pos+1
whilepos<len(text) andstack:
iftext[pos] =='{':
stack.append('{')
eliftext[pos] =='}':
stack.pop()
ifnotstack:
returnpos
pos+=1
return-1
def_find_java_definition(self, name, related_files):
class_pattern=re.compile(
rf'(?:public|private|protected|abstract|final)?\s+(?:class|interface|enum)\s+{re.escape(name)}\s*(?:extends\s+\w+(?:\.\w+)*)?(?:\s+implements\s+[\w\s,\.]+)?\s*\{{',
re.DOTALL
)
method_pattern=re.compile(
rf'(?:public|private|protected|static|final|abstract|synchronized)?\s+(?:[\w<>\[\],\s]+)\s+{re.escape(name)}\s*\([^)]*\)\s*(?:throws\s+[\w\s,\.]+)?\s*\{{',
re.MULTILINE
)
forfileinrelated_files:
content=file.code_content
class_match=class_pattern.search(content)
ifclass_match:
class_content=self._parse_java_class_content(content, class_match)
return {'type': 'class', 'content': class_content}
method_match=method_pattern.search(content)
ifmethod_match:
method_sig=self._parse_java_function_signature(content, method_match)
return {'type': 'method', 'signature': method_sig}
returnNone