You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

manual.py 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import copy
  17. import re
  18. from api.db import ParserType
  19. from rag.nlp import rag_tokenizer, tokenize, tokenize_table, add_positions, bullets_category, title_frequency, tokenize_chunks
  20. from deepdoc.parser import PdfParser, PlainParser
  21. from rag.utils import num_tokens_from_string
  22. class Pdf(PdfParser):
  23. def __init__(self):
  24. self.model_speciess = ParserType.MANUAL.value
  25. super().__init__()
  26. def __call__(self, filename, binary=None, from_page=0,
  27. to_page=100000, zoomin=3, callback=None):
  28. from timeit import default_timer as timer
  29. start = timer()
  30. callback(msg="OCR is running...")
  31. self.__images__(
  32. filename if not binary else binary,
  33. zoomin,
  34. from_page,
  35. to_page,
  36. callback
  37. )
  38. callback(msg="OCR finished.")
  39. # for bb in self.boxes:
  40. # for b in bb:
  41. # print(b)
  42. print("OCR:", timer() - start)
  43. self._layouts_rec(zoomin)
  44. callback(0.65, "Layout analysis finished.")
  45. print("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._concat_downward()
  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. return [(b["text"], b.get("layout_no", ""), self.get_position(b, zoomin))
  57. for i, b in enumerate(self.boxes)], tbls
  58. def chunk(filename, binary=None, from_page=0, to_page=100000,
  59. lang="Chinese", callback=None, **kwargs):
  60. """
  61. Only pdf is supported.
  62. """
  63. pdf_parser = None
  64. if re.search(r"\.pdf$", filename, re.IGNORECASE):
  65. pdf_parser = Pdf() if kwargs.get(
  66. "parser_config", {}).get(
  67. "layout_recognize", True) else PlainParser()
  68. sections, tbls = pdf_parser(filename if not binary else binary,
  69. from_page=from_page, to_page=to_page, callback=callback)
  70. if sections and len(sections[0]) < 3:
  71. sections = [(t, l, [[0] * 5]) for t, l in sections]
  72. else:
  73. raise NotImplementedError("file type not supported yet(pdf supported)")
  74. doc = {
  75. "docnm_kwd": filename
  76. }
  77. doc["title_tks"] = rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", doc["docnm_kwd"]))
  78. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  79. # is it English
  80. eng = lang.lower() == "english" # pdf_parser.is_english
  81. # set pivot using the most frequent type of title,
  82. # then merge between 2 pivot
  83. if len(sections) > 0 and len(pdf_parser.outlines) / len(sections) > 0.1:
  84. max_lvl = max([lvl for _, lvl in pdf_parser.outlines])
  85. most_level = max(0, max_lvl - 1)
  86. levels = []
  87. for txt, _, _ in sections:
  88. for t, lvl in pdf_parser.outlines:
  89. tks = set([t[i] + t[i + 1] for i in range(len(t) - 1)])
  90. tks_ = set([txt[i] + txt[i + 1]
  91. for i in range(min(len(t), len(txt) - 1))])
  92. if len(set(tks & tks_)) / max([len(tks), len(tks_), 1]) > 0.8:
  93. levels.append(lvl)
  94. break
  95. else:
  96. levels.append(max_lvl + 1)
  97. else:
  98. bull = bullets_category([txt for txt, _, _ in sections])
  99. most_level, levels = title_frequency(
  100. bull, [(txt, l) for txt, l, poss in sections])
  101. assert len(sections) == len(levels)
  102. sec_ids = []
  103. sid = 0
  104. for i, lvl in enumerate(levels):
  105. if lvl <= most_level and i > 0 and lvl != levels[i - 1]:
  106. sid += 1
  107. sec_ids.append(sid)
  108. # print(lvl, self.boxes[i]["text"], most_level, sid)
  109. sections = [(txt, sec_ids[i], poss)
  110. for i, (txt, _, poss) in enumerate(sections)]
  111. for (img, rows), poss in tbls:
  112. if not rows: continue
  113. sections.append((rows if isinstance(rows, str) else rows[0], -1,
  114. [(p[0] + 1 - from_page, p[1], p[2], p[3], p[4]) for p in poss]))
  115. def tag(pn, left, right, top, bottom):
  116. if pn + left + right + top + bottom == 0:
  117. return ""
  118. return "@@{}\t{:.1f}\t{:.1f}\t{:.1f}\t{:.1f}##" \
  119. .format(pn, left, right, top, bottom)
  120. chunks = []
  121. last_sid = -2
  122. tk_cnt = 0
  123. for txt, sec_id, poss in sorted(sections, key=lambda x: (
  124. x[-1][0][0], x[-1][0][3], x[-1][0][1])):
  125. poss = "\t".join([tag(*pos) for pos in poss])
  126. if tk_cnt < 32 or (tk_cnt < 1024 and (sec_id == last_sid or sec_id == -1)):
  127. if chunks:
  128. chunks[-1] += "\n" + txt + poss
  129. tk_cnt += num_tokens_from_string(txt)
  130. continue
  131. chunks.append(txt + poss)
  132. tk_cnt = num_tokens_from_string(txt)
  133. if sec_id > -1:
  134. last_sid = sec_id
  135. res = tokenize_table(tbls, doc, eng)
  136. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  137. return res
  138. if __name__ == "__main__":
  139. import sys
  140. def dummy(prog=None, msg=""):
  141. pass
  142. chunk(sys.argv[1], callback=dummy)