-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathcreate_dataset.py
More file actions
executable file
·235 lines (172 loc) · 6.03 KB
/
Copy pathcreate_dataset.py
File metadata and controls
executable file
·235 lines (172 loc) · 6.03 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
#!/usr/bin/env python
"""
Parse all files and write to a single file
"""
import re
import string
import urllib.error
import urllib.request
import zipfile
from pathlib import Path
from pathlib import PurePath
from typing import List, NamedTuple, Set
from typing import Optional
import numpy as np
from labml import lab, monit
from labml import logger
from labml.internal.util import rm_tree
PRINTABLE = set(string.printable)
class PythonFile(NamedTuple):
relative_path: str
project: str
path: Path
def get_python_files():
"""
Get list of python files and their paths inside `data/source` folder
"""
source_path = Path(lab.get_data_path() / 'source')
files: List[PythonFile] = []
def _add_file(path: Path):
"""
Add a file to the list of tiles
"""
project = path.relative_to(source_path).parents
relative_path = path.relative_to(source_path / project[len(project) - 3])
files.append(PythonFile(relative_path=str(relative_path),
project=str(project[len(project) - 2]),
path=path))
def _collect_python_files(path: Path):
"""
Recursively collect files
"""
for p in path.iterdir():
if p.is_dir():
_collect_python_files(p)
else:
_add_file(p)
_collect_python_files(source_path)
return files
def read_file(path: Path) -> str:
"""
Read a file
"""
with open(str(path)) as f:
content = f.read()
content = ''.join(filter(lambda x: x in PRINTABLE, content))
return content
def concat_and_save(path: PurePath, source_files: List[PythonFile]):
with open(str(path), 'w') as f:
for i, source in monit.enum(f"Write {path.name}", source_files):
f.write(f"# PROJECT: {source.project} FILE: {str(source.relative_path)}\n")
f.write(read_file(source.path) + "\n")
def get_repos_from_readme(filename: str):
with open(str(lab.get_data_path() / filename), 'r') as f:
content = f.read()
link_pattern = re.compile(r"""
\[(?P<title>[^\]]*)\] # title
\((?P<utl>[^\)]*)\) # url
""", re.VERBOSE)
res = link_pattern.findall(content)
github_repos = []
repo_pattern = re.compile(r'https://github.com/(?P<user>[^/]*)/(?P<repo>[^/#]*)$')
for title, url in res:
repos = repo_pattern.findall(url)
for r in repos:
github_repos.append((r[0], r[1]))
return github_repos
def get_awesome_pytorch_readme():
md = urllib.request.urlopen('https://raw.githubusercontent.com/bharathgs/Awesome-pytorch-list/master/README.md')
content = md.read()
with open(str(lab.get_data_path() / 'pytorch_awesome.md'), 'w') as f:
f.write(str(content))
def download_repo(org: str, repo: str, idx: Optional[int]):
zip_file = Path(lab.get_data_path() / 'download' / f'{org}_{repo}.zip')
if zip_file.exists():
return zip_file
if idx is not None:
idx_str = f"{idx:03}: "
else:
idx_str = ""
with monit.section(f"{idx_str} {org}/{repo}") as s:
try:
zip = urllib.request.urlopen(f'https://github.com/{org}/{repo}/archive/master.zip')
except urllib.error.HTTPError as e:
print(e)
return
content = zip.read()
size = len(content) // 1024
s.message = f"{size :,}KB"
with open(str(zip_file), 'wb') as f:
f.write(content)
return zip_file
def create_folders():
path = Path(lab.get_data_path() / 'download')
if not path.exists():
path.mkdir(parents=True)
source = Path(lab.get_data_path() / 'source')
if not source.exists():
source.mkdir(parents=True)
def extract_zip(file_path: Path, overwrite: bool = False):
source = Path(lab.get_data_path() / 'source')
with monit.section(f"Extract {file_path.stem}"):
repo_source = source / file_path.stem
if repo_source.exists():
if overwrite:
rm_tree(repo_source)
else:
return repo_source
try:
with zipfile.ZipFile(file_path, 'r') as repo_zip:
repo_zip.extractall(repo_source)
except zipfile.BadZipfile as e:
print(file_path, e)
return repo_source
def remove_files(path: Path, keep: Set[str]):
"""
Remove files
"""
for p in path.iterdir():
if p.is_symlink():
p.unlink()
continue
if p.is_dir():
remove_files(p, keep)
else:
if p.suffix not in keep:
p.unlink()
def batch(overwrite: bool = False):
with monit.section('Get pytorch_awesome'):
get_awesome_pytorch_readme()
repos = get_repos_from_readme('pytorch_awesome.md')
# Download zips
for i, r in monit.enum(f"Download {len(repos)} repos", repos):
download_repo(r[0], r[1], i)
# Extract downloads
with monit.section('Extract zips'):
download = Path(lab.get_data_path() / 'download')
for repo in download.iterdir():
extract_zip(repo, overwrite)
with monit.section('Remove non python files'):
remove_files(lab.get_data_path() / 'source', {'.py'})
def progressive(overwrite: bool = False):
# Get repos
get_awesome_pytorch_readme()
repos = get_repos_from_readme('pytorch_awesome.md')
# Download zips
for i, r in monit.enum(f"Download {len(repos)} repos", repos):
zip_file = download_repo(r[0], r[1], i)
extracted = extract_zip(zip_file, overwrite)
remove_files(extracted, {'.py'})
def main():
try:
batch()
except KeyboardInterrupt:
pass
source_files = get_python_files()
np.random.shuffle(source_files)
logger.inspect(source_files)
train_valid_split = int(len(source_files) * 0.9)
concat_and_save(lab.get_data_path() / 'train.py', source_files[:train_valid_split])
concat_and_save(lab.get_data_path() / 'valid.py', source_files[train_valid_split:])
if __name__ == '__main__':
main()