-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathslide_renderer.py
More file actions
2761 lines (2395 loc) Β· 112 KB
/
slide_renderer.py
File metadata and controls
2761 lines (2395 loc) Β· 112 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
"""Deterministic slide renderer β converts layout-input.json + layout-specs.json to PPTX.
This module is the app's structured PPTX renderer. It reads slide data,
precomputed layout specs, theme/style settings, and slide assets, then writes
the deck directly.
The renderer uses the shared utility functions already defined in
``pptx-python-runner.py`` (``fetch_icon``, ``safe_add_picture``,
``ensure_contrast``, etc.) so rendering, repair, and validation all operate on
the same runtime contract.
Usage (standalone test)::
python slide_renderer.py \\
--layout-input previews/layout-input.json \\
--layout-specs previews/layout-specs.json \\
--output previews/presentation-preview.pptx \\
--workspace-dir /path/to/workspace
Usage (from pptx-python-runner.py)::
from slide_renderer import render_presentation
render_presentation(layout_input, layout_specs, theme, style, ...)
"""
from __future__ import annotations
import json
import math
import os
import sys
import re
from dataclasses import dataclass, replace
from pathlib import Path
if __package__ in {None, ''}:
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from pptx.chart.data import CategoryChartData
from pptx import Presentation
from pptx.enum.chart import XL_CHART_TYPE, XL_LEGEND_POSITION
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN, MSO_ANCHOR, MSO_AUTO_SIZE
from pptx.enum.shapes import MSO_AUTO_SHAPE_TYPE
from scripts.layout.layout_specs import ( # noqa: E402
LayoutSpec,
RectSpec,
SLIDE_WIDTH_IN,
SLIDE_HEIGHT_IN,
big_number_font_profile,
estimate_text_height_in,
)
from scripts.style_config import StyleConfig # noqa: E402
# ββ Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
EMU_PER_INCH = 914400
# ββ Render context βββββββββββββββββββββββββββββββββββββββββββββββββββ
@dataclass
class RenderContext:
"""Shared state threaded through all render functions."""
prs: object # Presentation
theme: dict[str, str]
style: StyleConfig
font_family: str
slide_assets: list[dict]
accent_cycle: list[str]
workspace_dir: str
theme_explicit: bool # True when user provided custom theme colors
text_box_style: str
show_slide_icons: bool
# ββ Utilities (injected by caller) βββββββββββββββββββββββββββ
# These are references to the same functions from pptx-python-runner.py
rgb_color: object # Callable[[str, str], RGBColor]
ensure_contrast: object # Callable[[str, str, float], str]
set_fill_transparency: object # Callable[[shape, float], None]
apply_gradient_fill: object # Callable[[shape, list[str], int], None]
fetch_icon: object # Callable[[str, str, int, str | None], str | None]
safe_add_picture: object # Callable[..., object | None]
safe_add_design_picture: object # Callable[..., object | None]
add_design_shape: object # Callable[..., object]
add_managed_textbox: object # Callable[..., object]
add_managed_shape: object # Callable[..., object]
add_native_chart: object # Callable[..., object]
tag_as_design: object # Callable[[object, str], None]
resolve_font: object # Callable[[str, str], str]
apply_widescreen: object # Callable[[object], object]
slide_image_paths: object # Callable[[int], list[str]]
slide_icon_name: object # Callable[[int], str | None]
slide_icon_collection: object # Callable[[int], str | None]
ensure_parent_dir: object # Callable[[str], None]
safe_image_path: object # Callable[[str], str | None]
# ββ Color helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _build_accent_cycle(theme: dict[str, str]) -> list[str]:
keys = ["ACCENT1", "ACCENT3", "ACCENT4", "ACCENT5", "ACCENT6", "ACCENT2"]
cycle: list[str] = []
for k in keys:
v = theme.get(k, "")
if isinstance(v, str) and v.strip():
cycle.append(v.strip().lstrip("#").upper())
if not cycle:
cycle = ["4472C4", "70AD47", "FFC000", "ED7D31", "5B9BD5", "A5A5A5"]
return cycle
def _hex_color(theme: dict[str, str], *keys: str) -> str:
for key in keys:
val = theme.get(key)
if isinstance(val, str) and val.strip():
return val.strip().lstrip("#").upper()
return "000000"
def _build_colors(theme: dict[str, str]) -> dict[str, str]:
return {
"BG": _hex_color(theme, "BG", "WHITE"),
"TEXT": _hex_color(theme, "TEXT", "DK1", "DARK"),
"DARK": _hex_color(theme, "DARK", "DK1", "TEXT"),
"DARK2": _hex_color(theme, "DARK2", "DK2", "BORDER", "TEXT"),
"LIGHT": _hex_color(theme, "LIGHT", "LT1", "WHITE", "BG"),
"LIGHT2": _hex_color(theme, "LIGHT2", "LT2", "BORDER", "BG"),
"SECONDARY": _hex_color(theme, "SECONDARY", "ACCENT2", "LT2"),
"BORDER": _hex_color(theme, "BORDER", "SECONDARY", "ACCENT2"),
"ACCENT1": _hex_color(theme, "ACCENT1", "PRIMARY"),
"ACCENT2": _hex_color(theme, "ACCENT2", "SECONDARY"),
"ACCENT3": _hex_color(theme, "ACCENT3", "ACCENT1"),
"ACCENT4": _hex_color(theme, "ACCENT4", "ACCENT2"),
"ACCENT5": _hex_color(theme, "ACCENT5", "ACCENT3"),
"ACCENT6": _hex_color(theme, "ACCENT6", "ACCENT4"),
"PRIMARY": _hex_color(theme, "PRIMARY", "ACCENT1"),
}
def _mix_hex(a_hex: str, b_hex: str, weight_b: float) -> str:
"""Return a blended hex color with ``weight_b`` contribution from ``b_hex``."""
weight_b = max(0.0, min(weight_b, 1.0))
weight_a = 1.0 - weight_b
a_hex = (a_hex or "000000").strip().lstrip("#")[:6].ljust(6, "0")
b_hex = (b_hex or "000000").strip().lstrip("#")[:6].ljust(6, "0")
comps = []
for idx in (0, 2, 4):
a_val = int(a_hex[idx:idx + 2], 16)
b_val = int(b_hex[idx:idx + 2], 16)
mixed = round(a_val * weight_a + b_val * weight_b)
comps.append(f"{max(0, min(mixed, 255)):02X}")
return "".join(comps)
def _luminance(hex_color: str) -> float:
"""Return relative luminance (0..1) from a hex color string."""
h = (hex_color or "000000").strip().lstrip("#")[:6].ljust(6, "0")
r, g, b = int(h[0:2], 16) / 255.0, int(h[2:4], 16) / 255.0, int(h[4:6], 16) / 255.0
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def _effective_panel_bg(ctx: RenderContext, fill_hex: str, colors: dict[str, str]) -> str:
"""Return the colour text will actually sit on after frosted/tinted mixing.
During rendering, frosted panels mix ``fill_hex`` toward white (or dark),
and tinted panels use ``fill_hex`` at reduced opacity over the slide BG.
Contrast must be checked against this effective colour, not ``fill_hex``.
"""
style = ctx.style
if style.panel_fill == "frosted":
if style.dark_mode:
return _mix_hex(fill_hex, colors.get("DARK", "1B1B1B"), 0.45)
return _mix_hex(fill_hex, colors.get("LIGHT", "FFFFFF"), 0.55)
if style.panel_fill == "tinted":
# Tinted panels are fill_hex at panel_fill_opacity over the slide BG.
# Approximate the blended visual result.
opacity = style.panel_fill_opacity
return _mix_hex(colors["BG"], fill_hex, opacity)
if style.panel_fill == "transparent":
return colors["BG"]
# solid β fill_hex as-is
return fill_hex
def _apply_slide_bg_gradient(
slide, color_stops: tuple[str, ...], angle_degrees: float = 90.0,
) -> None:
"""Apply a linear gradient background to a slide via DrawingML XML."""
from lxml import etree
ns_a = "http://schemas.openxmlformats.org/drawingml/2006/main"
ns_p = "http://schemas.openxmlformats.org/presentationml/2006/main"
# Ensure the background XML structure exists
slide.background.fill.solid()
bg_pr = slide.background._element.find(f"{{{ns_p}}}bg/{{{ns_p}}}bgPr")
if bg_pr is None:
return
# Remove existing fill elements
for tag in ("solidFill", "gradFill", "pattFill", "blipFill", "noFill"):
for el in list(bg_pr.findall(f"{{{ns_a}}}{tag}")):
bg_pr.remove(el)
# Build gradient fill
grad = etree.Element(f"{{{ns_a}}}gradFill")
gs_lst = etree.SubElement(grad, f"{{{ns_a}}}gsLst")
n = max(len(color_stops) - 1, 1)
for i, c in enumerate(color_stops):
gs = etree.SubElement(gs_lst, f"{{{ns_a}}}gs")
gs.set("pos", str(int(round(i * 100000 / n))))
srgb = etree.SubElement(gs, f"{{{ns_a}}}srgbClr")
srgb.set("val", c.lstrip("#").upper())
lin = etree.SubElement(grad, f"{{{ns_a}}}lin")
lin.set("ang", str(int(round((angle_degrees % 360) * 60000))))
lin.set("scaled", "1")
# Insert before effectLst (must come first per OOXML schema)
bg_pr.insert(0, grad)
def _reset_slide_background(slide) -> None:
"""Remove any slide-level background override and inherit from layout/master."""
background = getattr(slide, "background", None)
element = getattr(background, "_element", None)
if element is None:
return
ns_p = "http://schemas.openxmlformats.org/presentationml/2006/main"
bg = element.find(f"{{{ns_p}}}bg")
if bg is not None:
element.remove(bg)
def _apply_slide_background(
slide, color_stops: tuple[str, ...], angle_degrees: float = 90.0,
) -> None:
"""Apply an intentional slide background fill.
Empty stops mean "leave inherited background alone".
"""
if not color_stops:
_reset_slide_background(slide)
return
if len(color_stops) == 1:
slide.background.fill.solid()
slide.background.fill.fore_color.rgb = RGBColor.from_string(
color_stops[0].lstrip("#").upper()
)
return
_apply_slide_bg_gradient(slide, color_stops, angle_degrees=angle_degrees)
def _extract_background_hex(surface) -> str | None:
"""Read a representative background hex from a slide-like surface."""
background = getattr(surface, "background", None)
fill = getattr(background, "fill", None)
fill_type = getattr(fill, "type", None)
if fill_type is not None and int(fill_type) == 1:
fore_color = getattr(fill, "fore_color", None)
rgb = getattr(fore_color, "rgb", None)
if rgb is not None:
return str(rgb)
element = getattr(background, "_element", None)
if element is None:
return None
ns_a = "http://schemas.openxmlformats.org/drawingml/2006/main"
ns_p = "http://schemas.openxmlformats.org/presentationml/2006/main"
bg_pr = element.find(f"{{{ns_p}}}bg/{{{ns_p}}}bgPr")
if bg_pr is None:
return None
grad = bg_pr.find(f"{{{ns_a}}}gradFill")
if grad is None:
return None
gs_lst = grad.find(f"{{{ns_a}}}gsLst")
if gs_lst is None:
return None
stops = gs_lst.findall(f"{{{ns_a}}}gs")
if not stops:
return None
srgb = stops[0].find(f"{{{ns_a}}}srgbClr")
if srgb is None:
return None
value = (srgb.get("val") or "").strip().upper()
return value if re.fullmatch(r"[0-9A-F]{6}", value) else None
def _resolve_slide_surface_hex(
slide,
*,
fallback_hex: str,
) -> str:
"""Return the visible slide surface used for contrast decisions."""
for surface in (slide, getattr(slide, "slide_layout", None), getattr(getattr(slide, "slide_layout", None), "slide_master", None)):
surface_hex = _extract_background_hex(surface)
if surface_hex:
return surface_hex
return fallback_hex
def _clear_seed_slides(prs) -> None:
"""Remove any pre-authored slides while keeping layouts and masters intact."""
slide_id_list = getattr(prs.slides, "_sldIdLst", None)
if slide_id_list is None:
return
for slide_id in list(slide_id_list):
rel_id = slide_id.rId
prs.part.drop_rel(rel_id)
slide_id_list.remove(slide_id)
def _resolve_slide_colors(
ctx: RenderContext,
base_colors: dict[str, str],
accent_a: str,
accent_b: str,
slide_index: int,
*,
prefer_style_background: bool = True,
) -> dict[str, str]:
"""Derive per-slide colour roles from the user's palette + the active style.
Slide background comes from the runtime BG role (or the style background
gradient fallback). Panels, borders, and secondary tones are then derived
from the remaining theme roles so they complement the active style.
"""
style = ctx.style
colors = dict(base_colors)
# Background: use style fallback when the user has not provided explicit
# theme colors and the style defines its own characteristic background.
# First color in bg_colors is the representative solid for contrast math.
bg_hex = colors["BG"]
if prefer_style_background and style.bg_colors:
bg_hex = style.bg_colors[0]
bg_is_dark = _luminance(bg_hex) < 0.22
if style.dark_mode:
panel_base = _mix_hex(colors["DARK2"], accent_a, 0.28)
panel_alt = _mix_hex(colors["DARK2"], accent_b, 0.24)
border_hex = _mix_hex(colors["LIGHT2"], accent_a, 0.40)
text_hex = ctx.ensure_contrast(colors["TEXT"], bg_hex)
secondary_hex = ctx.ensure_contrast(colors["LIGHT2"], bg_hex)
else:
panel_base = _mix_hex(colors["LIGHT"], accent_a, 0.28)
panel_alt = _mix_hex(colors["LIGHT"], accent_b, 0.22)
border_hex = _mix_hex(colors["BORDER"], accent_a, 0.35)
if bg_is_dark:
text_hex = ctx.ensure_contrast(colors["LIGHT"], bg_hex)
secondary_hex = ctx.ensure_contrast(colors["LIGHT2"], bg_hex)
else:
text_hex = ctx.ensure_contrast(colors["TEXT"], bg_hex)
secondary_hex = ctx.ensure_contrast(colors["TEXT"], panel_base)
# Style-specific panel fill overrides
if style.panel_fill == "solid":
panel_base = accent_a
panel_alt = accent_b if slide_index % 2 == 0 else _mix_hex(accent_b, colors["LIGHT"], 0.20)
elif style.panel_fill == "frosted":
if style.dark_mode:
panel_base = _mix_hex(colors["DARK2"], accent_a, 0.32)
panel_alt = _mix_hex(colors["DARK2"], accent_b, 0.28)
else:
panel_base = _mix_hex(bg_hex, accent_a, 0.25)
panel_alt = _mix_hex(bg_hex, accent_b, 0.20)
elif style.panel_fill == "tinted":
# Tinted panels should be clearly coloured β visible accent wash
if style.dark_mode:
panel_base = _mix_hex(colors["DARK2"], accent_a, 0.40)
panel_alt = _mix_hex(colors["DARK2"], accent_b, 0.35)
else:
panel_base = _mix_hex(bg_hex, accent_a, 0.38)
panel_alt = _mix_hex(bg_hex, accent_b, 0.30)
elif style.panel_fill == "transparent":
panel_base = _mix_hex(bg_hex, accent_a, 0.15)
panel_alt = _mix_hex(bg_hex, accent_b, 0.12)
colors["BG"] = bg_hex
colors["TEXT"] = text_hex
colors["SECONDARY"] = secondary_hex
colors["BORDER"] = border_hex
colors["PANEL_BASE"] = panel_base
colors["PANEL_ALT"] = panel_alt
return colors
# ββ Low-level PPTX writers ββββββββββββββββββββββββββββββββββββββββββ
def _write_run(paragraph, text: str, font_size_pt: float, color_hex: str,
bold: bool, font_name: str) -> object:
run = paragraph.add_run()
run.text = text
run.font.size = Pt(font_size_pt)
run.font.bold = bold
run.font.color.rgb = RGBColor.from_string(color_hex)
run.font.name = font_name
return run
def _add_textbox(ctx: RenderContext, slide, rect: RectSpec, text: str,
font_size_pt: float, color_hex: str, *,
bold: bool = False, name: str = "",
align: int = PP_ALIGN.LEFT, line_spacing: float = 0.0) -> object:
"""Add a textbox with NO fill (transparent by default)."""
tb = ctx.add_managed_textbox(
slide.shapes,
Inches(rect.x), Inches(rect.y),
Inches(rect.w), Inches(rect.h),
name=name,
)
tf = tb.text_frame
tf.word_wrap = True
tf.auto_size = MSO_AUTO_SIZE.NONE
tf.vertical_anchor = MSO_ANCHOR.TOP
tf.margin_left = Inches(0.02)
tf.margin_right = Inches(0.02)
tf.margin_top = Inches(0.01)
tf.margin_bottom = Inches(0.01)
# NO fill β textboxes are transparent by default
p = tf.paragraphs[0]
p.alignment = align
density = ctx.style.content_density
if density == "compact":
spacing_mult = 0.94
elif density == "spacious":
spacing_mult = 1.08
else:
spacing_mult = 1.0
if line_spacing:
p.line_spacing = line_spacing * spacing_mult
else:
base_spacing = 1.12 if font_size_pt >= 24 else 1.32
p.line_spacing = base_spacing * spacing_mult
_write_run(p, text, font_size_pt, color_hex, bold, ctx.font_family)
return tb
def _add_panel(ctx: RenderContext, slide, rect: RectSpec,
fill_hex: str, border_hex: str, *,
accent_b_hex: str = "", name: str = "") -> object:
"""Add a panel shape with fill controlled by StyleConfig."""
style = ctx.style
panel_shape_type = (
MSO_AUTO_SHAPE_TYPE.ROUNDED_RECTANGLE
if style.text_box_corner_style == "rounded"
else MSO_AUTO_SHAPE_TYPE.RECTANGLE
)
colors = _build_colors(ctx.theme)
if style.panel_shadow != "none" and style.panel_fill != "transparent":
shadow_dx = 0.10 if style.panel_shadow == "hard" else 0.06
shadow_dy = 0.11 if style.panel_shadow == "hard" else 0.08
shadow = ctx.add_design_shape(
slide.shapes,
panel_shape_type,
Inches(rect.x + shadow_dx), Inches(rect.y + shadow_dy),
Inches(rect.w), Inches(rect.h),
name=f"{name}_shadow" if name else "panel_shadow",
)
if style.panel_shadow == "hard":
shadow.fill.solid()
shadow.fill.fore_color.rgb = ctx.rgb_color(colors.get("DARK", "111111"))
else:
shadow.fill.solid()
shadow.fill.fore_color.rgb = ctx.rgb_color(accent_b_hex or colors.get("ACCENT2", fill_hex))
ctx.set_fill_transparency(shadow, 0.32 if style.dark_mode else 0.22)
shadow.line.fill.background()
shape = ctx.add_managed_shape(
slide.shapes,
panel_shape_type,
Inches(rect.x), Inches(rect.y),
Inches(rect.w), Inches(rect.h),
name=name,
)
if style.panel_fill == "transparent":
shape.fill.background()
elif style.panel_fill == "frosted":
# Frosted glass: semi-transparent accent-tinted fill
frost_color = _mix_hex(fill_hex, colors.get("LIGHT", "FFFFFF"), 0.55) if not style.dark_mode else _mix_hex(fill_hex, colors.get("DARK", "1B1B1B"), 0.45)
shape.fill.solid()
shape.fill.fore_color.rgb = ctx.rgb_color(frost_color)
ctx.set_fill_transparency(shape, 1.0 - style.panel_fill_opacity)
elif style.panel_fill == "tinted":
shape.fill.solid()
shape.fill.fore_color.rgb = ctx.rgb_color(fill_hex)
ctx.set_fill_transparency(shape, 1.0 - style.panel_fill_opacity)
elif style.panel_fill == "solid":
if style.color_treatment == "gradient" and accent_b_hex:
ctx.apply_gradient_fill(shape, [fill_hex, accent_b_hex],
angle_degrees=style.gradient_angle)
else:
shape.fill.solid()
shape.fill.fore_color.rgb = ctx.rgb_color(fill_hex)
if style.panel_fill_opacity < 1.0:
ctx.set_fill_transparency(shape, 1.0 - style.panel_fill_opacity)
else:
shape.fill.background()
if style.panel_border:
shape.line.fill.solid()
shape.line.color.rgb = ctx.rgb_color(border_hex or fill_hex)
shape.line.width = Pt(style.panel_border_weight_pt)
else:
shape.line.fill.background()
return shape
def _add_panel_stripe(ctx: RenderContext, slide, rect: RectSpec,
color_hex: str, idx: int) -> object | None:
"""Add a thin vertical color stripe on the left edge of a panel."""
if not ctx.style.panel_stripe:
return None
stripe_w = max(min(rect.w * 0.02, 0.08), 0.04)
stripe = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(rect.x), Inches(rect.y),
Inches(stripe_w), Inches(rect.h),
name=f"stripe_{idx}",
)
stripe.fill.solid()
stripe.fill.fore_color.rgb = ctx.rgb_color(color_hex)
stripe.line.fill.background()
return stripe
# ββ Design language (decorative accents) βββββββββββββββββββββββββββββ
def _add_design_language(ctx: RenderContext, slide, spec: LayoutSpec,
accent_a: str, accent_b: str,
colors: dict[str, str]) -> None:
"""Add optional decorative elements controlled by StyleConfig."""
style = ctx.style
ref = spec.title_rect or spec.content_rect or spec.key_message_rect
if ref is None:
return
if style.background_grid != "none":
grid_color = _mix_hex(accent_a, colors["BG"], 0.25 if style.dark_mode else 0.45)
if style.background_grid == "fine":
x = 0.0
while x <= SLIDE_WIDTH_IN:
line = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(x), Inches(0),
Inches(0.01), Inches(SLIDE_HEIGHT_IN),
name="bg_grid_v",
)
line.fill.solid()
line.fill.fore_color.rgb = ctx.rgb_color(grid_color)
ctx.set_fill_transparency(line, 0.86 if style.dark_mode else 0.90)
line.line.fill.background()
x += 0.72
y = 0.0
while y <= SLIDE_HEIGHT_IN:
line = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(0), Inches(y),
Inches(SLIDE_WIDTH_IN), Inches(0.01),
name="bg_grid_h",
)
line.fill.solid()
line.fill.fore_color.rgb = ctx.rgb_color(grid_color)
ctx.set_fill_transparency(line, 0.88 if style.dark_mode else 0.92)
line.line.fill.background()
y += 0.56
elif style.background_grid == "perspective":
horizon_y = SLIDE_HEIGHT_IN * 0.66
rail_y = horizon_y
rail_gap = 0.12
while rail_y < SLIDE_HEIGHT_IN:
rail = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(0), Inches(rail_y),
Inches(SLIDE_WIDTH_IN), Inches(0.014),
name="perspective_rail",
)
rail.fill.solid()
rail.fill.fore_color.rgb = ctx.rgb_color(grid_color)
ctx.set_fill_transparency(rail, 0.70 if style.dark_mode else 0.82)
rail.line.fill.background()
rail_y += rail_gap
rail_gap *= 1.23
vanish_x = SLIDE_WIDTH_IN / 2
bottom_y = SLIDE_HEIGHT_IN
for idx, base_x in enumerate([0.35, 1.4, 2.7, 4.2, 5.8, 7.2, 8.8, 10.3, 11.6, 12.5]):
dx = base_x - vanish_x
line_len = max(bottom_y - horizon_y, 1.6)
line = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(base_x), Inches(horizon_y),
Inches(0.014), Inches(line_len),
name=f"perspective_ray_{idx}",
)
line.rotation = max(min(-dx * 7.5, 42), -42)
line.fill.solid()
line.fill.fore_color.rgb = ctx.rgb_color(grid_color)
ctx.set_fill_transparency(line, 0.72 if style.dark_mode else 0.84)
line.line.fill.background()
if style.frame_outline != "none":
frame_color = _mix_hex(accent_a, accent_b, 0.30)
frame_specs = [(0.22, 0.22, SLIDE_WIDTH_IN - 0.44, SLIDE_HEIGHT_IN - 0.44, 1.2)]
if style.frame_outline == "double":
frame_specs.append((0.38, 0.38, SLIDE_WIDTH_IN - 0.76, SLIDE_HEIGHT_IN - 0.76, 0.8))
for idx, (x, y, w, h, width_pt) in enumerate(frame_specs):
frame = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(x), Inches(y),
Inches(w), Inches(h),
name=f"frame_outline_{idx}",
)
frame.fill.background()
frame.line.fill.solid()
frame.line.color.rgb = ctx.rgb_color(frame_color)
frame.line.width = Pt(width_pt)
if style.corner_brackets:
bracket_color = _mix_hex(accent_a, accent_b, 0.45)
pad = 0.12
arm = max(min(ref.w * 0.10, 0.42), 0.24)
thick = 0.03
corners = [
(ref.x - pad, ref.y - pad, 1, 1),
(ref.x + ref.w + pad, ref.y - pad, -1, 1),
(ref.x - pad, ref.y + ref.h + pad, 1, -1),
(ref.x + ref.w + pad, ref.y + ref.h + pad, -1, -1),
]
for idx, (cx, cy, sx, sy) in enumerate(corners):
h_bar = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(cx if sx > 0 else cx - arm), Inches(cy if sy > 0 else cy - thick),
Inches(arm), Inches(thick),
name=f"corner_h_{idx}",
)
v_bar = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(cx if sx > 0 else cx - thick), Inches(cy if sy > 0 else cy - arm),
Inches(thick), Inches(arm),
name=f"corner_v_{idx}",
)
for part in (h_bar, v_bar):
part.fill.solid()
part.fill.fore_color.rgb = ctx.rgb_color(bracket_color)
part.line.fill.background()
if style.accent_rings:
anchor = spec.icon_rect or spec.hero_rect or spec.sidebar_rect or ref
ring_color = _mix_hex(accent_b, accent_a, 0.45)
base_size = max(min(anchor.h * 0.28, 1.2), 0.62)
ring_x = min(anchor.x + anchor.w - base_size * 0.50, SLIDE_WIDTH_IN - base_size - 0.14)
ring_y = max(anchor.y - base_size * 0.08, 0.14)
for idx, scale in enumerate((1.0, 0.72, 0.44)):
size = base_size * scale
ring = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.OVAL,
Inches(ring_x + (base_size - size) / 2),
Inches(ring_y + (base_size - size) / 2),
Inches(size), Inches(size),
name=f"accent_ring_{idx}",
)
ring.fill.background()
ring.line.fill.solid()
ring.line.color.rgb = ctx.rgb_color(ring_color)
ring.line.width = Pt(1.6 if idx == 0 else 1.0)
# Vertical accent bar β thick enough to be a significant visual feature
if style.title_accent_bar:
bottom_limit = (spec.notes_rect.y - 0.08) if spec.notes_rect else min(ref.y + ref.h + 4.8, SLIDE_HEIGHT_IN - 0.12)
bar_w = max(min(ref.x * 0.28, 0.18), 0.10)
bar_gap = max(min(ref.x * 0.10, 0.08), 0.04)
bar_x = max(ref.x - bar_w - bar_gap, 0.02)
bar_y = max(ref.y - min(ref.h * 0.15, 0.08), 0.0)
bar_h = max(bottom_limit - bar_y, ref.h + 0.4)
bar = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(bar_x), Inches(bar_y),
Inches(bar_w), Inches(bar_h),
name="accent_bar",
)
bar.fill.solid()
bar.fill.fore_color.rgb = ctx.rgb_color(accent_a)
bar.line.fill.background()
if style.decorative_blob:
anchor = spec.content_rect or ref
blob_w = min(max(anchor.w * 0.42, 2.8), 4.4)
blob_h = min(max(anchor.h * 0.62, 1.9), 3.0)
blob_x = min(anchor.x + anchor.w - blob_w * 0.55, SLIDE_WIDTH_IN - blob_w - 0.10)
blob_y = max(ref.y - blob_h * 0.18, 0.10)
blob = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.OVAL,
Inches(blob_x), Inches(blob_y),
Inches(blob_w), Inches(blob_h),
name="bg_blob",
)
if style.color_treatment == "gradient":
ctx.apply_gradient_fill(blob, [_mix_hex(accent_a, "FFFFFF", 0.20), _mix_hex(accent_b, "FFFFFF", 0.40)],
angle_degrees=style.gradient_angle)
else:
blob.fill.solid()
blob.fill.fore_color.rgb = ctx.rgb_color(_mix_hex(accent_a, "FFFFFF", 0.45))
ctx.set_fill_transparency(blob, 0.65 if style.dark_mode else 0.78)
blob.line.fill.background()
# Horizontal accent rule β bold, extends full width of content area
if style.title_accent_rule and spec.accent_rect is not None:
rule_h = max(spec.accent_rect.h, 0.06) # at least 0.06" thick
rule = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(spec.accent_rect.x), Inches(spec.accent_rect.y),
Inches(spec.accent_rect.w), Inches(rule_h),
name="accent_rule",
)
if style.color_treatment == "gradient":
ctx.apply_gradient_fill(rule, [accent_a, accent_b],
angle_degrees=style.gradient_angle)
else:
rule.fill.solid()
rule.fill.fore_color.rgb = ctx.rgb_color(accent_a)
rule.line.fill.background()
# Decorative circle β large enough to be a visible design element
if style.decorative_circle:
anchor = spec.content_rect or ref
circle_size = max(min(anchor.h * 0.28, 1.0), 0.55)
circle_x = min(anchor.x + anchor.w - circle_size * 0.55, SLIDE_WIDTH_IN - circle_size - 0.06)
circle_y = (
min(spec.notes_rect.y - circle_size - 0.10, SLIDE_HEIGHT_IN - circle_size - 0.06)
if spec.notes_rect else
min(anchor.y + anchor.h - circle_size * 0.25, SLIDE_HEIGHT_IN - circle_size - 0.06)
)
circle = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.OVAL,
Inches(circle_x), Inches(circle_y),
Inches(circle_size), Inches(circle_size),
name="decor_circle",
)
circle.fill.background()
circle.line.fill.solid()
circle.line.color.rgb = ctx.rgb_color(accent_b)
circle.line.width = Pt(2.0)
if style.top_left_blocks:
block_y = 0.32
block_size = 0.10
gap = 0.03
start_x = 0.52
block_colors = list(style.top_left_block_colors[:2]) or [accent_a, _mix_hex(accent_a, colors.get("LIGHT", "FFFFFF"), 0.28)]
for idx, block_color in enumerate(block_colors):
block = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(start_x + idx * (block_size + gap)), Inches(block_y),
Inches(block_size), Inches(block_size),
name=f"top_left_block_{idx}",
)
block.fill.solid()
block.fill.fore_color.rgb = ctx.rgb_color(block_color)
block.line.fill.background()
# Rainbow spectrum stripe bars β full-width bands at top and bottom
if style.rainbow_stripe_bars:
accent_keys = ["ACCENT1", "ACCENT2", "ACCENT3", "ACCENT4", "ACCENT5", "ACCENT6"]
stripe_count = len(accent_keys)
bar_height = 0.08 # inches per stripe
segment_w = SLIDE_WIDTH_IN / stripe_count
for pos, y_base in [("top", 0.0), ("bottom", SLIDE_HEIGHT_IN - bar_height)]:
for i, key in enumerate(accent_keys):
stripe = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(i * segment_w), Inches(y_base),
Inches(segment_w + 0.01), Inches(bar_height),
name=f"rainbow_{pos}_{i}",
)
stripe.fill.solid()
stripe.fill.fore_color.rgb = ctx.rgb_color(colors.get(key, accent_a))
stripe.line.fill.background()
# Sparkle stars β small star shapes in corners
if style.sparkle_stars:
star_positions = [
(0.20, 0.18, 0.28), # top-left
(SLIDE_WIDTH_IN - 0.52, 0.14, 0.32), # top-right
(0.30, SLIDE_HEIGHT_IN - 0.55, 0.24), # bottom-left
(SLIDE_WIDTH_IN - 0.44, SLIDE_HEIGHT_IN - 0.48, 0.26), # bottom-right
]
star_colors = [accent_a, accent_b,
colors.get("ACCENT3", accent_a),
colors.get("ACCENT4", accent_b)]
for i, (sx, sy, sz) in enumerate(star_positions):
star = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.STAR_4_POINT,
Inches(sx), Inches(sy),
Inches(sz), Inches(sz),
name=f"sparkle_star_{i}",
)
star.fill.solid()
star.fill.fore_color.rgb = ctx.rgb_color(star_colors[i % len(star_colors)])
ctx.set_fill_transparency(star, 0.35)
star.line.fill.background()
# Scan-line overlay β thin horizontal lines across the slide
if style.scan_lines:
scan_color = colors.get("WHITE", "FFFFFF")
y = 0.0
idx = 0
while y < SLIDE_HEIGHT_IN:
line = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(0), Inches(y),
Inches(SLIDE_WIDTH_IN), Inches(0.008),
name=f"scan_line_{idx}",
)
line.fill.solid()
line.fill.fore_color.rgb = ctx.rgb_color(scan_color)
ctx.set_fill_transparency(line, 0.92)
line.line.fill.background()
y += 0.16
idx += 1
def _add_key_message_band(ctx: RenderContext, slide, spec: LayoutSpec,
accent_a: str, accent_b: str,
colors: dict[str, str]) -> str | None:
"""Optionally add a semi-transparent band behind the key-message text."""
if not ctx.style.key_message_band or spec.key_message_rect is None:
return None
r = spec.key_message_rect
# Band is clipped exactly to key_message_rect β no padding into title zone
band = ctx.add_design_shape(
slide.shapes,
MSO_AUTO_SHAPE_TYPE.RECTANGLE,
Inches(r.x), Inches(r.y),
Inches(r.w), Inches(r.h),
name="key_band",
)
if ctx.style.color_treatment == "gradient":
ctx.apply_gradient_fill(band, [accent_a, accent_b],
angle_degrees=ctx.style.gradient_angle)
else:
band.fill.solid()
band.fill.fore_color.rgb = ctx.rgb_color(accent_a)
ctx.set_fill_transparency(band, 1.0 - ctx.style.key_message_band_opacity)
band.line.fill.background()
return ctx.ensure_contrast(colors["TEXT"], accent_a)
# ββ Font sizing helpers ββββββββββββββββββββββββββββββββββββββββββββββ
def _adjust_title_font(
rect: RectSpec,
text: str,
base_pt: float,
scale: float = 1.0,
*,
min_pt: float = 22,
) -> float:
size = max(base_pt * scale, min_pt)
required = estimate_text_height_in(text, rect.w, size, line_height=1.08)
if required <= rect.h * 0.86:
return size
while size > min_pt and required > rect.h * 1.02:
size = max(min_pt, size - 2)
required = estimate_text_height_in(text, rect.w, size, line_height=1.08)
if required > rect.h * 0.92 and size > min_pt:
size = max(min_pt, size - 1)
return size
def _adjust_body_font(width_in: float, height_in: float, text: str,
base_pt: float) -> float:
required = estimate_text_height_in(text, width_in, base_pt, line_height=1.18)
if required > height_in * 1.05:
return max(11, base_pt - 1.2)
elif required > height_in * 0.85:
return max(11, base_pt - 0.6)
return base_pt
def _reflow_big_number_spec(
spec: LayoutSpec,
title_text: str,
key_message_text: str,
*,
title_pt: float,
key_pt: float,
) -> LayoutSpec:
if spec.title_rect is None:
return spec
title_height = max(
min(
estimate_text_height_in(title_text, spec.title_rect.w, title_pt, line_height=1.08) + 0.08,
spec.title_rect.h,
),
0.9,
)
title_rect = replace(spec.title_rect, h=round(title_height, 4))
next_y = round(title_rect.y + title_rect.h + 0.12, 4)
key_rect = spec.key_message_rect
if key_rect is not None:
key_height = key_rect.h
if key_message_text.strip():
key_height = max(
estimate_text_height_in(key_message_text, key_rect.w, key_pt, line_height=1.16) + 0.06,
0.4,
)
key_rect = replace(key_rect, y=next_y, h=round(key_height, 4))
next_y = round(key_rect.y + key_rect.h + 0.18, 4)
content_rect = spec.content_rect
if content_rect is not None:
notes_top = spec.notes_rect.y if spec.notes_rect is not None else (SLIDE_HEIGHT_IN - 0.62)
content_bottom = max(notes_top - 0.18, next_y + 0.8)
content_rect = replace(
content_rect,
y=next_y,
h=round(max(content_bottom - next_y, 0.8), 4),
)
return replace(spec, title_rect=title_rect, key_message_rect=key_rect, content_rect=content_rect)
def _density_gap_multiplier(density: str) -> float:
if density == "compact":
return 0.82
if density == "spacious":
return 1.24
return 1.0
def _whitespace_gap_multiplier(bias: str) -> float:
"""Additional gap scaling from ``StyleLayoutPolicy.whitespace_bias``."""
if bias == "tight":
return 0.85
if bias == "generous":
return 1.15
if bias == "editorial":
return 1.20
return 1.0
def _density_line_spacing_multiplier(density: str) -> float:
if density == "compact":
return 0.94
if density == "spacious":
return 1.08
return 1.0
def _density_padding_adjustment(density: str) -> float:
if density == "compact":
return -0.03
if density == "spacious":
return 0.04
return 0.0
def _density_font_adjustment(density: str) -> float:
if density == "compact":
return -0.6
if density == "spacious":
return 0.5
return 0.0