CheneyWong's picture
canonical OTSL ground truth: scripts/otsl_norm.py
46f3199 verified
Raw History Blame Contribute Delete
7.61 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""OTSL 归一化:把任意来源的表格标注统一成 **PaddleOCR-VL 1.6 的原生 OTSL 约定**。
为什么必须统一(2026-10-21 实测)
------------------------------
手上有三套互不兼容的 OTSL 约定:
| 来源 | rowspan 怎么写 | 行尾 | 词表 |
|---|---|---|---|
| 数据集自带(PubTables-1M/PubTabNet/tablet/ccocr/omnidocbench) | `<fcel><ulcel>NMES1` 同行塞标记,续接行直接少一格 | 补 `<ecel>` 到固定列数 | 含 `<ulcel>` |
| 我们自己的 html_to_otsl | `<fcel>` + `<ulcel>`*(rs-1) 拼在**同一行** | 不补 | 含 `<ulcel>` |
| **PaddleOCR-VL 1.6 原生** | 续接格是**独立的行**,内容为纯 `<ucel>` | 不补(ragged) | fcel/ecel/lcel/ucel/xcel/nl |
问题:
1. `<ulcel>` **不在 1.6 词表里**(模型吐不出来),而评测器 `canonical_teds.py` 的
`OTSL_KNOWN_FOREIGN` 也没收录它 → 被**当成单元格正文**吞掉
(`<fcel><ulcel><ulcel>characteristic` → 文本 "<ulcel><ulcel>characteristic")。
实测带 `<ulcel>` 的 GT 行占比:pubtables1m 37%、ccocr 33%、omnidocbench16 25%、
pubtabnet 23%、tablet 22%、omnidocbench15 20%、ocrbenchv2 17%。
2. 源约定"续接行少一格",而 1.6 解析器要求续接格占位 → 结构对不上。
3. 源约定每行补 `<ecel>`,模型输出是 ragged → 每行都被算成结构编辑
(这正是之前"加倍"口径的问题)。
本模块按 1.6 官方语义(paddlex `paddleocr_vl/uilts.py::otsl_parse_texts`)重建:
- 单元格起点: `<fcel>`(有文字) / `<ecel>`(无文字)
- colspan 续接: **同一行**右侧连续 `<lcel>`
- rowspan 续接: **下方行**同列连续 `<ucel>`
- 同时向上和向左合并: `<xcel>`
- 行尾不补空格(ragged),行内按列对齐(空槽 `<ecel>`)
- 文字: 去首尾空白 + 内部连续空白压成单空格
对外接口:
html_to_otsl(html) -> 规范 OTSL
otsl_stats(otsl) -> (行数, 槽位数, span 数) 便于对齐统计
has_foreign(otsl) -> 是否含 `<ulcel>` 等非法 token
"""
from __future__ import annotations
import re
from html.parser import HTMLParser
OTSL_NL = "<nl>"
OTSL_FCEL = "<fcel>"
OTSL_ECEL = "<ecel>"
OTSL_LCEL = "<lcel>"
OTSL_UCEL = "<ucel>"
OTSL_XCEL = "<xcel>"
_WS = re.compile(r"\s+")
_TOK = re.compile(r"(<fcel>|<ecel>|<lcel>|<ucel>|<xcel>|<nl>)")
_SPAN = ("<ucel>", "<lcel>", "<xcel>")
_FOREIGN = ("<ulcel>", "<ccel>", "<ched>", "<frow>", "<lrow>", "<ncol>",
"<ccol>", "<xrow>", "<xcol>", "<fc>", "<lc>", "<ec>", "<oc>")
def _norm_text(s: str) -> str:
return _WS.sub(" ", s or "").strip()
# ==========================================================================
# HTML -> 网格 -> 规范 OTSL
# ==========================================================================
class _TblParser(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.rows = []
self.cur = None
self.buf = None
self.attrs = None
self.depth = 0
def handle_starttag(self, tag, attrs):
if tag == "table":
self.depth += 1
return
if self.depth > 1:
return
if tag == "tr":
self.cur = []
elif tag in ("td", "th"):
if self.cur is None:
self.cur = []
a = dict(attrs)
def _i(k):
try:
return max(1, int(a.get(k, 1) or 1))
except Exception:
return 1
self.attrs = (_i("colspan"), _i("rowspan"))
self.buf = []
def handle_data(self, data):
if self.buf is not None:
self.buf.append(data)
def handle_endtag(self, tag):
if tag == "table":
self.depth = max(0, self.depth - 1)
return
if self.depth > 1:
return
if tag in ("td", "th") and self.buf is not None:
txt = _norm_text("".join(self.buf))
cs, rs = self.attrs or (1, 1)
self.cur.append((txt, cs, rs))
self.buf = None
self.attrs = None
elif tag == "tr" and self.cur is not None:
self.rows.append(self.cur)
self.cur = None
class _Cell:
__slots__ = ("text", "cs", "rs", "kind") # kind: origin|col|up|both
def __init__(self, text, cs, rs, kind):
self.text, self.cs, self.rs, self.kind = text, cs, rs, kind
def _build_grid(rows):
grid = []
for r, rcells in enumerate(rows):
while len(grid) <= r:
grid.append([])
row = grid[r]
c = 0
for (txt, cs, rs) in rcells:
while c < len(row) and row[c] is not None:
c += 1
while len(row) < c + cs:
row.append(None)
row[c] = _Cell(txt, cs, rs, "origin")
for dc in range(1, cs):
row[c + dc] = _Cell("", cs, rs, "col")
for dr in range(1, rs):
rr = r + dr
while len(grid) <= rr:
grid.append([])
rrow = grid[rr]
while len(rrow) < c + cs:
rrow.append(None)
rrow[c] = _Cell("", cs, rs, "up")
for dc in range(1, cs):
rrow[c + dc] = _Cell("", cs, rs, "both")
c += cs
return grid
def _grid_to_otsl(grid):
out = []
for row in grid:
last = len(row) - 1
while last >= 0 and row[last] is None:
last -= 1
if last < 0:
continue
parts = []
for c in range(last + 1):
cell = row[c]
if cell is None:
parts.append(OTSL_ECEL)
elif cell.kind == "origin":
parts.append(OTSL_FCEL + cell.text if cell.text else OTSL_ECEL)
elif cell.kind == "col":
parts.append(OTSL_LCEL)
elif cell.kind == "up":
parts.append(OTSL_UCEL)
else:
parts.append(OTSL_XCEL)
out.append("".join(parts))
return OTSL_NL.join(out)
def html_to_otsl(html: str) -> str:
"""HTML -> 规范 OTSL(1.6 约定)"""
if not html or "<table" not in html.lower():
return ""
p = _TblParser()
try:
p.feed(html)
p.close()
except Exception:
return ""
if not p.rows:
return ""
return _grid_to_otsl(_build_grid(p.rows))
# ==========================================================================
# 统计/体检
# ==========================================================================
def otsl_stats(otsl: str):
"""-> (行数, 槽位数, span token 数, 含非法 token 数)"""
if not otsl:
return (0, 0, 0, 0)
rows = [r for r in otsl.split(OTSL_NL) if r.strip()]
slots = 0
spans = 0
for r in rows:
toks = _TOK.findall(r)
slots += len(toks)
spans += sum(1 for t in toks if t in _SPAN)
foreign = sum(otsl.count(t) for t in _FOREIGN)
return (len(rows), slots, spans, foreign)
def has_foreign(otsl: str) -> bool:
return any(t in (otsl or "") for t in _FOREIGN)
if __name__ == "__main__":
demo = ("<table>"
"<tr><td rowspan=\"2\">A</td><td colspan=\"2\">B</td></tr>"
"<tr><td>C</td><td>D</td></tr>"
"<tr><td>E</td><td>F</td><td>G</td></tr>"
"</table>")
o = html_to_otsl(demo)
print(o)
for i, r in enumerate(o.split("<nl>")):
print(f" 行{i}: {r}")
print("stats:", otsl_stats(o))