Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

manual.py 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. # set pivot using the most frequent type of title,
  57. # then merge between 2 pivot
  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: sid += 1
  65. sec_ids.append(sid)
  66. #print(lvl, self.boxes[i]["text"], most_level)
  67. sections = [(b["text"], sec_ids[i], get_position(b)) 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. for txt, sec_id, poss in sorted(sections, key=lambda x: (x[-1][0][0], x[-1][0][3], x[-1][0][1])):
  73. poss = "\t".join([tag(*pos) for pos in poss])
  74. if sec_id == last_sid or sec_id == -1:
  75. if chunks:
  76. chunks[-1] += "\n" + txt + poss
  77. continue
  78. chunks.append(txt + poss)
  79. if sec_id >-1: last_sid = sec_id
  80. return chunks
  81. def chunk(filename, binary=None, from_page=0, to_page=100000, lang="Chinese", callback=None, **kwargs):
  82. """
  83. Only pdf is supported.
  84. """
  85. pdf_parser = None
  86. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  87. pdf_parser = Pdf()
  88. cks = pdf_parser(filename if not binary else binary,
  89. from_page=from_page, to_page=to_page, callback=callback)
  90. else: raise NotImplementedError("file type not supported yet(pdf supported)")
  91. doc = {
  92. "docnm_kwd": filename
  93. }
  94. doc["title_tks"] = huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", doc["docnm_kwd"]))
  95. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  96. # is it English
  97. eng = lang.lower() == "english"#pdf_parser.is_english
  98. i = 0
  99. chunk = []
  100. tk_cnt = 0
  101. res = []
  102. def add_chunk():
  103. nonlocal chunk, res, doc, pdf_parser, tk_cnt
  104. d = copy.deepcopy(doc)
  105. ck = "\n".join(chunk)
  106. tokenize(d, pdf_parser.remove_tag(ck), eng)
  107. d["image"], poss = pdf_parser.crop(ck, need_position=True)
  108. add_positions(d, poss)
  109. res.append(d)
  110. chunk = []
  111. tk_cnt = 0
  112. while i < len(cks):
  113. if tk_cnt > 256: add_chunk()
  114. txt = cks[i]
  115. txt_ = pdf_parser.remove_tag(txt)
  116. i += 1
  117. cnt = num_tokens_from_string(txt_)
  118. chunk.append(txt)
  119. tk_cnt += cnt
  120. if chunk: add_chunk()
  121. for i, d in enumerate(res):
  122. print(d)
  123. # d["image"].save(f"./logs/{i}.jpg")
  124. return res
  125. if __name__ == "__main__":
  126. import sys
  127. def dummy(prog=None, msg=""):
  128. pass
  129. chunk(sys.argv[1], callback=dummy)