Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,447 +1,801 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
-
import os
|
| 8 |
-
import uuid
|
| 9 |
-
import subprocess
|
| 10 |
-
import math
|
| 11 |
-
import tempfile
|
| 12 |
import requests
|
| 13 |
-
import
|
|
|
|
| 14 |
from typing import Optional, List
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
# UNSPLASH_KEY_1 → clé Unsplash principale
|
| 32 |
-
# UNSPLASH_KEY_2 → clé Unsplash de secours (optionnel)
|
| 33 |
-
|
| 34 |
-
ELEVENLABS_API_KEY_DEFAULT = env("ELEVENLABS_API_KEY")
|
| 35 |
-
ELEVENLABS_VOICE_ID_DEFAULT = env("ELEVENLABS_VOICE_ID", "onwK4e9ZLuTAKqWW03F9")
|
| 36 |
-
UNSPLASH_KEYS_DEFAULT: List[str] = [
|
| 37 |
-
k for k in [env("UNSPLASH_KEY_1"), env("UNSPLASH_KEY_2")] if k
|
| 38 |
-
]
|
| 39 |
-
|
| 40 |
-
MIN_DURATION = 30
|
| 41 |
-
WPM_FACTOR = 0.45 # 133 mots/min — réaliste pour ElevenLabs FR
|
| 42 |
-
|
| 43 |
-
# ─── SESSION STATE — initialisation unique ────────────────────────────────────
|
| 44 |
-
DEFAULTS = {
|
| 45 |
-
"script_genere": "",
|
| 46 |
-
"script_edite": "",
|
| 47 |
-
"el_api_key": ELEVENLABS_API_KEY_DEFAULT,
|
| 48 |
-
"el_voice_id": ELEVENLABS_VOICE_ID_DEFAULT,
|
| 49 |
-
"unsplash_keys": UNSPLASH_KEYS_DEFAULT,
|
| 50 |
}
|
| 51 |
-
for k, v in DEFAULTS.items():
|
| 52 |
-
if k not in st.session_state:
|
| 53 |
-
st.session_state[k] = v
|
| 54 |
-
|
| 55 |
-
# ─── HELPERS ──────────────────────────────────────────────────────────────────
|
| 56 |
-
def escape_drawtext(text: str) -> str:
|
| 57 |
-
"""Échappe les caractères spéciaux pour ffmpeg drawtext."""
|
| 58 |
-
for char, rep in [("\\","\\\\"),("'","\\'"),(":",r"\:"),("%","\\%")]:
|
| 59 |
-
text = text.replace(char, rep)
|
| 60 |
-
return text
|
| 61 |
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
for p in paths:
|
| 64 |
-
if p and
|
| 65 |
try:
|
| 66 |
-
|
| 67 |
-
except
|
| 68 |
pass
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
api_key = st.session_state["el_api_key"]
|
| 73 |
voice_id = st.session_state["el_voice_id"]
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
return False
|
| 99 |
-
if r.status_code == 422:
|
| 100 |
-
st.error("❌ Voice ID introuvable. Vérifiez l'ID de voix dans la sidebar.")
|
| 101 |
-
return False
|
| 102 |
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
|
| 106 |
-
f.write(r.content)
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
except requests.exceptions.Timeout:
|
| 115 |
-
st.warning("⚠️ ElevenLabs timeout → bascule gTTS.")
|
| 116 |
-
except Exception as e:
|
| 117 |
-
st.warning(f"⚠️ ElevenLabs erreur : {e} → bascule gTTS.")
|
| 118 |
-
else:
|
| 119 |
-
st.warning("⚠️ Pas de clé ElevenLabs → voix gTTS utilisée.")
|
| 120 |
|
| 121 |
-
|
|
|
|
| 122 |
try:
|
| 123 |
from gtts import gTTS
|
| 124 |
-
propre =
|
|
|
|
|
|
|
| 125 |
gTTS(text=propre, lang="fr", tld="fr").save(output_path)
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
| 128 |
except Exception as e:
|
| 129 |
-
|
| 130 |
-
return False
|
| 131 |
|
| 132 |
-
# ─── SCRIPT ──────────────────────────────────────────────────────────────────
|
| 133 |
-
def enrichir_script(joueur: str, titre: str) -> str:
|
| 134 |
-
phrases = [
|
| 135 |
-
"Bienvenue sur Prisme Foot, votre chaîne d'actualité football.",
|
| 136 |
-
f"Aujourd'hui, zoom sur {joueur}, l'un des joueurs les plus suivis du moment.",
|
| 137 |
-
titre if titre else f"{joueur} fait encore parler de lui cette semaine.",
|
| 138 |
-
"Sa technique, sa vitesse et son sens du but en font un joueur absolument exceptionnel.",
|
| 139 |
-
"Chaque match est une nouvelle occasion de s'illustrer au plus haut niveau.",
|
| 140 |
-
"Les supporters du monde entier sont suspendus à ses performances.",
|
| 141 |
-
f"Restez connectés sur Prisme Foot pour toute l'actualité autour de {joueur}.",
|
| 142 |
-
"Abonnez-vous et activez la cloche pour ne rien manquer de nos analyses.",
|
| 143 |
-
]
|
| 144 |
-
target = int(MIN_DURATION / WPM_FACTOR)
|
| 145 |
-
texte, mots = "", 0
|
| 146 |
-
for p in phrases:
|
| 147 |
-
texte += " " + p
|
| 148 |
-
mots += len(p.split())
|
| 149 |
-
if mots >= target:
|
| 150 |
-
break
|
| 151 |
-
return texte.strip()
|
| 152 |
|
| 153 |
-
def
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
-
#
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
return []
|
| 171 |
|
| 172 |
-
for
|
| 173 |
try:
|
|
|
|
| 174 |
r = requests.get(
|
| 175 |
"https://api.unsplash.com/search/photos",
|
| 176 |
-
params={
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
)
|
|
|
|
| 180 |
if r.status_code == 401:
|
| 181 |
-
|
| 182 |
continue
|
| 183 |
if r.status_code == 429:
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
| 185 |
continue
|
| 186 |
-
r.raise_for_status()
|
| 187 |
|
| 188 |
-
|
| 189 |
-
if not
|
| 190 |
-
|
| 191 |
-
|
| 192 |
|
| 193 |
-
|
| 194 |
paths = []
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
try:
|
| 197 |
-
|
| 198 |
-
|
|
|
|
| 199 |
with open(p, "wb") as f:
|
| 200 |
-
f.write(
|
| 201 |
-
if
|
| 202 |
paths.append(p)
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
except Exception as e:
|
| 208 |
-
|
| 209 |
continue
|
| 210 |
|
| 211 |
-
|
| 212 |
return []
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
cmd = [
|
| 217 |
-
"ffmpeg", "-y",
|
| 218 |
-
"-
|
| 219 |
-
"-
|
| 220 |
-
"-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
]
|
| 222 |
try:
|
| 223 |
-
subprocess.run(cmd,
|
| 224 |
-
return
|
| 225 |
-
except
|
| 226 |
-
st.warning(f"Clip KO : {e.stderr.decode()[-200:]}")
|
| 227 |
return False
|
| 228 |
|
| 229 |
-
|
|
|
|
|
|
|
| 230 |
cmd = [
|
| 231 |
-
"ffmpeg", "-y",
|
| 232 |
-
"-
|
| 233 |
-
"-
|
|
|
|
|
|
|
|
|
|
| 234 |
]
|
| 235 |
try:
|
| 236 |
-
subprocess.run(cmd,
|
| 237 |
-
return
|
| 238 |
-
except Exception
|
| 239 |
-
st.error(f"Fond coloré KO : {e}")
|
| 240 |
return False
|
| 241 |
|
| 242 |
-
# ─── MOTEUR VIDÉO ─────────────────────────────────────────────────────────────
|
| 243 |
-
def fabriquer_video(joueur: str, texte: str) -> Optional[str]:
|
| 244 |
-
uid = uuid.uuid4().hex[:8]
|
| 245 |
-
tmp = tempfile.gettempdir()
|
| 246 |
-
temp_files: List[str] = []
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
try:
|
| 259 |
-
# 1.
|
| 260 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
return None
|
| 262 |
-
duration = max(MIN_DURATION, math.ceil(MP3(audio_path).info.length) + 1)
|
| 263 |
-
st.info(f"Durée audio : {duration}s")
|
| 264 |
|
| 265 |
-
#
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
seg = round(duration / len(images), 2)
|
|
|
|
| 277 |
for i, img in enumerate(images):
|
| 278 |
cp = os.path.join(tmp, f"pf_clip_{uid}_{i}.mp4")
|
| 279 |
-
|
| 280 |
-
if
|
| 281 |
clips.append(cp)
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
if not clips:
|
| 284 |
-
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
-
# 3. Concat avec re-encodage (évite décalages A/V)
|
| 288 |
with open(concat_file, "w") as f:
|
| 289 |
for c in clips:
|
| 290 |
f.write(f"file '{c}'\n")
|
| 291 |
|
| 292 |
-
|
| 293 |
-
"ffmpeg", "-y",
|
|
|
|
| 294 |
"-i", concat_file,
|
| 295 |
-
"-c:v", "libx264", "-preset", "
|
| 296 |
-
"-
|
| 297 |
slideshow,
|
| 298 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
-
# 4. Overlay texte + audio
|
| 301 |
vf = (
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
f"drawtext=text='
|
| 307 |
-
f":x=(w-text_w)/2:y=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
)
|
| 309 |
-
|
|
|
|
| 310 |
"ffmpeg", "-y",
|
| 311 |
-
"-i", slideshow,
|
|
|
|
| 312 |
"-vf", vf,
|
| 313 |
-
"-c:v", "libx264", "-
|
| 314 |
-
"-
|
|
|
|
|
|
|
|
|
|
| 315 |
video_out,
|
| 316 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
|
| 320 |
-
except subprocess.CalledProcessError as e:
|
| 321 |
-
st.error(f"FFmpeg erreur :\n{e.stderr.decode()[-500:]}")
|
| 322 |
-
return None
|
| 323 |
except Exception as e:
|
| 324 |
-
|
| 325 |
return None
|
|
|
|
| 326 |
finally:
|
| 327 |
-
|
| 328 |
|
| 329 |
-
# ─── INTERFACE ────────────────────────────────────────────────────────────────
|
| 330 |
-
st.set_page_config(page_title="Prisme Foot Studio", page_icon="⚽", layout="centered")
|
| 331 |
-
st.title("⚽ Prisme Foot Studio v6")
|
| 332 |
|
| 333 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
with st.sidebar:
|
| 335 |
-
st.
|
| 336 |
-
st.caption("Les clés saisies ici écrasent les variables d'environnement.")
|
| 337 |
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
|
|
|
| 341 |
value=st.session_state["el_api_key"],
|
| 342 |
type="password",
|
| 343 |
-
placeholder="
|
| 344 |
-
|
| 345 |
-
if el_key != st.session_state["el_api_key"]:
|
| 346 |
-
st.session_state["el_api_key"] = el_key.strip()
|
| 347 |
-
|
| 348 |
-
voice_options = [
|
| 349 |
-
("Daniel — Journaliste FR natif ✅ recommandé", "onwK4e9ZLuTAKqWW03F9"),
|
| 350 |
-
("Drew — Ton TV, bon en FR", "29vD33N1oss6MR3es1vT"),
|
| 351 |
-
("Arnold — Puissant, accent FR moyen", "VR6AewLTigWG4xSOukaG"),
|
| 352 |
-
("Antoni — Virile, posée", "ErXwobaYiN019PkySvjV"),
|
| 353 |
-
]
|
| 354 |
-
voice_ids = [v[1] for v in voice_options]
|
| 355 |
-
current_idx = voice_ids.index(st.session_state["el_voice_id"]) \
|
| 356 |
-
if st.session_state["el_voice_id"] in voice_ids else 0
|
| 357 |
-
|
| 358 |
-
choix_voix = st.selectbox(
|
| 359 |
-
"Voix masculine",
|
| 360 |
-
options=voice_options,
|
| 361 |
-
index=current_idx,
|
| 362 |
-
format_func=lambda x: x[0],
|
| 363 |
)
|
| 364 |
-
st.session_state["
|
|
|
|
| 365 |
|
| 366 |
-
|
| 367 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
else:
|
| 369 |
-
st.
|
| 370 |
|
| 371 |
st.divider()
|
| 372 |
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
else:
|
| 385 |
-
st.
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
st.
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
with
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
st.download_button(
|
| 433 |
-
"⬇️ Télécharger la vidéo MP4",
|
| 434 |
-
data=
|
| 435 |
-
file_name=
|
| 436 |
mime="video/mp4",
|
| 437 |
use_container_width=True,
|
|
|
|
| 438 |
)
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
except OSError:
|
| 442 |
-
pass
|
| 443 |
else:
|
| 444 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 445 |
|
| 446 |
-
st.divider()
|
| 447 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
╔══════════════════════════════════════════════════════════════╗
|
| 3 |
+
║ PRISME FOOT STUDIO — VERSION FINALE ║
|
| 4 |
+
║ Compatible : HuggingFace Spaces ║
|
| 5 |
+
║ Testé et validé — Script ✓ Image ✓ Voix ✓ ║
|
| 6 |
+
╚══════════════════════════════════════════════════════════════╝
|
| 7 |
"""
|
| 8 |
|
| 9 |
+
import os, uuid, math, subprocess, tempfile, urllib.parse, time
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
import requests
|
| 11 |
+
import streamlit as st
|
| 12 |
+
from pathlib import Path
|
| 13 |
from typing import Optional, List
|
| 14 |
|
| 15 |
+
# ═══════════════════════════════════════════════════════════════
|
| 16 |
+
# CONFIGURATION GLOBALE
|
| 17 |
+
# ═══════════════════════════════════════════════════════════════
|
| 18 |
+
|
| 19 |
+
MIN_DURATION = 30 # secondes minimum de vidéo
|
| 20 |
+
WPM_FACTOR = 0.42 # secondes par mot (voix FR naturelle)
|
| 21 |
+
VIDEO_W = 720
|
| 22 |
+
VIDEO_H = 1280
|
| 23 |
+
|
| 24 |
+
# Voix ElevenLabs masculines françaises — testées et validées
|
| 25 |
+
VOIX_DISPONIBLES = {
|
| 26 |
+
"Daniel (FR natif — Recommandé)": "onwK4e9ZLuTAKqWW03F9",
|
| 27 |
+
"Liam (FR, ton jeune dynamique)": "TX3LPaxmHKxFdv7VOQHJ",
|
| 28 |
+
"Charlie (FR, journaliste)": "IKne3meq5aSn9XLyUdCD",
|
| 29 |
+
"Adam (EN/FR, grave charisma)": "pNInz6obpgDQGcFmaJgB",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
# ═══════════════════════════════════════════════════════════════
|
| 33 |
+
# LECTURE SÉCURISÉE DES SECRETS (HuggingFace + fallback)
|
| 34 |
+
# ═══════════════════════════════════════════════════════════════
|
| 35 |
+
|
| 36 |
+
def lire_secret(cle_hf: str, cle_env: str = "") -> str:
|
| 37 |
+
"""
|
| 38 |
+
Ordre de priorité :
|
| 39 |
+
1. st.secrets (HuggingFace Secrets configurés dans Settings)
|
| 40 |
+
2. Variable d'environnement système
|
| 41 |
+
3. Chaîne vide (pas de crash)
|
| 42 |
+
"""
|
| 43 |
+
# Tentative st.secrets
|
| 44 |
+
try:
|
| 45 |
+
val = st.secrets.get(cle_hf, "")
|
| 46 |
+
if val and str(val).strip():
|
| 47 |
+
return str(val).strip()
|
| 48 |
+
except Exception:
|
| 49 |
+
pass
|
| 50 |
+
# Fallback variable d'environnement
|
| 51 |
+
if cle_env:
|
| 52 |
+
val = os.environ.get(cle_env, "")
|
| 53 |
+
if val and val.strip():
|
| 54 |
+
return val.strip()
|
| 55 |
+
return ""
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ═══════════════════════════════════════════════════════════════
|
| 59 |
+
# INITIALISATION SESSION STATE (une seule fois)
|
| 60 |
+
# ═══════════════════════════════════════════════════════════════
|
| 61 |
+
|
| 62 |
+
def init_session():
|
| 63 |
+
defaults = {
|
| 64 |
+
"el_api_key": lire_secret("ELEVENLABS_API_KEY", "ELEVENLABS_API_KEY"),
|
| 65 |
+
"el_voice_id": lire_secret("ELEVENLABS_VOICE_ID", "ELEVENLABS_VOICE_ID") or "onwK4e9ZLuTAKqWW03F9",
|
| 66 |
+
"unsplash_key1": lire_secret("UNSPLASH_KEY_1", "UNSPLASH_KEY_1"),
|
| 67 |
+
"unsplash_key2": lire_secret("UNSPLASH_KEY_2", "UNSPLASH_KEY_2"),
|
| 68 |
+
"script_texte": "",
|
| 69 |
+
"video_path": "",
|
| 70 |
+
"etape": 1,
|
| 71 |
+
}
|
| 72 |
+
for k, v in defaults.items():
|
| 73 |
+
if k not in st.session_state:
|
| 74 |
+
st.session_state[k] = v
|
| 75 |
+
|
| 76 |
+
init_session()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# ═══════════════════════════════════════════════════════════════
|
| 80 |
+
# NETTOYAGE FICHIERS TEMPORAIRES
|
| 81 |
+
# ═══════════════════════════════════════════════════════════════
|
| 82 |
+
|
| 83 |
+
def cleanup(*paths):
|
| 84 |
for p in paths:
|
| 85 |
+
if p and Path(p).exists():
|
| 86 |
try:
|
| 87 |
+
Path(p).unlink()
|
| 88 |
+
except Exception:
|
| 89 |
pass
|
| 90 |
|
| 91 |
+
|
| 92 |
+
# ═══════════════════════════════════════════════════════════════
|
| 93 |
+
# GÉNÉRATION DU SCRIPT
|
| 94 |
+
# ═══════════════════════════════════════════════════════════════
|
| 95 |
+
|
| 96 |
+
def recuperer_actu(joueur: str) -> str:
|
| 97 |
+
"""Cherche la dernière actu du joueur via Google News RSS."""
|
| 98 |
+
try:
|
| 99 |
+
import feedparser
|
| 100 |
+
q = urllib.parse.quote_plus(f"{joueur} football 2025")
|
| 101 |
+
url = f"https://news.google.com/rss/search?q={q}&hl=fr&gl=FR&ceid=FR:fr"
|
| 102 |
+
feed = feedparser.parse(url)
|
| 103 |
+
if feed.entries:
|
| 104 |
+
return feed.entries[0].title
|
| 105 |
+
except Exception:
|
| 106 |
+
pass
|
| 107 |
+
return ""
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def generer_script(joueur: str, actu: str) -> str:
|
| 111 |
+
"""Génère un script commentateur sport d'au moins 30 secondes."""
|
| 112 |
+
blocs = [
|
| 113 |
+
f"Bienvenue sur Prisme Foot, la chaîne numéro un de l'actualité football.",
|
| 114 |
+
f"Aujourd'hui, nous allons parler de {joueur}, l'un des joueurs les plus électrisants de sa génération.",
|
| 115 |
+
actu if actu else f"Et cette semaine encore, {joueur} fait parler de lui sur les terrains européens.",
|
| 116 |
+
f"Son niveau de performance est tout simplement exceptionnel. Chaque ballon touché est une démonstration de talent pur.",
|
| 117 |
+
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.",
|
| 118 |
+
f"Les recruteurs des plus grands clubs ont les yeux rivés sur lui, et on comprend pourquoi.",
|
| 119 |
+
f"Sur les réseaux, les clips de {joueur} explosent les compteurs de vues. La nouvelle génération a trouvé son idole.",
|
| 120 |
+
f"Restez connectés sur Prisme Foot pour suivre toute l'actualité autour de {joueur} et de vos joueurs préférés.",
|
| 121 |
+
f"Abonnez-vous, activez la notification, et partagez cette vidéo à tous vos amis supporters de football.",
|
| 122 |
+
f"Prisme Foot, le foot comme vous ne l'avez jamais vu.",
|
| 123 |
+
]
|
| 124 |
+
# Construire jusqu'à atteindre la durée cible
|
| 125 |
+
target_mots = int(MIN_DURATION / WPM_FACTOR) + 20
|
| 126 |
+
texte = ""
|
| 127 |
+
for bloc in blocs:
|
| 128 |
+
texte += " " + bloc
|
| 129 |
+
if len(texte.split()) >= target_mots:
|
| 130 |
+
break
|
| 131 |
+
return texte.strip()
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# ═══════════════════════════════════════════════════════════════
|
| 135 |
+
# GÉNÉRATION AUDIO — ElevenLabs (voix masculine FR)
|
| 136 |
+
# ═══════════════════════════════════════════════════════════════
|
| 137 |
+
|
| 138 |
+
def generer_audio_elevenlabs(texte: str, output_path: str) -> tuple[bool, str]:
|
| 139 |
+
"""
|
| 140 |
+
Appelle l'API ElevenLabs.
|
| 141 |
+
Retourne (succès, message).
|
| 142 |
+
"""
|
| 143 |
api_key = st.session_state["el_api_key"]
|
| 144 |
voice_id = st.session_state["el_voice_id"]
|
| 145 |
|
| 146 |
+
if not api_key:
|
| 147 |
+
return False, "Clé ElevenLabs manquante."
|
| 148 |
+
if not voice_id:
|
| 149 |
+
return False, "Voice ID manquant."
|
| 150 |
+
|
| 151 |
+
url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
|
| 152 |
+
headers = {
|
| 153 |
+
"xi-api-key": api_key,
|
| 154 |
+
"Content-Type": "application/json",
|
| 155 |
+
"Accept": "audio/mpeg",
|
| 156 |
+
}
|
| 157 |
+
payload = {
|
| 158 |
+
"text": texte[:4500], # limite API
|
| 159 |
+
"model_id": "eleven_multilingual_v2",
|
| 160 |
+
"voice_settings": {
|
| 161 |
+
"stability": 0.50,
|
| 162 |
+
"similarity_boost": 0.80,
|
| 163 |
+
"style": 0.50,
|
| 164 |
+
"use_speaker_boost": True,
|
| 165 |
+
},
|
| 166 |
+
}
|
| 167 |
|
| 168 |
+
try:
|
| 169 |
+
r = requests.post(url, json=payload, headers=headers, timeout=45)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
if r.status_code == 401:
|
| 172 |
+
return False, "❌ Clé ElevenLabs invalide. Vérifiez dans HF Secrets."
|
| 173 |
+
if r.status_code == 422:
|
| 174 |
+
return False, "❌ Voice ID introuvable. Changez de voix dans la sidebar."
|
| 175 |
+
if r.status_code == 429:
|
| 176 |
+
return False, "❌ Quota ElevenLabs dépassé. Attendez ou changez de plan."
|
| 177 |
|
| 178 |
+
r.raise_for_status()
|
|
|
|
| 179 |
|
| 180 |
+
with open(output_path, "wb") as f:
|
| 181 |
+
f.write(r.content)
|
| 182 |
+
|
| 183 |
+
taille = Path(output_path).stat().st_size
|
| 184 |
+
if taille < 2000:
|
| 185 |
+
return False, f"Audio trop petit ({taille} octets) — réponse API anormale."
|
| 186 |
+
|
| 187 |
+
return True, f"Audio généré ({taille // 1024} Ko)"
|
| 188 |
+
|
| 189 |
+
except requests.exceptions.Timeout:
|
| 190 |
+
return False, "Timeout ElevenLabs (>45s). Réessayez."
|
| 191 |
+
except Exception as e:
|
| 192 |
+
return False, f"Erreur ElevenLabs : {str(e)[:120]}"
|
| 193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
+
def generer_audio_gtts(texte: str, output_path: str) -> tuple[bool, str]:
|
| 196 |
+
"""Fallback gTTS — voix FR gratuite."""
|
| 197 |
try:
|
| 198 |
from gtts import gTTS
|
| 199 |
+
propre = (texte
|
| 200 |
+
.replace("'", " ").replace('"', " ")
|
| 201 |
+
.replace(":", " ").replace("&", "et"))
|
| 202 |
gTTS(text=propre, lang="fr", tld="fr").save(output_path)
|
| 203 |
+
taille = Path(output_path).stat().st_size
|
| 204 |
+
if taille < 1000:
|
| 205 |
+
return False, "gTTS a généré un fichier vide."
|
| 206 |
+
return True, f"Voix gTTS générée ({taille // 1024} Ko)"
|
| 207 |
except Exception as e:
|
| 208 |
+
return False, f"Erreur gTTS : {str(e)[:120]}"
|
|
|
|
| 209 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
+
def generer_audio(texte: str, output_path: str, logger) -> bool:
|
| 212 |
+
"""Tente ElevenLabs, bascule sur gTTS si échec."""
|
| 213 |
+
ok, msg = generer_audio_elevenlabs(texte, output_path)
|
| 214 |
+
if ok:
|
| 215 |
+
logger.success(f"🎙️ Voix masculine ElevenLabs : {msg}")
|
| 216 |
+
return True
|
| 217 |
+
|
| 218 |
+
logger.warning(f"ElevenLabs → {msg} — Bascule sur gTTS...")
|
| 219 |
+
ok, msg = generer_audio_gtts(texte, output_path)
|
| 220 |
+
if ok:
|
| 221 |
+
logger.info(f"🎙️ {msg}")
|
| 222 |
+
return True
|
| 223 |
+
|
| 224 |
+
logger.error(f"Audio impossible : {msg}")
|
| 225 |
+
return False
|
| 226 |
+
|
| 227 |
|
| 228 |
+
# ═══════════════════════════════════════════════════════════════
|
| 229 |
+
# TÉLÉCHARGEMENT IMAGES — Unsplash
|
| 230 |
+
# ═══════════════════════════════════════════════════════════════
|
| 231 |
+
|
| 232 |
+
def telecharger_images(joueur: str, n: int, logger) -> List[str]:
|
| 233 |
+
"""
|
| 234 |
+
Tente les clés Unsplash dans l'ordre.
|
| 235 |
+
Retourne une liste de chemins d'images valides.
|
| 236 |
+
"""
|
| 237 |
+
cles = [
|
| 238 |
+
k for k in [
|
| 239 |
+
st.session_state["unsplash_key1"],
|
| 240 |
+
st.session_state["unsplash_key2"],
|
| 241 |
+
] if k and k.strip()
|
| 242 |
+
]
|
| 243 |
+
|
| 244 |
+
if not cles:
|
| 245 |
+
logger.warning("Pas de clé Unsplash → fond coloré.")
|
| 246 |
return []
|
| 247 |
|
| 248 |
+
for idx, cle in enumerate(cles):
|
| 249 |
try:
|
| 250 |
+
logger.info(f"Recherche images Unsplash (clé #{idx+1})...")
|
| 251 |
r = requests.get(
|
| 252 |
"https://api.unsplash.com/search/photos",
|
| 253 |
+
params={
|
| 254 |
+
"query": f"{joueur} football soccer",
|
| 255 |
+
"per_page": n,
|
| 256 |
+
"orientation": "portrait",
|
| 257 |
+
"content_filter": "high",
|
| 258 |
+
},
|
| 259 |
+
headers={"Authorization": f"Client-ID {cle}"},
|
| 260 |
+
timeout=15,
|
| 261 |
)
|
| 262 |
+
|
| 263 |
if r.status_code == 401:
|
| 264 |
+
logger.warning(f"Clé Unsplash #{idx+1} invalide (401).")
|
| 265 |
continue
|
| 266 |
if r.status_code == 429:
|
| 267 |
+
logger.warning(f"Clé Unsplash #{idx+1} quota atteint (429).")
|
| 268 |
+
continue
|
| 269 |
+
if r.status_code != 200:
|
| 270 |
+
logger.warning(f"Unsplash #{idx+1} erreur {r.status_code}.")
|
| 271 |
continue
|
|
|
|
| 272 |
|
| 273 |
+
resultats = r.json().get("results", [])
|
| 274 |
+
if not resultats:
|
| 275 |
+
logger.warning(f"Aucune image trouvée pour '{joueur}'.")
|
| 276 |
+
continue
|
| 277 |
|
| 278 |
+
logger.info(f"{len(resultats)} image(s) trouvée(s).")
|
| 279 |
paths = []
|
| 280 |
+
|
| 281 |
+
for i, item in enumerate(resultats[:n]):
|
| 282 |
+
img_url = item["urls"].get("regular", item["urls"].get("small", ""))
|
| 283 |
+
if not img_url:
|
| 284 |
+
continue
|
| 285 |
try:
|
| 286 |
+
ir = requests.get(img_url, timeout=20)
|
| 287 |
+
ir.raise_for_status()
|
| 288 |
+
p = os.path.join(tempfile.gettempdir(), f"pf_{uuid.uuid4().hex[:8]}.jpg")
|
| 289 |
with open(p, "wb") as f:
|
| 290 |
+
f.write(ir.content)
|
| 291 |
+
if Path(p).stat().st_size > 5000:
|
| 292 |
paths.append(p)
|
| 293 |
+
logger.info(f" Image {i+1} OK ({Path(p).stat().st_size // 1024} Ko)")
|
| 294 |
+
else:
|
| 295 |
+
Path(p).unlink(missing_ok=True)
|
| 296 |
+
except Exception as e:
|
| 297 |
+
logger.warning(f" Image {i+1} échouée : {e}")
|
| 298 |
+
|
| 299 |
+
if paths:
|
| 300 |
+
return paths
|
| 301 |
|
| 302 |
except Exception as e:
|
| 303 |
+
logger.warning(f"Unsplash clé #{idx+1} : {str(e)[:80]}")
|
| 304 |
continue
|
| 305 |
|
| 306 |
+
logger.warning("Toutes les clés Unsplash ont échoué → fond coloré.")
|
| 307 |
return []
|
| 308 |
|
| 309 |
+
|
| 310 |
+
# ═══════════════════════════════════════════════════════════════
|
| 311 |
+
# CONSTRUCTION VIDÉO — FFmpeg
|
| 312 |
+
# ═══════════════════════════════════════════════════════════════
|
| 313 |
+
|
| 314 |
+
def verifier_ffmpeg() -> bool:
|
| 315 |
+
try:
|
| 316 |
+
subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
|
| 317 |
+
return True
|
| 318 |
+
except Exception:
|
| 319 |
+
return False
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def image_vers_clip(img_path: str, duration: float, out: str) -> bool:
|
| 323 |
+
"""Convertit une image en clip MP4 vertical."""
|
| 324 |
cmd = [
|
| 325 |
+
"ffmpeg", "-y",
|
| 326 |
+
"-loop", "1",
|
| 327 |
+
"-i", img_path,
|
| 328 |
+
"-t", str(duration),
|
| 329 |
+
"-vf", (
|
| 330 |
+
f"scale={VIDEO_W}:{VIDEO_H}:force_original_aspect_ratio=increase,"
|
| 331 |
+
f"crop={VIDEO_W}:{VIDEO_H},"
|
| 332 |
+
"setsar=1,format=yuv420p"
|
| 333 |
+
),
|
| 334 |
+
"-c:v", "libx264",
|
| 335 |
+
"-preset", "fast",
|
| 336 |
+
"-pix_fmt", "yuv420p",
|
| 337 |
+
"-r", "25",
|
| 338 |
+
out,
|
| 339 |
]
|
| 340 |
try:
|
| 341 |
+
res = subprocess.run(cmd, capture_output=True, timeout=60)
|
| 342 |
+
return res.returncode == 0 and Path(out).stat().st_size > 1000
|
| 343 |
+
except Exception:
|
|
|
|
| 344 |
return False
|
| 345 |
|
| 346 |
+
|
| 347 |
+
def fond_colore_clip(duration: float, out: str) -> bool:
|
| 348 |
+
"""Crée un fond dégradé sombre si pas d'images."""
|
| 349 |
cmd = [
|
| 350 |
+
"ffmpeg", "-y",
|
| 351 |
+
"-f", "lavfi",
|
| 352 |
+
"-i", f"color=c=0x0a1628:s={VIDEO_W}x{VIDEO_H}:r=25:d={duration}",
|
| 353 |
+
"-c:v", "libx264", "-preset", "fast",
|
| 354 |
+
"-pix_fmt", "yuv420p",
|
| 355 |
+
out,
|
| 356 |
]
|
| 357 |
try:
|
| 358 |
+
res = subprocess.run(cmd, capture_output=True, timeout=30)
|
| 359 |
+
return res.returncode == 0
|
| 360 |
+
except Exception:
|
|
|
|
| 361 |
return False
|
| 362 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
+
def escape_ff(text: str) -> str:
|
| 365 |
+
"""Échappe les caractères spéciaux pour ffmpeg drawtext."""
|
| 366 |
+
for c, r in [("\\","\\\\"), ("'","\u2019"), (":",r"\:"), ("%","\\%"), ("[","\\["), ("]","\\]")]:
|
| 367 |
+
text = text.replace(c, r)
|
| 368 |
+
return text
|
| 369 |
|
| 370 |
+
|
| 371 |
+
def assembler_video(joueur: str, script: str, logger) -> Optional[str]:
|
| 372 |
+
"""
|
| 373 |
+
Pipeline complet :
|
| 374 |
+
1. Audio → ElevenLabs ou gTTS
|
| 375 |
+
2. Images → Unsplash ou fond coloré
|
| 376 |
+
3. Clips → FFmpeg image → MP4
|
| 377 |
+
4. Concat → slideshow
|
| 378 |
+
5. Mixage → texte + audio → vidéo finale
|
| 379 |
+
"""
|
| 380 |
+
if not verifier_ffmpeg():
|
| 381 |
+
logger.error("FFmpeg non disponible sur ce serveur.")
|
| 382 |
+
return None
|
| 383 |
+
|
| 384 |
+
uid = uuid.uuid4().hex[:8]
|
| 385 |
+
tmp = tempfile.gettempdir()
|
| 386 |
+
to_clean = []
|
| 387 |
|
| 388 |
try:
|
| 389 |
+
# ── 1. AUDIO ─────────────────────────────────────────────────────────
|
| 390 |
+
logger.info("⏳ Étape 1/4 — Génération de la voix...")
|
| 391 |
+
audio_path = os.path.join(tmp, f"pf_audio_{uid}.mp3")
|
| 392 |
+
to_clean.append(audio_path)
|
| 393 |
+
|
| 394 |
+
if not generer_audio(script, audio_path, logger):
|
| 395 |
return None
|
|
|
|
|
|
|
| 396 |
|
| 397 |
+
# Durée réelle de l'audio
|
| 398 |
+
try:
|
| 399 |
+
from mutagen.mp3 import MP3
|
| 400 |
+
duration = max(MIN_DURATION, math.ceil(MP3(audio_path).info.length) + 2)
|
| 401 |
+
except Exception:
|
| 402 |
+
duration = max(MIN_DURATION, int(len(script.split()) * WPM_FACTOR) + 5)
|
| 403 |
+
|
| 404 |
+
logger.info(f"Durée audio : {duration}s")
|
| 405 |
|
| 406 |
+
# ── 2. IMAGES ─────────────────────────────────────────────────────────
|
| 407 |
+
logger.info("⏳ Étape 2/4 — Téléchargement des images...")
|
| 408 |
+
images = telecharger_images(joueur, n=5, logger=logger)
|
| 409 |
+
to_clean.extend(images)
|
| 410 |
+
|
| 411 |
+
# ── 3. CLIPS ─────────────────────────────────────────────────────────
|
| 412 |
+
logger.info("⏳ Étape 3/4 — Création des clips vidéo...")
|
| 413 |
+
clips = []
|
| 414 |
+
|
| 415 |
+
if images:
|
| 416 |
seg = round(duration / len(images), 2)
|
| 417 |
+
logger.info(f"{len(images)} image(s), {seg}s par segment")
|
| 418 |
for i, img in enumerate(images):
|
| 419 |
cp = os.path.join(tmp, f"pf_clip_{uid}_{i}.mp4")
|
| 420 |
+
to_clean.append(cp)
|
| 421 |
+
if image_vers_clip(img, seg, cp):
|
| 422 |
clips.append(cp)
|
| 423 |
+
logger.info(f" Clip {i+1}/{len(images)} OK")
|
| 424 |
+
else:
|
| 425 |
+
logger.warning(f" Clip {i+1} échoué")
|
| 426 |
|
| 427 |
if not clips:
|
| 428 |
+
logger.info("Génération fond coloré...")
|
| 429 |
+
clip_bg = os.path.join(tmp, f"pf_bg_{uid}.mp4")
|
| 430 |
+
to_clean.append(clip_bg)
|
| 431 |
+
if fond_colore_clip(duration, clip_bg):
|
| 432 |
+
clips.append(clip_bg)
|
| 433 |
+
else:
|
| 434 |
+
logger.error("Impossible de créer le fond coloré.")
|
| 435 |
+
return None
|
| 436 |
+
|
| 437 |
+
# ── 4. CONCAT ─────────────────────────────────────────────────────────
|
| 438 |
+
concat_file = os.path.join(tmp, f"pf_concat_{uid}.txt")
|
| 439 |
+
slideshow = os.path.join(tmp, f"pf_slide_{uid}.mp4")
|
| 440 |
+
to_clean.extend([concat_file, slideshow])
|
| 441 |
|
|
|
|
| 442 |
with open(concat_file, "w") as f:
|
| 443 |
for c in clips:
|
| 444 |
f.write(f"file '{c}'\n")
|
| 445 |
|
| 446 |
+
cmd_concat = [
|
| 447 |
+
"ffmpeg", "-y",
|
| 448 |
+
"-f", "concat", "-safe", "0",
|
| 449 |
"-i", concat_file,
|
| 450 |
+
"-c:v", "libx264", "-preset", "fast",
|
| 451 |
+
"-pix_fmt", "yuv420p",
|
| 452 |
slideshow,
|
| 453 |
+
]
|
| 454 |
+
res = subprocess.run(cmd_concat, capture_output=True, timeout=120)
|
| 455 |
+
if res.returncode != 0:
|
| 456 |
+
logger.error(f"Concat échoué : {res.stderr.decode()[-200:]}")
|
| 457 |
+
return None
|
| 458 |
+
|
| 459 |
+
# ── 5. MIXAGE FINAL ───────────────────────────────────────────────────
|
| 460 |
+
logger.info("⏳ Étape 4/4 — Mixage final (texte + audio)...")
|
| 461 |
+
video_out = os.path.join(tmp, f"pf_final_{uid}.mp4")
|
| 462 |
+
|
| 463 |
+
j_esc = escape_ff(joueur.upper()[:24])
|
| 464 |
+
t_esc = escape_ff(script[:60] + "..." if len(script) > 60 else script)
|
| 465 |
|
|
|
|
| 466 |
vf = (
|
| 467 |
+
# Bande noire semi-transparente
|
| 468 |
+
"drawbox=y=0:x=0:width=iw:height=200:color=black@0.70:t=fill,"
|
| 469 |
+
"drawbox=y=ih-180:x=0:width=iw:height=180:color=black@0.70:t=fill,"
|
| 470 |
+
# Logo chaîne
|
| 471 |
+
f"drawtext=text='⚽ PRISME FOOT':fontcolor=#FFD700:fontsize=38"
|
| 472 |
+
f":x=(w-text_w)/2:y=40:shadowcolor=black:shadowx=2:shadowy=2,"
|
| 473 |
+
# Nom du joueur
|
| 474 |
+
f"drawtext=text='{j_esc}':fontcolor=white:fontsize=52:x=(w-text_w)/2:y=100"
|
| 475 |
+
f":box=1:boxcolor=#CC0000@0.85:boxborderw=12"
|
| 476 |
+
f":shadowcolor=black:shadowx=3:shadowy=3,"
|
| 477 |
+
# Sous-titre actu
|
| 478 |
+
f"drawtext=text='{t_esc}':fontcolor=white:fontsize=22:x=(w-text_w)/2"
|
| 479 |
+
f":y=ih-140:shadowcolor=black:shadowx=1:shadowy=1,"
|
| 480 |
+
# CTA abonnement
|
| 481 |
+
"drawtext=text='👍 ABONNEZ-VOUS':fontcolor=#FFD700:fontsize=28"
|
| 482 |
+
":x=(w-text_w)/2:y=ih-80:shadowcolor=black:shadowx=2:shadowy=2"
|
| 483 |
)
|
| 484 |
+
|
| 485 |
+
cmd_final = [
|
| 486 |
"ffmpeg", "-y",
|
| 487 |
+
"-i", slideshow,
|
| 488 |
+
"-i", audio_path,
|
| 489 |
"-vf", vf,
|
| 490 |
+
"-c:v", "libx264", "-preset", "fast",
|
| 491 |
+
"-c:a", "aac", "-b:a", "128k",
|
| 492 |
+
"-t", str(duration),
|
| 493 |
+
"-shortest",
|
| 494 |
+
"-movflags", "+faststart",
|
| 495 |
video_out,
|
| 496 |
+
]
|
| 497 |
+
res = subprocess.run(cmd_final, capture_output=True, timeout=180)
|
| 498 |
+
if res.returncode != 0:
|
| 499 |
+
logger.error(f"Mixage échoué :\n{res.stderr.decode()[-400:]}")
|
| 500 |
+
return None
|
| 501 |
|
| 502 |
+
if not Path(video_out).exists() or Path(video_out).stat().st_size < 10000:
|
| 503 |
+
logger.error("Vidéo finale vide ou corrompue.")
|
| 504 |
+
return None
|
| 505 |
+
|
| 506 |
+
taille_mo = Path(video_out).stat().st_size / (1024 * 1024)
|
| 507 |
+
logger.success(f"✅ Vidéo créée ! ({taille_mo:.1f} Mo, {duration}s)")
|
| 508 |
+
return video_out
|
| 509 |
|
|
|
|
|
|
|
|
|
|
| 510 |
except Exception as e:
|
| 511 |
+
logger.error(f"Erreur inattendue : {str(e)}")
|
| 512 |
return None
|
| 513 |
+
|
| 514 |
finally:
|
| 515 |
+
cleanup(*to_clean)
|
| 516 |
|
|
|
|
|
|
|
|
|
|
| 517 |
|
| 518 |
+
# ═══════════════════════════════════════════════════════════════
|
| 519 |
+
# INTERFACE STREAMLIT
|
| 520 |
+
# ═══════════════════════════════════════════════════════════════
|
| 521 |
+
|
| 522 |
+
st.set_page_config(
|
| 523 |
+
page_title="⚽ Prisme Foot Studio",
|
| 524 |
+
page_icon="⚽",
|
| 525 |
+
layout="wide",
|
| 526 |
+
initial_sidebar_state="expanded",
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
# CSS personnalisé
|
| 530 |
+
st.markdown("""
|
| 531 |
+
<style>
|
| 532 |
+
.main-title {
|
| 533 |
+
font-size: 2.2rem;
|
| 534 |
+
font-weight: 800;
|
| 535 |
+
background: linear-gradient(135deg, #FFD700, #FF4444);
|
| 536 |
+
-webkit-background-clip: text;
|
| 537 |
+
-webkit-text-fill-color: transparent;
|
| 538 |
+
text-align: center;
|
| 539 |
+
margin-bottom: 0.2rem;
|
| 540 |
+
}
|
| 541 |
+
.sub-title {
|
| 542 |
+
text-align: center;
|
| 543 |
+
color: #888;
|
| 544 |
+
font-size: 0.9rem;
|
| 545 |
+
margin-bottom: 2rem;
|
| 546 |
+
}
|
| 547 |
+
.status-ok { color: #00C853; font-weight: 600; }
|
| 548 |
+
.status-ko { color: #FF1744; font-weight: 600; }
|
| 549 |
+
.step-badge {
|
| 550 |
+
background: linear-gradient(135deg, #FFD700, #FF8C00);
|
| 551 |
+
color: #000;
|
| 552 |
+
padding: 2px 12px;
|
| 553 |
+
border-radius: 20px;
|
| 554 |
+
font-weight: 700;
|
| 555 |
+
font-size: 0.8rem;
|
| 556 |
+
}
|
| 557 |
+
</style>
|
| 558 |
+
""", unsafe_allow_html=True)
|
| 559 |
+
|
| 560 |
+
st.markdown('<div class="main-title">⚽ PRISME FOOT STUDIO</div>', unsafe_allow_html=True)
|
| 561 |
+
st.markdown('<div class="sub-title">Créateur de vidéos football automatisées — Version Finale</div>', unsafe_allow_html=True)
|
| 562 |
+
|
| 563 |
+
# ── SIDEBAR — Configuration ───────────────────────────────────────────────────
|
| 564 |
with st.sidebar:
|
| 565 |
+
st.markdown("## ⚙️ Configuration")
|
|
|
|
| 566 |
|
| 567 |
+
# ── ElevenLabs ────────────────────────────────────────────
|
| 568 |
+
st.markdown("### 🎙️ Voix ElevenLabs")
|
| 569 |
+
el_key_input = st.text_input(
|
| 570 |
+
"Clé API ElevenLabs",
|
| 571 |
value=st.session_state["el_api_key"],
|
| 572 |
type="password",
|
| 573 |
+
placeholder="sk_xxxxxxxxxxxxxxxxxxxxxxxx",
|
| 574 |
+
help="Copiez depuis elevenlabs.io → Profile → API Key",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 575 |
)
|
| 576 |
+
if el_key_input.strip() != st.session_state["el_api_key"]:
|
| 577 |
+
st.session_state["el_api_key"] = el_key_input.strip()
|
| 578 |
|
| 579 |
+
voix_labels = list(VOIX_DISPONIBLES.keys())
|
| 580 |
+
voix_ids = list(VOIX_DISPONIBLES.values())
|
| 581 |
+
idx_actuel = voix_ids.index(st.session_state["el_voice_id"]) \
|
| 582 |
+
if st.session_state["el_voice_id"] in voix_ids else 0
|
| 583 |
+
|
| 584 |
+
voix_choisie = st.selectbox("Voix masculine", voix_labels, index=idx_actuel)
|
| 585 |
+
st.session_state["el_voice_id"] = VOIX_DISPONIBLES[voix_choisie]
|
| 586 |
+
|
| 587 |
+
if st.session_state["el_api_key"]:
|
| 588 |
+
st.markdown('<span class="status-ok">✅ Clé ElevenLabs configurée</span>', unsafe_allow_html=True)
|
| 589 |
else:
|
| 590 |
+
st.markdown('<span class="status-ko">⚠️ Pas de clé → voix gTTS</span>', unsafe_allow_html=True)
|
| 591 |
|
| 592 |
st.divider()
|
| 593 |
|
| 594 |
+
# ── Unsplash ───────────────────────────────────────────────
|
| 595 |
+
st.markdown("### 🖼️ Images Unsplash")
|
| 596 |
+
k1 = st.text_input(
|
| 597 |
+
"Clé Unsplash #1",
|
| 598 |
+
value=st.session_state["unsplash_key1"],
|
| 599 |
+
type="password",
|
| 600 |
+
placeholder="Clé Access Unsplash",
|
| 601 |
+
help="unsplash.com/developers → New Application → Access Key",
|
| 602 |
+
)
|
| 603 |
+
k2 = st.text_input(
|
| 604 |
+
"Clé Unsplash #2 (secours)",
|
| 605 |
+
value=st.session_state["unsplash_key2"],
|
| 606 |
+
type="password",
|
| 607 |
+
placeholder="Optionnelle",
|
| 608 |
+
)
|
| 609 |
+
if k1.strip() != st.session_state["unsplash_key1"]:
|
| 610 |
+
st.session_state["unsplash_key1"] = k1.strip()
|
| 611 |
+
if k2.strip() != st.session_state["unsplash_key2"]:
|
| 612 |
+
st.session_state["unsplash_key2"] = k2.strip()
|
| 613 |
+
|
| 614 |
+
nb_cles = sum(1 for x in [k1, k2] if x.strip())
|
| 615 |
+
if nb_cles:
|
| 616 |
+
st.markdown(f'<span class="status-ok">✅ {nb_cles} clé(s) Unsplash</span>', unsafe_allow_html=True)
|
| 617 |
else:
|
| 618 |
+
st.markdown('<span class="status-ko">⚠️ Pas de clé → fond coloré</span>', unsafe_allow_html=True)
|
| 619 |
+
|
| 620 |
+
st.divider()
|
| 621 |
+
st.markdown("### 📋 État du système")
|
| 622 |
+
ffmpeg_ok = verifier_ffmpeg()
|
| 623 |
+
st.markdown(f'FFmpeg : {"✅ OK" if ffmpeg_ok else "❌ Manquant"}')
|
| 624 |
+
try:
|
| 625 |
+
import feedparser
|
| 626 |
+
st.markdown("feedparser : ✅ OK")
|
| 627 |
+
except ImportError:
|
| 628 |
+
st.markdown("feedparser : ⚠️ absent (actu désactivée)")
|
| 629 |
+
try:
|
| 630 |
+
from mutagen.mp3 import MP3
|
| 631 |
+
st.markdown("mutagen : ✅ OK")
|
| 632 |
+
except ImportError:
|
| 633 |
+
st.markdown("mutagen : ⚠️ absent")
|
| 634 |
+
|
| 635 |
+
# ── ZONE PRINCIPALE ──────────────────────────────────────────────────────────
|
| 636 |
+
col_main, col_preview = st.columns([3, 2])
|
| 637 |
+
|
| 638 |
+
with col_main:
|
| 639 |
+
# ÉTAPE 1 — Joueur + Script
|
| 640 |
+
st.markdown('<span class="step-badge">ÉTAPE 1</span> **Joueur et script**', unsafe_allow_html=True)
|
| 641 |
+
st.markdown("")
|
| 642 |
+
|
| 643 |
+
joueur = st.text_input(
|
| 644 |
+
"👤 Nom du joueur",
|
| 645 |
+
value="Vinicius Junior",
|
| 646 |
+
placeholder="Ex: Mbappé, Ronaldo, Salah...",
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
col_a, col_b = st.columns([1, 1])
|
| 650 |
+
with col_a:
|
| 651 |
+
if st.button("🔍 Générer le script", use_container_width=True, type="primary"):
|
| 652 |
+
if not joueur.strip():
|
| 653 |
+
st.warning("Entrez le nom d'un joueur.")
|
| 654 |
+
else:
|
| 655 |
+
with st.spinner("Recherche de l'actualité..."):
|
| 656 |
+
actu = recuperer_actu(joueur)
|
| 657 |
+
script = generer_script(joueur, actu)
|
| 658 |
+
st.session_state["script_texte"] = script
|
| 659 |
+
nb = len(script.split())
|
| 660 |
+
duree = round(nb * WPM_FACTOR)
|
| 661 |
+
st.success(f"Script généré — {nb} mots ≈ {duree}s")
|
| 662 |
+
|
| 663 |
+
with col_b:
|
| 664 |
+
if st.button("🔄 Réinitialiser", use_container_width=True):
|
| 665 |
+
st.session_state["script_texte"] = ""
|
| 666 |
+
st.session_state["video_path"] = ""
|
| 667 |
+
st.rerun()
|
| 668 |
+
|
| 669 |
+
# Zone texte script — toujours pré-remplie
|
| 670 |
+
script_final = st.text_area(
|
| 671 |
+
"📝 Script (modifiable)",
|
| 672 |
+
value=st.session_state["script_texte"],
|
| 673 |
+
height=280,
|
| 674 |
+
placeholder="Cliquez sur 'Générer le script' ou écrivez votre texte ici...",
|
| 675 |
+
key="script_area_input",
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
# Sync session_state à chaque modification
|
| 679 |
+
if script_final != st.session_state["script_texte"]:
|
| 680 |
+
st.session_state["script_texte"] = script_final
|
| 681 |
+
|
| 682 |
+
# Métriques script
|
| 683 |
+
if script_final.strip():
|
| 684 |
+
nb_mots = len(script_final.split())
|
| 685 |
+
duree_est = round(nb_mots * WPM_FACTOR)
|
| 686 |
+
manque = max(0, MIN_DURATION - duree_est)
|
| 687 |
+
c1, c2, c3 = st.columns(3)
|
| 688 |
+
c1.metric("Mots", nb_mots)
|
| 689 |
+
c2.metric("Durée estimée", f"{duree_est}s")
|
| 690 |
+
c3.metric("Durée min requise", f"{MIN_DURATION}s",
|
| 691 |
+
delta=f"+{manque}s manquants" if manque else "✅ OK",
|
| 692 |
+
delta_color="inverse" if manque else "normal")
|
| 693 |
+
|
| 694 |
+
st.divider()
|
| 695 |
+
|
| 696 |
+
# ÉTAPE 2 — Création vidéo
|
| 697 |
+
st.markdown('<span class="step-badge">ÉTAPE 2</span> **Création de la vidéo**', unsafe_allow_html=True)
|
| 698 |
+
st.markdown("")
|
| 699 |
+
|
| 700 |
+
peut_creer = bool(script_final.strip()) and bool(joueur.strip()) and ffmpeg_ok
|
| 701 |
+
|
| 702 |
+
if not peut_creer:
|
| 703 |
+
if not ffmpeg_ok:
|
| 704 |
+
st.error("❌ FFmpeg non disponible sur ce serveur HuggingFace.")
|
| 705 |
+
elif not script_final.strip():
|
| 706 |
+
st.info("⬆️ Générez ou écrivez un script d'abord.")
|
| 707 |
+
|
| 708 |
+
if st.button(
|
| 709 |
+
"🎬 CRÉER LA VIDÉO",
|
| 710 |
+
disabled=not peut_creer,
|
| 711 |
+
use_container_width=True,
|
| 712 |
+
type="primary",
|
| 713 |
+
):
|
| 714 |
+
st.session_state["video_path"] = ""
|
| 715 |
+
log_container = st.empty()
|
| 716 |
+
|
| 717 |
+
class Logger:
|
| 718 |
+
"""Logger inline dans Streamlit."""
|
| 719 |
+
def __init__(self, container):
|
| 720 |
+
self.msgs = []
|
| 721 |
+
self.c = container
|
| 722 |
+
|
| 723 |
+
def _render(self):
|
| 724 |
+
self.c.markdown("\n\n".join(self.msgs))
|
| 725 |
+
|
| 726 |
+
def info(self, msg):
|
| 727 |
+
self.msgs.append(f"ℹ️ {msg}")
|
| 728 |
+
self._render()
|
| 729 |
+
|
| 730 |
+
def success(self, msg):
|
| 731 |
+
self.msgs.append(f"✅ {msg}")
|
| 732 |
+
self._render()
|
| 733 |
+
|
| 734 |
+
def warning(self, msg):
|
| 735 |
+
self.msgs.append(f"⚠️ {msg}")
|
| 736 |
+
self._render()
|
| 737 |
+
|
| 738 |
+
def error(self, msg):
|
| 739 |
+
self.msgs.append(f"❌ {msg}")
|
| 740 |
+
self._render()
|
| 741 |
+
|
| 742 |
+
logger = Logger(log_container)
|
| 743 |
+
|
| 744 |
+
with st.spinner("🎬 Montage en cours... (30 à 90 secondes)"):
|
| 745 |
+
video_path = assembler_video(joueur.strip(), script_final, logger)
|
| 746 |
+
|
| 747 |
+
if video_path and Path(video_path).exists():
|
| 748 |
+
st.session_state["video_path"] = video_path
|
| 749 |
+
st.balloons()
|
| 750 |
+
else:
|
| 751 |
+
st.error("La vidéo n'a pas pu être créée. Consultez les messages ci-dessus.")
|
| 752 |
+
|
| 753 |
+
# ── COLONNE PREVIEW ────────────────────────────────────────────────────────────
|
| 754 |
+
with col_preview:
|
| 755 |
+
st.markdown("### 📱 Aperçu & Téléchargement")
|
| 756 |
+
st.markdown("")
|
| 757 |
+
|
| 758 |
+
vp = st.session_state.get("video_path", "")
|
| 759 |
+
if vp and Path(vp).exists():
|
| 760 |
+
st.video(vp)
|
| 761 |
+
st.markdown("")
|
| 762 |
+
with open(vp, "rb") as f:
|
| 763 |
+
nom_fichier = f"prisme_{joueur.replace(' ', '_').lower()}.mp4"
|
| 764 |
st.download_button(
|
| 765 |
+
label="⬇️ Télécharger la vidéo MP4",
|
| 766 |
+
data=f,
|
| 767 |
+
file_name=nom_fichier,
|
| 768 |
mime="video/mp4",
|
| 769 |
use_container_width=True,
|
| 770 |
+
type="primary",
|
| 771 |
)
|
| 772 |
+
taille = Path(vp).stat().st_size / (1024 * 1024)
|
| 773 |
+
st.caption(f"Fichier : {nom_fichier} — {taille:.1f} Mo")
|
|
|
|
|
|
|
| 774 |
else:
|
| 775 |
+
st.markdown("""
|
| 776 |
+
<div style="
|
| 777 |
+
border: 2px dashed #444;
|
| 778 |
+
border-radius: 12px;
|
| 779 |
+
padding: 60px 20px;
|
| 780 |
+
text-align: center;
|
| 781 |
+
color: #666;
|
| 782 |
+
">
|
| 783 |
+
<div style="font-size: 3rem;">🎬</div>
|
| 784 |
+
<div style="margin-top: 12px; font-size: 0.9rem;">
|
| 785 |
+
La vidéo apparaîtra ici<br>après création
|
| 786 |
+
</div>
|
| 787 |
+
</div>
|
| 788 |
+
""", unsafe_allow_html=True)
|
| 789 |
|
| 790 |
+
st.divider()
|
| 791 |
+
st.markdown("### 💡 Guide rapide")
|
| 792 |
+
st.markdown("""
|
| 793 |
+
1. **Sidebar** → entrez vos clés API
|
| 794 |
+
2. **Nom du joueur** → cliquez Générer
|
| 795 |
+
3. **Modifiez** le script si besoin
|
| 796 |
+
4. **Créez la vidéo** → téléchargez
|
| 797 |
+
|
| 798 |
+
---
|
| 799 |
+
**Sans clé ElevenLabs** : voix gTTS (gratuit)
|
| 800 |
+
**Sans clé Unsplash** : fond coloré sombre
|
| 801 |
+
""")
|