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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 copy
  17. import re
  18. from io import BytesIO
  19. from PIL import Image
  20. from api.db import LLMType
  21. from api.db.services.llm_service import LLMBundle
  22. from deepdoc.parser.pdf_parser import VisionParser
  23. from rag.nlp import tokenize, is_english
  24. from rag.nlp import rag_tokenizer
  25. from deepdoc.parser import PdfParser, PptParser, PlainParser
  26. from PyPDF2 import PdfReader as pdf2_read
  27. class Ppt(PptParser):
  28. def __call__(self, fnm, from_page, to_page, callback=None):
  29. txts = super().__call__(fnm, from_page, to_page)
  30. callback(0.5, "Text extraction finished.")
  31. import aspose.slides as slides
  32. import aspose.pydrawing as drawing
  33. imgs = []
  34. with slides.Presentation(BytesIO(fnm)) as presentation:
  35. for i, slide in enumerate(presentation.slides[from_page: to_page]):
  36. try:
  37. buffered = BytesIO()
  38. slide.get_thumbnail(
  39. 0.5, 0.5).save(
  40. buffered, drawing.imaging.ImageFormat.jpeg)
  41. imgs.append(Image.open(buffered))
  42. except RuntimeError as e:
  43. raise RuntimeError(f'ppt parse error at page {i+1}, original error: {str(e)}') from e
  44. assert len(imgs) == len(
  45. txts), "Slides text and image do not match: {} vs. {}".format(len(imgs), len(txts))
  46. callback(0.9, "Image extraction finished")
  47. self.is_english = is_english(txts)
  48. return [(txts[i], imgs[i]) for i in range(len(txts))]
  49. class Pdf(PdfParser):
  50. def __init__(self):
  51. super().__init__()
  52. def __garbage(self, txt):
  53. txt = txt.lower().strip()
  54. if re.match(r"[0-9\.,%/-]+$", txt):
  55. return True
  56. if len(txt) < 3:
  57. return True
  58. return False
  59. def __call__(self, filename, binary=None, from_page=0,
  60. to_page=100000, zoomin=3, callback=None):
  61. from timeit import default_timer as timer
  62. start = timer()
  63. callback(msg="OCR started")
  64. self.__images__(filename if not binary else binary,
  65. zoomin, from_page, to_page, callback)
  66. callback(msg="Page {}~{}: OCR finished ({:.2f}s)".format(from_page, min(to_page, self.total_page), timer() - start))
  67. assert len(self.boxes) == len(self.page_images), "{} vs. {}".format(
  68. len(self.boxes), len(self.page_images))
  69. res = []
  70. for i in range(len(self.boxes)):
  71. lines = "\n".join([b["text"] for b in self.boxes[i]
  72. if not self.__garbage(b["text"])])
  73. res.append((lines, self.page_images[i]))
  74. callback(0.9, "Page {}~{}: Parsing finished".format(
  75. from_page, min(to_page, self.total_page)))
  76. return res
  77. class PlainPdf(PlainParser):
  78. def __call__(self, filename, binary=None, from_page=0,
  79. to_page=100000, callback=None, **kwargs):
  80. self.pdf = pdf2_read(filename if not binary else BytesIO(binary))
  81. page_txt = []
  82. for page in self.pdf.pages[from_page: to_page]:
  83. page_txt.append(page.extract_text())
  84. callback(0.9, "Parsing finished")
  85. return [(txt, None) for txt in page_txt]
  86. def chunk(filename, binary=None, from_page=0, to_page=100000,
  87. lang="Chinese", callback=None, **kwargs):
  88. """
  89. The supported file formats are pdf, pptx.
  90. Every page will be treated as a chunk. And the thumbnail of every page will be stored.
  91. PPT file will be parsed by using this method automatically, setting-up for every PPT file is not necessary.
  92. """
  93. eng = lang.lower() == "english"
  94. doc = {
  95. "docnm_kwd": filename,
  96. "title_tks": rag_tokenizer.tokenize(re.sub(r"\.[a-zA-Z]+$", "", filename))
  97. }
  98. doc["title_sm_tks"] = rag_tokenizer.fine_grained_tokenize(doc["title_tks"])
  99. res = []
  100. if re.search(r"\.pptx?$", filename, re.IGNORECASE):
  101. ppt_parser = Ppt()
  102. for pn, (txt, img) in enumerate(ppt_parser(
  103. filename if not binary else binary, from_page, 1000000, callback)):
  104. d = copy.deepcopy(doc)
  105. pn += from_page
  106. d["image"] = img
  107. d["doc_type_kwd"] = "image"
  108. d["page_num_int"] = [pn + 1]
  109. d["top_int"] = [0]
  110. d["position_int"] = [(pn + 1, 0, img.size[0], 0, img.size[1])]
  111. tokenize(d, txt, eng)
  112. res.append(d)
  113. return res
  114. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  115. layout_recognizer = kwargs.get("layout_recognize", "DeepDOC")
  116. if layout_recognizer == "DeepDOC":
  117. pdf_parser = Pdf()
  118. sections = pdf_parser(filename, binary, from_page=from_page, to_page=to_page, callback=callback)
  119. elif layout_recognizer == "Plain Text":
  120. pdf_parser = PlainParser()
  121. sections, _ = pdf_parser(filename, binary, from_page=from_page, to_page=to_page, callback=callback)
  122. else:
  123. vision_model = LLMBundle(kwargs["tenant_id"], LLMType.IMAGE2TEXT, llm_name=layout_recognizer, lang=lang)
  124. pdf_parser = VisionParser(vision_model=vision_model, **kwargs)
  125. sections, _ = pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page,
  126. callback=callback)
  127. callback(0.8, "Finish parsing.")
  128. for pn, (txt, img) in enumerate(sections):
  129. d = copy.deepcopy(doc)
  130. pn += from_page
  131. if img:
  132. d["image"] = img
  133. d["page_num_int"] = [pn + 1]
  134. d["top_int"] = [0]
  135. d["position_int"] = [(pn + 1, 0, img.size[0] if img else 0, 0, img.size[1] if img else 0)]
  136. tokenize(d, txt, eng)
  137. res.append(d)
  138. return res
  139. raise NotImplementedError(
  140. "file type not supported yet(pptx, pdf supported)")
  141. if __name__ == "__main__":
  142. import sys
  143. def dummy(a, b):
  144. pass
  145. chunk(sys.argv[1], callback=dummy)