-
Notifications
You must be signed in to change notification settings - Fork 0
/
anchor_statistics.py
263 lines (226 loc) · 7.85 KB
/
anchor_statistics.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
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
import json
import logging
import multiprocessing
import time
import re
from argparse import ArgumentParser
from bz2 import BZ2File
from multiprocessing.context import Process
from queue import Empty
from threading import Thread
from xml.sax import parse
import psutil as psutil
from elasticsearch import Elasticsearch, NotFoundError, ElasticsearchException
from elasticsearch.helpers import parallel_bulk
from nlp import NLP, TownProvider, GeoProvider, Cache, NameProvider
from reader import WikiReader
INDEX = "vi_index_to2"
logging.getLogger().setLevel(logging.WARN)
mapping = {
"settings": {
"analysis": {
"analyzer": {
"standard_asciifolding": {
"tokenizer": "standard",
"filter": [
"lowercase",
"my_ascii_folding"
]
}
},
"filter": {
"my_ascii_folding": {
"type": "asciifolding",
"preserve_original": True
}
}
}
},
"mappings": {
"properties": {
"page_to": {
"type": "keyword"
},
"page_to_entity": {
"type": "keyword"
},
"anchors": {
"properties": {
"anchor_text": {
"type": "text",
"term_vector": "with_positions",
"analyzer": "standard_asciifolding"
},
"page_from": {
"type": "keyword"
}
}
}
}
}
}
es = Elasticsearch()
try:
es.indices.delete(index=INDEX)
except NotFoundError:
pass
es.indices.create(index=INDEX, body=mapping)
def get_anchors(source: str):
for match in re.finditer(pattern="\[\[(.*?)\]\]", string=source):
yield match.group(1)
def process_anchor(anchor):
anchor = anchor.split("|")
link_to = anchor[0]
anchor_text = anchor[1] if len(anchor) == 2 else link_to
return anchor_text, link_to
class ArticleProcessor:
def __init__(self, provider, output) -> None:
super().__init__()
self.output = output
self.provider = provider
def __call__(self):
for page_title, source in self.provider:
for anchor in get_anchors(source=source):
anchor_text, link_to = process_anchor(anchor)
if link_to is not None and len(link_to) > 0:
self.output({
"page_from": page_title,
"page_to": link_to,
"anchor_text": anchor_text
})
class ESWriter:
def __init__(self, iterator) -> None:
super().__init__()
self.iterator = iterator
self.esx = Elasticsearch()
self.counts = {}
def __call__(self):
while not shutdown or not output_queue.empty() or not article_queue.empty() or not anchor_queue.empty():
try:
for success, info in parallel_bulk(client=self.esx, actions=self.preprocess(read_from_queue(output_queue)),
chunk_size=250, request_timeout=60):
if not success:
print("Insert failed: ", info)
except ElasticsearchException as e:
print("NEVYDALO :(")
print(e)
self.__del__()
def __del__(self):
with open("entity_counts" + str(int(time.time())) + ".json", "w") as f:
json.dump(self.counts, f)
def preprocess(self, iterator):
for i in iterator:
try:
self.counts[i['page_to_entity']] += 1
except KeyError:
self.counts[i['page_to_entity']] = 1
yield self.create_action(**i)
@staticmethod
def create_action(page_to, page_to_entity, anchors):
return {
"_index": INDEX,
"_id": page_to,
"_op_type": "update",
"retry_on_conflict": 6,
"_source": {
"script": {
"source": "ctx._source.anchors.addAll(params.anchor)",
"lang": "painless",
"params": {
"anchor": anchors
}
},
"upsert": {
"page_to": page_to,
"anchors": anchors,
"page_to_entity": page_to_entity
}
}
}
class Aggregator:
def __init__(self, provider, output) -> None:
super().__init__()
self.provider = provider
self.output = output
self.nlp = NLP(NameProvider("gn_csv/mena.csv"),
TownProvider("gn_csv/GNKU.csv"),
GeoProvider("gn_csv/geograficky_nazov.csv"))
self.cache = Cache(100000, output)
def __call__(self):
for i in self.provider:
if i["page_to"] is None:
continue
if i["page_to"] not in self.cache:
self.cache[i["page_to"]] = {
"page_to": i["page_to"],
"page_to_entity": self.nlp[i["page_to"]],
"anchors": []
}
self.cache[i["page_to"]]["anchors"].append({"page_from": i["page_from"], "anchor_text": i["anchor_text"]})
for i in self.cache:
self.output(i)
def display():
while not shutdown or not output_queue.empty() or not article_queue.empty() or not anchor_queue.empty():
print("Queue sizes {4}: articles={0} anchors={1} output={2}. Read: {3}".format(
article_queue.qsize(),
anchor_queue.qsize(),
output_queue.qsize(),
reader.status_count, shutdown))
time.sleep(1)
print("Done: " + str(shutdown))
def read_from_queue(queue):
while not shutdown or not output_queue.empty() or not article_queue.empty() or not anchor_queue.empty():
try:
yield queue.get(timeout=1)
except EOFError:
continue
except Empty:
continue
def process_article():
ArticleProcessor(read_from_queue(article_queue), anchor_queue.put)()
if __name__ == "__main__":
shutdown = False
parser = ArgumentParser()
parser.add_argument("wiki", help="wiki dump file .xml.bz2")
# parser.add_argument("out", help="final file .txt")
args = parser.parse_args()
logging.debug("subor: " + args.wiki)
wiki = BZ2File(args.wiki)
logging.debug("nacitane")
# out_file = open(os.path.join(args.out), "w+")
manager = multiprocessing.Manager()
output_queue = manager.Queue(maxsize=5000)
article_queue = manager.Queue(maxsize=5000)
anchor_queue = manager.Queue(maxsize=5000)
reader = WikiReader(lambda ns: ns == 0, article_queue.put)
status = Thread(target=display, args=())
status.start()
processes = []
for _ in range(6):
process = Process(target=process_article)
process.start()
psproc = psutil.Process(process.pid)
psproc.nice(12)
processes.append(process)
# for _ in range(14):
# process = Process(target=write_out)
# process.start()
aggregators = []
for _ in range(8):
aggregator = Aggregator(provider=read_from_queue(anchor_queue), output=output_queue.put)
agg_thread = Process(target=aggregator)
agg_thread.start()
psproc = psutil.Process(agg_thread.pid)
psproc.nice(12)
aggregators.append(agg_thread)
writer = ESWriter(output_queue)
write_thread = Thread(target=writer)
write_thread.start()
parse(wiki, reader)
shutdown = True
for process in processes:
process.join()
for process in aggregators:
process.join()
write_thread.join()
status.join()