Spaces:
Sleeping

Video2Guide / app /pipeline /text_format.py
Claude
Audit-driven hardening: upload caps, registry quota, SSE timeout, OCR escape
7c2d809
Raw History Blame Contribute Delete
7.05 kB
"""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 <ul>/<ol> if they look like a list; else None.
Lines without a marker are treated as continuations of the previous item.
A block must start with a recognized marker to qualify as a list.
"""
items: list[tuple[str, str]] = []
has_bullet = False
has_ordered = False
for raw in lines:
stripped = raw.lstrip()
m_b = _BULLET_RE.match(stripped)
m_o = _ORDERED_RE.match(stripped)
m_l = _LETTERED_RE.match(stripped)
if m_b:
items.append(("unordered", m_b.group(2).strip()))
has_bullet = True
elif m_o:
items.append(("ordered", m_o.group(2).strip()))
has_ordered = True
elif m_l:
items.append(("ordered", m_l.group(2).strip()))
has_ordered = True
else:
if not items:
return None # block doesn't start with a marker → not a list
kind, content = items[-1]
items[-1] = (kind, f"{content} {stripped.strip()}")
if not items:
return None
tag = "ol" if (has_ordered and not has_bullet) else "ul"
body = "".join(f"<li>{escape(content)}</li>" for _, content in items)
return f"<{tag}>{body}</{tag}>"
def _render_block(lines: list[str]) -> str:
if len(lines) == 1 and _looks_like_equation(lines[0]):
latex = _normalize_to_latex(lines[0])
# Escape: a slide whose OCR survives _looks_like_equation can still
# contain '<' (less-than operator) which would otherwise inject HTML.
# MathJax processes the entity-decoded text, so escape is safe.
return f'<p class="ocr-equation">\\({escape(latex)}\\)</p>'
list_html = _try_render_list(lines)
if list_html is not None:
return list_html
parts = [escape(line) for line in lines]
return "<p>" + "<br>".join(parts) + "</p>"
def format_ocr_to_html(text: str | None) -> Markup:
"""Render OCR text as a chunk of safe HTML.
Returns an empty `Markup` if `text` is falsy. The returned `Markup` is
pre-escaped — Jinja will not double-escape it.
"""
if not text:
return Markup("")
blocks = _split_blocks(text)
if not blocks:
return Markup("")
return Markup("".join(_render_block(b) for b in blocks))
def ocr_has_math(text: str | None) -> bool:
"""True if any line in `text` looks like a math equation worth MathJax."""
if not text:
return False
return any(_looks_like_equation(line) for line in text.split("\n"))