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

pdf_parser.py 46KB

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