Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

table_structure_recognizer.py 22KB

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