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.

one.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. from io import BytesIO
  19. import re
  20. from deepdoc.parser.utils import get_text
  21. from rag.app import naive
  22. from rag.nlp import rag_tokenizer, tokenize
  23. from deepdoc.parser import PdfParser, ExcelParser, PlainParser, HtmlParser
  24. class Pdf(PdfParser):
  25. def __call__(self, filename, binary=None, from_page=0,
  26. to_page=100000, zoomin=3, callback=None):
  27. from timeit import default_timer as timer
  28. start = timer()
  29. callback(msg="OCR started")
  30. self.__images__(
  31. filename if not binary else binary,
  32. zoomin,
  33. from_page,
  34. to_page,
  35. callback
  36. )
  37. callback(msg="OCR finished ({:.2f}s)".format(timer() - start))
  38. start = timer()
  39. self._layouts_rec(zoomin, drop=False)
  40. callback(0.63, "Layout analysis ({:.2f}s)".format(timer() - start))
  41. logging.debug("layouts cost: {}s".format(timer() - start))
  42. start = timer()
  43. self._table_transformer_job(zoomin)
  44. callback(0.65, "Table analysis ({:.2f}s)".format(timer() - start))
  45. start = timer()
  46. self._text_merge()
  47. callback(0.67, "Text merged ({:.2f}s)".format(timer() - start))
  48. tbls = self._extract_table_figure(True, zoomin, True, True)
  49. self._concat_downward()
  50. sections = [(b["text"], self.get_position(b, zoomin))
  51. for i, b in enumerate(self.boxes)]
  52. for (img, rows), poss in tbls:
  53. if not rows:
  54. continue
  55. sections.append((rows if isinstance(rows, str) else rows[0],
  56. [(p[0] + 1 - from_page, p[1], p[2], p[3], p[4]) for p in poss]))
  57. return [(txt, "") for txt, _ in sorted(sections, key=lambda x: (
  58. x[-1][0][0], x[-1][0][3], x[-1][0][1]))], None
  59. def chunk(filename, binary=None, from_page=0, to_page=100000,
  60. lang="Chinese", callback=None, **kwargs):
  61. """
  62. Supported file formats are docx, pdf, excel, txt.
  63. One file forms a chunk which maintains original text order.
  64. """
  65. parser_config = kwargs.get(
  66. "parser_config", {
  67. "chunk_token_num": 512, "delimiter": "\n!?。;!?", "layout_recognize": "DeepDOC"})
  68. eng = lang.lower() == "english" # is_english(cks)
  69. if re.search(r"\.docx$", filename, re.IGNORECASE):
  70. callback(0.1, "Start to parse.")
  71. sections, tbls = naive.Docx()(filename, binary)
  72. sections = [s for s, _ in sections if s]
  73. for (_, html), _ in tbls:
  74. sections.append(html)
  75. callback(0.8, "Finish parsing.")
  76. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  77. pdf_parser = Pdf()
  78. if parser_config.get("layout_recognize", "DeepDOC") == "Plain Text":
  79. pdf_parser = PlainParser()
  80. sections, _ = pdf_parser(
  81. filename if not binary else binary, to_page=to_page, callback=callback)
  82. sections = [s for s, _ in sections if s]
  83. elif re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  84. callback(0.1, "Start to parse.")
  85. excel_parser = ExcelParser()
  86. sections = excel_parser.html(binary, 1000000000)
  87. elif re.search(r"\.(txt|md|markdown)$", filename, re.IGNORECASE):
  88. callback(0.1, "Start to parse.")
  89. txt = get_text(filename, binary)
  90. sections = txt.split("\n")
  91. sections = [s for s in sections if s]
  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 = [s for s in sections if s]
  97. callback(0.8, "Finish parsing.")
  98. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  99. callback(0.1, "Start to parse.")
  100. binary = BytesIO(binary)
  101. doc_parsed = parser.from_buffer(binary)
  102. sections = doc_parsed['content'].split('\n')
  103. sections = [s for s in sections if s]
  104. callback(0.8, "Finish parsing.")
  105. else:
  106. raise NotImplementedError(
  107. "file type not supported yet(doc, docx, pdf, txt supported)")
  108. doc = {
  109. "docnm_kwd": filename,
  110. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  111. }
  112. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  113. tokenize(doc, "\n".join(sections), eng)
  114. return [doc]
  115. if __name__ == "__main__":
  116. import sys
  117. def dummy(prog=None, msg=""):
  118. pass
  119. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)