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.

presentation.py 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. import copy
  14. import re
  15. from io import BytesIO
  16. from pptx import Presentation
  17. from deepdoc.parser import tokenize, is_english
  18. from rag.nlp import huqie
  19. from deepdoc.parser import PdfParser
  20. class Ppt(object):
  21. def __init__(self):
  22. super().__init__()
  23. def __extract(self, shape):
  24. if shape.shape_type == 19:
  25. tb = shape.table
  26. rows = []
  27. for i in range(1, len(tb.rows)):
  28. rows.append("; ".join([tb.cell(0, j).text + ": " + tb.cell(i, j).text for j in range(len(tb.columns)) if tb.cell(i, j)]))
  29. return "\n".join(rows)
  30. if shape.has_text_frame:
  31. return shape.text_frame.text
  32. if shape.shape_type == 6:
  33. texts = []
  34. for p in shape.shapes:
  35. t = self.__extract(p)
  36. if t: texts.append(t)
  37. return "\n".join(texts)
  38. def __call__(self, fnm, from_page, to_page, callback=None):
  39. ppt = Presentation(fnm) if isinstance(
  40. fnm, str) else Presentation(
  41. BytesIO(fnm))
  42. txts = []
  43. self.total_page = len(ppt.slides)
  44. for i, slide in enumerate(ppt.slides[from_page: to_page]):
  45. texts = []
  46. for shape in slide.shapes:
  47. txt = self.__extract(shape)
  48. if txt: texts.append(txt)
  49. txts.append("\n".join(texts))
  50. callback(0.5, "Text extraction finished.")
  51. import aspose.slides as slides
  52. import aspose.pydrawing as drawing
  53. imgs = []
  54. with slides.Presentation(BytesIO(fnm)) as presentation:
  55. for i, slide in enumerate(presentation.slides[from_page: to_page]):
  56. buffered = BytesIO()
  57. slide.get_thumbnail(0.5, 0.5).save(buffered, drawing.imaging.ImageFormat.jpeg)
  58. imgs.append(buffered.getvalue())
  59. assert len(imgs) == len(txts), "Slides text and image do not match: {} vs. {}".format(len(imgs), len(txts))
  60. callback(0.9, "Image extraction finished")
  61. self.is_english = is_english(txts)
  62. return [(txts[i], imgs[i]) for i in range(len(txts))]
  63. class Pdf(PdfParser):
  64. def __init__(self):
  65. super().__init__()
  66. def __garbage(self, txt):
  67. txt = txt.lower().strip()
  68. if re.match(r"[0-9\.,%/-]+$", txt): return True
  69. if len(txt) < 3:return True
  70. return False
  71. def __call__(self, filename, binary=None, from_page=0, to_page=100000, zoomin=3, callback=None):
  72. self.__images__(filename if not binary else binary, zoomin, from_page, to_page)
  73. callback(0.8, "Page {}~{}: OCR finished".format(from_page, min(to_page, self.total_page)))
  74. assert len(self.boxes) == len(self.page_images), "{} vs. {}".format(len(self.boxes), len(self.page_images))
  75. res = []
  76. #################### More precisely ###################
  77. # self._layouts_rec(zoomin)
  78. # self._text_merge()
  79. # pages = {}
  80. # for b in self.boxes:
  81. # if self.__garbage(b["text"]):continue
  82. # if b["page_number"] not in pages: pages[b["page_number"]] = []
  83. # pages[b["page_number"]].append(b["text"])
  84. # for i, lines in pages.items():
  85. # res.append(("\n".join(lines), self.page_images[i-1]))
  86. # return res
  87. ########################################
  88. for i in range(len(self.boxes)):
  89. lines = "\n".join([b["text"] for b in self.boxes[i] if not self.__garbage(b["text"])])
  90. res.append((lines, self.page_images[i]))
  91. callback(0.9, "Page {}~{}: Parsing finished".format(from_page, min(to_page, self.total_page)))
  92. return res
  93. def chunk(filename, binary=None, from_page=0, to_page=100000, callback=None, **kwargs):
  94. """
  95. The supported file formats are pdf, pptx.
  96. Every page will be treated as a chunk. And the thumbnail of every page will be stored.
  97. PPT file will be parsed by using this method automatically, setting-up for every PPT file is not necessary.
  98. """
  99. doc = {
  100. "docnm_kwd": filename,
  101. "title_tks": huqie.qie(re.sub(r"\.[a-zA-Z]+$", "", filename))
  102. }
  103. doc["title_sm_tks"] = huqie.qieqie(doc["title_tks"])
  104. res = []
  105. if re.search(r"\.pptx?$", filename, re.IGNORECASE):
  106. ppt_parser = Ppt()
  107. for txt,img in ppt_parser(filename if not binary else binary, from_page, 1000000, callback):
  108. d = copy.deepcopy(doc)
  109. d["image"] = img
  110. tokenize(d, txt, ppt_parser.is_english)
  111. res.append(d)
  112. return res
  113. elif re.search(r"\.pdf$", filename, re.IGNORECASE):
  114. pdf_parser = Pdf()
  115. for txt,img in pdf_parser(filename if not binary else binary, from_page=from_page, to_page=to_page, callback=callback):
  116. d = copy.deepcopy(doc)
  117. d["image"] = img
  118. tokenize(d, txt, pdf_parser.is_english)
  119. res.append(d)
  120. return res
  121. raise NotImplementedError("file type not supported yet(pptx, pdf supported)")
  122. if __name__== "__main__":
  123. import sys
  124. def dummy(a, b):
  125. pass
  126. chunk(sys.argv[1], callback=dummy)