forked from javdejong/nhk-pronunciation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnhk_pronunciation.py
429 lines (328 loc) · 12.6 KB
/
nhk_pronunciation.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
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# -*- coding: utf-8 -*-
from collections import namedtuple
import re
import codecs
import os
import cPickle
import time
from aqt import mw
from aqt.qt import *
from aqt.utils import showText
import japanese
import japanese.lookup
# ************************************************
# User Options *
# ************************************************
# Style mappings (edit this if you want different colors etc.):
styles = {'class="overline"': 'style="text-decoration:overline;"',
'class="nopron"': 'style="color: royalblue;"',
'class="nasal"': 'style="color: red;"',
'ꜜ': 'ꜜ'}
# The note type(s) that the plugin will act on.
# Add your own note types here, for example: note_types = ["japanese", "subs"]
note_types = ["japanese", "kanji"]
# The field name(s) that the plugin will search for.
# Add your own fields here, for example:
# srcFields = ['Expression', 'Kanji']
# dstFields = ['Pronunciation', 'Pitch Accent']
srcFields = ['Expression', 'Kanji Word']
dstFields = ['Pronunciation']
# Regenerate readings even if they already exist?
regenerate_readings = False
# Use hiragana instead of katakana for readings?
pronunciation_hiragana = False
# ************************************************
# Global Variables *
# ************************************************
# Paths to the database files and this particular file
thisfile = os.path.join(mw.pm.addonFolder(), "nhk_pronunciation.py")
derivative_database = os.path.join(mw.pm.addonFolder(), "nhk_pronunciation.csv")
derivative_pickle = os.path.join(mw.pm.addonFolder(), "nhk_pronunciation.pickle")
accent_database = os.path.join(mw.pm.addonFolder(), "ACCDB_unicode.csv")
# "Class" declaration
AccentEntry = namedtuple('AccentEntry', ['NID','ID','WAVname','K_FLD','ACT','midashigo','nhk','kanjiexpr','NHKexpr','numberchars','nopronouncepos','nasalsoundpos','majiri','kaisi','KWAV','midashigo1','akusentosuu','bunshou','ac'])
# The main dict used to store all entries
thedict = {}
# ************************************************
# Helper functions *
# ************************************************
def katakana_to_hiragana(to_translate):
hiragana = u'がぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺぽ' \
u'あいうえおかきくけこさしすせそたちつてと' \
u'なにぬねのはひふへほまみむめもやゆよらりるれろ' \
u'わをんぁぃぅぇぉゃゅょっ'
katakana = u'ガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ' \
u'アイウエオカキクケコサシスセソタチツテト' \
u'ナニヌネノハヒフヘホマミムメモヤユヨラリルレロ' \
u'ワヲンァィゥェォャュョッ'
katakana = [ord(char) for char in katakana]
translate_table = dict(zip(katakana, hiragana))
return to_translate.translate(translate_table)
# ************************************************
# Database generation functions *
# ************************************************
def format_entry(e):
""" Format an entry from the data in the original database to something that uses html """
txt = e.midashigo1
strlen = len(txt)
acclen = len(e.ac)
accent = "0"*(strlen-acclen) + e.ac
# Get the nasal positions
nasal = []
if e.nasalsoundpos:
positions = e.nasalsoundpos.split('0')
for p in positions:
if p:
nasal.append(int(p))
if not p:
# e.g. "20" would result in ['2', '']
nasal[-1] = nasal[-1] * 10
# Get the no pronounce positions
nopron = []
if e.nopronouncepos:
positions = e.nopronouncepos.split('0')
for p in positions:
if p:
nopron.append(int(p))
if not p:
# e.g. "20" would result in ['2', '']
nopron[-1] = nopron[-1] * 10
outstr = ""
overline = False
for i in range(strlen):
a = int(accent[i])
# Start or end overline when necessary
if not overline and a > 0:
outstr = outstr + '<span class="overline">'
overline = True
if overline and a == 0:
outstr = outstr + '</span>'
overline = False
if (i+1) in nopron:
outstr = outstr + '<span class="nopron">'
# Add the character stuff
outstr = outstr + txt[i]
# Add the pronunciation stuff
if (i+1) in nopron:
outstr = outstr + "</span>"
if (i+1) in nasal:
outstr = outstr + '<span class="nasal">°</span>'
# If we go down in pitch, add the downfall
if a == 2:
outstr = outstr + '</span>ꜜ'
overline = False
# Close the overline if it's still open
if overline:
outstr = outstr + "</span>"
return outstr
def build_database():
""" Build the derived database from the original database """
tempdict = {}
entries = []
f = codecs.open(accent_database, 'r', 'utf8')
for line in f:
line = re.sub("\{(.*),(.*)\}", "\{\1;\2\}", line.strip())
line = re.sub("\((.*),(.*)\)", "\(\1;\2\) ", line.strip())
entries.append(AccentEntry._make(line.split(",")))
f.close()
for e in entries:
textentry = format_entry(e)
# A tuple holding both the spelling in katakana, and the katakana with pitch/accent markup
kanapron = (e.midashigo, textentry)
# Add expressions for both
for key in [e.nhk, e.kanjiexpr]:
if key in tempdict:
if kanapron not in tempdict[key]:
tempdict[key].append(kanapron)
else:
tempdict[key] = [kanapron]
o = codecs.open(derivative_database, 'w', 'utf8')
for key in tempdict.iterkeys():
for kana, pron in tempdict[key]:
o.write("%s\t%s\t%s\n" % (key, kana, pron))
o.close()
def read_derivative():
""" Read the derivative file to memory """
f = codecs.open(derivative_database, 'r', 'utf8')
for line in f:
key, kana, pron = line.strip().split("\t")
kanapron = (kana, pron)
if key in thedict:
if kanapron not in thedict[key]:
thedict[key].append(kanapron)
else:
thedict[key] = [kanapron]
f.close()
# ************************************************
# Lookup Functions *
# ************************************************
def inline_style(txt):
""" Map style classes to their inline version """
for key in styles.iterkeys():
txt = txt.replace(key, styles[key])
return txt
def getPronunciations(expr):
""" Search pronuncations for a particular expression """
ret = []
if expr in thedict:
for kana, pron in thedict[expr]:
inlinepron = inline_style(pron)
if pronunciation_hiragana:
inlinepron = katakana_to_hiragana(inlinepron)
if inlinepron not in ret:
ret.append(inlinepron)
return ret
def lookupPronunciation(expr):
""" Show the pronunciation when the user does a manual lookup """
ret = getPronunciations(expr)
thehtml = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<style>
body {
font-size: 30px;
}
</style>
<TITLE>Pronunciations</TITLE>
<meta charset="UTF-8" />
</HEAD>
<BODY>
%s
</BODY>
</HTML>
""" % ("<br/><br/>\n".join(ret))
showText(thehtml, type="html")
def onLookupPronunciation():
""" Do a lookup on the selection """
japanese.lookup.initLookup()
mw.lookup.selection(lookupPronunciation)
# ************************************************
# Interface *
# ************************************************
def createMenu():
""" Add a hotkey and menu entry """
if not getattr(mw.form, "menuLookup", None):
ml = QMenu()
ml.setTitle("Lookup")
mw.form.menuTools.addAction(ml.menuAction())
ml = mw.form.menuLookup
# add action
a = QAction(mw)
a.setText("...pronunciation")
a.setShortcut("Ctrl+6")
ml.addAction(a)
mw.connect(a, SIGNAL("triggered()"), onLookupPronunciation)
def setupBrowserMenu(browser):
""" Add menu entry to browser window """
a = QAction("Bulk-add Pronunciations", browser)
browser.connect(a, SIGNAL("triggered()"), lambda e=browser: onRegenerate(e))
browser.form.menuEdit.addSeparator()
browser.form.menuEdit.addAction(a)
def onRegenerate(browser):
regeneratePronunciations(browser.selectedNotes())
def get_src_dst_fields(fields):
""" Set source and destination fieldnames """
src = None
srcIdx = None
dst = None
dstIdx = None
for i, f in enumerate(srcFields):
if f in fields:
src = f
srcIdx = i
break
for i, f in enumerate(dstFields):
if f in fields:
dst = f
dstIdx = i
break
return src, srcIdx, dst, dstIdx
def add_pronunciation_once(fields, model, data, n):
""" When possible, temporarily set the pronunciation to a field """
# Check if this is a supported note type. If it is not, return.
if not any(nt.lower() in model['name'].lower() for nt in note_types):
return fields
src, srcIdx, dst, dstIdx = get_src_dst_fields(fields)
if src is None or dst is None:
return fields
# Only add the pronunciation if there's not already one in the pronunciation field
if not fields[dst]:
prons = getPronunciations(fields[src])
fields[dst] = " *** ".join(prons)
return fields
def add_pronunciation_focusLost(flag, n, fidx):
# Check if this is a supported note type. If it is not, return.
if not any(nt.lower() in n.model()['name'].lower() for nt in note_types):
return flag
from aqt import mw
fields = mw.col.models.fieldNames(n.model())
src, srcIdx, dst, dstIdx = get_src_dst_fields(fields)
if not src or not dst:
return flag
# dst field already filled?
if n[dst]:
return flag
# event coming from src field?
if fidx != srcIdx:
return flag
# grab source text
srcTxt = mw.col.media.strip(n[src])
if not srcTxt:
return flag
# update field
try:
prons = getPronunciations(srcTxt)
n[dst] = " *** ".join(prons)
except Exception, e:
raise
return True
def regeneratePronunciations(nids):
mw.checkpoint("Bulk-add Pronunciations")
mw.progress.start()
for nid in nids:
note = mw.col.getNote(nid)
# Check if this is a supported note type. If it is not, skip.
if not any(nt.lower() in note.model()['name'].lower() for nt in note_types):
continue
src, srcIdx, dst, dstIdx = get_src_dst_fields(note)
if src is None or dst is None:
continue
if note[dst] and not regenerate_readings:
# already contains data, skip
continue
srcTxt = mw.col.media.strip(note[src])
if not srcTxt.strip():
continue
prons = getPronunciations(srcTxt.strip())
note[dst] = " *** ".join(prons)
note.flush()
mw.progress.finish()
mw.reset()
# ************************************************
# Main *
# ************************************************
# First check that either the original database, or the derivative text file are present:
if not os.path.exists(derivative_database) and not os.path.exists(accent_database):
raise IOError("Could not locate the original base or the derivative database!")
# Generate the derivative database if it does not exist yet
if (os.path.exists(accent_database) and not os.path.exists(derivative_database)) or (os.path.exists(accent_database) and os.stat(thisfile).st_mtime > os.stat(derivative_database).st_mtime):
build_database()
# If a pickle exists of the derivative file, use that. Otherwise, read from the derivative file and generate a pickle.
if (os.path.exists(derivative_pickle) and
os.stat(derivative_pickle).st_mtime > os.stat(derivative_database).st_mtime):
f = open(derivative_pickle, 'rb')
thedict = cPickle.load(f)
f.close()
else:
read_derivative()
f = open(derivative_pickle, 'wb')
cPickle.dump(thedict, f, cPickle.HIGHEST_PROTOCOL)
f.close()
# Create the manual look-up menu entry
createMenu()
from anki.hooks import addHook
addHook("mungeFields", add_pronunciation_once)
addHook('editFocusLost', add_pronunciation_focusLost)
# Bulk add
addHook("browser.setupMenus", setupBrowserMenu)