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

manual.py 4.7KB

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