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

pdf_parser.py 41KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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") or b.get("layout_type", "") in ["table", "figure", "equation"]:
  284. i += 1
  285. continue
  286. if abs(self._y_dis(b, b_)) < self.mean_height[bxs[i]["page_number"] - 1] / 3:
  287. # merge
  288. bxs[i]["x1"] = b_["x1"]
  289. bxs[i]["top"] = (b["top"] + b_["top"]) / 2
  290. bxs[i]["bottom"] = (b["bottom"] + b_["bottom"]) / 2
  291. bxs[i]["text"] += b_["text"]
  292. bxs.pop(i + 1)
  293. continue
  294. i += 1
  295. continue
  296. dis_thr = 1
  297. dis = b["x1"] - b_["x0"]
  298. if b.get("layout_type", "") != "text" or b_.get(
  299. "layout_type", "") != "text":
  300. if end_with(b, ",") or start_with(b_, "(,"):
  301. dis_thr = -8
  302. else:
  303. i += 1
  304. continue
  305. if abs(self._y_dis(b, b_)) < self.mean_height[bxs[i]["page_number"] - 1] / 5 \
  306. and dis >= dis_thr and b["x1"] < b_["x1"]:
  307. # merge
  308. bxs[i]["x1"] = b_["x1"]
  309. bxs[i]["top"] = (b["top"] + b_["top"]) / 2
  310. bxs[i]["bottom"] = (b["bottom"] + b_["bottom"]) / 2
  311. bxs[i]["text"] += b_["text"]
  312. bxs.pop(i + 1)
  313. continue
  314. i += 1
  315. self.boxes = bxs
  316. def _naive_vertical_merge(self):
  317. bxs = Recognizer.sort_Y_firstly(self.boxes, np.median(self.mean_height) / 3)
  318. i = 0
  319. while i + 1 < len(bxs):
  320. b = bxs[i]
  321. b_ = bxs[i + 1]
  322. if b["page_number"] < b_["page_number"] and re.match(r"[0-9 •一—-]+$", b["text"]):
  323. bxs.pop(i)
  324. continue
  325. if not b["text"].strip():
  326. bxs.pop(i)
  327. continue
  328. concatting_feats = [
  329. b["text"].strip()[-1] in ",;:'\",、‘“;:-",
  330. len(b["text"].strip()) > 1 and b["text"].strip()[-2] in ",;:'\",‘“、;:",
  331. b["text"].strip()[0] in "。;?!?”)),,、:",
  332. ]
  333. # features for not concating
  334. feats = [
  335. b.get("layoutno", 0) != b.get("layoutno", 0),
  336. b["text"].strip()[-1] in "。?!?",
  337. self.is_english and b["text"].strip()[-1] in ".!?",
  338. b["page_number"] == b_["page_number"] and b_["top"] - \
  339. b["bottom"] > self.mean_height[b["page_number"] - 1] * 1.5,
  340. b["page_number"] < b_["page_number"] and abs(
  341. b["x0"] - b_["x0"]) > self.mean_width[b["page_number"] - 1] * 4
  342. ]
  343. if any(feats) and not any(concatting_feats):
  344. i += 1
  345. continue
  346. # merge up and down
  347. b["bottom"] = b_["bottom"]
  348. b["text"] += b_["text"]
  349. b["x0"] = min(b["x0"], b_["x0"])
  350. b["x1"] = max(b["x1"], b_["x1"])
  351. bxs.pop(i + 1)
  352. self.boxes = bxs
  353. def _concat_downward(self, concat_between_pages=True):
  354. # count boxes in the same row as a feature
  355. for i in range(len(self.boxes)):
  356. mh = self.mean_height[self.boxes[i]["page_number"] - 1]
  357. self.boxes[i]["in_row"] = 0
  358. j = max(0, i - 12)
  359. while j < min(i + 12, len(self.boxes)):
  360. if j == i:
  361. j += 1
  362. continue
  363. ydis = self._y_dis(self.boxes[i], self.boxes[j]) / mh
  364. if abs(ydis) < 1:
  365. self.boxes[i]["in_row"] += 1
  366. elif ydis > 0:
  367. break
  368. j += 1
  369. # concat between rows
  370. boxes = deepcopy(self.boxes)
  371. blocks = []
  372. while boxes:
  373. chunks = []
  374. def dfs(up, dp):
  375. chunks.append(up)
  376. i = dp
  377. while i < min(dp + 12, len(boxes)):
  378. ydis = self._y_dis(up, boxes[i])
  379. smpg = up["page_number"] == boxes[i]["page_number"]
  380. mh = self.mean_height[up["page_number"] - 1]
  381. mw = self.mean_width[up["page_number"] - 1]
  382. if smpg and ydis > mh * 4:
  383. break
  384. if not smpg and ydis > mh * 16:
  385. break
  386. down = boxes[i]
  387. if not concat_between_pages and down["page_number"] > up["page_number"]:
  388. break
  389. if up.get("R", "") != down.get(
  390. "R", "") and up["text"][-1] != ",":
  391. i += 1
  392. continue
  393. if re.match(r"[0-9]{2,3}/[0-9]{3}$", up["text"]) \
  394. or re.match(r"[0-9]{2,3}/[0-9]{3}$", down["text"]):
  395. i += 1
  396. continue
  397. if not down["text"].strip():
  398. i += 1
  399. continue
  400. if up["x1"] < down["x0"] - 10 * \
  401. mw or up["x0"] > down["x1"] + 10 * mw:
  402. i += 1
  403. continue
  404. if i - dp < 5 and up.get("layout_type") == "text":
  405. if up.get("layoutno", "1") == down.get(
  406. "layoutno", "2"):
  407. dfs(down, i + 1)
  408. boxes.pop(i)
  409. return
  410. i += 1
  411. continue
  412. fea = self._updown_concat_features(up, down)
  413. if self.updown_cnt_mdl.predict(
  414. xgb.DMatrix([fea]))[0] <= 0.5:
  415. i += 1
  416. continue
  417. dfs(down, i + 1)
  418. boxes.pop(i)
  419. return
  420. dfs(boxes[0], 1)
  421. boxes.pop(0)
  422. if chunks:
  423. blocks.append(chunks)
  424. # concat within each block
  425. boxes = []
  426. for b in blocks:
  427. if len(b) == 1:
  428. boxes.append(b[0])
  429. continue
  430. t = b[0]
  431. for c in b[1:]:
  432. t["text"] = t["text"].strip()
  433. c["text"] = c["text"].strip()
  434. if not c["text"]:
  435. continue
  436. if t["text"] and re.match(
  437. r"[0-9\.a-zA-Z]+$", t["text"][-1] + c["text"][-1]):
  438. t["text"] += " "
  439. t["text"] += c["text"]
  440. t["x0"] = min(t["x0"], c["x0"])
  441. t["x1"] = max(t["x1"], c["x1"])
  442. t["page_number"] = min(t["page_number"], c["page_number"])
  443. t["bottom"] = c["bottom"]
  444. if not t["layout_type"] \
  445. and c["layout_type"]:
  446. t["layout_type"] = c["layout_type"]
  447. boxes.append(t)
  448. self.boxes = Recognizer.sort_Y_firstly(boxes, 0)
  449. def _filter_forpages(self):
  450. if not self.boxes:
  451. return
  452. findit = False
  453. i = 0
  454. while i < len(self.boxes):
  455. if not re.match(r"(contents|目录|目次|table of contents|致谢|acknowledge)$", re.sub(r"( | |\u3000)+", "", self.boxes[i]["text"].lower())):
  456. i += 1
  457. continue
  458. findit = True
  459. eng = re.match(r"[0-9a-zA-Z :'.-]{5,}", self.boxes[i]["text"].strip())
  460. self.boxes.pop(i)
  461. if i >= len(self.boxes): break
  462. prefix = self.boxes[i]["text"].strip()[:3] if not eng else " ".join(self.boxes[i]["text"].strip().split(" ")[:2])
  463. while not prefix:
  464. self.boxes.pop(i)
  465. if i >= len(self.boxes): break
  466. prefix = self.boxes[i]["text"].strip()[:3] if not eng else " ".join(self.boxes[i]["text"].strip().split(" ")[:2])
  467. self.boxes.pop(i)
  468. if i >= len(self.boxes) or not prefix: break
  469. for j in range(i, min(i + 128, len(self.boxes))):
  470. if not re.match(prefix, self.boxes[j]["text"]):
  471. continue
  472. for k in range(i, j): self.boxes.pop(i)
  473. break
  474. if findit:return
  475. page_dirty = [0] * len(self.page_images)
  476. for b in self.boxes:
  477. if re.search(r"(··|··|··)", b["text"]):
  478. page_dirty[b["page_number"]-1] += 1
  479. page_dirty = set([i+1 for i, t in enumerate(page_dirty) if t > 3])
  480. if not page_dirty: return
  481. i = 0
  482. while i < len(self.boxes):
  483. if self.boxes[i]["page_number"] in page_dirty:
  484. self.boxes.pop(i)
  485. continue
  486. i += 1
  487. def _merge_with_same_bullet(self):
  488. i = 0
  489. while i + 1 < len(self.boxes):
  490. b = self.boxes[i]
  491. b_ = self.boxes[i + 1]
  492. if not b["text"].strip():
  493. self.boxes.pop(i)
  494. continue
  495. if not b_["text"].strip():
  496. self.boxes.pop(i+1)
  497. continue
  498. if b["text"].strip()[0] != b_["text"].strip()[0] \
  499. or b["text"].strip()[0].lower() in set("qwertyuopasdfghjklzxcvbnm") \
  500. or huqie.is_chinese(b["text"].strip()[0]) \
  501. or b["top"] > b_["bottom"]:
  502. i += 1
  503. continue
  504. b_["text"] = b["text"] + "\n" + b_["text"]
  505. b_["x0"] = min(b["x0"], b_["x0"])
  506. b_["x1"] = max(b["x1"], b_["x1"])
  507. b_["top"] = b["top"]
  508. self.boxes.pop(i)
  509. def _extract_table_figure(self, need_image, ZM, return_html, need_position):
  510. tables = {}
  511. figures = {}
  512. # extract figure and table boxes
  513. i = 0
  514. lst_lout_no = ""
  515. nomerge_lout_no = []
  516. while i < len(self.boxes):
  517. if "layoutno" not in self.boxes[i]:
  518. i += 1
  519. continue
  520. lout_no = str(self.boxes[i]["page_number"]) + \
  521. "-" + str(self.boxes[i]["layoutno"])
  522. if TableStructureRecognizer.is_caption(self.boxes[i]) or self.boxes[i]["layout_type"] in ["table caption", "title",
  523. "figure caption", "reference"]:
  524. nomerge_lout_no.append(lst_lout_no)
  525. if self.boxes[i]["layout_type"] == "table":
  526. if re.match(r"(数据|资料|图表)*来源[:: ]", self.boxes[i]["text"]):
  527. self.boxes.pop(i)
  528. continue
  529. if lout_no not in tables:
  530. tables[lout_no] = []
  531. tables[lout_no].append(self.boxes[i])
  532. self.boxes.pop(i)
  533. lst_lout_no = lout_no
  534. continue
  535. if need_image and self.boxes[i]["layout_type"] == "figure":
  536. if re.match(r"(数据|资料|图表)*来源[:: ]", self.boxes[i]["text"]):
  537. self.boxes.pop(i)
  538. continue
  539. if lout_no not in figures:
  540. figures[lout_no] = []
  541. figures[lout_no].append(self.boxes[i])
  542. self.boxes.pop(i)
  543. lst_lout_no = lout_no
  544. continue
  545. i += 1
  546. # merge table on different pages
  547. nomerge_lout_no = set(nomerge_lout_no)
  548. tbls = sorted([(k, bxs) for k, bxs in tables.items()],
  549. key=lambda x: (x[1][0]["top"], x[1][0]["x0"]))
  550. i = len(tbls) - 1
  551. while i - 1 >= 0:
  552. k0, bxs0 = tbls[i - 1]
  553. k, bxs = tbls[i]
  554. i -= 1
  555. if k0 in nomerge_lout_no:
  556. continue
  557. if bxs[0]["page_number"] == bxs0[0]["page_number"]:
  558. continue
  559. if bxs[0]["page_number"] - bxs0[0]["page_number"] > 1:
  560. continue
  561. mh = self.mean_height[bxs[0]["page_number"] - 1]
  562. if self._y_dis(bxs0[-1], bxs[0]) > mh * 23:
  563. continue
  564. tables[k0].extend(tables[k])
  565. del tables[k]
  566. def x_overlapped(a, b):
  567. return not any([a["x1"] < b["x0"], a["x0"] > b["x1"]])
  568. # find captions and pop out
  569. i = 0
  570. while i < len(self.boxes):
  571. c = self.boxes[i]
  572. # mh = self.mean_height[c["page_number"]-1]
  573. if not TableStructureRecognizer.is_caption(c):
  574. i += 1
  575. continue
  576. # find the nearest layouts
  577. def nearest(tbls):
  578. nonlocal c
  579. mink = ""
  580. minv = 1000000000
  581. for k, bxs in tbls.items():
  582. for b in bxs[:10]:
  583. if b.get("layout_type", "").find("caption") >= 0:
  584. continue
  585. y_dis = self._y_dis(c, b)
  586. x_dis = self._x_dis(
  587. c, b) if not x_overlapped(
  588. c, b) else 0
  589. dis = y_dis * y_dis + x_dis * x_dis
  590. if dis < minv:
  591. mink = k
  592. minv = dis
  593. return mink, minv
  594. tk, tv = nearest(tables)
  595. fk, fv = nearest(figures)
  596. #if min(tv, fv) > 2000:
  597. # i += 1
  598. # continue
  599. if tv < fv:
  600. tables[tk].insert(0, c)
  601. logging.debug(
  602. "TABLE:" +
  603. self.boxes[i]["text"] +
  604. "; Cap: " +
  605. tk)
  606. else:
  607. figures[fk].insert(0, c)
  608. logging.debug(
  609. "FIGURE:" +
  610. self.boxes[i]["text"] +
  611. "; Cap: " +
  612. tk)
  613. self.boxes.pop(i)
  614. res = []
  615. positions = []
  616. def cropout(bxs, ltype, poss):
  617. nonlocal ZM
  618. pn = set([b["page_number"] - 1 for b in bxs])
  619. if len(pn) < 2:
  620. pn = list(pn)[0]
  621. ht = self.page_cum_height[pn]
  622. b = {
  623. "x0": np.min([b["x0"] for b in bxs]),
  624. "top": np.min([b["top"] for b in bxs]) - ht,
  625. "x1": np.max([b["x1"] for b in bxs]),
  626. "bottom": np.max([b["bottom"] for b in bxs]) - ht
  627. }
  628. louts = [l for l in self.page_layout[pn] if l["type"] == ltype]
  629. ii = Recognizer.find_overlapped(b, louts, naive=True)
  630. if ii is not None:
  631. b = louts[ii]
  632. else:
  633. logging.warn(
  634. f"Missing layout match: {pn + 1},%s" %
  635. (bxs[0].get(
  636. "layoutno", "")))
  637. left, top, right, bott = b["x0"], b["top"], b["x1"], b["bottom"]
  638. poss.append((pn+self.page_from, left, right, top, bott))
  639. return self.page_images[pn] \
  640. .crop((left * ZM, top * ZM,
  641. right * ZM, bott * ZM))
  642. pn = {}
  643. for b in bxs:
  644. p = b["page_number"] - 1
  645. if p not in pn:
  646. pn[p] = []
  647. pn[p].append(b)
  648. pn = sorted(pn.items(), key=lambda x: x[0])
  649. imgs = [cropout(arr, ltype, poss) for p, arr in pn]
  650. pic = Image.new("RGB",
  651. (int(np.max([i.size[0] for i in imgs])),
  652. int(np.sum([m.size[1] for m in imgs]))),
  653. (245, 245, 245))
  654. height = 0
  655. for img in imgs:
  656. pic.paste(img, (0, int(height)))
  657. height += img.size[1]
  658. return pic
  659. # crop figure out and add caption
  660. for k, bxs in figures.items():
  661. txt = "\n".join([b["text"] for b in bxs])
  662. if not txt:
  663. continue
  664. poss = []
  665. res.append(
  666. (cropout(
  667. bxs,
  668. "figure", poss),
  669. [txt]))
  670. positions.append(poss)
  671. for k, bxs in tables.items():
  672. if not bxs:
  673. continue
  674. bxs = Recognizer.sort_Y_firstly(bxs, np.mean([(b["bottom"]-b["top"])/2 for b in bxs]))
  675. poss = []
  676. res.append((cropout(bxs, "table", poss),
  677. self.tbl_det.construct_table(bxs, html=return_html, is_english=self.is_english)))
  678. positions.append(poss)
  679. assert len(positions) == len(res)
  680. if need_position: return list(zip(res, positions))
  681. return res
  682. def proj_match(self, line):
  683. if len(line) <= 2:
  684. return
  685. if re.match(r"[0-9 ().,%%+/-]+$", line):
  686. return False
  687. for p, j in [
  688. (r"第[零一二三四五六七八九十百]+章", 1),
  689. (r"第[零一二三四五六七八九十百]+[条节]", 2),
  690. (r"[零一二三四五六七八九十百]+[、  ]", 3),
  691. (r"[\((][零一二三四五六七八九十百]+[)\)]", 4),
  692. (r"[0-9]+(、|\.[  ]|\.[^0-9])", 5),
  693. (r"[0-9]+\.[0-9]+(、|[.  ]|[^0-9])", 6),
  694. (r"[0-9]+\.[0-9]+\.[0-9]+(、|[  ]|[^0-9])", 7),
  695. (r"[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+(、|[  ]|[^0-9])", 8),
  696. (r".{,48}[::??]$", 9),
  697. (r"[0-9]+)", 10),
  698. (r"[\((][0-9]+[)\)]", 11),
  699. (r"[零一二三四五六七八九十百]+是", 12),
  700. (r"[⚫•➢✓]", 12)
  701. ]:
  702. if re.match(p, line):
  703. return j
  704. return
  705. def _line_tag(self, bx, ZM):
  706. pn = [bx["page_number"]]
  707. top = bx["top"] - self.page_cum_height[pn[0] - 1]
  708. bott = bx["bottom"] - self.page_cum_height[pn[0] - 1]
  709. while bott * ZM > self.page_images[pn[-1] - 1].size[1]:
  710. bott -= self.page_images[pn[-1] - 1].size[1] / ZM
  711. pn.append(pn[-1] + 1)
  712. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  713. .format("-".join([str(p) for p in pn]),
  714. bx["x0"], bx["x1"], top, bott)
  715. def __filterout_scraps(self, boxes, ZM):
  716. def width(b):
  717. return b["x1"] - b["x0"]
  718. def height(b):
  719. return b["bottom"] - b["top"]
  720. def usefull(b):
  721. if b.get("layout_type"):
  722. return True
  723. if width(
  724. b) > self.page_images[b["page_number"] - 1].size[0] / ZM / 3:
  725. return True
  726. if b["bottom"] - b["top"] > self.mean_height[b["page_number"] - 1]:
  727. return True
  728. return False
  729. res = []
  730. while boxes:
  731. lines = []
  732. widths = []
  733. pw = self.page_images[boxes[0]["page_number"] - 1].size[0] / ZM
  734. mh = self.mean_height[boxes[0]["page_number"] - 1]
  735. mj = self.proj_match(
  736. boxes[0]["text"]) or boxes[0].get(
  737. "layout_type",
  738. "") == "title"
  739. def dfs(line, st):
  740. nonlocal mh, pw, lines, widths
  741. lines.append(line)
  742. widths.append(width(line))
  743. width_mean = np.mean(widths)
  744. mmj = self.proj_match(
  745. line["text"]) or line.get(
  746. "layout_type",
  747. "") == "title"
  748. for i in range(st + 1, min(st + 20, len(boxes))):
  749. if (boxes[i]["page_number"] - line["page_number"]) > 0:
  750. break
  751. if not mmj and self._y_dis(
  752. line, boxes[i]) >= 3 * mh and height(line) < 1.5 * mh:
  753. break
  754. if not usefull(boxes[i]):
  755. continue
  756. if mmj or \
  757. (self._x_dis(boxes[i], line) < pw / 10): \
  758. # and abs(width(boxes[i])-width_mean)/max(width(boxes[i]),width_mean)<0.5):
  759. # concat following
  760. dfs(boxes[i], i)
  761. boxes.pop(i)
  762. break
  763. try:
  764. if usefull(boxes[0]):
  765. dfs(boxes[0], 0)
  766. else:
  767. logging.debug("WASTE: " + boxes[0]["text"])
  768. except Exception as e:
  769. pass
  770. boxes.pop(0)
  771. mw = np.mean(widths)
  772. if mj or mw / pw >= 0.35 or mw > 200:
  773. res.append("\n".join([c["text"] + self._line_tag(c, ZM) for c in lines]))
  774. else:
  775. logging.debug("REMOVED: " +
  776. "<<".join([c["text"] for c in lines]))
  777. return "\n\n".join(res)
  778. @staticmethod
  779. def total_page_number(fnm, binary=None):
  780. try:
  781. pdf = pdfplumber.open(fnm) if not binary else pdfplumber.open(BytesIO(binary))
  782. return len(pdf.pages)
  783. except Exception as e:
  784. pdf = fitz.open(fnm) if not binary else fitz.open(stream=fnm, filetype="pdf")
  785. return len(pdf)
  786. def __images__(self, fnm, zoomin=3, page_from=0, page_to=299, callback=None):
  787. self.lefted_chars = []
  788. self.mean_height = []
  789. self.mean_width = []
  790. self.boxes = []
  791. self.garbages = {}
  792. self.page_cum_height = [0]
  793. self.page_layout = []
  794. self.page_from = page_from
  795. try:
  796. self.pdf = pdfplumber.open(fnm) if isinstance(fnm, str) else pdfplumber.open(BytesIO(fnm))
  797. self.page_images = [p.to_image(resolution=72 * zoomin).annotated for i, p in
  798. enumerate(self.pdf.pages[page_from:page_to])]
  799. self.page_chars = [[c for c in page.chars if self._has_color(c)] for page in self.pdf.pages[page_from:page_to]]
  800. self.total_page = len(self.pdf.pages)
  801. except Exception as e:
  802. self.pdf = fitz.open(fnm) if isinstance(fnm, str) else fitz.open(stream=fnm, filetype="pdf")
  803. self.page_images = []
  804. self.page_chars = []
  805. mat = fitz.Matrix(zoomin, zoomin)
  806. self.total_page = len(self.pdf)
  807. for i, page in enumerate(self.pdf):
  808. if i < page_from:continue
  809. if i >= page_to:break
  810. pix = page.get_pixmap(matrix=mat)
  811. img = Image.frombytes("RGB", [pix.width, pix.height],
  812. pix.samples)
  813. self.page_images.append(img)
  814. self.page_chars.append([])
  815. logging.info("Images converted.")
  816. 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))]
  817. if sum([1 if e else 0 for e in self.is_english]) > len(self.page_images) / 2:
  818. self.is_english = True
  819. else:
  820. self.is_english = False
  821. for i, img in enumerate(self.page_images):
  822. chars = self.page_chars[i] if not self.is_english else []
  823. self.mean_height.append(
  824. np.median(sorted([c["height"] for c in chars])) if chars else 0
  825. )
  826. self.mean_width.append(
  827. np.median(sorted([c["width"] for c in chars])) if chars else 8
  828. )
  829. self.page_cum_height.append(img.size[1] / zoomin)
  830. j = 0
  831. while j + 1 < len(chars):
  832. if chars[j]["text"] and chars[j + 1]["text"] \
  833. and re.match(r"[0-9a-zA-Z,.:;!%]+", chars[j]["text"] + chars[j + 1]["text"]) \
  834. and chars[j + 1]["x0"] - chars[j]["x1"] >= min(chars[j + 1]["width"],
  835. chars[j]["width"]) / 2:
  836. chars[j]["text"] += " "
  837. j += 1
  838. # if i > 0:
  839. # if not chars:
  840. # self.page_cum_height.append(img.size[1] / zoomin)
  841. # else:
  842. # self.page_cum_height.append(
  843. # np.max([c["bottom"] for c in chars]))
  844. self.__ocr(i + 1, img, chars, zoomin)
  845. if callback: callback(prog=(i+1)*0.6/len(self.page_images), msg="")
  846. if not self.is_english and not any([c for c in self.page_chars]) and self.boxes:
  847. bxes = [b for bxs in self.boxes for b in bxs]
  848. 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)))]))
  849. logging.info("Is it English:", self.is_english)
  850. self.page_cum_height = np.cumsum(self.page_cum_height)
  851. assert len(self.page_cum_height) == len(self.page_images) + 1
  852. def __call__(self, fnm, need_image=True, zoomin=3, return_html=False):
  853. self.__images__(fnm, zoomin)
  854. self._layouts_rec(zoomin)
  855. self._table_transformer_job(zoomin)
  856. self._text_merge()
  857. self._concat_downward()
  858. self._filter_forpages()
  859. tbls = self._extract_table_figure(need_image, zoomin, return_html, False)
  860. return self.__filterout_scraps(deepcopy(self.boxes), zoomin), tbls
  861. def remove_tag(self, txt):
  862. return re.sub(r"@@[\t0-9.-]+?##", "", txt)
  863. def crop(self, text, ZM=3, need_position=False):
  864. imgs = []
  865. poss = []
  866. for tag in re.findall(r"@@[0-9-]+\t[0-9.\t]+##", text):
  867. pn, left, right, top, bottom = tag.strip(
  868. "#").strip("@").split("\t")
  869. left, right, top, bottom = float(left), float(
  870. right), float(top), float(bottom)
  871. poss.append(([int(p) - 1 for p in pn.split("-")], left, right, top, bottom))
  872. if not poss:
  873. if need_position: return None, None
  874. return
  875. max_width = np.max([right-left for (_, left, right, _, _) in poss])
  876. GAP = 6
  877. pos = poss[0]
  878. poss.insert(0, ([pos[0][0]], pos[1], pos[2], max(0, pos[3]-120), max(pos[3]-GAP, 0)))
  879. pos = poss[-1]
  880. 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)))
  881. positions = []
  882. for ii, (pns, left, right, top, bottom) in enumerate(poss):
  883. right = left + max_width
  884. bottom *= ZM
  885. for pn in pns[1:]:
  886. bottom += self.page_images[pn - 1].size[1]
  887. imgs.append(
  888. self.page_images[pns[0]].crop((left * ZM, top * ZM,
  889. right *
  890. ZM, min(
  891. bottom, self.page_images[pns[0]].size[1])
  892. ))
  893. )
  894. if 0 < ii < len(poss)-1:
  895. positions.append((pns[0]+self.page_from, left, right, top, min(
  896. bottom, self.page_images[pns[0]].size[1])/ZM))
  897. bottom -= self.page_images[pns[0]].size[1]
  898. for pn in pns[1:]:
  899. imgs.append(
  900. self.page_images[pn].crop((left * ZM, 0,
  901. right * ZM,
  902. min(bottom,
  903. self.page_images[pn].size[1])
  904. ))
  905. )
  906. if 0 < ii < len(poss) - 1:
  907. positions.append((pn+self.page_from, left, right, 0, min(
  908. bottom, self.page_images[pn].size[1]) / ZM))
  909. bottom -= self.page_images[pn].size[1]
  910. if not imgs:
  911. if need_position: return None, None
  912. return
  913. height = 0
  914. for img in imgs:
  915. height += img.size[1] + GAP
  916. height = int(height)
  917. width = int(np.max([i.size[0] for i in imgs]))
  918. pic = Image.new("RGB",
  919. (width, height),
  920. (245, 245, 245))
  921. height = 0
  922. for ii, img in enumerate(imgs):
  923. if ii == 0 or ii + 1 == len(imgs):
  924. img = img.convert('RGBA')
  925. overlay = Image.new('RGBA', img.size, (0, 0, 0, 0))
  926. overlay.putalpha(128)
  927. img = Image.alpha_composite(img, overlay).convert("RGB")
  928. pic.paste(img, (0, int(height)))
  929. height += img.size[1] + GAP
  930. if need_position:
  931. return pic, positions
  932. return pic
  933. if __name__ == "__main__":
  934. pass