Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

paper.py 11KB

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