CheneyWong commited on
Commit
b0ca7b7
·
verified ·
1 Parent(s): d5b00e1

Upload scripts/fill_html.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/fill_html.py +111 -64
scripts/fill_html.py CHANGED
@@ -2,7 +2,18 @@
2
  """Fill missing `html` by converting each row's `otsl` (the reverse direction).
3
 
4
  OTSL and HTML are interconvertible. Sources that ship OTSL but no HTML
5
- (TabRecSet) get HTML generated here with a worker pool.
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  Usage: python3 fill_html.py <in.parquet> <out.parquet> [--workers N]
8
  """
@@ -13,51 +24,95 @@ import sys
13
  import pyarrow as pa
14
  import pyarrow.parquet as pq
15
 
16
- # OTSL -> HTML cell kind. PaddleOCR's tokens:
17
- # <fcel> new cell
18
- # <ecel> empty/blank cell
19
- # <lcel> cell merged with the one to its left (colspan)
20
- # <ulcel> cell merged with the one above (rowspan)
21
- # <xcel> merged both ways
22
- # <nl> end of row
23
- STRUCT = re.compile(r"<(fcel|ecel|lcel|ulcel|xcel|ucel|nl)>")
24
- TAG_RE = re.compile(r"<(/?)([a-zA-Z]+)[^>]*>")
25
-
26
-
27
- def _cell_html(tag, text):
28
- if tag in ("lcel",):
29
- return "" # continuation of the previous cell
30
- if tag == "ecel":
31
- return "<td></td>"
32
- if tag in ("ulcel", "ucel", "xcel"):
33
- return "<td></td>" # vertical continuation, rendered as a blank cell
34
- return f"<td>{text}</td>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
 
37
  def otsl_to_html(otsl):
38
- """Rebuild a minimal <table> from an OTSL token string."""
39
- if not otsl:
 
 
40
  return ""
41
- # split into rows, then into (token, text) pairs
42
- rows_html = []
43
- for row in STRUCT.split(otsl):
44
- if not row:
45
- continue
46
- parts = row.split(">")
47
- cells, buf = [], ""
48
- for p in parts:
49
- m = re.fullmatch(r"\s*(fcel|ecel|lcel|ulcel|xcel|ucel)\s*", p)
50
- if m:
51
- cells.append((m.group(1), buf))
52
- buf = ""
53
- else:
54
- buf += p
55
- out = "".join(_cell_html(t, tx) for t, tx in cells)
56
- if out:
57
- rows_html.append(f"<tr>{out}</tr>")
58
- if not rows_html:
59
- return ""
60
- return "<table>" + "".join(rows_html) + "</table>"
61
 
62
 
63
  def work(chunk):
@@ -70,33 +125,25 @@ def main():
70
 
71
  pf = pq.ParquetFile(src)
72
  schema = pf.schema_arrow
73
- out = pq.ParquetWriter(dst, schema, compression="zstd")
74
  total = filled = 0
75
-
76
  with mp.Pool(workers) as pool:
77
  for rg in range(pf.num_row_groups):
78
- tbl = pf.read_row_group(rg)
79
- htmls = tbl.column("html").to_pylist()
80
- otsls = tbl.column("otsl").to_pylist()
81
- todo = [i for i, h in enumerate(htmls) if not h and otsls[i]]
82
  if todo:
83
- chunks = [otsls[i] for i in todo]
84
- n = (len(chunks) + workers * 4 - 1) // (workers * 4)
85
- pieces = [chunks[k:k + n] for k in range(0, len(chunks), n)]
86
- done = 0
87
- for piece, res in zip(pieces, pool.map(work, pieces)):
88
- for i, s in zip(todo[done:done + len(piece)], res):
89
- htmls[i] = s
90
- done += len(piece)
91
- filled += done
92
  i = schema.get_field_index("html")
93
- tbl = tbl.set_column(i, schema.field("html"),
94
- pa.array(htmls, type=schema.field("html").type))
95
- out.write_table(tbl)
96
- total += tbl.num_rows
97
- print(f" {total} rows, filled {filled}", flush=True)
98
-
99
- out.close()
100
  print(f"done: {total} rows, {filled} html generated -> {dst}")
101
 
102
 
 
2
  """Fill missing `html` by converting each row's `otsl` (the reverse direction).
3
 
4
  OTSL and HTML are interconvertible. Sources that ship OTSL but no HTML
5
+ (TabRecSet) get HTML generated here.
6
+
7
+ Token grammar handled:
8
+ <fcel> new cell starts, text follows inline
9
+ <ecel> empty cell
10
+ <lcel> cell continues to the LEFT -> colspan += 1
11
+ <ulcel> cell continues ABOVE -> rowspan += 1
12
+ <xcel> continues both ways -> colspan += 1, rowspan += 1
13
+ <nl> end of row
14
+
15
+ Rows shorter than the widest row are padded with empty cells, matching the
16
+ square-grid convention PaddleOCR uses.
17
 
18
  Usage: python3 fill_html.py <in.parquet> <out.parquet> [--workers N]
19
  """
 
24
  import pyarrow as pa
25
  import pyarrow.parquet as pq
26
 
27
+ _TOK = re.compile(r"<(fcel|ecel|lcel|ulcel|xcel|nl)>")
28
+ _WS = re.compile(r"\s+")
29
+
30
+ _ESC = {"&": "&amp;", "<": "&lt;", ">": "&gt;"}
31
+
32
+
33
+ def _esc(t):
34
+ return "".join(_ESC.get(c, c) for c in t)
35
+
36
+
37
+ def parse_otsl(otsl):
38
+ """-> list of rows; each row is a list of (text, colspan, rowspan)."""
39
+ rows, cur = [], []
40
+ cell = None # [text, colspan, rowspan] of the cell being filled
41
+
42
+ def flush():
43
+ nonlocal cell
44
+ if cell is not None:
45
+ cur.append((cell[0].strip(), cell[1], cell[2]))
46
+ cell = None
47
+
48
+ pos = 0
49
+ for m in _TOK.finditer(otsl or ""):
50
+ text = otsl[pos:m.start()]
51
+ pos = m.end()
52
+ tag = m.group(1)
53
+ if cell is not None:
54
+ cell[0] += text
55
+ if tag == "fcel":
56
+ flush()
57
+ cell = ["", 1, 1]
58
+ elif tag == "ecel":
59
+ flush()
60
+ cur.append(("", 1, 1))
61
+ elif tag == "lcel":
62
+ # continuation extends the *current* cell if one is open,
63
+ # otherwise the last one already committed to this row
64
+ if cell is not None:
65
+ cell[1] += 1
66
+ elif cur:
67
+ t, cs, rs = cur[-1]
68
+ cur[-1] = (t, cs + 1, rs)
69
+ elif tag == "ulcel":
70
+ if cell is not None:
71
+ cell[2] += 1
72
+ elif cur:
73
+ t, cs, rs = cur[-1]
74
+ cur[-1] = (t, cs, rs + 1)
75
+ elif tag == "xcel":
76
+ if cell is not None:
77
+ cell[1] += 1
78
+ cell[2] += 1
79
+ elif cur:
80
+ t, cs, rs = cur[-1]
81
+ cur[-1] = (t, cs + 1, rs + 1)
82
+ elif tag == "nl":
83
+ flush()
84
+ rows.append(cur)
85
+ cur = []
86
+ flush()
87
+ if cur:
88
+ rows.append(cur)
89
+ return rows
90
 
91
 
92
  def otsl_to_html(otsl):
93
+ """Rebuild a <table> from an OTSL token string."""
94
+ rows = parse_otsl(otsl)
95
+ rows = [r for r in rows if r]
96
+ if not rows:
97
  return ""
98
+ width = max(sum(c[1] for c in r) for r in rows) or 1
99
+
100
+ body = []
101
+ for r in rows:
102
+ tds, used = [], 0
103
+ for text, cs, rs in r:
104
+ used += cs
105
+ attrs = ""
106
+ if cs > 1:
107
+ attrs += f' colspan="{cs}"'
108
+ if rs > 1:
109
+ attrs += f' rowspan="{rs}"'
110
+ tds.append(f"<td{attrs}>{_esc(text)}</td>")
111
+ while used < width: # pad short rows
112
+ tds.append("<td></td>")
113
+ used += 1
114
+ body.append("<tr>" + "".join(tds) + "</tr>")
115
+ return "<table>" + "".join(body) + "</table>"
 
 
116
 
117
 
118
  def work(chunk):
 
125
 
126
  pf = pq.ParquetFile(src)
127
  schema = pf.schema_arrow
128
+ writer = pq.ParquetWriter(dst, schema, compression="zstd")
129
  total = filled = 0
 
130
  with mp.Pool(workers) as pool:
131
  for rg in range(pf.num_row_groups):
132
+ t = pf.read_row_group(rg)
133
+ htmls = t.column("html").to_pylist()
134
+ otsls = t.column("otsl").to_pylist()
135
+ todo = [i for i in range(len(otsls)) if not htmls[i] and otsls[i]]
136
  if todo:
137
+ for i, s in zip(todo, pool.map(work, [otsls[i] for i in todo],
138
+ chunksize=64)):
139
+ htmls[i] = s
140
+ filled += len(todo)
 
 
 
 
 
141
  i = schema.get_field_index("html")
142
+ t = t.set_column(i, schema.field("html"),
143
+ pa.array(htmls, type=schema.field("html").type))
144
+ writer.write_table(t)
145
+ total += t.num_rows
146
+ writer.close()
 
 
147
  print(f"done: {total} rows, {filled} html generated -> {dst}")
148
 
149