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.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. doc = {
  63. "docnm_kwd": filename,
  64. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  65. }
  66. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  67. pdf_parser = None
  68. sections, tbls = [], []
  69. if re.search(r"\.docx$", filename, re.IGNORECASE):
  70. callback(0.1, "Start to parse.")
  71. doc_parser = DocxParser()
  72. # TODO: table of contents need to be removed
  73. sections, tbls = doc_parser(
  74. binary if binary else filename, from_page=from_page, to_page=to_page)
  75. remove_contents_table(sections, eng=is_english(
  76. random_choices([t for t, _ in sections], k=200)))
  77. tbls = [((None, lns), None) for lns in tbls]
  78. callback(0.8, "Finish parsing.")
  79. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  80. pdf_parser = Pdf()
  81. if kwargs.get("layout_recognize", "DeepDOC") == "Plain Text":
  82. pdf_parser = PlainParser()
  83. sections, tbls = pdf_parser(filename if not binary else binary,
  84. from_page=from_page, to_page=to_page, callback=callback)
  85. elif re.search(r"\.txt$", filename, re.IGNORECASE):
  86. callback(0.1, "Start to parse.")
  87. txt = get_text(filename, binary)
  88. sections = txt.split("\n")
  89. sections = [(line, "") for line in sections if line]
  90. remove_contents_table(sections, eng=is_english(
  91. random_choices([t for t, _ in sections], k=200)))
  92. callback(0.8, "Finish parsing.")
  93. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  94. callback(0.1, "Start to parse.")
  95. sections = HtmlParser()(filename, binary)
  96. sections = [(line, "") for line in sections if line]
  97. remove_contents_table(sections, eng=is_english(
  98. random_choices([t for t, _ in sections], k=200)))
  99. callback(0.8, "Finish parsing.")
  100. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  101. callback(0.1, "Start to parse.")
  102. binary = BytesIO(binary)
  103. doc_parsed = parser.from_buffer(binary)
  104. sections = doc_parsed['content'].split('\n')
  105. sections = [(line, "") for line in sections if line]
  106. remove_contents_table(sections, eng=is_english(
  107. random_choices([t for t, _ in sections], k=200)))
  108. callback(0.8, "Finish parsing.")
  109. else:
  110. raise NotImplementedError(
  111. "file type not supported yet(doc, docx, pdf, txt supported)")
  112. make_colon_as_title(sections)
  113. bull = bullets_category(
  114. [t for t in random_choices([t for t, _ in sections], k=100)])
  115. if bull >= 0:
  116. chunks = ["\n".join(ck)
  117. for ck in hierarchical_merge(bull, sections, 5)]
  118. else:
  119. sections = [s.split("@") for s, _ in sections]
  120. sections = [(pr[0], "@" + pr[1]) if len(pr) == 2 else (pr[0], '') for pr in sections ]
  121. chunks = naive_merge(
  122. sections, kwargs.get(
  123. "chunk_token_num", 256), kwargs.get(
  124. "delimer", "\n。;!?"))
  125. # is it English
  126. # is_english(random_choices([t for t, _ in sections], k=218))
  127. eng = lang.lower() == "english"
  128. res = tokenize_table(tbls, doc, eng)
  129. res.extend(tokenize_chunks(chunks, doc, eng, pdf_parser))
  130. return res
  131. if __name__ == "__main__":
  132. import sys
  133. def dummy(prog=None, msg=""):
  134. pass
  135. chunk(sys.argv[1], from_page=1, to_page=10, callback=dummy)