Files
DeepTutor/deeptutor/utils/text_display.py
Leveling d889815577 fix(mastery): resolve formatted choice answers by exact option body (#3129)
Fixes #2863.

Exact normalized option-body matching for resolve_answer (whitespace / Markdown / LaTeX wrappers), without normalized substring false positives. Preserves literal operators and unresolved ambiguity.

Co-authored-by: Chih-Kai-Wang <290806361+Chih-Kai-Wang@users.noreply.github.com>
2026-12-01 16:51:36 +08:00

62 lines
2.2 KiB
Python

"""Helpers for normalizing learner-facing text."""
from __future__ import annotations
import json
import re
# Match dense JSON-style ``\\uXXXX`` runs (3+ escapes), mirroring the web
# markdown decoder so mastery / ask_user cards do not leak literal escapes (#973).
_ESCAPED_UNICODE_RUN = re.compile(r"(?:\\u[0-9a-fA-F]{4}){3,}")
# Match paired delimiters and leave literal operators such as 2**3 intact.
_FORMATTING_WRAPPERS = (
re.compile(
r"(?<![\\*A-Za-z0-9])(\*\*|__)(?=\S)(?:(?!\1).)+?(?<=\S)(\1)(?![*A-Za-z0-9])",
re.DOTALL,
),
re.compile(r"(?<![\\\x60])(\x60+)[^\x60]+(\1)(?!\x60)"),
re.compile(r"(?<![\\$])(\${1,2})[^$]+(\1)(?![$0-9])"),
re.compile(r"(?<!\\)(\\\()(?:(?!\\[()]).)+?(\\\))", re.DOTALL),
re.compile(r"(?<!\\)(\\\[)(?:(?!\\[\[\]]).)+?(\\\])", re.DOTALL),
)
def inline_formatting_markers(text: str) -> dict[int, int]:
"""Map inline wrapper starts to end offsets while keeping wrapped text."""
markers = {}
for pattern in _FORMATTING_WRAPPERS:
for match in pattern.finditer(text):
for start, end in match.regs[1:]:
markers[start] = end
return markers
def decode_escaped_unicode_for_display(text: str) -> str:
"""Decode dense ``\\uXXXX`` runs when they clearly represent non-ASCII text."""
if not text or "\\u" not in text:
return text
def _replace(match: re.Match[str]) -> str:
run = match.group(0)
# Decode the run as a JSON string, like the web decoder's JSON.parse:
# characters outside the BMP (emoji, math letters) arrive as UTF-16
# surrogate pairs that must be joined into one code point.
# ``unicode_escape`` keeps the two halves as lone surrogates, which
# UTF-8 cannot encode.
try:
decoded = json.loads(f'"{run}"')
except ValueError:
return run
if any(0xD800 <= ord(ch) <= 0xDFFF for ch in decoded):
# An unpaired surrogate is not text; keep the escapes visible.
return run
if any(ord(ch) > 0x7F for ch in decoded):
return decoded
return run
return _ESCAPED_UNICODE_RUN.sub(_replace, text)
__all__ = ["decode_escaped_unicode_for_display", "inline_formatting_markers"]