# SPDX-License-Identifier: Apache-2.0 """Task-specific views of the model output (pure Python, no third-party import). The model's text itself is always returned unchanged; these are conveniences built from it. * ``table``: the model writes an OTSL-like cell sequence: ```` (cell with content), ```` (empty cell), ```` (merged with the cell to the left), ```` (merged with the cell above), ```` (merged both ways), ```` (end of row); the text of a cell follows its token. :func:`otsl_to_html` turns it into an HTML ```` with ``colspan`` / ``rowspan`` (clean-room implementation of the OTSL grid rules). * ``spotting`` (1.5 / 1.6): text lines with ``<|LOC_n|>`` tokens, n in 0..1000 = coordinates normalized to the image the model saw; :func:`parse_spotting` pairs every text run with its run of coordinates (4 values = a box, 8 = a quadrilateral, any even count = a polygon) and scales them to the original image. * ``formula``: the LaTeX without the ``\\[ \\]`` / ``$$`` display delimiters (:func:`strip_latex`). * ``chart``: rows of a ``|``-separated table when the output is one (:func:`parse_pipe_table`). """ from __future__ import annotations import html import re from typing import Any, Dict, List, Optional, Tuple OTSL_TOKENS = ("", "", "", "", "", "") _OTSL_RE = re.compile(r"(|||||)") _LOC_RE = re.compile(r"<\|LOC_(\d+)\|>") _LOC_SPLIT = re.compile(r"((?:<\|LOC_\d+\|>)+)") def is_otsl(text: str) -> bool: return any(t in text for t in OTSL_TOKENS) def otsl_grid(text: str) -> List[List[Tuple[str, str]]]: """[[(kind, text), ...] per row]; kind in fcel / ecel / lcel / ucel / xcel. Text before the first cell token is dropped; a trailing row without is kept.""" rows: List[List[Tuple[str, str]]] = [] row: List[Tuple[str, str]] = [] kind: Optional[str] = None buf = "" for part in _OTSL_RE.split(text): if part in OTSL_TOKENS: if kind is not None: row.append((kind, buf.strip())) buf = "" if part == "": kind = None rows.append(row) row = [] else: kind = part[1:-1] else: buf += part if kind is not None: row.append((kind, buf.strip())) if row: rows.append(row) return rows def otsl_to_html(text: str) -> str: """OTSL cell sequence -> ``
`` HTML (cells escaped; merged cells as colspan / rowspan).""" rows = otsl_grid(text) if not rows: return "
" ncol = max(len(r) for r in rows) grid = [r + [("ecel", "")] * (ncol - len(r)) for r in rows] nrow = len(grid) covered = [[False] * ncol for _ in range(nrow)] out = [""] for r in range(nrow): out.append("") for c in range(ncol): kind, txt = grid[r][c] if covered[r][c]: continue if kind in ("lcel", "ucel", "xcel"): # an orphan merge marker (nothing to merge into): render as a plain cell out.append(f"") continue cs = 1 while c + cs < ncol and grid[r][c + cs][0] == "lcel": cs += 1 rs = 1 while r + rs < nrow and grid[r + rs][c][0] in ("ucel", "xcel"): rs += 1 parts = [txt] if txt else [] for rr in range(r, r + rs): for cc in range(c, c + cs): if (rr, cc) != (r, c): covered[rr][cc] = True if grid[rr][cc][1]: parts.append(grid[rr][cc][1]) attrs = (f' colspan="{cs}"' if cs > 1 else "") + (f' rowspan="{rs}"' if rs > 1 else "") out.append(f"{html.escape(' '.join(parts))}") out.append("") out.append("
{html.escape(txt)}
") return "".join(out) def parse_spotting(text: str, width: Optional[int] = None, height: Optional[int] = None) -> List[Dict[str, Any]]: """Text runs paired with their ``<|LOC_n|>`` runs. Location runs may precede or follow the text (decided by the first run of the output); every item: ``text``, ``norm`` (points in 0..1000), and with ``width`` / ``height`` (the original image), ``points`` in pixels and the bounding ``box`` [x0, y0, x1, y1].""" parts = [p for p in _LOC_SPLIT.split(text) if p != ""] if not parts: return [] loc_first = bool(_LOC_RE.match(parts[0])) items: List[Dict[str, Any]] = [] pend_text: Optional[str] = None pend_loc: Optional[List[int]] = None for p in parts: if _LOC_RE.match(p) and _LOC_RE.sub("", p) == "": vals = [int(v) for v in _LOC_RE.findall(p)] if loc_first: if pend_loc is not None: items.append(_item("", pend_loc, width, height)) pend_loc = vals else: items.append(_item(pend_text or "", vals, width, height)) pend_text = None else: if loc_first: items.append(_item(p, pend_loc or [], width, height)) pend_loc = None else: if pend_text is not None and pend_text.strip(): items.append(_item(pend_text, [], width, height)) pend_text = p if pend_loc is not None: items.append(_item("", pend_loc, width, height)) if pend_text is not None and pend_text.strip(): items.append(_item(pend_text, [], width, height)) return items def _item(text: str, vals: List[int], width: Optional[int], height: Optional[int]) -> Dict[str, Any]: pts = [[vals[i], vals[i + 1]] for i in range(0, len(vals) - 1, 2)] d: Dict[str, Any] = {"text": text.strip(), "norm": pts} if len(vals) % 2: d["extra"] = vals[-1:] if pts and width and height: px = [[round(x * width / 1000.0, 1), round(y * height / 1000.0, 1)] for x, y in pts] d["points"] = px xs, ys = [p[0] for p in px], [p[1] for p in px] d["box"] = [min(xs), min(ys), max(xs), max(ys)] return d def strip_latex(text: str) -> str: s = text.strip() for a, b in (("\\[", "\\]"), ("$$", "$$"), ("\\(", "\\)"), ("$", "$")): if s.startswith(a) and s.endswith(b) and len(s) >= len(a) + len(b): return s[len(a):len(s) - len(b)].strip() return s def parse_pipe_table(text: str) -> Optional[List[List[str]]]: lines = [ln.strip() for ln in text.strip().splitlines() if ln.strip()] if len(lines) < 2 or not all("|" in ln for ln in lines): return None rows = [] for ln in lines: cells = [c.strip() for c in ln.strip("|").split("|")] if all(re.fullmatch(r":?-{2,}:?", c) for c in cells if c): continue # markdown separator row rows.append(cells) return rows or None def structured(task: str, text: str, width: Optional[int] = None, height: Optional[int] = None) -> Dict[str, Any]: """The task's structured view of ``text`` (empty dict for plain-text tasks).""" if task == "table" or (task == "custom" and is_otsl(text)): return {"otsl": text, "html": otsl_to_html(text), "rows": [[c[1] for c in r] for r in otsl_grid(text)]} if task == "spotting": return {"items": parse_spotting(text, width, height)} if task == "formula": return {"latex": strip_latex(text)} if task == "chart": rows = parse_pipe_table(text) return {"rows": rows} if rows else {} return {}