Is it possible to use the "prepareQA" hook to get the text of the card without it's outer HTML?

I’m currently trying to change the text of the card in the reviewer if some conditions are true. My code searches for a term or expression in the card and, if it’s there, it proceeds to implement the changes. The problem is that sometimes the searched term coincides with some term in the HTML. I then thought, “what if I could get just the text of the card, without the HTML?”, but I have no idea if it’s possible.

I’d appreciate to get some advices on how to do that.

P.s. I’m also thinking about making this changes only if the answer side of the card is shown. I’ve tried to use if kind == "answer": to achieve this but it didn’t work at all. Does anyone know how to properly do that?
Heres an exemple of what I’m trying to do:

import re
from anki.hooks import addHook

def change(text, card, kind):
    names = ["Hello", "world", "tEST", "SUCCEED", "Fail"]
    for name in names:
        pattern = re.compile(rf"\b{name}\b", re.IGNORECASE)
        matches = pattern.finditer(text)
        for match in matches:
            underline = f'<u>{match.group()}</u>'
            text = text[:match.start()] + underline + text[match.end():]
    return text

addHook("prepareQA", change)

Thank you in advance!

kind can be “reviewQuestion”, “reviewAnswer”, “clayoutQuestion”, “clayoutAnswer”, “previewQuestion” or “previewAnswer”, so you have to test if the string ends with Answer.

You can try getting the plain text using BeautifulSoup. Here is an untested example:

from aqt import gui_hooks
from bs4 import BeautifulSoup

def on_card_will_show(html, card, kind):
    if not kind.endsWith('Answer'):
        return html
    soup = BeautifulSoup(html, 'html.parser')
    text = soup.text
    # TODO: test for your conditions
    return html

gui_hooks.card_will_show.append(on_card_will_show)
2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.