-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogos.py
executable file
·177 lines (156 loc) · 4.93 KB
/
logos.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
#!/usr/bin/env python3
import bz2
import json
import re
import sys
import urllib.parse
import urllib.request
import xml.sax
from datetime import datetime, timezone
from xml.sax.handler import ContentHandler
# https://github.com/earwig/mwparserfromhell
import mwparserfromhell as mwp
logoBase = 'https://en.wikipedia.org/wiki/Special:Redirect/file'
url = 'http://localhost/enwiki-latest-pages-articles-multistream.xml.bz2'
tags = frozenset(['logo'])
articleCount = 0
infoCount = 0
startTime = None
svgLogoCount = 0
class JsonHandler():
def __init__(self, file=sys.stdout):
self.count = 0
self.file = file
def add(self, img, name, src):
if self.count:
print(',', file=self.file)
else:
text = self.buildJson()
offset = text.find(']')
print(text[:offset], file=self.file)
print(json.dumps({'img': img, 'name': name, 'src': src }, separators=(',', ':')), end='', file=self.file)
self.count = self.count + 1
def buildJson(self):
return json.dumps({
'handle': '',
'images': [],
'lastmodified': isodatetime(),
'logo': '',
'name': '',
'provider': '',
'provider_icon': '',
'url': '',
'website': ''
}, indent=0)
def end(self):
print('', file=self.file)
text = self.buildJson()
offset = text.find(']')
print(text[offset:], file=self.file)
class MarkupHandler():
def __init__(self, output):
self.output = output
def process(self, base, title, text):
global articleCount, infoCount, svgLogoCount
if articleCount % 1000 == 0:
now = datetime.utcnow()
delta = now - startTime
print(isodatetime(now), delta.total_seconds(), articleCount, infoCount, svgLogoCount, file=sys.stderr)
articleCount = articleCount + 1
parsed = mwp.parse(text)
hasInfobox = False
for template in parsed.ifilter_templates():
name = str(template.name).strip()
if name[0:7].lower() != 'infobox':
continue
infoCount = infoCount + 1
hasInfobox = True
for argument in template.params:
tag = str(argument.name).strip().lower()
if not tag in tags:
continue
pageUrl = urllib.parse.urljoin(base, urlencode(title))
logoUrls = imageValueToUrls(argument.value)
for logoUrl in logoUrls:
svgLogoCount = svgLogoCount + 1
self.output.add(logoUrl, title, pageUrl)
class TextHandler(ContentHandler):
def __init__(self, process):
self._chunks = []
self._parser = xml.sax.make_parser()
self._parser.setContentHandler(self)
self._process = process
self._base = ''
self._title = ''
def characters(self, chunk):
self._chunks.append(chunk)
def endElement(self, name):
text = ''.join(self._chunks)
if name == 'text':
self._process(self._base, self._title, text)
elif name == 'base':
self._base = text
elif name == 'title':
self._title = text
def feed(self, data):
self._parser.feed(data)
def startElement(self, name, attrs):
self._chunks = []
def decompress(byteStream, feed):
bufsize = 128 * 1024
decompressor = bz2.BZ2Decompressor()
while True:
compressed = byteStream.read(bufsize)
if not compressed:
break
while True:
decompressed = decompressor.decompress(compressed)
feed(decompressed)
if decompressor.eof:
compressed = decompressor.unused_data
decompressor = bz2.BZ2Decompressor()
else:
break
def isodatetime(when=None):
if when:
when = when.replace(tzinfo=timezone.utc)
else:
when = datetime.now(timezone.utc)
return when.isoformat()
refile = re.compile(r'(?i)^ *\[\[ *file *:')
def imageValueToUrls(value):
value = str(value).strip() if value else ''
values = [urlencode(value)]
if refile.match(value):
parsed = mwp.parse(value)
values = [urlencode(wikilink.title.strip()) for wikilink in parsed.ifilter_wikilinks()]
return [f'{logoBase}/{v}' for v in values if v.endswith('.svg')]
# See https://www.mediawiki.org/wiki/Manual:Page_title#Encoding
allowed = frozenset(b'\'(),-.0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz')
def urlencode(value):
chars = []
for b in value.encode():
if b in allowed:
chars.append(chr(b))
elif b == ord(' '):
chars.append('_')
else:
chars.append("%%%0.2X" % b)
return ''.join(chars)
def main(url):
global startTime
startTime = datetime.utcnow()
output = JsonHandler()
markupParser = MarkupHandler(output)
xmlParser = TextHandler(lambda base, title, text : markupParser.process(base, title, text))
with urllib.request.urlopen(url) as byteStream:
decompress(byteStream, lambda data : xmlParser.feed(data))
output.end()
now = datetime.utcnow()
delta = now - startTime
print('articleCount', articleCount, file=sys.stderr)
print('infoCount', infoCount, file=sys.stderr)
print('svgLogoCount', svgLogoCount, file=sys.stderr)
print('elapsed', delta, file=sys.stderr)
if __name__ == '__main__':
main(url)