Datasets:
Formats:
parquet
Size:
100K - 1M
Tags:
table-recognition
table-structure-recognition
document-image-analysis
ocr
document-understanding
teds
License:
File size: 7,609 Bytes
46f3199 | 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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | #!/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))
|