Skip to content

Commit bc7b06b

Browse files
✨ feat(skill-config): add config.json overlay + sync engine from internal
- skill/config.json for customizable templates_dir, styles_dir, asset_sources, preview.backend - config.json.example with defaults, config.json gitignored - sdpm/config.py: unified config loader (replaces assets/config.json) - PowerPoint/LibreOffice backend abstraction (preview/backend.py, preview/autofit.py) - pptx_builder.py: 5 hardcoded paths → config-based resolution - preview/__init__.py, converter/pipeline.py: refactored to use backend abstraction
1 parent 749b8d1 commit bc7b06b

13 files changed

Lines changed: 750 additions & 308 deletions

File tree

‎.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@ infra/config.yaml
5454
# Assets (downloaded via scripts)
5555
skill/assets/aws/
5656
skill/assets/material/
57+
58+
# Skill config (user-specific overlay paths)
59+
skill/config.json
5760
*.tsbuildinfo
5861
.ash/
5962
?/
63+
skill/sdpm/.cache/

‎skill/config.json.example‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"templates_dir": "./templates",
3+
"styles_dir": "./references/examples/styles",
4+
"asset_sources": [],
5+
"preview": {
6+
"backend": ""
7+
}
8+
}

‎skill/scripts/pptx_builder.py‎

Lines changed: 19 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
from sdpm.preview import (
5151
_is_wsl,
5252
check_layout_imbalance,
53+
export_pdf,
5354
get_tmp_project_dir,
5455
refresh_autofit,
5556
unlock_height_constraints,
@@ -71,7 +72,9 @@
7172

7273
def _resolve_template(data, input_path):
7374
"""Resolve template path: presentation.json "template" → templates/default-dark.pptx → repo fallback."""
74-
templates_dir = Path(__file__).parent.parent / "templates"
75+
from sdpm.config import resolve_templates_dir
76+
77+
templates_dir = resolve_templates_dir()
7578

7679
if data.get("template"):
7780
base_dir = Path(input_path).parent if input_path and input_path != "-" else Path(".")
@@ -256,58 +259,17 @@ def cmd_preview(args):
256259
import shutil
257260
shutil.rmtree(png_dir, ignore_errors=True)
258261
else:
259-
# macOS / WSL: PDF + pdftoppm pipeline
262+
# PDF + pdftoppm pipeline (macOS / WSL / Linux)
260263
pdf_path = output_dir / "slides.pdf"
261264
pre_generated_pdf = getattr(args, '_pdf_path', None)
262265

263266
if pre_generated_pdf and Path(pre_generated_pdf).exists():
264-
# PDF already generated by _refresh_autofit — skip PowerPoint
265267
import shutil
266268
if str(Path(pre_generated_pdf).resolve()) != str(pdf_path.resolve()):
267269
shutil.copy2(pre_generated_pdf, pdf_path)
268270
else:
269-
if _is_wsl():
270-
win_pptx = subprocess.run(["wslpath", "-w", str(pptx_path)], capture_output=True, text=True).stdout.strip() # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit
271-
win_pdf = subprocess.run(["wslpath", "-w", str(pdf_path)], capture_output=True, text=True).stdout.strip() # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit
272-
ps_cmd = (
273-
f"$app = New-Object -ComObject PowerPoint.Application; "
274-
f"$prs = $app.Presentations.Open('{win_pptx}', "
275-
f"[Microsoft.Office.Core.MsoTriState]::msoTrue, "
276-
f"[Microsoft.Office.Core.MsoTriState]::msoFalse, "
277-
f"[Microsoft.Office.Core.MsoTriState]::msoFalse); "
278-
f"$prs.SaveAs('{win_pdf}', 32); "
279-
f"$prs.Close(); $app.Quit()"
280-
)
281-
result = subprocess.run(
282-
["/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", "-Command", ps_cmd],
283-
capture_output=True, timeout=60) # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit
284-
result = subprocess.CompletedProcess(
285-
result.args, result.returncode,
286-
stdout=result.stdout.decode("cp932", errors="replace") if result.stdout else "",
287-
stderr=result.stderr.decode("cp932", errors="replace") if result.stderr else ""
288-
)
289-
else:
290-
from sdpm.preview import (
291-
_mac_open_pptx_background,
292-
_mac_restore_pptx_focus_async,
293-
)
294-
pptx_name = Path(pptx_path).name
295-
restore_info = _mac_open_pptx_background(pptx_path)
296-
_mac_restore_pptx_focus_async(restore_info)
297-
import time
298-
time.sleep(2)
299-
script = f'''
300-
tell application "Microsoft PowerPoint"
301-
set theDoc to presentation "{pptx_name}"
302-
set outPath to (POSIX file "{pdf_path}") as text
303-
save theDoc in outPath as save as PDF
304-
close theDoc saving no
305-
end tell
306-
'''
307-
result = subprocess.run(["osascript", "-e", script], capture_output=True, text=True) # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit
308-
309-
if result.returncode != 0 or not pdf_path.exists():
310-
print(f"Error: PDF export failed: {result.stderr}", file=sys.stderr)
271+
if not export_pdf(pptx_path, pdf_path):
272+
print("Error: PDF export failed", file=sys.stderr)
311273
sys.exit(1)
312274

313275
# Parse pages to export
@@ -417,7 +379,9 @@ def cmd_list_asset_sources(args):
417379

418380
def cmd_list_templates(args):
419381
"""List available PPTX templates."""
420-
templates_dir = Path(__file__).parent.parent / "templates"
382+
from sdpm.config import resolve_templates_dir
383+
384+
templates_dir = resolve_templates_dir()
421385
if not templates_dir.exists():
422386
print("No templates directory found.", file=sys.stderr)
423387
return
@@ -557,7 +521,9 @@ def cmd_examples(args):
557521

558522
# styles/ directory — always show full content
559523
if base == "styles":
560-
styles_dir = examples_dir / "styles"
524+
from sdpm.config import resolve_styles_dir
525+
526+
styles_dir = resolve_styles_dir()
561527
if not styles_dir.exists():
562528
print("# Not found: styles/", file=sys.stderr)
563529
continue
@@ -661,7 +627,9 @@ def cmd_init(args):
661627
spec_files = ["brief.md", "outline.md"]
662628
if args.style:
663629
# Copy style HTML as art-direction.html
664-
styles_dir = Path(__file__).parent.parent / "references" / "examples" / "styles"
630+
from sdpm.config import resolve_styles_dir
631+
632+
styles_dir = resolve_styles_dir()
665633
style_name = args.style if args.style.endswith(".html") else args.style + ".html"
666634
style_src = styles_dir / style_name
667635
if not style_src.exists():
@@ -1076,7 +1044,9 @@ def cmd_analyze_template(args):
10761044
name = args.input
10771045
if not name.endswith(".pptx"):
10781046
name += ".pptx"
1079-
candidate = Path(__file__).resolve().parent.parent / "templates" / name
1047+
from sdpm.config import resolve_templates_dir
1048+
1049+
candidate = resolve_templates_dir() / name
10801050
if candidate.exists():
10811051
template_path = candidate
10821052
else:

‎skill/sdpm/assets/__init__.py‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,24 @@ def _load_extra_sources() -> list[dict]:
6363
_manifest_cache: Optional[list[dict]] = None
6464

6565

66+
def _check_recolor_protected(cfg, item: dict) -> bool:
67+
"""Check if an icon entry is recolor-protected based on config."""
68+
if cfg is True:
69+
return True
70+
if isinstance(cfg, dict):
71+
when = cfg.get("when", {})
72+
types = when.get("type", [])
73+
if types and item.get("type") in types:
74+
return True
75+
return False
76+
77+
6678
def _load_manifest_file(
6779
manifest_path: Path,
6880
source_override: Optional[str],
6981
all_assets: list[dict],
7082
files_dir: Optional[Path] = None,
83+
recolor_protected=None,
7184
) -> None:
7285
"""Load a single manifest.json and append entries to all_assets.
7386
@@ -83,9 +96,11 @@ def _load_manifest_file(
8396
data = json.load(f)
8497
source = source_override or data.get("source", manifest_path.parent.name)
8598
resolved_dir = files_dir or manifest_path.parent
99+
recolor_cfg = recolor_protected or data.get("recolorProtected", False)
86100
for item in data.get("icons", []):
87101
item["_source"] = source
88102
item["_dir"] = resolved_dir
103+
item["_recolor_protected"] = _check_recolor_protected(recolor_cfg, item)
89104
all_assets.append(item)
90105

91106

@@ -113,7 +128,10 @@ def _load_manifests() -> list[dict]:
113128
manifest_path = Path(entry["manifest"]).expanduser()
114129
source_name = entry.get("source")
115130
files_dir = Path(entry["files_dir"]).expanduser() if "files_dir" in entry else None
116-
_load_manifest_file(manifest_path, source_override=source_name, all_assets=all_assets, files_dir=files_dir)
131+
_load_manifest_file(
132+
manifest_path, source_override=source_name, all_assets=all_assets,
133+
files_dir=files_dir, recolor_protected=entry.get("recolorProtected"),
134+
)
117135

118136
# Auto-detect legacy icons/ directory (sibling of assets/)
119137
legacy_icons = ASSETS_DIR.parent / "icons"
@@ -203,6 +221,28 @@ def check_asset_exists(ref: str, theme: str = "light") -> bool:
203221
check_icon_exists = check_asset_exists
204222

205223

224+
def is_recolor_protected(ref: str) -> bool:
225+
"""Check if an asset is recolor-protected (e.g. brand icons).
226+
227+
Args:
228+
ref: Asset reference — `assets:source/name` or `icons:name`.
229+
230+
Returns:
231+
True if the asset should not be recolored.
232+
"""
233+
if ref.startswith("assets:"):
234+
name = _strip_ext(ref.split(":", 1)[1].split("/", 1)[-1])
235+
elif ref.startswith("icons:"):
236+
name = _strip_ext(ref.split(":", 1)[1])
237+
else:
238+
return False
239+
for item in _load_manifests():
240+
file_stem = item["file"].rsplit(".", 1)[0]
241+
if file_stem == name:
242+
return item.get("_recolor_protected", False)
243+
return False
244+
245+
206246
def resolve_asset_path(ref: str, theme: str = "light") -> Path:
207247
"""Resolve asset reference to file path.
208248

‎skill/sdpm/builder/elements/image.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from sdpm.utils.effects import apply_effects
1010
from sdpm.utils.svg import _recolor_svg, get_svg_dimensions, generate_qr_svg, add_svg_to_slide
1111
from sdpm.utils.text import _expand_styled_newlines
12+
from sdpm.assets import is_recolor_protected
1213

1314
_DEFAULTS = ELEMENT_DEFAULTS["image"]
1415

@@ -91,10 +92,14 @@ def _add_image(self, slide, elem):
9192
svg_bytes = None
9293
if is_svg:
9394
svg_bytes = img_path.read_bytes()
94-
effective_icon_color = icon_color or self.theme_colors["text"]
95-
recolored = _recolor_svg(svg_bytes, effective_icon_color)
96-
if recolored:
97-
svg_bytes = recolored
95+
if src and is_recolor_protected(src):
96+
if icon_color:
97+
print(f"Warning: iconColor ignored (recolor-protected asset): {src}", file=sys.stderr)
98+
else:
99+
effective_icon_color = icon_color or self.theme_colors["text"]
100+
recolored = _recolor_svg(svg_bytes, effective_icon_color)
101+
if recolored:
102+
svg_bytes = recolored
98103
elif icon_color:
99104
print(f"Warning: iconColor ignored (not SVG): {img_path.name}", file=sys.stderr)
100105

‎skill/sdpm/config.py‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: MIT-0
3+
"""Skill-level configuration loader.
4+
5+
Reads skill/config.json to resolve customizable paths for templates,
6+
styles, and asset sources. Falls back to defaults when config is absent.
7+
Also provides preview backend configuration.
8+
"""
9+
10+
import json
11+
from pathlib import Path
12+
13+
# skill/ directory (parent of sdpm/)
14+
SKILL_ROOT: Path = Path(__file__).resolve().parent.parent
15+
16+
_config_cache: dict | None = None
17+
18+
19+
def load_skill_config() -> dict:
20+
"""Load skill/config.json and cache the result.
21+
22+
Returns:
23+
Parsed config dict, or empty dict if config.json does not exist.
24+
"""
25+
global _config_cache
26+
if _config_cache is not None:
27+
return _config_cache
28+
29+
config_path = SKILL_ROOT / "config.json"
30+
if not config_path.exists():
31+
_config_cache = {}
32+
return _config_cache
33+
34+
with open(config_path) as f:
35+
_config_cache = json.load(f)
36+
return _config_cache
37+
38+
39+
def resolve_templates_dir() -> Path:
40+
"""Resolve templates directory from config or default.
41+
42+
Config key: "templates_dir" (relative to skill/ or absolute).
43+
Default: skill/templates/
44+
45+
Returns:
46+
Resolved Path to templates directory.
47+
"""
48+
cfg = load_skill_config()
49+
if "templates_dir" in cfg:
50+
p = Path(cfg["templates_dir"]).expanduser()
51+
if not p.is_absolute():
52+
p = (SKILL_ROOT / p).resolve()
53+
return p
54+
return SKILL_ROOT / "templates"
55+
56+
57+
def resolve_styles_dir() -> Path:
58+
"""Resolve styles directory from config or default.
59+
60+
Config key: "styles_dir" (relative to skill/ or absolute).
61+
Default: skill/references/examples/styles/
62+
63+
Returns:
64+
Resolved Path to styles directory.
65+
"""
66+
cfg = load_skill_config()
67+
if "styles_dir" in cfg:
68+
p = Path(cfg["styles_dir"]).expanduser()
69+
if not p.is_absolute():
70+
p = (SKILL_ROOT / p).resolve()
71+
return p
72+
return SKILL_ROOT / "references" / "examples" / "styles"
73+
74+
75+
def get_asset_sources() -> list[dict]:
76+
"""Get asset sources from config.
77+
78+
Config key: "asset_sources" (same schema as old extra_sources).
79+
Default: empty list.
80+
81+
Returns:
82+
List of asset source dicts with 'source', 'manifest', and optional 'files_dir'.
83+
"""
84+
cfg = load_skill_config()
85+
return cfg.get("asset_sources", [])
86+
87+
88+
def load_config() -> dict:
89+
"""Load config for preview backend selection.
90+
91+
Config key: "preview" with sub-key "backend" ("powerpoint" or "libreoffice").
92+
Reads from skill/config.json (unified config).
93+
94+
Returns:
95+
Dict with preview settings, or empty dict if not configured.
96+
"""
97+
cfg = load_skill_config()
98+
return cfg

0 commit comments

Comments
 (0)