V5: Full PPT Master workflow — Strategist + spec_lock + Executor LLM SVG + finalize + export
Browse files- interface/app_gradio.py +322 -360
interface/app_gradio.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
PPT Master — Interface Gradio
|
| 4 |
-
|
| 5 |
"""
|
| 6 |
|
| 7 |
import gradio as gr
|
|
@@ -21,377 +21,390 @@ SCRIPT_DIR = Path(__file__).resolve().parent
|
|
| 21 |
SKILL_DIR = SCRIPT_DIR / "skills" / "ppt-master"
|
| 22 |
SCRIPTS_DIR = SKILL_DIR / "scripts"
|
| 23 |
PROJECTS_DIR = SCRIPT_DIR / "projects"
|
|
|
|
| 24 |
|
| 25 |
sys.path.insert(0, str(SCRIPTS_DIR))
|
| 26 |
-
from config import load_prefixed_env_file
|
| 27 |
|
| 28 |
# Load env
|
| 29 |
load_prefixed_env_file(("OPENROUTER_", "COMFYUI_", "IMAGE_", "PEXELS_", "PIXABAY_"))
|
| 30 |
|
| 31 |
# ============================================================
|
| 32 |
-
# LLM Client
|
| 33 |
# ============================================================
|
| 34 |
|
| 35 |
-
def llm_chat(prompt, system=None, max_tokens=
|
| 36 |
-
"""Call OpenRouter LLM."""
|
| 37 |
import requests
|
| 38 |
api_key = os.environ.get("OPENROUTER_API_KEY", "")
|
| 39 |
model = os.environ.get("OPENROUTER_MODEL", "tencent/hy3-preview:free")
|
| 40 |
base_url = os.environ.get("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1").rstrip("/")
|
| 41 |
-
|
| 42 |
if not api_key:
|
| 43 |
raise RuntimeError("OPENROUTER_API_KEY non configuré dans .env")
|
| 44 |
-
|
| 45 |
messages = []
|
| 46 |
if system:
|
| 47 |
messages.append({"role": "system", "content": system})
|
| 48 |
messages.append({"role": "user", "content": prompt})
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
"HTTP-Referer": "http://localhost/ppt-master",
|
| 56 |
-
"X-Title": "ppt-master-gradio",
|
| 57 |
-
},
|
| 58 |
-
json={
|
| 59 |
-
"model": model,
|
| 60 |
-
"messages": messages,
|
| 61 |
-
"temperature": temperature,
|
| 62 |
-
"max_tokens": max_tokens,
|
| 63 |
-
"reasoning": {"exclude": True},
|
| 64 |
-
},
|
| 65 |
-
timeout=300,
|
| 66 |
-
)
|
| 67 |
if r.status_code >= 400:
|
| 68 |
raise RuntimeError(f"OpenRouter erreur {r.status_code}: {r.text[:500]}")
|
| 69 |
data = r.json()
|
| 70 |
content = data.get("choices", [{}])[0].get("message", {}).get("content")
|
| 71 |
if not content:
|
| 72 |
-
raise RuntimeError(f"Pas de contenu
|
| 73 |
return content
|
| 74 |
|
| 75 |
|
| 76 |
# ============================================================
|
| 77 |
-
#
|
| 78 |
# ============================================================
|
| 79 |
|
| 80 |
-
def
|
| 81 |
-
"""
|
| 82 |
-
|
| 83 |
-
prompt = f"""
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
result = llm_chat(prompt, max_tokens=32000)
|
| 89 |
|
| 90 |
-
#
|
| 91 |
try:
|
| 92 |
-
# Try to find JSON in the response
|
| 93 |
json_match = re.search(r'\{[\s\S]*\}', result)
|
| 94 |
if json_match:
|
| 95 |
-
|
| 96 |
else:
|
| 97 |
-
|
| 98 |
-
except json.JSONDecodeError
|
| 99 |
-
# Try
|
| 100 |
-
|
| 101 |
-
# Remove trailing incomplete values
|
| 102 |
-
for _ in range(10):
|
| 103 |
try:
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
json_match = re.search(r'\{[\s\S]*\}', test)
|
| 109 |
-
if json_match:
|
| 110 |
-
outline = json.loads(json_match.group())
|
| 111 |
-
# Remove dummy slides if added
|
| 112 |
-
outline["slides"] = [s for s in outline.get("slides",[]) if s.get("number") != 99]
|
| 113 |
-
return outline
|
| 114 |
-
except:
|
| 115 |
-
continue
|
| 116 |
-
# Cut last incomplete entry and retry
|
| 117 |
-
last_brace = repaired.rfind('{')
|
| 118 |
-
if last_brace > 0:
|
| 119 |
-
repaired = repaired[:last_brace].rstrip().rstrip(',')
|
| 120 |
-
else:
|
| 121 |
break
|
| 122 |
except:
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
|
|
|
|
|
|
|
| 127 |
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
|
| 130 |
-
"
|
| 131 |
-
lines =
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
| 137 |
if slide.get("image_prompt"):
|
| 138 |
-
lines.append(f"\n🖼️ Image: *{slide['image_prompt']}*")
|
|
|
|
|
|
|
| 139 |
lines.append("")
|
|
|
|
| 140 |
return "\n".join(lines)
|
| 141 |
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
images_dir = Path(project_path) / "images"
|
| 146 |
images_dir.mkdir(parents=True, exist_ok=True)
|
| 147 |
|
| 148 |
-
|
|
|
|
| 149 |
prompt = slide.get("image_prompt", "")
|
| 150 |
if not prompt:
|
| 151 |
continue
|
| 152 |
-
|
| 153 |
filename = f"slide_{slide['number']:02d}"
|
| 154 |
|
| 155 |
-
if
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
-
if
|
| 159 |
try:
|
| 160 |
-
|
| 161 |
[sys.executable, str(SCRIPTS_DIR / "image_gen.py"),
|
| 162 |
prompt, "--backend", "comfyui",
|
| 163 |
"--aspect_ratio", "16:9", "--image_size", "1K",
|
| 164 |
"-o", str(images_dir), "--filename", filename],
|
| 165 |
-
capture_output=True, text=True, timeout=
|
| 166 |
-
cwd=str(SCRIPTS_DIR)
|
| 167 |
-
)
|
| 168 |
-
if result.returncode != 0:
|
| 169 |
-
print(f" [WARN] image_gen failed for slide {slide['number']}: {result.stderr[:200]}")
|
| 170 |
except Exception as e:
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
elif
|
| 174 |
try:
|
| 175 |
-
|
| 176 |
[sys.executable, str(SCRIPTS_DIR / "image_search.py"),
|
| 177 |
prompt, "--filename", f"{filename}.jpg",
|
| 178 |
-
"--orientation", "landscape",
|
| 179 |
-
|
| 180 |
-
capture_output=True, text=True, timeout=60,
|
| 181 |
-
cwd=str(SCRIPTS_DIR)
|
| 182 |
-
)
|
| 183 |
except Exception as e:
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
"-o", str(images_dir), "--filename", filename],
|
| 195 |
-
capture_output=True, text=True, timeout=120,
|
| 196 |
-
cwd=str(SCRIPTS_DIR)
|
| 197 |
-
)
|
| 198 |
-
except:
|
| 199 |
-
pass
|
| 200 |
-
else:
|
| 201 |
-
try:
|
| 202 |
-
subprocess.run(
|
| 203 |
-
[sys.executable, str(SCRIPTS_DIR / "image_search.py"),
|
| 204 |
-
prompt, "--filename", f"{filename}.jpg",
|
| 205 |
-
"--orientation", "landscape",
|
| 206 |
-
"-o", str(images_dir)],
|
| 207 |
-
capture_output=True, text=True, timeout=60,
|
| 208 |
-
cwd=str(SCRIPTS_DIR)
|
| 209 |
-
)
|
| 210 |
-
except:
|
| 211 |
-
pass
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
def generate_svgs(outline, project_path, style, progress_callback=None):
|
| 215 |
-
"""Generate SVG files for each slide using the LLM for high-quality output."""
|
| 216 |
svg_dir = Path(project_path) / "svg_output"
|
| 217 |
svg_dir.mkdir(parents=True, exist_ok=True)
|
| 218 |
images_dir = Path(project_path) / "images"
|
|
|
|
|
|
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
}
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
num = slide["number"]
|
| 235 |
name = f"slide_{num:02d}"
|
| 236 |
|
| 237 |
-
if
|
| 238 |
-
|
| 239 |
|
| 240 |
-
# Find image
|
| 241 |
img_ref = ""
|
| 242 |
for ext in ('.png', '.jpg', '.jpeg', '.webp'):
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
img_ref = f'Include this image: <image href="../images/{name}{ext}" preserveAspectRatio="xMidYMid slice"/>'
|
| 246 |
break
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
prompt = f"""Generate a beautiful SVG slide (viewBox="0 0 1280 720") for a presentation.
|
| 251 |
-
Slide {num}/{num_slides}. Layout: {slide.get('layout','content')}. Style: {style}.
|
| 252 |
-
|
| 253 |
-
Title: {slide['title']}
|
| 254 |
-
Content:
|
| 255 |
-
{content_text}
|
| 256 |
|
| 257 |
-
{
|
| 258 |
|
| 259 |
-
|
| 260 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
-
|
| 263 |
-
- viewBox="0 0 1280 720", include width="1280" height="720"
|
| 264 |
-
- Include xmlns="http://www.w3.org/2000/svg"
|
| 265 |
-
- Use gradients, decorative shapes (circles, lines, rects with opacity)
|
| 266 |
-
- {f'Place the image prominently (half-slide or background)' if img_ref else 'No image available, use shapes and colors creatively'}
|
| 267 |
-
- Show ALL content points as text elements, nicely positioned
|
| 268 |
-
- Add a page number {num}/{num_slides} in bottom right
|
| 269 |
-
- NO <style>, NO class, NO foreignObject, NO animate, NO script, NO mask
|
| 270 |
-
- NO HTML entities, use raw Unicode characters
|
| 271 |
-
- All text in absolute positioned <text> elements
|
| 272 |
-
- Make it visually rich and professional
|
| 273 |
|
| 274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
|
| 276 |
try:
|
| 277 |
svg_content = llm_chat(prompt, max_tokens=8000, temperature=0.3)
|
| 278 |
|
| 279 |
-
#
|
| 280 |
svg_start = svg_content.find('<svg')
|
| 281 |
svg_end = svg_content.rfind('</svg>')
|
| 282 |
if svg_start >= 0 and svg_end > svg_start:
|
| 283 |
svg_content = svg_content[svg_start:svg_end + 6]
|
| 284 |
elif svg_start >= 0:
|
| 285 |
-
svg_content =
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
if '<svg' not in svg_content:
|
| 289 |
-
raise RuntimeError("No SVG in response")
|
| 290 |
|
| 291 |
(svg_dir / f"{name}.svg").write_text(svg_content, encoding="utf-8")
|
| 292 |
|
| 293 |
except Exception as e:
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
|
|
|
|
|
|
| 311 |
title = slide["title"].replace('&','&').replace('<','<').replace('>','>')
|
| 312 |
content = slide.get("content", [])
|
| 313 |
|
| 314 |
lines = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720" width="1280" height="720">',
|
| 315 |
-
f' <rect width="1280" height="720" fill="{bg}"/>'
|
| 316 |
-
|
| 317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
for j, p in enumerate(content[:6]):
|
| 319 |
-
y =
|
| 320 |
p_esc = p.replace('&','&').replace('<','<').replace('>','>')[:100]
|
| 321 |
-
lines.append(f' <text x="80" y="{y}" font-family="
|
| 322 |
-
lines.append(f' <text x="1224" y="700" text-anchor="end" font-family="
|
| 323 |
lines.append('</svg>')
|
| 324 |
(svg_dir / f"{name}.svg").write_text("\n".join(lines), encoding="utf-8")
|
| 325 |
|
| 326 |
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
notes_dir.mkdir(parents=True, exist_ok=True)
|
| 331 |
-
|
| 332 |
-
total_lines = []
|
| 333 |
-
for slide in outline.get("slides", []):
|
| 334 |
-
name = f"slide_{slide['number']:02d}"
|
| 335 |
-
note = f"{slide['title']}. " + " ".join(slide.get("content", []))
|
| 336 |
-
(notes_dir / f"{name}.md").write_text(note, encoding="utf-8")
|
| 337 |
-
total_lines.append(f"# {name}\n\n{note}")
|
| 338 |
-
|
| 339 |
-
(notes_dir / "total.md").write_text("\n\n---\n\n".join(total_lines), encoding="utf-8")
|
| 340 |
-
|
| 341 |
|
| 342 |
-
def
|
| 343 |
-
"""Run
|
| 344 |
env = os.environ.copy()
|
| 345 |
|
| 346 |
# total_md_split
|
| 347 |
-
subprocess.run(
|
| 348 |
-
|
| 349 |
-
capture_output=True, text=True, timeout=60, cwd=str(SCRIPTS_DIR), env=env
|
| 350 |
-
)
|
| 351 |
|
| 352 |
# finalize_svg
|
| 353 |
-
subprocess.run(
|
| 354 |
-
|
| 355 |
-
capture_output=True, text=True, timeout=120, cwd=str(SCRIPTS_DIR), env=env
|
| 356 |
-
)
|
| 357 |
|
| 358 |
# svg_to_pptx
|
| 359 |
-
result = subprocess.run(
|
| 360 |
-
|
| 361 |
-
capture_output=True, text=True, timeout=120, cwd=str(SCRIPTS_DIR), env=env
|
| 362 |
-
)
|
| 363 |
|
| 364 |
return result.stdout + result.stderr
|
| 365 |
|
| 366 |
|
| 367 |
# ============================================================
|
| 368 |
-
#
|
| 369 |
# ============================================================
|
| 370 |
|
| 371 |
-
def
|
| 372 |
-
"""
|
| 373 |
if not subject.strip():
|
| 374 |
return "❌ Entre un sujet !", "", "{}"
|
| 375 |
-
|
| 376 |
try:
|
| 377 |
-
|
| 378 |
-
preview =
|
| 379 |
-
return f"✅
|
| 380 |
except Exception as e:
|
| 381 |
-
return f"❌ Erreur: {str(e)}", "", "{}"
|
| 382 |
|
| 383 |
|
| 384 |
-
def
|
| 385 |
-
"""Full
|
| 386 |
-
if not
|
| 387 |
return "❌ Génère d'abord le plan (étape 1)", None, ""
|
| 388 |
-
|
| 389 |
try:
|
| 390 |
-
|
| 391 |
except:
|
| 392 |
-
return "❌
|
| 393 |
|
| 394 |
-
# Create project
|
| 395 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 396 |
project_name = f"gradio_{timestamp}"
|
| 397 |
project_path = str(PROJECTS_DIR / project_name)
|
|
@@ -399,164 +412,113 @@ def step2_generate_pptx(outline_json, style, image_mode, progress=gr.Progress())
|
|
| 399 |
for d in ("svg_output", "svg_final", "images", "notes", "exports"):
|
| 400 |
os.makedirs(f"{project_path}/{d}", exist_ok=True)
|
| 401 |
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
# Step A: Generate images
|
| 405 |
-
num_slides = len(outline.get("slides", []))
|
| 406 |
-
progress(0.1, desc="Génération des images...")
|
| 407 |
-
log_lines.append("🖼️ Génération des images...")
|
| 408 |
-
|
| 409 |
-
def img_progress(msg):
|
| 410 |
-
log_lines.append(f" {msg}")
|
| 411 |
|
| 412 |
-
|
| 413 |
-
|
|
|
|
| 414 |
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
log_lines.append(f" ⏱️ ~60-90s par slide, {num_slides} slides à générer...")
|
| 419 |
|
| 420 |
-
|
| 421 |
-
|
|
|
|
|
|
|
| 422 |
|
| 423 |
-
|
| 424 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
generate_notes(outline, project_path)
|
| 429 |
-
log_lines.append("📝 Notes orateur générées\n")
|
| 430 |
|
| 431 |
-
#
|
| 432 |
-
progress(0.
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
|
| 437 |
-
# Find
|
| 438 |
pptx_files = glob.glob(f"{project_path}/exports/*.pptx")
|
| 439 |
if pptx_files:
|
| 440 |
pptx_path = pptx_files[0]
|
|
|
|
| 441 |
progress(1.0, desc="Terminé !")
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
return "✅ Présentation générée avec succès !", pptx_path, "\n".join(log_lines)
|
| 445 |
else:
|
| 446 |
-
|
| 447 |
-
log_lines.append("\n❌ Pas de PPTX trouvé dans exports/")
|
| 448 |
-
return "❌ Erreur lors de l'export", None, "\n".join(log_lines)
|
| 449 |
|
| 450 |
|
| 451 |
# ============================================================
|
| 452 |
-
#
|
| 453 |
# ============================================================
|
| 454 |
|
| 455 |
STYLES = ["Dark Fantasy", "Corporate", "Tech / Startup", "Nature / Zen", "Académique", "Minimaliste"]
|
| 456 |
LANGUAGES = ["Français", "English", "Español", "Deutsch", "中文", "日本語"]
|
| 457 |
IMAGE_MODES = ["ComfyUI (local GPU)", "Recherche web (Wikimedia)", "Les deux (ComfyUI + web)", "Aucune image"]
|
| 458 |
|
| 459 |
-
with gr.Blocks(
|
| 460 |
-
title="PPT Master — Générateur de Présentations IA",
|
| 461 |
-
theme=gr.themes.Soft(primary_hue="amber", secondary_hue="slate"),
|
| 462 |
-
css="""
|
| 463 |
-
.main-title { text-align: center; margin-bottom: 0.5em; }
|
| 464 |
-
.subtitle { text-align: center; color: #666; margin-bottom: 1.5em; }
|
| 465 |
-
"""
|
| 466 |
-
) as app:
|
| 467 |
|
| 468 |
-
# State
|
| 469 |
outline_state = gr.State("{}")
|
| 470 |
|
| 471 |
-
#
|
| 472 |
-
gr.Markdown("
|
| 473 |
-
gr.Markdown("*OpenRouter LLM + ComfyUI local + export PowerPoint natif*", elem_classes="subtitle")
|
| 474 |
|
| 475 |
with gr.Tabs():
|
| 476 |
-
|
| 477 |
-
with gr.Tab("1️⃣ Sujet & Plan", id="tab1"):
|
| 478 |
with gr.Row():
|
| 479 |
with gr.Column(scale=2):
|
| 480 |
-
subject = gr.Textbox(
|
| 481 |
-
label="📌 Sujet de la présentation",
|
| 482 |
-
placeholder="Ex: Game of Thrones, l'Intelligence Artificielle en 2025, la conquête spatiale...",
|
| 483 |
-
lines=2
|
| 484 |
-
)
|
| 485 |
with gr.Row():
|
| 486 |
-
num_slides = gr.Slider(5, 20, value=10, step=1, label="📄
|
| 487 |
language = gr.Dropdown(LANGUAGES, value="Français", label="🌐 Langue")
|
| 488 |
-
|
| 489 |
with gr.Column(scale=1):
|
| 490 |
-
style = gr.Dropdown(STYLES, value="Dark Fantasy", label="🎨 Style
|
| 491 |
-
audience = gr.Textbox(label="👥 Public
|
| 492 |
-
image_mode = gr.Dropdown(IMAGE_MODES, value="ComfyUI (local GPU)", label="🖼️
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
gr.Markdown("
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
gr.
|
| 503 |
-
gr.
|
| 504 |
-
|
| 505 |
-
btn_generate = gr.Button("⚡ Générer la présentation complète", variant="primary", size="lg")
|
| 506 |
-
status_generate = gr.Textbox(label="Statut", interactive=False)
|
| 507 |
-
|
| 508 |
with gr.Row():
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
with gr.Column():
|
| 512 |
-
pptx_file = gr.File(label="📥 Télécharger le PPTX")
|
| 513 |
|
| 514 |
-
# ─── TAB 3: À propos ───
|
| 515 |
with gr.Tab("ℹ️ À propos"):
|
| 516 |
gr.Markdown("""
|
| 517 |
-
## PPT Master
|
| 518 |
|
| 519 |
-
**
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
|
|
|
| 523 |
|
| 524 |
-
**
|
| 525 |
-
|
| 526 |
-
2. Tu valides → la pipeline génère les images, crée les SVG, exporte en PPTX
|
| 527 |
-
3. Tu télécharges le PowerPoint final, entièrement éditable dans PowerPoint/LibreOffice
|
| 528 |
|
| 529 |
-
**
|
| 530 |
-
- Fichier `.env` pour les clés API et chemins ComfyUI
|
| 531 |
-
- ComfyUI doit tourner en arrière-plan sur le port 8188
|
| 532 |
-
|
| 533 |
-
**Crédits:**
|
| 534 |
-
- PPT Master par Hugo He (https://github.com/hugohe3/ppt-master)
|
| 535 |
-
- Modifications: backend ComfyUI + OpenRouter + interface Gradio
|
| 536 |
""")
|
| 537 |
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
outputs=[status_outline, outline_preview, outline_state]
|
| 543 |
-
)
|
| 544 |
-
|
| 545 |
-
btn_generate.click(
|
| 546 |
-
fn=step2_generate_pptx,
|
| 547 |
-
inputs=[outline_state, style, image_mode],
|
| 548 |
-
outputs=[status_generate, pptx_file, log_output]
|
| 549 |
-
)
|
| 550 |
|
| 551 |
|
| 552 |
-
# ============================================================
|
| 553 |
-
# Launch
|
| 554 |
-
# ============================================================
|
| 555 |
-
|
| 556 |
if __name__ == "__main__":
|
| 557 |
-
app.launch(
|
| 558 |
-
server_name="127.0.0.1",
|
| 559 |
-
server_port=7860,
|
| 560 |
-
share=False,
|
| 561 |
-
inbrowser=True
|
| 562 |
-
)
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
PPT Master — Interface Gradio V5
|
| 4 |
+
Full PPT Master workflow: Strategist → spec_lock → Image Acquisition → Executor (LLM SVG) → Quality Check → Finalize → Export
|
| 5 |
"""
|
| 6 |
|
| 7 |
import gradio as gr
|
|
|
|
| 21 |
SKILL_DIR = SCRIPT_DIR / "skills" / "ppt-master"
|
| 22 |
SCRIPTS_DIR = SKILL_DIR / "scripts"
|
| 23 |
PROJECTS_DIR = SCRIPT_DIR / "projects"
|
| 24 |
+
REFS_DIR = SKILL_DIR / "references"
|
| 25 |
|
| 26 |
sys.path.insert(0, str(SCRIPTS_DIR))
|
| 27 |
+
from config import load_prefixed_env_file
|
| 28 |
|
| 29 |
# Load env
|
| 30 |
load_prefixed_env_file(("OPENROUTER_", "COMFYUI_", "IMAGE_", "PEXELS_", "PIXABAY_"))
|
| 31 |
|
| 32 |
# ============================================================
|
| 33 |
+
# LLM Client
|
| 34 |
# ============================================================
|
| 35 |
|
| 36 |
+
def llm_chat(prompt, system=None, max_tokens=32000, temperature=0.3):
|
|
|
|
| 37 |
import requests
|
| 38 |
api_key = os.environ.get("OPENROUTER_API_KEY", "")
|
| 39 |
model = os.environ.get("OPENROUTER_MODEL", "tencent/hy3-preview:free")
|
| 40 |
base_url = os.environ.get("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1").rstrip("/")
|
|
|
|
| 41 |
if not api_key:
|
| 42 |
raise RuntimeError("OPENROUTER_API_KEY non configuré dans .env")
|
|
|
|
| 43 |
messages = []
|
| 44 |
if system:
|
| 45 |
messages.append({"role": "system", "content": system})
|
| 46 |
messages.append({"role": "user", "content": prompt})
|
| 47 |
+
r = requests.post(f"{base_url}/chat/completions",
|
| 48 |
+
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json",
|
| 49 |
+
"HTTP-Referer": "http://localhost/ppt-master", "X-Title": "ppt-master-gradio"},
|
| 50 |
+
json={"model": model, "messages": messages, "temperature": temperature,
|
| 51 |
+
"max_tokens": max_tokens, "reasoning": {"exclude": True}},
|
| 52 |
+
timeout=600)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
if r.status_code >= 400:
|
| 54 |
raise RuntimeError(f"OpenRouter erreur {r.status_code}: {r.text[:500]}")
|
| 55 |
data = r.json()
|
| 56 |
content = data.get("choices", [{}])[0].get("message", {}).get("content")
|
| 57 |
if not content:
|
| 58 |
+
raise RuntimeError(f"Pas de contenu retourné par le LLM")
|
| 59 |
return content
|
| 60 |
|
| 61 |
|
| 62 |
# ============================================================
|
| 63 |
+
# STEP 1: STRATEGIST — Generate design_spec + spec_lock + outline
|
| 64 |
# ============================================================
|
| 65 |
|
| 66 |
+
def strategist_phase(subject, num_slides, style, language, audience):
|
| 67 |
+
"""The Strategist generates the full design specification."""
|
| 68 |
+
|
| 69 |
+
prompt = f"""You are the Strategist for PPT Master. Generate a complete design specification for a presentation.
|
| 70 |
+
|
| 71 |
+
Subject: {subject}
|
| 72 |
+
Number of slides: {num_slides}
|
| 73 |
+
Style: {style}
|
| 74 |
+
Language: {language}
|
| 75 |
+
Target audience: {audience}
|
| 76 |
+
Canvas: PPT 16:9 (1280x720, viewBox="0 0 1280 720")
|
| 77 |
+
|
| 78 |
+
Produce a JSON response with this EXACT structure:
|
| 79 |
+
{{
|
| 80 |
+
"title": "Presentation title",
|
| 81 |
+
"spec_lock": {{
|
| 82 |
+
"canvas": {{"viewBox": "0 0 1280 720", "format": "PPT 16:9"}},
|
| 83 |
+
"colors": {{"bg": "#...", "bg_alt": "#...", "primary": "#...", "accent": "#...", "secondary_accent": "#...", "text": "#...", "text_secondary": "#...", "border": "#..."}},
|
| 84 |
+
"typography": {{"title_family": "...", "body_family": "...", "body": 20, "title": 40, "subtitle": 26, "annotation": 14}},
|
| 85 |
+
"icons": {{"library": "chunk-filled", "inventory": ["icon1", "icon2", "..."]}},
|
| 86 |
+
"page_rhythm": {{"P01": "anchor", "P02": "dense", "...": "..."}}
|
| 87 |
+
}},
|
| 88 |
+
"slides": [
|
| 89 |
+
{{
|
| 90 |
+
"number": 1,
|
| 91 |
+
"title": "Slide title",
|
| 92 |
+
"layout": "cover",
|
| 93 |
+
"rhythm": "anchor",
|
| 94 |
+
"content": ["Point 1", "Point 2", "Point 3"],
|
| 95 |
+
"image_prompt": "English cinematic image description, no text",
|
| 96 |
+
"image_source": "ai",
|
| 97 |
+
"notes": "Speaker notes for this slide (conversational tone)"
|
| 98 |
+
}}
|
| 99 |
+
]
|
| 100 |
+
}}
|
| 101 |
+
|
| 102 |
+
Style guidelines:
|
| 103 |
+
- "Dark Fantasy": dark backgrounds (#0B0F17), gold (#C8A45D), red (#8B1E2D), ice blue (#6FA8B8)
|
| 104 |
+
- "Corporate": white, professional blue (#1A56DB), clean
|
| 105 |
+
- "Tech / Startup": dark navy (#0F172A), cyan (#06B6D4), purple (#8B5CF6)
|
| 106 |
+
- "Nature / Zen": warm white (#FEFDF8), green (#2D5016), amber (#B45309)
|
| 107 |
+
- "Académique": cream (#FFFBF5), burgundy (#7C2D12), blue (#1E40AF)
|
| 108 |
+
- "Minimaliste": pure white, black (#18181B), red accent (#DC2626)
|
| 109 |
+
|
| 110 |
+
Rules:
|
| 111 |
+
- Content points: max 20 words each, factual and specific
|
| 112 |
+
- image_prompt: English, cinematic, under 30 words, NO text in image
|
| 113 |
+
- image_source: "ai" for generated, "web" for stock photo search
|
| 114 |
+
- notes: conversational tone, 2-3 sentences, like talking to audience
|
| 115 |
+
- 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)
|
| 116 |
+
- First slide layout="cover", last="closing", others mix of "content"/"comparison"/"timeline"/"quote"
|
| 117 |
+
- page_rhythm: "anchor" for cover/closing, "dense" for data-heavy, "breathing" for impact pages
|
| 118 |
+
- Reply ONLY with raw JSON, no markdown code blocks, no explanation"""
|
| 119 |
|
| 120 |
result = llm_chat(prompt, max_tokens=32000)
|
| 121 |
|
| 122 |
+
# Parse JSON
|
| 123 |
try:
|
|
|
|
| 124 |
json_match = re.search(r'\{[\s\S]*\}', result)
|
| 125 |
if json_match:
|
| 126 |
+
data = json.loads(json_match.group())
|
| 127 |
else:
|
| 128 |
+
data = json.loads(result)
|
| 129 |
+
except json.JSONDecodeError:
|
| 130 |
+
# Try repair
|
| 131 |
+
for suffix in ['}]}', '"}]}', '"]}]}']:
|
|
|
|
|
|
|
| 132 |
try:
|
| 133 |
+
repaired = result.rstrip() + suffix
|
| 134 |
+
json_match = re.search(r'\{[\s\S]*\}', repaired)
|
| 135 |
+
if json_match:
|
| 136 |
+
data = json.loads(json_match.group())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
break
|
| 138 |
except:
|
| 139 |
+
continue
|
| 140 |
+
else:
|
| 141 |
+
raise RuntimeError(f"JSON invalide du Strategist.\n\nRéponse:\n{result[:3000]}")
|
| 142 |
+
|
| 143 |
+
return data
|
| 144 |
+
|
| 145 |
|
| 146 |
+
def format_strategist_preview(data):
|
| 147 |
+
"""Format strategist output as readable markdown."""
|
| 148 |
+
lines = [f"# {data.get('title', 'Présentation')}\n"]
|
| 149 |
|
| 150 |
+
spec = data.get("spec_lock", {})
|
| 151 |
+
colors = spec.get("colors", {})
|
| 152 |
+
typo = spec.get("typography", {})
|
| 153 |
|
| 154 |
+
lines.append("## 🎨 Design Spec\n")
|
| 155 |
+
lines.append(f"**Palette**: {' | '.join(f'{k}: `{v}`' for k,v in colors.items())}\n")
|
| 156 |
+
lines.append(f"**Typo**: titre={typo.get('title_family','?')}, corps={typo.get('body_family','?')}, taille={typo.get('body',20)}px\n")
|
| 157 |
+
lines.append(f"**Icônes**: {', '.join(spec.get('icons',{}).get('inventory',[]))}\n")
|
| 158 |
+
|
| 159 |
+
lines.append("\n## 📋 Plan des slides\n")
|
| 160 |
+
for slide in data.get("slides", []):
|
| 161 |
+
lines.append(f"### Slide {slide['number']}: {slide['title']}")
|
| 162 |
+
lines.append(f"*Layout: {slide.get('layout','content')} | Rythme: {slide.get('rhythm','dense')}*\n")
|
| 163 |
+
for p in slide.get("content", []):
|
| 164 |
+
lines.append(f"- {p}")
|
| 165 |
if slide.get("image_prompt"):
|
| 166 |
+
lines.append(f"\n🖼️ Image ({slide.get('image_source','ai')}): *{slide['image_prompt']}*")
|
| 167 |
+
if slide.get("notes"):
|
| 168 |
+
lines.append(f"\n🎙️ Notes: *{slide['notes'][:100]}...*")
|
| 169 |
lines.append("")
|
| 170 |
+
|
| 171 |
return "\n".join(lines)
|
| 172 |
|
| 173 |
|
| 174 |
+
# ============================================================
|
| 175 |
+
# STEP 2: IMAGE ACQUISITION
|
| 176 |
+
# ============================================================
|
| 177 |
+
|
| 178 |
+
def acquire_images(data, project_path, image_mode, progress_cb=None):
|
| 179 |
+
"""Generate/search images for each slide."""
|
| 180 |
images_dir = Path(project_path) / "images"
|
| 181 |
images_dir.mkdir(parents=True, exist_ok=True)
|
| 182 |
|
| 183 |
+
slides = data.get("slides", [])
|
| 184 |
+
for i, slide in enumerate(slides):
|
| 185 |
prompt = slide.get("image_prompt", "")
|
| 186 |
if not prompt:
|
| 187 |
continue
|
| 188 |
+
source = slide.get("image_source", "ai")
|
| 189 |
filename = f"slide_{slide['number']:02d}"
|
| 190 |
|
| 191 |
+
if progress_cb:
|
| 192 |
+
progress_cb(f"🖼️ [{i+1}/{len(slides)}] {prompt[:50]}...")
|
| 193 |
+
|
| 194 |
+
if image_mode == "Aucune image":
|
| 195 |
+
continue
|
| 196 |
+
|
| 197 |
+
use_comfyui = (image_mode == "ComfyUI (local GPU)") or \
|
| 198 |
+
(image_mode == "Les deux (ComfyUI + web)" and source == "ai")
|
| 199 |
+
use_web = (image_mode == "Recherche web (Wikimedia)") or \
|
| 200 |
+
(image_mode == "Les deux (ComfyUI + web)" and source == "web")
|
| 201 |
|
| 202 |
+
if use_comfyui:
|
| 203 |
try:
|
| 204 |
+
subprocess.run(
|
| 205 |
[sys.executable, str(SCRIPTS_DIR / "image_gen.py"),
|
| 206 |
prompt, "--backend", "comfyui",
|
| 207 |
"--aspect_ratio", "16:9", "--image_size", "1K",
|
| 208 |
"-o", str(images_dir), "--filename", filename],
|
| 209 |
+
capture_output=True, text=True, timeout=180, cwd=str(SCRIPTS_DIR))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
except Exception as e:
|
| 211 |
+
if progress_cb:
|
| 212 |
+
progress_cb(f" ⚠️ ComfyUI failed: {str(e)[:60]}")
|
| 213 |
+
elif use_web:
|
| 214 |
try:
|
| 215 |
+
subprocess.run(
|
| 216 |
[sys.executable, str(SCRIPTS_DIR / "image_search.py"),
|
| 217 |
prompt, "--filename", f"{filename}.jpg",
|
| 218 |
+
"--orientation", "landscape", "-o", str(images_dir)],
|
| 219 |
+
capture_output=True, text=True, timeout=60, cwd=str(SCRIPTS_DIR))
|
|
|
|
|
|
|
|
|
|
| 220 |
except Exception as e:
|
| 221 |
+
if progress_cb:
|
| 222 |
+
progress_cb(f" ⚠��� Web search failed: {str(e)[:60]}")
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# ============================================================
|
| 226 |
+
# STEP 3: EXECUTOR — LLM generates each SVG sequentially
|
| 227 |
+
# ============================================================
|
| 228 |
+
|
| 229 |
+
def executor_phase(data, project_path, style, progress_cb=None):
|
| 230 |
+
"""Generate SVG slides sequentially using the LLM as Executor."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
svg_dir = Path(project_path) / "svg_output"
|
| 232 |
svg_dir.mkdir(parents=True, exist_ok=True)
|
| 233 |
images_dir = Path(project_path) / "images"
|
| 234 |
+
notes_dir = Path(project_path) / "notes"
|
| 235 |
+
notes_dir.mkdir(parents=True, exist_ok=True)
|
| 236 |
|
| 237 |
+
spec_lock = data.get("spec_lock", {})
|
| 238 |
+
colors = spec_lock.get("colors", {})
|
| 239 |
+
typo = spec_lock.get("typography", {})
|
| 240 |
+
icons = spec_lock.get("icons", {})
|
| 241 |
+
slides = data.get("slides", [])
|
| 242 |
+
num_total = len(slides)
|
| 243 |
+
|
| 244 |
+
# Build color string for the prompt
|
| 245 |
+
color_str = ", ".join(f"{k}: {v}" for k, v in colors.items())
|
| 246 |
+
font_title = typo.get("title_family", "Georgia, Times New Roman, serif")
|
| 247 |
+
font_body = typo.get("body_family", "Arial, sans-serif")
|
| 248 |
+
icon_lib = icons.get("library", "chunk-filled")
|
| 249 |
+
icon_inv = ", ".join(icons.get("inventory", []))
|
| 250 |
+
|
| 251 |
+
# Shared executor instructions
|
| 252 |
+
executor_rules = f"""SVG RULES (MANDATORY):
|
| 253 |
+
- viewBox="0 0 1280 720" width="1280" height="720" xmlns="http://www.w3.org/2000/svg"
|
| 254 |
+
- Colors ONLY from spec_lock: {color_str}
|
| 255 |
+
- Title font: {font_title}. Body font: {font_body}
|
| 256 |
+
- Body size: {typo.get('body',20)}px, Title size: {typo.get('title',40)}px
|
| 257 |
+
- Icons: use <use data-icon="{icon_lib}/ICON_NAME" x="" y="" width="40" height="40" fill="COLOR"/>
|
| 258 |
+
- Available icons: {icon_inv}
|
| 259 |
+
- FORBIDDEN: <style>, class, foreignObject, animate, script, mask, @font-face, rgba(), <g opacity="">
|
| 260 |
+
- Use linearGradient/radialGradient in <defs> for backgrounds
|
| 261 |
+
- Decorative elements: circles, lines, rects with fill-opacity for visual richness
|
| 262 |
+
- All text as absolute <text> elements with font-family, font-size, fill attributes
|
| 263 |
+
- Images: <image href="../images/FILENAME" x="" y="" width="" height="" preserveAspectRatio="xMidYMid slice"/>
|
| 264 |
+
- Page number in bottom-right corner
|
| 265 |
+
- Reply ONLY with SVG code: start with <svg, end with </svg>"""
|
| 266 |
+
|
| 267 |
+
total_notes = []
|
| 268 |
+
|
| 269 |
+
for slide in slides:
|
| 270 |
num = slide["number"]
|
| 271 |
name = f"slide_{num:02d}"
|
| 272 |
|
| 273 |
+
if progress_cb:
|
| 274 |
+
progress_cb(f"🎨 SVG {num}/{num_total}: {slide['title'][:40]}...")
|
| 275 |
|
| 276 |
+
# Find image
|
| 277 |
img_ref = ""
|
| 278 |
for ext in ('.png', '.jpg', '.jpeg', '.webp'):
|
| 279 |
+
if (images_dir / f"{name}{ext}").exists():
|
| 280 |
+
img_ref = f'Image available: "../images/{name}{ext}"'
|
|
|
|
| 281 |
break
|
| 282 |
|
| 283 |
+
content_str = "\n".join(f" - {p}" for p in slide.get("content", []))
|
| 284 |
+
rhythm = slide.get("rhythm", "dense")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
+
prompt = f"""Generate SVG slide {num}/{num_total} for this presentation.
|
| 287 |
|
| 288 |
+
SLIDE SPEC:
|
| 289 |
+
- Title: {slide['title']}
|
| 290 |
+
- Layout: {slide.get('layout','content')}
|
| 291 |
+
- Rhythm: {rhythm} ({'full-bleed imagery, minimal text, breathing space' if rhythm == 'breathing' else 'information-rich, cards, structured content' if rhythm == 'dense' else 'structural, decorative, impactful'})
|
| 292 |
+
- Content:
|
| 293 |
+
{content_str}
|
| 294 |
+
- {img_ref or 'No image for this slide — use colors/shapes creatively'}
|
| 295 |
|
| 296 |
+
{executor_rules}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
+
Design direction for "{style}" style. Make it visually striking and professional.
|
| 299 |
+
{"Use the image prominently (background or half-slide). Add dark overlay for text readability." if img_ref else ""}
|
| 300 |
+
{"This is a COVER page: large title, dramatic, impactful." if slide.get('layout') == 'cover' else ""}
|
| 301 |
+
{"This is a CLOSING page: centered, memorable, call-to-action feel." if slide.get('layout') == 'closing' else ""}
|
| 302 |
+
{"This is a TIMELINE: show progression horizontally with nodes/circles." if slide.get('layout') == 'timeline' else ""}
|
| 303 |
+
{"This is a COMPARISON: show two sides contrasted." if slide.get('layout') == 'comparison' else ""}"""
|
| 304 |
|
| 305 |
try:
|
| 306 |
svg_content = llm_chat(prompt, max_tokens=8000, temperature=0.3)
|
| 307 |
|
| 308 |
+
# Extract SVG
|
| 309 |
svg_start = svg_content.find('<svg')
|
| 310 |
svg_end = svg_content.rfind('</svg>')
|
| 311 |
if svg_start >= 0 and svg_end > svg_start:
|
| 312 |
svg_content = svg_content[svg_start:svg_end + 6]
|
| 313 |
elif svg_start >= 0:
|
| 314 |
+
svg_content += '</svg>'
|
| 315 |
+
else:
|
| 316 |
+
raise RuntimeError("No <svg> found in response")
|
|
|
|
|
|
|
| 317 |
|
| 318 |
(svg_dir / f"{name}.svg").write_text(svg_content, encoding="utf-8")
|
| 319 |
|
| 320 |
except Exception as e:
|
| 321 |
+
if progress_cb:
|
| 322 |
+
progress_cb(f" ⚠️ Slide {num} failed ({str(e)[:50]}), using fallback")
|
| 323 |
+
_write_fallback_svg(svg_dir, name, slide, colors, font_title, font_body, num, num_total, img_ref)
|
| 324 |
+
|
| 325 |
+
# Write notes
|
| 326 |
+
note = slide.get("notes", f"{slide['title']}. " + " ".join(slide.get("content", [])))
|
| 327 |
+
(notes_dir / f"{name}.md").write_text(note, encoding="utf-8")
|
| 328 |
+
total_notes.append(f"# {name}\n\n{note}")
|
| 329 |
+
|
| 330 |
+
# Write total.md
|
| 331 |
+
(notes_dir / "total.md").write_text("\n\n---\n\n".join(total_notes), encoding="utf-8")
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def _write_fallback_svg(svg_dir, name, slide, colors, font_title, font_body, num, total, img_ref):
|
| 335 |
+
"""Minimal fallback SVG."""
|
| 336 |
+
bg = colors.get("bg", "#0B0F17")
|
| 337 |
+
primary = colors.get("primary", "#C8A45D")
|
| 338 |
+
text = colors.get("text", "#E8E2D6")
|
| 339 |
+
muted = colors.get("text_secondary", "#AAB2C0")
|
| 340 |
title = slide["title"].replace('&','&').replace('<','<').replace('>','>')
|
| 341 |
content = slide.get("content", [])
|
| 342 |
|
| 343 |
lines = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720" width="1280" height="720">',
|
| 344 |
+
f' <rect width="1280" height="720" fill="{bg}"/>']
|
| 345 |
+
if img_ref:
|
| 346 |
+
href = img_ref.split('"')[1] if '"' in img_ref else ""
|
| 347 |
+
if href:
|
| 348 |
+
lines.append(f' <image href="{href}" x="680" y="60" width="540" height="600" preserveAspectRatio="xMidYMid slice"/>')
|
| 349 |
+
lines.append(f' <text x="60" y="90" font-family="{font_title}" font-size="36" font-weight="bold" fill="{text}">{title}</text>')
|
| 350 |
+
lines.append(f' <rect x="60" y="108" width="160" height="4" fill="{primary}"/>')
|
| 351 |
for j, p in enumerate(content[:6]):
|
| 352 |
+
y = 170 + j * 75
|
| 353 |
p_esc = p.replace('&','&').replace('<','<').replace('>','>')[:100]
|
| 354 |
+
lines.append(f' <text x="80" y="{y}" font-family="{font_body}" font-size="20" fill="{text}">{p_esc}</text>')
|
| 355 |
+
lines.append(f' <text x="1224" y="700" text-anchor="end" font-family="{font_body}" font-size="12" fill="{muted}">{num}/{total}</text>')
|
| 356 |
lines.append('</svg>')
|
| 357 |
(svg_dir / f"{name}.svg").write_text("\n".join(lines), encoding="utf-8")
|
| 358 |
|
| 359 |
|
| 360 |
+
# ============================================================
|
| 361 |
+
# STEP 4: POST-PROCESSING & EXPORT
|
| 362 |
+
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
+
def postprocess_and_export(project_path):
|
| 365 |
+
"""Run finalize_svg + svg_to_pptx."""
|
| 366 |
env = os.environ.copy()
|
| 367 |
|
| 368 |
# total_md_split
|
| 369 |
+
subprocess.run([sys.executable, str(SCRIPTS_DIR / "total_md_split.py"), project_path],
|
| 370 |
+
capture_output=True, text=True, timeout=60, cwd=str(SCRIPTS_DIR), env=env)
|
|
|
|
|
|
|
| 371 |
|
| 372 |
# finalize_svg
|
| 373 |
+
subprocess.run([sys.executable, str(SCRIPTS_DIR / "finalize_svg.py"), project_path],
|
| 374 |
+
capture_output=True, text=True, timeout=120, cwd=str(SCRIPTS_DIR), env=env)
|
|
|
|
|
|
|
| 375 |
|
| 376 |
# svg_to_pptx
|
| 377 |
+
result = subprocess.run([sys.executable, str(SCRIPTS_DIR / "svg_to_pptx.py"), project_path],
|
| 378 |
+
capture_output=True, text=True, timeout=180, cwd=str(SCRIPTS_DIR), env=env)
|
|
|
|
|
|
|
| 379 |
|
| 380 |
return result.stdout + result.stderr
|
| 381 |
|
| 382 |
|
| 383 |
# ============================================================
|
| 384 |
+
# GRADIO HANDLERS
|
| 385 |
# ============================================================
|
| 386 |
|
| 387 |
+
def step1_handler(subject, num_slides, style, language, audience, image_mode):
|
| 388 |
+
"""Strategist phase."""
|
| 389 |
if not subject.strip():
|
| 390 |
return "❌ Entre un sujet !", "", "{}"
|
|
|
|
| 391 |
try:
|
| 392 |
+
data = strategist_phase(subject, int(num_slides), style, language, audience)
|
| 393 |
+
preview = format_strategist_preview(data)
|
| 394 |
+
return f"✅ Design spec généré — {len(data.get('slides',[]))} slides", preview, json.dumps(data, ensure_ascii=False)
|
| 395 |
except Exception as e:
|
| 396 |
+
return f"❌ Erreur Strategist: {str(e)[:300]}", "", "{}"
|
| 397 |
|
| 398 |
|
| 399 |
+
def step2_handler(data_json, style, image_mode, progress=gr.Progress()):
|
| 400 |
+
"""Full generation pipeline."""
|
| 401 |
+
if not data_json or data_json == "{}":
|
| 402 |
return "❌ Génère d'abord le plan (étape 1)", None, ""
|
|
|
|
| 403 |
try:
|
| 404 |
+
data = json.loads(data_json)
|
| 405 |
except:
|
| 406 |
+
return "❌ Données invalides", None, ""
|
| 407 |
|
|
|
|
| 408 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 409 |
project_name = f"gradio_{timestamp}"
|
| 410 |
project_path = str(PROJECTS_DIR / project_name)
|
|
|
|
| 412 |
for d in ("svg_output", "svg_final", "images", "notes", "exports"):
|
| 413 |
os.makedirs(f"{project_path}/{d}", exist_ok=True)
|
| 414 |
|
| 415 |
+
num_slides = len(data.get("slides", []))
|
| 416 |
+
log = [f"📁 Projet: {project_name}", f"📊 {num_slides} slides à générer\n"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
|
| 418 |
+
# Phase 1: Images
|
| 419 |
+
progress(0.05, desc="Acquisition des images...")
|
| 420 |
+
log.append("━━━ PHASE 1: Images ━━━")
|
| 421 |
|
| 422 |
+
def img_cb(msg): log.append(f" {msg}")
|
| 423 |
+
acquire_images(data, project_path, image_mode, progress_cb=img_cb)
|
| 424 |
+
log.append(" ✅ Images acquises\n")
|
|
|
|
| 425 |
|
| 426 |
+
# Phase 2: Executor (SVG generation via LLM)
|
| 427 |
+
progress(0.2, desc=f"Génération SVG par LLM (0/{num_slides})...")
|
| 428 |
+
log.append("━━━ PHASE 2: Executor (SVG via LLM) ━━━")
|
| 429 |
+
log.append(f" ⏱️ Estimation: ~60-90s par slide, {num_slides} slides\n")
|
| 430 |
|
| 431 |
+
slide_count = [0]
|
| 432 |
+
def svg_cb(msg):
|
| 433 |
+
log.append(f" {msg}")
|
| 434 |
+
slide_count[0] += 1
|
| 435 |
+
frac = 0.2 + 0.6 * (slide_count[0] / (num_slides * 2))
|
| 436 |
+
progress(min(frac, 0.8), desc=f"SVG {slide_count[0]//2}/{num_slides}...")
|
| 437 |
|
| 438 |
+
executor_phase(data, project_path, style, progress_cb=svg_cb)
|
| 439 |
+
log.append(" ✅ Tous les SVG générés\n")
|
|
|
|
|
|
|
| 440 |
|
| 441 |
+
# Phase 3: Post-processing
|
| 442 |
+
progress(0.85, desc="Export PPTX...")
|
| 443 |
+
log.append("━━━ PHASE 3: Post-traitement & Export ━━━")
|
| 444 |
+
pp_out = postprocess_and_export(project_path)
|
| 445 |
+
log.append(f" {pp_out[:400]}")
|
| 446 |
|
| 447 |
+
# Find PPTX
|
| 448 |
pptx_files = glob.glob(f"{project_path}/exports/*.pptx")
|
| 449 |
if pptx_files:
|
| 450 |
pptx_path = pptx_files[0]
|
| 451 |
+
size_mb = Path(pptx_path).stat().st_size / 1024 / 1024
|
| 452 |
progress(1.0, desc="Terminé !")
|
| 453 |
+
log.append(f"\n✅ PPTX: {Path(pptx_path).name} ({size_mb:.1f} MB)")
|
| 454 |
+
return "✅ Présentation générée !", pptx_path, "\n".join(log)
|
|
|
|
| 455 |
else:
|
| 456 |
+
return "❌ Export échoué", None, "\n".join(log)
|
|
|
|
|
|
|
| 457 |
|
| 458 |
|
| 459 |
# ============================================================
|
| 460 |
+
# GRADIO UI
|
| 461 |
# ============================================================
|
| 462 |
|
| 463 |
STYLES = ["Dark Fantasy", "Corporate", "Tech / Startup", "Nature / Zen", "Académique", "Minimaliste"]
|
| 464 |
LANGUAGES = ["Français", "English", "Español", "Deutsch", "中文", "日本語"]
|
| 465 |
IMAGE_MODES = ["ComfyUI (local GPU)", "Recherche web (Wikimedia)", "Les deux (ComfyUI + web)", "Aucune image"]
|
| 466 |
|
| 467 |
+
with gr.Blocks(title="PPT Master — Générateur IA") as app:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
|
|
|
|
| 469 |
outline_state = gr.State("{}")
|
| 470 |
|
| 471 |
+
gr.Markdown("# 🎯 PPT Master — Générateur de Présentations IA")
|
| 472 |
+
gr.Markdown("*Workflow complet: Strategist → Images → Executor SVG → PPTX natif*")
|
|
|
|
| 473 |
|
| 474 |
with gr.Tabs():
|
| 475 |
+
with gr.Tab("1️⃣ Sujet & Design"):
|
|
|
|
| 476 |
with gr.Row():
|
| 477 |
with gr.Column(scale=2):
|
| 478 |
+
subject = gr.Textbox(label="📌 Sujet", placeholder="Ex: Game of Thrones, L'IA en 2025...", lines=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
with gr.Row():
|
| 480 |
+
num_slides = gr.Slider(5, 20, value=10, step=1, label="📄 Slides")
|
| 481 |
language = gr.Dropdown(LANGUAGES, value="Français", label="🌐 Langue")
|
|
|
|
| 482 |
with gr.Column(scale=1):
|
| 483 |
+
style = gr.Dropdown(STYLES, value="Dark Fantasy", label="🎨 Style")
|
| 484 |
+
audience = gr.Textbox(label="👥 Public", value="Grand public", placeholder="Ex: professionnels, étudiants...")
|
| 485 |
+
image_mode = gr.Dropdown(IMAGE_MODES, value="ComfyUI (local GPU)", label="🖼️ Images")
|
| 486 |
+
|
| 487 |
+
btn_plan = gr.Button("🧠 Générer le design spec (Strategist)", variant="primary", size="lg")
|
| 488 |
+
status1 = gr.Textbox(label="Statut", interactive=False)
|
| 489 |
+
gr.Markdown("### 📋 Design Spec & Plan")
|
| 490 |
+
preview = gr.Markdown(value="*Le design spec apparaîtra ici...*")
|
| 491 |
+
|
| 492 |
+
with gr.Tab("2️⃣ Générer le PPTX"):
|
| 493 |
+
gr.Markdown("### 🚀 Pipeline complet: Images + SVG (LLM) + Export")
|
| 494 |
+
gr.Markdown("⏱️ **Temps estimé**: ~2 min (images) + ~8-12 min (SVG par LLM) + ~30s (export)")
|
| 495 |
+
btn_gen = gr.Button("⚡ Lancer la génération complète", variant="primary", size="lg")
|
| 496 |
+
status2 = gr.Textbox(label="Statut", interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 497 |
with gr.Row():
|
| 498 |
+
log_box = gr.Textbox(label="📜 Log", lines=20, interactive=False)
|
| 499 |
+
pptx_out = gr.File(label="📥 Télécharger PPTX")
|
|
|
|
|
|
|
| 500 |
|
|
|
|
| 501 |
with gr.Tab("ℹ️ À propos"):
|
| 502 |
gr.Markdown("""
|
| 503 |
+
## Workflow PPT Master complet
|
| 504 |
|
| 505 |
+
1. **Strategist** → Génère design_spec + spec_lock (palette, typo, icônes, rythme)
|
| 506 |
+
2. **Image Acquisition** → ComfyUI GPU ou recherche web
|
| 507 |
+
3. **Executor** → Le LLM génère chaque SVG individuellement en respectant le spec_lock
|
| 508 |
+
4. **Post-processing** → finalize_svg.py (icônes, images, rounded rects)
|
| 509 |
+
5. **Export** → svg_to_pptx.py → PPTX natif éditable
|
| 510 |
|
| 511 |
+
**Qualité**: Chaque slide est conçue par le LLM avec dégradés, décorations, typographie variée.
|
| 512 |
+
Le spec_lock garantit la cohérence couleurs/fonts sur l'ensemble du deck.
|
|
|
|
|
|
|
| 513 |
|
| 514 |
+
**Stack**: OpenRouter (tencent/hy3-preview:free) + ComfyUI local (RTX 5070 Ti)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 515 |
""")
|
| 516 |
|
| 517 |
+
btn_plan.click(fn=step1_handler, inputs=[subject, num_slides, style, language, audience, image_mode],
|
| 518 |
+
outputs=[status1, preview, outline_state])
|
| 519 |
+
btn_gen.click(fn=step2_handler, inputs=[outline_state, style, image_mode],
|
| 520 |
+
outputs=[status2, pptx_out, log_box])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 521 |
|
| 522 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 523 |
if __name__ == "__main__":
|
| 524 |
+
app.launch(server_name="127.0.0.1", server_port=7860, share=False, inbrowser=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|