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.

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