Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

presentation.py 5.5KB

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