You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pdf_parser.py 51KB

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