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.

manual.py 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import copy
  2. import re
  3. from api.db import ParserType
  4. from rag.nlp import huqie, tokenize, tokenize_table, add_positions, bullets_category, title_frequency, tokenize_chunks
  5. from deepdoc.parser import PdfParser, PlainParser
  6. from rag.utils import num_tokens_from_string
  7. class Pdf(PdfParser):
  8. def __init__(self):
  9. self.model_speciess = ParserType.MANUAL.value
  10. super().__init__()
  11. def __call__(self, filename, binary=None, from_page=0,
  12. to_page=100000, zoomin=3, callback=None):
  13. from timeit import default_timer as timer
  14. start = timer()
  15. callback(msg="OCR is running...")
  16. self.__images__(
  17. filename if not binary else binary,
  18. zoomin,
  19. from_page,
  20. to_page,
  21. callback
  22. )
  23. callback(msg="OCR finished.")
  24. #for bb in self.boxes:
  25. # for b in bb:
  26. # print(b)
  27. print("OCR:", timer()-start)
  28. self._layouts_rec(zoomin)
  29. callback(0.65, "Layout analysis finished.")
  30. print("paddle layouts:", timer() - start)
  31. self._table_transformer_job(zoomin)
  32. callback(0.67, "Table analysis finished.")
  33. self._text_merge()
  34. tbls = self._extract_table_figure(True, zoomin, True, True)
  35. self._concat_downward()
  36. self._filter_forpages()
  37. callback(0.68, "Text merging finished")
  38. # clean mess
  39. for b in self.boxes:
  40. b["text"] = re.sub(r"([\t  ]|\u3000){2,}", " ", b["text"].strip())
  41. return [(b["text"], b.get("layout_no", ""), self.get_position(b, zoomin)) for i, b in enumerate(self.boxes)]
  42. # set pivot using the most frequent type of title,
  43. # then merge between 2 pivot
  44. if len(self.boxes)>0 and len(self.outlines)/len(self.boxes) > 0.1:
  45. max_lvl = max([lvl for _, lvl in self.outlines])
  46. most_level = max(0, max_lvl-1)
  47. levels = []
  48. for b in self.boxes:
  49. for t,lvl in self.outlines:
  50. tks = set([t[i]+t[i+1] for i in range(len(t)-1)])
  51. tks_ = set([b["text"][i]+b["text"][i+1] for i in range(min(len(t), len(b["text"])-1))])
  52. if len(set(tks & tks_))/max([len(tks), len(tks_), 1]) > 0.8:
  53. levels.append(lvl)
  54. break
  55. else:
  56. levels.append(max_lvl + 1)
  57. else:
  58. bull = bullets_category([b["text"] for b in self.boxes])
  59. most_level, levels = title_frequency(bull, [(b["text"], b.get("layout_no","")) for b in self.boxes])
  60. assert len(self.boxes) == len(levels)
  61. sec_ids = []
  62. sid = 0
  63. for i, lvl in enumerate(levels):
  64. if lvl <= most_level and i > 0 and lvl != levels[i-1]: sid += 1
  65. sec_ids.append(sid)
  66. #print(lvl, self.boxes[i]["text"], most_level, sid)
  67. sections = [(b["text"], sec_ids[i], self.get_position(b, zoomin)) for i, b in enumerate(self.boxes)]
  68. for (img, rows), poss in tbls:
  69. sections.append((rows if isinstance(rows, str) else rows[0], -1, [(p[0]+1-from_page, p[1], p[2], p[3], p[4]) for p in poss]))
  70. chunks = []
  71. last_sid = -2
  72. tk_cnt = 0
  73. for txt, sec_id, poss in sorted(sections, key=lambda x: (x[-1][0][0], x[-1][0][3], x[-1][0][1])):
  74. poss = "\t".join([tag(*pos) for pos in poss])
  75. if tk_cnt < 2048 and (sec_id == last_sid or sec_id == -1):
  76. if chunks:
  77. chunks[-1] += "\n" + txt + poss
  78. tk_cnt += num_tokens_from_string(txt)
  79. continue
  80. chunks.append(txt + poss)
  81. tk_cnt = num_tokens_from_string(txt)
  82. if sec_id >-1: last_sid = sec_id
  83. return chunks, tbls
  84. def chunk(filename, binary=None, from_page=0, to_page=100000, lang="Chinese", callback=None, **kwargs):
  85. """
  86. Only pdf is supported.
  87. """
  88. pdf_parser = None
  89. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  90. pdf_parser = Pdf() if kwargs.get("parser_config",{}).get("layout_recognize", True) else PlainParser()
  91. sections, tbls = pdf_parser(filename if not binary else binary,
  92. from_page=from_page, to_page=to_page, callback=callback)
  93. if sections and len(sections[0])<3: cks = [(t, l, [0]*5) for t, l in sections]
  94. else: raise NotImplementedError("file type not supported yet(pdf supported)")
  95. doc = {
  96. "docnm_kwd": filename
  97. }
  98. doc["title_tks"] = huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", doc["docnm_kwd"]))
  99. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  100. # is it English
  101. eng = lang.lower() == "english"#pdf_parser.is_english
  102. # set pivot using the most frequent type of title,
  103. # then merge between 2 pivot
  104. if len(sections) > 0 and len(pdf_parser.outlines) / len(sections) > 0.1:
  105. max_lvl = max([lvl for _, lvl in pdf_parser.outlines])
  106. most_level = max(0, max_lvl - 1)
  107. levels = []
  108. for txt, _, _ in sections:
  109. for t, lvl in pdf_parser.outlines:
  110. tks = set([t[i] + t[i + 1] for i in range(len(t) - 1)])
  111. tks_ = set([txt[i] + txt[i + 1] for i in range(min(len(t), len(txt) - 1))])
  112. if len(set(tks & tks_)) / max([len(tks), len(tks_), 1]) > 0.8:
  113. levels.append(lvl)
  114. break
  115. else:
  116. levels.append(max_lvl + 1)
  117. else:
  118. bull = bullets_category([txt for txt,_,_ in sections])
  119. most_level, levels = title_frequency(bull, [(txt, l) for txt, l, poss in sections])
  120. assert len(sections) == len(levels)
  121. sec_ids = []
  122. sid = 0
  123. for i, lvl in enumerate(levels):
  124. if lvl <= most_level and i > 0 and lvl != levels[i - 1]: sid += 1
  125. sec_ids.append(sid)
  126. # print(lvl, self.boxes[i]["text"], most_level, sid)
  127. sections = [(txt, sec_ids[i], poss) for i, (txt, _, poss) in enumerate(sections)]
  128. for (img, rows), poss in tbls:
  129. sections.append((rows if isinstance(rows, str) else rows[0], -1,
  130. [(p[0] + 1 - from_page, p[1], p[2], p[3], p[4]) for p in poss]))
  131. def tag(pn, left, right, top, bottom):
  132. if pn+left+right+top+bottom == 0:
  133. return ""
  134. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  135. .format(pn, left, right, top, bottom)
  136. chunks = []
  137. last_sid = -2
  138. tk_cnt = 0
  139. for txt, sec_id, poss in sorted(sections, key=lambda x: (x[-1][0][0], x[-1][0][3], x[-1][0][1])):
  140. poss = "\t".join([tag(*pos) for pos in poss])
  141. if tk_cnt < 2048 and (sec_id == last_sid or sec_id == -1):
  142. if chunks:
  143. chunks[-1] += "\n" + txt + poss
  144. tk_cnt += num_tokens_from_string(txt)
  145. continue
  146. chunks.append(txt + poss)
  147. tk_cnt = num_tokens_from_string(txt)
  148. if sec_id > -1: last_sid = sec_id
  149. res = tokenize_table(tbls, doc, eng)
  150. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  151. return res
  152. if __name__ == "__main__":
  153. import sys
  154. def dummy(prog=None, msg=""):
  155. pass
  156. chunk(sys.argv[1], callback=dummy)