Albator2570 commited on
Commit
82e2e7e
·
verified ·
1 Parent(s): 931a703

V5: Full PPT Master workflow — Strategist + spec_lock + Executor LLM SVG + finalize + export

Browse files
Files changed (1) hide show
  1. 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
- Génère des présentations PowerPoint via LLM (OpenRouter) + images (ComfyUI/Web).
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, resolve_env_path
27
 
28
  # Load env
29
  load_prefixed_env_file(("OPENROUTER_", "COMFYUI_", "IMAGE_", "PEXELS_", "PIXABAY_"))
30
 
31
  # ============================================================
32
- # LLM Client (OpenRouter)
33
  # ============================================================
34
 
35
- def llm_chat(prompt, system=None, max_tokens=16000, temperature=0.4):
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
- r = requests.post(
51
- f"{base_url}/chat/completions",
52
- headers={
53
- "Authorization": f"Bearer {api_key}",
54
- "Content-Type": "application/json",
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: {json.dumps(data, ensure_ascii=False)[:500]}")
73
  return content
74
 
75
 
76
  # ============================================================
77
- # Pipeline Functions
78
  # ============================================================
79
 
80
- def generate_outline(subject, num_slides, style, language, audience, image_mode):
81
- """Step 1: Ask LLM to generate the slide outline."""
82
-
83
- prompt = f"""Generate a {num_slides}-slide presentation about "{subject}". Style: {style}. Language: {language}. Audience: {audience}.
84
- Reply ONLY raw JSON: {{"title":"...","slides":[{{"number":1,"title":"...","content":["point1","point2","point3"],"image_prompt":"english cinematic description","layout":"cover"}}]}}
85
- Layouts: cover(1st), content, comparison, timeline, closing(last).
86
- IMPORTANT: Keep each content point SHORT (max 20 words). Keep image_prompt under 30 words. No text in images."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  result = llm_chat(prompt, max_tokens=32000)
89
 
90
- # Extract JSON from response
91
  try:
92
- # Try to find JSON in the response
93
  json_match = re.search(r'\{[\s\S]*\}', result)
94
  if json_match:
95
- outline = json.loads(json_match.group())
96
  else:
97
- outline = json.loads(result)
98
- except json.JSONDecodeError as e:
99
- # Try to repair truncated JSON by closing brackets
100
- repaired = result.rstrip()
101
- # Remove trailing incomplete values
102
- for _ in range(10):
103
  try:
104
- # Try adding closing brackets
105
- for fix in ['}]}', '"}]}', '"]},{"number":99,"title":"FIN","content":[""],"image_prompt":"","layout":"closing"}]}']:
106
- try:
107
- test = repaired + fix
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
- break
124
- raise RuntimeError(f"Le LLM n'a pas retourné du JSON valide.\n\nRéponse:\n{result[:2000]}")
 
 
 
 
125
 
126
- return outline
 
 
127
 
 
 
 
128
 
129
- def outline_to_preview(outline):
130
- """Convert outline dict to readable markdown preview."""
131
- lines = [f"# {outline['title']}\n"]
132
- for slide in outline.get("slides", []):
133
- lines.append(f"## Slide {slide['number']}: {slide['title']}")
134
- lines.append(f"*Layout: {slide.get('layout', 'content')}*\n")
135
- for point in slide.get("content", []):
136
- lines.append(f"- {point}")
 
 
 
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
- def generate_images(outline, project_path, image_mode, progress_callback=None):
144
- """Generate images for each slide."""
 
 
 
 
145
  images_dir = Path(project_path) / "images"
146
  images_dir.mkdir(parents=True, exist_ok=True)
147
 
148
- for i, slide in enumerate(outline.get("slides", [])):
 
149
  prompt = slide.get("image_prompt", "")
150
  if not prompt:
151
  continue
152
-
153
  filename = f"slide_{slide['number']:02d}"
154
 
155
- if progress_callback:
156
- progress_callback(f"🖼️ Image {i+1}/{len(outline['slides'])}: {prompt[:60]}...")
 
 
 
 
 
 
 
 
157
 
158
- if image_mode == "ComfyUI (local GPU)":
159
  try:
160
- result = subprocess.run(
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=120,
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
- print(f" [WARN] Image generation error: {e}")
172
-
173
- elif image_mode == "Recherche web (Wikimedia)":
174
  try:
175
- result = subprocess.run(
176
  [sys.executable, str(SCRIPTS_DIR / "image_search.py"),
177
  prompt, "--filename", f"{filename}.jpg",
178
- "--orientation", "landscape",
179
- "-o", str(images_dir)],
180
- capture_output=True, text=True, timeout=60,
181
- cwd=str(SCRIPTS_DIR)
182
- )
183
  except Exception as e:
184
- print(f" [WARN] Image search error: {e}")
185
-
186
- elif image_mode == "Les deux (ComfyUI + web)":
187
- # Alternate between comfyui and web
188
- if i % 2 == 0:
189
- try:
190
- subprocess.run(
191
- [sys.executable, str(SCRIPTS_DIR / "image_gen.py"),
192
- prompt, "--backend", "comfyui",
193
- "--aspect_ratio", "16:9", "--image_size", "1K",
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
- # Style color palettes
221
- palettes = {
222
- "Dark Fantasy": "Dark background gradient (#0B0F17 to #111827), gold accent #C8A45D, red #8B1E2D, ice blue #6FA8B8, light text #E8E2D6, muted #AAB2C0",
223
- "Corporate": "White background #FFFFFF, blue primary #1A56DB, red accent #E02424, dark text #1F2937, clean professional",
224
- "Tech / Startup": "Dark navy background #0F172A to #1E293B, cyan #06B6D4, purple accent #8B5CF6, light text #F1F5F9",
225
- "Nature / Zen": "Warm white #FEFDF8, green primary #2D5016, amber accent #B45309, dark text #1C1917, organic soft",
226
- "Académique": "Cream background #FFFBF5, burgundy #7C2D12, blue accent #1E40AF, dark text, scholarly elegant",
227
- "Minimaliste": "Pure white #FFFFFF, black primary #18181B, red accent #DC2626, maximum whitespace, ultra clean",
228
- }
229
- palette_desc = palettes.get(style, palettes["Dark Fantasy"])
230
-
231
- num_slides = len(outline.get("slides", []))
232
-
233
- for slide in outline.get("slides", []):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  num = slide["number"]
235
  name = f"slide_{num:02d}"
236
 
237
- if progress_callback:
238
- progress_callback(f"🎨 SVG {num}/{num_slides}: {slide['title'][:50]}...")
239
 
240
- # Find image for this slide
241
  img_ref = ""
242
  for ext in ('.png', '.jpg', '.jpeg', '.webp'):
243
- candidate = images_dir / f"{name}{ext}"
244
- if candidate.exists():
245
- img_ref = f'Include this image: <image href="../images/{name}{ext}" preserveAspectRatio="xMidYMid slice"/>'
246
  break
247
 
248
- content_text = "\n".join(f"- {p}" for p in slide.get("content", []))
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
- {img_ref}
258
 
259
- Color palette: {palette_desc}
260
- Fonts: Georgia, Times New Roman, serif for titles. Arial, sans-serif for body text.
 
 
 
 
 
261
 
262
- Design rules:
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
- Reply with ONLY the SVG code. Start with <svg, end with </svg>."""
 
 
 
 
 
275
 
276
  try:
277
  svg_content = llm_chat(prompt, max_tokens=8000, temperature=0.3)
278
 
279
- # Clean up: extract just the SVG
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 = svg_content[svg_start:] + '</svg>'
286
-
287
- # Basic validation
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
- # Fallback: simple template SVG if LLM fails
295
- if progress_callback:
296
- progress_callback(f" ⚠️ LLM failed for slide {num}, using fallback: {str(e)[:60]}")
297
- _fallback_svg(svg_dir, name, slide, style, img_ref, num, num_slides)
298
-
299
-
300
- def _fallback_svg(svg_dir, name, slide, style, img_ref, num, total):
301
- """Simple fallback SVG when LLM generation fails."""
302
- palettes = {
303
- "Dark Fantasy": ('#0B0F17','#111827','#C8A45D','#E8E2D6','#AAB2C0','#344052'),
304
- "Corporate": ('#FFFFFF','#F4F6F9','#1A56DB','#1F2937','#6B7280','#E5E7EB'),
305
- "Tech / Startup": ('#0F172A','#1E293B','#06B6D4','#F1F5F9','#94A3B8','#334155'),
306
- "Nature / Zen": ('#FEFDF8','#F0EDE4','#2D5016','#1C1917','#78716C','#D6D3D1'),
307
- "Académique": ('#FFFBF5','#F5F0E8','#7C2D12','#1C1917','#57534E','#D6D3D1'),
308
- "Minimaliste": ('#FFFFFF','#FAFAFA','#18181B','#18181B','#71717A','#E4E4E7'),
309
- }
310
- bg, bg2, primary, text, muted, border = palettes.get(style, palettes["Dark Fantasy"])
 
 
311
  title = slide["title"].replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')
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
- f' <text x="60" y="90" font-family="Georgia, Times New Roman, serif" font-size="36" font-weight="bold" fill="{text}">{title}</text>',
317
- f' <rect x="60" y="108" width="160" height="4" fill="{primary}"/>']
 
 
 
 
318
  for j, p in enumerate(content[:6]):
319
- y = 180 + j * 80
320
  p_esc = p.replace('&','&amp;').replace('<','&lt;').replace('>','&gt;')[:100]
321
- lines.append(f' <text x="80" y="{y}" font-family="Arial, sans-serif" font-size="20" fill="{text}">{p_esc}</text>')
322
- lines.append(f' <text x="1224" y="700" text-anchor="end" font-family="Arial, sans-serif" font-size="12" fill="{muted}">{num}/{total}</text>')
323
  lines.append('</svg>')
324
  (svg_dir / f"{name}.svg").write_text("\n".join(lines), encoding="utf-8")
325
 
326
 
327
- def generate_notes(outline, project_path):
328
- """Generate speaker notes."""
329
- notes_dir = Path(project_path) / "notes"
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 run_postprocessing(project_path):
343
- """Run the PPT Master post-processing pipeline."""
344
  env = os.environ.copy()
345
 
346
  # total_md_split
347
- subprocess.run(
348
- [sys.executable, str(SCRIPTS_DIR / "total_md_split.py"), project_path],
349
- capture_output=True, text=True, timeout=60, cwd=str(SCRIPTS_DIR), env=env
350
- )
351
 
352
  # finalize_svg
353
- subprocess.run(
354
- [sys.executable, str(SCRIPTS_DIR / "finalize_svg.py"), project_path],
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
- [sys.executable, str(SCRIPTS_DIR / "svg_to_pptx.py"), project_path],
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
- # Main Gradio Pipeline
369
  # ============================================================
370
 
371
- def step1_generate_outline(subject, num_slides, style, language, audience, image_mode):
372
- """Generate and preview the outline."""
373
  if not subject.strip():
374
  return "❌ Entre un sujet !", "", "{}"
375
-
376
  try:
377
- outline = generate_outline(subject, num_slides, style, language, audience, image_mode)
378
- preview = outline_to_preview(outline)
379
- return f"✅ Plan généré avec succès — {len(outline.get('slides', []))} slides", preview, json.dumps(outline, ensure_ascii=False)
380
  except Exception as e:
381
- return f"❌ Erreur: {str(e)}", "", "{}"
382
 
383
 
384
- def step2_generate_pptx(outline_json, style, image_mode, progress=gr.Progress()):
385
- """Full pipeline: images → SVG → PPTX."""
386
- if not outline_json or outline_json == "{}":
387
  return "❌ Génère d'abord le plan (étape 1)", None, ""
388
-
389
  try:
390
- outline = json.loads(outline_json)
391
  except:
392
- return "❌ Plan invalide", None, ""
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
- log_lines = [f"📁 Projet: {project_name}\n"]
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
- generate_images(outline, project_path, image_mode, progress_callback=img_progress)
413
- log_lines.append(f" Images terminées\n")
 
414
 
415
- # Step B: Generate SVGs via LLM (high quality)
416
- progress(0.3, desc="Création des slides SVG via LLM (peut prendre plusieurs minutes)...")
417
- log_lines.append("🎨 Génération SVG par le LLM (qualité haute)...")
418
- log_lines.append(f" ⏱️ ~60-90s par slide, {num_slides} slides à générer...")
419
 
420
- def svg_progress(msg):
421
- log_lines.append(f" {msg}")
 
 
422
 
423
- generate_svgs(outline, project_path, style, progress_callback=svg_progress)
424
- log_lines.append(f" ✅ {num_slides} SVG générés\n")
 
 
 
 
425
 
426
- # Step C: Generate notes
427
- progress(0.6, desc="Notes orateur...")
428
- generate_notes(outline, project_path)
429
- log_lines.append("📝 Notes orateur générées\n")
430
 
431
- # Step D: Post-processing & export
432
- progress(0.7, desc="Export PPTX...")
433
- log_lines.append("📦 Post-traitement et export PPTX...")
434
- pp_output = run_postprocessing(project_path)
435
- log_lines.append(f" {pp_output[:500]}\n")
436
 
437
- # Find the exported PPTX
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
- log_lines.append(f"\n✅ PPTX généré: {Path(pptx_path).name}")
443
- log_lines.append(f" Taille: {Path(pptx_path).stat().st_size / 1024 / 1024:.1f} MB")
444
- return "✅ Présentation générée avec succès !", pptx_path, "\n".join(log_lines)
445
  else:
446
- progress(1.0, desc="Erreur")
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
- # Gradio Interface
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
- # Header
472
- gr.Markdown("# 🎯 PPT Master Générateur de Présentations IA", elem_classes="main-title")
473
- gr.Markdown("*OpenRouter LLM + ComfyUI local + export PowerPoint natif*", elem_classes="subtitle")
474
 
475
  with gr.Tabs():
476
- # ─── TAB 1: Configuration & Planification ───
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="📄 Nombre de slides")
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 visuel")
491
- audience = gr.Textbox(label="👥 Public cible", value="Grand public, curieux", placeholder="Ex: professionnels, étudiants...")
492
- image_mode = gr.Dropdown(IMAGE_MODES, value="ComfyUI (local GPU)", label="🖼️ Source d'images")
493
-
494
- btn_outline = gr.Button("🧠 Générer le plan (LLM)", variant="primary", size="lg")
495
- status_outline = gr.Textbox(label="Statut", interactive=False)
496
-
497
- gr.Markdown("### 📋 Aperçu du plan généré")
498
- outline_preview = gr.Markdown(label="Plan", value="*Le plan apparaîtra ici après génération...*")
499
-
500
- # ─── TAB 2: Génération ───
501
- with gr.Tab("2 Générer le PPTX", id="tab2"):
502
- gr.Markdown("### 🚀 Lancer la génération complète")
503
- gr.Markdown("Cliquer sur le bouton ci-dessous pour générer les images, créer les slides et exporter le PowerPoint.")
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
- with gr.Column():
510
- log_output = gr.Textbox(label="📜 Log de génération", lines=15, interactive=False)
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 — Interface Gradio
518
 
519
- **Stack technique:**
520
- - 🧠 **LLM**: OpenRouter tencent/hy3-preview:free (gratuit)
521
- - 🖼️ **Images**: ComfyUI local (RTX 5070 Ti) ou recherche web (Wikimedia/Openverse)
522
- - 📊 **Export**: PPT Master pipeline (SVG DrawingML → PPTX natif éditable)
 
523
 
524
- **Comment ça marche:**
525
- 1. Tu entres un sujet le LLM génère un plan structuré (titres, contenu, prompts image)
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
- **Configuration:**
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
- # ─── Event handlers ───
539
- btn_outline.click(
540
- fn=step1_generate_outline,
541
- inputs=[subject, num_slides, style, language, audience, image_mode],
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('&','&amp;').replace('<','&lt;').replace('>','&gt;')
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('&','&amp;').replace('<','&lt;').replace('>','&gt;')[: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)