Branchwell

Skillfarm / skills · skillfarm.ai / converted / pptx / scripts / slide_text.py

1"""Print each slide of a .pptx, .pptm, .potx or .ppsx as markdown under `<!-- Slide number: N -->`.
2
3Title, text, tables, chart data, picture alt text and speaker notes; shapes top to bottom.
4
5Usage: python slide_text.py deck.pptx
6"""
7
8import os
9import re
10import sys
11import zipfile
12
13from pptx.package import Package
14
15
16def _position(shape):
17 try:
18 return (shape.top or 0, shape.left or 0)
19 except Exception:
20 return (0, 0)
21
22
23def _one_line(text) -> str:
24 return " ".join(str(text).split())
25
26
27def _table(rows) -> list[str]:
28 lines = ["| " + " | ".join(_one_line(c).replace("|", "\\|") for c in r) + " |" for r in rows]
29 if lines:
30 lines.insert(1, "|" + " --- |" * len(rows[0]))
31 return lines
32
33
34def _chart(chart) -> list[str]:
35 heading = "### Chart"
36 try:
37 if chart.has_title and chart.chart_title.has_text_frame:
38 heading += ": " + _one_line(chart.chart_title.text_frame.text)
39 categories = [c.label for c in chart.plots[0].categories]
40 series = [(s.name, list(s.values)) for s in chart.series]
41 except Exception as e:
42 return [
43 heading,
44 f"[chart data not readable ({type(e).__name__}): render the slide to see it]",
45 ]
46 rows = [["Category", *(name for name, _ in series)]]
47 for i, category in enumerate(categories):
48 rows.append([category, *(v[i] if i < len(v) else "" for _, v in series)])
49 return [heading, "", *_table(rows)]
50
51
52def _shape(shape) -> list[str]:
53 tag = shape._element.tag
54 if tag.endswith("}grpSp"):
55 return _shapes(shape.shapes)
56 if tag.endswith("}pic"):
57 alt = _one_line(shape._element._nvXxPr.cNvPr.get("descr", ""))
58 return [f"![{alt}]({shape.name})"]
59 if getattr(shape, "has_table", False):
60 return ["", *_table([[c.text for c in r.cells] for r in shape.table.rows]), ""]
61 if getattr(shape, "has_chart", False):
62 return ["", *_chart(shape.chart), ""]
63 if shape.has_text_frame and shape.text_frame.text.strip():
64 text = shape.text_frame.text.replace("\v", "\n")
65 is_title = shape.is_placeholder and shape.placeholder_format.idx == 0
66 return ["# " + text.lstrip() if is_title else text]
67 return []
68
69
70def _members(shapes) -> list:
71 try:
72 return list(shapes)
73 except Exception:
74 pass
75 members = []
76 for i in range(len(shapes)):
77 try:
78 members.append(shapes[i])
79 except Exception as e:
80 members.append(e)
81 return members
82
83
84def _shapes(shapes) -> list[str]:
85 lines = []
86 for shape in sorted(_members(shapes), key=_position):
87 try:
88 if isinstance(shape, Exception):
89 raise shape
90 lines += _shape(shape)
91 except Exception as e:
92 lines.append(f"[shape not readable ({type(e).__name__}): render the slide to see it]")
93 return lines
94
95
96def slide_text(slide, number: int) -> str:
97 lines = [f"<!-- Slide number: {number} -->", *_shapes(slide.shapes)]
98 try:
99 notes = slide.notes_slide.notes_text_frame if slide.has_notes_slide else None
100 if notes is not None and notes.text.strip():
101 lines += ["", "### Notes:", notes.text.replace("\v", "\n")]
102 except Exception as e:
103 lines += ["", f"[notes not readable ({type(e).__name__})]"]
104 return re.sub(r"\n{3,}", "\n\n", "\n".join(lines).strip())
105
106
107def main() -> None:
108 if len(sys.argv) != 2:
109 sys.exit("Usage: python slide_text.py deck.pptx")
110 path = sys.argv[1]
111 if not os.path.isfile(path):
112 sys.exit(f"Error: {path} {'is not a file' if os.path.exists(path) else 'does not exist'}")
113 if not zipfile.is_zipfile(path):
114 sys.exit(
115 f"Error: {path} is corrupt, password-protected, or an old .ppt (not a zip archive)"
116 )
117 try:
118 deck = getattr(Package.open(path).main_document_part, "presentation", None)
119 except Exception as e:
120 sys.exit(f"Error: cannot read {path}: {e}")
121 if deck is None:
122 sys.exit(f"Error: {path} is not a .pptx, .pptm, .potx or .ppsx file")
123 sys.stdout.reconfigure(errors="replace")
124 try:
125 blocks = [slide_text(s, n) for n, s in enumerate(deck.slides, 1)]
126 print("\n\n".join(blocks) or "[no slides; layouts and masters are not printed]", flush=True)
127 except BrokenPipeError:
128 os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
129
130
131if __name__ == "__main__":
132 main()