File size: 6,569 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
"""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 ``<a:t>`` 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 <a:p> 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
    ``<p:sldIdLst>`` lists ``<p:sldId>`` 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
    # <p:sldIdLst> contains <p:sldId r:id="rId2" ...>
    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