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

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