選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

pdf_parser.py 51KB

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