r""" cms_text.py — CMS question HTML -> READABLE plain text for AI prompts. The old path (BeautifulSoup.get_text) destroyed the math: CMS stores equations as MathML, and get_text jams every symbol together ("x2y" for x²/y), silently drops images, and collapses tables. The AI then classifies a half-readable question. This module walks the HTML properly: * MathML -> compact LaTeX-style text inside $...$ (mfrac -> \frac{a}{b}, msup -> a^{b}, msqrt -> \sqrt{...}, mtable rows kept, ...) * / HTML -> ^{...} / _{...} * /
-> [figure] placeholder, so the AI KNOWS an image exists that it cannot see (instead of the question silently looking broken) * -> one line per row, cells joined with " | " * block tags -> line breaks; whitespace normalised Used by ai_assist.fetch_contents (LO Classifier + AI Tagging prompts). """ from __future__ import annotations import re from bs4 import BeautifulSoup, NavigableString, Tag # MathML elements whose children are joined with nothing (row-like containers). _MML_ROWS = {"math", "mrow", "mstyle", "semantics", "mpadded", "mphantom", "menclose"} _BLOCK_TAGS = {"p", "div", "br", "li", "ul", "ol", "h1", "h2", "h3", "h4", "tr"} def _mml(node) -> str: """One MathML node -> LaTeX-ish text.""" if isinstance(node, NavigableString): return str(node).strip() if not isinstance(node, Tag): return "" name = node.name.lower() if node.name else "" kids = [c for c in node.children if isinstance(c, Tag) or (isinstance(c, NavigableString) and str(c).strip())] def k(i): return _mml(kids[i]) if i < len(kids) else "" if name in ("mi", "mn", "mo", "mtext", "ms"): return node.get_text().strip() if name == "mfrac": return "\\frac{%s}{%s}" % (k(0), k(1)) if name == "msup": return "%s^{%s}" % (k(0), k(1)) if name == "msub": return "%s_{%s}" % (k(0), k(1)) if name == "msubsup": return "%s_{%s}^{%s}" % (k(0), k(1), k(2)) if name == "msqrt": return "\\sqrt{%s}" % "".join(_mml(c) for c in kids) if name == "mroot": return "\\sqrt[%s]{%s}" % (k(1), k(0)) if name in ("mover", "munder"): acc = k(1) if acc in ("→", "⃗"): # vector arrow return "\\vec{%s}" % k(0) if acc == "¯": # bar return "\\bar{%s}" % k(0) return "%s%s{%s}" % ("\\overset" if name == "mover" else "\\underset", "{%s}" % acc, k(0)) if name == "munderover": # sums / integrals with limits return "%s_{%s}^{%s}" % (k(0), k(1), k(2)) if name == "mfenced": op = node.get("open", "(") cl = node.get("close", ")") sep = node.get("separators", ",") or "," return op + (sep[0] + " ").join(_mml(c) for c in kids) + cl if name == "mtable": return " ; ".join(_mml(c) for c in kids) if name == "mtr": return " | ".join(_mml(c) for c in kids) if name in ("mtd", "mlabeledtr"): return "".join(_mml(c) for c in kids) if name == "mspace": return " " if name in _MML_ROWS or True: # any other container: join kids return "".join(_mml(c) for c in kids) def _walk(node, out): """Accumulate readable text pieces from an HTML tree into `out`.""" if isinstance(node, NavigableString): out.append(str(node)) return if not isinstance(node, Tag): return name = (node.name or "").lower() if name == "math": latex = re.sub(r"\s+", " ", _mml(node)).strip() if latex: out.append(f" ${latex}$ ") return if name == "img": out.append(" [figure] ") return if name == "figure": # CKEditor (the CMS editor) wraps TABLES in
, not # just images. Emitting the marker and returning threw the table away — # so a "match the following" question, whose List I / List II grid IS # the question, came back as nothing but "[figure]" and every downstream # tool reported it as image-based. Recurse instead: a nested still # emits the marker itself, and a nested
renders as rows. Only a # figure holding neither (an embed / media block) collapses to a marker. if node.find(("img", "table")) is None: out.append(" [figure] ") return # fall through to the normal child walk if name in ("script", "style"): return if name == "sup": out.append("^{" + node.get_text(strip=True) + "}") return if name == "sub": out.append("_{" + node.get_text(strip=True) + "}") return if name == "table": for tr in node.find_all("tr"): cells = [html_to_readable_inline(str(td)) for td in tr.find_all(("td", "th"))] out.append("\n" + " | ".join(c for c in cells) + "\n") return if name in _BLOCK_TAGS: out.append("\n") for c in node.children: _walk(c, out) if name in _BLOCK_TAGS: out.append("\n") def html_to_readable(html) -> str: """CMS HTML -> readable one-question text (math kept, [figure] marked).""" if not html: return "" s = str(html) if "<" not in s: return re.sub(r"\s+", " ", s).strip() soup = BeautifulSoup(s, "lxml") out = [] _walk(soup.body or soup, out) text = "".join(out) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r" ?\n ?", "\n", text) text = re.sub(r"\n{2,}", "\n", text).strip() # collapse repeated figure placeholders (figure wrapping was emitted once each) text = re.sub(r"(\[figure\] *){2,}", "[figure] ", text) return text def html_to_readable_inline(html) -> str: """Same, but single-line (for table cells / options).""" return re.sub(r"\s*\n\s*", " ", html_to_readable(html)).strip() # ── question-type-aware option / answer rendering ───────────────────────────── # Matrix-match questions store answer_options as ONE INNER LIST PER COLUMN # (Column-I items, Column-II items, ...), and correct_answer as a nested 1-based # index mapping like [[2],[2],[1],[3]]. Passage questions carry their real # sub-questions in question.child_questions. These helpers give every consumer # (ai_assist, ai_tagger/fetch_questions, ...) one correct rendering. _ROMAN = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII"] def _col_labels(fmt, n): """Label sequence for a matrix column ('capital_alpha' -> A B C ...).""" fmt = str(fmt or "").lower() count = max(int(n or 0), 26) if "roman" in fmt: labs = list(_ROMAN) + [str(i + 1) for i in range(len(_ROMAN), count)] elif "num" in fmt: labs = [str(i + 1) for i in range(count)] else: # capital_alpha / small_alpha / unknown labs = [chr(65 + i) if i < 26 else str(i + 1) for i in range(count)] if "small" in fmt: labs = [str(l).lower() for l in labs] return labs def matrix_option_lines(q, render=None): """None unless `q['answer_options']` is matrix-style (a list per column); otherwise readable lines like 'Column I: (A) ... (B) ...'.""" render = render or html_to_readable_inline q = q or {} opts = q.get("answer_options") or [] if not (len(opts) >= 2 and all(isinstance(o, (list, tuple)) for o in opts)): return None fmt_keys = ("matrix_column1_label_format", "matrix_column2_label_format", "matrix_column3_label_format") defaults = ("capital_alpha", "capital_roman", "capital_alpha") lines = [] for ci, col in enumerate(opts): fmt = (q.get(fmt_keys[ci]) if ci < len(fmt_keys) else None) \ or (defaults[ci] if ci < len(defaults) else "capital_alpha") labs = _col_labels(fmt, len(col)) items = " ".join(f"({labs[i]}) {render(x)}" for i, x in enumerate(col)) col_name = _ROMAN[ci] if ci < len(_ROMAN) else str(ci + 1) lines.append(f"Column {col_name}: {items}") return lines def correct_to_readable(q): """Readable correct answer for any question dict: 'A, C' for flagged MCQ options, 'A-II; B-II; C-I; D-III' for matrix mappings, plain values else.""" q = q or {} opts = q.get("answer_options") or [] if opts and all(isinstance(o, dict) for o in opts): letters = [chr(65 + i) for i, o in enumerate(opts) if o.get("is_correct") or o.get("isCorrect") or o.get("correct") or o.get("isAnswer")] if letters: return ", ".join(letters) ca = q.get("correct_answer") if not ca: return "" if isinstance(ca, list) and ca and all(isinstance(x, (list, tuple)) for x in ca): labs1 = _col_labels(q.get("matrix_column1_label_format") or "capital_alpha", len(ca)) labs2 = _col_labels(q.get("matrix_column2_label_format") or "capital_roman", 0) pairs = [] for i, targets in enumerate(ca): rendered = [] for t in targets: try: ti = int(t) rendered.append(labs2[ti - 1] if 1 <= ti <= len(labs2) else str(t)) except (TypeError, ValueError): rendered.append(str(t)) pairs.append(f"{labs1[i]}-{','.join(rendered) or '?'}") return "; ".join(pairs) if isinstance(ca, list): return ", ".join(str(x) for x in ca) return str(ca)