-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpptx-python-runner.py
More file actions
1775 lines (1478 loc) Β· 67.4 KB
/
pptx-python-runner.py
File metadata and controls
1775 lines (1478 loc) Β· 67.4 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import json
import os
import re
import sys
import time
from pathlib import Path
from typing import TYPE_CHECKING
if __package__ in {None, ''}:
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
# Layout engine lives in scripts/layout/ sub-package
sys.path.insert(0, str(Path(__file__).resolve().parent / 'layout'))
from pptx import Presentation
from pptx.dml.color import RGBColor
from pptx.enum.chart import XL_CHART_TYPE
from pptx.enum.text import MSO_AUTO_SIZE
from pptx.util import Inches, Pt
if TYPE_CHECKING:
from pptx.presentation import Presentation as PresentationType
else:
PresentationType = object # noqa: N816
from layout_specs import ( # type: ignore
LayoutSpec,
)
from layout_validator import ( # type: ignore
validate_presentation,
report_issues,
)
SLIDE_WIDTH_IN = 13.333
SLIDE_HEIGHT_IN = 7.5
PPTX_ICON_COLLECTION = (os.environ.get('PPTX_ICON_COLLECTION', 'all') or 'all').strip()
# ---------------------------------------------------------------------------
# Shape Semantic Registry β authoritative role metadata for every created shape
# ---------------------------------------------------------------------------
# Maps shape_id β role string ('template_design' | 'layout_managed').
# The validator reads this registry first; name-prefix and heuristic
# classification are used only when a shape is not resolved from the registry.
_SHAPE_ROLE_REGISTRY: dict[int, str] = {}
def _register_shape_role(shape, role: str) -> None:
"""Record the semantic role for *shape* in the global registry."""
shape_id = getattr(shape, 'shape_id', None)
if shape_id is not None:
_SHAPE_ROLE_REGISTRY[int(shape_id)] = role
def get_shape_role_registry() -> dict[int, str]:
"""Return a snapshot of the current shape-role registry."""
return dict(_SHAPE_ROLE_REGISTRY)
def clear_shape_role_registry() -> None:
"""Reset the registry (called between generation runs)."""
_SHAPE_ROLE_REGISTRY.clear()
# Module-level reference to the loaded layout specs (set during renderer initialization).
_LOADED_LAYOUT_SPECS: list[LayoutSpec] | None = None
# Module-level reference to the active style guardrails (set in renderer-mode).
_ACTIVE_GUARDRAILS: object | None = None
def _get_precomputed_specs_for_validation() -> list[LayoutSpec] | None:
"""Return the layout specs loaded at namespace-build time, if any."""
return _LOADED_LAYOUT_SPECS
# ---------------------------------------------------------------------------
# Font resolution
# ---------------------------------------------------------------------------
# The user selects a font from the system font list in the palette UI.
# resolve_font() always returns that font unchanged β PowerPoint handles
# glyph substitution for missing characters at render time.
# ---------------------------------------------------------------------------
def resolve_font(text: str, base_font: str = 'Calibri') -> str:
"""Return *base_font* unchanged.
PowerPoint handles font fallback for missing glyphs (e.g. CJK characters
in a Latin-only font) at render time. We never substitute fonts at the
python-pptx level.
"""
return base_font
def _has_real_transparency(image) -> bool:
if 'A' not in image.getbands():
return False
min_alpha, max_alpha = image.getchannel('A').getextrema()
return min_alpha < 255 and max_alpha > 0
def _has_visible_alpha(image) -> bool:
if 'A' not in image.getbands():
return False
return image.getchannel('A').getbbox() is not None
def _make_background_transparent(image):
bg_samples = [
image.getpixel((0, 0)),
image.getpixel((image.width - 1, 0)),
image.getpixel((0, image.height - 1)),
image.getpixel((image.width - 1, image.height - 1)),
]
bg_r = sum(sample[0] for sample in bg_samples) // len(bg_samples)
bg_g = sum(sample[1] for sample in bg_samples) // len(bg_samples)
bg_b = sum(sample[2] for sample in bg_samples) // len(bg_samples)
converted = image.copy()
pixels = converted.load()
assert pixels is not None
for y in range(converted.height):
for x in range(converted.width):
r, g, b, _ = pixels[x, y] # type: ignore[misc]
diff = max(abs(r - bg_r), abs(g - bg_g), abs(b - bg_b))
if diff <= 12:
pixels[x, y] = (0, 0, 0, 0) # type: ignore[index]
continue
alpha = min(255, diff * 4)
pixels[x, y] = (0, 0, 0, alpha) # type: ignore[index]
return converted
def _make_transparent(png_path: str) -> str:
"""Convert a black-on-white RGB icon to black-on-transparent RGBA.
Returns the path to the transparent version (cached alongside the original).
If the source already has an alpha channel with real transparency, returns it as-is.
"""
suffix = '_t.png'
transparent_path = os.path.join(
os.path.dirname(png_path),
f'{Path(png_path).stem}{suffix}',
)
if os.path.isfile(transparent_path):
return transparent_path
try:
from PIL import Image
img = Image.open(png_path).convert('RGBA')
# If image already has real transparency, skip conversion
if _has_real_transparency(img):
return png_path
converted = img.copy()
pixels = converted.load()
assert pixels is not None
w, h = converted.size
for y in range(h):
for x in range(w):
r, g, b, _ = pixels[x, y] # type: ignore[misc]
# Luminance: near-white β transparent, darker β opaque icon stroke
lum = r * 0.299 + g * 0.587 + b * 0.114
if lum > 240:
pixels[x, y] = (0, 0, 0, 0) # type: ignore[index]
else:
# Map luminance to alpha: black=255, mid-gray=partial
alpha = min(255, int((255 - lum) * (255 / 200)))
pixels[x, y] = (0, 0, 0, alpha) # type: ignore[index]
if not _has_visible_alpha(converted):
converted = _make_background_transparent(img)
if not _has_visible_alpha(converted):
return png_path
converted.save(transparent_path, 'PNG')
return transparent_path
except Exception:
return png_path
def _recolor_png(png_path: str, color_hex: str) -> str:
"""Tint an icon PNG to the requested color.
Handles both RGBA (transparent bg) and RGB (white bg) source icons.
"""
# First ensure we have a transparent version
png_path = _make_transparent(png_path)
color = color_hex.lstrip('#')
if color == '000000':
return png_path # already black-on-transparent
colored_path = os.path.join(
os.path.dirname(png_path),
f'{Path(png_path).stem}_{color}.png',
)
if os.path.isfile(colored_path):
return colored_path
try:
from PIL import Image
img = Image.open(png_path).convert('RGBA')
r_tgt = int(color[0:2], 16)
g_tgt = int(color[2:4], 16)
b_tgt = int(color[4:6], 16)
pixels = img.load()
assert pixels is not None
w, h = img.size
for y in range(h):
for x in range(w):
_, _, _, a = pixels[x, y] # type: ignore[misc]
if a > 0:
pixels[x, y] = (r_tgt, g_tgt, b_tgt, a) # type: ignore[index]
if not _has_visible_alpha(img):
return png_path
img.save(colored_path, 'PNG')
return colored_path
except Exception:
return png_path
# ---------------------------------------------------------------------------
# Icon fetch β downloads from Iconify public API with host redundancy
# ---------------------------------------------------------------------------
_MISSING_ICONS: list[dict[str, str]] = []
_ICON_FETCH_ATTEMPTS = 0
ICONIFY_API_HOSTS = [
'https://api.iconify.design',
'https://api.simplesvg.com',
'https://api.unisvg.com',
]
_ICON_TEMP_DIR: str | None = None
def _get_icon_temp_dir() -> str:
global _ICON_TEMP_DIR
if _ICON_TEMP_DIR is None:
import tempfile
_ICON_TEMP_DIR = tempfile.mkdtemp(prefix='pptx_icons_')
return _ICON_TEMP_DIR
def _download_svg(prefix: str, icon_name: str) -> bytes | None:
import urllib.request
import urllib.error
for host in ICONIFY_API_HOSTS:
url = f'{host}/{prefix}/{icon_name}.svg?box=1'
try:
req = urllib.request.Request(url, headers={'User-Agent': 'pptx-slide-agent/1.0'})
with urllib.request.urlopen(req, timeout=8) as resp:
if resp.status == 200:
data = resp.read()
if data and b'<svg' in data.lower():
print(f'[icon] fetched {prefix}:{icon_name} from {host}', file=sys.stderr)
return data
except Exception as exc:
print(f'[icon] {host} failed for {prefix}:{icon_name}: {exc}', file=sys.stderr)
return None
def _preprocess_svg(svg_data: bytes) -> bytes:
"""Replace currentColor with black so svglib can render strokes/fills."""
import re
text = svg_data.decode('utf-8', errors='replace')
text = text.replace('currentColor', '#000000')
# Ensure stroke-only icons (fill="none") get visible strokes
if 'stroke=' not in text and 'fill="none"' in text:
text = text.replace('fill="none"', 'fill="none" stroke="#000000"')
# If no stroke-width is set, add a default for thin icons
if 'stroke-width' not in text and 'stroke=' in text:
text = re.sub(r'(<svg[^>]*>)', r'\1<style>*{stroke-width:2}</style>', text, count=1)
return text.encode('utf-8')
def _svg_to_png(svg_data: bytes, size: int = 256) -> bytes | None:
# Preprocess SVG to fix currentColor and stroke visibility for svglib
svg_data = _preprocess_svg(svg_data)
try:
import importlib
cairosvg = importlib.import_module('cairosvg')
return cairosvg.svg2png(bytestring=svg_data, output_width=size, output_height=size)
except ImportError:
pass
try:
import io
import tempfile as _tf
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
# svglib requires a file path, write SVG to a temp file
with _tf.NamedTemporaryFile(suffix='.svg', delete=False) as tmp:
tmp.write(svg_data)
tmp_path = tmp.name
try:
drawing = svg2rlg(tmp_path)
finally:
os.unlink(tmp_path)
if drawing is None:
return None
scale_x = size / drawing.width if drawing.width else 1
scale_y = size / drawing.height if drawing.height else 1
scale = min(scale_x, scale_y)
drawing.width = size
drawing.height = size
drawing.scale(scale, scale)
buf = io.BytesIO()
renderPM.drawToFile(drawing, buf, fmt='PNG')
return buf.getvalue()
except Exception as exc:
print(f'[icon] svglib/reportlab conversion failed: {exc}', file=sys.stderr)
return None
def fetch_icon(
name: str,
color_hex: str = '000000',
size: int = 256,
required_collection: str | None = None,
) -> str | None:
"""Fetch an icon from the Iconify public API, convert to PNG, recolor."""
global _ICON_FETCH_ATTEMPTS
_ICON_FETCH_ATTEMPTS += 1
requested_name = name.strip()
has_explicit_prefix = ':' in requested_name
normalized_required_collection = (required_collection or '').strip()
if not has_explicit_prefix:
default_prefix = (
normalized_required_collection
if normalized_required_collection and normalized_required_collection != 'all'
else PPTX_ICON_COLLECTION
if PPTX_ICON_COLLECTION and PPTX_ICON_COLLECTION != 'all'
else 'mdi'
)
requested_name = f'{default_prefix}:{requested_name}'
prefix, icon_name = requested_name.split(':', 1)
effective_collection = (
normalized_required_collection
if normalized_required_collection and normalized_required_collection != 'all'
else PPTX_ICON_COLLECTION
if not has_explicit_prefix and PPTX_ICON_COLLECTION != 'all'
else 'all'
)
if effective_collection != 'all' and prefix != effective_collection:
_MISSING_ICONS.append({'icon': f'{prefix}:{icon_name}', 'reason': 'outside_selected_collection'})
print(f'[icon] REJECTED: {prefix}:{icon_name} outside collection {effective_collection}', file=sys.stderr)
return None
# Check temp dir for already-fetched icon this run
temp_dir = _get_icon_temp_dir()
png_path = os.path.join(temp_dir, prefix, f'{icon_name}.png')
if os.path.isfile(png_path):
return _recolor_png(png_path, color_hex)
svg_data = _download_svg(prefix, icon_name)
if svg_data is None:
_MISSING_ICONS.append({'icon': f'{prefix}:{icon_name}', 'reason': 'network_all_hosts_failed'})
return None
png_data = _svg_to_png(svg_data, size)
if png_data is None:
_MISSING_ICONS.append({'icon': f'{prefix}:{icon_name}', 'reason': 'svg_conversion_failed'})
return None
os.makedirs(os.path.join(temp_dir, prefix), exist_ok=True)
with open(png_path, 'wb') as f:
f.write(png_data)
return _recolor_png(png_path, color_hex)
def get_missing_icons() -> list[dict[str, str]]:
"""Return a copy of the missing-icon audit list."""
return list(_MISSING_ICONS)
def split_icon_audit_entries(entries: list[dict[str, str]]) -> tuple[list[dict[str, str]], list[dict[str, str]]]:
"""Split icon audit entries into collection-policy rejections vs real fetch failures."""
rejected: list[dict[str, str]] = []
unresolved: list[dict[str, str]] = []
for entry in entries:
if entry.get('reason') == 'outside_selected_collection':
rejected.append(entry)
else:
unresolved.append(entry)
return rejected, unresolved
def get_icon_audit_stats() -> dict[str, float | int]:
"""Return aggregate icon audit stats for post-staging QA classification."""
rejected, unresolved = split_icon_audit_entries(_MISSING_ICONS)
missing = len(unresolved)
requested = _ICON_FETCH_ATTEMPTS
missing_ratio = (missing / requested) if requested > 0 else 0.0
rejected_ratio = (len(rejected) / requested) if requested > 0 else 0.0
return {
'requested': requested,
'missing': missing,
'missingRatio': missing_ratio,
'rejectedByCollection': len(rejected),
'rejectedRatio': rejected_ratio,
}
def _load_theme_payload() -> dict[str, object]:
raw = os.environ.get('PPTX_THEME_JSON', '{}')
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
return {}
return parsed if isinstance(parsed, dict) else {}
def _load_theme() -> dict[str, str]:
parsed = _load_theme_payload()
raw_colors = parsed.get('C') if isinstance(parsed.get('C'), dict) else parsed
if not isinstance(raw_colors, dict):
return {}
return {
str(k): str(v).strip().lstrip('#').upper()
for k, v in raw_colors.items()
if isinstance(v, str) and v.strip()
}
def _load_slide_assets() -> list[dict[str, object]]:
raw = os.environ.get('PPTX_SLIDE_ASSETS_JSON', '')
if not raw.strip():
return []
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
return []
return parsed if isinstance(parsed, list) else []
def slide_assets(slide_index: int) -> dict[str, object]:
if 0 <= slide_index < len(SLIDE_ASSETS):
asset = SLIDE_ASSETS[slide_index]
if isinstance(asset, dict):
return asset
return {}
def slide_image_paths(slide_index: int) -> list[str]:
asset = slide_assets(slide_index)
paths: list[str] = []
selected_images = asset.get('selectedImages')
if isinstance(selected_images, list):
for image in selected_images:
if isinstance(image, dict):
image_path = image.get('imagePath')
if isinstance(image_path, str) and image_path.strip():
paths.append(image_path)
primary_path = asset.get('primaryImagePath')
if isinstance(primary_path, str) and primary_path.strip() and primary_path not in paths:
paths.insert(0, primary_path)
return paths
def slide_icon_name(slide_index: int) -> str | None:
asset = slide_assets(slide_index)
icon_name = asset.get('iconName') or asset.get('icon')
return icon_name if isinstance(icon_name, str) and icon_name.strip() else None
def slide_icon_collection(slide_index: int) -> str | None:
asset = slide_assets(slide_index)
collection = asset.get('iconCollection')
return collection if isinstance(collection, str) and collection.strip() else None
SLIDE_ASSETS = _load_slide_assets()
def rgb_color(value: str | None, fallback: str = '000000') -> RGBColor:
normalized = (value or fallback).strip().lstrip('#').upper()
if len(normalized) != 6:
normalized = fallback
return RGBColor.from_string(normalized)
def ensure_parent_dir(file_path: str) -> None:
Path(file_path).expanduser().resolve().parent.mkdir(parents=True, exist_ok=True)
def apply_widescreen(prs: PresentationType) -> PresentationType:
prs.slide_width = Inches(SLIDE_WIDTH_IN)
prs.slide_height = Inches(SLIDE_HEIGHT_IN)
return prs
def _convert_to_pptx_compatible(source: Path) -> Path:
"""Convert unsupported image formats (e.g. WebP) to PNG for python-pptx."""
if source.suffix.lower() not in ('.webp',):
return source
target = source.with_suffix('.png')
if target.exists():
return target
from PIL import Image
with Image.open(source) as img:
img.save(target, 'PNG')
return target
def safe_image_path(value: str | None) -> str | None:
if not value:
return None
candidate = Path(value).expanduser().resolve()
if not candidate.exists():
return None
candidate = _convert_to_pptx_compatible(candidate)
return str(candidate)
ICON_MAX_RENDER_DIMENSION_IN = 1.5
ICON_MAX_RENDER_DIMENSION_EMU = int(ICON_MAX_RENDER_DIMENSION_IN * 914400)
def _is_icon_asset(path: str) -> bool:
if _ICON_TEMP_DIR is None:
return False
normalized = os.path.normcase(os.path.normpath(path))
return normalized.startswith(os.path.normcase(os.path.normpath(_ICON_TEMP_DIR)) + os.sep)
def safe_add_picture(shapes, image_path: str | None, left, top, width=None, height=None):
# Guard: LLMs sometimes pass a Slide object instead of slide.shapes
if hasattr(shapes, 'shapes') and not hasattr(shapes, 'add_picture'):
shapes = shapes.shapes
resolved = safe_image_path(image_path)
if not resolved:
return None
if width is not None and height is not None and _is_icon_asset(resolved):
max_requested_dim = max(int(width), int(height))
if max_requested_dim > ICON_MAX_RENDER_DIMENSION_EMU:
icon_scale = ICON_MAX_RENDER_DIMENSION_EMU / max_requested_dim
scaled_width = max(1, int(width * icon_scale))
scaled_height = max(1, int(height * icon_scale))
left = left + int((width - scaled_width) / 2)
top = top + int((height - scaled_height) / 2)
width = scaled_width
height = scaled_height
# Preserve aspect ratio when both width and height are specified
if width is not None and height is not None:
try:
from PIL import Image as _PILImage
with _PILImage.open(resolved) as _img:
img_w, img_h = _img.size
if img_w > 0 and img_h > 0:
scale = min(width / img_w, height / img_h)
fit_w = int(img_w * scale)
fit_h = int(img_h * scale)
# Center within the bounding box
left = left + (width - fit_w) // 2
top = top + (height - fit_h) // 2
width = fit_w
height = fit_h
except Exception:
pass # Fall back to stretched dimensions
picture = shapes.add_picture(resolved, left, top, width=width, height=height)
if _is_icon_asset(resolved):
base_name = getattr(picture, 'name', '') or 'picture'
if not base_name.lower().startswith(('icon_', 'design_icon_', 'decor_icon_')):
picture.name = f'icon_{base_name}'
_register_shape_role(picture, 'template_design')
else:
_register_shape_role(picture, 'layout_managed')
return picture
def tag_as_design(shape, name: str = '') -> object:
"""Mark a shape as template/design β excluded from collision checks.
Sets a ``design_`` name prefix recognised by the layout validator and
registers the shape in the semantic role registry.
Call on any decorative shape (backgrounds, borders, accent blobs,
watermarks) so it does not trigger overlap warnings against
blueprint-managed content.
"""
base = name or getattr(shape, 'name', '') or 'shape'
if not base.lower().startswith(('design_', 'tmpl_', 'decor_', 'bg_')):
shape.name = f'design_{base}'
else:
shape.name = base
_register_shape_role(shape, 'template_design')
return shape
def safe_add_design_picture(shapes, image_path: str | None, left, top, width=None, height=None):
"""Add an image as a template/design element β excluded from collision checks.
Identical to ``safe_add_picture`` but tags the result with ``design_`` prefix.
"""
pic = safe_add_picture(shapes, image_path, left, top, width, height)
if pic is not None:
tag_as_design(pic)
return pic
def add_design_shape(shapes, auto_shape_type, left, top, width, height, name: str = ''):
"""Add an auto-shape and register it as template/design.
Use for decorative elements (backgrounds, borders, accent blobs, etc.)
that should not participate in collision or cramped-spacing checks.
"""
if hasattr(shapes, 'shapes') and not hasattr(shapes, 'add_shape'):
shapes = shapes.shapes
shape = shapes.add_shape(auto_shape_type, left, top, width, height)
tag_as_design(shape, name=name)
return shape
def add_managed_textbox(shapes, left, top, width, height, name: str = ''):
"""Add a textbox and register it as layout-managed.
Use for structural content placed from PRECOMPUTED_LAYOUT_SPECS β these
shapes participate in all validation checks including collision detection.
"""
if hasattr(shapes, 'shapes') and not hasattr(shapes, 'add_textbox'):
shapes = shapes.shapes
tb = shapes.add_textbox(left, top, width, height)
if name:
tb.name = name
_register_shape_role(tb, 'layout_managed')
return tb
def add_managed_shape(shapes, auto_shape_type, left, top, width, height, name: str = ''):
"""Add an auto-shape and register it as layout-managed.
Use for structural content (cards, panels, stat boxes) placed from
PRECOMPUTED_LAYOUT_SPECS that should participate in collision checks.
"""
if hasattr(shapes, 'shapes') and not hasattr(shapes, 'add_shape'):
shapes = shapes.shapes
shape = shapes.add_shape(auto_shape_type, left, top, width, height)
if name:
shape.name = name
_register_shape_role(shape, 'layout_managed')
return shape
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument('output_path')
parser.add_argument('--render-dir', default=None,
help='Preview render directory managed by the caller')
parser.add_argument('--workspace-dir', default=None,
help='Absolute path to the user workspace directory')
parser.add_argument('--post-process-only', action='store_true',
help='Run only post-processing on an existing PPTX (validation, preview, notebooklm)')
parser.add_argument('--renderer-mode', action='store_true',
help='Use the deterministic slide renderer')
return parser.parse_args()
# ---------------------------------------------------------------------------
# Color contrast utilities (WCAG 2.1)
# ---------------------------------------------------------------------------
def _srgb_to_linear(c: float) -> float:
"""Convert sRGB component (0-1) to linear."""
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
def _hex_to_rgb(hex_color: str) -> tuple[int, int, int]:
h = hex_color.lstrip('#')
return (int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))
def _luminance_hex(hex_color: str) -> float:
"""WCAG relative luminance from a hex color string."""
r, g, b = _hex_to_rgb(hex_color)
rs = _srgb_to_linear(r / 255)
gs = _srgb_to_linear(g / 255)
bs = _srgb_to_linear(b / 255)
return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs
def _blend_hex(fg_hex: str, bg_hex: str, fg_opacity: float) -> str:
"""Alpha-blend ``fg_hex`` over ``bg_hex`` at ``fg_opacity`` (0..1)."""
fg_hex = fg_hex.lstrip('#')[:6].ljust(6, '0')
bg_hex = bg_hex.lstrip('#')[:6].ljust(6, '0')
op = max(0.0, min(fg_opacity, 1.0))
parts: list[str] = []
for idx in (0, 2, 4):
f = int(fg_hex[idx:idx + 2], 16)
b = int(bg_hex[idx:idx + 2], 16)
parts.append(f'{max(0, min(round(f * op + b * (1.0 - op)), 255)):02X}')
return ''.join(parts)
def contrast_ratio(fg_hex: str, bg_hex: str) -> float:
"""WCAG 2.1 contrast ratio between two hex colors."""
l1 = _luminance_hex(fg_hex)
l2 = _luminance_hex(bg_hex)
lighter = max(l1, l2)
darker = min(l1, l2)
return (lighter + 0.05) / (darker + 0.05)
def _shift_lightness(hex_color: str, toward_dark: bool) -> list[str]:
"""Return up to 8 candidates by shifting only the L channel of *hex_color*
in 10 % increments toward 0 (dark) or 1 (light), preserving hue/saturation."""
r, g, b = _hex_to_rgb(hex_color)
# Convert to HLS (Python colorsys uses HLS, not HSL)
import colorsys
h, l, s = colorsys.rgb_to_hls(r / 255, g / 255, b / 255) # noqa: E741
candidates: list[str] = []
step = 0.10
for i in range(1, 9):
new_l = l - step * i if toward_dark else l + step * i
new_l = max(0.0, min(1.0, new_l))
nr, ng, nb = colorsys.hls_to_rgb(h, new_l, s)
candidates.append(f'{int(round(nr * 255)):02X}{int(round(ng * 255)):02X}{int(round(nb * 255)):02X}')
return candidates
def ensure_contrast(fg_hex: str, bg_hex: str, *, min_ratio: float = 4.5) -> str:
"""Return *fg_hex* if contrast is sufficient, else a lightness-adjusted variant.
Shifts only the L channel of *fg_hex* toward the appropriate extreme in 10 %
increments before falling back to the generic dark/light fallback, so hue and
saturation of accent colors are preserved where possible.
``min_ratio`` defaults to WCAG AA (4.5) for normal text; use 3.0 for large text.
"""
fg_hex = fg_hex.lstrip('#')
bg_hex = bg_hex.lstrip('#')
if contrast_ratio(fg_hex, bg_hex) >= min_ratio:
return fg_hex
bg_lum = _luminance_hex(bg_hex)
toward_dark = bg_lum > 0.4
for candidate in _shift_lightness(fg_hex, toward_dark):
if contrast_ratio(candidate, bg_hex) >= min_ratio:
return candidate
return '2D2D2D' if toward_dark else 'F0F0F0'
def add_native_chart(
slide,
chart_type,
chart_data,
left,
top,
width,
height,
*,
theme: dict[str, str] | None = None,
name: str = '',
):
"""Add an editable python-pptx chart to a slide and apply theme colours.
``chart_type`` should be a python-pptx chart enum member.
``chart_data`` should be a python-pptx chart data object.
Returns the chart shape.
"""
graphic_frame = slide.shapes.add_chart(chart_type, left, top, width, height, chart_data)
if name:
graphic_frame.name = name
_register_shape_role(graphic_frame, 'layout_managed')
chart = graphic_frame.chart
if theme:
keys = ['ACCENT1', 'ACCENT2', 'ACCENT3', 'ACCENT4', 'ACCENT5', 'ACCENT6']
colors = [theme[k].lstrip('#').upper() for k in keys if k in theme and theme[k]]
if colors and hasattr(chart, 'series'):
for idx, series in enumerate(chart.series):
hex_val = colors[idx % len(colors)]
try:
series.format.fill.solid()
series.format.fill.fore_color.rgb = RGBColor.from_string(hex_val)
except Exception:
pass
try:
series.format.line.color.rgb = RGBColor.from_string(hex_val)
except Exception:
pass
if chart_type in {XL_CHART_TYPE.PIE, XL_CHART_TYPE.DOUGHNUT}:
try:
for point_idx, point in enumerate(series.points):
point_hex = colors[point_idx % len(colors)]
point.format.fill.solid()
point.format.fill.fore_color.rgb = RGBColor.from_string(point_hex)
except Exception:
pass
return graphic_frame
def _cleanup_rogue_pptx(directory: Path, canonical_name: str) -> None:
"""Remove any PPTX files in *directory* that are not the canonical output."""
for entry in directory.iterdir():
if entry.is_file() and entry.suffix.lower() == '.pptx' and entry.name != canonical_name:
print(f'[runner] Removing rogue PPTX: {entry.name}', file=sys.stderr)
entry.unlink(missing_ok=True)
def _build_completion_report(
output_path: Path,
*,
warnings: list[str] | None = None,
contrast_fixes: int = 0,
missing_icons: list[dict[str, str]] | None = None,
rejected_icons: list[dict[str, str]] | None = None,
icon_stats: dict[str, float | int] | None = None,
missing_images: list[str] | None = None,
layout_issues: list[dict[str, str]] | None = None,
timing: dict[str, int | float] | None = None,
) -> dict:
"""Build a structured completion report for the TypeScript caller.
Includes a ``qa`` sub-object with post-staging QA findings so the
renderer can decide whether to trigger the poststaging workflow.
"""
report: dict = {
'status': 'error',
'outputPath': str(output_path),
'fileExists': False,
'slideCount': 0,
'fileSizeBytes': 0,
'warnings': warnings or [],
'timing': timing or {},
'qa': {
'contrastFixes': contrast_fixes,
'missingIcons': missing_icons or [],
'rejectedIcons': rejected_icons or [],
'iconStats': icon_stats or {'requested': 0, 'missing': 0, 'missingRatio': 0.0, 'rejectedByCollection': 0, 'rejectedRatio': 0.0},
'missingImages': missing_images or [],
'layoutIssues': layout_issues or [],
},
}
if not output_path.exists():
report['error'] = f'Output file not found: {output_path}'
return report
report['fileExists'] = True
report['fileSizeBytes'] = output_path.stat().st_size
if report['fileSizeBytes'] == 0:
report['error'] = 'Output file is empty (0 bytes)'
return report
try:
prs = Presentation(str(output_path))
report['slideCount'] = len(prs.slides)
if report['slideCount'] == 0:
report['status'] = 'warning'
report['warnings'].append('PPTX file contains 0 slides')
else:
report['status'] = 'success'
except Exception as exc:
report['error'] = f'Failed to open PPTX for verification: {exc}'
return report
def _normalize_shape_text(value: str) -> str:
return ' '.join(value.split())
def _extract_python_pptx_shape_text(shape) -> str:
if not getattr(shape, 'has_text_frame', False):
return ''
try:
return _normalize_shape_text('\n'.join(paragraph.text for paragraph in shape.text_frame.paragraphs))
except Exception:
return ''
def _find_shape_for_overflow(slide, *, shape_id: int | None, shape_name: str, shape_text: str, fallback_index: int):
shapes_list = list(slide.shapes)
if shape_id is not None:
for candidate in shapes_list:
if getattr(candidate, 'shape_id', None) == shape_id:
return candidate
if shape_name:
matching_name = [candidate for candidate in shapes_list if (getattr(candidate, 'name', '') or '') == shape_name]
if len(matching_name) == 1:
return matching_name[0]
if shape_text:
for candidate in matching_name:
if _extract_python_pptx_shape_text(candidate) == shape_text:
return candidate
if shape_text:
matching_text = [candidate for candidate in shapes_list if _extract_python_pptx_shape_text(candidate) == shape_text]
if len(matching_text) == 1:
return matching_text[0]
if 0 <= fallback_index < len(shapes_list):
return shapes_list[fallback_index]
return None
def _shrink_text_frame_fonts(shape, scale: float) -> bool:
changed = False
minimum_pt = 8.0
for para in shape.text_frame.paragraphs:
if para.font.size is not None:
para.font.size = Pt(max(round(para.font.size.pt * scale, 1), minimum_pt))
changed = True
for run in para.runs:
if run.font.size is not None:
run.font.size = Pt(max(round(run.font.size.pt * scale, 1), minimum_pt))
changed = True
return changed
def _collect_pillow_overflows(output_path: Path) -> list[dict[str, object]] | None:
"""Return Pillow-measured overflow metadata, or None if Pillow is unavailable."""
try:
from font_text_measure import TextMeasureRequest, measure_text_heights # type: ignore
except ImportError:
return None
prs = Presentation(str(output_path))
overflows: list[dict[str, object]] = []
for si, slide in enumerate(prs.slides):
shapes_list = list(slide.shapes)
for shi, shape in enumerate(shapes_list):
if not shape.has_text_frame:
continue
text = shape.text_frame.text
if not text or not text.strip():
continue
# Collect dominant font properties across all paragraphs/runs
max_font_size_pt = 18.0
font_family = 'Calibri'
is_bold = False
for para in shape.text_frame.paragraphs:
for run in para.runs:
if run.font.size is not None:
size_pt = run.font.size.pt
if size_pt > max_font_size_pt:
max_font_size_pt = size_pt
if run.font.name:
font_family = run.font.name
is_bold = bool(run.font.bold)
# Shape dimensions in inches (EMU β inches)
shape_width_in = shape.width / 914400.0
shape_height_in = shape.height / 914400.0
# Internal margins (EMU β inches, default ~0.05in each side)
tf = shape.text_frame
margin_left = (tf.margin_left if tf.margin_left is not None else 91440) / 914400.0
margin_right = (tf.margin_right if tf.margin_right is not None else 91440) / 914400.0
margin_top = (tf.margin_top if tf.margin_top is not None else 45720) / 914400.0
margin_bottom = (tf.margin_bottom if tf.margin_bottom is not None else 45720) / 914400.0
text_width_in = max(shape_width_in - margin_left - margin_right, 0.2)
usable_height_in = max(shape_height_in - margin_top - margin_bottom, 0.1)
normalized_text = _normalize_shape_text(text)
is_textbox = (shape.shape_type is not None and int(shape.shape_type) == 17)
req = TextMeasureRequest(
text=text,
width_in=text_width_in,
font_family=font_family,
font_size_pt=max_font_size_pt,
bold=is_bold,
)
heights = measure_text_heights([req])
required_height_in = heights[0] if heights else usable_height_in
# 5% tolerance (same as COM collector)
if required_height_in > usable_height_in * 1.05:
scale = min(usable_height_in / required_height_in, 1.0)
overflows.append({
'slide_idx': si,
'shape_idx': shi,
'shape_id': getattr(shape, 'shape_id', None),
'shape_name': str(getattr(shape, 'name', '') or ''),
'shape_text': normalized_text,
'scale': scale,
'is_textbox': is_textbox,
})
print(
f'[layout] Slide {si + 1}, "{shape.name}": '
f'need {required_height_in:.2f}in, have {usable_height_in:.2f}in '
f'(scale={scale:.0%}, {"textbox" if is_textbox else "shape"}) [pillow]',
file=sys.stderr,
)
return overflows
def _fix_text_overflow(output_path: Path) -> int:
"""Measure text overflow and repair text-bearing shapes.