Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import copy
  2. import re
  3. from api.db import ParserType
  4. from rag.nlp import rag_tokenizer, 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("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))
  42. for i, b in enumerate(self.boxes)], tbls
  43. def chunk(filename, binary=None, from_page=0, to_page=100000,
  44. lang="Chinese", callback=None, **kwargs):
  45. """
  46. Only pdf is supported.
  47. """
  48. pdf_parser = None
  49. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  50. pdf_parser = Pdf() if kwargs.get(
  51. "parser_config", {}).get(
  52. "layout_recognize", True) else PlainParser()
  53. sections, tbls = pdf_parser(filename if not binary else binary,
  54. from_page=from_page, to_page=to_page, callback=callback)
  55. if sections and len(sections[0]) < 3:
  56. sections = [(t, l, [[0] * 5]) for t, l in sections]
  57. else:
  58. raise NotImplementedError("file type not supported yet(pdf supported)")
  59. doc = {
  60. "docnm_kwd": filename
  61. }
  62. doc["title_tks"] = rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", doc["docnm_kwd"]))
  63. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  64. # is it English
  65. eng = lang.lower() == "english" # pdf_parser.is_english
  66. # set pivot using the most frequent type of title,
  67. # then merge between 2 pivot
  68. if len(sections) > 0 and len(pdf_parser.outlines) / len(sections) > 0.1:
  69. max_lvl = max([lvl for _, lvl in pdf_parser.outlines])
  70. most_level = max(0, max_lvl - 1)
  71. levels = []
  72. for txt, _, _ in sections:
  73. for t, lvl in pdf_parser.outlines:
  74. tks = set([t[i] + t[i + 1] for i in range(len(t) - 1)])
  75. tks_ = set([txt[i] + txt[i + 1]
  76. for i in range(min(len(t), len(txt) - 1))])
  77. if len(set(tks & tks_)) / max([len(tks), len(tks_), 1]) > 0.8:
  78. levels.append(lvl)
  79. break
  80. else:
  81. levels.append(max_lvl + 1)
  82. else:
  83. bull = bullets_category([txt for txt, _, _ in sections])
  84. most_level, levels = title_frequency(
  85. bull, [(txt, l) for txt, l, poss in sections])
  86. assert len(sections) == len(levels)
  87. sec_ids = []
  88. sid = 0
  89. for i, lvl in enumerate(levels):
  90. if lvl <= most_level and i > 0 and lvl != levels[i - 1]:
  91. sid += 1
  92. sec_ids.append(sid)
  93. # print(lvl, self.boxes[i]["text"], most_level, sid)
  94. sections = [(txt, sec_ids[i], poss)
  95. for i, (txt, _, poss) in enumerate(sections)]
  96. for (img, rows), poss in tbls:
  97. if not rows: continue
  98. sections.append((rows if isinstance(rows, str) else rows[0], -1,
  99. [(p[0] + 1 - from_page, p[1], p[2], p[3], p[4]) for p in poss]))
  100. def tag(pn, left, right, top, bottom):
  101. if pn + left + right + top + bottom == 0:
  102. return ""
  103. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  104. .format(pn, left, right, top, bottom)
  105. chunks = []
  106. last_sid = -2
  107. tk_cnt = 0
  108. for txt, sec_id, poss in sorted(sections, key=lambda x: (
  109. x[-1][0][0], x[-1][0][3], x[-1][0][1])):
  110. poss = "\t".join([tag(*pos) for pos in poss])
  111. if tk_cnt < 32 or (tk_cnt < 1024 and (sec_id == last_sid or sec_id == -1)):
  112. if chunks:
  113. chunks[-1] += "\n" + txt + poss
  114. tk_cnt += num_tokens_from_string(txt)
  115. continue
  116. chunks.append(txt + poss)
  117. tk_cnt = num_tokens_from_string(txt)
  118. if sec_id > -1:
  119. last_sid = sec_id
  120. res = tokenize_table(tbls, doc, eng)
  121. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  122. return res
  123. if __name__ == "__main__":
  124. import sys
  125. def dummy(prog=None, msg=""):
  126. pass
  127. chunk(sys.argv[1], callback=dummy)