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

pdf_parser.py 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. # -*- coding: utf-8 -*-
  2. import random
  3. import fitz
  4. import xgboost as xgb
  5. from io import BytesIO
  6. import torch
  7. import re
  8. import pdfplumber
  9. import logging
  10. from PIL import Image, ImageDraw
  11. import numpy as np
  12. from api.db import ParserType
  13. from deepdoc.vision import OCR, Recognizer, LayoutRecognizer, TableStructureRecognizer
  14. from rag.nlp import huqie
  15. from copy import deepcopy
  16. from huggingface_hub import hf_hub_download
  17. logging.getLogger("pdfminer").setLevel(logging.WARNING)
  18. class HuParser:
  19. def __init__(self):
  20. self.ocr = OCR()
  21. if hasattr(self, "model_speciess"):
  22. self.layouter = LayoutRecognizer("layout."+self.model_speciess)
  23. else:
  24. self.layouter = LayoutRecognizer("layout")
  25. self.tbl_det = TableStructureRecognizer()
  26. self.updown_cnt_mdl = xgb.Booster()
  27. if torch.cuda.is_available():
  28. self.updown_cnt_mdl.set_param({"device": "cuda"})
  29. self.updown_cnt_mdl.load_model(hf_hub_download(repo_id="InfiniFlow/text_concat_xgb_v1.0",
  30. filename="updown_concat_xgb.model"))
  31. self.page_from = 0
  32. """
  33. If you have trouble downloading HuggingFace models, -_^ this might help!!
  34. For Linux:
  35. export HF_ENDPOINT=https://hf-mirror.com
  36. For Windows:
  37. Good luck
  38. ^_-
  39. """
  40. def __char_width(self, c):
  41. return (c["x1"] - c["x0"]) // len(c["text"])
  42. def __height(self, c):
  43. return c["bottom"] - c["top"]
  44. def _x_dis(self, a, b):
  45. return min(abs(a["x1"] - b["x0"]), abs(a["x0"] - b["x1"]),
  46. abs(a["x0"] + a["x1"] - b["x0"] - b["x1"]) / 2)
  47. def _y_dis(
  48. self, a, b):
  49. return (
  50. b["top"] + b["bottom"] - a["top"] - a["bottom"]) / 2
  51. def _match_proj(self, b):
  52. proj_patt = [
  53. r"第[零一二三四五六七八九十百]+章",
  54. r"第[零一二三四五六七八九十百]+[条节]",
  55. r"[零一二三四五六七八九十百]+[、是  ]",
  56. r"[\((][零一二三四五六七八九十百]+[)\)]",
  57. r"[\((][0-9]+[)\)]",
  58. r"[0-9]+(、|\.[  ]|)|\.[^0-9./a-zA-Z_%><-]{4,})",
  59. r"[0-9]+\.[0-9.]+(、|\.[  ])",
  60. r"[⚫•➢①② ]",
  61. ]
  62. return any([re.match(p, b["text"]) for p in proj_patt])
  63. def _updown_concat_features(self, up, down):
  64. w = max(self.__char_width(up), self.__char_width(down))
  65. h = max(self.__height(up), self.__height(down))
  66. y_dis = self._y_dis(up, down)
  67. LEN = 6
  68. tks_down = huqie.qie(down["text"][:LEN]).split(" ")
  69. tks_up = huqie.qie(up["text"][-LEN:]).split(" ")
  70. tks_all = up["text"][-LEN:].strip() \
  71. + (" " if re.match(r"[a-zA-Z0-9]+",
  72. up["text"][-1] + down["text"][0]) else "") \
  73. + down["text"][:LEN].strip()
  74. tks_all = huqie.qie(tks_all).split(" ")
  75. fea = [
  76. up.get("R", -1) == down.get("R", -1),
  77. y_dis / h,
  78. down["page_number"] - up["page_number"],
  79. up["layout_type"] == down["layout_type"],
  80. up["layout_type"] == "text",
  81. down["layout_type"] == "text",
  82. up["layout_type"] == "table",
  83. down["layout_type"] == "table",
  84. True if re.search(
  85. r"([。?!;!?;+))]|[a-z]\.)$",
  86. up["text"]) else False,
  87. True if re.search(r"[,:‘“、0-9(+-]$", up["text"]) else False,
  88. True if re.search(
  89. r"(^.?[/,?;:\],。;:’”?!》】)-])",
  90. down["text"]) else False,
  91. True if re.match(r"[\((][^\(\)()]+[)\)]$", up["text"]) else False,
  92. True if re.search(r"[,,][^。.]+$", up["text"]) else False,
  93. True if re.search(r"[,,][^。.]+$", up["text"]) else False,
  94. True if re.search(r"[\((][^\))]+$", up["text"])
  95. and re.search(r"[\))]", down["text"]) else False,
  96. self._match_proj(down),
  97. True if re.match(r"[A-Z]", down["text"]) else False,
  98. True if re.match(r"[A-Z]", up["text"][-1]) else False,
  99. True if re.match(r"[a-z0-9]", up["text"][-1]) else False,
  100. True if re.match(r"[0-9.%,-]+$", down["text"]) else False,
  101. up["text"].strip()[-2:] == down["text"].strip()[-2:] if len(up["text"].strip()
  102. ) > 1 and len(
  103. down["text"].strip()) > 1 else False,
  104. up["x0"] > down["x1"],
  105. abs(self.__height(up) - self.__height(down)) / min(self.__height(up),
  106. self.__height(down)),
  107. self._x_dis(up, down) / max(w, 0.000001),
  108. (len(up["text"]) - len(down["text"])) /
  109. max(len(up["text"]), len(down["text"])),
  110. len(tks_all) - len(tks_up) - len(tks_down),
  111. len(tks_down) - len(tks_up),
  112. tks_down[-1] == tks_up[-1],
  113. max(down["in_row"], up["in_row"]),
  114. abs(down["in_row"] - up["in_row"]),
  115. len(tks_down) == 1 and huqie.tag(tks_down[0]).find("n") >= 0,
  116. len(tks_up) == 1 and huqie.tag(tks_up[0]).find("n") >= 0
  117. ]
  118. return fea
  119. @staticmethod
  120. def sort_X_by_page(arr, threashold):
  121. # sort using y1 first and then x1
  122. arr = sorted(arr, key=lambda r: (r["page_number"], r["x0"], r["top"]))
  123. for i in range(len(arr) - 1):
  124. for j in range(i, -1, -1):
  125. # restore the order using th
  126. if abs(arr[j + 1]["x0"] - arr[j]["x0"]) < threashold \
  127. and arr[j + 1]["top"] < arr[j]["top"]\
  128. and arr[j + 1]["page_number"] == arr[j]["page_number"]:
  129. tmp = arr[j]
  130. arr[j] = arr[j + 1]
  131. arr[j + 1] = tmp
  132. return arr
  133. def _has_color(self, o):
  134. if o.get("ncs", "") == "DeviceGray":
  135. if o["stroking_color"] and o["stroking_color"][0] == 1 and o["non_stroking_color"] and \
  136. o["non_stroking_color"][0] == 1:
  137. if re.match(r"[a-zT_\[\]\(\)-]+", o.get("text", "")):
  138. return False
  139. return True
  140. def _table_transformer_job(self, ZM):
  141. logging.info("Table processing...")
  142. imgs, pos = [], []
  143. tbcnt = [0]
  144. MARGIN = 10
  145. self.tb_cpns = []
  146. assert len(self.page_layout) == len(self.page_images)
  147. for p, tbls in enumerate(self.page_layout): # for page
  148. tbls = [f for f in tbls if f["type"] == "table"]
  149. tbcnt.append(len(tbls))
  150. if not tbls:
  151. continue
  152. for tb in tbls: # for table
  153. left, top, right, bott = tb["x0"] - MARGIN, tb["top"] - MARGIN, \
  154. tb["x1"] + MARGIN, tb["bottom"] + MARGIN
  155. left *= ZM
  156. top *= ZM
  157. right *= ZM
  158. bott *= ZM
  159. pos.append((left, top))
  160. imgs.append(self.page_images[p].crop((left, top, right, bott)))
  161. assert len(self.page_images) == len(tbcnt) - 1
  162. if not imgs:
  163. return
  164. recos = self.tbl_det(imgs)
  165. tbcnt = np.cumsum(tbcnt)
  166. for i in range(len(tbcnt) - 1): # for page
  167. pg = []
  168. for j, tb_items in enumerate(
  169. recos[tbcnt[i]: tbcnt[i + 1]]): # for table
  170. poss = pos[tbcnt[i]: tbcnt[i + 1]]
  171. for it in tb_items: # for table components
  172. it["x0"] = (it["x0"] + poss[j][0])
  173. it["x1"] = (it["x1"] + poss[j][0])
  174. it["top"] = (it["top"] + poss[j][1])
  175. it["bottom"] = (it["bottom"] + poss[j][1])
  176. for n in ["x0", "x1", "top", "bottom"]:
  177. it[n] /= ZM
  178. it["top"] += self.page_cum_height[i]
  179. it["bottom"] += self.page_cum_height[i]
  180. it["pn"] = i
  181. it["layoutno"] = j
  182. pg.append(it)
  183. self.tb_cpns.extend(pg)
  184. def gather(kwd, fzy=10, ption=0.6):
  185. eles = Recognizer.sort_Y_firstly(
  186. [r for r in self.tb_cpns if re.match(kwd, r["label"])], fzy)
  187. eles = Recognizer.layouts_cleanup(self.boxes, eles, 5, ption)
  188. return Recognizer.sort_Y_firstly(eles, 0)
  189. # add R,H,C,SP tag to boxes within table layout
  190. headers = gather(r".*header$")
  191. rows = gather(r".* (row|header)")
  192. spans = gather(r".*spanning")
  193. clmns = sorted([r for r in self.tb_cpns if re.match(
  194. r"table column$", r["label"])], key=lambda x: (x["pn"], x["layoutno"], x["x0"]))
  195. clmns = Recognizer.layouts_cleanup(self.boxes, clmns, 5, 0.5)
  196. for b in self.boxes:
  197. if b.get("layout_type", "") != "table":
  198. continue
  199. ii = Recognizer.find_overlapped_with_threashold(b, rows, thr=0.3)
  200. if ii is not None:
  201. b["R"] = ii
  202. b["R_top"] = rows[ii]["top"]
  203. b["R_bott"] = rows[ii]["bottom"]
  204. ii = Recognizer.find_overlapped_with_threashold(b, headers, thr=0.3)
  205. if ii is not None:
  206. b["H_top"] = headers[ii]["top"]
  207. b["H_bott"] = headers[ii]["bottom"]
  208. b["H_left"] = headers[ii]["x0"]
  209. b["H_right"] = headers[ii]["x1"]
  210. b["H"] = ii
  211. ii = Recognizer.find_horizontally_tightest_fit(b, clmns)
  212. if ii is not None:
  213. b["C"] = ii
  214. b["C_left"] = clmns[ii]["x0"]
  215. b["C_right"] = clmns[ii]["x1"]
  216. ii = Recognizer.find_overlapped_with_threashold(b, spans, thr=0.3)
  217. if ii is not None:
  218. b["H_top"] = spans[ii]["top"]
  219. b["H_bott"] = spans[ii]["bottom"]
  220. b["H_left"] = spans[ii]["x0"]
  221. b["H_right"] = spans[ii]["x1"]
  222. b["SP"] = ii
  223. def __ocr(self, pagenum, img, chars, ZM=3):
  224. bxs = self.ocr(np.array(img))
  225. if not bxs:
  226. self.boxes.append([])
  227. return
  228. bxs = [(line[0], line[1][0]) for line in bxs]
  229. bxs = Recognizer.sort_Y_firstly(
  230. [{"x0": b[0][0] / ZM, "x1": b[1][0] / ZM,
  231. "top": b[0][1] / ZM, "text": "", "txt": t,
  232. "bottom": b[-1][1] / ZM,
  233. "page_number": pagenum} for b, t in bxs if b[0][0] <= b[1][0] and b[0][1] <= b[-1][1]],
  234. self.mean_height[-1] / 3
  235. )
  236. # merge chars in the same rect
  237. for c in Recognizer.sort_X_firstly(chars, self.mean_width[pagenum - 1] // 4):
  238. ii = Recognizer.find_overlapped(c, bxs)
  239. if ii is None:
  240. self.lefted_chars.append(c)
  241. continue
  242. ch = c["bottom"] - c["top"]
  243. bh = bxs[ii]["bottom"] - bxs[ii]["top"]
  244. if abs(ch - bh) / max(ch, bh) >= 0.7 and c["text"] != ' ':
  245. self.lefted_chars.append(c)
  246. continue
  247. if c["text"] == " " and bxs[ii]["text"]:
  248. if re.match(r"[0-9a-zA-Z,.?;:!%%]", bxs[ii]["text"][-1]): bxs[ii]["text"] += " "
  249. else:
  250. bxs[ii]["text"] += c["text"]
  251. for b in bxs:
  252. if not b["text"]:
  253. b["text"] = b["txt"]
  254. del b["txt"]
  255. if self.mean_height[-1] == 0:
  256. self.mean_height[-1] = np.median([b["bottom"] - b["top"]
  257. for b in bxs])
  258. self.boxes.append(bxs)
  259. def _layouts_rec(self, ZM):
  260. assert len(self.page_images) == len(self.boxes)
  261. self.boxes, self.page_layout = self.layouter(self.page_images, self.boxes, ZM)
  262. # cumlative Y
  263. for i in range(len(self.boxes)):
  264. self.boxes[i]["top"] += \
  265. self.page_cum_height[self.boxes[i]["page_number"] - 1]
  266. self.boxes[i]["bottom"] += \
  267. self.page_cum_height[self.boxes[i]["page_number"] - 1]
  268. def _text_merge(self):
  269. # merge adjusted boxes
  270. bxs = self.boxes
  271. def end_with(b, txt):
  272. txt = txt.strip()
  273. tt = b.get("text", "").strip()
  274. return tt and tt.find(txt) == len(tt) - len(txt)
  275. def start_with(b, txts):
  276. tt = b.get("text", "").strip()
  277. return tt and any([tt.find(t.strip()) == 0 for t in txts])
  278. # horizontally merge adjacent box with the same layout
  279. i = 0
  280. while i < len(bxs) - 1:
  281. b = bxs[i]
  282. b_ = bxs[i + 1]
  283. if b.get("layoutno", "0") != b_.get("layoutno", "1"):
  284. i += 1
  285. continue
  286. dis_thr = 1
  287. dis = b["x1"] - b_["x0"]
  288. if b.get("layout_type", "") != "text" or b_.get(
  289. "layout_type", "") != "text":
  290. if end_with(b, ",") or start_with(b_, "(,"):
  291. dis_thr = -8
  292. else:
  293. i += 1
  294. continue
  295. if abs(self._y_dis(b, b_)) < self.mean_height[bxs[i]["page_number"] - 1] / 5 \
  296. and dis >= dis_thr and b["x1"] < b_["x1"]:
  297. # merge
  298. bxs[i]["x1"] = b_["x1"]
  299. bxs[i]["top"] = (b["top"] + b_["top"]) / 2
  300. bxs[i]["bottom"] = (b["bottom"] + b_["bottom"]) / 2
  301. bxs[i]["text"] += b_["text"]
  302. bxs.pop(i + 1)
  303. continue
  304. i += 1
  305. self.boxes = bxs
  306. def _naive_vertical_merge(self):
  307. bxs = Recognizer.sort_Y_firstly(self.boxes, np.median(self.mean_height) / 3)
  308. i = 0
  309. while i + 1 < len(bxs):
  310. b = bxs[i]
  311. b_ = bxs[i + 1]
  312. if b["page_number"] < b_["page_number"] and re.match(r"[0-9 •一—-]+$", b["text"]):
  313. bxs.pop(i)
  314. continue
  315. concatting_feats = [
  316. b["text"].strip()[-1] in ",;:'\",、‘“;:-",
  317. len(b["text"].strip()) > 1 and b["text"].strip()[-2] in ",;:'\",‘“、;:",
  318. b["text"].strip()[0] in "。;?!?”)),,、:",
  319. ]
  320. # features for not concating
  321. feats = [
  322. b.get("layoutno", 0) != b.get("layoutno", 0),
  323. b["text"].strip()[-1] in "。?!?",
  324. self.is_english and b["text"].strip()[-1] in ".!?",
  325. b["page_number"] == b_["page_number"] and b_["top"] - \
  326. b["bottom"] > self.mean_height[b["page_number"] - 1] * 1.5,
  327. b["page_number"] < b_["page_number"] and abs(
  328. b["x0"] - b_["x0"]) > self.mean_width[b["page_number"] - 1] * 4
  329. ]
  330. if any(feats) and not any(concatting_feats):
  331. i += 1
  332. continue
  333. # merge up and down
  334. b["bottom"] = b_["bottom"]
  335. b["text"] += b_["text"]
  336. b["x0"] = min(b["x0"], b_["x0"])
  337. b["x1"] = max(b["x1"], b_["x1"])
  338. bxs.pop(i + 1)
  339. self.boxes = bxs
  340. def _concat_downward(self, concat_between_pages=True):
  341. # count boxes in the same row as a feature
  342. for i in range(len(self.boxes)):
  343. mh = self.mean_height[self.boxes[i]["page_number"] - 1]
  344. self.boxes[i]["in_row"] = 0
  345. j = max(0, i - 12)
  346. while j < min(i + 12, len(self.boxes)):
  347. if j == i:
  348. j += 1
  349. continue
  350. ydis = self._y_dis(self.boxes[i], self.boxes[j]) / mh
  351. if abs(ydis) < 1:
  352. self.boxes[i]["in_row"] += 1
  353. elif ydis > 0:
  354. break
  355. j += 1
  356. # concat between rows
  357. boxes = deepcopy(self.boxes)
  358. blocks = []
  359. while boxes:
  360. chunks = []
  361. def dfs(up, dp):
  362. chunks.append(up)
  363. i = dp
  364. while i < min(dp + 12, len(boxes)):
  365. ydis = self._y_dis(up, boxes[i])
  366. smpg = up["page_number"] == boxes[i]["page_number"]
  367. mh = self.mean_height[up["page_number"] - 1]
  368. mw = self.mean_width[up["page_number"] - 1]
  369. if smpg and ydis > mh * 4:
  370. break
  371. if not smpg and ydis > mh * 16:
  372. break
  373. down = boxes[i]
  374. if not concat_between_pages and down["page_number"] > up["page_number"]:
  375. break
  376. if up.get("R", "") != down.get(
  377. "R", "") and up["text"][-1] != ",":
  378. i += 1
  379. continue
  380. if re.match(r"[0-9]{2,3}/[0-9]{3}$", up["text"]) \
  381. or re.match(r"[0-9]{2,3}/[0-9]{3}$", down["text"]):
  382. i += 1
  383. continue
  384. if not down["text"].strip():
  385. i += 1
  386. continue
  387. if up["x1"] < down["x0"] - 10 * \
  388. mw or up["x0"] > down["x1"] + 10 * mw:
  389. i += 1
  390. continue
  391. if i - dp < 5 and up.get("layout_type") == "text":
  392. if up.get("layoutno", "1") == down.get(
  393. "layoutno", "2"):
  394. dfs(down, i + 1)
  395. boxes.pop(i)
  396. return
  397. i += 1
  398. continue
  399. fea = self._updown_concat_features(up, down)
  400. if self.updown_cnt_mdl.predict(
  401. xgb.DMatrix([fea]))[0] <= 0.5:
  402. i += 1
  403. continue
  404. dfs(down, i + 1)
  405. boxes.pop(i)
  406. return
  407. dfs(boxes[0], 1)
  408. boxes.pop(0)
  409. if chunks:
  410. blocks.append(chunks)
  411. # concat within each block
  412. boxes = []
  413. for b in blocks:
  414. if len(b) == 1:
  415. boxes.append(b[0])
  416. continue
  417. t = b[0]
  418. for c in b[1:]:
  419. t["text"] = t["text"].strip()
  420. c["text"] = c["text"].strip()
  421. if not c["text"]:
  422. continue
  423. if t["text"] and re.match(
  424. r"[0-9\.a-zA-Z]+$", t["text"][-1] + c["text"][-1]):
  425. t["text"] += " "
  426. t["text"] += c["text"]
  427. t["x0"] = min(t["x0"], c["x0"])
  428. t["x1"] = max(t["x1"], c["x1"])
  429. t["page_number"] = min(t["page_number"], c["page_number"])
  430. t["bottom"] = c["bottom"]
  431. if not t["layout_type"] \
  432. and c["layout_type"]:
  433. t["layout_type"] = c["layout_type"]
  434. boxes.append(t)
  435. self.boxes = Recognizer.sort_Y_firstly(boxes, 0)
  436. def _filter_forpages(self):
  437. if not self.boxes:
  438. return
  439. findit = False
  440. i = 0
  441. while i < len(self.boxes):
  442. if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$", re.sub(r"( | |\u3000)+", "", self.boxes[i]["text"].lower())):
  443. i += 1
  444. continue
  445. findit = True
  446. eng = re.match(r"[0-9a-zA-Z :'.-]{5,}", self.boxes[i]["text"].strip())
  447. self.boxes.pop(i)
  448. if i >= len(self.boxes): break
  449. prefix = self.boxes[i]["text"].strip()[:3] if not eng else " ".join(self.boxes[i]["text"].strip().split(" ")[:2])
  450. while not prefix:
  451. self.boxes.pop(i)
  452. if i >= len(self.boxes): break
  453. prefix = self.boxes[i]["text"].strip()[:3] if not eng else " ".join(self.boxes[i]["text"].strip().split(" ")[:2])
  454. self.boxes.pop(i)
  455. if i >= len(self.boxes) or not prefix: break
  456. for j in range(i, min(i + 128, len(self.boxes))):
  457. if not re.match(prefix, self.boxes[j]["text"]):
  458. continue
  459. for k in range(i, j): self.boxes.pop(i)
  460. break
  461. if findit:return
  462. page_dirty = [0] * len(self.page_images)
  463. for b in self.boxes:
  464. if re.search(r"(··|··|··)", b["text"]):
  465. page_dirty[b["page_number"]-1] += 1
  466. page_dirty = set([i+1 for i, t in enumerate(page_dirty) if t > 3])
  467. if not page_dirty: return
  468. i = 0
  469. while i < len(self.boxes):
  470. if self.boxes[i]["page_number"] in page_dirty:
  471. self.boxes.pop(i)
  472. continue
  473. i += 1
  474. def _merge_with_same_bullet(self):
  475. i = 0
  476. while i + 1 < len(self.boxes):
  477. b = self.boxes[i]
  478. b_ = self.boxes[i + 1]
  479. if not b["text"].strip():
  480. self.boxes.pop(i)
  481. continue
  482. if not b_["text"].strip():
  483. self.boxes.pop(i+1)
  484. continue
  485. if b["text"].strip()[0] != b_["text"].strip()[0] \
  486. or b["text"].strip()[0].lower() in set("qwertyuopasdfghjklzxcvbnm") \
  487. or huqie.is_chinese(b["text"].strip()[0]) \
  488. or b["top"] > b_["bottom"]:
  489. i += 1
  490. continue
  491. b_["text"] = b["text"] + "\n" + b_["text"]
  492. b_["x0"] = min(b["x0"], b_["x0"])
  493. b_["x1"] = max(b["x1"], b_["x1"])
  494. b_["top"] = b["top"]
  495. self.boxes.pop(i)
  496. def _extract_table_figure(self, need_image, ZM, return_html, need_position):
  497. tables = {}
  498. figures = {}
  499. # extract figure and table boxes
  500. i = 0
  501. lst_lout_no = ""
  502. nomerge_lout_no = []
  503. while i < len(self.boxes):
  504. if "layoutno" not in self.boxes[i]:
  505. i += 1
  506. continue
  507. lout_no = str(self.boxes[i]["page_number"]) + \
  508. "-" + str(self.boxes[i]["layoutno"])
  509. if TableStructureRecognizer.is_caption(self.boxes[i]) or self.boxes[i]["layout_type"] in ["table caption", "title",
  510. "figure caption", "reference"]:
  511. nomerge_lout_no.append(lst_lout_no)
  512. if self.boxes[i]["layout_type"] == "table":
  513. if re.match(r"(数据|资料|图表)*来源[:: ]", self.boxes[i]["text"]):
  514. self.boxes.pop(i)
  515. continue
  516. if lout_no not in tables:
  517. tables[lout_no] = []
  518. tables[lout_no].append(self.boxes[i])
  519. self.boxes.pop(i)
  520. lst_lout_no = lout_no
  521. continue
  522. if need_image and self.boxes[i]["layout_type"] == "figure":
  523. if re.match(r"(数据|资料|图表)*来源[:: ]", self.boxes[i]["text"]):
  524. self.boxes.pop(i)
  525. continue
  526. if lout_no not in figures:
  527. figures[lout_no] = []
  528. figures[lout_no].append(self.boxes[i])
  529. self.boxes.pop(i)
  530. lst_lout_no = lout_no
  531. continue
  532. i += 1
  533. # merge table on different pages
  534. nomerge_lout_no = set(nomerge_lout_no)
  535. tbls = sorted([(k, bxs) for k, bxs in tables.items()],
  536. key=lambda x: (x[1][0]["top"], x[1][0]["x0"]))
  537. i = len(tbls) - 1
  538. while i - 1 >= 0:
  539. k0, bxs0 = tbls[i - 1]
  540. k, bxs = tbls[i]
  541. i -= 1
  542. if k0 in nomerge_lout_no:
  543. continue
  544. if bxs[0]["page_number"] == bxs0[0]["page_number"]:
  545. continue
  546. if bxs[0]["page_number"] - bxs0[0]["page_number"] > 1:
  547. continue
  548. mh = self.mean_height[bxs[0]["page_number"] - 1]
  549. if self._y_dis(bxs0[-1], bxs[0]) > mh * 23:
  550. continue
  551. tables[k0].extend(tables[k])
  552. del tables[k]
  553. def x_overlapped(a, b):
  554. return not any([a["x1"] < b["x0"], a["x0"] > b["x1"]])
  555. # find captions and pop out
  556. i = 0
  557. while i < len(self.boxes):
  558. c = self.boxes[i]
  559. # mh = self.mean_height[c["page_number"]-1]
  560. if not TableStructureRecognizer.is_caption(c):
  561. i += 1
  562. continue
  563. # find the nearest layouts
  564. def nearest(tbls):
  565. nonlocal c
  566. mink = ""
  567. minv = 1000000000
  568. for k, bxs in tbls.items():
  569. for b in bxs[:10]:
  570. if b.get("layout_type", "").find("caption") >= 0:
  571. continue
  572. y_dis = self._y_dis(c, b)
  573. x_dis = self._x_dis(
  574. c, b) if not x_overlapped(
  575. c, b) else 0
  576. dis = y_dis * y_dis + x_dis * x_dis
  577. if dis < minv:
  578. mink = k
  579. minv = dis
  580. return mink, minv
  581. tk, tv = nearest(tables)
  582. fk, fv = nearest(figures)
  583. if min(tv, fv) > 2000:
  584. i += 1
  585. continue
  586. if tv < fv:
  587. tables[tk].insert(0, c)
  588. logging.debug(
  589. "TABLE:" +
  590. self.boxes[i]["text"] +
  591. "; Cap: " +
  592. tk)
  593. else:
  594. figures[fk].insert(0, c)
  595. logging.debug(
  596. "FIGURE:" +
  597. self.boxes[i]["text"] +
  598. "; Cap: " +
  599. tk)
  600. self.boxes.pop(i)
  601. res = []
  602. positions = []
  603. def cropout(bxs, ltype, poss):
  604. nonlocal ZM
  605. pn = set([b["page_number"] - 1 for b in bxs])
  606. if len(pn) < 2:
  607. pn = list(pn)[0]
  608. ht = self.page_cum_height[pn]
  609. b = {
  610. "x0": np.min([b["x0"] for b in bxs]),
  611. "top": np.min([b["top"] for b in bxs]) - ht,
  612. "x1": np.max([b["x1"] for b in bxs]),
  613. "bottom": np.max([b["bottom"] for b in bxs]) - ht
  614. }
  615. louts = [l for l in self.page_layout[pn] if l["type"] == ltype]
  616. ii = Recognizer.find_overlapped(b, louts, naive=True)
  617. if ii is not None:
  618. b = louts[ii]
  619. else:
  620. logging.warn(
  621. f"Missing layout match: {pn + 1},%s" %
  622. (bxs[0].get(
  623. "layoutno", "")))
  624. left, top, right, bott = b["x0"], b["top"], b["x1"], b["bottom"]
  625. poss.append((pn+self.page_from, left, right, top, bott))
  626. return self.page_images[pn] \
  627. .crop((left * ZM, top * ZM,
  628. right * ZM, bott * ZM))
  629. pn = {}
  630. for b in bxs:
  631. p = b["page_number"] - 1
  632. if p not in pn:
  633. pn[p] = []
  634. pn[p].append(b)
  635. pn = sorted(pn.items(), key=lambda x: x[0])
  636. imgs = [cropout(arr, ltype, poss) for p, arr in pn]
  637. pic = Image.new("RGB",
  638. (int(np.max([i.size[0] for i in imgs])),
  639. int(np.sum([m.size[1] for m in imgs]))),
  640. (245, 245, 245))
  641. height = 0
  642. for img in imgs:
  643. pic.paste(img, (0, int(height)))
  644. height += img.size[1]
  645. return pic
  646. # crop figure out and add caption
  647. for k, bxs in figures.items():
  648. txt = "\n".join(
  649. [b["text"] for b in bxs
  650. if not re.match(r"[0-9a-z.\+%-]", b["text"].strip())
  651. and len(b["text"].strip()) >= 4
  652. ]
  653. )
  654. if not txt:
  655. continue
  656. poss = []
  657. res.append(
  658. (cropout(
  659. bxs,
  660. "figure", poss),
  661. [txt] if not return_html else [f"<p>{txt}</p>"]))
  662. positions.append(poss)
  663. for k, bxs in tables.items():
  664. if not bxs:
  665. continue
  666. bxs = Recognizer.sort_Y_firstly(bxs, np.mean([(b["bottom"]-b["top"])/2 for b in bxs]))
  667. poss = []
  668. res.append((cropout(bxs, "table", poss),
  669. self.tbl_det.construct_table(bxs, html=return_html, is_english=self.is_english)))
  670. positions.append(poss)
  671. assert len(positions) == len(res)
  672. if need_position: return list(zip(res, positions))
  673. return res
  674. def proj_match(self, line):
  675. if len(line) <= 2:
  676. return
  677. if re.match(r"[0-9 ().,%%+/-]+$", line):
  678. return False
  679. for p, j in [
  680. (r"第[零一二三四五六七八九十百]+章", 1),
  681. (r"第[零一二三四五六七八九十百]+[条节]", 2),
  682. (r"[零一二三四五六七八九十百]+[、  ]", 3),
  683. (r"[\((][零一二三四五六七八九十百]+[)\)]", 4),
  684. (r"[0-9]+(、|\.[  ]|\.[^0-9])", 5),
  685. (r"[0-9]+\.[0-9]+(、|[.  ]|[^0-9])", 6),
  686. (r"[0-9]+\.[0-9]+\.[0-9]+(、|[  ]|[^0-9])", 7),
  687. (r"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(、|[  ]|[^0-9])", 8),
  688. (r".{,48}[::??]$", 9),
  689. (r"[0-9]+)", 10),
  690. (r"[\((][0-9]+[)\)]", 11),
  691. (r"[零一二三四五六七八九十百]+是", 12),
  692. (r"[⚫•➢✓]", 12)
  693. ]:
  694. if re.match(p, line):
  695. return j
  696. return
  697. def _line_tag(self, bx, ZM):
  698. pn = [bx["page_number"]]
  699. top = bx["top"] - self.page_cum_height[pn[0] - 1]
  700. bott = bx["bottom"] - self.page_cum_height[pn[0] - 1]
  701. while bott * ZM > self.page_images[pn[-1] - 1].size[1]:
  702. bott -= self.page_images[pn[-1] - 1].size[1] / ZM
  703. pn.append(pn[-1] + 1)
  704. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  705. .format("-".join([str(p) for p in pn]),
  706. bx["x0"], bx["x1"], top, bott)
  707. def __filterout_scraps(self, boxes, ZM):
  708. def width(b):
  709. return b["x1"] - b["x0"]
  710. def height(b):
  711. return b["bottom"] - b["top"]
  712. def usefull(b):
  713. if b.get("layout_type"):
  714. return True
  715. if width(
  716. b) > self.page_images[b["page_number"] - 1].size[0] / ZM / 3:
  717. return True
  718. if b["bottom"] - b["top"] > self.mean_height[b["page_number"] - 1]:
  719. return True
  720. return False
  721. res = []
  722. while boxes:
  723. lines = []
  724. widths = []
  725. pw = self.page_images[boxes[0]["page_number"] - 1].size[0] / ZM
  726. mh = self.mean_height[boxes[0]["page_number"] - 1]
  727. mj = self.proj_match(
  728. boxes[0]["text"]) or boxes[0].get(
  729. "layout_type",
  730. "") == "title"
  731. def dfs(line, st):
  732. nonlocal mh, pw, lines, widths
  733. lines.append(line)
  734. widths.append(width(line))
  735. width_mean = np.mean(widths)
  736. mmj = self.proj_match(
  737. line["text"]) or line.get(
  738. "layout_type",
  739. "") == "title"
  740. for i in range(st + 1, min(st + 20, len(boxes))):
  741. if (boxes[i]["page_number"] - line["page_number"]) > 0:
  742. break
  743. if not mmj and self._y_dis(
  744. line, boxes[i]) >= 3 * mh and height(line) < 1.5 * mh:
  745. break
  746. if not usefull(boxes[i]):
  747. continue
  748. if mmj or \
  749. (self._x_dis(boxes[i], line) < pw / 10): \
  750. # and abs(width(boxes[i])-width_mean)/max(width(boxes[i]),width_mean)<0.5):
  751. # concat following
  752. dfs(boxes[i], i)
  753. boxes.pop(i)
  754. break
  755. try:
  756. if usefull(boxes[0]):
  757. dfs(boxes[0], 0)
  758. else:
  759. logging.debug("WASTE: " + boxes[0]["text"])
  760. except Exception as e:
  761. pass
  762. boxes.pop(0)
  763. mw = np.mean(widths)
  764. if mj or mw / pw >= 0.35 or mw > 200:
  765. res.append("\n".join([c["text"] + self._line_tag(c, ZM) for c in lines]))
  766. else:
  767. logging.debug("REMOVED: " +
  768. "<<".join([c["text"] for c in lines]))
  769. return "\n\n".join(res)
  770. @staticmethod
  771. def total_page_number(fnm, binary=None):
  772. try:
  773. pdf = pdfplumber.open(fnm) if not binary else pdfplumber.open(BytesIO(binary))
  774. return len(pdf.pages)
  775. except Exception as e:
  776. pdf = fitz.open(fnm) if not binary else fitz.open(stream=fnm, filetype="pdf")
  777. return len(pdf)
  778. def __images__(self, fnm, zoomin=3, page_from=0, page_to=299):
  779. self.lefted_chars = []
  780. self.mean_height = []
  781. self.mean_width = []
  782. self.boxes = []
  783. self.garbages = {}
  784. self.page_cum_height = [0]
  785. self.page_layout = []
  786. self.page_from = page_from
  787. try:
  788. self.pdf = pdfplumber.open(fnm) if isinstance(fnm, str) else pdfplumber.open(BytesIO(fnm))
  789. self.page_images = [p.to_image(resolution=72 * zoomin).annotated for i, p in
  790. enumerate(self.pdf.pages[page_from:page_to])]
  791. self.page_chars = [[c for c in page.chars if self._has_color(c)] for page in self.pdf.pages[page_from:page_to]]
  792. self.total_page = len(self.pdf.pages)
  793. except Exception as e:
  794. self.pdf = fitz.open(fnm) if isinstance(fnm, str) else fitz.open(stream=fnm, filetype="pdf")
  795. self.page_images = []
  796. self.page_chars = []
  797. mat = fitz.Matrix(zoomin, zoomin)
  798. self.total_page = len(self.pdf)
  799. for i, page in enumerate(self.pdf):
  800. if i < page_from:continue
  801. if i >= page_to:break
  802. pix = page.get_pixmap(matrix=mat)
  803. img = Image.frombytes("RGB", [pix.width, pix.height],
  804. pix.samples)
  805. self.page_images.append(img)
  806. self.page_chars.append([])
  807. logging.info("Images converted.")
  808. self.is_english = [re.search(r"[a-zA-Z0-9,/¸;:'\[\]\(\)!@#$%^&*\"?<>._-]{30,}", "".join(random.choices([c["text"] for c in self.page_chars[i]], k=min(100, len(self.page_chars[i]))))) for i in range(len(self.page_chars))]
  809. if sum([1 if e else 0 for e in self.is_english]) > len(self.page_images) / 2:
  810. self.is_english = True
  811. else:
  812. self.is_english = False
  813. for i, img in enumerate(self.page_images):
  814. chars = self.page_chars[i] if not self.is_english else []
  815. self.mean_height.append(
  816. np.median(sorted([c["height"] for c in chars])) if chars else 0
  817. )
  818. self.mean_width.append(
  819. np.median(sorted([c["width"] for c in chars])) if chars else 8
  820. )
  821. self.page_cum_height.append(img.size[1] / zoomin)
  822. j = 0
  823. while j + 1 < len(chars):
  824. if chars[j]["text"] and chars[j + 1]["text"] \
  825. and re.match(r"[0-9a-zA-Z,.:;!%]+", chars[j]["text"] + chars[j + 1]["text"]) \
  826. and chars[j + 1]["x0"] - chars[j]["x1"] >= min(chars[j + 1]["width"],
  827. chars[j]["width"]) / 2:
  828. chars[j]["text"] += " "
  829. j += 1
  830. # if i > 0:
  831. # if not chars:
  832. # self.page_cum_height.append(img.size[1] / zoomin)
  833. # else:
  834. # self.page_cum_height.append(
  835. # np.max([c["bottom"] for c in chars]))
  836. self.__ocr(i + 1, img, chars, zoomin)
  837. if not self.is_english and not any([c for c in self.page_chars]) and self.boxes:
  838. bxes = [b for bxs in self.boxes for b in bxs]
  839. self.is_english = re.search(r"[\na-zA-Z0-9,/¸;:'\[\]\(\)!@#$%^&*\"?<>._-]{30,}", "".join([b["text"] for b in random.choices(bxes, k=min(30, len(bxes)))]))
  840. logging.info("Is it English:", self.is_english)
  841. self.page_cum_height = np.cumsum(self.page_cum_height)
  842. assert len(self.page_cum_height) == len(self.page_images) + 1
  843. def __call__(self, fnm, need_image=True, zoomin=3, return_html=False):
  844. self.__images__(fnm, zoomin)
  845. self._layouts_rec(zoomin)
  846. self._table_transformer_job(zoomin)
  847. self._text_merge()
  848. self._concat_downward()
  849. self._filter_forpages()
  850. tbls = self._extract_table_figure(need_image, zoomin, return_html, False)
  851. return self.__filterout_scraps(deepcopy(self.boxes), zoomin), tbls
  852. def remove_tag(self, txt):
  853. return re.sub(r"@@[\t0-9.-]+?##", "", txt)
  854. def crop(self, text, ZM=3, need_position=False):
  855. imgs = []
  856. poss = []
  857. for tag in re.findall(r"@@[0-9-]+\t[0-9.\t]+##", text):
  858. pn, left, right, top, bottom = tag.strip(
  859. "#").strip("@").split("\t")
  860. left, right, top, bottom = float(left), float(
  861. right), float(top), float(bottom)
  862. poss.append(([int(p) - 1 for p in pn.split("-")], left, right, top, bottom))
  863. if not poss:
  864. if need_position: return None, None
  865. return
  866. max_width = np.max([right-left for (_, left, right, _, _) in poss])
  867. GAP = 6
  868. pos = poss[0]
  869. poss.insert(0, ([pos[0][0]], pos[1], pos[2], max(0, pos[3]-120), max(pos[3]-GAP, 0)))
  870. pos = poss[-1]
  871. poss.append(([pos[0][-1]], pos[1], pos[2], min(self.page_images[pos[0][-1]].size[1]/ZM, pos[4]+GAP), min(self.page_images[pos[0][-1]].size[1]/ZM, pos[4]+120)))
  872. positions = []
  873. for ii, (pns, left, right, top, bottom) in enumerate(poss):
  874. right = left + max_width
  875. bottom *= ZM
  876. for pn in pns[1:]:
  877. bottom += self.page_images[pn - 1].size[1]
  878. imgs.append(
  879. self.page_images[pns[0]].crop((left * ZM, top * ZM,
  880. right *
  881. ZM, min(
  882. bottom, self.page_images[pns[0]].size[1])
  883. ))
  884. )
  885. if 0 < ii < len(poss)-1:
  886. positions.append((pns[0]+self.page_from, left, right, top, min(
  887. bottom, self.page_images[pns[0]].size[1])/ZM))
  888. bottom -= self.page_images[pns[0]].size[1]
  889. for pn in pns[1:]:
  890. imgs.append(
  891. self.page_images[pn].crop((left * ZM, 0,
  892. right * ZM,
  893. min(bottom,
  894. self.page_images[pn].size[1])
  895. ))
  896. )
  897. if 0 < ii < len(poss) - 1:
  898. positions.append((pn+self.page_from, left, right, 0, min(
  899. bottom, self.page_images[pn].size[1]) / ZM))
  900. bottom -= self.page_images[pn].size[1]
  901. if not imgs:
  902. if need_position: return None, None
  903. return
  904. height = 0
  905. for img in imgs:
  906. height += img.size[1] + GAP
  907. height = int(height)
  908. width = int(np.max([i.size[0] for i in imgs]))
  909. pic = Image.new("RGB",
  910. (width, height),
  911. (245, 245, 245))
  912. height = 0
  913. for ii, img in enumerate(imgs):
  914. if ii == 0 or ii + 1 == len(imgs):
  915. img = img.convert('RGBA')
  916. overlay = Image.new('RGBA', img.size, (0, 0, 0, 0))
  917. overlay.putalpha(128)
  918. img = Image.alpha_composite(img, overlay).convert("RGB")
  919. pic.paste(img, (0, int(height)))
  920. height += img.size[1] + GAP
  921. if need_position:
  922. return pic, positions
  923. return pic
  924. if __name__ == "__main__":
  925. pass