Albator2570 commited on
Commit
0f5e4e6
·
verified ·
1 Parent(s): 1ac4f62

V7 Ultimate Quality: Strategist + GPT-OSS Executor + HY3 Art Director + quality repair loop + original PPT Master gates

Browse files
Files changed (1) hide show
  1. interface/app_gradio.py +215 -15
interface/app_gradio.py CHANGED
@@ -62,7 +62,9 @@ def llm_chat(prompt, system=None, max_tokens=32000, temperature=0.3, model_overr
62
 
63
  # Model selection: use the best model for each task
64
  MODEL_STRATEGIST = "tencent/hy3-preview:free" # Good at planning/reasoning
65
- MODEL_EXECUTOR = "openai/gpt-oss-120b:free" # Best at SVG code generation (fast + high quality)
 
 
66
 
67
 
68
  # ============================================================
@@ -177,6 +179,75 @@ def format_strategist_preview(data):
177
  return "\n".join(lines)
178
 
179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  # ============================================================
181
  # STEP 2: IMAGE ACQUISITION
182
  # ============================================================
@@ -228,6 +299,119 @@ def acquire_images(data, project_path, image_mode, progress_cb=None):
228
  progress_cb(f" ⚠️ Web search failed: {str(e)[:60]}")
229
 
230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  # ============================================================
232
  # STEP 3: EXECUTOR — LLM generates each SVG sequentially
233
  # ============================================================
@@ -325,17 +509,19 @@ Reply with ONLY the SVG. Start <svg, end </svg>. No explanation."""
325
  try:
326
  svg_content = llm_chat(prompt, max_tokens=10000, temperature=0.3, model_override=MODEL_EXECUTOR)
327
 
328
- # Extract SVG
329
- svg_start = svg_content.find('<svg')
330
- svg_end = svg_content.rfind('</svg>')
331
- if svg_start >= 0 and svg_end > svg_start:
332
- svg_content = svg_content[svg_start:svg_end + 6]
333
- elif svg_start >= 0:
334
- svg_content += '</svg>'
335
- else:
336
- raise RuntimeError("No <svg> found in response")
 
337
 
338
- (svg_dir / f"{name}.svg").write_text(svg_content, encoding="utf-8")
 
339
 
340
  except Exception as e:
341
  if progress_cb:
@@ -382,22 +568,32 @@ def _write_fallback_svg(svg_dir, name, slide, colors, font_title, font_body, num
382
  # ============================================================
383
 
384
  def postprocess_and_export(project_path):
385
- """Run finalize_svg + svg_to_pptx."""
386
  env = os.environ.copy()
387
 
 
 
 
 
 
 
 
388
  # total_md_split
389
- subprocess.run([sys.executable, str(SCRIPTS_DIR / "total_md_split.py"), project_path],
390
  capture_output=True, text=True, timeout=60, cwd=str(SCRIPTS_DIR), env=env)
 
391
 
392
  # finalize_svg
393
- subprocess.run([sys.executable, str(SCRIPTS_DIR / "finalize_svg.py"), project_path],
394
  capture_output=True, text=True, timeout=120, cwd=str(SCRIPTS_DIR), env=env)
 
395
 
396
  # svg_to_pptx
397
  result = subprocess.run([sys.executable, str(SCRIPTS_DIR / "svg_to_pptx.py"), project_path],
398
  capture_output=True, text=True, timeout=180, cwd=str(SCRIPTS_DIR), env=env)
 
399
 
400
- return result.stdout + result.stderr
401
 
402
 
403
  # ============================================================
@@ -435,6 +631,10 @@ def step2_handler(data_json, style, image_mode, progress=gr.Progress()):
435
  num_slides = len(data.get("slides", []))
436
  log = [f"📁 Projet: {project_name}", f"📊 {num_slides} slides à générer\n"]
437
 
 
 
 
 
438
  # Phase 1: Images
439
  progress(0.05, desc="Acquisition des images...")
440
  log.append("━━━ PHASE 1: Images ━━━")
 
62
 
63
  # Model selection: use the best model for each task
64
  MODEL_STRATEGIST = "tencent/hy3-preview:free" # Good at planning/reasoning
65
+ MODEL_EXECUTOR = "openai/gpt-oss-120b:free" # Best tested free model for SVG code generation
66
+ MODEL_CRITIC = "tencent/hy3-preview:free" # Good visual/design critic and instruction follower
67
+ MODEL_FALLBACK_EXECUTOR = "tencent/hy3-preview:free" # Fallback if GPT-OSS is rate-limited
68
 
69
 
70
  # ============================================================
 
179
  return "\n".join(lines)
180
 
181
 
182
+
183
+
184
+ def write_project_specs(data, project_path):
185
+ """Write design_spec.md and spec_lock.md like original PPT Master so quality checker can enforce drift."""
186
+ project = Path(project_path)
187
+ spec = data.get("spec_lock", {})
188
+ colors = spec.get("colors", {})
189
+ typo = spec.get("typography", {})
190
+ icons = spec.get("icons", {})
191
+ rhythms = spec.get("page_rhythm", {})
192
+
193
+ design_lines = [f"# {data.get('title','Presentation')} - Design Spec", "", "## I. Project Information", "", f"- Canvas Format: PPT 16:9 (1280×720)", f"- Page Count: {len(data.get('slides', []))}", "- Design Style: AI-generated via PPT Master full workflow", "", "## III. Visual Theme", ""]
194
+ for k,v in colors.items():
195
+ design_lines.append(f"- {k}: `{v}`")
196
+ design_lines += ["", "## IV. Typography", ""]
197
+ for k,v in typo.items():
198
+ design_lines.append(f"- {k}: {v}")
199
+ design_lines += ["", "## IX. Content Outline", ""]
200
+ for sl in data.get('slides', []):
201
+ design_lines.append(f"### Slide {sl.get('number'):02d} - {sl.get('title')}")
202
+ for pt in sl.get('content', []):
203
+ design_lines.append(f"- {pt}")
204
+ design_lines.append("")
205
+ (project / "design_spec.md").write_text("\n".join(design_lines), encoding="utf-8")
206
+
207
+ lock = ["# Execution Lock", "", "## canvas", "- viewBox: 0 0 1280 720", "- format: PPT 16:9", "", "## colors"]
208
+ for k,v in colors.items():
209
+ lock.append(f"- {k}: {v}")
210
+ # Add common colors used by gradients/overlays if not present
211
+ for k,v in {"black":"#000000", "white":"#FFFFFF"}.items():
212
+ if k not in colors:
213
+ lock.append(f"- {k}: {v}")
214
+ lock += ["", "## typography"]
215
+ if "font_family" not in typo:
216
+ lock.append(f"- font_family: {typo.get('body_family','Arial, sans-serif')}")
217
+ for k,v in typo.items():
218
+ lock.append(f"- {k}: {v}")
219
+ lock += ["", "## icons", f"- library: {icons.get('library','chunk-filled')}", f"- inventory: {', '.join(icons.get('inventory', []))}", "", "## images"]
220
+ for sl in data.get('slides', []):
221
+ n = int(sl.get('number', 0))
222
+ lock.append(f"- slide_{n:02d}: images/slide_{n:02d}.png")
223
+ lock.append(f"- slide_{n:02d}_jpg: images/slide_{n:02d}.jpg")
224
+ lock += ["", "## page_rhythm"]
225
+ for sl in data.get('slides', []):
226
+ key=f"P{int(sl.get('number',0)):02d}"
227
+ lock.append(f"- {key}: {sl.get('rhythm') or rhythms.get(key,'dense')}")
228
+ lock += ["", "## forbidden", "- Mixing icon libraries", "- rgba()", "- <style>, class, <foreignObject>, textPath, @font-face, <animate*>, <script>, <iframe>, <symbol>+<use>", "- <g opacity>", "- HTML named entities"]
229
+ (project / "spec_lock.md").write_text("\n".join(lock), encoding="utf-8")
230
+
231
+
232
+ def check_and_repair_svg(project_path, svg_path, slide, spec_summary, progress_cb=None):
233
+ """Run svg_quality_checker and repair with LLM if errors are found."""
234
+ try:
235
+ result = subprocess.run([sys.executable, str(SCRIPTS_DIR / "svg_quality_checker.py"), project_path], capture_output=True, text=True, timeout=120, cwd=str(SCRIPTS_DIR))
236
+ out = result.stdout + result.stderr
237
+ # If this specific file has errors, repair once
238
+ if "[ERROR]" in out and Path(svg_path).name in out:
239
+ if progress_cb:
240
+ progress_cb(f" 🔧 Réparation qualité: {Path(svg_path).name}")
241
+ svg = Path(svg_path).read_text(encoding="utf-8")
242
+ fixed = _repair_svg_with_llm(svg, out, slide, spec_summary)
243
+ Path(svg_path).write_text(fixed, encoding="utf-8")
244
+ # second check, no infinite loop
245
+ return True
246
+ except Exception as e:
247
+ if progress_cb:
248
+ progress_cb(f" ⚠️ Quality check skipped: {str(e)[:50]}")
249
+ return False
250
+
251
  # ============================================================
252
  # STEP 2: IMAGE ACQUISITION
253
  # ============================================================
 
299
  progress_cb(f" ⚠️ Web search failed: {str(e)[:60]}")
300
 
301
 
302
+
303
+ # ============================================================
304
+ # PREMIUM DESIGN SYSTEM — distilled from original PPT Master examples
305
+ # ============================================================
306
+
307
+ PREMIUM_EXEMPLAR_COVER = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
308
+ <defs>
309
+ <linearGradient id="coverOverlay" x1="0" y1="0" x2="0" y2="1">
310
+ <stop offset="0%" stop-color="#0A0A0A" stop-opacity="0.25"/>
311
+ <stop offset="40%" stop-color="#0A0A0A" stop-opacity="0.45"/>
312
+ <stop offset="75%" stop-color="#0A0A0A" stop-opacity="0.82"/>
313
+ <stop offset="100%" stop-color="#0A0A0A" stop-opacity="0.95"/>
314
+ </linearGradient>
315
+ <linearGradient id="goldLine" x1="0" y1="0" x2="1" y2="0">
316
+ <stop offset="0%" stop-color="#C9A96E" stop-opacity="0"/>
317
+ <stop offset="20%" stop-color="#C9A96E" stop-opacity="1"/>
318
+ <stop offset="80%" stop-color="#E8D5B5" stop-opacity="1"/>
319
+ <stop offset="100%" stop-color="#E8D5B5" stop-opacity="0"/>
320
+ </linearGradient>
321
+ </defs>
322
+ <image href="../images/slide_01.png" x="0" y="0" width="1280" height="720" preserveAspectRatio="xMidYMid slice"/>
323
+ <rect width="1280" height="720" fill="url(#coverOverlay)"/>
324
+ <text x="50" y="35" font-family="Georgia, serif" font-size="11" fill="#C9A96E" fill-opacity="0.7" letter-spacing="3">SECTION LABEL</text>
325
+ <rect x="440" y="500" width="400" height="1.5" fill="url(#goldLine)"/>
326
+ </svg>"""
327
+
328
+ PREMIUM_EXEMPLAR_CONTENT = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720" width="1280" height="720">
329
+ <defs>
330
+ <radialGradient id="glow" cx="50%" cy="35%" r="50%">
331
+ <stop offset="0%" stop-color="#D4A574" stop-opacity="0.06"/>
332
+ <stop offset="100%" stop-color="#D4A574" stop-opacity="0"/>
333
+ </radialGradient>
334
+ <filter id="statGlow" x="-30%" y="-30%" width="160%" height="160%">
335
+ <feGaussianBlur in="SourceAlpha" stdDeviation="6" result="blur"/>
336
+ <feFlood flood-color="#D4A574" flood-opacity="0.4" result="glowColor"/>
337
+ <feComposite in="glowColor" in2="blur" operator="in" result="glow"/>
338
+ <feMerge><feMergeNode in="glow"/><feMergeNode in="SourceGraphic"/></feMerge>
339
+ </filter>
340
+ </defs>
341
+ <rect width="1280" height="720" fill="#0D1117"/>
342
+ <rect width="1280" height="720" fill="url(#glow)"/>
343
+ <g id="header"><rect x="60" y="50" width="4" height="30" fill="#D4A574"/><text x="76" y="75" font-size="14" fill="#8B949E" letter-spacing="3">THE PROBLEM</text></g>
344
+ <g id="hero-stat"><text x="640" y="260" text-anchor="middle" font-size="120" font-weight="bold" fill="#D4A574" filter="url(#statGlow)">93%</text></g>
345
+ <rect x="180" y="580" width="920" height="60" rx="8" fill="#161B22" stroke="#30363D" stroke-width="1"/>
346
+ </svg>"""
347
+
348
+ def _extract_svg(text: str) -> str:
349
+ """Extract clean SVG code from an LLM response."""
350
+ if not text:
351
+ raise RuntimeError("Empty SVG response")
352
+ text = text.replace('```svg', '').replace('```xml', '').replace('```', '').strip()
353
+ start = text.find('<svg')
354
+ end = text.rfind('</svg>')
355
+ if start >= 0 and end > start:
356
+ return text[start:end+6]
357
+ if start >= 0:
358
+ return text[start:] + '\n</svg>'
359
+ raise RuntimeError("No <svg> found")
360
+
361
+ def _design_critique_and_improve(svg: str, slide: dict, spec_summary: str) -> str:
362
+ """Second-pass design critic: ask a different model to improve visual quality while preserving validity."""
363
+ prompt = f"""You are a senior presentation art director and SVG engineer. Improve this SVG slide to look more premium and closer to high-end PPT Master examples.
364
+
365
+ Slide title: {slide.get('title')}
366
+ Spec: {spec_summary}
367
+
368
+ Improve ONLY if useful:
369
+ - stronger hierarchy, better spacing, more premium gradients/overlays
370
+ - better image/text composition
371
+ - add subtle glow/filter/letter-spacing/accent lines/cards if missing
372
+ - keep all existing content and image hrefs
373
+ - keep SVG valid and PPT-safe
374
+
375
+ Hard constraints:
376
+ - NO <style>, class, foreignObject, mask, animate, script, rgba(), @font-face
377
+ - keep viewBox 0 0 1280 720
378
+ - return ONLY final SVG code
379
+
380
+ SVG to improve:
381
+ {svg}
382
+ """
383
+ try:
384
+ improved = llm_chat(prompt, max_tokens=12000, temperature=0.25, model_override=MODEL_CRITIC)
385
+ improved = _extract_svg(improved)
386
+ # Basic guard: only accept if still substantial and has svg end
387
+ if len(improved) > max(800, int(len(svg) * 0.6)) and '</svg>' in improved:
388
+ return improved
389
+ except Exception:
390
+ return svg
391
+ return svg
392
+
393
+ def _repair_svg_with_llm(svg: str, checker_output: str, slide: dict, spec_summary: str) -> str:
394
+ """Ask executor model to repair SVG according to quality checker output."""
395
+ prompt = f"""Repair this SVG so it passes PPT Master svg_quality_checker.py.
396
+
397
+ Slide: {slide.get('title')}
398
+ Spec: {spec_summary}
399
+ Checker output/errors:
400
+ {checker_output[:3000]}
401
+
402
+ Hard constraints:
403
+ - Preserve design and all content
404
+ - NO <style>, class, foreignObject, mask, animate, script, rgba(), @font-face
405
+ - inline attributes only
406
+ - valid XML
407
+ - return ONLY SVG
408
+
409
+ SVG:
410
+ {svg}
411
+ """
412
+ fixed = llm_chat(prompt, max_tokens=12000, temperature=0.2, model_override=MODEL_EXECUTOR)
413
+ return _extract_svg(fixed)
414
+
415
  # ============================================================
416
  # STEP 3: EXECUTOR — LLM generates each SVG sequentially
417
  # ============================================================
 
509
  try:
510
  svg_content = llm_chat(prompt, max_tokens=10000, temperature=0.3, model_override=MODEL_EXECUTOR)
511
 
512
+ svg_content = _extract_svg(svg_content)
513
+
514
+ # Art Director second pass: improve composition/visual polish (slow but high quality)
515
+ spec_summary = f"colors={color_str}; fonts title={font_title}, body={font_body}; icons={icon_lib}: {icon_inv}"
516
+ if progress_cb:
517
+ progress_cb(f" 🎭 Art Director polish {num}/{num_total}...")
518
+ svg_content = _design_critique_and_improve(svg_content, slide, spec_summary)
519
+
520
+ svg_path = svg_dir / f"{name}.svg"
521
+ svg_path.write_text(svg_content, encoding="utf-8")
522
 
523
+ # Quality gate repair, one pass
524
+ check_and_repair_svg(project_path, svg_path, slide, spec_summary, progress_cb=progress_cb)
525
 
526
  except Exception as e:
527
  if progress_cb:
 
568
  # ============================================================
569
 
570
  def postprocess_and_export(project_path):
571
+ """Run quality check + finalize_svg + svg_to_pptx."""
572
  env = os.environ.copy()
573
 
574
+ outputs = []
575
+
576
+ # final quality check before finalize (original PPT Master gate)
577
+ qc = subprocess.run([sys.executable, str(SCRIPTS_DIR / "svg_quality_checker.py"), project_path],
578
+ capture_output=True, text=True, timeout=120, cwd=str(SCRIPTS_DIR), env=env)
579
+ outputs.append(qc.stdout + qc.stderr)
580
+
581
  # total_md_split
582
+ tms = subprocess.run([sys.executable, str(SCRIPTS_DIR / "total_md_split.py"), project_path],
583
  capture_output=True, text=True, timeout=60, cwd=str(SCRIPTS_DIR), env=env)
584
+ outputs.append(tms.stdout + tms.stderr)
585
 
586
  # finalize_svg
587
+ fin = subprocess.run([sys.executable, str(SCRIPTS_DIR / "finalize_svg.py"), project_path],
588
  capture_output=True, text=True, timeout=120, cwd=str(SCRIPTS_DIR), env=env)
589
+ outputs.append(fin.stdout + fin.stderr)
590
 
591
  # svg_to_pptx
592
  result = subprocess.run([sys.executable, str(SCRIPTS_DIR / "svg_to_pptx.py"), project_path],
593
  capture_output=True, text=True, timeout=180, cwd=str(SCRIPTS_DIR), env=env)
594
+ outputs.append(result.stdout + result.stderr)
595
 
596
+ return "\n".join(outputs)
597
 
598
 
599
  # ============================================================
 
631
  num_slides = len(data.get("slides", []))
632
  log = [f"📁 Projet: {project_name}", f"📊 {num_slides} slides à générer\n"]
633
 
634
+ # Write design_spec.md and spec_lock.md like the original PPT Master workflow
635
+ write_project_specs(data, project_path)
636
+ log.append("🧭 design_spec.md + spec_lock.md écrits\n")
637
+
638
  # Phase 1: Images
639
  progress(0.05, desc="Acquisition des images...")
640
  log.append("━━━ PHASE 1: Images ━━━")