Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

presentation.py 5.7KB

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