-
Notifications
You must be signed in to change notification settings - Fork 129
/
extract_code.py
executable file
·166 lines (130 loc) · 4.2 KB
/
extract_code.py
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
#!/usr/bin/env python
"""
Parse all files and write to a single file
"""
import os
from pathlib import Path
from typing import List, NamedTuple
from labml import logger, monit
from parser import tokenizer
from parser.tokenizer import encode, parse_string
COMMENT = '#'
MULTI_COMMENT = '"""'
class _PythonFile(NamedTuple):
relative_path: str
project: str
path: Path
class _GetPythonFiles:
"""
Get list of python files and their paths inside `data/source` folder
"""
def __init__(self):
self.source_path = Path(os.getcwd()) / 'data' / 'source'
self.files: List[_PythonFile] = []
self.get_python_files(self.source_path)
logger.inspect([f.path for f in self.files])
def add_file(self, path: Path):
"""
Add a file to the list of tiles
"""
project = path.relative_to(self.source_path).parents
project = project[len(project) - 2]
relative_path = path.relative_to(self.source_path / project)
self.files.append(_PythonFile(relative_path=str(relative_path),
project=str(project),
path=path))
def get_python_files(self, path: Path):
"""
Recursively collect files
"""
for p in path.iterdir():
if p.is_dir():
self.get_python_files(p)
else:
if p.suffix == '.py':
self.add_file(p)
def _fix_indentation(parsed: List[tokenizer.ParsedToken]) -> List[tokenizer.ParsedToken]:
"""
Change indentation tokens. Remove `DEDENT` tokens and
add `INDENT` tokens to each line.
This is easier for prediction.
"""
res: List[tokenizer.ParsedToken] = []
indentation = 0
indented = False
for t in parsed:
if t.type == tokenizer.TokenType.indent:
indentation += 1
elif t.type == tokenizer.TokenType.dedent:
indentation -= 1
elif t.type in [tokenizer.TokenType.new_line,
tokenizer.TokenType.eof]:
indented = False
res.append(t)
else:
if not indented:
for _ in range(indentation):
res.append(tokenizer.ParsedToken(tokenizer.TokenType.indent, 0))
indented = True
res.append(t)
return res
def _remove_comments(parsed: List[tokenizer.ParsedToken]) -> List[tokenizer.ParsedToken]:
"""
Remove comment tokens
"""
res = []
for p in parsed:
if p.type == tokenizer.TokenType.comment:
continue
else:
res.append(p)
return res
def _remove_empty_lines(parsed: List[tokenizer.ParsedToken]) -> List[tokenizer.ParsedToken]:
"""
Remove empty lines
"""
tokens = [tokenizer.TokenType.new_line, tokenizer.TokenType.new_line]
res = []
for p in parsed:
for i in range(1):
tokens[i] = tokens[i + 1]
tokens[-1] = p.type
all_new_line = True
for t in tokens:
if t != tokenizer.TokenType.new_line:
all_new_line = False
if all_new_line:
continue
else:
res.append(p)
return res
def _read_file(path: Path) -> List[int]:
"""
Read and encode a file
"""
with open(str(path)) as f:
content = f.read()
parsed = parse_string(content)
parsed = _remove_comments(parsed)
parsed = _remove_empty_lines(parsed)
parsed = _fix_indentation(parsed)
serialized = encode(parsed)
# deserialized = tokenizer.deserialize(serialized)
# for i in range(len(serialized)):
# assert deserialized[i] == parsed[i]
#
# res = to_text(deserialized)
# print(res)
return serialized
def main():
source_files = _GetPythonFiles().files
logger.inspect(source_files)
with open(str(Path(os.getcwd()) / 'data' / 'all.py'), 'w') as f:
for i, source in monit.enum("Parse", source_files):
serialized = _read_file(source.path)
# return
serialized = [str(t) for t in serialized]
f.write(f"{str(source.path)}\n")
f.write(" ".join(serialized) + "\n")
if __name__ == '__main__':
main()