您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

manual.py 5.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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
  5. from deepdoc.parser import PdfParser
  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. def get_position(bx):
  29. poss = []
  30. pn = bx["page_number"]
  31. top = bx["top"] - self.page_cum_height[pn - 1]
  32. bott = bx["bottom"] - self.page_cum_height[pn - 1]
  33. poss.append((pn, bx["x0"], bx["x1"], top, min(bott, self.page_images[pn-1].size[1]/zoomin)))
  34. while bott * zoomin > self.page_images[pn - 1].size[1]:
  35. bott -= self.page_images[pn- 1].size[1] / zoomin
  36. top = 0
  37. pn += 1
  38. poss.append((pn, bx["x0"], bx["x1"], top, min(bott, self.page_images[pn - 1].size[1] / zoomin)))
  39. return poss
  40. def tag(pn, left, right, top, bottom):
  41. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  42. .format(pn, left, right, top, bottom)
  43. self._layouts_rec(zoomin)
  44. callback(0.65, "Layout analysis finished.")
  45. print("paddle layouts:", timer() - start)
  46. self._table_transformer_job(zoomin)
  47. callback(0.67, "Table analysis finished.")
  48. self._text_merge()
  49. tbls = self._extract_table_figure(True, zoomin, True, True)
  50. self._naive_vertical_merge()
  51. self._filter_forpages()
  52. callback(0.68, "Text merging finished")
  53. # clean mess
  54. for b in self.boxes:
  55. b["text"] = re.sub(r"([\t  ]|\u3000){2,}", " ", b["text"].strip())
  56. # merge chunks with the same bullets
  57. self._merge_with_same_bullet()
  58. # set pivot using the most frequent type of title,
  59. # then merge between 2 pivot
  60. bull = bullets_category([b["text"] for b in self.boxes])
  61. most_level, levels = title_frequency(bull, [(b["text"], b.get("layout_no","")) for b in self.boxes])
  62. assert len(self.boxes) == len(levels)
  63. sec_ids = []
  64. sid = 0
  65. for i, lvl in enumerate(levels):
  66. if lvl <= most_level: sid += 1
  67. sec_ids.append(sid)
  68. #print(lvl, self.boxes[i]["text"], most_level)
  69. sections = [(b["text"], sec_ids[i], get_position(b)) for i, b in enumerate(self.boxes)]
  70. for (img, rows), poss in tbls:
  71. sections.append((rows[0], -1, [(p[0]+1, p[1], p[2], p[3], p[4]) for p in poss]))
  72. chunks = []
  73. last_sid = -2
  74. for txt, sec_id, poss in sorted(sections, key=lambda x: (x[-1][0][0], x[-1][0][3], x[-1][0][1])):
  75. poss = "\t".join([tag(*pos) for pos in poss])
  76. if sec_id == last_sid or sec_id == -1:
  77. if chunks:
  78. chunks[-1] += "\n" + txt + poss
  79. continue
  80. chunks.append(txt + poss)
  81. if sec_id >-1: last_sid = sec_id
  82. return chunks
  83. def chunk(filename, binary=None, from_page=0, to_page=100000, lang="Chinese", callback=None, **kwargs):
  84. """
  85. Only pdf is supported.
  86. """
  87. pdf_parser = None
  88. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  89. pdf_parser = Pdf()
  90. cks = pdf_parser(filename if not binary else binary,
  91. from_page=from_page, to_page=to_page, callback=callback)
  92. else: raise NotImplementedError("file type not supported yet(pdf supported)")
  93. doc = {
  94. "docnm_kwd": filename
  95. }
  96. doc["title_tks"] = huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", doc["docnm_kwd"]))
  97. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  98. # is it English
  99. eng = lang.lower() == "english"#pdf_parser.is_english
  100. i = 0
  101. chunk = []
  102. tk_cnt = 0
  103. res = []
  104. def add_chunk():
  105. nonlocal chunk, res, doc, pdf_parser, tk_cnt
  106. d = copy.deepcopy(doc)
  107. ck = "\n".join(chunk)
  108. tokenize(d, pdf_parser.remove_tag(ck), eng)
  109. d["image"], poss = pdf_parser.crop(ck, need_position=True)
  110. add_positions(d, poss)
  111. res.append(d)
  112. chunk = []
  113. tk_cnt = 0
  114. while i < len(cks):
  115. if tk_cnt > 256: add_chunk()
  116. txt = cks[i]
  117. txt_ = pdf_parser.remove_tag(txt)
  118. i += 1
  119. cnt = num_tokens_from_string(txt_)
  120. chunk.append(txt)
  121. tk_cnt += cnt
  122. if chunk: add_chunk()
  123. for i, d in enumerate(res):
  124. print(d)
  125. # d["image"].save(f"./logs/{i}.jpg")
  126. return res
  127. if __name__ == "__main__":
  128. import sys
  129. def dummy(prog=None, msg=""):
  130. pass
  131. chunk(sys.argv[1], callback=dummy)