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.

book.py 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. #
  2. # Copyright 2025 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 logging
  17. from tika import parser
  18. import re
  19. from io import BytesIO
  20. from deepdoc.parser.utils import get_text
  21. from rag.nlp import bullets_category, is_english,remove_contents_table, \
  22. hierarchical_merge, make_colon_as_title, naive_merge, random_choices, tokenize_table, \
  23. tokenize_chunks
  24. from rag.nlp import rag_tokenizer
  25. from deepdoc.parser import PdfParser, DocxParser, PlainParser, HtmlParser
  26. class Pdf(PdfParser):
  27. def __call__(self, filename, binary=None, from_page=0,
  28. to_page=100000, zoomin=3, callback=None):
  29. from timeit import default_timer as timer
  30. start = timer()
  31. callback(msg="OCR started")
  32. self.__images__(
  33. filename if not binary else binary,
  34. zoomin,
  35. from_page,
  36. to_page,
  37. callback)
  38. callback(msg="OCR finished ({:.2f}s)".format(timer() - start))
  39. start = timer()
  40. self._layouts_rec(zoomin)
  41. callback(0.67, "Layout analysis ({:.2f}s)".format(timer() - start))
  42. logging.debug("layouts: {}".format(timer() - start))
  43. start = timer()
  44. self._table_transformer_job(zoomin)
  45. callback(0.68, "Table analysis ({:.2f}s)".format(timer() - start))
  46. start = timer()
  47. self._text_merge()
  48. tbls = self._extract_table_figure(True, zoomin, True, True)
  49. self._naive_vertical_merge()
  50. self._filter_forpages()
  51. self._merge_with_same_bullet()
  52. callback(0.8, "Text extraction ({:.2f}s)".format(timer() - start))
  53. return [(b["text"] + self._line_tag(b, zoomin), b.get("layoutno", ""))
  54. for b in self.boxes], tbls
  55. def chunk(filename, binary=None, from_page=0, to_page=100000,
  56. lang="Chinese", callback=None, **kwargs):
  57. """
  58. Supported file formats are docx, pdf, txt.
  59. Since a book is long and not all the parts are useful, if it's a PDF,
  60. please setup the page ranges for every book in order eliminate negative effects and save elapsed computing time.
  61. """
  62. parser_config = kwargs.get(
  63. "parser_config", {
  64. "chunk_token_num": 512, "delimiter": "\n!?。;!?", "layout_recognize": "DeepDOC"})
  65. doc = {
  66. "docnm_kwd": filename,
  67. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  68. }
  69. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  70. pdf_parser = None
  71. sections, tbls = [], []
  72. if re.search(r"\.docx$", filename, re.IGNORECASE):
  73. callback(0.1, "Start to parse.")
  74. doc_parser = DocxParser()
  75. # TODO: table of contents need to be removed
  76. sections, tbls = doc_parser(
  77. binary if binary else filename, from_page=from_page, to_page=to_page)
  78. remove_contents_table(sections, eng=is_english(
  79. random_choices([t for t, _ in sections], k=200)))
  80. tbls = [((None, lns), None) for lns in tbls]
  81. callback(0.8, "Finish parsing.")
  82. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  83. pdf_parser = Pdf()
  84. if parser_config.get("layout_recognize", "DeepDOC") == "Plain Text":
  85. pdf_parser = PlainParser()
  86. sections, tbls = pdf_parser(filename if not binary else binary,
  87. from_page=from_page, to_page=to_page, callback=callback)
  88. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  89. callback(0.1, "Start to parse.")
  90. txt = get_text(filename, binary)
  91. sections = txt.split("\n")
  92. sections = [(line, "") for line in sections if line]
  93. remove_contents_table(sections, eng=is_english(
  94. random_choices([t for t, _ in sections], k=200)))
  95. callback(0.8, "Finish parsing.")
  96. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  97. callback(0.1, "Start to parse.")
  98. sections = HtmlParser()(filename, binary)
  99. sections = [(line, "") for line in sections if line]
  100. remove_contents_table(sections, eng=is_english(
  101. random_choices([t for t, _ in sections], k=200)))
  102. callback(0.8, "Finish parsing.")
  103. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  104. callback(0.1, "Start to parse.")
  105. binary = BytesIO(binary)
  106. doc_parsed = parser.from_buffer(binary)
  107. sections = doc_parsed['content'].split('\n')
  108. sections = [(line, "") for line in sections if line]
  109. remove_contents_table(sections, eng=is_english(
  110. random_choices([t for t, _ in sections], k=200)))
  111. callback(0.8, "Finish parsing.")
  112. else:
  113. raise NotImplementedError(
  114. "file type not supported yet(doc, docx, pdf, txt supported)")
  115. make_colon_as_title(sections)
  116. bull = bullets_category(
  117. [t for t in random_choices([t for t, _ in sections], k=100)])
  118. if bull >= 0:
  119. chunks = ["\n".join(ck)
  120. for ck in hierarchical_merge(bull, sections, 5)]
  121. else:
  122. sections = [s.split("@") for s, _ in sections]
  123. sections = [(pr[0], "@" + pr[1]) if len(pr) == 2 else (pr[0], '') for pr in sections ]
  124. chunks = naive_merge(
  125. sections, kwargs.get(
  126. "chunk_token_num", 256), kwargs.get(
  127. "delimer", "\n。;!?"))
  128. # is it English
  129. # is_english(random_choices([t for t, _ in sections], k=218))
  130. eng = lang.lower() == "english"
  131. res = tokenize_table(tbls, doc, eng)
  132. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  133. return res
  134. if __name__ == "__main__":
  135. import sys
  136. def dummy(prog=None, msg=""):
  137. pass
  138. chunk(sys.argv[1], from_page=1, to_page=10, callback=dummy)