"""Format raw OCR output into structured HTML. The OCR pipeline emits a plain string with one slide-line per `\n`. Rendering that directly produces a wall of run-on text. This module turns it into: - paragraphs (groups of lines separated by blank lines) - bullet/numbered lists (auto-detected from line prefixes) - inline equations (heuristically detected lines wrapped in MathJax \\(...\\)) The equation detection is intentionally conservative — only lines that look clearly mathematical (short, contain =/Greek/operator chars, few alphabetic words) get wrapped. Misfires render as best-effort math; reviewers can fix them in the editor. """ from __future__ import annotations import re from html import escape from markupsafe import Markup __all__ = ["format_ocr_to_html", "ocr_has_math"] _BULLET_RE = re.compile(r"^([•●○◦‣▪▫■\-–—\*])\s+(.+)$") _ORDERED_RE = re.compile(r"^(\d{1,3})[.)]\s+(.+)$") _LETTERED_RE = re.compile(r"^([A-Za-z])[.)]\s+(.+)$") # Characters that strongly suggest a math expression. _MATH_OPERATOR_CHARS = set("=≤≥≠≈±") _MATH_SYMBOL_CHARS = set("∑∫∏√∂∇∞→⇒⇔↔∈∉⊂⊃∪∩") _GREEK_RE = re.compile(r"[Ͱ-Ͽ]") _SUPERSCRIPT_RE = re.compile(r"[²³¹⁰⁴-⁹]") _SUBSCRIPT_RE = re.compile(r"[₀-₉]") _SENTENCE_BREAK_RE = re.compile(r"[.!?]\s+[A-Z]") _WORD_RE = re.compile(r"[A-Za-z]{2,}") # Map of UTF-8 math chars → LaTeX commands used inside detected equation lines. _LATEX_REPLACEMENTS: list[tuple[str, str]] = [ ("×", r"\times "), ("÷", r"\div "), ("·", r"\cdot "), ("±", r"\pm "), ("≤", r"\leq "), ("≥", r"\geq "), ("≠", r"\neq "), ("≈", r"\approx "), ("∞", r"\infty "), ("∑", r"\sum "), ("∫", r"\int "), ("∏", r"\prod "), ("√", r"\sqrt "), ("∂", r"\partial "), ("∇", r"\nabla "), ("→", r"\to "), ("⇒", r"\Rightarrow "), ("⇔", r"\Leftrightarrow "), ("↔", r"\leftrightarrow "), ("∈", r"\in "), ("∉", r"\notin "), ("⊂", r"\subset "), ("⊃", r"\supset "), ("∪", r"\cup "), ("∩", r"\cap "), ] _GREEK_LOWER = "αβγδεζηθικλμνξοπρστυφχψω" _GREEK_LOWER_NAMES = [ "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi", "rho", "sigma", "tau", "upsilon", "phi", "chi", "psi", "omega", ] _GREEK_UPPER = "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ" for _ch, _name in zip(_GREEK_LOWER, _GREEK_LOWER_NAMES): _LATEX_REPLACEMENTS.append((_ch, f"\\{_name} ")) for _ch, _name in zip(_GREEK_UPPER, _GREEK_LOWER_NAMES): _LATEX_REPLACEMENTS.append((_ch, f"\\{_name.capitalize()} ")) _SUPERSCRIPT_MAP = { "²": "^2", "³": "^3", "¹": "^1", "⁰": "^0", "⁴": "^4", "⁵": "^5", "⁶": "^6", "⁷": "^7", "⁸": "^8", "⁹": "^9", } _SUBSCRIPT_MAP = { "₀": "_0", "₁": "_1", "₂": "_2", "₃": "_3", "₄": "_4", "₅": "_5", "₆": "_6", "₇": "_7", "₈": "_8", "₉": "_9", } def _looks_like_equation(line: str) -> bool: s = line.strip() if not s or len(s) > 80: return False has_op = any(c in _MATH_OPERATOR_CHARS for c in s) has_sym = any(c in _MATH_SYMBOL_CHARS for c in s) has_greek = bool(_GREEK_RE.search(s)) has_super = bool(_SUPERSCRIPT_RE.search(s)) has_sub = bool(_SUBSCRIPT_RE.search(s)) has_caret = "^" in s and bool(re.search(r"[A-Za-z0-9)\]]\^", s)) if not (has_op or has_sym or has_greek or has_super or has_sub or has_caret): return False if _SENTENCE_BREAK_RE.search(s): return False word_count = len(_WORD_RE.findall(s)) if word_count > 8: return False return True def _normalize_to_latex(line: str) -> str: s = line.strip() for ch, repl in _SUPERSCRIPT_MAP.items(): s = s.replace(ch, repl) for ch, repl in _SUBSCRIPT_MAP.items(): s = s.replace(ch, repl) for ch, repl in _LATEX_REPLACEMENTS: s = s.replace(ch, repl) s = re.sub(r"\s+", " ", s).strip() return s def _split_blocks(text: str) -> list[list[str]]: blocks: list[list[str]] = [] current: list[str] = [] for raw in text.split("\n"): if raw.strip(): current.append(raw.rstrip()) elif current: blocks.append(current) current = [] if current: blocks.append(current) return blocks def _try_render_list(lines: list[str]) -> str | None: """Render lines as a
\\({escape(latex)}\\)
' list_html = _try_render_list(lines) if list_html is not None: return list_html parts = [escape(line) for line in lines] return "" + "
".join(parts) + "