-
Notifications
You must be signed in to change notification settings - Fork 0
/
item-analysis.py
executable file
·344 lines (299 loc) · 10.2 KB
/
item-analysis.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env python2
import sys, bz2, time, gzip, os, urllib, re
import json
from collections import defaultdict
# This scripts creates the knowledge base and collects a few numbers by going through
# all dailies up to and the latest available dump. This usually runs a few hours.
def log(txt) :
print txt
log('Calculating Wikidata stats')
start_time = time.time()
# for dictionary creation
langs = [ 'en', 'de', 'hr', 'uz' ]
# read the list of bots
log('Loading list of bots')
bots = []
botsjson = urllib.urlopen('http://www.wikidata.org/w/api.php?action=query&list=allusers&augroup=bot&aulimit=500&format=json').read()
botsjson = eval(botsjson)
for bot in botsjson['query']['allusers'] :
bots.append(bot['name'])
log('List of bots: ' + str(bots))
linecount = 0
charactercount = 0
# Items
itemcount = 0
itemswithclaims = 0
claimcount = 0
claimsperitem = {}
claimswithrefs = 0
refs = 0
itemswithrefs = 0
labelcount = 0
descriptioncount = 0
sitelinkcount = 0
itemrevisioncount = 0
botrevisioncount = 0
revisionsperitem = {}
titleofmostclaims = ''
langlabels = {}
langdescriptions = {}
langsitelinks = {}
# Properties
propertycount = 0
propertylabelcount = 0
propertydescriptioncount = 0
# General
pagecount = 0
revisioncount = 0
processedpages = set()
processedrevisions = set()
#langsofitem
langsofitem = defaultdict(list)
# if there is no data directory, create one
if not os.path.exists('data') :
os.makedirs('data')
os.chdir('data')
# download the dumps directory file and figure out the date of the latest dump
log('Checking for the date of the last dump')
latestdump = '20121026'
for line in urllib.urlopen('http://dumps.wikimedia.org/wikidatawiki/') :
if not line.startswith('<tr><td class="n">') : continue
date = line[27:35]
if not re.match('\d\d\d\d\d\d\d\d', date) : continue
log("Checking dump of " + date)
# check if dump is finished
finished = False
for md5 in urllib.urlopen('http://dumps.wikimedia.org/wikidatawiki/' + date + '/wikidatawiki-' + date + '-md5sums.txt') :
if md5.endswith('-pages-meta-history.xml.bz2' + "\n") :
finished = True
if finished :
latestdump = date
log('Latest dump has been on ' + latestdump)
#latestdump = '20130417'
# download the latest stats if needed
if not os.path.exists('dump' + latestdump) :
os.makedirs('dump' + latestdump)
os.chdir('dump' + latestdump)
if not os.path.exists('site_stats.sql.gz') :
log('Downloading stats of the latest dump')
urllib.urlretrieve('http://dumps.wikimedia.org/wikidatawiki/' + latestdump + '/wikidatawiki-' + latestdump + '-site_stats.sql.gz', 'site_stats.sql.gz')
# download the latest dump if needed
if not os.path.exists('pages-meta-history.xml.bz2') :
log('Downloading latest dump')
urllib.urlretrieve('http://dumps.wikimedia.org/wikidatawiki/' + latestdump + '/wikidatawiki-' + latestdump + '-pages-meta-history.xml.bz2', 'pages-meta-history.xml.bz2')
# get the maxrevid of the latest dump
maxrevid = 0
for line in gzip.open('site_stats.sql.gz'):
if not line.startswith('INSERT INTO') : continue
stats = eval(line[32:-2])
maxrevid = int(stats[2])
log('maxrevid of the latest dump: ' + str(maxrevid))
os.chdir('..')
# check the dailies
dailies = []
for line in urllib.urlopen('http://dumps.wikimedia.org/other/incr/wikidatawiki/') :
if not line.startswith('<tr><td class="n">') : continue
date = line[27:35]
if not re.match('\d\d\d\d\d\d\d\d', date) : continue
dailies.append(date)
# download the dailies in reversed order until the daily maxrevid is smaller than our maxrevid
stopdaily = '20121026'
lastdaily = 0
for daily in reversed(dailies) :
log('Checking daily of ' + daily)
if not os.path.exists('daily' + daily) :
os.makedirs('daily' + daily)
os.chdir('daily' + daily)
if not os.path.exists('maxrevid.txt') :
urllib.urlretrieve('http://dumps.wikimedia.org/other/incr/wikidatawiki/' + daily + '/maxrevid.txt', 'maxrevid.txt')
dailymaxrevid = int(open('maxrevid.txt').read())
if dailymaxrevid < maxrevid :
log('Daily ' + daily + ' is within latest dump')
stopdaily = daily
os.chdir('..')
break
if not os.path.exists('pages-meta-hist-incr.xml.bz2') :
log('Downloading daily ' + daily)
if urllib.urlopen('http://dumps.wikimedia.org/other/incr/wikidatawiki/' + daily + '/status.txt').read() == 'done' :
urllib.urlretrieve('http://dumps.wikimedia.org/other/incr/wikidatawiki/' + daily + '/wikidatawiki-' + daily + '-pages-meta-hist-incr.xml.bz2', 'pages-meta-hist-incr.xml.bz2')
log('Done downloading daily ' + daily)
if lastdaily == 0 : lastdaily = daily
else :
log('Daily not done yet - download aborted')
os.chdir('..')
def processfile(file) :
global linecount
global charactercount
# Items
global itemcount
global itemswithclaims
global claimcount
global claimsperitem
global claimswithrefs
global refs
global itemswithrefs
global mostclaims
global labelcount
global descriptioncount
global sitelinkcount
global itemrevisioncount
global botrevisioncount
global titleofmostclaims
global langlabels
global langdescriptions
global langsitelinks
# Properties
global propertycount
global propertylabelcount
global propertydescriptioncount
# General
global revisioncount
#langsofitem
global langsofitem
# local variables
title = ''
item = False
property = False
newrev = False
newtitle = False
val = {}
revid = 0
for line in file :
linecount += 1
charactercount += len(line)
if linecount % 1000000 == 0 : log(str(linecount / 1000000))
# starts a new page
if line == ' <page>\n' :
title = ''
item = False
property = False
newrev = False
newtitle = False
val = {}
content = ''
revid = 0
if line == ' <revision>\n' :
revid = 0
# title
if line.startswith(' <title>') :
title = line[11:-9]
item = title.startswith('Q')
property = title.startswith('Property:P')
if title not in processedpages :
newtitle = True
processedpages.add(title)
if line.startswith(' <id>') :
revid = line[10:-6]
if revid not in processedrevisions :
newrev = True
processedrevisions.add(revid)
# finished a page
if line == ' </page>\n' :
if not newtitle : continue
if item:
content = content.replace('"', '"')
val = eval(content)
#langsofitem begin
try:
for langlink in val['links']:
langsofitem[title].append(langlink[:-4])
except KeyError:
print val
ri = raw_input()
#print langsofitem
#ri = raw_input
if line == ' </revision>\n' :
if not newrev : continue
revisioncount += 1
if item:
itemrevisioncount += 1
if line.startswith(' <username>') :
if not newrev : continue
username = line[18:-12]
if username in bots:
botrevisioncount += 1
if line.startswith(' <timestamp>') :
timestamp = line[17:-23]
# checks for anomalies
if line.startswith(' <text xml:space="preserve">') :
if item or property :
if not line.endswith('</text>\n') :
log(line)
else :
content = line[33:-8]
#if linecount >= 1000000 : break
kb = open('kb.txt', 'w')
kb.write('# ' + str(lastdaily) + "\n")
dic = dict()
for lang in langs:
dic[lang] = open('dict-' + lang + '.txt', 'w')
# process the dailies, starting with the newest
files = 0
for daily in reversed(dailies) :
if daily == stopdaily : break
log('Analysing daily ' + daily)
os.chdir('daily' + daily)
if not os.path.exists('pages-meta-hist-incr.xml.bz2') :
log('No data available')
os.chdir('..')
continue
file = bz2.BZ2File('pages-meta-hist-incr.xml.bz2')
processfile(file)
os.chdir('..')
# process the dump
log('Analysing dump ' + str(latestdump))
os.chdir('dump' + latestdump)
file = bz2.BZ2File('pages-meta-history.xml.bz2')
processfile(file)
os.chdir('..')
langsofitemfile = open('langsofitem.json', 'w')
json.dump(langsofitem, langsofitemfile, indent=4)
langsofitemfile.close()
kb.close()
for lang in langs:
dic[lang].close()
os.chdir('..')
# if there is no results directory, create one
if not os.path.exists('results') :
os.makedirs('results')
output = open('results/daily.html', 'w')
output.write('<!doctype html>' + "\n")
output.write('<html>' + "\n")
output.write(' <head>' + "\n")
output.write(' <meta charset="utf-8">' + "\n")
output.write(' <title>Analysis results</title>' + "\n")
output.write(' <link rel="stylesheet" href="analysis.css" />' + "\n")
output.write(' </head>' + "\n")
output.write(' <body>' + "\n")
output.write(' <h1>Analysis results on the Wikidata dump</h1>' + "\n")
output.write(' <p>' + "\n")
output.write(' As of: ' + str(lastdaily) + '<br>' + "\n")
output.write(' Pages: ' + str(len(processedpages)) + '<br>' + "\n")
output.write(' Items: ' + str(itemcount) + '<br>' + "\n")
output.write(' Items with claims: ' + str(itemswithclaims) + '<br>' + "\n")
output.write(' Claims: ' + str(claimcount) + '<br>' + "\n")
output.write(' Claims per item: ' + str(claimsperitem) + '<br>' + "\n")
output.write(' References: ' + str(refs) + '<br>' + "\n")
output.write(' Claims with references: ' + str(claimswithrefs) + '<br>' + "\n")
output.write(' Items with references: ' + str(itemswithrefs) + '<br>' + "\n")
output.write(' Item with most claims: ' + titleofmostclaims + '<br>' + "\n")
output.write(' Properties: ' + str(propertycount) + '<br>' + "\n")
output.write(' Links: ' + str(sitelinkcount) + '<br>' + "\n")
output.write(' Links per language: ' + str(langsitelinks) + '<br>' + "\n")
output.write(' Labels: ' + str(labelcount) + '<br>' + "\n")
output.write(' Labels per language: ' + str(langlabels) + '<br>' + "\n")
output.write(' Labels of properties: ' + str(propertylabelcount) + '<br>' + "\n")
output.write(' Descriptions: ' + str(descriptioncount) + '<br>' + "\n")
output.write(' Descriptions per language: ' + str(langdescriptions) + '<br>' + "\n")
output.write(' Descriptions of properties: ' + str(propertydescriptioncount) + '<br>' + "\n")
output.write(' Revisions: ' + str(revisioncount) + '<br>' + "\n")
output.write(' Item revisions: ' + str(itemrevisioncount) + '<br>' + "\n")
output.write(' Bot revisions: ' + str(botrevisioncount) + '<br>' + "\n")
output.write(' Lines: ' + str(linecount) + '<br>' + "\n")
output.write(' Characters: ' + str(charactercount) + '<br>' + "\n")
output.write(' Time: ' + str(time.time() - start_time) + ' seconds<br>' + "\n")
output.write(' </p>' + "\n")
output.write(' </body>' + "\n")
output.write('</html>' + "\n")
output.close()
log('Done.')