-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate-dataset.py
executable file
·223 lines (199 loc) · 9.03 KB
/
generate-dataset.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
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
#!/bin/python
import os
import re
import time
import json
import bz2
import html
from bs4 import BeautifulSoup
def main(dump, output, allowed, verbose):
print("\nLoading...")
start_time = time.perf_counter()
titles = set()
articles = []
with open(allowed, "r") as f:
for line in f:
line = line.strip()
titles.add(line)
print("Starting...")
with open(output, "w") as output_file:
first_article = True
total_size = os.path.getsize(dump)
current_position = 0
output_file.write("[")
try:
with bz2.open(dump, 'rt') as f:
line = f.readline()
while line:
if line.startswith(" <title>"):
title = line.split("<title>")[1].split("</title>")[0]
print(f"[{(f.tell()/total_size)*100:.2f}%] ", end="")
if title not in titles:
print(f"\033[31m{title}\033[0m")
line = f.readline()
continue
while not line.startswith(" <text"):
line = f.readline()
if '#REDIRECT' in line:
print(f"\033[33m{title}\033[0m")
line = f.readline()
continue
article = ""
line = f.readline()
while not line.endswith("</text>\n"):
article += line
line = f.readline()
article, size = format_article(article, title)
if size < 2000:
print(f"\033[34m{title}\033[0m")
line = f.readline()
continue
print(f"\033[32m{title}\033[0m")
if not first_article:
output_file.write(",")
else:
first_article = False
json.dump(article, output_file, indent=None)
line = f.readline()
except KeyboardInterrupt:
pass
finally:
output_file.write("]")
print("\nDataset generated.")
def format_article(article, title):
article = translate_convertions(article)
article = re.sub("{{(vr|IPA|angbr| )+\|(.*?)}}", r'"\2"', article)
article = re.sub("{{(vr|IPA|angbr| )+\|/\[\[.*?\|(.*?)\]\]/}}", r'"\2"', article)
article = re.sub("{{lang(\||\-).*?\|(.*?)}}", r"\2", article)
article = re.sub("{{Lang-.*?\|(.*?)}}", r"\1", article)
article = re.sub("''{{transl\|.*?\|(.*?)}}''", r'"\1"', article)
article = re.sub("{{'(s)?}}", r"'\1", article)
article = article.replace(" (", "(")
article = clean_parenthesis(article)
article = re.sub("\n.*?<(math|code|su(b|p))>.*", "", article)
article = re.sub("<ref(>)?.*?(<)?/ref(>)?", "", article)
article = html.unescape(article)
article = BeautifulSoup(article, "html.parser").get_text()
article = re.sub("\{\{.*(\'\'\'.*?\'\'\').*\}\}", r"\1", article)
article = re.sub("^(?=.*\'\'\').*\n", "", article)
article = article.replace("\'\'\'", "")
article = re.sub("(\n|^)(\*|\_|\{|\}|\||!|&|#|@|;|:|\.| |,|\?|%|\/|\\\\|\[?\[?(File|Image|Category):).*", "", article)
article = re.sub("\n.*?\[http.*", "", article)
article = re.sub("\[\[([^\||\]\]]*?)\]\]", r"\1", article)
article = re.sub("\[\[.*?\|(.*?)\]\]", r"\1", article)
article = re.sub("\[(.*?)\]", r"\1", article)
article = re.sub("[ ]+(\.|:|;|,)", r"\1", article)
article = article.replace("—", "-")
article = article.replace("–", "-")
article = article.replace("−", "-")
article = article.replace("‐", "-")
article = article.replace("―", "-")
article = article.replace("’", "'")
article = article.replace("ʼ", "'")
article = article.replace("“", "\"")
article = article.replace("”", "\"")
article = article.replace("″", "\"")
article = article.replace("ʻ", "\'")
article = article.replace("ʻ", "\'")
article = article.replace("′", "\'")
article = article.replace("‘", "\'")
article = article.replace("ˈ", "\'")
article = article.replace(" ", " ")
article = article.replace("±", "+/-")
article = article.replace("а", "a")
article = article.replace("с", "c")
article = article.replace("ο", "o")
article = article.replace("∼", "~")
article = article.replace("≈", "~")
article = article.replace("½", "1/2")
article = article.replace("⅓", "1/3")
article = article.replace("…", "...")
article = article.replace("․", ".")
article = article.replace("∗", "*")
article = re.sub("\.\.\. ([a-z])", r"\1", article)
article = re.sub("\.{4,}", "...", article)
article = re.sub(r'\n.*?([^\x00-\x7F\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036FΔωστλβμ£€ηδρπαθε]).*', '', article)
article = article.replace(" [...] ", " ")
article = article.replace("\'\'\'\'", "")
article = article.replace("''", "\"")
article = article.replace('""', '"')
article = article.replace(',"', '"')
article = article.replace(". ...", ".")
article = re.sub("([a-z])\.\"( *[A-Z])", r'\1".\2', article)
article = re.sub("(.) ,", r"\1,", article)
article = re.sub("\n.*(:|;|!|\?|,|[A-Za-z0-9]) *(?=\n|$)", "", article)
article = re.sub("\n[a-z].*", "", article)
article = re.sub("\n.*((?<!=)=(?!=)|\||\[|\]).*", "", article)
article = re.sub(" +(\n|$)", r"\1", article)
article = remove_odd(article)
article = f"==Definition==\n{article}"
article = re.sub("[ ]{2,}", " ", article)
article = re.sub("\n{2,}", "\n", article)
article = re.sub("\n={2,}[^=]+={2,}\n.{0,300}(?=\n={2,})", "", article, flags=re.DOTALL)
article = re.sub("(?i)\n={2,}[^\n]*?(link|further reading|sources|references|notes|citations|see also)[^\n]*?={2,}\n.*?(?=\n==|\n?$)", "", article, flags=re.DOTALL)
article = re.sub("(={2,} ?.* ?={2,}\n+)+(={2,} ?.* ?={2,}\n+|[\n ]*$)", r"\2", article)
article = re.sub("\n?={2,} ?(.*?) ?={2,}\n", fr'\n\n##### {title}, \1\n', article)
article = re.sub(r"^\n+#####", "\n\n#####", article)
article = re.sub(r"\n*$", "", article)
sections = re.split(f'\n\n##### ([^\n]+)\n', article)
sections.pop(0)
result = [{'title': sections[i], 'content': sections[i+1]} for i in range(0, len(sections), 2)]
return result, len(article)
def clean_parenthesis(string):
cleaned = []
nest = 0
paren_map = {'{': '}', '(': ')'}
for char in string:
if char in paren_map:
nest += 1
elif char in paren_map.values() and nest > 0:
nest -= 1
elif nest == 0:
cleaned.append(char)
return ''.join(cleaned)
def remove_odd(input_string: str) -> str:
lines = input_string.split('\n')
output_lines = []
for line in lines:
quotes = 0
parens = 0
for char in line:
if char == '"':
quotes += 1
elif char == "(":
parens += 1
elif char == ")":
parens += 1
if quotes % 2 == 0 and parens % 2 == 0:
output_lines.append(line)
return '\n'.join(output_lines)
def translate_convertions(string):
value = "([0-9\.,\- /\+x\*×±(by)(to)(and)]+)"
multiplier = "(y|z|a|f|p|n|µ|m|c|d|da|h|k|M|G|T|P|E|Z|Y|L|S|e6|(U|u)\.?(S|s)\.?)"
unit = "(in|inche?s?|ft|feet|foot|mi|miles?|yd|yards?|lbs?|gal|floz|oz|oilbbl|carat|°?C|°?F|atm|$|€|£|ha|acres?|t|tonnes?|PS|T|J|W|o|B|iB|D|m|meters?|metres?|min|minutes?|s|sec|seconds?|p?h|hours?|d|days?|g|gf|A|K|mol|cd|L|l|liters?|e?V|J|W|Pa|bar|n|N|psi|AU|ly|lbf|pc|cal|hp|knot|(M|m)ach|cc)"
pattern = re.compile(f"{{{{((c|C)onvert|cvt) *\| *{value} *\| *((sq)?{multiplier}?{unit}([0-9]*|²?|³?)((/|p|\.)(sq)?{multiplier}?{unit}([0-9]*|²?|³?))?) *(\|.*?}}}}|}}}})")
converted = re.sub(r"({{((c|C)onvert|cvt) *\|.*?)\|(by|to|and|or|x|×|\-|\+/\-|±|\*)\|(.*?}})", r"\2 \3 \4", string)
# converted = re.sub(r"({{((c|C)onvert|cvt).*?)(\-change|\(-\))(.*?}})", r"\1\3", converted)
converted = re.sub(pattern, r"\3 \4", converted)
converted = re.sub(r"(\n|^).*?{{((c|C)onvert|cvt).*?}}.*", "", converted)
return converted
# For debugging the regex
# oldarticle = article
# diff(article, oldarticle)
def diff(string1, string2):
differ = Differ()
# diff = list(differ.compare(string2.split(" "), string1.split(" ")))
diff = list(differ.compare(string2.splitlines(), string1.splitlines()))
for line in diff:
# if line[0] == ' ':
# print(line[2:])
if line[0] == '+':
print(f"\033[92m{line[2:]}\033[0m")
elif line[0] == '-':
print(f"\033[91m{line[2:]}\033[0m")
if __name__ == "__main__":
dump = "wikipedia.bz2"
output = "dataset.json"
allowed = "titles.txt"
verbose = True
main(dump, output, allowed, verbose)