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

pdf_parser.py 46KB

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