Overview
Chapter 04: Programmatic Slide Generation with Python-PPTX & Marp
Playbook Track: 05 – Presentation Slides & Architecture Diagrams (Visual Systems, Claude Code & Antigravity Workflows)
Target Audience: Year 1 Computer Science & Software Engineering Students Core Tooling Stack: python-pptx, Marp CLI, Slidev, Gemini 2.5 Flash (Slide Synthesis), Python 3.11+
Delivery Status: 🔍 Ready for Review (Tier 1 Markdown)
1. The Big Picture & Real-World Analogy
Writing Markdown vs. Dragging Text Boxes in Photoshop
Imagine you need to publish a clean 5-page lab report:
- The Photoshop Nightmare: You open an image editor. For every single sentence, you have to create a new text layer, click and drag the box to align with the margin, manually press enter when words hit the edge, and guess whether the paragraph is centered. If you add one sentence to page 1, you have to manually drag every single text box on the next 4 pages down by 20 pixels!
- The Modern Markdown Approach: You open a text editor and type
# Introductionand- Bullet point. The Markdown viewer or LaTeX engine automatically calculates line wrapping, font sizes, margins, and page numbers.
Traditional presentation design in PowerPoint or Google Slides is that exact Photoshop nightmare:
- Engineers waste hours dragging rectangles, fiddling with fonts, and lining up cards.
- If benchmark numbers change or a new metric is added, the whole slide has to be rearranged by hand.
Programmatic Slide Generation (Marp & python-pptx) brings the Markdown revolution to presentation decks!
You write your slide content in structured Markdown (marp: true) or JSON. An automated geometry engine calculates exact 16:9 widescreen coordinates, prevents text boxes from colliding, and compiles native .pptx, .pdf, and interactive .html decks in automated CI/CD pipelines.
2. Engineering Jargon Demystifier Table
| Industry Term | What It Actually Means | Freshman Student Analogy |
|---|---|---|
| Marp (Markdown Presentation) | An open-source CLI compiler that converts Markdown documents into slide presentations (.pdf, .pptx, .html). |
A static site generator like Jekyll or Hugo, but for presentation slides. |
| python-pptx | A Python library for programmatically creating, modifying, and styling Microsoft PowerPoint .pptx files. |
Writing a Python script that generates PowerPoint files from database records. |
| 16:9 Widescreen Standard | The modern display aspect ratio ($13.333 \times 7.5$ inches) used by laptops, monitors, and modern conference projectors. | A modern widescreen movie format compared to old boxy 1980s television sets (4:3). |
| Bounding Box $(x, y, w, h)$ | The mathematical rectangle enclosing a slide element (X-position, Y-position, Width, Height). | The coordinates and dimensions of a picture frame hung on a wall. |
| Bounding Box Collision (AABB) | A visual defect where two text boxes or images accidentally overlap on a slide, making text unreadable. | Two people trying to sit in the same chair at the same time. |
| Gutter | The clean, empty margin space left between two adjacent cards or columns on a slide. | The median strip or safety lane between two highway traffic lanes. |
| Headless Rendering | Running a web browser (like Chromium) in the background with no monitor to export HTML slides to PDF. | Running a compiler from the command line without opening a graphical window. |
3. The 5-Minute Micro-Lab: The Slide Collision Detector
Run this zero-dependency Python script to see how 2D Axis-Aligned Bounding Box (AABB) collision detection prevents overlapping text boxes on a slide:
"""
Micro-Lab: 2D Slide Bounding Box Collision Detector
PB-05 Chapter 4 Micro-Lab (Zero External Dependencies)
"""
def detect_box_collision(box1: dict, box2: dict) -> bool:
"""
Checks if two Axis-Aligned Bounding Boxes (AABB) overlap on a slide canvas.
Box format: {"x": float, "y": float, "w": float, "h": float}
"""
x1_min, x1_max = box1["x"], box1["x"] + box1["w"]
y1_min, y1_max = box1["y"], box1["y"] + box1["h"]
x2_min, x2_max = box2["x"], box2["x"] + box2["w"]
y2_min, y2_max = box2["y"], box2["y"] + box2["h"]
# Separating axis theorem: if separated on either axis, no collision
if x1_max <= x2_min or x2_max <= x1_min:
return False
if y1_max <= y2_min or y2_max <= y1_min:
return False
return True
if __name__ == "__main__":
# Slide dimensions: 13.33 x 7.50 inches (16:9 standard)
card_a = {"name": "MetricsCard", "x": 1.0, "y": 2.0, "w": 5.0, "h": 3.0}
# Overlapping card (collides with Card A!)
bad_card_b = {"name": "GraphCard", "x": 4.5, "y": 3.0, "w": 5.0, "h": 3.0}
# Clean card placed to the right with 0.5 inch gutter
good_card_b = {"name": "GraphCard", "x": 6.5, "y": 2.0, "w": 5.0, "h": 3.0}
print("=== Testing Overlapping Cards ===")
collision1 = detect_box_collision(card_a, bad_card_b)
print(f"Collision Detected: {collision1} -> SLIDE REJECTED!")
print("\n=== Testing Well-Spaced Cards ===")
collision2 = detect_box_collision(card_a, good_card_b)
print(f"Collision Detected: {collision2} -> SLIDE APPROVED!")
4. Slide Automation & Geometry Math
In technical organizations, the friction between engineering reality and executive communication is acute:
- Engineers spend weeks designing complex microservice architectures and running rigorous benchmarks.
- When it comes time to report progress to the VP of Engineering, CTO, or enterprise clients, the engineer must spend three days manually copying metrics, formatting bullet points, dragging colored boxes, and fighting with Microsoft PowerPoint or Google Slides.
- As soon as benchmark numbers update or service topologies change, the entire presentation deck must be redrawn manually.
To eliminate this productivity drain, modern teams adopt Programmatic Slide Engineering:
- Separation of Content and Presentation: Defining presentation decks in clean, version-controlled Markdown or structured JSON schemas.
- Automated Layout Coordinate Geometry: Using algorithmic positioning engines to compute millimeter-accurate 16:9 bounding boxes, preventing text collisions and visual crowding.
- Headless Multi-Format Compilers: Compiling presentations directly into
.pptx, vector.pdf, and standalone.htmlvia python-pptx and Marp CLI in automated CI/CD pipelines.
+---------------------------------------------------------------------------------------------------+
| PROGRAMMATIC SLIDE COMPILATION ARCHITECTURE |
+---------------------------------------------------------------------------------------------------+
| |
| +--------------------------+ +--------------------------+ |
| | RAW METRICS & ARCH DATA | ------> | AI SLIDE SYNTHESIZER | |
| | - Benchmark Telemetry | | - Gemini 2.5 Flash | |
| | - System Topology Graph | | - Claude 3.7 Sonnet | |
| +--------------------------+ +--------------------------+ |
| | |
| v Structured Slide AST |
| +--------------------------+ +--------------------------+ |
| | HEADLESS CLI COMPILERS | <------ | SLIDE GEOMETRY ENGINE | |
| | - Marp CLI (marp-cli) | | - 16:9 Widescreen Math | |
| | - python-pptx Engine | | - Collision Detector | |
| | - Headless Chromium | | - Golden Ratio Gutters | |
| +--------------------------+ +--------------------------+ |
| | |
| v |
| +-------------------------------------------------------------------------------------------+ |
| | EXECUTIVE-READY ARTIFACT OUTPUTS | |
| | - Native PowerPoint Presentation (.pptx) with Master Slide Inheritance | |
| | - Print-Ready Vector PDF (.pdf) for Board Meetings | |
| | - Responsive Interactive HTML (.html) with Pan/Zoom & Presenter Notes | |
| +-------------------------------------------------------------------------------------------+ |
| |
+---------------------------------------------------------------------------------------------------+
1.1 The 16:9 Widescreen Coordinate Geometry Standard
Microsoft PowerPoint and OpenXML define slide space using English Metric Units (EMUs) or fractional inches:
- $1 ext{ inch} = 914,400 ext{ EMUs} = 25.4 ext{ mm} = 72 ext{ points}$.
- Modern enterprise displays and conference projectors strictly use the 16:9 Widescreen Standard: $$ ext{Width} = 13.333 ext{ inches } (12,192,000 ext{ EMUs}) \quad imes \quad ext{Height} = 7.500 ext{ inches } (6,858,000 ext{ EMUs})$$
- By calculating bounding box coordinates $(x, y, w, h)$ mathematically, programmatic slide generators guarantee that:
- Card widths are distributed uniformly across horizontal available space: $$W_{ ext{card}} = rac{W_{ ext{available}} - (N - 1) \cdot G_{ ext{gutter}}}{N}$$
- Bounding boxes are guaranteed to be mutually disjoint: $$orall i eq j, \quad ext{Box}_i \cap ext{Box}_j = \emptyset$$
- All visual elements remain strictly within printable safe margins ($M_x \ge 0.8 ext{in}$, $M_y \ge 0.6 ext{in}$).
2. Programmatic Slide Generation State Machine
flowchart TD
A["Raw Data Ingestion: Telemetry JSON + Architecture Spec"] --> B["Slide Decomposition: Partition into 5-10 Discrete Storyboard Units"]
B --> C["Layout Template Selection: Title, Two-Column, 3-Card Metric, or Hero Diagram"]
C --> D["Geometry Engine: Compute Bounding Boxes, Gutters & Safe Margins"]
D --> E{"Collision & Overflow Audit"}
E -- "Collision / Spill Detected" --> F["Refactor Geometry: Adjust Font Scale or Expand Slide Count"]
E -- "Geometry Clean" --> G["Transpile Target: Marp Markdown or python-pptx XML"]
G --> H["Headless Build: marp-cli --pdf / python-pptx save()"]
H --> I["Artifact Delivery: Executive 16:9 Presentation Deck"]
style A fill:#f5f5f5,stroke:#9e9e9e,stroke-width:2px;
style E fill:#fff3e0,stroke:#ff9800,stroke-width:2px;
style F fill:#ffebee,stroke:#f44336,stroke-width:2px;
style I fill:#e8f5e9,stroke:#4caf50,stroke-width:2px;
3. Gate 2: Mandatory Manual vs. Programmatic Contrasts
Automating slide creation eliminates the repetitive toil of manual presentation crafting.
| Presentation Dimension | Manual PowerPoint Dragging | Programmatic Slide Engineering (Marp, python-pptx) | Operational Consequence |
|---|---|---|---|
| Data Synchronization | Manual copy-pasting of benchmark numbers and graphs into slide text boxes. | Dynamic binding: slide generator ingests raw JSON/CSV and compiles updated slides in seconds. | Zero human error; numbers on slides are guaranteed to match production telemetry. |
| Layout Consistency | Human aligns boxes by eye; slight misalignments and irregular gutters look amateur. | Mathematical alignment: coordinate engine calculates exact pixel/millimeter margins and gutters. | Executive-grade polish and visual symmetry across all 20+ slides in the deck. |
| Version Control | Binary .pptx files committed to Git, bloating repository size with unmergeable diffs. |
Plain-text Markdown (presentation.md) or Python scripts; fully diffable and reviewable in PRs. |
Team collaboration via standard Git pull requests instead of emailing attachments. |
| Automation in CI/CD | Impossible: requires desktop GUI application and human operator. | Native headless execution: marp-cli generates .pdf and .pptx directly inside GitHub Actions. |
Automatic release of updated executive slide decks on every major software release tag. |
| Cognitive Density Control | "Wall of Text": author crams 200 words per slide in 10pt font. | Algorithmic linting: enforces the 30-word limit per slide and formats data as structured cards. | Dramatically higher audience engagement and executive comprehension. |
4. Gate 3: Frontier AI Prompts & Slide Schemas
Frontier models like Gemini 2.5 Flash excel at transforming unstructured engineering reports into structured 16:9 presentation storyboards.
4.1 Executive Slide Deck Drafter Prompt (gemini-2.5-flash)
SYSTEM INSTRUCTION: You are an Executive Technical Storyboard Specialist and Visual Communications Architect.
TASK: Transform the provided system architecture and benchmark telemetry into a 6-slide Executive Briefing Deck.
CONSTRAINTS:
1. Strict 16:9 Widescreen Orientation.
2. The "Less is More" Rule: Maximum 30 words per slide. Zero walls of text.
3. Every slide MUST use one of the canonical layout archetypes:
- TITLE_SLIDE: Hero title, subtitle, author, metadata.
- THREE_METRIC_CARDS: 3 high-impact metric boxes (e.g., Latency, Cost, Accuracy).
- TWO_COLUMN: Left side 60% concept explanation; right side 40% architecture diagram.
- ARCHITECTURE_HERO: Centered high-resolution C4 container diagram with 3 key takeaway callouts.
4. Output valid JSON adhering to the SlideDeckSpecificationSchema.
4.2 Structured JSON Schema for Slide Decks (SlideDeckSpecificationSchema)
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "SlideDeckSpecification",
"type": "object",
"properties": {
"title": { "type": "string" },
"author": { "type": "string" },
"theme": { "type": "string", "enum": ["gaia", "uncover", "default", "corporate_blue"] },
"slides": {
"type": "array",
"items": {
"type": "object",
"properties": {
"slide_number": { "type": "integer", "minimum": 1 },
"title": { "type": "string" },
"layout_type": { "type": "string", "enum": ["TITLE_SLIDE", "TWO_COLUMN", "THREE_METRIC_CARDS", "ARCHITECTURE_HERO"] },
"cards": {
"type": "array",
"items": {
"type": "object",
"properties": {
"headline": { "type": "string" },
"metric_value": { "type": "string" },
"body": { "type": "string" }
},
"required": ["headline", "metric_value", "body"]
}
},
"diagram_source": { "type": "string" }
},
"required": ["slide_number", "title", "layout_type"]
}
}
},
"required": ["title", "author", "theme", "slides"]
}
5. Gate 4: Quantitative Visual & Tooling Trade-Off Matrix
Choosing a slide generation stack depends on presentation fidelity, programmatic flexibility, and deployment context:
| Slide Toolchain | Headless CI/CD Automation | Programmatic Data Binding | Custom CSS / Theming | Interactive Animations | Executive Readiness |
|---|---|---|---|---|---|
| Desktop PowerPoint / Keynote | [FAIL] None (GUI only) | [FAIL] Manual copy-paste | Restricted (Ribbon UI) | Native PowerPoint transitions | High (Familiar) |
python-pptx Library |
Native (Python script) | Complete (Direct data structures) | XML manipulation | [FAIL] Static layouts only | High (Native .pptx output) |
| Marp (Markdown Presentation) | Fast (marp-cli Go/Node) |
High (Markdown templates) | Modern CSS3 Flexbox/Grid | Basic CSS transitions | Superior (Clean & modern) |
| Slidev (Vue / Vite Stack) | High (slidev export) |
Moderate (Vue reactive state) | Full Tailwind CSS & Vue components | Rich (Monaco editor inline) | Developer Conference Gold |
| Quarto Reveal.js | High (quarto render) |
High (Jupyter / R chunks) | SCSS theming | Fragment animations | Academic & Scientific Gold |
6. Gate 5: The 10 Methodological Threats to Validity & Slide Anti-Patterns
When generating programmatic presentation decks, teams must guard against ten visual and technical failure modes:
1. The "Wall of Text" Cognitive Choke
- Anti-Pattern: Generating slides with 6 bullet points of 3 sentences each. Audience members read the text and stop listening to the speaker.
- Defense: The 3-30 Rule: Maximum 3 visual cards or concepts per slide, and maximum 30 total words per slide.
2. Bounding Box Overlap & Font Clipping
- Anti-Pattern: Dynamic text expanding beyond the pre-calculated card boundary, overlapping with the slide footer.
- Defense: Implement automated bounding box collision checks; use dynamic font-scaling algorithms that reduce font size if string length exceeds limits.
3. Aspect Ratio Distortion (4:3 vs. 16:9 Mismatch)
- Anti-Pattern: Compiling slides in legacy 4:3 format, resulting in ugly black pillarboxes on modern wide projectors.
- Defense: Explicitly set widescreen dimensions: $13.333 imes 7.500$ inches in
python-pptxandaspect: 16:9in Marp.
4. Unembedded Custom Font Corruption
- Anti-Pattern: Styling slides with a boutique font installed on the developer's laptop; when presented on the CEO's machine, it falls back to Times New Roman.
- Defense: Use universal system font stacks (e.g.,
'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif) or export to vector PDF.
5. Low-Contrast Background Bleed
- Anti-Pattern: Placing white text over light gray cards, rendering metrics unreadable on low-brightness conference room screens.
- Defense: Enforce WCAG 2.1 AA contrast ratio ($\ge 4.5:1$); pair dark slate text (
#0f172a) with crisp white card containers (#ffffff).
6. Bullet Point Monotony
- Anti-Pattern: Every slide looks identical: a title followed by 4 dashed bullet points.
- Defense: Use varied spatial layouts: 3-column metric cards, 2-column comparison tables, and full-bleed architecture hero views.
7. Missing Visual Anchors in Data Visualizations
- Anti-Pattern: Presenting a bar chart or diagram without a bolded takeaway callout.
- Defense: Always accompany diagrams with an Executive Takeaway Badge summarizing the primary insight in 6 words.
8. Hardcoded Absolute Coordinates
- Anti-Pattern: Hardcoding pixel positions like
left: 450px, causing elements to misalign if margins change. - Defense: Calculate coordinates relative to dynamic layout gutters and available content widths.
9. Headless Chromium Dependency Drift
- Anti-Pattern:
marp-clifailing in CI/CD because the local Docker runner lacks Chromium rendering libraries. - Defense: Use containerized Marp runners (
marpteam/marp-cli) or nativepython-pptxcompilation without browser dependencies.
10. Neglecting Presenter Notes
- Anti-Pattern: Omitting talking points from programmatic decks, leaving speakers without presentation cues.
- Defense: Generate automated presenter notes inside Marp Markdown (
<!-- speaker notes -->) and PowerPoint note slides.
11. Gate 6: Mandatory Hands-On Lab (Visual Engineering Challenge)
Objective
You will implement an automated Slide Geometry Engine & Marp Compiler in zero-dependency Python 3.11+. The engine will mathematically calculate 16:9 widescreen layout coordinates, audit elements for boundary overflows and visual collisions, and compile structured slide specifications into production-grade Marp presentation decks.
Experimental Protocol
- Coordinate Geometry Calculation: Compute bounding boxes for a 3-card metric layout, ensuring uniform card widths, $0.4 ext{in}$ gutters, and $0.8 ext{in}$ safe margins within a $13.333 imes 7.500 ext{in}$ 16:9 canvas.
- Collision & Overflow Auditing: Programmatically detect boundary overflows ($x > 13.333 ext{in}$) and pairwise bounding-box intersections.
- Marp Deck Compilation: Transpile the validated slide structures into production-ready Marp Markdown, including theme directives (
theme: gaia), CSS grid columns, and executive styling. - Self-Test Verification: Run built-in assertions confirming that all geometric constraints, collision detectors, and compiler outputs operate flawlessly.
12. Gate 7: Mandatory Recommended Answer & Executable Solution
The following zero-dependency Python 3.11+ script provides the complete reference implementation of the Slide Geometry Engine & Marp Compiler.
"""
test_ch04_diagram_engine.py
Zero-dependency Python 3.11+ engine for PB-05 Chapter 4:
SlideGeometryEngine & MarpCompiler
"""
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Dict, Any, Optional, Tuple
class SlideLayoutType(str, Enum):
TITLE_SLIDE = "TITLE_SLIDE"
TWO_COLUMN = "TWO_COLUMN"
THREE_METRIC_CARDS = "THREE_METRIC_CARDS"
ARCHITECTURE_HERO = "ARCHITECTURE_HERO"
@dataclass
class BoundingBox:
left: float # Inches
top: float # Inches
width: float # Inches
height: float # Inches
@property
def right(self) -> float:
return self.left + self.width
@property
def bottom(self) -> float:
return self.top + self.height
def intersects(self, other: "BoundingBox") -> bool:
"""Checks if two bounding boxes overlap with non-zero area."""
return not (
self.right <= other.left or
self.left >= other.right or
self.bottom <= other.top or
self.top >= other.bottom
)
@dataclass
class SlideElement:
element_id: str
element_type: str # "TITLE", "BODY", "CARD", "DIAGRAM", "FOOTER"
box: BoundingBox
content: str
@dataclass
class SlideDefinition:
slide_number: int
title: str
layout_type: SlideLayoutType
elements: List[SlideElement] = field(default_factory=list)
class SlideGeometryEngine:
"""Calculates 16:9 widescreen layout geometry and enforces visual collision avoidance."""
# 16:9 Standard Widescreen Dimensions in Inches
SLIDE_WIDTH = 13.333
SLIDE_HEIGHT = 7.500
MARGIN_X = 0.800
MARGIN_TOP = 0.800
MARGIN_BOTTOM = 0.600
@classmethod
def create_three_card_layout(cls, slide_num: int, title: str, card_contents: List[Tuple[str, str]]) -> SlideDefinition:
"""Generates a mathematically balanced 3-card metric layout."""
if len(card_contents) != 3:
raise ValueError("Exactly 3 cards required for THREE_METRIC_CARDS layout.")
elements: List[SlideElement] = []
# 1. Title Element
title_box = BoundingBox(
left=cls.MARGIN_X,
top=cls.MARGIN_TOP,
width=cls.SLIDE_WIDTH - (2 * cls.MARGIN_X),
height=1.000
)
elements.append(SlideElement("title", "TITLE", title_box, title))
# 2. Compute 3 Cards with 2 Gutters
available_width = cls.SLIDE_WIDTH - (2 * cls.MARGIN_X)
gutter = 0.400
card_width = (available_width - (2 * gutter)) / 3.0
card_top = title_box.bottom + 0.400
card_height = cls.SLIDE_HEIGHT - card_top - cls.MARGIN_BOTTOM
for i, (headline, metric_body) in enumerate(card_contents):
card_left = cls.MARGIN_X + (i * (card_width + gutter))
c_box = BoundingBox(left=round(card_left, 3), top=round(card_top, 3), width=round(card_width, 3), height=round(card_height, 3))
content_str = f"**{headline}**\n\n{metric_body}"
elements.append(SlideElement(f"card_{i+1}", "CARD", c_box, content_str))
return SlideDefinition(slide_number=slide_num, title=title, layout_type=SlideLayoutType.THREE_METRIC_CARDS, elements=elements)
@classmethod
def validate_slide_geometry(cls, slide: SlideDefinition) -> List[Dict[str, str]]:
"""Audits slide elements for boundary overflows and bounding-box collisions."""
findings: List[Dict[str, str]] = []
# 1. Boundary overflow check
for elem in slide.elements:
b = elem.box
if b.left < 0 or b.top < 0 or b.right > cls.SLIDE_WIDTH or b.bottom > cls.SLIDE_HEIGHT:
findings.append({
"code": "GEO_001",
"severity": "ERROR",
"message": f"Element '{elem.element_id}' exceeds 16:9 slide boundaries (bounds: {b.right:.2f}x{b.bottom:.2f} in)."
})
# 2. Pairwise collision check
for i in range(len(slide.elements)):
for j in range(i + 1, len(slide.elements)):
e1 = slide.elements[i]
e2 = slide.elements[j]
if e1.box.intersects(e2.box):
findings.append({
"code": "GEO_002",
"severity": "ERROR",
"message": f"Visual collision: Element '{e1.element_id}' intersects with '{e2.element_id}'."
})
return findings
class MarpSlideCompiler:
"""Compiles structured slide definitions into production-grade Marp Markdown presentation decks."""
@classmethod
def compile_deck(cls, title: str, author: str, slides: List[SlideDefinition]) -> str:
lines = [
"---",
"marp: true",
"theme: gaia",
"_class: lead",
"paginate: true",
"backgroundColor: #f5f8fa",
"color: #1e293b",
f"title: \"{title}\"",
f"author: \"{author}\"",
"style: |",
" section { font-family: 'Inter', sans-serif; }",
" h1 { color: #0f172a; font-weight: 700; }",
" .columns { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }",
" .card { background: #ffffff; border-radius: 8px; padding: 24px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }",
"---",
"",
f"# {title}",
f"### Executive Architecture Brief",
f"**Author**: {author}",
""
]
for s in slides:
lines.extend([
"---",
"",
f"## {s.title}",
""
])
if s.layout_type == SlideLayoutType.THREE_METRIC_CARDS:
lines.append("<div class=\"columns\">")
cards = [e for e in s.elements if e.element_type == "CARD"]
for c in cards:
lines.extend([
"<div class=\"card\">",
"",
c.content,
"",
"</div>"
])
lines.append("</div>")
else:
for e in s.elements:
if e.element_type != "TITLE":
lines.append(e.content)
lines.append("")
return "\n".join(lines)
# ==========================================
# Self-Test Verification Suite
# ==========================================
if __name__ == "__main__":
import unittest
class TestSlideGeometryAndMarp(unittest.TestCase):
def test_three_card_geometry_generation(self):
cards_data = [
("Coordination Tax", "Reduced by 42% via hierarchical topology."),
("Inference Latency", "P95 response time capped under 450ms."),
("Token Efficiency", "1.2M tokens saved per 10k automated runs.")
]
slide = SlideGeometryEngine.create_three_card_layout(
slide_num=2,
title="System Performance & Cost Breakthroughs",
card_contents=cards_data
)
self.assertEqual(len(slide.elements), 4) # 1 Title + 3 Cards
# Validate geometry bounds & zero collisions
findings = SlideGeometryEngine.validate_slide_geometry(slide)
self.assertEqual(len(findings), 0)
def test_catch_slide_boundary_overflow(self):
# Element intentionally placed outside 13.333x7.500 boundary
overflow_elem = SlideElement("overflow_btn", "CARD", BoundingBox(12.0, 6.0, 2.5, 2.0), "Spill")
slide = SlideDefinition(1, "Overflow Test", SlideLayoutType.TITLE_SLIDE, [overflow_elem])
findings = SlideGeometryEngine.validate_slide_geometry(slide)
self.assertEqual(len(findings), 1)
self.assertEqual(findings[0]["code"], "GEO_001")
def test_catch_bounding_box_collision(self):
# Two overlapping boxes
e1 = SlideElement("box1", "CARD", BoundingBox(2.0, 2.0, 4.0, 3.0), "First")
e2 = SlideElement("box2", "CARD", BoundingBox(3.0, 2.5, 4.0, 3.0), "Overlapping")
slide = SlideDefinition(1, "Collision Test", SlideLayoutType.TITLE_SLIDE, [e1, e2])
findings = SlideGeometryEngine.validate_slide_geometry(slide)
self.assertEqual(len(findings), 1)
self.assertEqual(findings[0]["code"], "GEO_002")
def test_marp_deck_compilation(self):
cards_data = [
("Throughput", "15k req/sec"),
("Error Rate", "< 0.001%"),
("Cost", "$0.004/run")
]
slide = SlideGeometryEngine.create_three_card_layout(2, "Operational Metrics", cards_data)
deck_md = MarpSlideCompiler.compile_deck("Enterprise Architecture Deck", "Principal Architect", [slide])
self.assertIn("marp: true", deck_md)
self.assertIn("theme: gaia", deck_md)
self.assertIn("## Operational Metrics", deck_md)
self.assertIn("<div class=\"columns\">", deck_md)
self.assertIn("15k req/sec", deck_md)
suite = unittest.TestLoader().loadTestsFromTestCase(TestSlideGeometryAndMarp)
runner = unittest.TextTestRunner(verbosity=2)
test_result = runner.run(suite)
if not test_result.wasSuccessful():
exit(1)
print("\n[PASS] All PB-05 Chapter 4 Unit Tests Passed Successfully (100% Conformance).")
Verification & Execution Output
When executed in Python 3.11+, this engine confirms 16:9 layout calculation, boundary overflow detection, collision avoidance, and Marp deck compilation:
test_catch_bounding_box_collision (__main__.TestSlideGeometryAndMarp.test_catch_bounding_box_collision) ... ok
test_catch_slide_boundary_overflow (__main__.TestSlideGeometryAndMarp.test_catch_slide_boundary_overflow) ... ok
test_marp_deck_compilation (__main__.TestSlideGeometryAndMarp.test_marp_deck_compilation) ... ok
test_three_card_geometry_generation (__main__.TestSlideGeometryAndMarp.test_three_card_geometry_generation) ... ok
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
[PASS] All PB-05 Chapter 4 Unit Tests Passed Successfully (100% Conformance).
9. Summary & Visual Engineering Milestone Checklist
Before moving to Chapter 05 (Claude Code & Antigravity CLI Workflows, Skills & Plugins):
- Mastered 16:9 widescreen coordinate geometry ($13.333 imes 7.500$ inches).
- Engineered bounding box collision avoidance and overflow detection.
- Automated Marp Markdown deck compilation with CSS grid card layouts.
- Contrasted manual PowerPoint dragging with programmatic slide engineering.
- Calibrated Gemini 2.5 Flash prompts for structured slide specification generation.
- Compiled the Quantitative Trade-Off Matrix for slide toolchains (python-pptx vs. Marp vs. Slidev).
- Mitigated the 10 Visual Slide Anti-Patterns (including the Wall of Text).
- Executed and validated the zero-dependency Python 3.11+ slide geometry engine.