-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathffnmeta.py
More file actions
executable file
·376 lines (319 loc) · 10.2 KB
/
ffnmeta.py
File metadata and controls
executable file
·376 lines (319 loc) · 10.2 KB
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/env python
import sys
import traceback
from typing import Set, Dict, Optional, Any
from bs4 import BeautifulSoup # type: ignore
import urllib.parse
from oil import oil
from weaver import RemoteWebScraper, WebQueue
import weaver.enc as enc
from minerva import FFNLanguage, FFNCategory, FFNGenre, FFNFandom, FFNCharacter
db = oil.open()
scraper = RemoteWebScraper(db)
#scraper.baseDelay = 30
scraper.requestTimeout = 300
scraper.mustyThreshold = 60 * 60 * 24 * 30 * 1
def stripAfter(s: str, needle: str) -> str:
idx = s.find(needle)
if idx < 0:
return s
return s[:idx]
baseUrl = 'https://www.fanfiction.net'
baseCrossoverUrl = 'https://www.fanfiction.net/crossovers'
def getCategories(scraper: RemoteWebScraper) -> Set[str]:
categoryBlacklist = ['support', 'cookies', 'privacy', 'tos',
'betareaders', 'forums', 'communities', 'j', '',
'u', 's', 'crossovers']
categories: Set[str] = set()
root = scraper.softScrape(baseUrl)
assert(root.url is not None)
dec = enc.decode(root.response, root.url)
assert(dec is not None)
html = dec[1]
soup = BeautifulSoup(html, 'html5lib')
#print(len(html))
for a in soup.findAll('a'):
href = urllib.parse.urljoin(baseUrl, a.get('href'))
href = stripAfter(href, '#')
href = stripAfter(href, '?')
if not href.startswith(baseUrl):
continue
end = href[len(baseUrl):]
if end.find('/') < 0:
continue
category = end.split('/')[1]
if category in categoryBlacklist:
continue
ffnCategory = FFNCategory.lookup(db, category, a.getText().strip())
#print(f"{category}: {ffnCategory.id} {ffnCategory.name}")
categories |= { category }
#print(category)
#print(f"{a.get('href')} {href}")
return categories
categories = getCategories(scraper)
#print(categories)
fandomNameMap: Dict[str, Optional[int]] = {}
fandomIdMap: Dict[int, str] = {}
fandomStubMap: Dict[str, str] = {}
for category in categories:
url = f"{baseUrl}/{category}/"
w = scraper.softScrape(url)
assert(w.url is not None)
dec = enc.decode(w.response, w.url)
assert(dec is not None)
html = dec[1]
soup = BeautifulSoup(html, 'html5lib')
for a in soup.findAll('a'):
href = urllib.parse.urljoin(w.url, a.get('href'))
href = stripAfter(href, '#')
href = stripAfter(href, '?')
if not href.startswith(url):
continue
if href == url:
continue
fandomName = stripAfter(href[len(url):], '/')
fandomName = urllib.parse.unquote(fandomName)
fandomName = f"{category}/{fandomName}"
if fandomName in fandomNameMap:
e = fandomNameMap[fandomName]
if e is not None:
raise Exception(f"conflicting fandom ids: {fandomName} {e}")
fandomNameMap[fandomName] = None
fandomStubMap[fandomName] = a.getText().strip()
curl = f"{baseUrl}/crossovers/{category}/"
cw = scraper.softScrape(curl)
assert(cw.url is not None)
dec = enc.decode(cw.response, cw.url)
assert(dec is not None)
html = dec[1]
soup = BeautifulSoup(html, 'html5lib')
for a in soup.findAll('a'):
#print(a.get('href'))
href = urllib.parse.urljoin(cw.url, a.get('href'))
#print(href)
href = stripAfter(href, '#')
href = stripAfter(href, '?')
if not href.startswith(baseCrossoverUrl + '/'):
continue
parts = href[len(baseCrossoverUrl):].split('/')
if len(parts) == 3 and parts[1] in categories:
continue # category base
if len(parts) != 4:
raise Exception(f"unknown crossover parts: {parts}")
fandomName = urllib.parse.unquote(parts[1])
fandomName = f"{category}/{fandomName}"
fandomId = int(parts[2])
if fandomName in fandomNameMap:
en = fandomNameMap[fandomName]
if en is not None and en != fandomId:
raise Exception(f"conflicting fandom ids: {fandomName} {fandomId} {en}")
fandomNameMap[fandomName] = fandomId
fandomStubMap[fandomName] = a.getText().strip()
if fandomId in fandomIdMap:
ei = fandomIdMap[fandomId]
if ei != fandomName:
raise Exception(f"conflicting fandom names: {fandomId} {fandomName} {ei}")
fandomIdMap[fandomId] = fandomName
def lookupAbbreviatedFandoms() -> None:
global fandomStubMap
ks = [k for k in dict.keys(fandomStubMap)]
ks.sort()
ks.reverse()
cnt=0
for k in ks:
if not fandomStubMap[k].endswith('...'):
continue
#print(f"{k}: {fandomStubMap[k]}")
purl = f"{baseUrl}/{k}"
#print(purl)
cnt+=1
w = scraper.softScrape(purl)
assert(w.url is not None)
dec = enc.decode(w.response, w.url)
assert(dec is not None)
html = dec[1]
soup = BeautifulSoup(html, 'html5lib')
title = soup.find('title').getText().strip()
sufs = [' | FanFiction', 'FanFiction Archive']
hasSuf = True
while hasSuf:
hasSuf = False
for suf in sufs:
if title.endswith(suf):
hasSuf = True
title = title[:-len(suf)].strip()
break
#print(f"{k} => {title}")
fandomStubMap[k] = title
#print(cnt)
#print(fandomNameMap)
#print(len(fandomNameMap))
#lookupAbbreviatedFandoms()
def toUrl(s: str) -> str:
s = s.replace(' ', '-')
s = s.replace('.', '-')
s = s.replace(',', '-')
s = s.replace('/', '-')
s = s.replace(':', '-')
s = s.replace('+', '-')
s = s.replace("'", '-')
s = s.replace("・", '-')
while s.find('--') >= 0:
s = s.replace('--', '-')
return s.strip('-')
#ks = [k for k in dict.keys(fandomStubMap)]
#ks.sort()
#ks.reverse()
#cnt=0
#for k in ks:
# ksub = k[k.find('/')+1:]
# if toUrl(fandomStubMap[k]) != ksub:
# print(f"{fandomStubMap[k]} => {ksub} != {toUrl(fandomStubMap[k])}")
nm: Dict[str, Any] = {}
ks = [k for k in dict.keys(fandomStubMap)]
ks.sort()
for k in ks:
nm[k] = { 'name': fandomStubMap[k] }
if k in fandomNameMap and fandomNameMap[k] is not None:
nm[k]['id'] = fandomNameMap[k]
#import json
#print(json.dumps(nm))
#sys.exit(0)
categoryMap = {}
for category in categories:
ffnCategory = FFNCategory.lookup(db, category)
categoryMap[category] = ffnCategory
print(categoryMap)
languageIdMap: Dict[int, FFNLanguage] = {}
genreIdMap: Dict[int, FFNGenre] = {}
characterIdMap: Dict[int, FFNCharacter] = {}
def extractLanguages(soup: Any, html: str, url: str) -> None:
global languageIdMap
try:
ls = soup.find('select', { 'name': 'languageid' })
for o in ls.findAll('option'):
rid = int(o.get('value'))
name = o.getText().strip()
if rid == 0:
continue
if rid < 0:
raise Exception(f"found negative language id: {rid}")
ffnLanguage = FFNLanguage.lookup(db, rid, name)
if rid not in languageIdMap:
print(f"language {rid} {name}")
languageIdMap[rid] = ffnLanguage
except:
print(f"{purl} failed to process languages")
fn = url.replace('/', '_').replace(':', '_')
with open(f"./tmp_language_{fn}.html", "w") as f:
f.write(html)
def saveGenres(soup: Any) -> None:
global genreIdMap
for o in soup.findAll('option'):
rid = int(o.get('value'))
name = o.getText().strip()
if rid == 0:
continue
if rid < 0:
raise Exception(f"found negative genre id: {rid}")
if rid not in genreIdMap:
print(f"genre {rid} {name}")
ffnGenre = FFNGenre.lookup(db, rid, name)
genreIdMap[rid] = ffnGenre
def extractGenres(soup: Any, html: str, url: str) -> None:
try:
saveGenres(soup.find('select', { 'name': 'genreid1' }))
saveGenres(soup.find('select', { 'name': 'genreid2' }))
saveGenres(soup.find('select', { 'name': '_genreid1' }))
except:
print(f"{purl} failed to process genres")
fn = url.replace('/', '_').replace(':', '_')
with open(f"./tmp_genre_{fn}.html", "w") as f:
f.write(html)
traceback.print_exc()
def saveCharacters(soup: Any, ffnFandom: FFNFandom) -> None:
if soup is None:
return
global characterIdMap
for o in soup.findAll('option'):
rid = int(o.get('value'))
name = o.getText().strip()
if rid == 0:
continue
if rid < 0:
raise Exception(f"found negative character id: {rid}")
if rid not in characterIdMap:
print(f"character {rid} {name}")
ffnCharacter = FFNCharacter.lookup(db, rid, name, ffnFandom.id)
characterIdMap[rid] = ffnCharacter
elif characterIdMap[rid].fandomId != ffnFandom.id:
print(f"character fandom mismatch {characterIdMap[rid].fandomId} {ffnFandom.id}")
def extractCharacters(soup: Any, html: str, url: str, ffnFandom: FFNFandom
) -> None:
try:
saveCharacters(soup.find('select', { 'name': 'characterid1' }), ffnFandom)
saveCharacters(soup.find('select', { 'name': 'characterid2' }), ffnFandom)
saveCharacters(soup.find('select', { 'name': 'characterid3' }), ffnFandom)
saveCharacters(soup.find('select', { 'name': 'characterid4' }), ffnFandom)
saveCharacters(soup.find('select', { 'name': '_characterid1' }), ffnFandom)
saveCharacters(soup.find('select', { 'name': '_characterid2' }), ffnFandom)
except:
print(f"{purl} failed to process characters")
fn = url.replace('/', '_').replace(':', '_')
with open(f"./tmp_characters_{fn}.html", "w") as f:
f.write(html)
traceback.print_exc()
def processSearchPage(ts: int, url: str, html: str, ffnFandom: FFNFandom
) -> None:
soup = BeautifulSoup(html, 'html5lib')
extractLanguages(soup, html, url)
extractGenres(soup, html, url)
extractCharacters(soup, html, url, ffnFandom)
ks = [k for k in dict.keys(fandomNameMap)]
ks.sort()
ks.reverse()
kt = 0
for k in ks:
name = None # unknown
remoteId = fandomNameMap[k]
category = k.split('/')[0]
stub = k[k.find('/')+1:]
ffnCategory = categoryMap[category]
print(f"{category} {ffnCategory.id} {stub} {remoteId}")
assert(ffnCategory.id is not None)
ffnFandom = FFNFandom.lookup(db, ffnCategory.id, stub, name, remoteId)
purl = f"{baseUrl}/{ffnCategory.stub}/{ffnFandom.stub}"
print(purl)
try:
scraper.softScrape(purl)
except:
pass
kt += 1
if kt > 10:
break
print(f"len(fandomNameMap): {len(fandomNameMap)}")
print(f"len(fandomIdMap): {len(fandomIdMap)}")
kt = 0
print("extracting languages")
for k in ks:
name = None # unknown
remoteId = fandomNameMap[k]
category = k.split('/')[0]
stub = k[k.find('/')+1:]
ffnCategory = categoryMap[category]
assert(ffnCategory.id is not None)
ffnFandom = FFNFandom.lookup(db, ffnCategory.id, stub, name, remoteId)
purl = f"{baseUrl}/{ffnCategory.stub}/{ffnFandom.stub}"
w = scraper.softScrape(purl)
assert(w.url is not None and w.created is not None)
dec = enc.decode(w.response, w.url)
assert(dec is not None)
html = dec[1]
try:
processSearchPage(w.created, w.url, html, ffnFandom)
except:
print(f"{purl} failed to process")
print(f"len(languageIdMap): {len(languageIdMap)}")
print(f"len(genreIdMap): {len(genreIdMap)}")
print(f"len(characterIdMap): {len(characterIdMap)}")
# TODO: these can be found on any "search" page