""" ╔══════════════════════════════════════════════════════════════╗ ║ 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(""" """, unsafe_allow_html=True) st.markdown('