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

manual.py 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import copy
  2. import re
  3. from api.db import ParserType
  4. from rag.nlp import huqie, tokenize
  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. self.__images__(
  14. filename if not binary else binary,
  15. zoomin,
  16. from_page,
  17. to_page)
  18. callback(0.2, "OCR finished.")
  19. from timeit import default_timer as timer
  20. start = timer()
  21. self._layouts_rec(zoomin)
  22. callback(0.5, "Layout analysis finished.")
  23. print("paddle layouts:", timer() - start)
  24. self._table_transformer_job(zoomin)
  25. callback(0.7, "Table analysis finished.")
  26. self._text_merge()
  27. self._concat_downward(concat_between_pages=False)
  28. self._filter_forpages()
  29. callback(0.77, "Text merging finished")
  30. tbls = self._extract_table_figure(True, zoomin, False)
  31. # clean mess
  32. for b in self.boxes:
  33. b["text"] = re.sub(r"([\t  ]|\u3000){2,}", " ", b["text"].strip())
  34. # merge chunks with the same bullets
  35. self._merge_with_same_bullet()
  36. # merge title with decent chunk
  37. i = 0
  38. while i + 1 < len(self.boxes):
  39. b = self.boxes[i]
  40. if b.get("layoutno","").find("title") < 0:
  41. i += 1
  42. continue
  43. b_ = self.boxes[i + 1]
  44. b_["text"] = b["text"] + "\n" + b_["text"]
  45. b_["x0"] = min(b["x0"], b_["x0"])
  46. b_["x1"] = max(b["x1"], b_["x1"])
  47. b_["top"] = b["top"]
  48. self.boxes.pop(i)
  49. callback(0.8, "Parsing finished")
  50. for b in self.boxes: print(b["text"], b.get("layoutno"))
  51. print(tbls)
  52. return [b["text"] + self._line_tag(b, zoomin) for b in self.boxes], tbls
  53. def chunk(filename, binary=None, from_page=0, to_page=100000, lang="Chinese", callback=None, **kwargs):
  54. """
  55. Only pdf is supported.
  56. """
  57. pdf_parser = None
  58. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  59. pdf_parser = Pdf()
  60. cks, tbls = pdf_parser(filename if not binary else binary,
  61. from_page=from_page, to_page=to_page, callback=callback)
  62. else: raise NotImplementedError("file type not supported yet(pdf supported)")
  63. doc = {
  64. "docnm_kwd": filename
  65. }
  66. doc["title_tks"] = huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", doc["docnm_kwd"]))
  67. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  68. # is it English
  69. eng = lang.lower() == "english"#pdf_parser.is_english
  70. res = []
  71. # add tables
  72. for img, rows in tbls:
  73. bs = 10
  74. de = ";" if eng else ";"
  75. for i in range(0, len(rows), bs):
  76. d = copy.deepcopy(doc)
  77. r = de.join(rows[i:i + bs])
  78. r = re.sub(r"\t——(来自| in ).*”%s" % de, "", r)
  79. tokenize(d, r, eng)
  80. d["image"] = img
  81. res.append(d)
  82. i = 0
  83. chunk = []
  84. tk_cnt = 0
  85. def add_chunk():
  86. nonlocal chunk, res, doc, pdf_parser, tk_cnt
  87. d = copy.deepcopy(doc)
  88. ck = "\n".join(chunk)
  89. tokenize(d, pdf_parser.remove_tag(ck), pdf_parser.is_english)
  90. d["image"] = pdf_parser.crop(ck)
  91. res.append(d)
  92. chunk = []
  93. tk_cnt = 0
  94. while i < len(cks):
  95. if tk_cnt > 128: add_chunk()
  96. txt = cks[i]
  97. txt_ = pdf_parser.remove_tag(txt)
  98. i += 1
  99. cnt = num_tokens_from_string(txt_)
  100. chunk.append(txt)
  101. tk_cnt += cnt
  102. if chunk: add_chunk()
  103. for i, d in enumerate(res):
  104. print(d)
  105. # d["image"].save(f"./logs/{i}.jpg")
  106. return res
  107. if __name__ == "__main__":
  108. import sys
  109. def dummy(a, b):
  110. pass
  111. chunk(sys.argv[1], callback=dummy)