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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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 copy
  18. import re
  19. from api.db import ParserType
  20. from rag.nlp import rag_tokenizer, tokenize, tokenize_table, add_positions, bullets_category, title_frequency, tokenize_chunks
  21. from deepdoc.parser import PdfParser, PlainParser
  22. import numpy as np
  23. class Pdf(PdfParser):
  24. def __init__(self):
  25. self.model_speciess = ParserType.PAPER.value
  26. super().__init__()
  27. def __call__(self, filename, binary=None, from_page=0,
  28. to_page=100000, zoomin=3, callback=None):
  29. from timeit import default_timer as timer
  30. start = timer()
  31. callback(msg="OCR started")
  32. self.__images__(
  33. filename if not binary else binary,
  34. zoomin,
  35. from_page,
  36. to_page,
  37. callback
  38. )
  39. callback(msg="OCR finished ({:.2f}s)".format(timer() - start))
  40. start = timer()
  41. self._layouts_rec(zoomin)
  42. callback(0.63, "Layout analysis ({:.2f}s)".format(timer() - start))
  43. logging.debug(f"layouts cost: {timer() - start}s")
  44. start = timer()
  45. self._table_transformer_job(zoomin)
  46. callback(0.68, "Table analysis ({:.2f}s)".format(timer() - start))
  47. start = timer()
  48. self._text_merge()
  49. tbls = self._extract_table_figure(True, zoomin, True, True)
  50. column_width = np.median([b["x1"] - b["x0"] for b in self.boxes])
  51. self._concat_downward()
  52. self._filter_forpages()
  53. callback(0.75, "Text merged ({:.2f}s)".format(timer() - start))
  54. # clean mess
  55. if column_width < self.page_images[0].size[0] / zoomin / 2:
  56. logging.debug("two_column................... {} {}".format(column_width,
  57. self.page_images[0].size[0] / zoomin / 2))
  58. self.boxes = self.sort_X_by_page(self.boxes, column_width / 2)
  59. for b in self.boxes:
  60. b["text"] = re.sub(r"([\t  ]|\u3000){2,}", " ", b["text"].strip())
  61. def _begin(txt):
  62. return re.match(
  63. "[0-9. 一、i]*(introduction|abstract|摘要|引言|keywords|key words|关键词|background|背景|目录|前言|contents)",
  64. txt.lower().strip())
  65. if from_page > 0:
  66. return {
  67. "title": "",
  68. "authors": "",
  69. "abstract": "",
  70. "sections": [(b["text"] + self._line_tag(b, zoomin), b.get("layoutno", "")) for b in self.boxes if
  71. re.match(r"(text|title)", b.get("layoutno", "text"))],
  72. "tables": tbls
  73. }
  74. # get title and authors
  75. title = ""
  76. authors = []
  77. i = 0
  78. while i < min(32, len(self.boxes)-1):
  79. b = self.boxes[i]
  80. i += 1
  81. if b.get("layoutno", "").find("title") >= 0:
  82. title = b["text"]
  83. if _begin(title):
  84. title = ""
  85. break
  86. for j in range(3):
  87. if _begin(self.boxes[i + j]["text"]):
  88. break
  89. authors.append(self.boxes[i + j]["text"])
  90. break
  91. break
  92. # get abstract
  93. abstr = ""
  94. i = 0
  95. while i + 1 < min(32, len(self.boxes)):
  96. b = self.boxes[i]
  97. i += 1
  98. txt = b["text"].lower().strip()
  99. if re.match("(abstract|摘要)", txt):
  100. if len(txt.split()) > 32 or len(txt) > 64:
  101. abstr = txt + self._line_tag(b, zoomin)
  102. break
  103. txt = self.boxes[i]["text"].lower().strip()
  104. if len(txt.split()) > 32 or len(txt) > 64:
  105. abstr = txt + self._line_tag(self.boxes[i], zoomin)
  106. i += 1
  107. break
  108. if not abstr:
  109. i = 0
  110. callback(
  111. 0.8, "Page {}~{}: Text merging finished".format(
  112. from_page, min(
  113. to_page, self.total_page)))
  114. for b in self.boxes:
  115. logging.debug("{} {}".format(b["text"], b.get("layoutno")))
  116. logging.debug("{}".format(tbls))
  117. return {
  118. "title": title,
  119. "authors": " ".join(authors),
  120. "abstract": abstr,
  121. "sections": [(b["text"] + self._line_tag(b, zoomin), b.get("layoutno", "")) for b in self.boxes[i:] if
  122. re.match(r"(text|title)", b.get("layoutno", "text"))],
  123. "tables": tbls
  124. }
  125. def chunk(filename, binary=None, from_page=0, to_page=100000,
  126. lang="Chinese", callback=None, **kwargs):
  127. """
  128. Only pdf is supported.
  129. The abstract of the paper will be sliced as an entire chunk, and will not be sliced partly.
  130. """
  131. parser_config = kwargs.get(
  132. "parser_config", {
  133. "chunk_token_num": 512, "delimiter": "\n!?。;!?", "layout_recognize": "DeepDOC"})
  134. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  135. if parser_config.get("layout_recognize", "DeepDOC") == "Plain Text":
  136. pdf_parser = PlainParser()
  137. paper = {
  138. "title": filename,
  139. "authors": " ",
  140. "abstract": "",
  141. "sections": pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page)[0],
  142. "tables": []
  143. }
  144. else:
  145. pdf_parser = Pdf()
  146. paper = pdf_parser(filename if not binary else binary,
  147. from_page=from_page, to_page=to_page, callback=callback)
  148. else:
  149. raise NotImplementedError("file type not supported yet(pdf supported)")
  150. doc = {"docnm_kwd": filename, "authors_tks": rag_tokenizer.tokenize(paper["authors"]),
  151. "title_tks": rag_tokenizer.tokenize(paper["title"] if paper["title"] else filename)}
  152. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  153. doc["authors_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["authors_tks"])
  154. # is it English
  155. eng = lang.lower() == "english" # pdf_parser.is_english
  156. logging.debug("It's English.....{}".format(eng))
  157. res = tokenize_table(paper["tables"], doc, eng)
  158. if paper["abstract"]:
  159. d = copy.deepcopy(doc)
  160. txt = pdf_parser.remove_tag(paper["abstract"])
  161. d["important_kwd"] = ["abstract", "总结", "概括", "summary", "summarize"]
  162. d["important_tks"] = " ".join(d["important_kwd"])
  163. d["image"], poss = pdf_parser.crop(
  164. paper["abstract"], need_position=True)
  165. add_positions(d, poss)
  166. tokenize(d, txt, eng)
  167. res.append(d)
  168. sorted_sections = paper["sections"]
  169. # set pivot using the most frequent type of title,
  170. # then merge between 2 pivot
  171. bull = bullets_category([txt for txt, _ in sorted_sections])
  172. most_level, levels = title_frequency(bull, sorted_sections)
  173. assert len(sorted_sections) == len(levels)
  174. sec_ids = []
  175. sid = 0
  176. for i, lvl in enumerate(levels):
  177. if lvl <= most_level and i > 0 and lvl != levels[i - 1]:
  178. sid += 1
  179. sec_ids.append(sid)
  180. logging.debug("{} {} {} {}".format(lvl, sorted_sections[i][0], most_level, sid))
  181. chunks = []
  182. last_sid = -2
  183. for (txt, _), sec_id in zip(sorted_sections, sec_ids):
  184. if sec_id == last_sid:
  185. if chunks:
  186. chunks[-1] += "\n" + txt
  187. continue
  188. chunks.append(txt)
  189. last_sid = sec_id
  190. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  191. return res
  192. """
  193. readed = [0] * len(paper["lines"])
  194. # find colon firstly
  195. i = 0
  196. while i + 1 < len(paper["lines"]):
  197. txt = pdf_parser.remove_tag(paper["lines"][i][0])
  198. j = i
  199. if txt.strip("\n").strip()[-1] not in "::":
  200. i += 1
  201. continue
  202. i += 1
  203. while i < len(paper["lines"]) and not paper["lines"][i][0]:
  204. i += 1
  205. if i >= len(paper["lines"]): break
  206. proj = [paper["lines"][i][0].strip()]
  207. i += 1
  208. while i < len(paper["lines"]) and paper["lines"][i][0].strip()[0] == proj[-1][0]:
  209. proj.append(paper["lines"][i])
  210. i += 1
  211. for k in range(j, i): readed[k] = True
  212. txt = txt[::-1]
  213. if eng:
  214. r = re.search(r"(.*?) ([\\.;?!]|$)", txt)
  215. txt = r.group(1)[::-1] if r else txt[::-1]
  216. else:
  217. r = re.search(r"(.*?) ([。?;!]|$)", txt)
  218. txt = r.group(1)[::-1] if r else txt[::-1]
  219. for p in proj:
  220. d = copy.deepcopy(doc)
  221. txt += "\n" + pdf_parser.remove_tag(p)
  222. d["image"], poss = pdf_parser.crop(p, need_position=True)
  223. add_positions(d, poss)
  224. tokenize(d, txt, eng)
  225. res.append(d)
  226. i = 0
  227. chunk = []
  228. tk_cnt = 0
  229. def add_chunk():
  230. nonlocal chunk, res, doc, pdf_parser, tk_cnt
  231. d = copy.deepcopy(doc)
  232. ck = "\n".join(chunk)
  233. tokenize(d, pdf_parser.remove_tag(ck), pdf_parser.is_english)
  234. d["image"], poss = pdf_parser.crop(ck, need_position=True)
  235. add_positions(d, poss)
  236. res.append(d)
  237. chunk = []
  238. tk_cnt = 0
  239. while i < len(paper["lines"]):
  240. if tk_cnt > 128:
  241. add_chunk()
  242. if readed[i]:
  243. i += 1
  244. continue
  245. readed[i] = True
  246. txt, layouts = paper["lines"][i]
  247. txt_ = pdf_parser.remove_tag(txt)
  248. i += 1
  249. cnt = num_tokens_from_string(txt_)
  250. if any([
  251. layouts.find("title") >= 0 and chunk,
  252. cnt + tk_cnt > 128 and tk_cnt > 32,
  253. ]):
  254. add_chunk()
  255. chunk = [txt]
  256. tk_cnt = cnt
  257. else:
  258. chunk.append(txt)
  259. tk_cnt += cnt
  260. if chunk: add_chunk()
  261. for i, d in enumerate(res):
  262. print(d)
  263. # d["image"].save(f"./logs/{i}.jpg")
  264. return res
  265. """
  266. if __name__ == "__main__":
  267. import sys
  268. def dummy(prog=None, msg=""):
  269. pass
  270. chunk(sys.argv[1], callback=dummy)