pptx_read.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. #!/usr/bin/env python3
  2. """Read a .pptx file: JSON outline, notes, or export embedded images.
  3. Modes:
  4. --outline JSON with per-slide layout, texts, tables, notes,
  5. chart data, and image inventory (default mode).
  6. --notes JSON list of speaker notes per slide.
  7. --images DIR Export every embedded picture to DIR as files.
  8. """
  9. import argparse
  10. import json
  11. import os
  12. import sys
  13. from pptx import Presentation
  14. from pptx.enum.shapes import MSO_SHAPE_TYPE
  15. from pptx.util import Emu
  16. def iter_shapes(shapes):
  17. """Yield shapes, descending into groups."""
  18. for shape in shapes:
  19. if shape.shape_type == MSO_SHAPE_TYPE.GROUP:
  20. yield from iter_shapes(shape.shapes)
  21. else:
  22. yield shape
  23. def chart_info(chart):
  24. info = {"type": str(chart.chart_type),
  25. "categories": [str(c) for c in chart.plots[0].categories],
  26. "series": []}
  27. for plot in chart.plots:
  28. for series in plot.series:
  29. try:
  30. name = series.name
  31. except (AttributeError, KeyError):
  32. name = None
  33. info["series"].append({"name": name,
  34. "values": list(series.values)})
  35. return info
  36. def slide_record(index, slide):
  37. rec = {"index": index, "layout": slide.slide_layout.name,
  38. "texts": [], "tables": [], "images": [], "charts": [],
  39. "notes": None}
  40. for shape in iter_shapes(slide.shapes):
  41. if shape.has_text_frame and shape.text_frame.text.strip():
  42. rec["texts"].append(shape.text_frame.text)
  43. if shape.has_table:
  44. rec["tables"].append(
  45. [[cell.text for cell in row.cells]
  46. for row in shape.table.rows])
  47. if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
  48. try:
  49. img = shape.image
  50. rec["images"].append({"filename": img.filename,
  51. "ext": img.ext,
  52. "size_bytes": len(img.blob)})
  53. except (KeyError, ValueError):
  54. rec["images"].append({"filename": None, "ext": None,
  55. "size_bytes": None,
  56. "note": "linked or unreadable"})
  57. if shape.has_chart:
  58. rec["charts"].append(chart_info(shape.chart))
  59. if slide.has_notes_slide:
  60. rec["notes"] = slide.notes_slide.notes_text_frame.text
  61. return rec
  62. def export_images(prs, out_dir):
  63. os.makedirs(out_dir, exist_ok=True)
  64. written = []
  65. for i, slide in enumerate(prs.slides):
  66. for j, shape in enumerate(iter_shapes(slide.shapes)):
  67. if shape.shape_type != MSO_SHAPE_TYPE.PICTURE:
  68. continue
  69. try:
  70. img = shape.image
  71. except (KeyError, ValueError):
  72. continue
  73. path = os.path.join(out_dir, f"slide{i}_img{j}.{img.ext}")
  74. with open(path, "wb") as fh:
  75. fh.write(img.blob)
  76. written.append(path)
  77. return written
  78. def main(argv=None):
  79. if hasattr(sys.stdout, "reconfigure"):
  80. sys.stdout.reconfigure(encoding="utf-8", errors="replace")
  81. parser = argparse.ArgumentParser(
  82. description="Read a .pptx: outline/notes as JSON, export images.")
  83. parser.add_argument("pptx", help="path to the .pptx file")
  84. parser.add_argument("--outline", action="store_true",
  85. help="print full JSON outline (default)")
  86. parser.add_argument("--notes", action="store_true",
  87. help="print speaker notes only")
  88. parser.add_argument("--images", metavar="DIR",
  89. help="export embedded images into DIR")
  90. args = parser.parse_args(argv)
  91. prs = Presentation(args.pptx)
  92. if args.images:
  93. written = export_images(prs, args.images)
  94. print(json.dumps({"ok": True, "exported": written}, indent=2))
  95. return 0
  96. if args.notes:
  97. notes = [slide.notes_slide.notes_text_frame.text
  98. if slide.has_notes_slide else None
  99. for slide in prs.slides]
  100. print(json.dumps({"ok": True, "notes": notes},
  101. indent=2, ensure_ascii=True))
  102. return 0
  103. outline = {
  104. "ok": True,
  105. "slide_size_inches": [round(Emu(prs.slide_width).inches, 3),
  106. round(Emu(prs.slide_height).inches, 3)],
  107. "slide_count": len(prs.slides._sldIdLst),
  108. "layouts_available": [lay.name for lay in prs.slide_layouts],
  109. "slides": [slide_record(i, s) for i, s in enumerate(prs.slides)],
  110. }
  111. print(json.dumps(outline, indent=2, ensure_ascii=True))
  112. return 0
  113. if __name__ == "__main__":
  114. sys.exit(main())