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.

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