@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +90 -2
  3. package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
  4. package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
  5. package/bundled-assets/skill/LICENSE +21 -0
  6. package/bundled-assets/skill/README.md +61 -0
  7. package/bundled-assets/skill/SKILL.md +185 -0
  8. package/bundled-assets/skill/references/art-directions.md +99 -0
  9. package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
  10. package/bundled-assets/skill/references/design-baseline.txt +1 -0
  11. package/bundled-assets/skill/references/prompt-compiler.md +99 -0
  12. package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
  13. package/bundled-assets/skill/references/staged-pptx.md +71 -0
  14. package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
  15. package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
  16. package/bundled-assets/skill/scripts/brand_ref.py +776 -0
  17. package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
  18. package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
  19. package/bundled-assets/skill/scripts/export_images.py +280 -0
  20. package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
  21. package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
  22. package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
  23. package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
  24. package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
  25. package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
  26. package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
  27. package/bundled-assets/skill/scripts/render_gradient.py +258 -0
  28. package/bundled-assets/skill/scripts/slide_brand.py +111 -0
  29. package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
  30. package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
  31. package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
  32. package/bundled-assets/skill/vendor/README.md +4 -0
  33. package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
  34. package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
  35. package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
  36. package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
  37. package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
  38. package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
  39. package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
  40. package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
  41. package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
  42. package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
  43. package/bundled-assets/skill/vendor/codex-ppt/styles//345/205/232/346/224/277/347/272/242/351/243/216/346/240/274.md +98 -0
  44. package/bundled-assets/skill/vendor/codex-ppt/styles//345/210/233/346/204/217/346/235/202/345/277/227/351/243/216.md +72 -0
  45. package/bundled-assets/skill/vendor/codex-ppt/styles//345/244/215/345/217/244/346/211/201/345/271/263/346/217/222/347/224/273/351/243/216.md +72 -0
  46. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/346/212/200/346/234/257/350/247/243/351/207/212/351/243/216.md +86 -0
  47. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/347/231/275/346/235/277/351/243/216.md +72 -0
  48. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/231/345/255/246/350/257/276/344/273/266/351/243/216.md +107 -0
  49. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/260/346/215/256/344/273/252/350/241/250/347/233/230/351/243/216.md +73 -0
  50. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/205/347/210/275/344/270/223/344/270/232/351/243/216.md +87 -0
  51. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/251/346/232/226/346/211/213/345/267/245/351/243/216.md +72 -0
  52. package/bundled-assets/skill/vendor/codex-ppt/styles//347/224/265/345/255/220/345/242/250/346/260/264/346/235/202/345/277/227/351/243/216.md +86 -0
  53. package/bundled-assets/skill/vendor/codex-ppt/styles//347/247/221/347/240/224/347/255/224/350/276/251/351/243/216.md +138 -0
  54. package/bundled-assets/skill/vendor/codex-ppt/styles//351/272/246/350/202/257/351/224/241/351/243/216/346/240/274.md +119 -0
  55. package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
  56. package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
  57. package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
  58. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
  59. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
  60. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
  61. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
  62. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
  63. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
  64. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
  65. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
  66. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
  67. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
  68. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
  69. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
  70. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
  71. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
  72. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
  73. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
  74. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
  75. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
  76. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
  77. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
  78. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
  79. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
  80. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
  81. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
  82. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
  83. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
  84. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
  85. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
  86. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
  87. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
  88. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
  89. package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
  90. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
  91. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
  92. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
  93. package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
  94. package/cordis.patch.yml +3 -0
  95. package/lib/client.js +11423 -0
  96. package/lib/index.js +2638 -0
  97. package/package.json +140 -4
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env python3
2
+ """Export approved Stage-1 slide images as numbered canvas-resolution PNGs and a zip archive."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import re
8
+ import sys
9
+ import zipfile
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from PIL import Image
14
+
15
+ CANVAS_SIZES: dict[str, tuple[int, int]] = {
16
+ "16:9": (1920, 1080),
17
+ "3:4": (1080, 1440),
18
+ "9:16": (1080, 1920),
19
+ "1:1": (1440, 1440),
20
+ }
21
+
22
+ SLIDE_FILENAME_RE = re.compile(r"^s(\d+)\.(?:png|jpe?g|webp)$", re.IGNORECASE)
23
+ NUMBERED_PNG_RE = re.compile(r"^\d{2,}\.png$", re.IGNORECASE)
24
+ RATIO_TOLERANCE = 0.01
25
+
26
+
27
+ def normalize_ratio(raw: str | None) -> str:
28
+ s = (raw or "").strip().lower().replace(":", ":").replace("×", "x")
29
+ if s in ("3:4", "3x4", "1080x1440", "portrait"):
30
+ return "3:4"
31
+ if s in ("9:16", "9x16", "1080x1920", "vertical"):
32
+ return "9:16"
33
+ if s in ("1:1", "1x1", "1440x1440", "square"):
34
+ return "1:1"
35
+ if s in ("16:9", "16x9", "1920x1080", "landscape"):
36
+ return "16:9"
37
+ raise ValueError(f"Unsupported canvas ratio: {raw!r} (expected 16:9, 3:4, 9:16, or 1:1)")
38
+
39
+
40
+ def _infer_ratio_from_size(width: int, height: int) -> str:
41
+ if width <= 0 or height <= 0:
42
+ return "16:9"
43
+ actual = width / float(height)
44
+ best_ratio = "16:9"
45
+ best_err = float("inf")
46
+ for key, (cw, ch) in CANVAS_SIZES.items():
47
+ expected = cw / float(ch)
48
+ err = abs(actual - expected) / expected
49
+ if err < best_err:
50
+ best_err = err
51
+ best_ratio = key
52
+ return best_ratio
53
+
54
+
55
+ def _detect_deck_ratio(deck_dir: Path | None, first_image: Path | None) -> str:
56
+ if deck_dir is not None:
57
+ meta_path = deck_dir / "meta.json"
58
+ if meta_path.is_file():
59
+ try:
60
+ meta = json.loads(meta_path.read_text(encoding="utf-8"))
61
+ if isinstance(meta, dict):
62
+ raw = meta.get("aspect_ratio") or meta.get("ratio")
63
+ if isinstance(raw, str) and raw.strip():
64
+ return normalize_ratio(raw)
65
+ except Exception:
66
+ pass
67
+ html_path = deck_dir / "web" / "index.html"
68
+ if html_path.is_file():
69
+ try:
70
+ head = html_path.read_text(encoding="utf-8", errors="ignore")[:16384]
71
+ m = re.search(r'\bdata-ratio=["\']([^"\']+)["\']', head, re.IGNORECASE)
72
+ if m:
73
+ return normalize_ratio(m.group(1))
74
+ except Exception:
75
+ pass
76
+ if first_image is not None and first_image.is_file():
77
+ try:
78
+ with Image.open(first_image) as im:
79
+ return _infer_ratio_from_size(*im.size)
80
+ except Exception:
81
+ pass
82
+ return "16:9"
83
+
84
+
85
+ def _collect_slide_images(
86
+ deck_dir: Path | None,
87
+ ref_dir: Path | None,
88
+ inputs: list[Path] | None,
89
+ ) -> list[Path]:
90
+ if inputs:
91
+ for p in inputs:
92
+ if not p.is_file():
93
+ raise FileNotFoundError(f"Slide image not found: {p}")
94
+ return list(inputs)
95
+
96
+ search_dirs: list[Path] = []
97
+ if ref_dir is not None:
98
+ search_dirs.append(ref_dir)
99
+ if deck_dir is not None:
100
+ search_dirs.append(deck_dir / "assets" / "reference")
101
+ search_dirs.append(deck_dir)
102
+
103
+ for cand_dir in search_dirs:
104
+ if not cand_dir.is_dir():
105
+ continue
106
+ matched: list[tuple[int, str, Path]] = []
107
+ for entry in cand_dir.iterdir():
108
+ if not entry.is_file():
109
+ continue
110
+ m = SLIDE_FILENAME_RE.match(entry.name)
111
+ if m:
112
+ matched.append((int(m.group(1)), entry.name, entry))
113
+ if matched:
114
+ matched.sort(key=lambda t: (t[0], t[1]))
115
+ return [t[2] for t in matched]
116
+
117
+ target_desc = str(ref_dir or deck_dir or ".")
118
+ raise FileNotFoundError(f"No Stage-1 slide images (s1.png .. sN.png) found under {target_desc}")
119
+
120
+
121
+ def export_deck_images(
122
+ deck_dir: Path | str | None = None,
123
+ *,
124
+ ref_dir: Path | str | None = None,
125
+ inputs: list[Path | str] | None = None,
126
+ ratio: str | None = None,
127
+ out_dir: Path | str | None = None,
128
+ out_zip: Path | str | None = None,
129
+ tolerance: float = RATIO_TOLERANCE,
130
+ ) -> dict[str, Any]:
131
+ """Export approved Stage-1 slides to dist/images/01.png..NN.png and dist/images.zip at canvas size."""
132
+ resolved_deck = Path(deck_dir).resolve() if deck_dir is not None else None
133
+ resolved_ref = Path(ref_dir).resolve() if ref_dir is not None else None
134
+ resolved_inputs = [Path(p).resolve() for p in inputs] if inputs else None
135
+
136
+ if resolved_deck is None and resolved_ref is not None:
137
+ if resolved_ref.name == "reference" and resolved_ref.parent.name == "assets":
138
+ resolved_deck = resolved_ref.parent.parent
139
+ else:
140
+ resolved_deck = resolved_ref.parent
141
+ if resolved_deck is None:
142
+ resolved_deck = Path.cwd().resolve()
143
+
144
+ slides = _collect_slide_images(resolved_deck, resolved_ref, resolved_inputs)
145
+ norm_ratio = normalize_ratio(ratio) if (ratio and ratio.strip()) else _detect_deck_ratio(resolved_deck, slides[0])
146
+ canvas_w, canvas_h = CANVAS_SIZES[norm_ratio]
147
+ expected_aspect = canvas_w / float(canvas_h)
148
+
149
+ target_dir = Path(out_dir).resolve() if out_dir is not None else (resolved_deck / "dist" / "images")
150
+ target_zip = Path(out_zip).resolve() if out_zip is not None else (resolved_deck / "dist" / "images.zip")
151
+
152
+ # Validate all images first before writing outputs
153
+ inspected: list[tuple[Path, int, int]] = []
154
+ for src in slides:
155
+ with Image.open(src) as im:
156
+ w, h = im.size
157
+ if w <= 0 or h <= 0:
158
+ raise ValueError(f"Invalid image dimensions for {src}: {w}x{h}")
159
+ actual_aspect = w / float(h)
160
+ rel_err = abs(actual_aspect - expected_aspect) / expected_aspect
161
+ if rel_err > tolerance:
162
+ raise ValueError(
163
+ f"{src.name} aspect ratio {w}x{h} ({actual_aspect:.4f}) does not match deck ratio "
164
+ f"{norm_ratio} ({canvas_w}x{canvas_h}, {expected_aspect:.4f}; diff {rel_err * 100:.2f}% > {tolerance * 100:.1f}%)"
165
+ )
166
+ inspected.append((src, w, h))
167
+
168
+ target_dir.mkdir(parents=True, exist_ok=True)
169
+ target_zip.parent.mkdir(parents=True, exist_ok=True)
170
+
171
+ # Remove stale numbered PNGs from prior exports
172
+ for existing in target_dir.iterdir():
173
+ if existing.is_file() and NUMBERED_PNG_RE.match(existing.name):
174
+ existing.unlink()
175
+
176
+ warnings: list[str] = []
177
+ exported: list[dict[str, Any]] = []
178
+ written_paths: list[tuple[str, Path]] = []
179
+
180
+ for idx, (src, w, h) in enumerate(inspected, start=1):
181
+ out_name = f"{idx:02d}.png"
182
+ out_path = target_dir / out_name
183
+ upscaled = False
184
+ resized = False
185
+ with Image.open(src) as raw:
186
+ im = raw.convert("RGBA") if raw.mode in ("RGBA", "LA") else raw.convert("RGB")
187
+ if w < canvas_w or h < canvas_h:
188
+ upscaled = True
189
+ resized = True
190
+ warn_msg = (
191
+ f"{src.name}: source size {w}x{h} is below {norm_ratio} canvas size "
192
+ f"{canvas_w}x{canvas_h}; upscaling with Lanczos."
193
+ )
194
+ warnings.append(warn_msg)
195
+ print(f"[export_images] warning: {warn_msg}", file=sys.stderr)
196
+ im = im.resize((canvas_w, canvas_h), Image.Resampling.LANCZOS)
197
+ elif (w, h) != (canvas_w, canvas_h):
198
+ resized = True
199
+ im = im.resize((canvas_w, canvas_h), Image.Resampling.LANCZOS)
200
+ im.save(out_path, format="PNG", optimize=True)
201
+
202
+ written_paths.append((out_name, out_path))
203
+ exported.append(
204
+ {
205
+ "slide": idx,
206
+ "name": out_name,
207
+ "source": str(src),
208
+ "path": str(out_path),
209
+ "source_size": [w, h],
210
+ "size": [canvas_w, canvas_h],
211
+ "upscaled": upscaled,
212
+ "resized": resized,
213
+ }
214
+ )
215
+
216
+ with zipfile.ZipFile(target_zip, "w", compression=zipfile.ZIP_DEFLATED) as zf:
217
+ for arcname, file_path in written_paths:
218
+ zf.write(file_path, arcname=arcname)
219
+
220
+ return {
221
+ "ok": True,
222
+ "ratio": norm_ratio,
223
+ "canvas": {"width": canvas_w, "height": canvas_h},
224
+ "count": len(exported),
225
+ "out_dir": str(target_dir),
226
+ "zip": str(target_zip),
227
+ "images": exported,
228
+ "warnings": warnings,
229
+ }
230
+
231
+
232
+ def _configure_utf8_stdio() -> None:
233
+ for stream in (sys.stdout, sys.stderr):
234
+ if stream is not None:
235
+ try:
236
+ if not stream.isatty() and hasattr(stream, "reconfigure"):
237
+ stream.reconfigure(encoding="utf-8", errors="replace")
238
+ except Exception:
239
+ pass
240
+
241
+
242
+ def main(argv: list[str] | None = None) -> int:
243
+ _configure_utf8_stdio()
244
+ parser = argparse.ArgumentParser(
245
+ description="Export Stage-1 slide images to dist/images/01..NN.png at canvas size and dist/images.zip."
246
+ )
247
+ parser.add_argument("deck_pos", nargs="?", default=None, help="Deck folder path (optional positional)")
248
+ parser.add_argument("--deck", "--deck-dir", dest="deck_dir", default=None, help="Deck folder path")
249
+ parser.add_argument("--ref-dir", default=None, help="Override reference images directory")
250
+ parser.add_argument("--inputs", nargs="+", default=None, help="Explicit slide image paths in order")
251
+ parser.add_argument("--ratio", default=None, help="Canvas ratio: 16:9, 3:4, 9:16, or 1:1")
252
+ parser.add_argument("--out-dir", default=None, help="Output directory for numbered PNGs (default: <deck>/dist/images)")
253
+ parser.add_argument("--out-zip", default=None, help="Output zip path (default: <deck>/dist/images.zip)")
254
+ parser.add_argument("--json", action="store_true", help="Print JSON summary")
255
+ args = parser.parse_args(argv)
256
+
257
+ deck_arg = args.deck_dir or args.deck_pos
258
+ try:
259
+ res = export_deck_images(
260
+ deck_dir=deck_arg,
261
+ ref_dir=args.ref_dir,
262
+ inputs=args.inputs,
263
+ ratio=args.ratio,
264
+ out_dir=args.out_dir,
265
+ out_zip=args.out_zip,
266
+ )
267
+ except Exception as exc:
268
+ err_payload = {"ok": False, "error": str(exc)}
269
+ if args.json:
270
+ print(json.dumps(err_payload, ensure_ascii=False))
271
+ else:
272
+ print(f"error: {exc}", file=sys.stderr)
273
+ return 1
274
+
275
+ print(json.dumps(res, ensure_ascii=False, indent=None if args.json else 2))
276
+ return 0
277
+
278
+
279
+ if __name__ == "__main__":
280
+ raise SystemExit(main())
@@ -0,0 +1,360 @@
1
+ #!/usr/bin/env python3
2
+ """Extract text, tables, speaker notes, and embedded images from an existing .pptx deck.
3
+
4
+ Enables redesigning/overhauling an existing PowerPoint presentation while preserving
5
+ all original copy, data tables, speaker notes, and usable embedded images.
6
+
7
+ Usage:
8
+ python3 scripts/extract_pptx.py <input.pptx> [--out-dir assets/media/pptx-import] [--json]
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import hashlib
14
+ import io
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+
21
+ _DIRECT_IMAGE_EXTS = {"png", "jpg", "jpeg", "webp", "gif", "svg"}
22
+ _RASTER_CONVERT_EXTS = {"bmp", "tif", "tiff", "dib", "ico", "ppm", "pgm", "pbm"}
23
+
24
+
25
+ def _iter_shapes_recursive(shapes: Any):
26
+ """Yield shapes in reading order, descending into grouped shapes."""
27
+ for shape in shapes:
28
+ yield shape
29
+ if getattr(shape, "shape_type", None) == 6: # MSO_SHAPE_TYPE.GROUP
30
+ sub_shapes = getattr(shape, "shapes", None)
31
+ if sub_shapes is not None:
32
+ yield from _iter_shapes_recursive(sub_shapes)
33
+
34
+
35
+ def _normalize_image_bytes(blob: bytes, raw_ext: str) -> tuple[bytes, str, list[int] | None, str | None]:
36
+ """Return (out_bytes, ext, [w, h] | None, warning | None). Converts uncommon raster formats to PNG."""
37
+ ext = (raw_ext or "").lower().lstrip(".")
38
+ if ext == "jpeg":
39
+ ext = "jpg"
40
+
41
+ if ext == "svg":
42
+ return blob, "svg", None, None
43
+
44
+ size_px: list[int] | None = None
45
+ try:
46
+ from PIL import Image
47
+
48
+ with Image.open(io.BytesIO(blob)) as im:
49
+ size_px = [int(im.width), int(im.height)]
50
+ if ext in _DIRECT_IMAGE_EXTS:
51
+ return blob, ext, size_px, None
52
+ if ext in _RASTER_CONVERT_EXTS or not ext:
53
+ buf = io.BytesIO()
54
+ out_im = im.convert("RGBA") if im.mode in ("RGBA", "LA", "P") else im.convert("RGB")
55
+ out_im.save(buf, format="PNG")
56
+ return buf.getvalue(), "png", size_px, f"converted .{ext or 'bin'} to .png"
57
+ # Try converting any other Pillow-readable raster format to PNG
58
+ buf = io.BytesIO()
59
+ out_im = im.convert("RGBA") if im.mode in ("RGBA", "LA", "P") else im.convert("RGB")
60
+ out_im.save(buf, format="PNG")
61
+ return buf.getvalue(), "png", size_px, f"converted .{ext} to .png"
62
+ except Exception as exc:
63
+ if ext in _DIRECT_IMAGE_EXTS:
64
+ return blob, ext, size_px, f"dimension probe skipped: {exc}"
65
+ return blob, ext or "bin", None, f"unsupported vector/raster image format (.{ext or 'bin'}): {exc}"
66
+
67
+
68
+ def _extract_shape_image(shape: Any) -> tuple[bytes, str] | None:
69
+ """Safely extract embedded image blob + extension from a picture or picture placeholder shape."""
70
+ shape_type = getattr(shape, "shape_type", None)
71
+ # 13 = MSO_SHAPE_TYPE.PICTURE, 14 = PLACEHOLDER (may contain picture)
72
+ if shape_type not in (13, 14):
73
+ return None
74
+ try:
75
+ image = shape.image
76
+ except Exception:
77
+ return None
78
+ if image is None:
79
+ return None
80
+ try:
81
+ blob = image.blob
82
+ ext = str(getattr(image, "ext", "") or "").lower().lstrip(".")
83
+ except Exception:
84
+ return None
85
+ if not blob:
86
+ return None
87
+ return blob, ext
88
+
89
+
90
+ def extract_pptx_package(
91
+ pptx_path: Path,
92
+ *,
93
+ out_dir: Path | None = None,
94
+ rel_prefix: str | None = None,
95
+ write_manifest: bool = False,
96
+ ) -> dict[str, Any]:
97
+ """Extract per-slide titles, text, tables, speaker notes, and deduplicated embedded images.
98
+
99
+ Parameters
100
+ ----------
101
+ pptx_path:
102
+ Source `.pptx` file path.
103
+ out_dir:
104
+ Directory where extracted images (and optional manifest) are written.
105
+ If None, images are skipped and only text/tables/notes are extracted.
106
+ rel_prefix:
107
+ Optional relative path prefix reported in JSON/text output (e.g. 'assets/media/pptx-deck').
108
+ Defaults to `out_dir.as_posix()` when `out_dir` is provided.
109
+ write_manifest:
110
+ When True and `out_dir` is provided, writes `extracted-slides.json` into `out_dir`.
111
+ """
112
+ from pptx import Presentation
113
+
114
+ src = Path(pptx_path).resolve()
115
+ prs = Presentation(str(src))
116
+ slide_w_emu = int(getattr(prs, "slide_width", 0) or 0)
117
+ slide_h_emu = int(getattr(prs, "slide_height", 0) or 0)
118
+
119
+ if out_dir is not None:
120
+ out_dir = Path(out_dir).resolve()
121
+ out_dir.mkdir(parents=True, exist_ok=True)
122
+ prefix = (rel_prefix or (out_dir.as_posix() if out_dir is not None else "")).rstrip("/")
123
+
124
+ seen_hashes: dict[str, dict[str, Any]] = {}
125
+ unique_images: list[dict[str, Any]] = []
126
+ slides_data: list[dict[str, Any]] = []
127
+ warnings: list[str] = []
128
+ total_image_refs = 0
129
+ notes_count = 0
130
+
131
+ for slide_idx, slide in enumerate(prs.slides, start=1):
132
+ title_shape = getattr(slide.shapes, "title", None)
133
+ title_text = ""
134
+ texts: list[str] = []
135
+ tables: list[list[list[str]]] = []
136
+ images: list[dict[str, Any]] = []
137
+ img_seq = 0
138
+
139
+ for shape in _iter_shapes_recursive(slide.shapes):
140
+ if getattr(shape, "has_text_frame", False) and shape.text_frame is not None:
141
+ paras = [(p.text or "").strip() for p in shape.text_frame.paragraphs]
142
+ paras = [t for t in paras if t]
143
+ if paras:
144
+ if title_shape is not None and shape == title_shape and not title_text:
145
+ title_text = " ".join(paras)
146
+ else:
147
+ texts.extend(paras)
148
+
149
+ if getattr(shape, "has_table", False) and shape.table is not None:
150
+ rows_out: list[list[str]] = []
151
+ for row in shape.table.rows:
152
+ cells = [(cell.text or "").strip().replace("\n", " ") for cell in row.cells]
153
+ if any(cells):
154
+ rows_out.append(cells)
155
+ if rows_out:
156
+ tables.append(rows_out)
157
+
158
+ if out_dir is not None:
159
+ img_payload = _extract_shape_image(shape)
160
+ if img_payload is not None:
161
+ blob, raw_ext = img_payload
162
+ digest = hashlib.sha256(blob).hexdigest()
163
+ bbox_pct: list[float] | None = None
164
+ try:
165
+ if slide_w_emu > 0 and slide_h_emu > 0:
166
+ bbox_pct = [
167
+ round(float(shape.left) / slide_w_emu * 100.0, 1),
168
+ round(float(shape.top) / slide_h_emu * 100.0, 1),
169
+ round(float(shape.width) / slide_w_emu * 100.0, 1),
170
+ round(float(shape.height) / slide_h_emu * 100.0, 1),
171
+ ]
172
+ except Exception:
173
+ bbox_pct = None
174
+
175
+ if digest in seen_hashes:
176
+ cached = seen_hashes[digest]
177
+ entry: dict[str, Any] = {
178
+ "path": cached["path"],
179
+ "ext": cached["ext"],
180
+ "bytes": cached["bytes"],
181
+ "sha256": digest[:12],
182
+ "reused": True,
183
+ }
184
+ if cached.get("size_px"):
185
+ entry["size_px"] = list(cached["size_px"])
186
+ if bbox_pct is not None:
187
+ entry["bbox_pct"] = bbox_pct
188
+ images.append(entry)
189
+ total_image_refs += 1
190
+ else:
191
+ img_seq += 1
192
+ out_bytes, out_ext, size_px, warn = _normalize_image_bytes(blob, raw_ext)
193
+ if warn:
194
+ warnings.append(f"Slide {slide_idx} image {img_seq}: {warn}")
195
+ filename = f"slide{slide_idx:02d}_img{img_seq:02d}.{out_ext}"
196
+ target_path = out_dir / filename
197
+ target_path.write_bytes(out_bytes)
198
+ rel_path = f"{prefix}/{filename}" if prefix else filename
199
+ record: dict[str, Any] = {
200
+ "path": rel_path,
201
+ "ext": out_ext,
202
+ "bytes": len(out_bytes),
203
+ "sha256": digest[:12],
204
+ "reused": False,
205
+ }
206
+ if size_px:
207
+ record["size_px"] = size_px
208
+ if bbox_pct is not None:
209
+ record["bbox_pct"] = bbox_pct
210
+ seen_hashes[digest] = record
211
+ unique_images.append(
212
+ {
213
+ "path": rel_path,
214
+ "first_slide": slide_idx,
215
+ "ext": out_ext,
216
+ "bytes": len(out_bytes),
217
+ **({"size_px": size_px} if size_px else {}),
218
+ }
219
+ )
220
+ images.append(record)
221
+ total_image_refs += 1
222
+
223
+ notes_text = ""
224
+ try:
225
+ if slide.has_notes_slide and slide.notes_slide.notes_text_frame is not None:
226
+ notes_text = (slide.notes_slide.notes_text_frame.text or "").strip()
227
+ except Exception:
228
+ notes_text = ""
229
+ if notes_text:
230
+ notes_count += 1
231
+
232
+ slides_data.append(
233
+ {
234
+ "slide_number": slide_idx,
235
+ "title": title_text,
236
+ "texts": texts,
237
+ "tables": tables,
238
+ "images": images,
239
+ "notes": notes_text,
240
+ }
241
+ )
242
+
243
+ result: dict[str, Any] = {
244
+ "ok": True,
245
+ "source": src.name,
246
+ "slide_count": len(slides_data),
247
+ "image_ref_count": total_image_refs,
248
+ "unique_image_count": len(unique_images),
249
+ "notes_count": notes_count,
250
+ "assets_dir": prefix if out_dir is not None else None,
251
+ "extracted_images": unique_images,
252
+ "slides": slides_data,
253
+ "warnings": warnings,
254
+ }
255
+
256
+ if write_manifest and out_dir is not None:
257
+ manifest_path = out_dir / "extracted-slides.json"
258
+ manifest_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
259
+ result["manifest"] = f"{prefix}/extracted-slides.json" if prefix else str(manifest_path)
260
+
261
+ return result
262
+
263
+
264
+ def format_pptx_markdown(package: dict[str, Any]) -> str:
265
+ """Format an extracted PPTX package as a clean, agent-readable per-slide text summary."""
266
+ blocks: list[str] = []
267
+ for slide in package.get("slides") or []:
268
+ idx = slide.get("slide_number", 0)
269
+ lines: list[str] = [f"--- Slide {idx} ---"]
270
+ title = (slide.get("title") or "").strip()
271
+ if title:
272
+ lines.append(f"[Title] {title}")
273
+ for txt in slide.get("texts") or []:
274
+ if txt:
275
+ lines.append(txt)
276
+ for tbl in slide.get("tables") or []:
277
+ for row in tbl:
278
+ lines.append(" | ".join(row))
279
+ for img in slide.get("images") or []:
280
+ dim = ""
281
+ size_px = img.get("size_px")
282
+ if isinstance(size_px, list) and len(size_px) == 2:
283
+ dim = f" ({size_px[0]}x{size_px[1]})"
284
+ reused = ", reused" if img.get("reused") else ""
285
+ lines.append(f"[Image] {img['path']}{dim}{reused}")
286
+ notes = (slide.get("notes") or "").strip()
287
+ if notes:
288
+ lines.append(f"[Notes] {notes}")
289
+ if len(lines) > 1:
290
+ blocks.append("\n".join(lines))
291
+ return "\n\n".join(blocks)
292
+
293
+
294
+ def _configure_utf8_stdio() -> None:
295
+ for stream in (sys.stdout, sys.stderr):
296
+ if stream is not None:
297
+ try:
298
+ if not stream.isatty() and hasattr(stream, "reconfigure"):
299
+ stream.reconfigure(encoding="utf-8", errors="replace")
300
+ except Exception:
301
+ pass
302
+
303
+
304
+ def main() -> int:
305
+ _configure_utf8_stdio()
306
+ parser = argparse.ArgumentParser(
307
+ description="Extract slide text, tables, speaker notes, and embedded images from a .pptx file."
308
+ )
309
+ parser.add_argument("input_pptx", type=Path, help="Path to source .pptx file")
310
+ parser.add_argument(
311
+ "--out-dir",
312
+ type=Path,
313
+ default=None,
314
+ help="Output directory for extracted images and extracted-slides.json (default: assets/media/pptx-<stem>)",
315
+ )
316
+ parser.add_argument(
317
+ "--rel-prefix",
318
+ type=str,
319
+ default=None,
320
+ help="Optional relative path prefix recorded in manifest/text (e.g. assets/media/pptx-deck)",
321
+ )
322
+ parser.add_argument("--markdown", type=Path, default=None, help="Optional path to write readable markdown summary")
323
+ parser.add_argument("--json", action="store_true", help="Print structured JSON summary to stdout")
324
+ args = parser.parse_args()
325
+
326
+ if not args.input_pptx.is_file():
327
+ print(f"Error: .pptx file not found: {args.input_pptx}", file=sys.stderr)
328
+ return 2
329
+
330
+ out_dir = args.out_dir or (Path("assets/media") / f"pptx-{args.input_pptx.stem}")
331
+ rel_prefix = args.rel_prefix or out_dir.as_posix()
332
+
333
+ res = extract_pptx_package(
334
+ args.input_pptx,
335
+ out_dir=out_dir,
336
+ rel_prefix=rel_prefix,
337
+ write_manifest=True,
338
+ )
339
+ if args.markdown:
340
+ args.markdown.parent.mkdir(parents=True, exist_ok=True)
341
+ args.markdown.write_text(format_pptx_markdown(res), encoding="utf-8")
342
+ res["markdown_path"] = args.markdown.as_posix()
343
+
344
+ if args.json:
345
+ print(json.dumps(res, ensure_ascii=False, indent=2))
346
+ else:
347
+ print(
348
+ f"extract_pptx: slides={res['slide_count']} unique_images={res['unique_image_count']} "
349
+ f"notes={res['notes_count']} out={res['assets_dir']}"
350
+ )
351
+ for s in res["slides"]:
352
+ print(
353
+ f" Slide {s['slide_number']:02d}: {s['title'] or '(no title)'} "
354
+ f"({len(s['images'])} img, {'notes' if s['notes'] else 'no notes'})"
355
+ )
356
+ return 0
357
+
358
+
359
+ if __name__ == "__main__":
360
+ raise SystemExit(main())