-
Notifications
You must be signed in to change notification settings - Fork 0
/
fandom.py
318 lines (261 loc) · 11.6 KB
/
fandom.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
# fandom.com operations related
import av
import time
import urllib
import config
import bs4
import requests
import urllib.parse
import common
def fetch_quest_entries_from_chapter_page(page_url: str) -> list[str]:
"""
This function takes a chapter page URL and returns a list of quest entries present in the chapter.
Params:
page_url (str): URL of the chapter page.
Returns:
list[str]: List of quest entries present in the chapter.
"""
collection = []
req = common.request_retry_wrapper(lambda: requests.get(page_url))
req.encoding = "utf-8"
document = bs4.BeautifulSoup(req.text, "html.parser")
# find all <li> tags with ::marker
# ol : list[bs4.element.Tag]
li : bs4.element.Tag
for ol in document.find_all("ol"):
for li in ol.find_all("li"):
label = li.find("a")
if label:
real_url = urllib.parse.urljoin(page_url, label.get("href"))
common.log(f"Found quest entry: {real_url}")
collection.append(real_url)
return collection
def fetch_quest_entries_from_tribe_quest_page(page_url: str) -> list[str]:
"""
This function takes a tribe quest page URL and returns a list of quest entries present in the tribe quest.
Params:
page_url (str): URL of the tribe quest page.
Returns:
list[str]: List of quest entries present in the tribe quest.
"""
collection = []
req = common.request_retry_wrapper(lambda: requests.get(page_url))
req.encoding = "utf-8"
document = bs4.BeautifulSoup(req.text, "html.parser")
# find all <ul> tags
li : bs4.element.Tag
# start from div class="mw-parser-output"
div = document.find('div', {'class':'mw-parser-output'})
if div is None:
common.log(f"unexpected fandom page: {page_url}")
return collection
for ul in div.find_all("ul"):
for li in ul.find_all("li"):
label = li.find("a")
if label and li.text.strip().startswith("Act"):
real_url = urllib.parse.urljoin(page_url, label.get("href"))
collection.append(real_url)
common.log(collection)
return collection
def fetch_quest_entries(input: str):
common.log(f"Fetching quest entries from {input}")
if input.startswith('tribe:'):
# tribe quest, get url after :
url = input[6:]
common.log(f"Fetching quest entries from tribe quest page: {url}")
return fetch_quest_entries_from_tribe_quest_page(url)
else:
# chapter, get url
return fetch_quest_entries_from_chapter_page(input)
def fetch_target_vo_from_quest_page(page_url: str, target_va: list[str]) -> dict[str, list[tuple[str, str]]]:
"""
This function takes a quest page URL and returns the target VO of the quest.
Params:
page_url (str): URL of the quest page.
Returns:
dict[str, list[tuple[str, str]]]: Dictionary containing the VO of each target VA of the quest.
"""
collection = {}
req: requests.Response = common.request_retry_wrapper(lambda: requests.get(page_url))
req.encoding = "utf-8"
document = bs4.BeautifulSoup(req.text, "html.parser")
dialogueParts = document.find_all('div', {'class': 'dialogue'})
common.log(f"Found {len(dialogueParts)} dialogue parts for {page_url}")
if dialogueParts is None:
common.log(f"unexpected dialogue part: {page_url}")
return collection
else:
common.log(f"Found dialogue part for {page_url}")
for dialoguePart in dialogueParts:
ddLabels = dialoguePart.find_all(name='dd')
for i in ddLabels:
bLabel = i.find('b')
if bLabel is None:
# useless dialogue, skip
continue
char = bLabel.text[0:-1]
if char in target_va:
if i.find('span') is None:
common.log(f"No vocal file found for character: {char} in text: {i.text}")
continue
src = i.find('span').find('a').attrs['href']
common.log(f"Found character {char} vocal file: {src}")
# remove other texts
text = i.get_text()
text = text[text.find(f'{char}: ') + len(f'{char}: '):]
for i in config.necessary_replacements:
common.log(f"Replacing {i} with {config.necessary_replacements[i]} in text: {text}")
text = text.replace(i, config.necessary_replacements[i])
if collection.get(char) is None:
collection[char] = []
collection[char].append((text, src))
# workaround for hsr wiki
# find all span with Play
playableVoiceLines = dialoguePart.find_all("span", {"title": "Play"})
for i in playableVoiceLines:
i.parent #dd label
char = i.parent.find('b').text[0:-1]
text = i.parent.get_text()
text = text[text.find(f'{char}: ') + len(f'{char}: '):]
for i in config.necessary_replacements:
common.log(f"Replacing {i} with {config.necessary_replacements[i]} in text: {text}")
text = text.replace(i, config.necessary_replacements[i])
aLabel = i.find('a')
if aLabel is None:
common.log(f"No vocal file found for character: {char} in text: {i.text}")
continue
src = aLabel.attrs['href']
if char in target_va:
common.log(f"Found character {char} subtitle: {text}")
if collection.get(char) is None:
collection[char] = []
collection[char].append((text, src))
return collection
def merge_voice_collections(collections: list[dict[str, list[tuple[str, str]]]]) -> dict[str, list[tuple[str, str]]]:
"""
This function takes a list of collections and merge them into a single collection.
Params:
collections (list[dict[str, list[tuple[str, str]]]]): List of collections.
Returns:
dict[str, list[tuple[str, str]]]: Merged collection.
"""
merged = {}
for collection in collections:
for char, vo_list in collection.items():
if merged.get(char) is None:
merged[char] = []
merged[char].extend(vo_list)
return merged
def fetch_target_subtitles(page_url: str, target_va: list[str]) -> dict[str, list[str]]:
"""
This function takes a chapter page URL and returns the target VO of the chapter.
Params:
page_url (str): URL of the chapter page.
Returns:
dict[str, list[tuple[str, str]]]: Dictionary containing the VO of each target VA of the chapter.
"""
collection = {}
req = common.request_retry_wrapper(lambda: requests.get(page_url))
req.encoding = "utf-8"
document = bs4.BeautifulSoup(req.text, "html.parser")
dialogueParts = document.find_all('div', {'class': 'dialogue'})
common.log(f"Found {len(dialogueParts)} dialogue parts for target VA {target_va} in {page_url}")
if dialogueParts is None:
common.log(f"unexpected dialogue part: {page_url}")
return collection
for dialoguePart in dialogueParts:
ddLabels = dialoguePart.find_all(name='dd')
for i in ddLabels:
bLabel = i.find('b')
if bLabel is None:
# useless dialogue, skip
continue
char = bLabel.text[0:-1]
if char in target_va:
if i.find('span') is None:
common.log(f"No subtitle found for character: {char} in text: {i.text}, trying fallback method")
if i.text.strip().startswith(f'{char}: '):
text = i.text.strip()[len(f'{char}: '):]
common.log(f"Found character {char} subtitle: {text}")
if collection.get(char) is None:
collection[char] = []
collection[char].append(text)
else:
common.log(f"No subtitle found for character: {char} in text: {i.text}")
continue
# get text after `char:`
text = i.text
text = text[text.find(f'{char}: ') + len(f'{char}: '):]
common.log(f"Found character {char} subtitle: {text}")
if collection.get(char) is None:
collection[char] = []
collection[char].append(text)
return collection
def merge_subtitle_collections(collections: list[dict[str, list[str]]]):
"""
This function takes a list of collections and merge them into a single collection.
Params:
collections (list[dict[str, list[str]]]): List of collections.
Returns:
dict[str, list[str]]: Merged collection.
"""
merged = {}
for collection in collections:
for char, sub_list in collection.items():
if merged.get(char) is None:
merged[char] = []
merged[char].extend(sub_list)
return merged
def find_potentially_missing_voice_over_chars(page_url: str, target_va: list[str]) -> list[str]:
"""
Params:
page_url (str): URL of the chapter page.
Returns:
"""
import threading
result = []
threads = []
req = common.request_retry_wrapper(lambda: requests.get(page_url))
req.encoding = "utf-8"
document = bs4.BeautifulSoup(req.text, "html.parser")
dialogueParts = document.find_all('div', {'class': 'dialogue'})
if dialogueParts is None:
common.log(f"unexpected dialogue part: {page_url}")
return []
for dialoguePart in dialogueParts:
ddLabels = dialoguePart.find_all(name='dd')
for i in ddLabels:
bLabel = i.find('b')
if bLabel is None:
# useless dialogue, skip
continue
char = bLabel.text[0:-1]
# print(f"Checking character {char}", i.text.strip())
if char not in target_va and f"{char}:" in i.text.strip() and char not in config.ignored_characters and '&' not in char:
if i.find('span') is None:
common.log(f"Possible missing character {char} voiceline: {i.text}")
result.append(char)
else:
# check if voice is usable
x = i.find('span')
if x.find('a') is None:
common.log(f"Possible missing character {char} voiceline: {i.text}")
result.append(char)
else:
def func():
try:
src = x.find('a').attrs['href']
audio = av.open(src)
if audio.duration < 1:
common.log(f"Possible missing character {char} voiceline: {i.text}")
audio.close()
result.append(char)
except:
common.log(f"Failed to load {src} for character {char}")
result.append(char)
threads.append(threading.Thread(target=func))
for t in threads:
t.start()
for t in threads:
t.join()
return [i for i in set(result)]