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.

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