Skip to content

Commit af6d627

Browse files
chel-ouscott2000
authored andcommitted
Use newly created hooks to avoid monkey patching for Anki 25.03+
1 parent c5c91dc commit af6d627

File tree

1 file changed

+47
-14
lines changed

1 file changed

+47
-14
lines changed

answerset/__init__.py

Lines changed: 47 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,53 @@ def correct(
5858
except:
5959
pass
6060

61-
# Anki 2.1.56+ (correction was moved to Rust backend)
61+
62+
def compare_answer_html(config: Config, correct: str, given: str) -> str:
63+
"""Remove HTML tags and AV tags before comparing"""
64+
# Strip AV tags if possible
65+
try:
66+
import aqt
67+
68+
correct = aqt.mw.col.media.strip_av_tags(correct)
69+
except:
70+
pass
71+
72+
try:
73+
from anki.utils import html_to_text_line
74+
75+
correct = html_to_text_line(correct)
76+
except:
77+
pass
78+
79+
return compare_answer_no_html(config, correct, given)
80+
81+
82+
# Anki 25.03+ (hooks were created in Anki to avoid monkey patching)
6283
try:
63-
import aqt
84+
from aqt.gui_hooks import ( # type: ignore
85+
reviewer_will_compare_answer,
86+
reviewer_will_render_compared_answer,
87+
)
88+
89+
def deactivate_default_rendering(
90+
expected_provided_tuple: tuple[str, str], type_pattern: str,
91+
) -> tuple[str, str]:
92+
return "", ""
93+
94+
reviewer_will_compare_answer.append(deactivate_default_rendering)
95+
96+
def render_compare_answer(
97+
output: str, initial_expected: str, initial_provided: str, type_pattern: str,
98+
) -> str:
99+
return new_css + compare_answer_html(
100+
user_config, initial_expected, initial_provided,
101+
)
102+
103+
reviewer_will_render_compared_answer.append(render_compare_answer)
104+
105+
# Anki 2.1.56+ (correction was moved to Rust backend)
106+
except ImportError:
64107
from anki.collection import Collection
65-
from anki.utils import html_to_text_line
66108

67109
# TODO: handle "combining" argument
68110
def compare_answer(
@@ -72,18 +114,9 @@ def compare_answer(
72114
*args: Any,
73115
**kwargs: Any,
74116
) -> str:
75-
# Strip AV tags if possible
76-
try:
77-
if aqt.mw:
78-
expected = aqt.mw.col.media.strip_av_tags(expected)
79-
except:
80-
pass
81-
82-
# Strip HTML tags
83-
expected = html_to_text_line(expected)
84-
85-
return new_css + compare_answer_no_html(user_config, expected, provided)
117+
return new_css + compare_answer_html(user_config, expected, provided)
86118

87119
Collection.compare_answer = compare_answer # type: ignore
120+
88121
except:
89122
pass

0 commit comments

Comments
 (0)