Branchwell

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

1"""Add a slide to a PPTX: duplicate an existing slide or instantiate a layout.
2
3Does all of the package bookkeeping, so the deck stays valid:
4 - writes the new ppt/slides/slideN.xml (and its .rels, minus any
5 notesSlide reference, so the source's speaker notes aren't shared)
6 - registers it in [Content_Types].xml
7 - adds a slide relationship with a fresh rId to presentation.xml.rels
8 - inserts <p:sldId id="..." r:id="..."/> with a fresh id into
9 <p:sldIdLst> — at the end, or after --after SLIDE
10 - counts the new slide in docProps/app.xml
11
12Works on an unpacked directory (during an editing session) or directly on a
13.pptx/.potx file (extracted to a temp dir, then rezipped atomically; the
14temp dir is discarded, so unpack the output if you still need to edit the
15new slide's content).
16
17Usage:
18 python add_slide.py unpacked/ slide2.xml # duplicate slide2
19 python add_slide.py unpacked/ slideLayout3.xml # new slide from a layout
20 python add_slide.py unpacked/ slide2.xml --after slide2.xml
21 python add_slide.py deck.pptx slide2.xml # rewrite deck.pptx in place
22 python add_slide.py deck.pptx slide2.xml -o out.pptx
23
24A duplicated slide still holds the source's content: edit ppt/slides/slideN.xml
25(printed on success) to change it. To list layouts: ls <dir>/ppt/slideLayouts/
26"""
27
28import argparse
29import posixpath
30import re
31import shutil
32import sys
33from typing import NoReturn
34import tempfile
35import zipfile
36from pathlib import Path
37from xml.parsers.expat import ExpatError
38
39import defusedxml.minidom
40from defusedxml.common import DefusedXmlException
41
42from office.helpers import opc_target, rezip, safe_extract
43
44MINIMAL_SLIDE_XML = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
45<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">
46 <p:cSld>
47 <p:spTree>
48 <p:nvGrpSpPr>
49 <p:cNvPr id="1" name=""/>
50 <p:cNvGrpSpPr/>
51 <p:nvPr/>
52 </p:nvGrpSpPr>
53 <p:grpSpPr>
54 <a:xfrm>
55 <a:off x="0" y="0"/>
56 <a:ext cx="0" cy="0"/>
57 <a:chOff x="0" y="0"/>
58 <a:chExt cx="0" cy="0"/>
59 </a:xfrm>
60 </p:grpSpPr>
61 </p:spTree>
62 </p:cSld>
63 <p:clrMapOvr>
64 <a:masterClrMapping/>
65 </p:clrMapOvr>
66</p:sld>'''
67
68SHARED_PART_TYPES = ("chart", "diagramData", "oleObject", "package")
69
70NOTES_SLIDE_TYPE_RE = re.compile(r"""Type=["'][^"']*/relationships/notesSlide["']""")
71TAGS_TYPE_RE = re.compile(r"""Type=["'][^"']*/relationships/tags["']""")
72TAGS_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.presentationml.tags+xml"
73RELATIONSHIP_RE = re.compile(r"<Relationship\b[^>]*?(?:/>|>.*?</Relationship\s*>)", re.DOTALL)
74
75SLIDE_ID_MIN = 256
76SLIDE_ID_MAX = 2147483647
77
78
79def _die(msg: str) -> NoReturn:
80 print(f"Error: {msg}", file=sys.stderr)
81 sys.exit(1)
82
83
84def get_next_slide_number(slides_dir: Path) -> int:
85 existing = [int(m.group(1)) for f in slides_dir.glob("slide*.xml")
86 if (m := re.match(r"slide(\d+)\.xml", f.name))]
87 return max(existing) + 1 if existing else 1
88
89
90def parse_source(source: str) -> tuple[str, str | None]:
91 if source.startswith("slideLayout") and source.endswith(".xml"):
92 return ("layout", source)
93
94 return ("slide", None)
95
96
97def create_slide_from_layout(unpacked_dir: Path, layout_file: str, after: str | None = None) -> str:
98 slides_dir = unpacked_dir / "ppt" / "slides"
99 rels_dir = slides_dir / "_rels"
100 layout_path = unpacked_dir / "ppt" / "slideLayouts" / layout_file
101
102 if not layout_path.exists():
103 _die(f"{layout_path} not found")
104
105 next_num = get_next_slide_number(slides_dir)
106 dest = f"slide{next_num}.xml"
107 after_rid = _precheck_registration(unpacked_dir, after, dest)
108 slides_dir.mkdir(parents=True, exist_ok=True)
109
110 (slides_dir / dest).write_text(MINIMAL_SLIDE_XML, encoding="utf-8")
111
112 rels_dir.mkdir(exist_ok=True)
113 rels_xml = f'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
114<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
115 <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/{layout_file}"/>
116</Relationships>'''
117 (rels_dir / f"{dest}.rels").write_text(rels_xml, encoding="utf-8")
118
119 _register_slide(unpacked_dir, dest, layout_file, after_rid)
120 return dest
121
122
123def duplicate_slide(unpacked_dir: Path, source: str, after: str | None = None) -> str:
124 slides_dir = unpacked_dir / "ppt" / "slides"
125 rels_dir = slides_dir / "_rels"
126 source_slide = slides_dir / source
127
128 if not source_slide.exists():
129 _die(f"{source_slide} not found")
130
131 next_num = get_next_slide_number(slides_dir)
132 dest = f"slide{next_num}.xml"
133 after_rid = _precheck_registration(unpacked_dir, after, dest)
134
135 shutil.copy2(source_slide, slides_dir / dest)
136
137 source_rels = rels_dir / f"{source}.rels"
138 shared_parts: list[str] = []
139 if source_rels.exists():
140 dest_rels = rels_dir / f"{dest}.rels"
141 shutil.copy2(source_rels, dest_rels)
142 rels_content = dest_rels.read_text(encoding="utf-8")
143 rels_content = RELATIONSHIP_RE.sub(
144 lambda m: "" if NOTES_SLIDE_TYPE_RE.search(m.group(0)) else m.group(0),
145 rels_content,
146 )
147 rels_content = RELATIONSHIP_RE.sub(
148 lambda m: _with_own_tags_part(unpacked_dir, m.group(0), f"ppt/slides/{dest}")
149 if TAGS_TYPE_RE.search(m.group(0)) else m.group(0),
150 rels_content,
151 )
152 dest_rels.write_text(rels_content, encoding="utf-8")
153 shared_parts = sorted({
154 t for t in re.findall(r'Type="[^"]*/relationships/(\w+)"', rels_content)
155 if t in SHARED_PART_TYPES
156 })
157
158 _register_slide(unpacked_dir, dest, source, after_rid)
159 if shared_parts:
160 print(
161 f"Note: {dest} shares its {', '.join(shared_parts)} part(s) with {source} "
162 f"(they are referenced, not copied) — editing those parts changes both slides"
163 )
164 return dest
165
166
167def _with_own_tags_part(unpacked_dir: Path, relationship: str, slide_part: str) -> str:
168 target = re.search(r"""Target=["']([^"']*)["']""", relationship)
169 try:
170 source = opc_target(target.group(1), slide_part) if target else None
171 except ValueError:
172 source = None
173 if source is None or not (unpacked_dir / source).is_file():
174 return relationship
175
176 tags_dir = (unpacked_dir / source).parent
177 content_types_path = unpacked_dir / "[Content_Types].xml"
178 content_types = content_types_path.read_text(encoding="utf-8")
179 names = [f.name for f in tags_dir.iterdir()] + re.findall(r"""PartName=["'][^"']*/([^/"']+)["']""", content_types)
180 taken = [int(m.group(1)) for name in names if (m := re.fullmatch(r"tag(\d{1,9})\.xml", name, re.I))]
181 copy = tags_dir / f"tag{max(taken, default=0) + 1}.xml"
182 shutil.copy2(unpacked_dir / source, copy)
183
184 part = copy.relative_to(unpacked_dir).as_posix()
185 override = f'<Override PartName="/{part}" ContentType="{TAGS_CONTENT_TYPE}"/>'
186 content_types_path.write_text(
187 content_types.replace("</Types>", f" {override}\n</Types>"), encoding="utf-8"
188 )
189 relative = posixpath.relpath(part, posixpath.dirname(slide_part))
190 return relationship.replace(target.group(0), f'Target="{relative}"')
191
192
193def _precheck_registration(unpacked_dir: Path, after: str | None, dest: str) -> str | None:
194 pres_path = unpacked_dir / "ppt" / "presentation.xml"
195 if not pres_path.exists():
196 _die(f"{pres_path} not found — is this an unpacked PPTX?")
197 xml = pres_path.read_text(encoding="utf-8")
198
199 has_slot = (
200 "</p:sldIdLst>" in xml
201 or re.search(r"<p:sldIdLst\s*/>", xml)
202 or "</p:sldMasterIdLst>" in xml
203 )
204 if not has_slot:
205 _die("presentation.xml has no <p:sldIdLst> (or <p:sldMasterIdLst> to anchor a new one)")
206
207 stale = []
208 content_types = unpacked_dir / "[Content_Types].xml"
209 if content_types.exists() and f'PartName="/ppt/slides/{dest}"' in content_types.read_text(encoding="utf-8"):
210 stale.append("[Content_Types].xml")
211 pres_rels = unpacked_dir / "ppt" / "_rels" / "presentation.xml.rels"
212 if pres_rels.exists() and _find_slide_relationship(
213 pres_rels.read_text(encoding="utf-8"), dest
214 ):
215 stale.append("presentation.xml.rels")
216 if stale:
217 _die(
218 f"{dest} is still registered in {' and '.join(stale)} but absent from ppt/slides/ — "
219 f"run clean.py first"
220 )
221
222 if not after:
223 return None
224 after_rid = _rid_for_slide(unpacked_dir, after)
225 if not re.search(rf'<p:sldId\b[^>]*r:id="{re.escape(after_rid)}"[^>]*>', xml):
226 _die(f"{after} ({after_rid}) is not listed in <p:sldIdLst>")
227 return after_rid
228
229
230def _register_slide(unpacked_dir: Path, dest: str, source_desc: str, after_rid: str | None) -> None:
231 _add_to_content_types(unpacked_dir, dest)
232 rid = _add_to_presentation_rels(unpacked_dir, dest)
233 slide_id = _get_next_slide_id(unpacked_dir)
234 pos, total = _insert_into_sld_id_lst(unpacked_dir, slide_id, rid, after_rid)
235
236 _count_slide_in_app_properties(unpacked_dir, pos)
237
238 print(f"Created ppt/slides/{dest} from {source_desc}")
239 print(
240 f'Inserted <p:sldId id="{slide_id}" r:id="{rid}"/> into <p:sldIdLst> '
241 f"at position {pos} of {total}"
242 )
243
244
245def _count_slide_in_app_properties(unpacked_dir: Path, position: int) -> None:
246 path = unpacked_dir / "docProps" / "app.xml"
247 if not path.is_file():
248 return
249 try:
250 dom = defusedxml.minidom.parse(str(path))
251 slides = _only_child(dom.documentElement, "Slides")
252 was = int(slides.firstChild.data)
253 if not _add_slide_title(dom, was, position):
254 return
255 except (AttributeError, LookupError, ValueError, TypeError, OSError, ExpatError, DefusedXmlException):
256 return
257 slides.firstChild.data = str(was + 1)
258 path.write_bytes(dom.toxml(encoding="UTF-8", standalone=dom.standalone))
259
260
261def _add_slide_title(dom, was: int, position: int) -> bool:
262 heading_pairs = _only_child(dom.documentElement, "HeadingPairs")
263 titles_of_parts = _only_child(dom.documentElement, "TitlesOfParts")
264 if heading_pairs is None and titles_of_parts is None:
265 return True
266 headings, titles = _only_child(heading_pairs, "vector"), _only_child(titles_of_parts, "vector")
267 pairs = [v.getElementsByTagName("*")[0] for v in _elements(headings)]
268 names = [n.firstChild.data if n.firstChild else "" for n in pairs[0::2]]
269 counts = pairs[1::2]
270 sizes = [int(c.firstChild.data) for c in counts]
271 entries = _elements(titles)
272 consistent = (
273 int(headings.getAttribute("size")) == 2 * len(counts) == len(_elements(headings))
274 and int(titles.getAttribute("size")) == len(entries) == sum(sizes)
275 )
276 titled = [i for i, name in enumerate(names) if name == "Slide Titles"]
277 as_long = [i for i in titled or range(len(sizes)) if sizes[i] == was > 0]
278 if not consistent or len(as_long) != 1:
279 return False
280 (group,) = as_long
281
282 title = entries[0].cloneNode(False)
283 title.appendChild(dom.createTextNode(f"Slide {was + 1}"))
284 at = sum(sizes[:group]) + min(position - 1, was)
285 titles.insertBefore(title, entries[at] if at < len(entries) else None)
286 titles.setAttribute("size", str(len(entries) + 1))
287 counts[group].firstChild.data = str(was + 1)
288 return True
289
290
291def _elements(node) -> list:
292 return [c for c in node.childNodes if c.nodeType == c.ELEMENT_NODE]
293
294
295def _only_child(node, local_name: str):
296 found = [c for c in _elements(node) if c.localName == local_name] if node else []
297 return found[0] if len(found) == 1 else None
298
299
300def _add_to_content_types(unpacked_dir: Path, dest: str) -> None:
301 content_types_path = unpacked_dir / "[Content_Types].xml"
302 content_types = content_types_path.read_text(encoding="utf-8")
303
304 new_override = f'<Override PartName="/ppt/slides/{dest}" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>'
305
306 if f'PartName="/ppt/slides/{dest}"' not in content_types:
307 content_types = content_types.replace("</Types>", f" {new_override}\n</Types>")
308 content_types_path.write_text(content_types, encoding="utf-8")
309
310
311def _add_to_presentation_rels(unpacked_dir: Path, dest: str) -> str:
312 pres_rels_path = unpacked_dir / "ppt" / "_rels" / "presentation.xml.rels"
313 pres_rels = pres_rels_path.read_text(encoding="utf-8")
314
315 existing = _find_slide_relationship(pres_rels, dest)
316 if existing:
317 return existing
318
319 pres_xml = (unpacked_dir / "ppt" / "presentation.xml").read_text(encoding="utf-8")
320 used = {int(n) for n in re.findall(r'\bId="rId(\d+)"', pres_rels)}
321 used |= {int(n) for n in re.findall(r'\br:id="rId(\d+)"', pres_xml)}
322 rid = f"rId{max(used) + 1 if used else 1}"
323
324 new_rel = f'<Relationship Id="{rid}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/{dest}"/>'
325 pres_rels = pres_rels.replace("</Relationships>", f" {new_rel}\n</Relationships>")
326 pres_rels_path.write_text(pres_rels, encoding="utf-8")
327
328 return rid
329
330
331def _find_slide_relationship(pres_rels: str, slide_name: str) -> str | None:
332 for m in re.finditer(r"<Relationship\b[^>]*>", pres_rels):
333 element = m.group(0)
334 if re.search(rf'Target="(?:/ppt/)?slides/{re.escape(slide_name)}"', element):
335 id_match = re.search(r'\bId="([^"]+)"', element)
336 if id_match:
337 return id_match.group(1)
338 return None
339
340
341def _get_next_slide_id(unpacked_dir: Path) -> int:
342 pres_content = (unpacked_dir / "ppt" / "presentation.xml").read_text(encoding="utf-8")
343 used = {int(m) for m in re.findall(r'<p:sldId[^>]*\bid="(\d+)"', pres_content)}
344
345 candidate = max((i for i in used if i >= SLIDE_ID_MIN), default=SLIDE_ID_MIN - 1) + 1
346 if candidate <= SLIDE_ID_MAX and candidate not in used:
347 return candidate
348 for i in range(SLIDE_ID_MIN, SLIDE_ID_MAX + 1):
349 if i not in used:
350 return i
351 _die("no slide id available in [256, 2147483647] — the deck is full")
352
353
354def _insert_into_sld_id_lst(
355 unpacked_dir: Path, slide_id: int, rid: str, after_rid: str | None = None
356) -> tuple[int, int]:
357 pres_path = unpacked_dir / "ppt" / "presentation.xml"
358 xml = pres_path.read_text(encoding="utf-8")
359 entry = f'<p:sldId id="{slide_id}" r:id="{rid}"/>'
360
361 if f'r:id="{rid}"' in xml:
362 _die(f"presentation.xml already references {rid}; refusing to add a duplicate")
363
364 if after_rid:
365 open_tag = re.search(rf'<p:sldId\b[^>]*r:id="{re.escape(after_rid)}"[^>]*>', xml)
366 if not open_tag:
367 _die(f"{after_rid} is not listed in <p:sldIdLst>")
368 end = open_tag.end()
369 if not open_tag.group(0).endswith("/>"):
370 close = xml.find("</p:sldId>", end)
371 if close == -1:
372 _die(f"unclosed <p:sldId> for {after_rid} in presentation.xml")
373 end = close + len("</p:sldId>")
374 xml = xml[:end] + entry + xml[end:]
375 elif "</p:sldIdLst>" in xml:
376 xml = xml.replace("</p:sldIdLst>", f"{entry}</p:sldIdLst>", 1)
377 elif re.search(r"<p:sldIdLst\s*/>", xml):
378 xml = re.sub(r"<p:sldIdLst\s*/>", f"<p:sldIdLst>{entry}</p:sldIdLst>", xml, count=1)
379 elif "</p:sldMasterIdLst>" in xml:
380 xml = xml.replace(
381 "</p:sldMasterIdLst>", f"</p:sldMasterIdLst><p:sldIdLst>{entry}</p:sldIdLst>", 1
382 )
383 else:
384 _die("presentation.xml has no <p:sldIdLst> (or <p:sldMasterIdLst> to anchor a new one)")
385
386 pres_path.write_text(xml, encoding="utf-8")
387
388 lst = re.search(r"<p:sldIdLst>(.*)</p:sldIdLst>", xml, re.DOTALL)
389 entries = re.findall(r"<p:sldId\b[^>]*>", lst.group(1)) if lst else []
390 position = next(
391 (i for i, e in enumerate(entries, 1) if f'r:id="{rid}"' in e), len(entries)
392 )
393 return position, len(entries)
394
395
396def _rid_for_slide(unpacked_dir: Path, slide_name: str) -> str:
397 pres_rels_path = unpacked_dir / "ppt" / "_rels" / "presentation.xml.rels"
398 rid = _find_slide_relationship(pres_rels_path.read_text(encoding="utf-8"), slide_name)
399 if not rid:
400 _die(f"{slide_name} has no relationship in presentation.xml.rels")
401 return rid
402
403
404def add_slide(unpacked_dir: Path, source: str, after: str | None = None) -> str:
405 source_type, layout_file = parse_source(source)
406 if source_type == "layout" and layout_file is not None:
407 return create_slide_from_layout(unpacked_dir, layout_file, after)
408 return duplicate_slide(unpacked_dir, source, after)
409
410
411def add_slide_to_package(
412 package: Path, source: str, after: str | None = None, output: Path | None = None
413) -> str:
414 out = output or package
415 with tempfile.TemporaryDirectory() as tmp:
416 tmp_path = Path(tmp)
417 with zipfile.ZipFile(package) as zf:
418 safe_extract(zf, tmp_path)
419 dest = add_slide(tmp_path, source, after)
420 rezip(tmp_path, out)
421 print(f"Wrote {out} — the new slide is ppt/slides/{dest} inside it (unpack to edit its content)")
422 return dest
423
424
425def main() -> None:
426 parser = argparse.ArgumentParser(
427 description="Add a slide to a PPTX: duplicate a slide or instantiate a layout. "
428 "Registers content types, relationships, and <p:sldIdLst>."
429 )
430 parser.add_argument("target", help="Unpacked PPTX directory OR a .pptx/.potx file")
431 parser.add_argument(
432 "source",
433 help="slideN.xml to duplicate, or slideLayoutN.xml to create from a layout "
434 "(list layouts with: ls <dir>/ppt/slideLayouts/)",
435 )
436 parser.add_argument(
437 "--after",
438 metavar="SLIDE",
439 help="insert after this slide, e.g. slide2.xml (default: append at the end)",
440 )
441 parser.add_argument(
442 "-o",
443 "--output",
444 help="output file (only with a .pptx/.potx target; default: rewrite the input in place)",
445 )
446 args = parser.parse_args()
447
448 target = Path(args.target)
449 if target.is_dir():
450 if args.output:
451 parser.error("--output is only valid for .pptx/.potx input; a directory is modified in place")
452 add_slide(target, args.source, args.after)
453 elif target.is_file() and target.suffix.lower() in (".pptx", ".potx"):
454 try:
455 add_slide_to_package(target, args.source, args.after, Path(args.output) if args.output else None)
456 except (OSError, ValueError, zipfile.BadZipFile) as e:
457 _die(str(e))
458 else:
459 _die(f"{target} is neither a directory nor a .pptx/.potx file")
460
461
462if __name__ == "__main__":
463 main()