您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

presentation.py 6.7KB

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