You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

table_structure_recognizer.py 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. import logging
  14. import os
  15. import re
  16. from collections import Counter
  17. import numpy as np
  18. from huggingface_hub import snapshot_download
  19. from api.utils.file_utils import get_project_base_directory
  20. from rag.nlp import rag_tokenizer
  21. from .recognizer import Recognizer
  22. class TableStructureRecognizer(Recognizer):
  23. labels = [
  24. "table",
  25. "table column",
  26. "table row",
  27. "table column header",
  28. "table projected row header",
  29. "table spanning cell",
  30. ]
  31. def __init__(self):
  32. try:
  33. super().__init__(self.labels, "tsr", os.path.join(
  34. get_project_base_directory(),
  35. "rag/res/deepdoc"))
  36. except Exception:
  37. super().__init__(self.labels, "tsr", snapshot_download(repo_id="InfiniFlow/deepdoc",
  38. local_dir=os.path.join(get_project_base_directory(), "rag/res/deepdoc"),
  39. local_dir_use_symlinks=False))
  40. def __call__(self, images, thr=0.2):
  41. tbls = super().__call__(images, thr)
  42. res = []
  43. # align left&right for rows, align top&bottom for columns
  44. for tbl in tbls:
  45. lts = [{"label": b["type"],
  46. "score": b["score"],
  47. "x0": b["bbox"][0], "x1": b["bbox"][2],
  48. "top": b["bbox"][1], "bottom": b["bbox"][-1]
  49. } for b in tbl]
  50. if not lts:
  51. continue
  52. left = [b["x0"] for b in lts if b["label"].find(
  53. "row") > 0 or b["label"].find("header") > 0]
  54. right = [b["x1"] for b in lts if b["label"].find(
  55. "row") > 0 or b["label"].find("header") > 0]
  56. if not left:
  57. continue
  58. left = np.mean(left) if len(left) > 4 else np.min(left)
  59. right = np.mean(right) if len(right) > 4 else np.max(right)
  60. for b in lts:
  61. if b["label"].find("row") > 0 or b["label"].find("header") > 0:
  62. if b["x0"] > left:
  63. b["x0"] = left
  64. if b["x1"] < right:
  65. b["x1"] = right
  66. top = [b["top"] for b in lts if b["label"] == "table column"]
  67. bottom = [b["bottom"] for b in lts if b["label"] == "table column"]
  68. if not top:
  69. res.append(lts)
  70. continue
  71. top = np.median(top) if len(top) > 4 else np.min(top)
  72. bottom = np.median(bottom) if len(bottom) > 4 else np.max(bottom)
  73. for b in lts:
  74. if b["label"] == "table column":
  75. if b["top"] > top:
  76. b["top"] = top
  77. if b["bottom"] < bottom:
  78. b["bottom"] = bottom
  79. res.append(lts)
  80. return res
  81. @staticmethod
  82. def is_caption(bx):
  83. patt = [
  84. r"[图表]+[ 0-9::]{2,}"
  85. ]
  86. if any([re.match(p, bx["text"].strip()) for p in patt]) \
  87. or bx["layout_type"].find("caption") >= 0:
  88. return True
  89. return False
  90. @staticmethod
  91. def blockType(b):
  92. patt = [
  93. ("^(20|19)[0-9]{2}[年/-][0-9]{1,2}[月/-][0-9]{1,2}日*$", "Dt"),
  94. (r"^(20|19)[0-9]{2}年$", "Dt"),
  95. (r"^(20|19)[0-9]{2}[年-][0-9]{1,2}月*$", "Dt"),
  96. ("^[0-9]{1,2}[月-][0-9]{1,2}日*$", "Dt"),
  97. (r"^第*[一二三四1-4]季度$", "Dt"),
  98. (r"^(20|19)[0-9]{2}年*[一二三四1-4]季度$", "Dt"),
  99. (r"^(20|19)[0-9]{2}[ABCDE]$", "Dt"),
  100. ("^[0-9.,+%/ -]+$", "Nu"),
  101. (r"^[0-9A-Z/\._~-]+$", "Ca"),
  102. (r"^[A-Z]*[a-z' -]+$", "En"),
  103. (r"^[0-9.,+-]+[0-9A-Za-z/$¥%<>()()' -]+$", "NE"),
  104. (r"^.{1}$", "Sg")
  105. ]
  106. for p, n in patt:
  107. if re.search(p, b["text"].strip()):
  108. return n
  109. tks = [t for t in rag_tokenizer.tokenize(b["text"]).split() if len(t) > 1]
  110. if len(tks) > 3:
  111. if len(tks) < 12:
  112. return "Tx"
  113. else:
  114. return "Lx"
  115. if len(tks) == 1 and rag_tokenizer.tag(tks[0]) == "nr":
  116. return "Nr"
  117. return "Ot"
  118. @staticmethod
  119. def construct_table(boxes, is_english=False, html=False):
  120. cap = ""
  121. i = 0
  122. while i < len(boxes):
  123. if TableStructureRecognizer.is_caption(boxes[i]):
  124. if is_english:
  125. cap + " "
  126. cap += boxes[i]["text"]
  127. boxes.pop(i)
  128. i -= 1
  129. i += 1
  130. if not boxes:
  131. return []
  132. for b in boxes:
  133. b["btype"] = TableStructureRecognizer.blockType(b)
  134. max_type = Counter([b["btype"] for b in boxes]).items()
  135. max_type = max(max_type, key=lambda x: x[1])[0] if max_type else ""
  136. logging.debug("MAXTYPE: " + max_type)
  137. rowh = [b["R_bott"] - b["R_top"] for b in boxes if "R" in b]
  138. rowh = np.min(rowh) if rowh else 0
  139. boxes = Recognizer.sort_R_firstly(boxes, rowh / 2)
  140. #for b in boxes:print(b)
  141. boxes[0]["rn"] = 0
  142. rows = [[boxes[0]]]
  143. btm = boxes[0]["bottom"]
  144. for b in boxes[1:]:
  145. b["rn"] = len(rows) - 1
  146. lst_r = rows[-1]
  147. if lst_r[-1].get("R", "") != b.get("R", "") \
  148. or (b["top"] >= btm - 3 and lst_r[-1].get("R", "-1") != b.get("R", "-2")
  149. ): # new row
  150. btm = b["bottom"]
  151. b["rn"] += 1
  152. rows.append([b])
  153. continue
  154. btm = (btm + b["bottom"]) / 2.
  155. rows[-1].append(b)
  156. colwm = [b["C_right"] - b["C_left"] for b in boxes if "C" in b]
  157. colwm = np.min(colwm) if colwm else 0
  158. crosspage = len(set([b["page_number"] for b in boxes])) > 1
  159. if crosspage:
  160. boxes = Recognizer.sort_X_firstly(boxes, colwm / 2, False)
  161. else:
  162. boxes = Recognizer.sort_C_firstly(boxes, colwm / 2)
  163. boxes[0]["cn"] = 0
  164. cols = [[boxes[0]]]
  165. right = boxes[0]["x1"]
  166. for b in boxes[1:]:
  167. b["cn"] = len(cols) - 1
  168. lst_c = cols[-1]
  169. if (int(b.get("C", "1")) - int(lst_c[-1].get("C", "1")) == 1 and b["page_number"] == lst_c[-1][
  170. "page_number"]) \
  171. or (b["x0"] >= right and lst_c[-1].get("C", "-1") != b.get("C", "-2")): # new col
  172. right = b["x1"]
  173. b["cn"] += 1
  174. cols.append([b])
  175. continue
  176. right = (right + b["x1"]) / 2.
  177. cols[-1].append(b)
  178. tbl = [[[] for _ in range(len(cols))] for _ in range(len(rows))]
  179. for b in boxes:
  180. tbl[b["rn"]][b["cn"]].append(b)
  181. if len(rows) >= 4:
  182. # remove single in column
  183. j = 0
  184. while j < len(tbl[0]):
  185. e, ii = 0, 0
  186. for i in range(len(tbl)):
  187. if tbl[i][j]:
  188. e += 1
  189. ii = i
  190. if e > 1:
  191. break
  192. if e > 1:
  193. j += 1
  194. continue
  195. f = (j > 0 and tbl[ii][j - 1] and tbl[ii]
  196. [j - 1][0].get("text")) or j == 0
  197. ff = (j + 1 < len(tbl[ii]) and tbl[ii][j + 1] and tbl[ii]
  198. [j + 1][0].get("text")) or j + 1 >= len(tbl[ii])
  199. if f and ff:
  200. j += 1
  201. continue
  202. bx = tbl[ii][j][0]
  203. logging.debug("Relocate column single: " + bx["text"])
  204. # j column only has one value
  205. left, right = 100000, 100000
  206. if j > 0 and not f:
  207. for i in range(len(tbl)):
  208. if tbl[i][j - 1]:
  209. left = min(left, np.min(
  210. [bx["x0"] - a["x1"] for a in tbl[i][j - 1]]))
  211. if j + 1 < len(tbl[0]) and not ff:
  212. for i in range(len(tbl)):
  213. if tbl[i][j + 1]:
  214. right = min(right, np.min(
  215. [a["x0"] - bx["x1"] for a in tbl[i][j + 1]]))
  216. assert left < 100000 or right < 100000
  217. if left < right:
  218. for jj in range(j, len(tbl[0])):
  219. for i in range(len(tbl)):
  220. for a in tbl[i][jj]:
  221. a["cn"] -= 1
  222. if tbl[ii][j - 1]:
  223. tbl[ii][j - 1].extend(tbl[ii][j])
  224. else:
  225. tbl[ii][j - 1] = tbl[ii][j]
  226. for i in range(len(tbl)):
  227. tbl[i].pop(j)
  228. else:
  229. for jj in range(j + 1, len(tbl[0])):
  230. for i in range(len(tbl)):
  231. for a in tbl[i][jj]:
  232. a["cn"] -= 1
  233. if tbl[ii][j + 1]:
  234. tbl[ii][j + 1].extend(tbl[ii][j])
  235. else:
  236. tbl[ii][j + 1] = tbl[ii][j]
  237. for i in range(len(tbl)):
  238. tbl[i].pop(j)
  239. cols.pop(j)
  240. assert len(cols) == len(tbl[0]), "Column NO. miss matched: %d vs %d" % (
  241. len(cols), len(tbl[0]))
  242. if len(cols) >= 4:
  243. # remove single in row
  244. i = 0
  245. while i < len(tbl):
  246. e, jj = 0, 0
  247. for j in range(len(tbl[i])):
  248. if tbl[i][j]:
  249. e += 1
  250. jj = j
  251. if e > 1:
  252. break
  253. if e > 1:
  254. i += 1
  255. continue
  256. f = (i > 0 and tbl[i - 1][jj] and tbl[i - 1]
  257. [jj][0].get("text")) or i == 0
  258. ff = (i + 1 < len(tbl) and tbl[i + 1][jj] and tbl[i + 1]
  259. [jj][0].get("text")) or i + 1 >= len(tbl)
  260. if f and ff:
  261. i += 1
  262. continue
  263. bx = tbl[i][jj][0]
  264. logging.debug("Relocate row single: " + bx["text"])
  265. # i row only has one value
  266. up, down = 100000, 100000
  267. if i > 0 and not f:
  268. for j in range(len(tbl[i - 1])):
  269. if tbl[i - 1][j]:
  270. up = min(up, np.min(
  271. [bx["top"] - a["bottom"] for a in tbl[i - 1][j]]))
  272. if i + 1 < len(tbl) and not ff:
  273. for j in range(len(tbl[i + 1])):
  274. if tbl[i + 1][j]:
  275. down = min(down, np.min(
  276. [a["top"] - bx["bottom"] for a in tbl[i + 1][j]]))
  277. assert up < 100000 or down < 100000
  278. if up < down:
  279. for ii in range(i, len(tbl)):
  280. for j in range(len(tbl[ii])):
  281. for a in tbl[ii][j]:
  282. a["rn"] -= 1
  283. if tbl[i - 1][jj]:
  284. tbl[i - 1][jj].extend(tbl[i][jj])
  285. else:
  286. tbl[i - 1][jj] = tbl[i][jj]
  287. tbl.pop(i)
  288. else:
  289. for ii in range(i + 1, len(tbl)):
  290. for j in range(len(tbl[ii])):
  291. for a in tbl[ii][j]:
  292. a["rn"] -= 1
  293. if tbl[i + 1][jj]:
  294. tbl[i + 1][jj].extend(tbl[i][jj])
  295. else:
  296. tbl[i + 1][jj] = tbl[i][jj]
  297. tbl.pop(i)
  298. rows.pop(i)
  299. # which rows are headers
  300. hdset = set([])
  301. for i in range(len(tbl)):
  302. cnt, h = 0, 0
  303. for j, arr in enumerate(tbl[i]):
  304. if not arr:
  305. continue
  306. cnt += 1
  307. if max_type == "Nu" and arr[0]["btype"] == "Nu":
  308. continue
  309. if any([a.get("H") for a in arr]) \
  310. or (max_type == "Nu" and arr[0]["btype"] != "Nu"):
  311. h += 1
  312. if h / cnt > 0.5:
  313. hdset.add(i)
  314. if html:
  315. return TableStructureRecognizer.__html_table(cap, hdset,
  316. TableStructureRecognizer.__cal_spans(boxes, rows,
  317. cols, tbl, True)
  318. )
  319. return TableStructureRecognizer.__desc_table(cap, hdset,
  320. TableStructureRecognizer.__cal_spans(boxes, rows, cols, tbl,
  321. False),
  322. is_english)
  323. @staticmethod
  324. def __html_table(cap, hdset, tbl):
  325. # constrcut HTML
  326. html = "<table>"
  327. if cap:
  328. html += f"<caption>{cap}</caption>"
  329. for i in range(len(tbl)):
  330. row = "<tr>"
  331. txts = []
  332. for j, arr in enumerate(tbl[i]):
  333. if arr is None:
  334. continue
  335. if not arr:
  336. row += "<td></td>" if i not in hdset else "<th></th>"
  337. continue
  338. txt = ""
  339. if arr:
  340. h = min(np.min([c["bottom"] - c["top"]
  341. for c in arr]) / 2, 10)
  342. txt = " ".join([c["text"]
  343. for c in Recognizer.sort_Y_firstly(arr, h)])
  344. txts.append(txt)
  345. sp = ""
  346. if arr[0].get("colspan"):
  347. sp = "colspan={}".format(arr[0]["colspan"])
  348. if arr[0].get("rowspan"):
  349. sp += " rowspan={}".format(arr[0]["rowspan"])
  350. if i in hdset:
  351. row += f"<th {sp} >" + txt + "</th>"
  352. else:
  353. row += f"<td {sp} >" + txt + "</td>"
  354. if i in hdset:
  355. if all([t in hdset for t in txts]):
  356. continue
  357. for t in txts:
  358. hdset.add(t)
  359. if row != "<tr>":
  360. row += "</tr>"
  361. else:
  362. row = ""
  363. html += "\n" + row
  364. html += "\n</table>"
  365. return html
  366. @staticmethod
  367. def __desc_table(cap, hdr_rowno, tbl, is_english):
  368. # get text of every colomn in header row to become header text
  369. clmno = len(tbl[0])
  370. rowno = len(tbl)
  371. headers = {}
  372. hdrset = set()
  373. lst_hdr = []
  374. de = "的" if not is_english else " for "
  375. for r in sorted(list(hdr_rowno)):
  376. headers[r] = ["" for _ in range(clmno)]
  377. for i in range(clmno):
  378. if not tbl[r][i]:
  379. continue
  380. txt = " ".join([a["text"].strip() for a in tbl[r][i]])
  381. headers[r][i] = txt
  382. hdrset.add(txt)
  383. if all([not t for t in headers[r]]):
  384. del headers[r]
  385. hdr_rowno.remove(r)
  386. continue
  387. for j in range(clmno):
  388. if headers[r][j]:
  389. continue
  390. if j >= len(lst_hdr):
  391. break
  392. headers[r][j] = lst_hdr[j]
  393. lst_hdr = headers[r]
  394. for i in range(rowno):
  395. if i not in hdr_rowno:
  396. continue
  397. for j in range(i + 1, rowno):
  398. if j not in hdr_rowno:
  399. break
  400. for k in range(clmno):
  401. if not headers[j - 1][k]:
  402. continue
  403. if headers[j][k].find(headers[j - 1][k]) >= 0:
  404. continue
  405. if len(headers[j][k]) > len(headers[j - 1][k]):
  406. headers[j][k] += (de if headers[j][k]
  407. else "") + headers[j - 1][k]
  408. else:
  409. headers[j][k] = headers[j - 1][k] \
  410. + (de if headers[j - 1][k] else "") \
  411. + headers[j][k]
  412. logging.debug(
  413. f">>>>>>>>>>>>>>>>>{cap}:SIZE:{rowno}X{clmno} Header: {hdr_rowno}")
  414. row_txt = []
  415. for i in range(rowno):
  416. if i in hdr_rowno:
  417. continue
  418. rtxt = []
  419. def append(delimer):
  420. nonlocal rtxt, row_txt
  421. rtxt = delimer.join(rtxt)
  422. if row_txt and len(row_txt[-1]) + len(rtxt) < 64:
  423. row_txt[-1] += "\n" + rtxt
  424. else:
  425. row_txt.append(rtxt)
  426. r = 0
  427. if len(headers.items()):
  428. _arr = [(i - r, r) for r, _ in headers.items() if r < i]
  429. if _arr:
  430. _, r = min(_arr, key=lambda x: x[0])
  431. if r not in headers and clmno <= 2:
  432. for j in range(clmno):
  433. if not tbl[i][j]:
  434. continue
  435. txt = "".join([a["text"].strip() for a in tbl[i][j]])
  436. if txt:
  437. rtxt.append(txt)
  438. if rtxt:
  439. append(":")
  440. continue
  441. for j in range(clmno):
  442. if not tbl[i][j]:
  443. continue
  444. txt = "".join([a["text"].strip() for a in tbl[i][j]])
  445. if not txt:
  446. continue
  447. ctt = headers[r][j] if r in headers else ""
  448. if ctt:
  449. ctt += ":"
  450. ctt += txt
  451. if ctt:
  452. rtxt.append(ctt)
  453. if rtxt:
  454. row_txt.append("; ".join(rtxt))
  455. if cap:
  456. if is_english:
  457. from_ = " in "
  458. else:
  459. from_ = "来自"
  460. row_txt = [t + f"\t——{from_}“{cap}”" for t in row_txt]
  461. return row_txt
  462. @staticmethod
  463. def __cal_spans(boxes, rows, cols, tbl, html=True):
  464. # caculate span
  465. clft = [np.mean([c.get("C_left", c["x0"]) for c in cln])
  466. for cln in cols]
  467. crgt = [np.mean([c.get("C_right", c["x1"]) for c in cln])
  468. for cln in cols]
  469. rtop = [np.mean([c.get("R_top", c["top"]) for c in row])
  470. for row in rows]
  471. rbtm = [np.mean([c.get("R_btm", c["bottom"])
  472. for c in row]) for row in rows]
  473. for b in boxes:
  474. if "SP" not in b:
  475. continue
  476. b["colspan"] = [b["cn"]]
  477. b["rowspan"] = [b["rn"]]
  478. # col span
  479. for j in range(0, len(clft)):
  480. if j == b["cn"]:
  481. continue
  482. if clft[j] + (crgt[j] - clft[j]) / 2 < b["H_left"]:
  483. continue
  484. if crgt[j] - (crgt[j] - clft[j]) / 2 > b["H_right"]:
  485. continue
  486. b["colspan"].append(j)
  487. # row span
  488. for j in range(0, len(rtop)):
  489. if j == b["rn"]:
  490. continue
  491. if rtop[j] + (rbtm[j] - rtop[j]) / 2 < b["H_top"]:
  492. continue
  493. if rbtm[j] - (rbtm[j] - rtop[j]) / 2 > b["H_bott"]:
  494. continue
  495. b["rowspan"].append(j)
  496. def join(arr):
  497. if not arr:
  498. return ""
  499. return "".join([t["text"] for t in arr])
  500. # rm the spaning cells
  501. for i in range(len(tbl)):
  502. for j, arr in enumerate(tbl[i]):
  503. if not arr:
  504. continue
  505. if all(["rowspan" not in a and "colspan" not in a for a in arr]):
  506. continue
  507. rowspan, colspan = [], []
  508. for a in arr:
  509. if isinstance(a.get("rowspan", 0), list):
  510. rowspan.extend(a["rowspan"])
  511. if isinstance(a.get("colspan", 0), list):
  512. colspan.extend(a["colspan"])
  513. rowspan, colspan = set(rowspan), set(colspan)
  514. if len(rowspan) < 2 and len(colspan) < 2:
  515. for a in arr:
  516. if "rowspan" in a:
  517. del a["rowspan"]
  518. if "colspan" in a:
  519. del a["colspan"]
  520. continue
  521. rowspan, colspan = sorted(rowspan), sorted(colspan)
  522. rowspan = list(range(rowspan[0], rowspan[-1] + 1))
  523. colspan = list(range(colspan[0], colspan[-1] + 1))
  524. assert i in rowspan, rowspan
  525. assert j in colspan, colspan
  526. arr = []
  527. for r in rowspan:
  528. for c in colspan:
  529. arr_txt = join(arr)
  530. if tbl[r][c] and join(tbl[r][c]) != arr_txt:
  531. arr.extend(tbl[r][c])
  532. tbl[r][c] = None if html else arr
  533. for a in arr:
  534. if len(rowspan) > 1:
  535. a["rowspan"] = len(rowspan)
  536. elif "rowspan" in a:
  537. del a["rowspan"]
  538. if len(colspan) > 1:
  539. a["colspan"] = len(colspan)
  540. elif "colspan" in a:
  541. del a["colspan"]
  542. tbl[rowspan[0]][colspan[0]] = arr
  543. return tbl