forked from EstravenX/anki2sm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Formatters.py
214 lines (165 loc) · 5.65 KB
/
Formatters.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
import re
from gettext import gettext
from html.entities import name2codepoint
import mustache
reComment = re.compile("(?s)<!--.*?-->")
reStyle = re.compile("(?si)<style.*?>.*?</style>")
reScript = re.compile("(?si)<script.*?>.*?</script>")
reTag = re.compile("(?s)<.*?>")
reEnts = re.compile(r"&#?\w+;")
reMedia = re.compile("(?i)<img[^>]+src=[\"']?([^\"'>]+)[\"']?[^>]*>")
reSound = re.compile(r"\[sound:[^]]+\]")
def entsToTxt(html: str) -> str:
# entitydefs defines nbsp as \xa0 instead of a standard space, so we
# replace it first
html = html.replace(" ", " ")
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return chr(int(text[3:-1], 16))
else:
return chr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = chr(name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return reEnts.sub(fixup, html)
def stripHTML(s: str) -> str:
s = reComment.sub("", s)
s = reStyle.sub("", s)
s = reScript.sub("", s)
s = reTag.sub("", s)
s = entsToTxt(s)
return s
def _removeFormattingFromMathjax(txt, ordi) -> str:
creg = clozeReg.replace("(?si)", "")
in_mathjax = False
def replace(match):
nonlocal in_mathjax
if match.group("mathjax_open"):
if in_mathjax:
print("MathJax opening found while already in MathJax")
in_mathjax = True
elif match.group("mathjax_close"):
if not in_mathjax:
print("MathJax close found while not in MathJax")
in_mathjax = False
elif match.group("cloze"):
if in_mathjax:
return match.group(0).replace("{{c{}::".format(ordi), "{{C{}::".format(ordi))
else:
print("Unexpected: no expected capture group is present")
return match.group(0)
return re.sub(r"(?si)(?P<mathjax_open>\\[([])|(?P<mathjax_close>\\[\])])|(?P<cloze>" + (creg % ordi) + ")", replace,
txt)
FURIGANA = re.compile(r" ?([^ >]+?)\[(.+?)\]")
clozeReg = r"(?si)\{\{(?P<tag>c)%s::(?P<content>.*?)(::(?P<hint>.*?))?\}\}"
CLOZE_REGEX_MATCH_GROUP_TAG = "tag"
CLOZE_REGEX_MATCH_GROUP_CONTENT = "content"
CLOZE_REGEX_MATCH_GROUP_HINT = "hint"
def _clozeText(txt: str, ordi: str, type: str) -> str:
"""Process the given Cloze deletion within the given template."""
reg = clozeReg
currentRegex = clozeReg % ordi
if not re.search(currentRegex, txt):
# No Cloze deletion was found in txt.
return ""
txt = _removeFormattingFromMathjax(txt, str(ordi))
def repl(m):
if type == "q":
if m.group(CLOZE_REGEX_MATCH_GROUP_HINT):
buf = "[%s]" % m.group(CLOZE_REGEX_MATCH_GROUP_HINT)
else:
buf = "[...]"
else:
buf = m.group(CLOZE_REGEX_MATCH_GROUP_CONTENT)
# uppercase = no formatting
if m.group(CLOZE_REGEX_MATCH_GROUP_TAG) == "c":
buf = "<span class=cloze>%s</span>" % buf
return buf
if type == 'q':
txt = re.sub(currentRegex, repl, txt)
# and display other clozes normally
return re.sub(reg % r"\d+", "\\2", txt)
else:
txt = re.search(currentRegex, txt)
if txt:
return repl(txt)
# filter args is a regex argument to the cloze {{c%s}}
def _cloze_filter(field_text: str, filter_args: str, q_or_a: str):
return _clozeText(field_text, filter_args, q_or_a)
def cloze_q_filter(field_text: str, filter_args: str, *args):
return _cloze_filter(field_text, filter_args, "q")
def cloze_a_filter(field_text: str, filter_args: str, *args):
return _cloze_filter(field_text, filter_args, "a")
def text_filter(txt: str, *args) -> str:
return stripHTML(txt)
def hint_filter(txt: str, args, context, tag: str, fullname) -> str:
if not txt.strip():
return ""
domid = "hint%d" % id(txt)
return """<a class=hint href="#"onclick="this.style.display='none';document.getElementById('%s').style.display='block';return false;">
%s</a><div id="%s" class=hint style="display: none">%s</div>
""" % (
domid,
gettext("Show %s") % tag,
domid, txt,
)
def captured_sound(groups: re.Match):
return groups.group(2).startswith("sound")
def kana_filter(txt: str) -> str:
def replace(match: re.Match) -> str:
if captured_sound(match):
return match.group(0)
else:
return match.group(2)
return FURIGANA.sub(replace, txt.replace(" ", " "))
def kanji_filter(txt: str) -> str:
def replace(match: re.Match) -> str:
if captured_sound(match):
return match.group(0)
else:
return match.group(1)
return FURIGANA.sub(replace, txt.replace(" ", " "))
def furigana_filter(txt: str) -> str:
def replace(match: re.Match) -> str:
if captured_sound(match):
return match.group(0)
else:
return "<ruby><rb>{}</rb><rt>{}</rt></ruby>"\
.format(match.group(1),
match.group(2))
return FURIGANA.sub(replace, txt.replace(" ", " "))
# #EXPANDS THE CLOSES INTO Hint and the actual Text
# given expand_clozes("{{c1::a}} {{c2::b}} {{c3::c}} {{c4::d}}")
# output ['[...] b cd', 'a [...] cd', 'a b [...]d', 'a b c [...]', 'a b c d']
# first second third forth fifth .... continues in order
def expand_clozes(string: str):
ords = set(re.findall(r"{{c(\d+)::.+?}}", string))
strings = []
def qrepl(m):
if m.group(CLOZE_REGEX_MATCH_GROUP_HINT):
return "[%s]" % m.group(CLOZE_REGEX_MATCH_GROUP_HINT)
else:
return "[...]"
def arepl(m):
return m.group(CLOZE_REGEX_MATCH_GROUP_CONTENT)
for ord in ords:
s = re.sub(clozeReg % ord, qrepl, string)
s = re.sub(clozeReg % ".+?", arepl, s)
strings.append(s)
strings.append(re.sub(clozeReg % ".+?", arepl, string))
return strings
mustache.filters["hint"] = hint_filter
mustache.filters["Text"] = text_filter
mustache.filters["furigana"] = furigana_filter
mustache.filters["kanji"] = kanji_filter
mustache.filters["kana"] = kana_filter