Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 rag_tokenizer, tokenize, tokenize_table, add_positions, bullets_category, title_frequency, tokenize_chunks
  18. from deepdoc.parser import PdfParser, PlainParser
  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("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. def _begin(txt):
  57. return re.match(
  58. "[0-9. 一、i]*(introduction|abstract|摘要|引言|keywords|key words|关键词|background|背景|目录|前言|contents)",
  59. txt.lower().strip())
  60. if from_page > 0:
  61. return {
  62. "title": "",
  63. "authors": "",
  64. "abstract": "",
  65. "sections": [(b["text"] + self._line_tag(b, zoomin), b.get("layoutno", "")) for b in self.boxes if
  66. re.match(r"(text|title)", b.get("layoutno", "text"))],
  67. "tables": tbls
  68. }
  69. # get title and authors
  70. title = ""
  71. authors = []
  72. i = 0
  73. while i < min(32, len(self.boxes)-1):
  74. b = self.boxes[i]
  75. i += 1
  76. if b.get("layoutno", "").find("title") >= 0:
  77. title = b["text"]
  78. if _begin(title):
  79. title = ""
  80. break
  81. for j in range(3):
  82. if _begin(self.boxes[i + j]["text"]):
  83. break
  84. authors.append(self.boxes[i + j]["text"])
  85. break
  86. break
  87. # get abstract
  88. abstr = ""
  89. i = 0
  90. while i + 1 < min(32, len(self.boxes)):
  91. b = self.boxes[i]
  92. i += 1
  93. txt = b["text"].lower().strip()
  94. if re.match("(abstract|摘要)", txt):
  95. if len(txt.split(" ")) > 32 or len(txt) > 64:
  96. abstr = txt + self._line_tag(b, zoomin)
  97. break
  98. txt = self.boxes[i]["text"].lower().strip()
  99. if len(txt.split(" ")) > 32 or len(txt) > 64:
  100. abstr = txt + self._line_tag(self.boxes[i], zoomin)
  101. i += 1
  102. break
  103. if not abstr:
  104. i = 0
  105. callback(
  106. 0.8, "Page {}~{}: Text merging finished".format(
  107. from_page, min(
  108. to_page, self.total_page)))
  109. for b in self.boxes:
  110. print(b["text"], b.get("layoutno"))
  111. print(tbls)
  112. return {
  113. "title": title,
  114. "authors": " ".join(authors),
  115. "abstract": abstr,
  116. "sections": [(b["text"] + self._line_tag(b, zoomin), b.get("layoutno", "")) for b in self.boxes[i:] if
  117. re.match(r"(text|title)", b.get("layoutno", "text"))],
  118. "tables": tbls
  119. }
  120. def chunk(filename, binary=None, from_page=0, to_page=100000,
  121. lang="Chinese", callback=None, **kwargs):
  122. """
  123. Only pdf is supported.
  124. The abstract of the paper will be sliced as an entire chunk, and will not be sliced partly.
  125. """
  126. pdf_parser = None
  127. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  128. if not kwargs.get("parser_config", {}).get("layout_recognize", True):
  129. pdf_parser = PlainParser()
  130. paper = {
  131. "title": filename,
  132. "authors": " ",
  133. "abstract": "",
  134. "sections": pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page)[0],
  135. "tables": []
  136. }
  137. else:
  138. pdf_parser = Pdf()
  139. paper = pdf_parser(filename if not binary else binary,
  140. from_page=from_page, to_page=to_page, callback=callback)
  141. else:
  142. raise NotImplementedError("file type not supported yet(pdf supported)")
  143. doc = {"docnm_kwd": filename, "authors_tks": rag_tokenizer.tokenize(paper["authors"]),
  144. "title_tks": rag_tokenizer.tokenize(paper["title"] if paper["title"] else filename)}
  145. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  146. doc["authors_sm_tks"] = rag_tokenizer.fine_grained_tokenize(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(
  157. paper["abstract"], need_position=True)
  158. add_positions(d, poss)
  159. tokenize(d, txt, eng)
  160. res.append(d)
  161. sorted_sections = paper["sections"]
  162. # set pivot using the most frequent type of title,
  163. # then merge between 2 pivot
  164. bull = bullets_category([txt for txt, _ in sorted_sections])
  165. most_level, levels = title_frequency(bull, sorted_sections)
  166. assert len(sorted_sections) == len(levels)
  167. sec_ids = []
  168. sid = 0
  169. for i, lvl in enumerate(levels):
  170. if lvl <= most_level and i > 0 and lvl != levels[i - 1]:
  171. sid += 1
  172. sec_ids.append(sid)
  173. print(lvl, sorted_sections[i][0], most_level, sid)
  174. chunks = []
  175. last_sid = -2
  176. for (txt, _), sec_id in zip(sorted_sections, sec_ids):
  177. if sec_id == last_sid:
  178. if chunks:
  179. chunks[-1] += "\n" + txt
  180. continue
  181. chunks.append(txt)
  182. last_sid = sec_id
  183. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  184. return res
  185. """
  186. readed = [0] * len(paper["lines"])
  187. # find colon firstly
  188. i = 0
  189. while i + 1 < len(paper["lines"]):
  190. txt = pdf_parser.remove_tag(paper["lines"][i][0])
  191. j = i
  192. if txt.strip("\n").strip()[-1] not in "::":
  193. i += 1
  194. continue
  195. i += 1
  196. while i < len(paper["lines"]) and not paper["lines"][i][0]:
  197. i += 1
  198. if i >= len(paper["lines"]): break
  199. proj = [paper["lines"][i][0].strip()]
  200. i += 1
  201. while i < len(paper["lines"]) and paper["lines"][i][0].strip()[0] == proj[-1][0]:
  202. proj.append(paper["lines"][i])
  203. i += 1
  204. for k in range(j, i): readed[k] = True
  205. txt = txt[::-1]
  206. if eng:
  207. r = re.search(r"(.*?) ([\\.;?!]|$)", txt)
  208. txt = r.group(1)[::-1] if r else txt[::-1]
  209. else:
  210. r = re.search(r"(.*?) ([。?;!]|$)", txt)
  211. txt = r.group(1)[::-1] if r else txt[::-1]
  212. for p in proj:
  213. d = copy.deepcopy(doc)
  214. txt += "\n" + pdf_parser.remove_tag(p)
  215. d["image"], poss = pdf_parser.crop(p, need_position=True)
  216. add_positions(d, poss)
  217. tokenize(d, txt, eng)
  218. res.append(d)
  219. i = 0
  220. chunk = []
  221. tk_cnt = 0
  222. def add_chunk():
  223. nonlocal chunk, res, doc, pdf_parser, tk_cnt
  224. d = copy.deepcopy(doc)
  225. ck = "\n".join(chunk)
  226. tokenize(d, pdf_parser.remove_tag(ck), pdf_parser.is_english)
  227. d["image"], poss = pdf_parser.crop(ck, need_position=True)
  228. add_positions(d, poss)
  229. res.append(d)
  230. chunk = []
  231. tk_cnt = 0
  232. while i < len(paper["lines"]):
  233. if tk_cnt > 128:
  234. add_chunk()
  235. if readed[i]:
  236. i += 1
  237. continue
  238. readed[i] = True
  239. txt, layouts = paper["lines"][i]
  240. txt_ = pdf_parser.remove_tag(txt)
  241. i += 1
  242. cnt = num_tokens_from_string(txt_)
  243. if any([
  244. layouts.find("title") >= 0 and chunk,
  245. cnt + tk_cnt > 128 and tk_cnt > 32,
  246. ]):
  247. add_chunk()
  248. chunk = [txt]
  249. tk_cnt = cnt
  250. else:
  251. chunk.append(txt)
  252. tk_cnt += cnt
  253. if chunk: add_chunk()
  254. for i, d in enumerate(res):
  255. print(d)
  256. # d["image"].save(f"./logs/{i}.jpg")
  257. return res
  258. """
  259. if __name__ == "__main__":
  260. import sys
  261. def dummy(prog=None, msg=""):
  262. pass
  263. chunk(sys.argv[1], callback=dummy)