File size: 7,681 Bytes
22e0325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# 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: ``<fcel>`` (cell with content), ``<ecel>`` (empty cell),
  ``<lcel>`` (merged with the cell to the left), ``<ucel>`` (merged with the cell above), ``<xcel>`` (merged both
  ways), ``<nl>`` (end of row); the text of a cell follows its token. :func:`otsl_to_html` turns it into an HTML
  ``<table>`` 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 = ("<fcel>", "<ecel>", "<lcel>", "<ucel>", "<xcel>", "<nl>")
_OTSL_RE = re.compile(r"(<fcel>|<ecel>|<lcel>|<ucel>|<xcel>|<nl>)")
_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 <nl> 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 == "<nl>":
                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 -> ``<table>`` HTML (cells escaped; merged cells as colspan / rowspan)."""
    rows = otsl_grid(text)
    if not rows:
        return "<table></table>"
    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 = ["<table>"]
    for r in range(nrow):
        out.append("<tr>")
        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"<td>{html.escape(txt)}</td>")
                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"<td{attrs}>{html.escape(' '.join(parts))}</td>")
        out.append("</tr>")
    out.append("</table>")
    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 {}