Skip to content

Commit e8a2766

Browse files
authored
feat(deck): notesMode keep|strip|export — speaker notes policy for the PPTX build (#666)
* feat(deck): notesMode keep|strip|export — speaker notes policy for the PPTX build deck.json "notesMode" decides what the build does with each slide's "notes": "keep" (default, unchanged) writes them as speaker notes; "strip" leaves them out of the .pptx; "export" leaves them out and writes <output stem>.notes.md next to the .pptx (one "## pageNN — title" section per slide, {{...}} styling removed), returned as notes_path by generate / generate_pptx. A deck handed to an audience must not carry the presenter's script, which imported slides often bring along in their original notes. The slide files keep their notes, so composing and check_specs are unchanged; an invalid value is a check_specs error and stops the build (no silent default). Partial builds (only_slugs / iso.pptx) write no notes file. - engine/schema: NOTES_MODES, deck_notes_mode(), validate_specs error - engine/builder: PPTXBuilder(write_notes=...) - engine/notes.py: plain_notes_text, speaker_notes_markdown - api: BuildConfig.notes_mode, generate() export + notes_path - guide slide-json-spec.md, CHANGELOG, tests/test_notes_mode.py (22) * fix(notesMode): remote generate_pptx uploads the exported notes; stale notes file cleanup; PPTX-only note Review on #666: 1. servers/remote generate_pptx built into a temp workspace and uploaded only the .pptx, so "export" silently acted like "strip" on the AWS stack. The notes file now goes to pptx/<deckId>/<build>.notes.md (same build id as the .pptx), the deck record gets notesS3Key (cleared on a keep/strip rebuild), the superseded notes object is deleted like the old .pptx, and the result carries notesS3Key plus a signed notesUrl. 2. A full build in keep/strip mode deletes a <stem>.notes.md left by an earlier export build; partial builds never touch it. 3. Guide: PPTX decks only (HTML decks keep their <aside class="notes">). Tests: test_mcp_generate (export upload + keep clears), test_notes_mode (stale cleanup). --------- Co-authored-by: Hyunmin Kim <4966343+hmkim@users.noreply.github.com>
1 parent 30f2b6a commit e8a2766

10 files changed

Lines changed: 439 additions & 14 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,18 @@ Under an Upgrading section, the bullets after **Local installs (`sdpm update`).*
1515

1616
### Added
1717

18+
- **Speaker notes policy** (`deck.json` `"notesMode"`). `"keep"` (the default, unchanged
19+
behaviour) writes each slide's `notes` as speaker notes; `"strip"` leaves them out of the
20+
.pptx; `"export"` leaves them out and writes them to `<output stem>.notes.md` next to the
21+
.pptx (one `## pageNN — title` section per slide, `{{...}}` styling removed), returned as
22+
`notes_path` by `generate_pptx`. A deck handed to an audience no longer carries the
23+
presenter's script, which imported slides often bring along in their original notes. The
24+
slide files keep their `notes`, so composing and `check_specs` are unchanged; an invalid
25+
value is a `check_specs` error and stops the build. Partial builds (`iso.pptx`) write no
26+
notes file; a full build in `keep` or `strip` mode deletes a notes file left by an earlier
27+
`export` build. PPTX decks only. On the AWS stack the remote `generate_pptx` uploads the
28+
notes beside the deck (`pptx/<deckId>/<build>.notes.md`, deck record `notesS3Key`) and
29+
returns `notesS3Key` and a signed `notesUrl`.
1830
- **Area charts** (`chartType: "area"`, #620). An area chart takes the same categories and
1931
series as a bar chart; `stacked: true` stacks the areas, and series `color`, `valueAxis`,
2032
`categoryAxis`, `style`, `legend` and `dataLabels` work as for `bar`. `pptx_to_json`

‎sdpm/references/guides/slide-json-spec.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ Metadata only. Do NOT put slides here.
3939
- `"defaultBackground"`: Optional. Solid ground for every slide that does not set its own `background` (e.g. `"#FFF6E5"`). `apply_style` fills it from the style's `--color-bg`; omit to keep the template background. Table auto-colors and icon theme (dark/light) follow it.
4040
- `"title"`: Optional. Document title written to the PPTX properties (shown by PowerPoint and read by screen readers). Defaults to the first slide's title text.
4141
- `"language"`: Optional. Document language as a BCP 47 tag (e.g. `"en-US"`, `"ja-JP"`), written to the PPTX properties.
42+
- `"notesMode"`: Optional. What the build does with each slide's `notes`: `"keep"` (default) writes them as speaker notes; `"strip"` leaves them out of the .pptx; `"export"` leaves them out and writes them to `<output stem>.notes.md` next to the .pptx (`output.pptx` → `output.notes.md`, one `## pageNN — title` section per slide, styling removed). Use `strip` or `export` for a deck handed to the audience: imported slides often carry their presenter's internal notes. The slide files keep their `notes` either way, so composing is unchanged. A full build in `keep` or `strip` mode deletes a `<output stem>.notes.md` left by an earlier `export` build. PPTX decks only: an HTML deck keeps its `<aside class="notes">` whatever the value. Any other value stops the build.
4243
- Line color, table color, and chart color are auto-resolved from the template's theme colors.
4344

4445
### slides/{slug}.json

‎sdpm/sdpm/api.py‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,7 @@ class BuildConfig:
649649
default_background: str | None = None # deck.json "defaultBackground"; None keeps template ground
650650
title: str | None = None # deck.json "title" -> dc:title; None falls back to the first slide's title
651651
language: str | None = None # deck.json "language" -> dc:language (BCP 47, e.g. "en-US")
652+
notes_mode: str = "keep" # deck.json "notesMode": keep | strip | export (sdpm.engine.schema.NOTES_MODES)
652653

653654

654655
def _assemble_slides_from_dir(
@@ -793,6 +794,11 @@ def _resolve_config(
793794

794795
template_file, custom = _resolve_template(data, str(input_path), templates_dirs)
795796

797+
# Speaker notes policy; an invalid value stops the build (no silent default)
798+
from sdpm.engine.schema import deck_notes_mode
799+
800+
notes_mode = deck_notes_mode(data)
801+
796802
# Auto-fill fonts
797803
from sdpm.engine.analyzer import extract_fonts as _extract_fonts
798804
from sdpm.engine.analyzer import _extract_theme_colors_raw
@@ -888,6 +894,7 @@ def _resolve_config(
888894
default_background=data.get("defaultBackground") or None,
889895
title=data.get("title") or None,
890896
language=data.get("language") or None,
897+
notes_mode=notes_mode,
891898
)
892899

893900

@@ -903,13 +910,20 @@ def _build(config: BuildConfig, output_path: Path) -> Path:
903910
default_text_color=config.default_text_color,
904911
auto_spacing=config.auto_spacing,
905912
default_background=config.default_background,
913+
write_notes=config.notes_mode == "keep",
906914
)
907915
for s in config.slides:
908916
builder.add_slide(s)
909917
builder.save(output_path, title=config.title, language=config.language)
910918
return output_path, builder.invalid_layouts
911919

912920

921+
def _notes_export_path(output_path: Path) -> Path:
922+
"""Where ``notesMode: "export"`` writes the speaker notes: ``<output stem>.notes.md``
923+
next to the .pptx (``output.pptx`` -> ``output.notes.md``)."""
924+
return output_path.with_name(f"{output_path.stem}.notes.md")
925+
926+
913927
def generate(
914928
json_path: str | Path,
915929
output_path: str | Path | None = None,
@@ -931,7 +945,10 @@ def generate(
931945
bias lines are then left out of ``warnings``.
932946
933947
Returns:
934-
Dict with output_path, slide_count, slides summary, warnings.
948+
Dict with output_path, slide_count, slides summary, warnings. With deck.json
949+
``"notesMode": "export"`` and a full build (``only_slugs`` None), also
950+
``notes_path``: the Markdown file holding the speaker notes that were left
951+
out of the .pptx (``<output stem>.notes.md`` next to it).
935952
"""
936953
from sdpm.engine.preview import check_layout_imbalance_data
937954

@@ -948,6 +965,23 @@ def generate(
948965

949966
_, invalid_layouts = _build(config, out)
950967

968+
# "export": the notes stay out of the .pptx and go to a Markdown file beside it.
969+
# A partial build (only_slugs, e.g. iso.pptx) does not write one: it would hold
970+
# only the rebuilt slides and overwrite nothing useful.
971+
notes_path: Path | None = None
972+
if only_slugs is None:
973+
if config.notes_mode == "export":
974+
from sdpm.engine.notes import speaker_notes_markdown
975+
976+
notes_path = _notes_export_path(out)
977+
notes_path.write_text(speaker_notes_markdown(config.slides, title=config.title), encoding="utf-8")
978+
else:
979+
# A notes file from an earlier "export" build must not outlive the mode
980+
# change: with "strip" it is the very script the deck now leaves out.
981+
stale = _notes_export_path(out)
982+
if stale.is_file():
983+
stale.unlink()
984+
951985
imbalance = check_layout_imbalance_data(out, config.slides)
952986
if imbalance and not include_checks:
953987
for a in imbalance:
@@ -967,6 +1001,8 @@ def generate(
9671001
"slides": summary,
9681002
"warnings": config.warnings,
9691003
}
1004+
if notes_path is not None:
1005+
result["notes_path"] = str(notes_path)
9701006
if invalid_layouts:
9711007
result["invalid_layouts"] = [
9721008
{"slug": e["slug"], "attempted": e["attempted"], "used": e["used"]} for e in invalid_layouts

‎sdpm/sdpm/engine/builder/__init__.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ class PPTXBuilder(
7676
def __init__(self, template_path: Path, custom_template: bool = False,
7777
fonts: dict = None, base_dir: Path = None, keep_empty_placeholders: bool = False,
7878
default_text_color: str = None, auto_spacing: bool = True,
79-
default_background: str = None):
79+
default_background: str = None, write_notes: bool = True):
8080
"""Initialize PPTXBuilder.
8181
8282
Args:
@@ -90,6 +90,8 @@ def __init__(self, template_path: Path, custom_template: bool = False,
9090
default_background: Solid background applied to every slide that does
9191
not set its own "background" (deck.json "defaultBackground").
9292
None keeps the template background.
93+
write_notes: Write each slide's "notes" as speaker notes. False leaves
94+
them out of the .pptx (deck.json "notesMode" strip / export).
9395
9496
Raises:
9597
ValueError: If fonts or default_text_color is not provided.
@@ -122,6 +124,7 @@ def __init__(self, template_path: Path, custom_template: bool = False,
122124
self.custom_template = custom_template
123125
self.fonts = fonts
124126
self.auto_spacing = auto_spacing # CJK↔Latin spacing; False = keep source text verbatim
127+
self.write_notes = write_notes # False: slide "notes" stay out of the .pptx
125128
self.keep_empty_placeholders = keep_empty_placeholders
126129
self.layouts = self._build_layout_map()
127130
self.invalid_layouts: list[dict] = [] # {"slug", "attempted", "used", "available"}
@@ -385,7 +388,7 @@ def add_slide(self, slide_def: dict):
385388
sp_tree.insert(back_cursor, node)
386389
back_cursor += 1
387390

388-
if "notes" in slide_def:
391+
if "notes" in slide_def and self.write_notes:
389392
notes_frame = slide.notes_slide.notes_text_frame
390393
if notes_frame is not None:
391394
notes_frame.clear()

‎sdpm/sdpm/engine/notes.py‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: MIT-0
3+
"""Speaker notes export: slide ``notes`` as a Markdown document.
4+
5+
Used by the PPTX build when deck.json ``notesMode`` is ``"export"``: the notes
6+
stay out of the .pptx (a deck handed to an audience must not carry the
7+
presenter's script) and are written next to it instead.
8+
"""
9+
10+
from __future__ import annotations
11+
12+
from sdpm.utils.text import parse_styled_text
13+
14+
15+
def plain_notes_text(notes: object) -> str:
16+
"""Return ``notes`` without ``{{attr:...}}`` styling, as the presenter reads it.
17+
18+
A hyperlink keeps its text and its URL (``text <URL>``). Non-string notes
19+
(a degenerate slide file) become an empty string.
20+
"""
21+
if not isinstance(notes, str) or not notes.strip():
22+
return ""
23+
parts: list[str] = []
24+
for seg in parse_styled_text(notes, auto_spacing=False):
25+
text = seg.get("text", "")
26+
link = seg.get("link")
27+
if link and link != text:
28+
text = f"{text} <{link}>"
29+
parts.append(text)
30+
return "".join(parts).replace("\u000b", "\n").strip()
31+
32+
33+
def slide_title_text(slide: dict) -> str:
34+
"""Title of a slide dict for the export heading: the ``title`` field (a string or a
35+
``{"text": ...}`` object), else the first placeholder text, else an empty string."""
36+
title = slide.get("title")
37+
if isinstance(title, dict):
38+
title = title.get("text")
39+
if isinstance(title, str) and title.strip():
40+
return plain_notes_text(title)
41+
placeholders = slide.get("placeholders")
42+
if isinstance(placeholders, dict):
43+
for value in placeholders.values():
44+
if isinstance(value, str) and value.strip():
45+
return plain_notes_text(value)
46+
return ""
47+
48+
49+
def speaker_notes_markdown(slides: list[dict], title: str | None = None) -> str:
50+
"""Render the speaker notes of ``slides`` (build order) as Markdown.
51+
52+
One ``## pageNN — <slide title>`` section per slide, each holding that slide's
53+
plain notes or ``(no notes)``. The slide ``id`` (slug) follows the heading as a
54+
comment so the file can be matched back to ``slides/<slug>.json``.
55+
56+
Args:
57+
slides: Resolved slide dicts in deck order (``sdpm.api.BuildConfig.slides``).
58+
title: Deck title for the top heading; ``"Speaker notes"`` alone when None.
59+
60+
Returns:
61+
The Markdown text, ending with a newline.
62+
"""
63+
heading = "# Speaker notes" + (f" — {title.strip()}" if title and title.strip() else "")
64+
lines: list[str] = [heading, ""]
65+
for index, slide in enumerate(slides, 1):
66+
slide_title = slide_title_text(slide)
67+
section = f"## page{index:02d}" + (f" — {slide_title}" if slide_title else "")
68+
slug = slide.get("id")
69+
if isinstance(slug, str) and slug:
70+
section += f" <!-- {slug} -->"
71+
lines.append(section)
72+
lines.append("")
73+
notes = plain_notes_text(slide.get("notes"))
74+
lines.append(notes if notes else "(no notes)")
75+
lines.append("")
76+
return "\n".join(lines)

‎sdpm/sdpm/engine/schema/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33

44
from sdpm.engine.schema.deck_spec import (
55
DECK_JSON_SKELETON,
6+
NOTES_MODES,
67
OUTPUT_FORMATS,
78
complete_deck_skeleton,
9+
deck_notes_mode,
810
deck_output_format,
911
is_html_build_input,
1012
is_pptx_build_input,
@@ -18,11 +20,13 @@
1820

1921
__all__ = [
2022
"DECK_JSON_SKELETON",
23+
"NOTES_MODES",
2124
"OUTLINE_SLUG_RE",
2225
"OUTPUT_FORMATS",
2326
"SLUG_RE",
2427
"affected_slugs",
2528
"complete_deck_skeleton",
29+
"deck_notes_mode",
2630
"deck_output_format",
2731
"extract_regions",
2832
"is_comment_element",

‎sdpm/sdpm/engine/schema/deck_spec.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@
2424
# HTML decks so PPTX deck.json stays unchanged (not part of DECK_JSON_SKELETON).
2525
OUTPUT_FORMATS: tuple[str, ...] = ("pptx", "html")
2626

27+
# deck.json "notesMode" values: what the PPTX build does with slide "notes".
28+
# "keep" (the default when absent) writes them as speaker notes; "strip" leaves
29+
# them out of the .pptx; "export" leaves them out and writes them to a Markdown
30+
# file next to the .pptx. Optional, so not part of DECK_JSON_SKELETON.
31+
NOTES_MODES: tuple[str, ...] = ("keep", "strip", "export")
32+
2733
_SUB_ITEM_RE = re.compile(r"^\s{2,}-\s+(body|visual|evidence)\s*:")
2834
_COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{6}$")
2935
_REQUIRED_SUB_ITEMS = ("body", "visual", "evidence")
@@ -107,6 +113,27 @@ def deck_output_format(deck_json: Any) -> Literal["pptx", "html"]:
107113
raise ValueError(f'deck.json outputFormat must be "pptx" or "html", got {value!r}')
108114

109115

116+
def deck_notes_mode(deck_json: Any) -> Literal["keep", "strip", "export"]:
117+
"""Return the deck's speaker-notes policy: "keep" when notesMode is absent or None,
118+
or when deck.json is not an object.
119+
120+
Raises ValueError naming the value when notesMode is anything other than
121+
"keep", "strip" or "export".
122+
"""
123+
if not isinstance(deck_json, dict):
124+
return "keep"
125+
value = deck_json.get("notesMode")
126+
if value is None:
127+
return "keep"
128+
if value == "keep":
129+
return "keep"
130+
if value == "strip":
131+
return "strip"
132+
if value == "export":
133+
return "export"
134+
raise ValueError(f'deck.json notesMode must be "keep", "strip" or "export", got {value!r}')
135+
136+
110137
def read_deck_format(deck_dir: str | Path) -> Literal["pptx", "html"]:
111138
"""Output format of the deck in ``deck_dir``, read from its deck.json.
112139
@@ -215,6 +242,12 @@ def validate_specs(
215242
except ValueError:
216243
errors.append('deck.json outputFormat must be "pptx" or "html"')
217244

245+
if "notesMode" in deck_json:
246+
try:
247+
deck_notes_mode(deck_json)
248+
except ValueError:
249+
errors.append('deck.json notesMode must be "keep", "strip" or "export"')
250+
218251
if not _is_non_empty(fonts.get("halfwidth")):
219252
errors.append("deck.json fonts.halfwidth is empty")
220253
if not _is_non_empty(fonts.get("fullwidth")):

‎servers/remote/tools/generate.py‎

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -368,26 +368,41 @@ def generate_pptx(
368368
gen_result = api_generate(json_path=tmpdir, output_path=out)
369369

370370
# Upload PPTX to S3
371-
pptx_key = f"pptx/{deck_id}/{uuid.uuid4()}.pptx"
371+
build_id = uuid.uuid4()
372+
pptx_key = f"pptx/{deck_id}/{build_id}.pptx"
372373
storage.upload_file(
373374
key=pptx_key, data=out.read_bytes(),
374375
content_type="application/vnd.openxmlformats-officedocument.presentationml.presentation",
375376
)
376377

378+
# deck.json "notesMode": "export" — the speaker notes left out of the .pptx
379+
# were written next to it; they go to S3 beside the deck (same build id) so
380+
# the remote user gets them too (the temp workspace is deleted below).
381+
notes_key: str | None = None
382+
if gen_result.get("notes_path"):
383+
notes_key = f"pptx/{deck_id}/{build_id}.notes.md"
384+
storage.upload_file(
385+
key=notes_key, data=Path(gen_result["notes_path"]).read_bytes(),
386+
content_type="text/markdown; charset=utf-8",
387+
)
388+
377389
# Update deck record
378390
deck = storage.get_deck(deck_id, user_id)
379391
now = datetime.now(timezone.utc).isoformat()
380-
old = storage.update_deck(deck_id=deck_id, user_id=user_id, updates={
381-
"pptxS3Key": pptx_key, "updatedAt": now, "slideCount": len(slides),
382-
})
383-
# Delete the superseded artifact (best effort) — every refresh
392+
updates: dict = {"pptxS3Key": pptx_key, "updatedAt": now, "slideCount": len(slides)}
393+
# notesS3Key follows the build: set with "export", cleared otherwise, so a
394+
# deck rebuilt with "keep" / "strip" does not keep pointing at old notes.
395+
updates["notesS3Key"] = notes_key
396+
old = storage.update_deck(deck_id=deck_id, user_id=user_id, updates=updates)
397+
# Delete the superseded artifacts (best effort) — every refresh
384398
# uploads a new UUID key and only the newest is referenced.
385-
old_key = (old or {}).get("pptxS3Key")
386-
if old_key and old_key != pptx_key:
387-
try:
388-
storage._s3.delete_object(Bucket=storage.pptx_bucket, Key=old_key)
389-
except Exception:
390-
pass
399+
for field, new_key in (("pptxS3Key", pptx_key), ("notesS3Key", notes_key)):
400+
old_key = (old or {}).get(field)
401+
if old_key and old_key != new_key:
402+
try:
403+
storage._s3.delete_object(Bucket=storage.pptx_bucket, Key=old_key)
404+
except Exception:
405+
pass
391406

392407
# Preview: epoch-keyed WebP (background)
393408
slugs = [s.get("id") or f"slide_{i + 1:02d}" for i, s in enumerate(slides)]
@@ -420,6 +435,12 @@ def generate_pptx(
420435
"slideCount": gen_result["slide_count"],
421436
"slides": gen_result["slides"],
422437
}
438+
if notes_key:
439+
result["notesS3Key"] = notes_key
440+
try:
441+
result["notesUrl"] = storage.presign_url(notes_key)
442+
except Exception as e: # the key is still in the result and the deck record
443+
logger.warning("presign of %s failed: %s", notes_key, e)
423444
# Structured usage event: source for per-user slide-build measurement
424445
# (Logs Insights: filter kind = "slides_built" | stats sum(slide_count) by user_id)
425446
logger.info(json.dumps({

0 commit comments

Comments
 (0)