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

ppt_parser.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 logging
  14. from io import BytesIO
  15. from pptx import Presentation
  16. class RAGFlowPptParser(object):
  17. def __init__(self):
  18. super().__init__()
  19. def __extract(self, shape):
  20. if shape.shape_type == 19:
  21. tb = shape.table
  22. rows = []
  23. for i in range(1, len(tb.rows)):
  24. rows.append("; ".join([tb.cell(
  25. 0, j).text + ": " + tb.cell(i, j).text for j in range(len(tb.columns)) if tb.cell(i, j)]))
  26. return "\n".join(rows)
  27. if shape.has_text_frame:
  28. return shape.text_frame.text
  29. if shape.shape_type == 6:
  30. texts = []
  31. for p in sorted(shape.shapes, key=lambda x: (x.top // 10, x.left)):
  32. t = self.__extract(p)
  33. if t:
  34. texts.append(t)
  35. return "\n".join(texts)
  36. def __call__(self, fnm, from_page, to_page, callback=None):
  37. ppt = Presentation(fnm) if isinstance(
  38. fnm, str) else Presentation(
  39. BytesIO(fnm))
  40. txts = []
  41. self.total_page = len(ppt.slides)
  42. for i, slide in enumerate(ppt.slides):
  43. if i < from_page:
  44. continue
  45. if i >= to_page:
  46. break
  47. texts = []
  48. for shape in sorted(
  49. slide.shapes, key=lambda x: ((x.top if x.top is not None else 0) // 10, x.left)):
  50. try:
  51. txt = self.__extract(shape)
  52. if txt:
  53. texts.append(txt)
  54. except Exception as e:
  55. logging.exception(e)
  56. txts.append("\n".join(texts))
  57. return txts