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.

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