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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. eng = lang.lower() == "english" # is_english(cks)
  66. if re.search(r"\.docx$", filename, re.IGNORECASE):
  67. callback(0.1, "Start to parse.")
  68. sections, tbls = naive.Docx()(filename, binary)
  69. sections = [s for s, _ in sections if s]
  70. for (_, html), _ in tbls:
  71. sections.append(html)
  72. callback(0.8, "Finish parsing.")
  73. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  74. pdf_parser = Pdf() if kwargs.get(
  75. "parser_config", {}).get(
  76. "layout_recognize", True) else PlainParser()
  77. sections, _ = pdf_parser(
  78. filename if not binary else binary, to_page=to_page, callback=callback)
  79. sections = [s for s, _ in sections if s]
  80. elif re.search(r"\.xlsx?$", filename, re.IGNORECASE):
  81. callback(0.1, "Start to parse.")
  82. excel_parser = ExcelParser()
  83. sections = excel_parser.html(binary, 1000000000)
  84. elif re.search(r"\.(txt|md|markdown)$", filename, re.IGNORECASE):
  85. callback(0.1, "Start to parse.")
  86. txt = get_text(filename, binary)
  87. sections = txt.split("\n")
  88. sections = [s for s in sections if s]
  89. callback(0.8, "Finish parsing.")
  90. elif re.search(r"\.(htm|html)$", filename, re.IGNORECASE):
  91. callback(0.1, "Start to parse.")
  92. sections = HtmlParser()(filename, binary)
  93. sections = [s for s in sections if s]
  94. callback(0.8, "Finish parsing.")
  95. elif re.search(r"\.doc$", filename, re.IGNORECASE):
  96. callback(0.1, "Start to parse.")
  97. binary = BytesIO(binary)
  98. doc_parsed = parser.from_buffer(binary)
  99. sections = doc_parsed['content'].split('\n')
  100. sections = [s for s in sections if s]
  101. callback(0.8, "Finish parsing.")
  102. else:
  103. raise NotImplementedError(
  104. "file type not supported yet(doc, docx, pdf, txt supported)")
  105. doc = {
  106. "docnm_kwd": filename,
  107. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  108. }
  109. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  110. tokenize(doc, "\n".join(sections), eng)
  111. return [doc]
  112. if __name__ == "__main__":
  113. import sys
  114. def dummy(prog=None, msg=""):
  115. pass
  116. chunk(sys.argv[1], from_page=0, to_page=10, callback=dummy)