Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

pdf_parser.py 46KB

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