"""Raw-zip notes reader — side-effect-free alternative to python-pptx notes API. python-pptx lazily creates an empty notes slide on disk when you access ``slide.notes_slide`` on a slide that has no existing notes. This module reads speaker notes by opening the ``.pptx`` (which is a ZIP archive) and parsing ``ppt/notesSlides/notesSlide*.xml`` directly, so the source file is **never mutated**. Public API ---------- read_notes_xml(path: Path) -> dict[int, str] Returns a mapping of *1-indexed slide number* → notes text. Only slides that have a non-empty notes file are included (slides without a notes file at all are absent from the dict, not present with an empty string). The slide-number mapping is derived from the ``notesSlide*.xml.rels`` file that accompanies each notes slide: ppt/notesSlides/_rels/notesSlideN.xml.rels contains a ``Relationship`` element whose ``Target`` attribute points to ``../slides/slideM.xml``. We parse that to resolve notesSlideN → slideM, then use the slide ordering in ``ppt/presentation.xml`` to convert slideM filename to a 1-indexed slide number. """ from __future__ import annotations import re import zipfile from pathlib import Path from xml.etree import ElementTree as ET # --------------------------------------------------------------------------- # XML namespace shortcuts # --------------------------------------------------------------------------- _NS_DRAWINGML = "http://schemas.openxmlformats.org/drawingml/2006/main" _NS_RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships" _NS_PRESENTATION = "http://schemas.openxmlformats.org/presentationml/2006/main" # Pattern matching actual notes slide XML (not rels, not master) _NOTES_SLIDE_RE = re.compile(r"^ppt/notesSlides/notesSlide(\d+)\.xml$") _NOTES_RELS_RE = re.compile(r"^ppt/notesSlides/_rels/notesSlide(\d+)\.xml\.rels$") def _extract_text_from_xml(xml_bytes: bytes) -> str: """Return all ```` text content joined with newlines.""" root = ET.fromstring(xml_bytes) texts: list[str] = [] for elem in root.iter(f"{{{_NS_DRAWINGML}}}t"): if elem.text: texts.append(elem.text) # Join runs; paragraphs are separated by but we keep it simple here # (the consumer wants readable plain text, not XML structure). return "\n".join(t for t in texts if t.strip()) def _build_slide_order(zip_file: zipfile.ZipFile) -> dict[str, int]: """Return a mapping of slide filename (e.g. 'slide3.xml') → 1-based index. The authoritative slide order comes from ``ppt/presentation.xml`` where ```` lists ```` elements in display order; each has an ``r:id`` attribute we can match against the presentation relationships. """ # Read presentation.xml try: prs_xml = zip_file.read("ppt/presentation.xml") except KeyError: return {} # Read presentation relationships to resolve r:id → slide filename try: prs_rels_xml = zip_file.read("ppt/_rels/presentation.xml.rels") except KeyError: return {} rels_root = ET.fromstring(prs_rels_xml) rid_to_target: dict[str, str] = {} for rel in rels_root.iter(f"{{{_NS_RELATIONSHIPS}}}Relationship"): rid = rel.get("Id", "") target = rel.get("Target", "") # We only care about slide relationships if "slides/slide" in target and "_rels" not in target: # Target is relative: "slides/slide1.xml" filename = target.split("/")[-1] rid_to_target[rid] = filename # Parse presentation.xml for the ordered list of slide r:ids prs_root = ET.fromstring(prs_xml) ns_r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships" slide_order: dict[str, int] = {} idx = 1 # contains for sld_id_elem in prs_root.iter(f"{{{_NS_PRESENTATION}}}sldId"): rid = sld_id_elem.get(f"{{{ns_r}}}id", "") if rid in rid_to_target: slide_order[rid_to_target[rid]] = idx idx += 1 return slide_order def _resolve_notes_to_slide_numbers( zip_file: zipfile.ZipFile, ) -> dict[int, int]: """Return mapping of notes-slide index N → 1-based slide number. Each ``ppt/notesSlides/_rels/notesSlideN.xml.rels`` has a Relationship whose Target ends with ``../slides/slideM.xml``. We combine that with the slide order map to get the final 1-based slide number. """ slide_order = _build_slide_order(zip_file) notes_to_slide: dict[int, int] = {} for name in zip_file.namelist(): m = _NOTES_RELS_RE.match(name) if not m: continue notes_idx = int(m.group(1)) try: rels_xml = zip_file.read(name) except KeyError: continue rels_root = ET.fromstring(rels_xml) for rel in rels_root.iter(f"{{{_NS_RELATIONSHIPS}}}Relationship"): target = rel.get("Target", "") if "slides/slide" in target: filename = target.split("/")[-1] # e.g. "slide3.xml" slide_num = slide_order.get(filename) if slide_num is not None: notes_to_slide[notes_idx] = slide_num break return notes_to_slide def read_notes_xml(path: Path) -> dict[int, str]: """Return ``{slide_number: notes_text}`` by reading the ZIP directly. Parameters ---------- path: Absolute or relative path to the ``.pptx`` file. Returns ------- dict[int, str] Mapping of 1-indexed slide number to speaker notes text. Only slides with non-empty notes content are included. The file at *path* is opened read-only and is never modified. """ path = Path(path) result: dict[int, str] = {} with zipfile.ZipFile(path, "r") as zf: notes_to_slide = _resolve_notes_to_slide_numbers(zf) for name in zf.namelist(): m = _NOTES_SLIDE_RE.match(name) if not m: continue notes_idx = int(m.group(1)) slide_num = notes_to_slide.get(notes_idx) if slide_num is None: # Fallback: use notes index directly as slide number slide_num = notes_idx try: xml_bytes = zf.read(name) except KeyError: continue text = _extract_text_from_xml(xml_bytes) if text.strip(): result[slide_num] = text return result