您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

table_structure_recognizer.py 22KB

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