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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  132. if kwargs.get("parser_config", {}).get("layout_recognize", "DeepDOC") == "Plain Text":
  133. pdf_parser = PlainParser()
  134. paper = {
  135. "title": filename,
  136. "authors": " ",
  137. "abstract": "",
  138. "sections": pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page)[0],
  139. "tables": []
  140. }
  141. else:
  142. pdf_parser = Pdf()
  143. paper = pdf_parser(filename if not binary else binary,
  144. from_page=from_page, to_page=to_page, callback=callback)
  145. else:
  146. raise NotImplementedError("file type not supported yet(pdf supported)")
  147. doc = {"docnm_kwd": filename, "authors_tks": rag_tokenizer.tokenize(paper["authors"]),
  148. "title_tks": rag_tokenizer.tokenize(paper["title"] if paper["title"] else filename)}
  149. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  150. doc["authors_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["authors_tks"])
  151. # is it English
  152. eng = lang.lower() == "english" # pdf_parser.is_english
  153. logging.debug("It's English.....{}".format(eng))
  154. res = tokenize_table(paper["tables"], doc, eng)
  155. if paper["abstract"]:
  156. d = copy.deepcopy(doc)
  157. txt = pdf_parser.remove_tag(paper["abstract"])
  158. d["important_kwd"] = ["abstract", "总结", "概括", "summary", "summarize"]
  159. d["important_tks"] = " ".join(d["important_kwd"])
  160. d["image"], poss = pdf_parser.crop(
  161. paper["abstract"], need_position=True)
  162. add_positions(d, poss)
  163. tokenize(d, txt, eng)
  164. res.append(d)
  165. sorted_sections = paper["sections"]
  166. # set pivot using the most frequent type of title,
  167. # then merge between 2 pivot
  168. bull = bullets_category([txt for txt, _ in sorted_sections])
  169. most_level, levels = title_frequency(bull, sorted_sections)
  170. assert len(sorted_sections) == len(levels)
  171. sec_ids = []
  172. sid = 0
  173. for i, lvl in enumerate(levels):
  174. if lvl <= most_level and i > 0 and lvl != levels[i - 1]:
  175. sid += 1
  176. sec_ids.append(sid)
  177. logging.debug("{} {} {} {}".format(lvl, sorted_sections[i][0], most_level, sid))
  178. chunks = []
  179. last_sid = -2
  180. for (txt, _), sec_id in zip(sorted_sections, sec_ids):
  181. if sec_id == last_sid:
  182. if chunks:
  183. chunks[-1] += "\n" + txt
  184. continue
  185. chunks.append(txt)
  186. last_sid = sec_id
  187. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  188. return res
  189. """
  190. readed = [0] * len(paper["lines"])
  191. # find colon firstly
  192. i = 0
  193. while i + 1 < len(paper["lines"]):
  194. txt = pdf_parser.remove_tag(paper["lines"][i][0])
  195. j = i
  196. if txt.strip("\n").strip()[-1] not in "::":
  197. i += 1
  198. continue
  199. i += 1
  200. while i < len(paper["lines"]) and not paper["lines"][i][0]:
  201. i += 1
  202. if i >= len(paper["lines"]): break
  203. proj = [paper["lines"][i][0].strip()]
  204. i += 1
  205. while i < len(paper["lines"]) and paper["lines"][i][0].strip()[0] == proj[-1][0]:
  206. proj.append(paper["lines"][i])
  207. i += 1
  208. for k in range(j, i): readed[k] = True
  209. txt = txt[::-1]
  210. if eng:
  211. r = re.search(r"(.*?) ([\\.;?!]|$)", txt)
  212. txt = r.group(1)[::-1] if r else txt[::-1]
  213. else:
  214. r = re.search(r"(.*?) ([。?;!]|$)", txt)
  215. txt = r.group(1)[::-1] if r else txt[::-1]
  216. for p in proj:
  217. d = copy.deepcopy(doc)
  218. txt += "\n" + pdf_parser.remove_tag(p)
  219. d["image"], poss = pdf_parser.crop(p, need_position=True)
  220. add_positions(d, poss)
  221. tokenize(d, txt, eng)
  222. res.append(d)
  223. i = 0
  224. chunk = []
  225. tk_cnt = 0
  226. def add_chunk():
  227. nonlocal chunk, res, doc, pdf_parser, tk_cnt
  228. d = copy.deepcopy(doc)
  229. ck = "\n".join(chunk)
  230. tokenize(d, pdf_parser.remove_tag(ck), pdf_parser.is_english)
  231. d["image"], poss = pdf_parser.crop(ck, need_position=True)
  232. add_positions(d, poss)
  233. res.append(d)
  234. chunk = []
  235. tk_cnt = 0
  236. while i < len(paper["lines"]):
  237. if tk_cnt > 128:
  238. add_chunk()
  239. if readed[i]:
  240. i += 1
  241. continue
  242. readed[i] = True
  243. txt, layouts = paper["lines"][i]
  244. txt_ = pdf_parser.remove_tag(txt)
  245. i += 1
  246. cnt = num_tokens_from_string(txt_)
  247. if any([
  248. layouts.find("title") >= 0 and chunk,
  249. cnt + tk_cnt > 128 and tk_cnt > 32,
  250. ]):
  251. add_chunk()
  252. chunk = [txt]
  253. tk_cnt = cnt
  254. else:
  255. chunk.append(txt)
  256. tk_cnt += cnt
  257. if chunk: add_chunk()
  258. for i, d in enumerate(res):
  259. print(d)
  260. # d["image"].save(f"./logs/{i}.jpg")
  261. return res
  262. """
  263. if __name__ == "__main__":
  264. import sys
  265. def dummy(prog=None, msg=""):
  266. pass
  267. chunk(sys.argv[1], callback=dummy)