ppt-master-got-test / interface /app_gradio.py
Albator2570's picture
V9.1 fix export: SVG sanitize before export, full diagnostics, backup PPTX fallback
8840a52 verified
#!/usr/bin/env python3
"""
PPT Master — Interface Gradio V5
Full PPT Master workflow: Strategist → spec_lock → Image Acquisition → Executor (LLM SVG) → Quality Check → Finalize → Export
"""
import gradio as gr
import json
import os
import sys
import time
import glob
import shutil
import subprocess
import re
import urllib.parse
import urllib.request
import base64
import mimetypes
from pathlib import Path
from datetime import datetime
# Setup paths
SCRIPT_DIR = Path(__file__).resolve().parent
SKILL_DIR = SCRIPT_DIR / "skills" / "ppt-master"
SCRIPTS_DIR = SKILL_DIR / "scripts"
PROJECTS_DIR = SCRIPT_DIR / "projects"
REFS_DIR = SKILL_DIR / "references"
sys.path.insert(0, str(SCRIPTS_DIR))
from config import load_prefixed_env_file
# Load env
load_prefixed_env_file(("OPENROUTER_", "COMFYUI_", "IMAGE_", "PEXELS_", "PIXABY_", "PIXABAY_", "GROQ_"))
# ============================================================
# LLM Client
# ============================================================
def llm_chat(prompt, system=None, max_tokens=32000, temperature=0.3, model_override=None):
import requests
api_key = os.environ.get("OPENROUTER_API_KEY", "")
model = model_override or os.environ.get("OPENROUTER_MODEL", "tencent/hy3-preview:free")
base_url = os.environ.get("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1").rstrip("/")
if not api_key:
raise RuntimeError("OPENROUTER_API_KEY non configuré dans .env")
messages = []
if system:
messages.append({"role": "system", "content": system})
messages.append({"role": "user", "content": prompt})
payload = {"model": model, "messages": messages, "temperature": temperature, "max_tokens": max_tokens}
# For reasoning models, exclude internal reasoning from output
if "hy3" in model or "qwen3" in model:
payload["reasoning"] = {"exclude": True}
r = requests.post(f"{base_url}/chat/completions",
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json",
"HTTP-Referer": "http://localhost/ppt-master", "X-Title": "ppt-master-gradio"},
json=payload, timeout=600)
if r.status_code >= 400:
raise RuntimeError(f"OpenRouter erreur {r.status_code}: {r.text[:500]}")
data = r.json()
content = data.get("choices", [{}])[0].get("message", {}).get("content")
if not content:
raise RuntimeError(f"Pas de contenu retourné par le LLM")
return content
# Model selection: use the best model for each task
MODEL_STRATEGIST = "tencent/hy3-preview:free" # Good at planning/reasoning
MODEL_EXECUTOR = "openai/gpt-oss-120b:free" # Best tested free model for SVG code generation
MODEL_CRITIC = "tencent/hy3-preview:free" # Good visual/design critic and instruction follower
MODEL_FALLBACK_EXECUTOR = "tencent/hy3-preview:free" # Fallback if GPT-OSS is rate-limited
# ============================================================
# WEB RESEARCH (optional, no API key)
# ============================================================
def web_research(subject, max_results=6):
"""Fetch lightweight recent/contextual info from the web using no-key sources.
Uses DuckDuckGo HTML snippets + Wikipedia summaries as fallback/context.
"""
snippets = []
q = subject.strip()
if not q:
return ""
# DuckDuckGo HTML snippets
try:
url = "https://duckduckgo.com/html/?" + urllib.parse.urlencode({"q": q})
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
html = urllib.request.urlopen(req, timeout=12).read().decode("utf-8", errors="ignore")
# Extract result title/snippet pairs (rough but dependency-free)
blocks = re.findall(r'<a rel="nofollow" class="result__a"[^>]*>(.*?)</a>.*?<a class="result__snippet"[^>]*>(.*?)</a>', html, flags=re.S)
for title, snip in blocks[:max_results]:
clean_title = re.sub('<.*?>', '', title).strip()
clean_snip = re.sub('<.*?>', '', snip).strip()
clean_snip = clean_snip.replace('&quot;', '"').replace('&amp;', '&').replace('&#x27;', "'")
if clean_title or clean_snip:
snippets.append(f"- {clean_title}: {clean_snip}")
except Exception:
pass
# Wikipedia summary fallback / enrichment
try:
search_url = "https://en.wikipedia.org/w/api.php?" + urllib.parse.urlencode({
"action": "opensearch", "search": q, "limit": 3, "namespace": 0, "format": "json"
})
req = urllib.request.Request(search_url, headers={"User-Agent": "Mozilla/5.0"})
data = json.loads(urllib.request.urlopen(req, timeout=10).read().decode("utf-8"))
titles = data[1] if len(data) > 1 else []
for title in titles[:3]:
summary_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + urllib.parse.quote(title)
req2 = urllib.request.Request(summary_url, headers={"User-Agent": "Mozilla/5.0"})
summary = json.loads(urllib.request.urlopen(req2, timeout=10).read().decode("utf-8"))
extract = summary.get("extract")
if extract:
snippets.append(f"- Wikipedia — {title}: {extract[:600]}")
except Exception:
pass
if not snippets:
return ""
return "WEB RESEARCH CONTEXT (use for factual accuracy and recent/contextual details):\n" + "\n".join(snippets[:max_results+3])
# ============================================================
# STEP 1: STRATEGIST — Generate design_spec + spec_lock + outline
# ============================================================
def strategist_phase(subject, num_slides, style, language, audience, use_web=False):
"""The Strategist generates the full design specification."""
research_context = web_research(subject) if use_web else ""
prompt = f"""You are the Strategist for PPT Master. Generate a complete design specification for a presentation.
Subject: {subject}
Number of slides: {num_slides}
Style: {style}
Language: {language}
Target audience: {audience}
Canvas: PPT 16:9 (1280x720, viewBox="0 0 1280 720")
{research_context}
Produce a JSON response with this EXACT structure:
{{
"title": "Presentation title",
"spec_lock": {{
"canvas": {{"viewBox": "0 0 1280 720", "format": "PPT 16:9"}},
"colors": {{"bg": "#...", "bg_alt": "#...", "primary": "#...", "accent": "#...", "secondary_accent": "#...", "text": "#...", "text_secondary": "#...", "border": "#..."}},
"typography": {{"title_family": "...", "body_family": "...", "body": 20, "title": 40, "subtitle": 26, "annotation": 14}},
"icons": {{"library": "chunk-filled", "inventory": ["icon1", "icon2", "..."]}},
"page_rhythm": {{"P01": "anchor", "P02": "dense", "...": "..."}}
}},
"slides": [
{{
"number": 1,
"title": "Slide title",
"layout": "cover",
"rhythm": "anchor",
"design_pattern": "cinematic_full_bleed",
"content": ["Point 1", "Point 2", "Point 3"],
"image_prompt": "English cinematic image description, no text",
"image_source": "ai",
"notes": "Speaker notes for this slide (conversational tone)"
}}
]
}}
Style guidelines:
- "Dark Fantasy": dark backgrounds (#0B0F17), gold (#C8A45D), red (#8B1E2D), ice blue (#6FA8B8)
- "Corporate": white, professional blue (#1A56DB), clean
- "Tech / Startup": dark navy (#0F172A), cyan (#06B6D4), purple (#8B5CF6)
- "Nature / Zen": warm white (#FEFDF8), green (#2D5016), amber (#B45309)
- "Académique": cream (#FFFBF5), burgundy (#7C2D12), blue (#1E40AF)
- "Minimaliste": pure white, black (#18181B), red accent (#DC2626)
- "Luxury Editorial": deep charcoal/cream, champagne gold, magazine typography, full-bleed imagery
- "McKinsey Consulting": white/ink blue, precise grids, executive charts, numbered insights
- "Cinematic Documentary": dark cinematic overlays, frame bars, photography-first, caption labels
- "Neo Futuristic": black, electric cyan/magenta, glow grids, sci-fi panels
- "Japanese Minimal Zen": warm paper, ink black, muted green, asymmetry, generous whitespace
- "Swiss Modern": white, red/black, strong grid, huge typography, brutal clarity
- "Vintage Scientific": parchment/cream, sepia, blueprint lines, diagrams, annotations
- "Premium Data Story": dark/white hybrid, hero metrics, dashboards, elegant charts
Rules:
- Content points: max 20 words each, factual and specific
- image_prompt: English, cinematic, under 30 words, NO text in image
- image_source: "ai" for generated, "web" for stock photo search
- design_pattern: choose one of cinematic_full_bleed, editorial_split, consulting_dashboard, hero_metric, timeline_ribbon, comparison_duel, image_mosaic, map_pins, quote_breathing, process_flow, card_grid, blueprint_diagram, luxury_catalog, swiss_poster
- notes: conversational tone, 2-3 sentences, like talking to audience
- icons inventory: pick from chunk-filled library (crown, shield, sword, fire, users, chart-bar, lightbulb, target, bolt, map, castle, skull, book-open, globe, rocket, heart, star, trophy, flag, clock)
- First slide layout="cover", last="closing", others mix of "content"/"comparison"/"timeline"/"quote"
- page_rhythm: "anchor" for cover/closing, "dense" for data-heavy, "breathing" for impact pages
- Reply ONLY with raw JSON, no markdown code blocks, no explanation"""
result = llm_chat(prompt, max_tokens=32000, model_override=MODEL_STRATEGIST)
# Parse JSON
try:
json_match = re.search(r'\{[\s\S]*\}', result)
if json_match:
data = json.loads(json_match.group())
else:
data = json.loads(result)
except json.JSONDecodeError:
# Try repair
for suffix in ['}]}', '"}]}', '"]}]}']:
try:
repaired = result.rstrip() + suffix
json_match = re.search(r'\{[\s\S]*\}', repaired)
if json_match:
data = json.loads(json_match.group())
break
except:
continue
else:
raise RuntimeError(f"JSON invalide du Strategist.\n\nRéponse:\n{result[:3000]}")
return data
def format_strategist_preview(data):
"""Format strategist output as readable markdown."""
lines = [f"# {data.get('title', 'Présentation')}\n"]
spec = data.get("spec_lock", {})
colors = spec.get("colors", {})
typo = spec.get("typography", {})
lines.append("## 🎨 Design Spec\n")
lines.append(f"**Palette**: {' | '.join(f'{k}: `{v}`' for k,v in colors.items())}\n")
lines.append(f"**Typo**: titre={typo.get('title_family','?')}, corps={typo.get('body_family','?')}, taille={typo.get('body',20)}px\n")
lines.append(f"**Icônes**: {', '.join(spec.get('icons',{}).get('inventory',[]))}\n")
lines.append("\n## 📋 Plan des slides\n")
for slide in data.get("slides", []):
lines.append(f"### Slide {slide['number']}: {slide['title']}")
lines.append(f"*Layout: {slide.get('layout','content')} | Rythme: {slide.get('rhythm','dense')} | Pattern: {slide.get('design_pattern','auto')}*\n")
for p in slide.get("content", []):
lines.append(f"- {p}")
if slide.get("image_prompt"):
lines.append(f"\n🖼️ Image ({slide.get('image_source','ai')}): *{slide['image_prompt']}*")
if slide.get("notes"):
lines.append(f"\n🎙️ Notes: *{slide['notes'][:100]}...*")
lines.append("")
return "\n".join(lines)
def write_project_specs(data, project_path):
"""Write design_spec.md and spec_lock.md like original PPT Master so quality checker can enforce drift."""
project = Path(project_path)
spec = data.get("spec_lock", {})
colors = spec.get("colors", {})
typo = spec.get("typography", {})
icons = spec.get("icons", {})
rhythms = spec.get("page_rhythm", {})
design_lines = [f"# {data.get('title','Presentation')} - Design Spec", "", "## I. Project Information", "", f"- Canvas Format: PPT 16:9 (1280×720)", f"- Page Count: {len(data.get('slides', []))}", "- Design Style: AI-generated via PPT Master full workflow", "", "## III. Visual Theme", ""]
for k,v in colors.items():
design_lines.append(f"- {k}: `{v}`")
design_lines += ["", "## IV. Typography", ""]
for k,v in typo.items():
design_lines.append(f"- {k}: {v}")
design_lines += ["", "## IX. Content Outline", ""]
for sl in data.get('slides', []):
design_lines.append(f"### Slide {sl.get('number'):02d} - {sl.get('title')}")
for pt in sl.get('content', []):
design_lines.append(f"- {pt}")
design_lines.append("")
(project / "design_spec.md").write_text("\n".join(design_lines), encoding="utf-8")
lock = ["# Execution Lock", "", "## canvas", "- viewBox: 0 0 1280 720", "- format: PPT 16:9", "", "## colors"]
for k,v in colors.items():
lock.append(f"- {k}: {v}")
# Add common colors used by gradients/overlays if not present
for k,v in {"black":"#000000", "white":"#FFFFFF"}.items():
if k not in colors:
lock.append(f"- {k}: {v}")
lock += ["", "## typography"]
if "font_family" not in typo:
lock.append(f"- font_family: {typo.get('body_family','Arial, sans-serif')}")
for k,v in typo.items():
lock.append(f"- {k}: {v}")
lock += ["", "## icons", f"- library: {icons.get('library','chunk-filled')}", f"- inventory: {', '.join(icons.get('inventory', []))}", "", "## images"]
for sl in data.get('slides', []):
n = int(sl.get('number', 0))
lock.append(f"- slide_{n:02d}: images/slide_{n:02d}.png")
lock.append(f"- slide_{n:02d}_jpg: images/slide_{n:02d}.jpg")
lock += ["", "## page_rhythm"]
for sl in data.get('slides', []):
key=f"P{int(sl.get('number',0)):02d}"
lock.append(f"- {key}: {sl.get('rhythm') or rhythms.get(key,'dense')}")
lock += ["", "## forbidden", "- Mixing icon libraries", "- rgba()", "- <style>, class, <foreignObject>, textPath, @font-face, <animate*>, <script>, <iframe>, <symbol>+<use>", "- <g opacity>", "- HTML named entities"]
(project / "spec_lock.md").write_text("\n".join(lock), encoding="utf-8")
def check_and_repair_svg(project_path, svg_path, slide, spec_summary, progress_cb=None):
"""Run svg_quality_checker and repair with LLM if errors are found."""
try:
result = subprocess.run([sys.executable, str(SCRIPTS_DIR / "svg_quality_checker.py"), project_path], capture_output=True, text=True, timeout=120, cwd=str(SCRIPTS_DIR))
out = result.stdout + result.stderr
# If this specific file has errors, repair once
if "[ERROR]" in out and Path(svg_path).name in out:
if progress_cb:
progress_cb(f" 🔧 Réparation qualité: {Path(svg_path).name}")
svg = Path(svg_path).read_text(encoding="utf-8")
fixed = _repair_svg_with_llm(svg, out, slide, spec_summary)
Path(svg_path).write_text(fixed, encoding="utf-8")
# second check, no infinite loop
return True
except Exception as e:
if progress_cb:
progress_cb(f" ⚠️ Quality check skipped: {str(e)[:50]}")
return False
# ============================================================
# STEP 2: IMAGE ACQUISITION
# ============================================================
def acquire_images(data, project_path, image_mode, progress_cb=None):
"""Generate/search images for each slide."""
images_dir = Path(project_path) / "images"
images_dir.mkdir(parents=True, exist_ok=True)
slides = data.get("slides", [])
for i, slide in enumerate(slides):
prompt = slide.get("image_prompt", "")
if not prompt:
continue
source = slide.get("image_source", "ai")
filename = f"slide_{slide['number']:02d}"
if progress_cb:
progress_cb(f"🖼️ [{i+1}/{len(slides)}] {prompt[:50]}...")
if image_mode == "Aucune image":
continue
use_comfyui = (image_mode == "ComfyUI (local GPU)") or \
(image_mode == "Les deux (ComfyUI + web)" and source == "ai")
use_web = (image_mode == "Recherche web (Wikimedia)") or \
(image_mode == "Les deux (ComfyUI + web)" and source == "web")
if use_comfyui:
try:
subprocess.run(
[sys.executable, str(SCRIPTS_DIR / "image_gen.py"),
prompt, "--backend", "comfyui",
"--aspect_ratio", "16:9", "--image_size", "1K",
"-o", str(images_dir), "--filename", filename],
capture_output=True, text=True, timeout=180, cwd=str(SCRIPTS_DIR))
except Exception as e:
if progress_cb:
progress_cb(f" ⚠️ ComfyUI failed: {str(e)[:60]}")
elif use_web:
try:
subprocess.run(
[sys.executable, str(SCRIPTS_DIR / "image_search.py"),
prompt, "--filename", f"{filename}.jpg",
"--orientation", "landscape", "-o", str(images_dir)],
capture_output=True, text=True, timeout=60, cwd=str(SCRIPTS_DIR))
except Exception as e:
if progress_cb:
progress_cb(f" ⚠️ Web search failed: {str(e)[:60]}")
# ============================================================
# PREMIUM DESIGN SYSTEM — distilled from original PPT Master examples
# ============================================================
PREMIUM_EXEMPLAR_COVER = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
<defs>
<linearGradient id="coverOverlay" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#0A0A0A" stop-opacity="0.25"/>
<stop offset="40%" stop-color="#0A0A0A" stop-opacity="0.45"/>
<stop offset="75%" stop-color="#0A0A0A" stop-opacity="0.82"/>
<stop offset="100%" stop-color="#0A0A0A" stop-opacity="0.95"/>
</linearGradient>
<linearGradient id="goldLine" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#C9A96E" stop-opacity="0"/>
<stop offset="20%" stop-color="#C9A96E" stop-opacity="1"/>
<stop offset="80%" stop-color="#E8D5B5" stop-opacity="1"/>
<stop offset="100%" stop-color="#E8D5B5" stop-opacity="0"/>
</linearGradient>
</defs>
<image href="../images/slide_01.png" x="0" y="0" width="1280" height="720" preserveAspectRatio="xMidYMid slice"/>
<rect width="1280" height="720" fill="url(#coverOverlay)"/>
<text x="50" y="35" font-family="Georgia, serif" font-size="11" fill="#C9A96E" fill-opacity="0.7" letter-spacing="3">SECTION LABEL</text>
<rect x="440" y="500" width="400" height="1.5" fill="url(#goldLine)"/>
</svg>"""
PREMIUM_EXEMPLAR_CONTENT = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720" width="1280" height="720">
<defs>
<radialGradient id="glow" cx="50%" cy="35%" r="50%">
<stop offset="0%" stop-color="#D4A574" stop-opacity="0.06"/>
<stop offset="100%" stop-color="#D4A574" stop-opacity="0"/>
</radialGradient>
<filter id="statGlow" x="-30%" y="-30%" width="160%" height="160%">
<feGaussianBlur in="SourceAlpha" stdDeviation="6" result="blur"/>
<feFlood flood-color="#D4A574" flood-opacity="0.4" result="glowColor"/>
<feComposite in="glowColor" in2="blur" operator="in" result="glow"/>
<feMerge><feMergeNode in="glow"/><feMergeNode in="SourceGraphic"/></feMerge>
</filter>
</defs>
<rect width="1280" height="720" fill="#0D1117"/>
<rect width="1280" height="720" fill="url(#glow)"/>
<g id="header"><rect x="60" y="50" width="4" height="30" fill="#D4A574"/><text x="76" y="75" font-size="14" fill="#8B949E" letter-spacing="3">THE PROBLEM</text></g>
<g id="hero-stat"><text x="640" y="260" text-anchor="middle" font-size="120" font-weight="bold" fill="#D4A574" filter="url(#statGlow)">93%</text></g>
<rect x="180" y="580" width="920" height="60" rx="8" fill="#161B22" stroke="#30363D" stroke-width="1"/>
</svg>"""
def _extract_svg(text: str) -> str:
"""Extract clean SVG code from an LLM response."""
if not text:
raise RuntimeError("Empty SVG response")
text = text.replace('```svg', '').replace('```xml', '').replace('```', '').strip()
start = text.find('<svg')
end = text.rfind('</svg>')
if start >= 0 and end > start:
return text[start:end+6]
if start >= 0:
return text[start:] + '\n</svg>'
raise RuntimeError("No <svg> found")
def _design_critique_and_improve(svg: str, slide: dict, spec_summary: str) -> str:
"""Second-pass design critic: ask a different model to improve visual quality while preserving validity."""
prompt = f"""You are a senior presentation art director and SVG engineer. Improve this SVG slide to look more premium and closer to high-end PPT Master examples.
Slide title: {slide.get('title')}
Spec: {spec_summary}
Improve ONLY if useful:
- stronger hierarchy, better spacing, more premium gradients/overlays
- better image/text composition
- add subtle glow/filter/letter-spacing/accent lines/cards if missing
- keep all existing content and image hrefs
- keep SVG valid and PPT-safe
Hard constraints:
- NO <style>, class, foreignObject, mask, animate, script, rgba(), @font-face
- keep viewBox 0 0 1280 720
- return ONLY final SVG code
SVG to improve:
{svg}
"""
try:
improved = llm_chat(prompt, max_tokens=12000, temperature=0.25, model_override=MODEL_CRITIC)
improved = _extract_svg(improved)
# Basic guard: only accept if still substantial and has svg end
if len(improved) > max(800, int(len(svg) * 0.6)) and '</svg>' in improved:
return improved
except Exception:
return svg
return svg
def _repair_svg_with_llm(svg: str, checker_output: str, slide: dict, spec_summary: str) -> str:
"""Ask executor model to repair SVG according to quality checker output."""
prompt = f"""Repair this SVG so it passes PPT Master svg_quality_checker.py.
Slide: {slide.get('title')}
Spec: {spec_summary}
Checker output/errors:
{checker_output[:3000]}
Hard constraints:
- Preserve design and all content
- NO <style>, class, foreignObject, mask, animate, script, rgba(), @font-face
- inline attributes only
- valid XML
- return ONLY SVG
SVG:
{svg}
"""
fixed = llm_chat(prompt, max_tokens=12000, temperature=0.2, model_override=MODEL_EXECUTOR)
return _extract_svg(fixed)
# ============================================================
# VISION QUALITY GATE — verify image relevance
# ============================================================
GROQ_API_KEY_DEFAULT = "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"
GROQ_VISION_MODEL = "meta-llama/llama-4-scout-17b-16e-instruct"
def _find_slide_image(images_dir: Path, slide_number: int):
name = f"slide_{slide_number:02d}"
for ext in ('.png', '.jpg', '.jpeg', '.webp'):
p = images_dir / f"{name}{ext}"
if p.exists():
return p
return None
def vision_score_image(image_path: Path, expected_prompt: str, slide_title: str, slide_content: list):
"""Use Groq Llama-4-Scout vision to score whether image matches the slide needs.
Returns dict: {score:int, verdict:str, issues:list, suggestion:str}
"""
try:
import requests
api_key = os.environ.get("GROQ_API_KEY", GROQ_API_KEY_DEFAULT)
mime = mimetypes.guess_type(str(image_path))[0] or "image/png"
b64 = base64.b64encode(image_path.read_bytes()).decode('utf-8')
text = f"""Evaluate if this image matches a PowerPoint slide.
Slide title: {slide_title}
Slide content: {slide_content}
Expected image prompt: {expected_prompt}
Return ONLY JSON:
{{"score":0-10,"verdict":"good|acceptable|bad","issues":["..."],"suggestion":"better image prompt if bad"}}
Criteria: relevance to subject, visual quality, no unwanted text/watermark, fits professional presentation."""
payload = {
"model": GROQ_VISION_MODEL,
"messages": [{"role": "user", "content": [
{"type": "text", "text": text},
{"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}}
]}],
"temperature": 0.1,
"max_tokens": 800,
}
r = requests.post("https://api.groq.com/openai/v1/chat/completions",
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
json=payload, timeout=60)
if r.status_code >= 400:
return {"score": 0, "verdict": "error", "issues": [r.text[:200]], "suggestion": expected_prompt}
content = r.json().get("choices", [{}])[0].get("message", {}).get("content", "")
m = re.search(r'\{[\s\S]*\}', content)
if m:
return json.loads(m.group())
return {"score": 5, "verdict": "acceptable", "issues": ["No JSON from vision model"], "suggestion": expected_prompt}
except Exception as e:
return {"score": 5, "verdict": "unknown", "issues": [str(e)[:200]], "suggestion": expected_prompt}
def verify_images_with_vision(data, project_path, image_mode, progress_cb=None, min_score=6):
"""Analyze generated/web images. If clearly bad and ComfyUI is available, regenerate once with improved prompt."""
images_dir = Path(project_path) / "images"
for slide in data.get("slides", []):
img = _find_slide_image(images_dir, int(slide.get("number", 0)))
if not img:
continue
if progress_cb:
progress_cb(f"👁️ Vision check slide {slide.get('number')}: {img.name}")
result = vision_score_image(img, slide.get("image_prompt", ""), slide.get("title", ""), slide.get("content", []))
score = int(result.get("score", 5) or 5)
verdict = result.get("verdict", "?")
if progress_cb:
progress_cb(f" score={score}/10 verdict={verdict}")
if score < min_score and image_mode in ("ComfyUI (local GPU)", "Les deux (ComfyUI + web)"):
suggestion = result.get("suggestion") or slide.get("image_prompt", "")
improved_prompt = suggestion + ", professional presentation image, cinematic, no text, no watermark, high quality"
if progress_cb:
progress_cb(f" 🔁 Regeneration image avec prompt amélioré")
try:
subprocess.run([sys.executable, str(SCRIPTS_DIR / "image_gen.py"), improved_prompt,
"--backend", "comfyui", "--aspect_ratio", "16:9", "--image_size", "1K",
"-o", str(images_dir), "--filename", f"slide_{int(slide.get('number')):02d}"],
capture_output=True, text=True, timeout=180, cwd=str(SCRIPTS_DIR))
except Exception as e:
if progress_cb:
progress_cb(f" ⚠️ regeneration failed: {str(e)[:80]}")
# ============================================================
# STEP 3: EXECUTOR — LLM generates each SVG sequentially
# ============================================================
def executor_phase(data, project_path, style, progress_cb=None):
"""Generate SVG slides sequentially using the LLM as Executor."""
svg_dir = Path(project_path) / "svg_output"
svg_dir.mkdir(parents=True, exist_ok=True)
images_dir = Path(project_path) / "images"
notes_dir = Path(project_path) / "notes"
notes_dir.mkdir(parents=True, exist_ok=True)
spec_lock = data.get("spec_lock", {})
colors = spec_lock.get("colors", {})
typo = spec_lock.get("typography", {})
icons = spec_lock.get("icons", {})
slides = data.get("slides", [])
num_total = len(slides)
# Build color string for the prompt
color_str = ", ".join(f"{k}: {v}" for k, v in colors.items())
font_title = typo.get("title_family", "Georgia, Times New Roman, serif")
font_body = typo.get("body_family", "Arial, sans-serif")
icon_lib = icons.get("library", "chunk-filled")
icon_inv = ", ".join(icons.get("inventory", []))
# Shared executor instructions — based on real PPT Master high-quality examples
executor_rules = f"""SVG TECHNICAL RULES (MANDATORY — violation = broken export):
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720" width="1280" height="720">
- Colors ONLY from spec_lock: {color_str}
- Title font: {font_title}. Body font: {font_body}
- Body size: {typo.get('body',20)}px, Title: {typo.get('title',40)}px, Subtitle: {typo.get('subtitle',26)}px, Annotation: {typo.get('annotation',14)}px
- Icons: <use data-icon="{icon_lib}/ICON_NAME" x="" y="" width="40" height="40" fill="COLOR"/>
- Available icons: {icon_inv}
- FORBIDDEN: <style>, class, foreignObject, animate, script, mask, @font-face, rgba(), <g opacity="">
- Use fill-opacity/stop-opacity instead of rgba. Use inline attributes only.
- Images: <image href="../images/FILENAME" preserveAspectRatio="xMidYMid slice"/>
VISUAL QUALITY RULES (for premium output):
- Use <defs> with linearGradient (3-4 stops with varying stop-opacity) for rich overlays
- Use radialGradient for subtle background glows (stop-opacity="0.06" to "0")
- Use <filter> for glow effects: feGaussianBlur + feFlood + feComposite + feMerge
- Use letter-spacing="3" on category labels / section headers for editorial feel
- Use vertical accent bars: <rect x="" y="" width="4" height="30" fill="PRIMARY"/>
- Use thin separators: <rect width="200" height="1" fill="BORDER"/> between sections
- Hierarchy: hero numbers at 80-120px bold, then 24px subtitle, then 16-18px body
- Cards: rounded rects (rx="12") with subtle stroke, padding 20-30px inside
- Top-level <g id="..."> grouping for each logical section (header, content, footer)
- Page number: bottom-right, annotation size, muted color
- Add decorative circles/dots at low opacity (0.06-0.15) for visual texture
- Text must be readable: ensure contrast between text color and background
- For breathing pages: big whitespace, one dominant element, dramatic
DESIGN PATTERN LIBRARY (pick/adapt according to slide.design_pattern):
- cinematic_full_bleed: image full canvas + multi-stop dark overlay + title near bottom third + hairline accents
- editorial_split: 55/45 asymmetry, image crop on one side, text column with small caps label
- consulting_dashboard: KPI cards, microcharts, numbered insights, strict 12-column grid
- hero_metric: one huge number/word (90-140px) with glow + two supporting facts
- timeline_ribbon: horizontal or vertical progression with nodes, date tags, connector line
- comparison_duel: two opposing panels separated by thin divider, mirrored structure
- image_mosaic: 3-5 image tiles with consistent gutters + captions, magazine layout
- map_pins: map/image background with pins, labels, legend panel
- quote_breathing: huge quote, single image/texture, extreme whitespace
- process_flow: chevrons/arrows/steps with numbered circles, clear directionality
- card_grid: 3/4/6 cards with icons, accent bars, equal spacing
- blueprint_diagram: thin strokes, dashed lines, labels, technical schematic feel
- luxury_catalog: product/image hero, serif typography, gold dividers, editorial footer
- swiss_poster: huge typography, strict grid, red/black/white, minimal but striking"""
total_notes = []
for slide in slides:
num = slide["number"]
name = f"slide_{num:02d}"
if progress_cb:
progress_cb(f"🎨 SVG {num}/{num_total}: {slide['title'][:40]}...")
# Find image
img_ref = ""
for ext in ('.png', '.jpg', '.jpeg', '.webp'):
if (images_dir / f"{name}{ext}").exists():
img_ref = f'Image available: "../images/{name}{ext}"'
break
content_str = "\n".join(f" - {p}" for p in slide.get("content", []))
rhythm = slide.get("rhythm", "dense")
prompt = f"""Generate a premium-quality SVG slide. This must look like a professionally designed presentation.
SLIDE {num}/{num_total}:
- Title: {slide['title']}
- Layout: {slide.get('layout','content')}
- Rhythm: {rhythm} ({'dramatic full-bleed, big whitespace, one dominant element, cinematic' if rhythm == 'breathing' else 'information-rich, structured cards/lists, clear visual hierarchy' if rhythm == 'dense' else 'structural, impactful, decorative'})
- Content:
{content_str}
- {img_ref or 'No image — use gradients, shapes, and strong typography as visual interest'}
{executor_rules}
DESIGN THIS SLIDE:
{"COVER PAGE: dramatic, large title (60-80px), cinematic image as background with multi-stop gradient overlay, accent line, subtitle below. Make it impactful and memorable." if slide.get('layout') == 'cover' else ""}
{"CLOSING PAGE: centered composition, large title, accent divider, final message. Elegant and memorable." if slide.get('layout') == 'closing' else ""}
{"TIMELINE: horizontal line with circular nodes, dates/phases below, title at top. Clean and structured." if slide.get('layout') == 'timeline' else ""}
{"COMPARISON: two-column layout with visual separator, contrasting elements side by side." if slide.get('layout') == 'comparison' else ""}
{"CONTENT PAGE: asymmetric layout (image right/left, text opposite). Use accent bar before title. Bullet points with colored circles. Cards with rx=12 for grouped info." if slide.get('layout') == 'content' else ""}
{"Use the image as background with dark gradient overlay (3-4 stops, progressive opacity)" if img_ref and rhythm == 'breathing' else f"Place image on one side (540px wide), text content on the other side" if img_ref else ""}
Reply with ONLY the SVG. Start <svg, end </svg>. No explanation."""
try:
svg_content = llm_chat(prompt, max_tokens=10000, temperature=0.3, model_override=MODEL_EXECUTOR)
svg_content = _extract_svg(svg_content)
# Art Director second pass: improve composition/visual polish (slow but high quality)
spec_summary = f"colors={color_str}; fonts title={font_title}, body={font_body}; icons={icon_lib}: {icon_inv}"
if progress_cb:
progress_cb(f" 🎭 Art Director polish {num}/{num_total}...")
svg_content = _design_critique_and_improve(svg_content, slide, spec_summary)
svg_path = svg_dir / f"{name}.svg"
svg_path.write_text(svg_content, encoding="utf-8")
# Quality gate repair, one pass
check_and_repair_svg(project_path, svg_path, slide, spec_summary, progress_cb=progress_cb)
except Exception as e:
if progress_cb:
progress_cb(f" ⚠️ Slide {num} failed ({str(e)[:50]}), using fallback")
_write_fallback_svg(svg_dir, name, slide, colors, font_title, font_body, num, num_total, img_ref)
# Write notes
note = slide.get("notes", f"{slide['title']}. " + " ".join(slide.get("content", [])))
(notes_dir / f"{name}.md").write_text(note, encoding="utf-8")
total_notes.append(f"# {name}\n\n{note}")
# Write total.md
(notes_dir / "total.md").write_text("\n\n---\n\n".join(total_notes), encoding="utf-8")
def _write_fallback_svg(svg_dir, name, slide, colors, font_title, font_body, num, total, img_ref):
"""Minimal fallback SVG."""
bg = colors.get("bg", "#0B0F17")
primary = colors.get("primary", "#C8A45D")
text = colors.get("text", "#E8E2D6")
muted = colors.get("text_secondary", "#AAB2C0")
title = slide["title"].replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')
content = slide.get("content", [])
lines = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720" width="1280" height="720">',
f' <rect width="1280" height="720" fill="{bg}"/>']
if img_ref:
href = img_ref.split('"')[1] if '"' in img_ref else ""
if href:
lines.append(f' <image href="{href}" x="680" y="60" width="540" height="600" preserveAspectRatio="xMidYMid slice"/>')
lines.append(f' <text x="60" y="90" font-family="{font_title}" font-size="36" font-weight="bold" fill="{text}">{title}</text>')
lines.append(f' <rect x="60" y="108" width="160" height="4" fill="{primary}"/>')
for j, p in enumerate(content[:6]):
y = 170 + j * 75
p_esc = p.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')[:100]
lines.append(f' <text x="80" y="{y}" font-family="{font_body}" font-size="20" fill="{text}">{p_esc}</text>')
lines.append(f' <text x="1224" y="700" text-anchor="end" font-family="{font_body}" font-size="12" fill="{muted}">{num}/{total}</text>')
lines.append('</svg>')
(svg_dir / f"{name}.svg").write_text("\n".join(lines), encoding="utf-8")
# ============================================================
# STEP 4: POST-PROCESSING & EXPORT
# ============================================================
def sanitize_svgs_for_export(project_path):
"""Final safety pass before svg_to_pptx.
Removes/normalizes SVG constructs that sometimes pass the checker but break the converter.
"""
svg_dir = Path(project_path) / "svg_output"
for svg_file in svg_dir.glob("*.svg"):
txt = svg_file.read_text(encoding="utf-8", errors="ignore")
# Remove SVG filters if converter chokes on them; visual loss is minor vs export failure
txt = re.sub(r'<filter[\s\S]*?</filter>', '', txt)
txt = re.sub(r'\sfilter="url\([^\"]+\)"', '', txt)
# Replace auto dimensions in images (invalid for DrawingML conversion)
txt = re.sub(r'height="auto"', 'height="400"', txt)
txt = re.sub(r'width="auto"', 'width="400"', txt)
# Remove CSS-ish attributes that are not essential and can upset conversion
txt = re.sub(r'\sletter-spacing="[^"]*"', '', txt)
# Remove comments
txt = re.sub(r'<!--[\s\S]*?-->', '', txt)
# Ensure XML ampersands are escaped when not entities
txt = re.sub(r'&(?!amp;|lt;|gt;|quot;|apos;|#\d+;|#x[0-9A-Fa-f]+;)', '&amp;', txt)
svg_file.write_text(txt, encoding="utf-8")
def postprocess_and_export(project_path):
"""Run quality check + finalize_svg + svg_to_pptx."""
env = os.environ.copy()
outputs = []
sanitize_svgs_for_export(project_path)
outputs.append("[SANITIZE] SVG safety pass completed before export\n")
# final quality check before finalize (original PPT Master gate)
qc = subprocess.run([sys.executable, str(SCRIPTS_DIR / "svg_quality_checker.py"), project_path],
capture_output=True, text=True, timeout=120, cwd=str(SCRIPTS_DIR), env=env)
outputs.append(qc.stdout + qc.stderr)
# total_md_split
tms = subprocess.run([sys.executable, str(SCRIPTS_DIR / "total_md_split.py"), project_path],
capture_output=True, text=True, timeout=60, cwd=str(SCRIPTS_DIR), env=env)
outputs.append(tms.stdout + tms.stderr)
# finalize_svg
fin = subprocess.run([sys.executable, str(SCRIPTS_DIR / "finalize_svg.py"), project_path],
capture_output=True, text=True, timeout=120, cwd=str(SCRIPTS_DIR), env=env)
outputs.append(fin.stdout + fin.stderr)
# svg_to_pptx
result = subprocess.run([sys.executable, str(SCRIPTS_DIR / "svg_to_pptx.py"), project_path],
capture_output=True, text=True, timeout=180, cwd=str(SCRIPTS_DIR), env=env)
outputs.append(result.stdout + result.stderr)
return "\n".join(outputs)
# ============================================================
# GRADIO HANDLERS
# ============================================================
def step1_handler(subject, num_slides, style, language, audience, image_mode, use_web):
"""Strategist phase."""
if not subject.strip():
return "❌ Entre un sujet !", "", "{}"
try:
data = strategist_phase(subject, int(num_slides), style, language, audience, use_web=use_web)
preview = format_strategist_preview(data)
return f"✅ Design spec généré — {len(data.get('slides',[]))} slides", preview, json.dumps(data, ensure_ascii=False, indent=2)
except Exception as e:
return f"❌ Erreur Strategist: {str(e)[:300]}", "", "{}"
def step2_handler(data_json, style, image_mode, verify_vision=True, progress=gr.Progress()):
"""Full generation pipeline."""
if not data_json or data_json == "{}":
return "❌ Génère d'abord le plan (étape 1)", None, ""
try:
data = json.loads(data_json)
except:
return "❌ Données invalides", None, ""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
project_name = f"gradio_{timestamp}"
project_path = str(PROJECTS_DIR / project_name)
os.makedirs(project_path, exist_ok=True)
for d in ("svg_output", "svg_final", "images", "notes", "exports"):
os.makedirs(f"{project_path}/{d}", exist_ok=True)
num_slides = len(data.get("slides", []))
log = [f"📁 Projet: {project_name}", f"📊 {num_slides} slides à générer\n"]
# Write design_spec.md and spec_lock.md like the original PPT Master workflow
write_project_specs(data, project_path)
log.append("🧭 design_spec.md + spec_lock.md écrits\n")
# Phase 1: Images
progress(0.05, desc="Acquisition des images...")
log.append("━━━ PHASE 1: Images ━━━")
def img_cb(msg): log.append(f" {msg}")
acquire_images(data, project_path, image_mode, progress_cb=img_cb)
log.append(" ✅ Images acquises")
if verify_vision and image_mode != "Aucune image":
log.append(" 👁️ Vérification vision des images...")
verify_images_with_vision(data, project_path, image_mode, progress_cb=img_cb)
log.append(" ✅ Vérification vision terminée")
log.append("")
# Phase 2: Executor (SVG generation via LLM)
progress(0.2, desc=f"Génération SVG par LLM (0/{num_slides})...")
log.append("━━━ PHASE 2: Executor (SVG via GPT-OSS-120B) ━━━")
log.append(f" ⏱️ Estimation: ~30-45s par slide, {num_slides} slides\n")
slide_count = [0]
def svg_cb(msg):
log.append(f" {msg}")
slide_count[0] += 1
frac = 0.2 + 0.6 * (slide_count[0] / (num_slides * 2))
progress(min(frac, 0.8), desc=f"SVG {slide_count[0]//2}/{num_slides}...")
executor_phase(data, project_path, style, progress_cb=svg_cb)
log.append(" ✅ Tous les SVG générés\n")
# Phase 3: Post-processing
progress(0.85, desc="Export PPTX...")
log.append("━━━ PHASE 3: Post-traitement & Export ━━━")
pp_out = postprocess_and_export(project_path)
log.append(pp_out[-6000:])
# Find PPTX
pptx_files = glob.glob(f"{project_path}/exports/*.pptx")
if pptx_files:
pptx_path = pptx_files[0]
size_mb = Path(pptx_path).stat().st_size / 1024 / 1024
progress(1.0, desc="Terminé !")
log.append(f"\n✅ PPTX: {Path(pptx_path).name} ({size_mb:.1f} MB)")
return "✅ Présentation générée !", pptx_path, "\n".join(log)
else:
return "❌ Export échoué", None, "\n".join(log)
def refresh_preview_from_json(data_json):
"""Refresh markdown preview from edited JSON."""
try:
data = json.loads(data_json)
return "✅ Aperçu mis à jour", format_strategist_preview(data), json.dumps(data, ensure_ascii=False, indent=2)
except Exception as e:
return f"❌ JSON invalide: {str(e)[:200]}", "", data_json
# ============================================================
# GRADIO UI
# ============================================================
STYLES = [
"Dark Fantasy", "Corporate", "Tech / Startup", "Nature / Zen", "Académique", "Minimaliste",
"Luxury Editorial", "McKinsey Consulting", "Cinematic Documentary", "Neo Futuristic",
"Japanese Minimal Zen", "Swiss Modern", "Vintage Scientific", "Premium Data Story"
]
LANGUAGES = ["Français", "English", "Español", "Deutsch", "中文", "日本語"]
IMAGE_MODES = ["ComfyUI (local GPU)", "Recherche web (Wikimedia)", "Les deux (ComfyUI + web)", "Aucune image"]
with gr.Blocks(title="PPT Master — Générateur IA") as app:
outline_state = gr.State("{}")
gr.Markdown("# 🎯 PPT Master — Générateur de Présentations IA")
gr.Markdown("*Workflow complet: Strategist → Images → Executor SVG → PPTX natif*")
with gr.Tabs():
with gr.Tab("1️⃣ Sujet & Design"):
with gr.Row():
with gr.Column(scale=2):
subject = gr.Textbox(label="📌 Sujet", placeholder="Ex: Game of Thrones, L'IA en 2025...", lines=2)
with gr.Row():
num_slides = gr.Slider(5, 20, value=10, step=1, label="📄 Slides")
language = gr.Dropdown(LANGUAGES, value="Français", label="🌐 Langue")
with gr.Column(scale=1):
style = gr.Dropdown(STYLES, value="Dark Fantasy", label="🎨 Style")
audience = gr.Textbox(label="👥 Public", value="Grand public", placeholder="Ex: professionnels, étudiants...")
image_mode = gr.Dropdown(IMAGE_MODES, value="ComfyUI (local GPU)", label="🖼️ Images")
use_web = gr.Checkbox(label="🌐 Recherche web pour données récentes", value=True)
verify_vision = gr.Checkbox(label="👁️ Vérifier les images avec Llama-4-Scout Vision", value=True)
btn_plan = gr.Button("🧠 Générer le design spec (Strategist)", variant="primary", size="lg")
status1 = gr.Textbox(label="Statut", interactive=False)
gr.Markdown("### 📋 Design Spec & Plan")
preview = gr.Markdown(value="*Le design spec apparaîtra ici...*")
gr.Markdown("### ✏️ Modifier la trame avant génération")
gr.Markdown("Tu peux modifier le JSON ci-dessous : titres, contenu, prompts images, layout, notes, couleurs, etc. Puis clique sur **Mettre à jour l’aperçu** avant génération.")
outline_editor = gr.Textbox(label="JSON éditable du plan/spec", lines=18, interactive=True)
btn_refresh = gr.Button("🔄 Mettre à jour l’aperçu depuis mes modifications", variant="secondary")
with gr.Tab("2️⃣ Générer le PPTX"):
gr.Markdown("### 🚀 Pipeline complet: Images + SVG (LLM) + Export")
gr.Markdown("⏱️ **Temps estimé Ultra**: ~2 min (images) + ~5-8 min (SVG GPT-OSS) + ~8-12 min (Art Director HY3) + export. Qualité maximale.")
btn_gen = gr.Button("⚡ Lancer la génération complète", variant="primary", size="lg")
status2 = gr.Textbox(label="Statut", interactive=False)
with gr.Row():
log_box = gr.Textbox(label="📜 Log", lines=20, interactive=False)
pptx_out = gr.File(label="📥 Télécharger PPTX")
with gr.Tab("ℹ️ À propos"):
gr.Markdown("""
## Workflow PPT Master complet
1. **Strategist** (HY3-preview) → design_spec + spec_lock (palette, typo, icônes, rythme)
2. **Image Acquisition** → ComfyUI GPU ou recherche web
3. **Executor** (GPT-OSS-120B) → Génère chaque SVG individuellement, qualité premium
4. **Post-processing** → finalize_svg.py (icônes, images, rounded rects)
5. **Export** → svg_to_pptx.py → PPTX natif éditable
**Approche multi-modèles**: HY3 pour la planification (raisonnement), GPT-OSS-120B pour le code SVG (rapide + précis).
Le spec_lock garantit la cohérence couleurs/fonts sur l'ensemble du deck.
**Stack**: OpenRouter (2 modèles gratuits) + ComfyUI local (RTX 5070 Ti)
""")
btn_plan.click(fn=step1_handler, inputs=[subject, num_slides, style, language, audience, image_mode, use_web],
outputs=[status1, preview, outline_editor])
btn_refresh.click(fn=refresh_preview_from_json, inputs=[outline_editor], outputs=[status1, preview, outline_editor])
btn_gen.click(fn=step2_handler, inputs=[outline_editor, style, image_mode, verify_vision],
outputs=[status2, pptx_out, log_box])
if __name__ == "__main__":
app.launch(server_name="127.0.0.1", server_port=7860, share=False, inbrowser=True)