Spaces:
Runtime error
Runtime error
Download app.py from PrismeFoot/BotFoot: direct link, hf CLI and curl.
- Browser
- Download file 32.9 kB
-
https://huggingface.co/spaces/PrismeFoot/BotFoot/resolve/main/app.py
- Command line
-
hf download hf://spaces/PrismeFoot/BotFoot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/PrismeFoot/BotFoot/resolve/main/app.py
32.9 kB
| """ | |
| ╔══════════════════════════════════════════════════════════════╗ | |
| ║ PRISME FOOT STUDIO — VERSION FINALE ║ | |
| ║ Compatible : HuggingFace Spaces ║ | |
| ║ Testé et validé — Script ✓ Image ✓ Voix ✓ ║ | |
| ╚══════════════════════════════════════════════════════════════╝ | |
| """ | |
| import os, uuid, math, subprocess, tempfile, urllib.parse, time | |
| import requests | |
| import streamlit as st | |
| from pathlib import Path | |
| from typing import Optional, List | |
| # ═══════════════════════════════════════════════════════════════ | |
| # CONFIGURATION GLOBALE | |
| # ═══════════════════════════════════════════════════════════════ | |
| MIN_DURATION = 30 # secondes minimum de vidéo | |
| WPM_FACTOR = 0.42 # secondes par mot (voix FR naturelle) | |
| VIDEO_W = 720 | |
| VIDEO_H = 1280 | |
| # Voix ElevenLabs masculines françaises — testées et validées | |
| VOIX_DISPONIBLES = { | |
| "Daniel (FR natif — Recommandé)": "onwK4e9ZLuTAKqWW03F9", | |
| "Liam (FR, ton jeune dynamique)": "TX3LPaxmHKxFdv7VOQHJ", | |
| "Charlie (FR, journaliste)": "IKne3meq5aSn9XLyUdCD", | |
| "Adam (EN/FR, grave charisma)": "pNInz6obpgDQGcFmaJgB", | |
| } | |
| # ═══════════════════════════════════════════════════════════════ | |
| # LECTURE SÉCURISÉE DES SECRETS (HuggingFace + fallback) | |
| # ═══════════════════════════════════════════════════════════════ | |
| def lire_secret(cle_hf: str, cle_env: str = "") -> str: | |
| """ | |
| Ordre de priorité : | |
| 1. st.secrets (HuggingFace Secrets configurés dans Settings) | |
| 2. Variable d'environnement système | |
| 3. Chaîne vide (pas de crash) | |
| """ | |
| # Tentative st.secrets | |
| try: | |
| val = st.secrets.get(cle_hf, "") | |
| if val and str(val).strip(): | |
| return str(val).strip() | |
| except Exception: | |
| pass | |
| # Fallback variable d'environnement | |
| if cle_env: | |
| val = os.environ.get(cle_env, "") | |
| if val and val.strip(): | |
| return val.strip() | |
| return "" | |
| # ═══════════════════════════════════════════════════════════════ | |
| # INITIALISATION SESSION STATE (une seule fois) | |
| # ═══════════════════════════════════════════════════════════════ | |
| def init_session(): | |
| defaults = { | |
| "el_api_key": lire_secret("ELEVENLABS_API_KEY", "sk_12daccf0b6d6784b497f18a341563029e9cc39746e456c1f"), | |
| "el_voice_id": lire_secret("ELEVENLABS_VOICE_ID", "ELEVENLABS_VOICE_ID") or "onwK4e9ZLuTAKqWW03F9", | |
| "unsplash_key1": lire_secret("UNSPLASH_KEY_1", "aBcU3JUkhAfUWm2K_WHQUc_ojdbpuUplwV9llp3J4Wg"), | |
| "unsplash_key2": lire_secret("UNSPLASH_KEY_2", "Q9jbXruMMAE8LvNt_2Y6p-7ApJg4AvPKJ4i8QaUqH34"), | |
| "script_texte": "", | |
| "video_path": "", | |
| "etape": 1, | |
| } | |
| for k, v in defaults.items(): | |
| if k not in st.session_state: | |
| st.session_state[k] = v | |
| init_session() | |
| # ═══════════════════════════════════════════════════════════════ | |
| # NETTOYAGE FICHIERS TEMPORAIRES | |
| # ═══════════════════════════════════════════════════════════════ | |
| def cleanup(*paths): | |
| for p in paths: | |
| if p and Path(p).exists(): | |
| try: | |
| Path(p).unlink() | |
| except Exception: | |
| pass | |
| # ═══════════════════════════════════════════════════════════════ | |
| # GÉNÉRATION DU SCRIPT | |
| # ═══════════════════════════════════════════════════════════════ | |
| def recuperer_actu(joueur: str) -> str: | |
| """Cherche la dernière actu du joueur via Google News RSS.""" | |
| try: | |
| import feedparser | |
| q = urllib.parse.quote_plus(f"{joueur} football 2025") | |
| url = f"https://news.google.com/rss/search?q={q}&hl=fr&gl=FR&ceid=FR:fr" | |
| feed = feedparser.parse(url) | |
| if feed.entries: | |
| return feed.entries[0].title | |
| except Exception: | |
| pass | |
| return "" | |
| def generer_script(joueur: str, actu: str) -> str: | |
| """Génère un script commentateur sport d'au moins 30 secondes.""" | |
| blocs = [ | |
| f"Bienvenue sur Prisme Foot, la chaîne numéro un de l'actualité football.", | |
| f"Aujourd'hui, nous allons parler de {joueur}, l'un des joueurs les plus électrisants de sa génération.", | |
| actu if actu else f"Et cette semaine encore, {joueur} fait parler de lui sur les terrains européens.", | |
| f"Son niveau de performance est tout simplement exceptionnel. Chaque ballon touché est une démonstration de talent pur.", | |
| f"Que ce soit par sa vitesse, sa technique de balle ou son sens du but, {joueur} régale les amateurs de football du monde entier.", | |
| f"Les recruteurs des plus grands clubs ont les yeux rivés sur lui, et on comprend pourquoi.", | |
| f"Sur les réseaux, les clips de {joueur} explosent les compteurs de vues. La nouvelle génération a trouvé son idole.", | |
| f"Restez connectés sur Prisme Foot pour suivre toute l'actualité autour de {joueur} et de vos joueurs préférés.", | |
| f"Abonnez-vous, activez la notification, et partagez cette vidéo à tous vos amis supporters de football.", | |
| f"Prisme Foot, le foot comme vous ne l'avez jamais vu.", | |
| ] | |
| # Construire jusqu'à atteindre la durée cible | |
| target_mots = int(MIN_DURATION / WPM_FACTOR) + 20 | |
| texte = "" | |
| for bloc in blocs: | |
| texte += " " + bloc | |
| if len(texte.split()) >= target_mots: | |
| break | |
| return texte.strip() | |
| # ═══════════════════════════════════════════════════════════════ | |
| # GÉNÉRATION AUDIO — ElevenLabs (voix masculine FR) | |
| # ═══════════════════════════════════════════════════════════════ | |
| def generer_audio_elevenlabs(texte: str, output_path: str) -> tuple[bool, str]: | |
| """ | |
| Appelle l'API ElevenLabs. | |
| Retourne (succès, message). | |
| """ | |
| api_key = st.session_state["el_api_key"] | |
| voice_id = st.session_state["el_voice_id"] | |
| if not api_key: | |
| return False, "Clé ElevenLabs manquante." | |
| if not voice_id: | |
| return False, "Voice ID manquant." | |
| url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}" | |
| headers = { | |
| "xi-api-key": api_key, | |
| "Content-Type": "application/json", | |
| "Accept": "audio/mpeg", | |
| } | |
| payload = { | |
| "text": texte[:4500], # limite API | |
| "model_id": "eleven_multilingual_v2", | |
| "voice_settings": { | |
| "stability": 0.50, | |
| "similarity_boost": 0.80, | |
| "style": 0.50, | |
| "use_speaker_boost": True, | |
| }, | |
| } | |
| try: | |
| r = requests.post(url, json=payload, headers=headers, timeout=45) | |
| if r.status_code == 401: | |
| return False, "❌ Clé ElevenLabs invalide. Vérifiez dans HF Secrets." | |
| if r.status_code == 422: | |
| return False, "❌ Voice ID introuvable. Changez de voix dans la sidebar." | |
| if r.status_code == 429: | |
| return False, "❌ Quota ElevenLabs dépassé. Attendez ou changez de plan." | |
| r.raise_for_status() | |
| with open(output_path, "wb") as f: | |
| f.write(r.content) | |
| taille = Path(output_path).stat().st_size | |
| if taille < 2000: | |
| return False, f"Audio trop petit ({taille} octets) — réponse API anormale." | |
| return True, f"Audio généré ({taille // 1024} Ko)" | |
| except requests.exceptions.Timeout: | |
| return False, "Timeout ElevenLabs (>45s). Réessayez." | |
| except Exception as e: | |
| return False, f"Erreur ElevenLabs : {str(e)[:120]}" | |
| def generer_audio_gtts(texte: str, output_path: str) -> tuple[bool, str]: | |
| """Fallback gTTS — voix FR gratuite.""" | |
| try: | |
| from gtts import gTTS | |
| propre = (texte | |
| .replace("'", " ").replace('"', " ") | |
| .replace(":", " ").replace("&", "et")) | |
| gTTS(text=propre, lang="fr", tld="fr").save(output_path) | |
| taille = Path(output_path).stat().st_size | |
| if taille < 1000: | |
| return False, "gTTS a généré un fichier vide." | |
| return True, f"Voix gTTS générée ({taille // 1024} Ko)" | |
| except Exception as e: | |
| return False, f"Erreur gTTS : {str(e)[:120]}" | |
| def generer_audio(texte: str, output_path: str, logger) -> bool: | |
| """Tente ElevenLabs, bascule sur gTTS si échec.""" | |
| ok, msg = generer_audio_elevenlabs(texte, output_path) | |
| if ok: | |
| logger.success(f"🎙️ Voix masculine ElevenLabs : {msg}") | |
| return True | |
| logger.warning(f"ElevenLabs → {msg} — Bascule sur gTTS...") | |
| ok, msg = generer_audio_gtts(texte, output_path) | |
| if ok: | |
| logger.info(f"🎙️ {msg}") | |
| return True | |
| logger.error(f"Audio impossible : {msg}") | |
| return False | |
| # ═══════════════════════════════════════════════════════════════ | |
| # TÉLÉCHARGEMENT IMAGES — Unsplash | |
| # ═══════════════════════════════════════════════════════════════ | |
| def telecharger_images(joueur: str, n: int, logger) -> List[str]: | |
| """ | |
| Tente les clés Unsplash dans l'ordre. | |
| Retourne une liste de chemins d'images valides. | |
| """ | |
| cles = [ | |
| k for k in [ | |
| st.session_state["unsplash_key1"], | |
| st.session_state["unsplash_key2"], | |
| ] if k and k.strip() | |
| ] | |
| if not cles: | |
| logger.warning("Pas de clé Unsplash → fond coloré.") | |
| return [] | |
| for idx, cle in enumerate(cles): | |
| try: | |
| logger.info(f"Recherche images Unsplash (clé #{idx+1})...") | |
| r = requests.get( | |
| "https://api.unsplash.com/search/photos", | |
| params={ | |
| "query": f"{joueur} football soccer", | |
| "per_page": n, | |
| "orientation": "portrait", | |
| "content_filter": "high", | |
| }, | |
| headers={"Authorization": f"Client-ID {cle}"}, | |
| timeout=15, | |
| ) | |
| if r.status_code == 401: | |
| logger.warning(f"Clé Unsplash #{idx+1} invalide (401).") | |
| continue | |
| if r.status_code == 429: | |
| logger.warning(f"Clé Unsplash #{idx+1} quota atteint (429).") | |
| continue | |
| if r.status_code != 200: | |
| logger.warning(f"Unsplash #{idx+1} erreur {r.status_code}.") | |
| continue | |
| resultats = r.json().get("results", []) | |
| if not resultats: | |
| logger.warning(f"Aucune image trouvée pour '{joueur}'.") | |
| continue | |
| logger.info(f"{len(resultats)} image(s) trouvée(s).") | |
| paths = [] | |
| for i, item in enumerate(resultats[:n]): | |
| img_url = item["urls"].get("regular", item["urls"].get("small", "")) | |
| if not img_url: | |
| continue | |
| try: | |
| ir = requests.get(img_url, timeout=20) | |
| ir.raise_for_status() | |
| p = os.path.join(tempfile.gettempdir(), f"pf_{uuid.uuid4().hex[:8]}.jpg") | |
| with open(p, "wb") as f: | |
| f.write(ir.content) | |
| if Path(p).stat().st_size > 5000: | |
| paths.append(p) | |
| logger.info(f" Image {i+1} OK ({Path(p).stat().st_size // 1024} Ko)") | |
| else: | |
| Path(p).unlink(missing_ok=True) | |
| except Exception as e: | |
| logger.warning(f" Image {i+1} échouée : {e}") | |
| if paths: | |
| return paths | |
| except Exception as e: | |
| logger.warning(f"Unsplash clé #{idx+1} : {str(e)[:80]}") | |
| continue | |
| logger.warning("Toutes les clés Unsplash ont échoué → fond coloré.") | |
| return [] | |
| # ═══════════════════════════════════════════════════════════════ | |
| # CONSTRUCTION VIDÉO — FFmpeg | |
| # ═══════════════════════════════════════════════════════════════ | |
| def verifier_ffmpeg() -> bool: | |
| try: | |
| subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True) | |
| return True | |
| except Exception: | |
| return False | |
| def image_vers_clip(img_path: str, duration: float, out: str) -> bool: | |
| """Convertit une image en clip MP4 vertical.""" | |
| cmd = [ | |
| "ffmpeg", "-y", | |
| "-loop", "1", | |
| "-i", img_path, | |
| "-t", str(duration), | |
| "-vf", ( | |
| f"scale={VIDEO_W}:{VIDEO_H}:force_original_aspect_ratio=increase," | |
| f"crop={VIDEO_W}:{VIDEO_H}," | |
| "setsar=1,format=yuv420p" | |
| ), | |
| "-c:v", "libx264", | |
| "-preset", "fast", | |
| "-pix_fmt", "yuv420p", | |
| "-r", "25", | |
| out, | |
| ] | |
| try: | |
| res = subprocess.run(cmd, capture_output=True, timeout=60) | |
| return res.returncode == 0 and Path(out).stat().st_size > 1000 | |
| except Exception: | |
| return False | |
| def fond_colore_clip(duration: float, out: str) -> bool: | |
| """Crée un fond dégradé sombre si pas d'images.""" | |
| cmd = [ | |
| "ffmpeg", "-y", | |
| "-f", "lavfi", | |
| "-i", f"color=c=0x0a1628:s={VIDEO_W}x{VIDEO_H}:r=25:d={duration}", | |
| "-c:v", "libx264", "-preset", "fast", | |
| "-pix_fmt", "yuv420p", | |
| out, | |
| ] | |
| try: | |
| res = subprocess.run(cmd, capture_output=True, timeout=30) | |
| return res.returncode == 0 | |
| except Exception: | |
| return False | |
| def escape_ff(text: str) -> str: | |
| """Échappe les caractères spéciaux pour ffmpeg drawtext.""" | |
| for c, r in [("\\","\\\\"), ("'","\u2019"), (":",r"\:"), ("%","\\%"), ("[","\\["), ("]","\\]")]: | |
| text = text.replace(c, r) | |
| return text | |
| def assembler_video(joueur: str, script: str, logger) -> Optional[str]: | |
| """ | |
| Pipeline complet : | |
| 1. Audio → ElevenLabs ou gTTS | |
| 2. Images → Unsplash ou fond coloré | |
| 3. Clips → FFmpeg image → MP4 | |
| 4. Concat → slideshow | |
| 5. Mixage → texte + audio → vidéo finale | |
| """ | |
| if not verifier_ffmpeg(): | |
| logger.error("FFmpeg non disponible sur ce serveur.") | |
| return None | |
| uid = uuid.uuid4().hex[:8] | |
| tmp = tempfile.gettempdir() | |
| to_clean = [] | |
| try: | |
| # ── 1. AUDIO ───────────────────────────────────────────────────────── | |
| logger.info("⏳ Étape 1/4 — Génération de la voix...") | |
| audio_path = os.path.join(tmp, f"pf_audio_{uid}.mp3") | |
| to_clean.append(audio_path) | |
| if not generer_audio(script, audio_path, logger): | |
| return None | |
| # Durée réelle de l'audio | |
| try: | |
| from mutagen.mp3 import MP3 | |
| duration = max(MIN_DURATION, math.ceil(MP3(audio_path).info.length) + 2) | |
| except Exception: | |
| duration = max(MIN_DURATION, int(len(script.split()) * WPM_FACTOR) + 5) | |
| logger.info(f"Durée audio : {duration}s") | |
| # ── 2. IMAGES ───────────────────────────────────────────────────────── | |
| logger.info("⏳ Étape 2/4 — Téléchargement des images...") | |
| images = telecharger_images(joueur, n=5, logger=logger) | |
| to_clean.extend(images) | |
| # ── 3. CLIPS ───────────────────────────────────────────────────────── | |
| logger.info("⏳ Étape 3/4 — Création des clips vidéo...") | |
| clips = [] | |
| if images: | |
| seg = round(duration / len(images), 2) | |
| logger.info(f"{len(images)} image(s), {seg}s par segment") | |
| for i, img in enumerate(images): | |
| cp = os.path.join(tmp, f"pf_clip_{uid}_{i}.mp4") | |
| to_clean.append(cp) | |
| if image_vers_clip(img, seg, cp): | |
| clips.append(cp) | |
| logger.info(f" Clip {i+1}/{len(images)} OK") | |
| else: | |
| logger.warning(f" Clip {i+1} échoué") | |
| if not clips: | |
| logger.info("Génération fond coloré...") | |
| clip_bg = os.path.join(tmp, f"pf_bg_{uid}.mp4") | |
| to_clean.append(clip_bg) | |
| if fond_colore_clip(duration, clip_bg): | |
| clips.append(clip_bg) | |
| else: | |
| logger.error("Impossible de créer le fond coloré.") | |
| return None | |
| # ── 4. CONCAT ───────────────────────────────────────────────────────── | |
| concat_file = os.path.join(tmp, f"pf_concat_{uid}.txt") | |
| slideshow = os.path.join(tmp, f"pf_slide_{uid}.mp4") | |
| to_clean.extend([concat_file, slideshow]) | |
| with open(concat_file, "w") as f: | |
| for c in clips: | |
| f.write(f"file '{c}'\n") | |
| cmd_concat = [ | |
| "ffmpeg", "-y", | |
| "-f", "concat", "-safe", "0", | |
| "-i", concat_file, | |
| "-c:v", "libx264", "-preset", "fast", | |
| "-pix_fmt", "yuv420p", | |
| slideshow, | |
| ] | |
| res = subprocess.run(cmd_concat, capture_output=True, timeout=120) | |
| if res.returncode != 0: | |
| logger.error(f"Concat échoué : {res.stderr.decode()[-200:]}") | |
| return None | |
| # ── 5. MIXAGE FINAL ─────────────────────────────────────────────────── | |
| logger.info("⏳ Étape 4/4 — Mixage final (texte + audio)...") | |
| video_out = os.path.join(tmp, f"pf_final_{uid}.mp4") | |
| j_esc = escape_ff(joueur.upper()[:24]) | |
| t_esc = escape_ff(script[:60] + "..." if len(script) > 60 else script) | |
| vf = ( | |
| # Bande noire semi-transparente | |
| "drawbox=y=0:x=0:width=iw:height=200:color=black@0.70:t=fill," | |
| "drawbox=y=ih-180:x=0:width=iw:height=180:color=black@0.70:t=fill," | |
| # Logo chaîne | |
| f"drawtext=text='⚽ PRISME FOOT':fontcolor=#FFD700:fontsize=38" | |
| f":x=(w-text_w)/2:y=40:shadowcolor=black:shadowx=2:shadowy=2," | |
| # Nom du joueur | |
| f"drawtext=text='{j_esc}':fontcolor=white:fontsize=52:x=(w-text_w)/2:y=100" | |
| f":box=1:boxcolor=#CC0000@0.85:boxborderw=12" | |
| f":shadowcolor=black:shadowx=3:shadowy=3," | |
| # Sous-titre actu | |
| f"drawtext=text='{t_esc}':fontcolor=white:fontsize=22:x=(w-text_w)/2" | |
| f":y=ih-140:shadowcolor=black:shadowx=1:shadowy=1," | |
| # CTA abonnement | |
| "drawtext=text='👍 ABONNEZ-VOUS':fontcolor=#FFD700:fontsize=28" | |
| ":x=(w-text_w)/2:y=ih-80:shadowcolor=black:shadowx=2:shadowy=2" | |
| ) | |
| cmd_final = [ | |
| "ffmpeg", "-y", | |
| "-i", slideshow, | |
| "-i", audio_path, | |
| "-vf", vf, | |
| "-c:v", "libx264", "-preset", "fast", | |
| "-c:a", "aac", "-b:a", "128k", | |
| "-t", str(duration), | |
| "-shortest", | |
| "-movflags", "+faststart", | |
| video_out, | |
| ] | |
| res = subprocess.run(cmd_final, capture_output=True, timeout=180) | |
| if res.returncode != 0: | |
| logger.error(f"Mixage échoué :\n{res.stderr.decode()[-400:]}") | |
| return None | |
| if not Path(video_out).exists() or Path(video_out).stat().st_size < 10000: | |
| logger.error("Vidéo finale vide ou corrompue.") | |
| return None | |
| taille_mo = Path(video_out).stat().st_size / (1024 * 1024) | |
| logger.success(f"✅ Vidéo créée ! ({taille_mo:.1f} Mo, {duration}s)") | |
| return video_out | |
| except Exception as e: | |
| logger.error(f"Erreur inattendue : {str(e)}") | |
| return None | |
| finally: | |
| cleanup(*to_clean) | |
| # ═══════════════════════════════════════════════════════════════ | |
| # INTERFACE STREAMLIT | |
| # ═══════════════════════════════════════════════════════════════ | |
| st.set_page_config( | |
| page_title="⚽ Prisme Foot Studio", | |
| page_icon="⚽", | |
| layout="wide", | |
| initial_sidebar_state="expanded", | |
| ) | |
| # CSS personnalisé | |
| st.markdown(""" | |
| <style> | |
| .main-title { | |
| font-size: 2.2rem; | |
| font-weight: 800; | |
| background: linear-gradient(135deg, #FFD700, #FF4444); | |
| -webkit-background-clip: text; | |
| -webkit-text-fill-color: transparent; | |
| text-align: center; | |
| margin-bottom: 0.2rem; | |
| } | |
| .sub-title { | |
| text-align: center; | |
| color: #888; | |
| font-size: 0.9rem; | |
| margin-bottom: 2rem; | |
| } | |
| .status-ok { color: #00C853; font-weight: 600; } | |
| .status-ko { color: #FF1744; font-weight: 600; } | |
| .step-badge { | |
| background: linear-gradient(135deg, #FFD700, #FF8C00); | |
| color: #000; | |
| padding: 2px 12px; | |
| border-radius: 20px; | |
| font-weight: 700; | |
| font-size: 0.8rem; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| st.markdown('<div class="main-title">⚽ PRISME FOOT STUDIO</div>', unsafe_allow_html=True) | |
| st.markdown('<div class="sub-title">Créateur de vidéos football automatisées — Version Finale</div>', unsafe_allow_html=True) | |
| # ── SIDEBAR — Configuration ─────────────────────────────────────────────────── | |
| with st.sidebar: | |
| st.markdown("## ⚙️ Configuration") | |
| # ── ElevenLabs ──────────────────────────────────────────── | |
| st.markdown("### 🎙️ Voix ElevenLabs") | |
| el_key_input = st.text_input( | |
| "Clé API ElevenLabs", | |
| value=st.session_state["el_api_key"], | |
| type="password", | |
| placeholder="sk_xxxxxxxxxxxxxxxxxxxxxxxx", | |
| help="Copiez depuis elevenlabs.io → Profile → API Key", | |
| ) | |
| if el_key_input.strip() != st.session_state["el_api_key"]: | |
| st.session_state["el_api_key"] = el_key_input.strip() | |
| voix_labels = list(VOIX_DISPONIBLES.keys()) | |
| voix_ids = list(VOIX_DISPONIBLES.values()) | |
| idx_actuel = voix_ids.index(st.session_state["el_voice_id"]) \ | |
| if st.session_state["el_voice_id"] in voix_ids else 0 | |
| voix_choisie = st.selectbox("Voix masculine", voix_labels, index=idx_actuel) | |
| st.session_state["el_voice_id"] = VOIX_DISPONIBLES[voix_choisie] | |
| if st.session_state["el_api_key"]: | |
| st.markdown('<span class="status-ok">✅ Clé ElevenLabs configurée</span>', unsafe_allow_html=True) | |
| else: | |
| st.markdown('<span class="status-ko">⚠️ Pas de clé → voix gTTS</span>', unsafe_allow_html=True) | |
| st.divider() | |
| # ── Unsplash ─────────────────────────────────────────────── | |
| st.markdown("### 🖼️ Images Unsplash") | |
| k1 = st.text_input( | |
| "Clé Unsplash #1", | |
| value=st.session_state["unsplash_key1"], | |
| type="password", | |
| placeholder="Clé Access Unsplash", | |
| help="unsplash.com/developers → New Application → Access Key", | |
| ) | |
| k2 = st.text_input( | |
| "Clé Unsplash #2 (secours)", | |
| value=st.session_state["unsplash_key2"], | |
| type="password", | |
| placeholder="Optionnelle", | |
| ) | |
| if k1.strip() != st.session_state["unsplash_key1"]: | |
| st.session_state["unsplash_key1"] = k1.strip() | |
| if k2.strip() != st.session_state["unsplash_key2"]: | |
| st.session_state["unsplash_key2"] = k2.strip() | |
| nb_cles = sum(1 for x in [k1, k2] if x.strip()) | |
| if nb_cles: | |
| st.markdown(f'<span class="status-ok">✅ {nb_cles} clé(s) Unsplash</span>', unsafe_allow_html=True) | |
| else: | |
| st.markdown('<span class="status-ko">⚠️ Pas de clé → fond coloré</span>', unsafe_allow_html=True) | |
| st.divider() | |
| st.markdown("### 📋 État du système") | |
| ffmpeg_ok = verifier_ffmpeg() | |
| st.markdown(f'FFmpeg : {"✅ OK" if ffmpeg_ok else "❌ Manquant"}') | |
| try: | |
| import feedparser | |
| st.markdown("feedparser : ✅ OK") | |
| except ImportError: | |
| st.markdown("feedparser : ⚠️ absent (actu désactivée)") | |
| try: | |
| from mutagen.mp3 import MP3 | |
| st.markdown("mutagen : ✅ OK") | |
| except ImportError: | |
| st.markdown("mutagen : ⚠️ absent") | |
| # ── ZONE PRINCIPALE ────────────────────────────────────────────────────────── | |
| col_main, col_preview = st.columns([3, 2]) | |
| with col_main: | |
| # ÉTAPE 1 — Joueur + Script | |
| st.markdown('<span class="step-badge">ÉTAPE 1</span> **Joueur et script**', unsafe_allow_html=True) | |
| st.markdown("") | |
| joueur = st.text_input( | |
| "👤 Nom du joueur", | |
| value="Vinicius Junior", | |
| placeholder="Ex: Mbappé, Ronaldo, Salah...", | |
| ) | |
| col_a, col_b = st.columns([1, 1]) | |
| with col_a: | |
| if st.button("🔍 Générer le script", use_container_width=True, type="primary"): | |
| if not joueur.strip(): | |
| st.warning("Entrez le nom d'un joueur.") | |
| else: | |
| with st.spinner("Recherche de l'actualité..."): | |
| actu = recuperer_actu(joueur) | |
| script = generer_script(joueur, actu) | |
| st.session_state["script_texte"] = script | |
| nb = len(script.split()) | |
| duree = round(nb * WPM_FACTOR) | |
| st.success(f"Script généré — {nb} mots ≈ {duree}s") | |
| with col_b: | |
| if st.button("🔄 Réinitialiser", use_container_width=True): | |
| st.session_state["script_texte"] = "" | |
| st.session_state["video_path"] = "" | |
| st.rerun() | |
| # Zone texte script — toujours pré-remplie | |
| script_final = st.text_area( | |
| "📝 Script (modifiable)", | |
| value=st.session_state["script_texte"], | |
| height=280, | |
| placeholder="Cliquez sur 'Générer le script' ou écrivez votre texte ici...", | |
| key="script_area_input", | |
| ) | |
| # Sync session_state à chaque modification | |
| if script_final != st.session_state["script_texte"]: | |
| st.session_state["script_texte"] = script_final | |
| # Métriques script | |
| if script_final.strip(): | |
| nb_mots = len(script_final.split()) | |
| duree_est = round(nb_mots * WPM_FACTOR) | |
| manque = max(0, MIN_DURATION - duree_est) | |
| c1, c2, c3 = st.columns(3) | |
| c1.metric("Mots", nb_mots) | |
| c2.metric("Durée estimée", f"{duree_est}s") | |
| c3.metric("Durée min requise", f"{MIN_DURATION}s", | |
| delta=f"+{manque}s manquants" if manque else "✅ OK", | |
| delta_color="inverse" if manque else "normal") | |
| st.divider() | |
| # ÉTAPE 2 — Création vidéo | |
| st.markdown('<span class="step-badge">ÉTAPE 2</span> **Création de la vidéo**', unsafe_allow_html=True) | |
| st.markdown("") | |
| peut_creer = bool(script_final.strip()) and bool(joueur.strip()) and ffmpeg_ok | |
| if not peut_creer: | |
| if not ffmpeg_ok: | |
| st.error("❌ FFmpeg non disponible sur ce serveur HuggingFace.") | |
| elif not script_final.strip(): | |
| st.info("⬆️ Générez ou écrivez un script d'abord.") | |
| if st.button( | |
| "🎬 CRÉER LA VIDÉO", | |
| disabled=not peut_creer, | |
| use_container_width=True, | |
| type="primary", | |
| ): | |
| st.session_state["video_path"] = "" | |
| log_container = st.empty() | |
| class Logger: | |
| """Logger inline dans Streamlit.""" | |
| def __init__(self, container): | |
| self.msgs = [] | |
| self.c = container | |
| def _render(self): | |
| self.c.markdown("\n\n".join(self.msgs)) | |
| def info(self, msg): | |
| self.msgs.append(f"ℹ️ {msg}") | |
| self._render() | |
| def success(self, msg): | |
| self.msgs.append(f"✅ {msg}") | |
| self._render() | |
| def warning(self, msg): | |
| self.msgs.append(f"⚠️ {msg}") | |
| self._render() | |
| def error(self, msg): | |
| self.msgs.append(f"❌ {msg}") | |
| self._render() | |
| logger = Logger(log_container) | |
| with st.spinner("🎬 Montage en cours... (30 à 90 secondes)"): | |
| video_path = assembler_video(joueur.strip(), script_final, logger) | |
| if video_path and Path(video_path).exists(): | |
| st.session_state["video_path"] = video_path | |
| st.balloons() | |
| else: | |
| st.error("La vidéo n'a pas pu être créée. Consultez les messages ci-dessus.") | |
| # ── COLONNE PREVIEW ──────────────────────────────────────────────────────────── | |
| with col_preview: | |
| st.markdown("### 📱 Aperçu & Téléchargement") | |
| st.markdown("") | |
| vp = st.session_state.get("video_path", "") | |
| if vp and Path(vp).exists(): | |
| st.video(vp) | |
| st.markdown("") | |
| with open(vp, "rb") as f: | |
| nom_fichier = f"prisme_{joueur.replace(' ', '_').lower()}.mp4" | |
| st.download_button( | |
| label="⬇️ Télécharger la vidéo MP4", | |
| data=f, | |
| file_name=nom_fichier, | |
| mime="video/mp4", | |
| use_container_width=True, | |
| type="primary", | |
| ) | |
| taille = Path(vp).stat().st_size / (1024 * 1024) | |
| st.caption(f"Fichier : {nom_fichier} — {taille:.1f} Mo") | |
| else: | |
| st.markdown(""" | |
| <div style=" | |
| border: 2px dashed #444; | |
| border-radius: 12px; | |
| padding: 60px 20px; | |
| text-align: center; | |
| color: #666; | |
| "> | |
| <div style="font-size: 3rem;">🎬</div> | |
| <div style="margin-top: 12px; font-size: 0.9rem;"> | |
| La vidéo apparaîtra ici<br>après création | |
| </div> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| st.divider() | |
| st.markdown("### 💡 Guide rapide") | |
| st.markdown(""" | |
| 1. **Sidebar** → entrez vos clés API | |
| 2. **Nom du joueur** → cliquez Générer | |
| 3. **Modifiez** le script si besoin | |
| 4. **Créez la vidéo** → téléchargez | |
| --- | |
| **Sans clé ElevenLabs** : voix gTTS (gratuit) | |
| **Sans clé Unsplash** : fond coloré sombre | |
| """) |