1
# -*- coding: utf-8 -*-
2
# Copyright: Damien Elmes <anki@ichi2.net>
3
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
6
from anki.utils import findTag, stripHTML
7
from anki.hooks import addHook
10
cantoneseTag = "Cantonese"
11
mandarinTag = "Mandarin"
12
srcField = "Expression"
15
class UnihanController(object):
17
def __init__(self, target):
18
base = os.path.dirname(os.path.abspath(__file__))
19
if not os.path.exists(base):
20
if sys.platform.startswith("darwin"):
21
base = os.path.dirname(sys.argv[0])
23
base = os.path.join(os.path.dirname(sys.argv[0]),
25
self.engine = create_engine("sqlite:///" + os.path.abspath(
26
os.path.join(base, "unihan.db")),
27
echo=False, strategy='threadlocal')
28
self.session = sessionmaker(bind=self.engine,
33
def reading(self, text):
34
text = stripHTML(text)
36
s = SessionHelper(self.session())
39
ret = s.scalar("select %s from unihan where id = :id"
42
result.append(self.formatMatch(ret))
43
return u" ".join(result)
45
def formatMatch(self, match):
49
return "{%s}" % (",".join(m))
52
##########################################################################
54
class ChineseGenerator(object):
59
def toReading(self, type, val):
62
self.unihan = UnihanController(type)
64
self.unihan.type = type
65
return self.unihan.reading(val)
69
unihan = ChineseGenerator()
71
def onFocusLost(fact, field):
72
if field.name != srcField:
74
if findTag(cantoneseTag, fact.model.tags):
76
elif findTag(mandarinTag, fact.model.tags):
85
fact[dstField] = unihan.toReading(type, field.value)
87
addHook('fact.focusLost', onFocusLost)