Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,73 +1,147 @@
|
|
| 1 |
-
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import streamlit as st
|
| 3 |
from mutagen.mp3 import MP3
|
| 4 |
|
| 5 |
-
# ─── CONFIG ──────
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
]
|
| 12 |
-
UNSPLASH_KEYS = [k for k in UNSPLASH_KEYS if k.strip()] # retire les clés vides
|
| 13 |
-
|
| 14 |
-
# ElevenLabs — voix masculine très humaine, idéale sport/football
|
| 15 |
-
# Créez un compte gratuit sur https://elevenlabs.io → Profile → API Key
|
| 16 |
-
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY", "sk_12daccf0b6d6784b497f18a341563029e9cc39746e456c1f")
|
| 17 |
-
# ID de voix recommandées (masculines, dynamiques, sport) :
|
| 18 |
-
# "pNInz6obpgDQGcFmaJgB" → Adam (voix grave, charismatique)
|
| 19 |
-
# "ErXwobaYiN019PkySvjV" → Antoni (voix douce mais virile)
|
| 20 |
-
# "VR6AewLTigWG4xSOukaG" → Arnold (voix puissante, stade)
|
| 21 |
-
# "29vD33N1oss6MR3es1vT" → Drew (voix journaliste TV)
|
| 22 |
-
ELEVENLABS_VOICE_ID = os.getenv("ELEVENLABS_VOICE_ID", "pNInz6obpgDQGcFmaJgB") # Adam par défaut
|
| 23 |
|
| 24 |
MIN_DURATION = 30
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
def generer_audio(texte: str, output_path: str) -> bool:
|
| 29 |
"""
|
| 30 |
-
Priorité 1 : ElevenLabs
|
| 31 |
-
Priorité 2 : gTTS
|
| 32 |
-
Retourne True si succès.
|
| 33 |
"""
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
| 36 |
try:
|
| 37 |
-
url = f"https://api.elevenlabs.io/v1/text-to-speech/{
|
| 38 |
headers = {
|
| 39 |
-
"xi-api-key":
|
| 40 |
"Content-Type": "application/json",
|
| 41 |
"Accept": "audio/mpeg",
|
| 42 |
}
|
| 43 |
payload = {
|
| 44 |
"text": texte,
|
| 45 |
-
"model_id": "eleven_multilingual_v2",
|
| 46 |
"voice_settings": {
|
| 47 |
-
"stability":
|
| 48 |
-
"similarity_boost":
|
| 49 |
-
"style":
|
| 50 |
-
"use_speaker_boost": True,
|
| 51 |
},
|
| 52 |
}
|
| 53 |
r = requests.post(url, json=payload, headers=headers, timeout=30)
|
| 54 |
r.raise_for_status()
|
| 55 |
with open(output_path, "wb") as f:
|
| 56 |
f.write(r.content)
|
| 57 |
-
st.success("
|
| 58 |
return True
|
|
|
|
|
|
|
|
|
|
| 59 |
except Exception as e:
|
| 60 |
-
st.warning(f"
|
| 61 |
|
| 62 |
-
#
|
| 63 |
try:
|
| 64 |
from gtts import gTTS
|
| 65 |
-
texte_clean =
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
| 68 |
return True
|
| 69 |
except Exception as e:
|
| 70 |
-
st.error(f"Erreur
|
| 71 |
return False
|
| 72 |
|
| 73 |
# ─── ENRICHISSEMENT SCRIPT ────────────────────────────────────────────────────
|
|
@@ -93,26 +167,43 @@ def enrichir_script(joueur: str, titre: str) -> str:
|
|
| 93 |
# ─── RECHERCHE NEWS ───────────────────────────────────────────────────────────
|
| 94 |
def recuperer_news_reelle(joueur: str) -> str:
|
| 95 |
try:
|
| 96 |
-
import feedparser
|
| 97 |
q = urllib.parse.quote(f"{joueur} football")
|
| 98 |
url = f"https://news.google.com/rss/search?q={q}&hl=fr&gl=FR&ceid=FR:fr"
|
| 99 |
fx = feedparser.parse(url)
|
| 100 |
return fx.entries[0].title if fx.entries else ""
|
|
|
|
|
|
|
|
|
|
| 101 |
except Exception as e:
|
| 102 |
-
st.
|
| 103 |
return ""
|
| 104 |
|
| 105 |
-
# ─── TÉLÉCHARGEMENT D'IMAGES (rotation multi-clés) ──────────
|
| 106 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
"""
|
| 108 |
-
Essaie chaque clé Unsplash
|
| 109 |
-
|
| 110 |
"""
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
| 113 |
return []
|
| 114 |
|
| 115 |
-
for idx_key, key in enumerate(
|
| 116 |
try:
|
| 117 |
r = requests.get(
|
| 118 |
"https://api.unsplash.com/search/photos",
|
|
@@ -121,40 +212,42 @@ def telecharger_images(joueur: str, n: int = 4) -> list:
|
|
| 121 |
timeout=10,
|
| 122 |
)
|
| 123 |
if r.status_code in (401, 403):
|
| 124 |
-
st.warning(f"Clé Unsplash #{idx_key+1} invalide
|
| 125 |
continue
|
| 126 |
if r.status_code == 429:
|
| 127 |
-
st.warning(f"Clé Unsplash #{idx_key+1} quota atteint
|
| 128 |
continue
|
| 129 |
r.raise_for_status()
|
| 130 |
|
| 131 |
results = r.json().get("results", [])
|
| 132 |
-
st.info(f"Unsplash (clé #{idx_key+1}) : {len(results)} résultat(s)
|
| 133 |
paths = []
|
|
|
|
| 134 |
for item in results[:n]:
|
| 135 |
img_url = item["urls"]["regular"]
|
| 136 |
-
img_data =
|
| 137 |
-
|
|
|
|
|
|
|
| 138 |
with open(p, "wb") as f:
|
| 139 |
f.write(img_data)
|
| 140 |
-
|
| 141 |
-
if size > 5000:
|
| 142 |
paths.append(p)
|
| 143 |
-
st.info(f" ✅ Image sauvée : {p} ({size//1024} Ko)")
|
| 144 |
else:
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
| 147 |
|
| 148 |
except Exception as e:
|
| 149 |
st.warning(f"Unsplash clé #{idx_key+1} erreur : {e}")
|
| 150 |
continue
|
| 151 |
|
| 152 |
-
st.warning("Toutes les clés Unsplash ont échoué → fond coloré
|
| 153 |
return []
|
| 154 |
|
| 155 |
# ─── CONVERTIR UNE IMAGE EN CLIP .MP4 ────────────────────────────────────────
|
| 156 |
-
def image_en_clip(img_path: str, duration: float,
|
| 157 |
-
out = f"/tmp/clip_{uid}_{idx}.mp4"
|
| 158 |
cmd = [
|
| 159 |
"ffmpeg", "-y",
|
| 160 |
"-loop", "1",
|
|
@@ -170,95 +263,112 @@ def image_en_clip(img_path: str, duration: float, uid: str, idx: int) -> str | N
|
|
| 170 |
"-c:v", "libx264",
|
| 171 |
"-preset", "ultrafast",
|
| 172 |
"-pix_fmt", "yuv420p",
|
| 173 |
-
|
| 174 |
]
|
| 175 |
try:
|
| 176 |
subprocess.run(cmd, check=True, capture_output=True)
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
return None
|
| 182 |
except subprocess.CalledProcessError as e:
|
| 183 |
-
st.warning(f"Clip
|
| 184 |
-
return
|
| 185 |
|
| 186 |
# ─── FOND COLORÉ DE SECOURS ──────────────────────────────────────────────────
|
| 187 |
-
def fond_colore_clip(duration: float,
|
| 188 |
-
out = f"/tmp/clip_{uid}_bg.mp4"
|
| 189 |
cmd = [
|
| 190 |
"ffmpeg", "-y",
|
| 191 |
"-f", "lavfi",
|
| 192 |
"-i", f"color=c=0x001a33:s=720x1280:r=25:d={duration}",
|
| 193 |
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
|
| 194 |
-
|
| 195 |
]
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
# ─── MOTEUR VIDÉO PRINCIPAL ───────────────────────────────────────────────────
|
| 200 |
-
def fabriquer_video(joueur: str, texte: str) -> str
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
-
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
try:
|
| 211 |
-
# ── 1.
|
| 212 |
if not generer_audio(texte_clean, audio_path):
|
| 213 |
return None
|
| 214 |
duration = max(MIN_DURATION, math.ceil(MP3(audio_path).info.length) + 1)
|
| 215 |
-
st.info(f"Durée audio
|
| 216 |
|
| 217 |
-
# ── 2. Images
|
| 218 |
images = telecharger_images(joueur, n=4)
|
| 219 |
-
|
|
|
|
|
|
|
| 220 |
|
| 221 |
-
clips = []
|
| 222 |
if n_img == 0:
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
else:
|
| 228 |
seg = round(duration / n_img, 2)
|
| 229 |
st.info(f"{n_img} image(s) → {seg}s par segment")
|
| 230 |
for i, img in enumerate(images):
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
temp_files.append(img)
|
| 236 |
|
| 237 |
if not clips:
|
| 238 |
st.error("Aucun clip vidéo généré.")
|
| 239 |
return None
|
| 240 |
|
| 241 |
-
# ── 3. Concat ────────
|
| 242 |
with open(concat_list, "w") as f:
|
| 243 |
for c in clips:
|
| 244 |
f.write(f"file '{c}'\n")
|
| 245 |
|
| 246 |
-
slideshow = f"/tmp/slide_{uid}.mp4"
|
| 247 |
-
temp_files.append(slideshow)
|
| 248 |
subprocess.run([
|
| 249 |
"ffmpeg", "-y",
|
| 250 |
"-f", "concat", "-safe", "0",
|
| 251 |
"-i", concat_list,
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
slideshow
|
| 254 |
], check=True, capture_output=True)
|
| 255 |
|
| 256 |
# ── 4. Overlay texte + audio ───────────────────────────────────────────
|
| 257 |
-
titre_court = texte_clean[:55] + ("..." if len(texte_clean) > 55 else "")
|
|
|
|
| 258 |
vf = (
|
| 259 |
f"drawbox=y=ih/2-110:color=black@0.65:width=iw:height=300:t=fill,"
|
| 260 |
f"drawtext=text='PRISME FOOT':fontcolor=yellow:fontsize=42:x=(w-text_w)/2:y=160,"
|
| 261 |
-
f"drawtext=text='{
|
| 262 |
f":x=(w-text_w)/2:y=305:box=1:boxcolor=red@0.8,"
|
| 263 |
f"drawtext=text='{titre_court}':fontcolor=white:fontsize=28"
|
| 264 |
f":x=(w-text_w)/2:y=(h-text_h)/2+55"
|
|
@@ -274,94 +384,110 @@ def fabriquer_video(joueur: str, texte: str) -> str | None:
|
|
| 274 |
video_out
|
| 275 |
], check=True, capture_output=True)
|
| 276 |
|
| 277 |
-
# ── 5. Nettoyage ───────────────────────────────────────────────────────
|
| 278 |
-
for f in temp_files:
|
| 279 |
-
if f and os.path.exists(f):
|
| 280 |
-
os.remove(f)
|
| 281 |
-
|
| 282 |
return video_out if os.path.exists(video_out) else None
|
| 283 |
|
| 284 |
except subprocess.CalledProcessError as e:
|
| 285 |
st.error(f"FFmpeg erreur :\n{e.stderr.decode()[-600:]}")
|
|
|
|
| 286 |
except Exception as e:
|
| 287 |
st.error(f"Erreur générale : {e}")
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
# ─── INTERFACE STREAMLIT ──────────────────────────────────────────────────────
|
| 291 |
st.set_page_config(page_title="Prisme Foot Studio", page_icon="⚽")
|
| 292 |
-
st.title("⚽ Prisme Foot Studio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
|
| 294 |
with st.sidebar:
|
| 295 |
st.header("⚙️ Configuration")
|
| 296 |
|
| 297 |
-
st.subheader("🖼️ Unsplash
|
| 298 |
-
key1 = st.text_input("Clé Unsplash #1", type="password"
|
| 299 |
-
help="unsplash.com/developers → Access Key")
|
| 300 |
key2 = st.text_input("Clé Unsplash #2 (optionnelle)", type="password")
|
| 301 |
key3 = st.text_input("Clé Unsplash #3 (optionnelle)", type="password")
|
| 302 |
-
|
| 303 |
-
if
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
st.subheader("🎙️ ElevenLabs
|
| 308 |
-
el_key = st.text_input("Clé ElevenLabs", type="password"
|
| 309 |
-
help="elevenlabs.io → Profile → API Key")
|
| 310 |
voice_choice = st.selectbox(
|
| 311 |
-
"Voix masculine",
|
| 312 |
options=[
|
| 313 |
-
("
|
| 314 |
-
("
|
| 315 |
-
("
|
| 316 |
-
("Antoni — Virile et posée",
|
| 317 |
],
|
| 318 |
format_func=lambda x: x[0],
|
| 319 |
)
|
| 320 |
if el_key:
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
if not ELEVENLABS_API_KEY and not el_key:
|
| 330 |
st.warning("Sans clé ElevenLabs → voix gTTS (moins réaliste).")
|
| 331 |
|
| 332 |
-
|
| 333 |
-
st.session_state["script"] = ""
|
| 334 |
-
|
| 335 |
nom = st.text_input("👤 Nom du joueur", "Vinicius Junior")
|
| 336 |
|
| 337 |
-
if st.button("🔍 1.
|
| 338 |
with st.spinner("Recherche RSS..."):
|
| 339 |
titre = recuperer_news_reelle(nom)
|
| 340 |
-
|
| 341 |
-
|
|
|
|
|
|
|
| 342 |
st.success(f"Script prêt — {nb} mots ≈ {round(nb * WPM_FACTOR)}s")
|
| 343 |
|
| 344 |
-
|
| 345 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
)
|
|
|
|
|
|
|
|
|
|
| 347 |
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
delta = max(0, 30 - duree_est)
|
| 353 |
-
st.metric("⏱ Durée estimée", f"{duree_est}s", delta=f"-{delta}s" if delta else "OK")
|
| 354 |
|
| 355 |
-
if st.button("🎬 2.
|
| 356 |
with st.spinner("Montage en cours…"):
|
| 357 |
-
|
| 358 |
-
if
|
| 359 |
st.success("✅ Vidéo prête !")
|
| 360 |
-
st.video(
|
| 361 |
-
with open(
|
| 362 |
st.download_button(
|
| 363 |
"⬇️ Télécharger MP4",
|
| 364 |
fv,
|
| 365 |
file_name=f"prisme_{nom.replace(' ', '_')}.mp4",
|
| 366 |
mime="video/mp4",
|
| 367 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
| 3 |
+
import subprocess
|
| 4 |
+
import math
|
| 5 |
+
import tempfile
|
| 6 |
+
import requests
|
| 7 |
+
import urllib.parse
|
| 8 |
+
from contextlib import contextmanager
|
| 9 |
+
from typing import Optional, List
|
| 10 |
+
|
| 11 |
import streamlit as st
|
| 12 |
from mutagen.mp3 import MP3
|
| 13 |
|
| 14 |
+
# ─── CONFIG — TOUTES LES CLÉS VIENNENT DE st.secrets OU variables d'env ──────
|
| 15 |
+
# Ne jamais hardcoder de clés ici. Configurer dans .streamlit/secrets.toml :
|
| 16 |
+
# [elevenlabs]
|
| 17 |
+
# api_key = "sk_..."
|
| 18 |
+
# voice_id = "..." (optionnel)
|
| 19 |
+
# [unsplash]
|
| 20 |
+
# key1 = "..."
|
| 21 |
+
# key2 = "..." (optionnel)
|
| 22 |
+
|
| 23 |
+
def _get_secret(section: str, key: str, env_fallback: str = "") -> str:
|
| 24 |
+
"""Lit un secret depuis st.secrets, puis les variables d'env."""
|
| 25 |
+
try:
|
| 26 |
+
return st.secrets[section][key]
|
| 27 |
+
except (KeyError, AttributeError):
|
| 28 |
+
return os.getenv(env_fallback, "")
|
| 29 |
+
|
| 30 |
+
ELEVENLABS_API_KEY = _get_secret("elevenlabs", "api_key", "ELEVENLABS_API_KEY")
|
| 31 |
+
# Voix française masculine recommandée : Georges (FR natif, voix de journaliste)
|
| 32 |
+
# ID ElevenLabs disponibles en français :
|
| 33 |
+
# "VR6AewLTigWG4xSOukaG" → Arnold (anglais natif, accent FR moyen)
|
| 34 |
+
# "XB0fDUnXU5powFXDhCwa" → Charlotte (FR natif, féminine — éviter)
|
| 35 |
+
# "onwK4e9ZLuTAKqWW03F9" → Daniel (FR natif, masculin, journaliste)
|
| 36 |
+
# "29vD33N1oss6MR3es1vT" → Drew (FR acceptable, ton TV)
|
| 37 |
+
ELEVENLABS_VOICE_ID = _get_secret("elevenlabs", "voice_id", "ELEVENLABS_VOICE_ID") \
|
| 38 |
+
or "onwK4e9ZLuTAKqWW03F9" # Daniel FR par défaut
|
| 39 |
+
|
| 40 |
+
UNSPLASH_KEYS: List[str] = [
|
| 41 |
+
k for k in [
|
| 42 |
+
_get_secret("unsplash", "key1", "UNSPLASH_ACCESS_KEY"),
|
| 43 |
+
_get_secret("unsplash", "key2", "UNSPLASH_ACCESS_KEY_2"),
|
| 44 |
+
_get_secret("unsplash", "key3", "UNSPLASH_ACCESS_KEY_3"),
|
| 45 |
+
] if k.strip()
|
| 46 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
MIN_DURATION = 30
|
| 49 |
+
# Corrigé : 0.45s/mot ≈ 133 mots/min, plus réaliste pour ElevenLabs FR
|
| 50 |
+
WPM_FACTOR = 0.45
|
| 51 |
+
|
| 52 |
+
# ─── UTILITAIRE : nettoyage garanti des fichiers temporaires ──────────────────
|
| 53 |
+
@contextmanager
|
| 54 |
+
def temp_file(suffix: str = ".tmp"):
|
| 55 |
+
"""Crée un fichier temporaire et le supprime à la sortie du contexte."""
|
| 56 |
+
path = os.path.join(tempfile.gettempdir(), f"pf_{uuid.uuid4().hex[:8]}{suffix}")
|
| 57 |
+
try:
|
| 58 |
+
yield path
|
| 59 |
+
finally:
|
| 60 |
+
if os.path.exists(path):
|
| 61 |
+
try:
|
| 62 |
+
os.remove(path)
|
| 63 |
+
except OSError:
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
def supprimer_fichiers(paths: List[str]) -> None:
|
| 67 |
+
"""Supprime une liste de fichiers en ignorant les erreurs."""
|
| 68 |
+
for p in paths:
|
| 69 |
+
if p and os.path.exists(p):
|
| 70 |
+
try:
|
| 71 |
+
os.remove(p)
|
| 72 |
+
except OSError:
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
# ─── ÉCHAPPEMENT FFMPEG drawtext ──────────────────────────────────────────────
|
| 76 |
+
def escape_drawtext(text: str) -> str:
|
| 77 |
+
"""
|
| 78 |
+
Échappe les caractères spéciaux pour ffmpeg drawtext.
|
| 79 |
+
Voir : https://ffmpeg.org/ffmpeg-filters.html#drawtext
|
| 80 |
+
"""
|
| 81 |
+
# Ordre important : échapper \ en premier
|
| 82 |
+
for char, escaped in [
|
| 83 |
+
("\\", "\\\\"),
|
| 84 |
+
("'", "\\'"),
|
| 85 |
+
(":", "\\:"),
|
| 86 |
+
("%", "\\%"),
|
| 87 |
+
("{", "\\{"),
|
| 88 |
+
("}", "\\}"),
|
| 89 |
+
("[", "\\["),
|
| 90 |
+
("]", "\\]"),
|
| 91 |
+
]:
|
| 92 |
+
text = text.replace(char, escaped)
|
| 93 |
+
return text
|
| 94 |
+
|
| 95 |
+
# ─── GÉNÉRATION AUDIO ─────────────────────────────────────────────────────────
|
| 96 |
def generer_audio(texte: str, output_path: str) -> bool:
|
| 97 |
"""
|
| 98 |
+
Priorité 1 : ElevenLabs (voix FR masculine ultra-réaliste)
|
| 99 |
+
Priorité 2 : gTTS FR (fallback gratuit)
|
|
|
|
| 100 |
"""
|
| 101 |
+
api_key = st.session_state.get("el_key_runtime", ELEVENLABS_API_KEY)
|
| 102 |
+
voice_id = st.session_state.get("el_voice_runtime", ELEVENLABS_VOICE_ID)
|
| 103 |
+
|
| 104 |
+
if api_key:
|
| 105 |
try:
|
| 106 |
+
url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
|
| 107 |
headers = {
|
| 108 |
+
"xi-api-key": api_key,
|
| 109 |
"Content-Type": "application/json",
|
| 110 |
"Accept": "audio/mpeg",
|
| 111 |
}
|
| 112 |
payload = {
|
| 113 |
"text": texte,
|
| 114 |
+
"model_id": "eleven_multilingual_v2",
|
| 115 |
"voice_settings": {
|
| 116 |
+
"stability": 0.45, # légèrement plus stable → moins de décrochages FR
|
| 117 |
+
"similarity_boost": 0.85,
|
| 118 |
+
"style": 0.55,
|
| 119 |
+
"use_speaker_boost": True,
|
| 120 |
},
|
| 121 |
}
|
| 122 |
r = requests.post(url, json=payload, headers=headers, timeout=30)
|
| 123 |
r.raise_for_status()
|
| 124 |
with open(output_path, "wb") as f:
|
| 125 |
f.write(r.content)
|
| 126 |
+
st.success("Voix ElevenLabs (masculine FR) générée.")
|
| 127 |
return True
|
| 128 |
+
except requests.HTTPError as e:
|
| 129 |
+
code = e.response.status_code if e.response else "?"
|
| 130 |
+
st.warning(f"ElevenLabs HTTP {code} → bascule gTTS.")
|
| 131 |
except Exception as e:
|
| 132 |
+
st.warning(f"ElevenLabs indisponible : {e} → bascule gTTS.")
|
| 133 |
|
| 134 |
+
# Fallback gTTS
|
| 135 |
try:
|
| 136 |
from gtts import gTTS
|
| 137 |
+
texte_clean = (texte
|
| 138 |
+
.replace("'", " ").replace('"', " ")
|
| 139 |
+
.replace(":", " ").replace("&", "et"))
|
| 140 |
+
gTTS(text=texte_clean, lang="fr", tld="fr").save(output_path)
|
| 141 |
+
st.info("Voix gTTS (fallback) utilisée.")
|
| 142 |
return True
|
| 143 |
except Exception as e:
|
| 144 |
+
st.error(f"Erreur gTTS : {e}")
|
| 145 |
return False
|
| 146 |
|
| 147 |
# ─── ENRICHISSEMENT SCRIPT ────────────────────────────────────────────────────
|
|
|
|
| 167 |
# ─── RECHERCHE NEWS ───────────────────────────────────────────────────────────
|
| 168 |
def recuperer_news_reelle(joueur: str) -> str:
|
| 169 |
try:
|
| 170 |
+
import feedparser # pip install feedparser
|
| 171 |
q = urllib.parse.quote(f"{joueur} football")
|
| 172 |
url = f"https://news.google.com/rss/search?q={q}&hl=fr&gl=FR&ceid=FR:fr"
|
| 173 |
fx = feedparser.parse(url)
|
| 174 |
return fx.entries[0].title if fx.entries else ""
|
| 175 |
+
except ImportError:
|
| 176 |
+
st.warning("feedparser non installé. Ajoutez-le à requirements.txt.")
|
| 177 |
+
return ""
|
| 178 |
except Exception as e:
|
| 179 |
+
st.warning(f"Erreur RSS : {e}")
|
| 180 |
return ""
|
| 181 |
|
| 182 |
+
# ─── TÉLÉCHARGEMENT D'IMAGES (rotation multi-clés + retry par image) ──────────
|
| 183 |
+
def telecharger_une_image(url: str, retries: int = 3) -> Optional[bytes]:
|
| 184 |
+
"""Télécharge une image avec retry automatique."""
|
| 185 |
+
for tentative in range(retries):
|
| 186 |
+
try:
|
| 187 |
+
r = requests.get(url, timeout=15)
|
| 188 |
+
r.raise_for_status()
|
| 189 |
+
return r.content
|
| 190 |
+
except Exception as e:
|
| 191 |
+
if tentative == retries - 1:
|
| 192 |
+
st.warning(f"Image inaccessible après {retries} essais : {e}")
|
| 193 |
+
return None
|
| 194 |
+
|
| 195 |
+
def telecharger_images(joueur: str, n: int = 4) -> List[str]:
|
| 196 |
"""
|
| 197 |
+
Essaie chaque clé Unsplash en rotation.
|
| 198 |
+
Chaque image est téléchargée individuellement avec retry.
|
| 199 |
"""
|
| 200 |
+
keys = st.session_state.get("unsplash_keys_runtime", UNSPLASH_KEYS)
|
| 201 |
+
|
| 202 |
+
if not keys:
|
| 203 |
+
st.warning("Aucune clé Unsplash → fond coloré utilisé.")
|
| 204 |
return []
|
| 205 |
|
| 206 |
+
for idx_key, key in enumerate(keys):
|
| 207 |
try:
|
| 208 |
r = requests.get(
|
| 209 |
"https://api.unsplash.com/search/photos",
|
|
|
|
| 212 |
timeout=10,
|
| 213 |
)
|
| 214 |
if r.status_code in (401, 403):
|
| 215 |
+
st.warning(f"Clé Unsplash #{idx_key+1} invalide.")
|
| 216 |
continue
|
| 217 |
if r.status_code == 429:
|
| 218 |
+
st.warning(f"Clé Unsplash #{idx_key+1} quota atteint.")
|
| 219 |
continue
|
| 220 |
r.raise_for_status()
|
| 221 |
|
| 222 |
results = r.json().get("results", [])
|
| 223 |
+
st.info(f"Unsplash (clé #{idx_key+1}) : {len(results)} résultat(s)")
|
| 224 |
paths = []
|
| 225 |
+
|
| 226 |
for item in results[:n]:
|
| 227 |
img_url = item["urls"]["regular"]
|
| 228 |
+
img_data = telecharger_une_image(img_url)
|
| 229 |
+
if img_data is None:
|
| 230 |
+
continue
|
| 231 |
+
p = os.path.join(tempfile.gettempdir(), f"pf_img_{uuid.uuid4().hex[:8]}.jpg")
|
| 232 |
with open(p, "wb") as f:
|
| 233 |
f.write(img_data)
|
| 234 |
+
if os.path.getsize(p) > 5000:
|
|
|
|
| 235 |
paths.append(p)
|
|
|
|
| 236 |
else:
|
| 237 |
+
os.remove(p)
|
| 238 |
+
st.warning("Image ignorée (trop petite).")
|
| 239 |
+
|
| 240 |
+
return paths # succès avec cette clé
|
| 241 |
|
| 242 |
except Exception as e:
|
| 243 |
st.warning(f"Unsplash clé #{idx_key+1} erreur : {e}")
|
| 244 |
continue
|
| 245 |
|
| 246 |
+
st.warning("Toutes les clés Unsplash ont échoué → fond coloré.")
|
| 247 |
return []
|
| 248 |
|
| 249 |
# ─── CONVERTIR UNE IMAGE EN CLIP .MP4 ────────────────────────────────────────
|
| 250 |
+
def image_en_clip(img_path: str, duration: float, out_path: str) -> bool:
|
|
|
|
| 251 |
cmd = [
|
| 252 |
"ffmpeg", "-y",
|
| 253 |
"-loop", "1",
|
|
|
|
| 263 |
"-c:v", "libx264",
|
| 264 |
"-preset", "ultrafast",
|
| 265 |
"-pix_fmt", "yuv420p",
|
| 266 |
+
out_path
|
| 267 |
]
|
| 268 |
try:
|
| 269 |
subprocess.run(cmd, check=True, capture_output=True)
|
| 270 |
+
ok = os.path.exists(out_path) and os.path.getsize(out_path) > 1000
|
| 271 |
+
if not ok:
|
| 272 |
+
st.warning(f"Clip vide après ffmpeg : {out_path}")
|
| 273 |
+
return ok
|
|
|
|
| 274 |
except subprocess.CalledProcessError as e:
|
| 275 |
+
st.warning(f"Clip KO : {e.stderr.decode()[-300:]}")
|
| 276 |
+
return False
|
| 277 |
|
| 278 |
# ─── FOND COLORÉ DE SECOURS ──────────────────────────────────────────────────
|
| 279 |
+
def fond_colore_clip(duration: float, out_path: str) -> bool:
|
|
|
|
| 280 |
cmd = [
|
| 281 |
"ffmpeg", "-y",
|
| 282 |
"-f", "lavfi",
|
| 283 |
"-i", f"color=c=0x001a33:s=720x1280:r=25:d={duration}",
|
| 284 |
"-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
|
| 285 |
+
out_path
|
| 286 |
]
|
| 287 |
+
try:
|
| 288 |
+
subprocess.run(cmd, check=True, capture_output=True)
|
| 289 |
+
return os.path.exists(out_path)
|
| 290 |
+
except subprocess.CalledProcessError as e:
|
| 291 |
+
st.error(f"Fond coloré KO : {e.stderr.decode()[-200:]}")
|
| 292 |
+
return False
|
| 293 |
|
| 294 |
# ─── MOTEUR VIDÉO PRINCIPAL ───────────────────────────────────────────────────
|
| 295 |
+
def fabriquer_video(joueur: str, texte: str) -> Optional[str]:
|
| 296 |
+
"""
|
| 297 |
+
Crée la vidéo finale. Tous les fichiers temporaires sont nettoyés
|
| 298 |
+
qu'il y ait succès ou erreur (via try/finally).
|
| 299 |
+
"""
|
| 300 |
+
uid = uuid.uuid4().hex[:8]
|
| 301 |
+
tmp_dir = tempfile.gettempdir()
|
| 302 |
+
temp_files: List[str] = []
|
| 303 |
+
|
| 304 |
+
audio_path = os.path.join(tmp_dir, f"pf_audio_{uid}.mp3")
|
| 305 |
+
concat_list = os.path.join(tmp_dir, f"pf_concat_{uid}.txt")
|
| 306 |
+
slideshow = os.path.join(tmp_dir, f"pf_slide_{uid}.mp4")
|
| 307 |
+
video_out = os.path.join(tmp_dir, f"pf_out_{uid}.mp4")
|
| 308 |
|
| 309 |
+
temp_files.extend([audio_path, concat_list, slideshow])
|
| 310 |
+
# video_out n'est PAS dans temp_files (c'est la sortie à conserver)
|
| 311 |
+
|
| 312 |
+
texte_clean = (texte
|
| 313 |
+
.replace("'", " ").replace('"', " ")
|
| 314 |
+
.replace(":", " ").replace("&", "et"))
|
| 315 |
+
joueur_up = joueur.upper().replace("'", " ")[:30] # tronqué pour sécurité
|
| 316 |
|
| 317 |
try:
|
| 318 |
+
# ── 1. Audio ──────────────────────────────────────────────────────────
|
| 319 |
if not generer_audio(texte_clean, audio_path):
|
| 320 |
return None
|
| 321 |
duration = max(MIN_DURATION, math.ceil(MP3(audio_path).info.length) + 1)
|
| 322 |
+
st.info(f"Durée audio : {duration}s")
|
| 323 |
|
| 324 |
+
# ── 2. Images ─────────────────────────────────────────────────────────
|
| 325 |
images = telecharger_images(joueur, n=4)
|
| 326 |
+
temp_files.extend(images)
|
| 327 |
+
n_img = len(images)
|
| 328 |
+
clips: List[str] = []
|
| 329 |
|
|
|
|
| 330 |
if n_img == 0:
|
| 331 |
+
clip_bg = os.path.join(tmp_dir, f"pf_clip_bg_{uid}.mp4")
|
| 332 |
+
temp_files.append(clip_bg)
|
| 333 |
+
if fond_colore_clip(duration, clip_bg):
|
| 334 |
+
clips.append(clip_bg)
|
| 335 |
else:
|
| 336 |
seg = round(duration / n_img, 2)
|
| 337 |
st.info(f"{n_img} image(s) → {seg}s par segment")
|
| 338 |
for i, img in enumerate(images):
|
| 339 |
+
clip_path = os.path.join(tmp_dir, f"pf_clip_{uid}_{i}.mp4")
|
| 340 |
+
temp_files.append(clip_path)
|
| 341 |
+
if image_en_clip(img, seg, clip_path):
|
| 342 |
+
clips.append(clip_path)
|
|
|
|
| 343 |
|
| 344 |
if not clips:
|
| 345 |
st.error("Aucun clip vidéo généré.")
|
| 346 |
return None
|
| 347 |
|
| 348 |
+
# ── 3. Concat (avec re-encodage pour éviter les décalages A/V) ────────
|
| 349 |
with open(concat_list, "w") as f:
|
| 350 |
for c in clips:
|
| 351 |
f.write(f"file '{c}'\n")
|
| 352 |
|
|
|
|
|
|
|
| 353 |
subprocess.run([
|
| 354 |
"ffmpeg", "-y",
|
| 355 |
"-f", "concat", "-safe", "0",
|
| 356 |
"-i", concat_list,
|
| 357 |
+
# Re-encodage obligatoire : les segments ont des durées légèrement
|
| 358 |
+
# différentes → -c copy crée des décalages audio/vidéo
|
| 359 |
+
"-c:v", "libx264", "-preset", "ultrafast",
|
| 360 |
+
"-c:a", "aac",
|
| 361 |
+
"-pix_fmt", "yuv420p",
|
| 362 |
slideshow
|
| 363 |
], check=True, capture_output=True)
|
| 364 |
|
| 365 |
# ── 4. Overlay texte + audio ───────────────────────────────────────────
|
| 366 |
+
titre_court = escape_drawtext(texte_clean[:55] + ("..." if len(texte_clean) > 55 else ""))
|
| 367 |
+
joueur_esc = escape_drawtext(joueur_up)
|
| 368 |
vf = (
|
| 369 |
f"drawbox=y=ih/2-110:color=black@0.65:width=iw:height=300:t=fill,"
|
| 370 |
f"drawtext=text='PRISME FOOT':fontcolor=yellow:fontsize=42:x=(w-text_w)/2:y=160,"
|
| 371 |
+
f"drawtext=text='{joueur_esc}':fontcolor=white:fontsize=55"
|
| 372 |
f":x=(w-text_w)/2:y=305:box=1:boxcolor=red@0.8,"
|
| 373 |
f"drawtext=text='{titre_court}':fontcolor=white:fontsize=28"
|
| 374 |
f":x=(w-text_w)/2:y=(h-text_h)/2+55"
|
|
|
|
| 384 |
video_out
|
| 385 |
], check=True, capture_output=True)
|
| 386 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
return video_out if os.path.exists(video_out) else None
|
| 388 |
|
| 389 |
except subprocess.CalledProcessError as e:
|
| 390 |
st.error(f"FFmpeg erreur :\n{e.stderr.decode()[-600:]}")
|
| 391 |
+
return None
|
| 392 |
except Exception as e:
|
| 393 |
st.error(f"Erreur générale : {e}")
|
| 394 |
+
return None
|
| 395 |
+
finally:
|
| 396 |
+
# Nettoyage GARANTI même en cas d'erreur
|
| 397 |
+
supprimer_fichiers(temp_files)
|
| 398 |
|
| 399 |
# ─── INTERFACE STREAMLIT ──────────────────────────────────────────────────────
|
| 400 |
st.set_page_config(page_title="Prisme Foot Studio", page_icon="⚽")
|
| 401 |
+
st.title("⚽ Prisme Foot Studio v5")
|
| 402 |
+
|
| 403 |
+
# Initialisation session_state
|
| 404 |
+
for key, default in [
|
| 405 |
+
("script", ""),
|
| 406 |
+
("script_edite", ""),
|
| 407 |
+
("el_key_runtime", ELEVENLABS_API_KEY),
|
| 408 |
+
("el_voice_runtime", ELEVENLABS_VOICE_ID),
|
| 409 |
+
("unsplash_keys_runtime", UNSPLASH_KEYS[:]),
|
| 410 |
+
]:
|
| 411 |
+
if key not in st.session_state:
|
| 412 |
+
st.session_state[key] = default
|
| 413 |
|
| 414 |
with st.sidebar:
|
| 415 |
st.header("⚙️ Configuration")
|
| 416 |
|
| 417 |
+
st.subheader("🖼️ Unsplash")
|
| 418 |
+
key1 = st.text_input("Clé Unsplash #1", type="password")
|
|
|
|
| 419 |
key2 = st.text_input("Clé Unsplash #2 (optionnelle)", type="password")
|
| 420 |
key3 = st.text_input("Clé Unsplash #3 (optionnelle)", type="password")
|
| 421 |
+
nouvelles_cles = [k.strip() for k in [key1, key2, key3] if k.strip()]
|
| 422 |
+
if nouvelles_cles:
|
| 423 |
+
st.session_state["unsplash_keys_runtime"] = nouvelles_cles
|
| 424 |
+
st.success(f"{len(nouvelles_cles)} clé(s) Unsplash enregistrée(s).")
|
| 425 |
+
|
| 426 |
+
st.subheader("🎙️ ElevenLabs")
|
| 427 |
+
el_key = st.text_input("Clé ElevenLabs", type="password")
|
|
|
|
| 428 |
voice_choice = st.selectbox(
|
| 429 |
+
"Voix masculine FR",
|
| 430 |
options=[
|
| 431 |
+
("Daniel — Journaliste FR natif (recommandé)", "onwK4e9ZLuTAKqWW03F9"),
|
| 432 |
+
("Drew — Ton TV, FR acceptable", "29vD33N1oss6MR3es1vT"),
|
| 433 |
+
("Arnold — Puissant, accent FR moyen", "VR6AewLTigWG4xSOukaG"),
|
| 434 |
+
("Antoni — Virile et posée", "ErXwobaYiN019PkySvjV"),
|
| 435 |
],
|
| 436 |
format_func=lambda x: x[0],
|
| 437 |
)
|
| 438 |
if el_key:
|
| 439 |
+
# Utiliser session_state au lieu de modifier __main__
|
| 440 |
+
st.session_state["el_key_runtime"] = el_key
|
| 441 |
+
st.session_state["el_voice_runtime"] = voice_choice[1]
|
| 442 |
+
st.success("Clé ElevenLabs enregistrée.")
|
| 443 |
+
|
| 444 |
+
if not st.session_state["unsplash_keys_runtime"]:
|
| 445 |
+
st.warning("Sans clé Unsplash → fond coloré.")
|
| 446 |
+
if not st.session_state["el_key_runtime"]:
|
|
|
|
| 447 |
st.warning("Sans clé ElevenLabs → voix gTTS (moins réaliste).")
|
| 448 |
|
| 449 |
+
# ─── ZONE PRINCIPALE ──────────────────────────────────────────────────────────
|
|
|
|
|
|
|
| 450 |
nom = st.text_input("👤 Nom du joueur", "Vinicius Junior")
|
| 451 |
|
| 452 |
+
if st.button("🔍 1. Chercher l'actu"):
|
| 453 |
with st.spinner("Recherche RSS..."):
|
| 454 |
titre = recuperer_news_reelle(nom)
|
| 455 |
+
script = enrichir_script(nom, titre)
|
| 456 |
+
st.session_state["script"] = script
|
| 457 |
+
st.session_state["script_edite"] = script
|
| 458 |
+
nb = len(script.split())
|
| 459 |
st.success(f"Script prêt — {nb} mots ≈ {round(nb * WPM_FACTOR)}s")
|
| 460 |
|
| 461 |
+
# Persistance du script édité manuellement
|
| 462 |
+
script_edite = st.text_area(
|
| 463 |
+
"📝 Script (modifiable)",
|
| 464 |
+
value=st.session_state.get("script_edite", st.session_state.get("script", "")),
|
| 465 |
+
height=200,
|
| 466 |
+
key="script_area"
|
| 467 |
)
|
| 468 |
+
# Sauvegarder les modifications manuelles
|
| 469 |
+
if script_edite != st.session_state.get("script_edite", ""):
|
| 470 |
+
st.session_state["script_edite"] = script_edite
|
| 471 |
|
| 472 |
+
nb_mots = len(script_edite.split()) if script_edite else 0
|
| 473 |
+
duree_est = round(nb_mots * WPM_FACTOR)
|
| 474 |
+
delta = max(0, 30 - duree_est)
|
| 475 |
+
st.metric("⏱ Durée estimée", f"{duree_est}s", delta=f"-{delta}s si trop court" if delta else "OK")
|
|
|
|
|
|
|
| 476 |
|
| 477 |
+
if st.button("🎬 2. Créer la vidéo", disabled=not script_edite.strip()):
|
| 478 |
with st.spinner("Montage en cours…"):
|
| 479 |
+
video_path = fabriquer_video(nom, script_edite)
|
| 480 |
+
if video_path and os.path.exists(video_path):
|
| 481 |
st.success("✅ Vidéo prête !")
|
| 482 |
+
st.video(video_path)
|
| 483 |
+
with open(video_path, "rb") as fv:
|
| 484 |
st.download_button(
|
| 485 |
"⬇️ Télécharger MP4",
|
| 486 |
fv,
|
| 487 |
file_name=f"prisme_{nom.replace(' ', '_')}.mp4",
|
| 488 |
mime="video/mp4",
|
| 489 |
+
)
|
| 490 |
+
# Nettoyage de la vidéo finale après téléchargement proposé
|
| 491 |
+
# (laisser le fichier pour la session, Streamlit le gère)
|
| 492 |
+
else:
|
| 493 |
+
st.error("La vidéo n'a pas pu être générée. Vérifiez les logs ci-dessus.")
|