-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcount_genres.py
298 lines (266 loc) · 9.79 KB
/
count_genres.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# copied from harvest_template.py which is due to:
# (C) 2013 Multichill, Amir
# (C) 2013 Pywikipediabot team
#
# Distributed under the terms of MIT License.
#
import re
import json
import pywikibot
from pywikibot import pagegenerators as pg
from pywikibot import textlib
import mwparserfromhell
from collections import defaultdict
en_wikipedia = pywikibot.Site('en', 'wikipedia')
wikidata = en_wikipedia.data_repository()
if not wikidata.logged_in(): wikidata.login()
if not en_wikipedia.logged_in(): en_wikipedia.login()
properties = {'isbn13':'P212',
'genre': 'P136'}
wplangs = {'en':'Q328',
'de':'Q48183',
'fr':'Q8447',
'it':'Q11920',
"es": "q8449",
"ja": "q177837",
"ru": "q206855",
"pl": "q1551807",
"sv": "q169514",
'imported_from': 'P143'}
wpsites = {'en': {'isbn': u'isbn',
'oclc': u'oclc',
'author': u'author',
'illustrator': u'illustrator',
'translator': u'translator',
'language': u'language',
'published': u'published',
'genre': u'genre',
'dewey': u'dewey'},
'it': {'isbn': None,
'oclc': None,
'author': u'autore',
'illustrator': None,
'translator': None,
'language': u'lingua',
'published': u'annoorig',
'genre': u'genere',
'dewey': None},
'fr': {'isbn': u'isbn',
'oclc': None,
'author': u'auteur',
'illustrator': u'dessinateur',
'translator': u'traducteur',
'language': u'langue',
'published': u'dateparution_orig',
'genre': u'genere',
'dewey': None},
'es': {'isbn': u'isbn',
'oclc': u'oclc',
'author': u'autor',
'illustrator': u'ilustrador',
'translator': u'traductor',
'language': u'idioma original',
'published': u'publicación original',
'genre': u'género',
'dewey': None},
'ja': {'isbn': None,
'oclc': None,
'author': u'author',
'illustrator': u'illustrator',
'translator': u'translator',
'language': u'language',
'published': u'published',
'genre': u'genre',
'dewey': None},
'pl': {'isbn': None,
'oclc': None,
'author': u'autor',
'illustrator': None,
'translator': u'tłumacz',
'language': u'język oryg wyd',
'published': u'data I wyd oryg',
'genre': u'tematyka',
'dewey': None},
'pt': {'isbn': u'isbn',
'oclc': None,
'author': u'autor',
'illustrator': u'ilustrador',
'translator': u'tradutor_br',
'language': u'idioma',
'published': u'lançamento',
'genre': u'gênero',
'dewey': None},
'sv': {'isbn': u'isbn',
'oclc': None,
'author': u'autor',
'illustrator': u'ilustrador',
'translator': u'tradutor_br',
'language': u'idioma',
'published': u'lançamento',
'genre': u'gênero',
'dewey': None},
'ru': {'isbn': u'isbn',
'oclc': None,
'author': u'Автор',
'illustrator': u'illustratör ',
'translator': u'Переводчик',
'language': u'Язык',
'published': u'Оригинал выпуска',
'genre': u'Жанр',
'dewey': None}
}
templateTitleDict = {'en': u'Infobox book',
'it': u'Libro',
'fr': u'Infobox Livre',
'es': u'Ficha de libro',
'ja': u'基礎情報 書籍',
'pl': u'Książka infobox',
'pt': u'Info/Livro',
'sv': u'Bokfakta',
'ru': u'Издание'}
templateNSDict = {'en': u'Template:',
'it': u'Template:',
'fr': u'Modèle:',
'es': u'Plantilla:',
'ja': u'Template:',
'pl': u'Szablon:',
'pt': u'Predefinição:',
'sv': u'Mall:',
'ru': u'Шаблон:'}
def makeGenerator(lang):
templateNS = templateNSDict[lang]
templateTitle = templateTitleDict[lang]
tsite = pywikibot.Site(lang, 'wikipedia')
templatePage = pywikibot.Page(tsite, templateNS+templateTitle)
generator = pg.ReferringPageGenerator(templatePage, followRedirects=False,
withTemplateInclusion=True,
onlyTemplateInclusion=True,
step=None, total=None, content=False)
return generator
class bookdata:
def __init__(self, wditem):
self.wditem = wditem
self.isbns = list()
self.xisbns = list()
self.ocns = list()
self.xocns = list()
self.deweys = list()
self.authors = list()
self.illustrators = list()
self.translators = list()
self.langs = list()
self.publishdate = list()
self.genres = list()
def dictify(self):
bookdict = dict()
for k, v in self.__dict__.iteritems():
try:
bookdict[k] = str(v)
except pywikibot.exceptions.NoPage:
bookdict[k] = 'pywikibot.exceptions.NoPage'
try:
bookdict['wditem'] = self.wditem.getID()
except pywikibot.exceptions.NoPage:
bookdict[k] = 'pywikibot.exceptions.NoPage'
return bookdict
def processLinks(param, wpsitelang):
itempagelist = list()
tsite = pywikibot.Site(wpsitelang, 'wikipedia')
for mwnode in param.value.filter():
if type(mwnode) == mwparserfromhell.nodes.wikilink.Wikilink:
try:
paramLinkRedir = pywikibot.Page(tsite, mwnode.title).isRedirectPage()
except:
paramLinkRedir = False
if paramLinkRedir:
redirpage = pywikibot.Page(tsite, mwnode.title).getRedirectTarget()
pagetitle = redirpage.title()
else:
pagetitle = mwnode.title
#hopefully here you can see im trying to add to the returnlist a Wikdata ItemPage associated with a mwparerfromhell wikilink
try:
appendpage = pywikibot.ItemPage.fromPage(pywikibot.Page(tsite, pagetitle))
itempagelist.append(appendpage)
except:
continue
existlist = list()
for itempage in itempagelist:
try:
itempage.getID()
existlist.append(itempage)
except pywikibot.exceptions.NoPage:
continue
return existlist
def processGenre(param, book, wpsitelang):
book.genres.extend(processLinks(param, wpsitelang))
def processPage(page, wpsitelang):
"""
Process a single page
"""
paramdict = wpsites[wpsitelang]
wditem = pywikibot.ItemPage.fromPage(page)
book = bookdata(wditem)
pywikibot.output('Processing %s' % page)
pagetext = page.get()
wikicode = mwparserfromhell.parse(pagetext)
for template in wikicode.filter_templates():
if template.name.startswith(templateTitleDict[wpsitelang]):
for param in template.params:
paramname = param.name.strip()
if paramname == paramdict['genre']:
processGenre(param, book, wpsitelang)
return book
def savecases():
casesJSON = open('cases.JSON', 'w')
json.dump(cases, casesJSON, indent=4)
casesJSON.close()
allbooksJSON = open('allbooks.json', 'w')
json.dump(allbooks, allbooksJSON, indent=4)
allbooksJSON.close()
def run(wpsitelang):
touched = 0
prevtouch = wpsitelang+'prevtouched'
generator = makeGenerator(wpsitelang)
for page in generator:
touched += 1
fake = False
'''
if fake:
page = pywikibot.Page(en_wikipedia, "Sophie's_World")
wpsitelang = 'en'
'''
if not fake:
if cases[prevtouch] >= touched:
continue
if page.namespace() == 0:
#make our book instance from wpdata
book = processPage(page, wpsitelang)
#save a copy to a json flat db for later statistics
allbooks[wpsitelang].append(book.dictify())
cases[prevtouch] = touched
savecases()
if __name__ == "__main__":
'''open our saves'''
try:
casesJSON = open('cases.JSON','r')
cases = defaultdict(int)
savedcases = json.load(casesJSON)
for k, v in savedcases.iteritems():
cases[k] = v
casesJSON.close()
except IOError:
cases = defaultdict(int)
for wpsitelang in wpsites.iterkeys():
cases[wpsitelang+'prevtouched'] = 0
try:
allbooksJSON = open('allbooks.JSON','r')
allbooks = json.load(allbooksJSON)
allbooksJSON.close()
except IOError:
allbooks = defaultdict(list)
for lang in wpsites.iterkeys():
print 'running now on language: ', lang
run(lang)
print 'done with language: ', lang