Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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