PrismeFoot commited on
Commit
1ec6ce1
·
verified ·
1 Parent(s): 89d8c98

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +691 -337
app.py CHANGED
@@ -1,447 +1,801 @@
1
  """
2
- Prisme Foot Studio v6
3
- Compatible : Replit, Hugging Face Spaces, local
4
- Corrections : secrets via os.environ, script persisté, images + voix masculine FR
 
 
5
  """
6
 
7
- import os
8
- import uuid
9
- import subprocess
10
- import math
11
- import tempfile
12
  import requests
13
- import urllib.parse
 
14
  from typing import Optional, List
15
 
16
- import streamlit as st
17
- from mutagen.mp3 import MP3
18
-
19
- # ─── LECTURE DES SECRETS (Replit Secrets / HF Env Vars) ──────────────────────
20
- # Sur Replit : Onglet "Secrets" → ajouter les clés ci-dessous
21
- # Sur HF : Settings → Repository secrets
22
- # En local : créer un fichier .env et lancer avec python-dotenv
23
-
24
- def env(key: str, default: str = "") -> str:
25
- """Lit une variable d'environnement, avec fallback sur default."""
26
- return os.environ.get(key, default).strip()
27
-
28
- # Noms des variables à définir dans Replit Secrets :
29
- # ELEVENLABS_API_KEY → votre clé sk_...
30
- # ELEVENLABS_VOICE_ID → optionnel, défaut = Daniel FR
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
- def supprimer_fichiers(paths: List[str]) -> None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  for p in paths:
64
- if p and os.path.exists(p):
65
  try:
66
- os.remove(p)
67
- except OSError:
68
  pass
69
 
70
- # ─── GÉNÉRATION AUDIO ElevenLabs ─────────────────────────────────────────────
71
- def generer_audio(texte: str, output_path: str) -> bool:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  api_key = st.session_state["el_api_key"]
73
  voice_id = st.session_state["el_voice_id"]
74
 
75
- # ── Tentative ElevenLabs ─────────────────────────────────────────────────
76
- if api_key:
77
- try:
78
- url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
79
- headers = {
80
- "xi-api-key": api_key,
81
- "Content-Type": "application/json",
82
- "Accept": "audio/mpeg",
83
- }
84
- payload = {
85
- "text": texte,
86
- "model_id": "eleven_multilingual_v2",
87
- "voice_settings": {
88
- "stability": 0.45,
89
- "similarity_boost": 0.85,
90
- "style": 0.55,
91
- "use_speaker_boost": True,
92
- },
93
- }
94
- r = requests.post(url, json=payload, headers=headers, timeout=30)
 
95
 
96
- if r.status_code == 401:
97
- st.error("❌ Clé ElevenLabs invalide ou expirée. Vérifiez dans la sidebar.")
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
- r.raise_for_status()
 
 
 
 
 
104
 
105
- with open(output_path, "wb") as f:
106
- f.write(r.content)
107
 
108
- if os.path.getsize(output_path) < 1000:
109
- st.warning("⚠️ Audio ElevenLabs trop petit → bascule gTTS.")
110
- else:
111
- st.success("🎙️ Voix ElevenLabs masculine FR générée.")
112
- return True
 
 
 
 
 
 
 
 
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
- # ── Fallback gTTS ────────────────────────────────────────────────────────
 
122
  try:
123
  from gtts import gTTS
124
- propre = texte.replace("'", " ").replace('"', " ").replace(":", " ")
 
 
125
  gTTS(text=propre, lang="fr", tld="fr").save(output_path)
126
- st.info("🎙️ Voix gTTS (fallback) utilisée.")
127
- return True
 
 
128
  except Exception as e:
129
- st.error(f"❌ Erreur gTTS : {e}")
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 recuperer_news(joueur: str) -> str:
154
- try:
155
- import feedparser
156
- q = urllib.parse.quote(f"{joueur} football")
157
- url = f"https://news.google.com/rss/search?q={q}&hl=fr&gl=FR&ceid=FR:fr"
158
- fx = feedparser.parse(url)
159
- return fx.entries[0].title if fx.entries else ""
160
- except ImportError:
161
- return ""
162
- except Exception:
163
- return ""
 
 
 
 
 
164
 
165
- # ─── IMAGES UNSPLASH ─────────────────────────────────────────────────────────
166
- def telecharger_images(joueur: str, n: int = 4) -> List[str]:
167
- keys = st.session_state["unsplash_keys"]
168
- if not keys:
169
- st.warning("⚠️ Pas de clé Unsplash → fond coloré utilisé.")
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  return []
171
 
172
- for i, key in enumerate(keys):
173
  try:
 
174
  r = requests.get(
175
  "https://api.unsplash.com/search/photos",
176
- params={"query": f"{joueur} football", "per_page": n, "orientation": "portrait"},
177
- headers={"Authorization": f"Client-ID {key}"},
178
- timeout=10,
 
 
 
 
 
179
  )
 
180
  if r.status_code == 401:
181
- st.warning(f"Clé Unsplash #{i+1} invalide.")
182
  continue
183
  if r.status_code == 429:
184
- st.warning(f"Clé Unsplash #{i+1} quota atteint.")
 
 
 
185
  continue
186
- r.raise_for_status()
187
 
188
- results = r.json().get("results", [])
189
- if not results:
190
- st.warning(f"Unsplash : aucune image trouvée pour '{joueur}'.")
191
- return []
192
 
193
- st.info(f"Unsplash clé #{i+1} : {len(results)} image(s) trouvée(s).")
194
  paths = []
195
- for item in results[:n]:
 
 
 
 
196
  try:
197
- img_data = requests.get(item["urls"]["regular"], timeout=15).content
198
- p = os.path.join(tempfile.gettempdir(), f"pf_img_{uuid.uuid4().hex[:8]}.jpg")
 
199
  with open(p, "wb") as f:
200
- f.write(img_data)
201
- if os.path.getsize(p) > 5000:
202
  paths.append(p)
203
- except Exception:
204
- continue
205
- return paths
 
 
 
 
 
206
 
207
  except Exception as e:
208
- st.warning(f"Unsplash clé #{i+1} erreur : {e}")
209
  continue
210
 
211
- st.warning("⚠️ Toutes les clés Unsplash ont échoué → fond coloré.")
212
  return []
213
 
214
- # ─── CLIPS VIDÉO ─────────────────────────────────────────────────────────────
215
- def image_en_clip(img_path: str, duration: float, out_path: str) -> bool:
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  cmd = [
217
- "ffmpeg", "-y", "-loop", "1", "-framerate", "25",
218
- "-i", img_path, "-t", str(duration),
219
- "-vf", "scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,setsar=1,format=yuv420p",
220
- "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", out_path,
 
 
 
 
 
 
 
 
 
 
221
  ]
222
  try:
223
- subprocess.run(cmd, check=True, capture_output=True)
224
- return os.path.exists(out_path) and os.path.getsize(out_path) > 1000
225
- except subprocess.CalledProcessError as e:
226
- st.warning(f"Clip KO : {e.stderr.decode()[-200:]}")
227
  return False
228
 
229
- def fond_colore_clip(duration: float, out_path: str) -> bool:
 
 
230
  cmd = [
231
- "ffmpeg", "-y", "-f", "lavfi",
232
- "-i", f"color=c=0x001a33:s=720x1280:r=25:d={duration}",
233
- "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", out_path,
 
 
 
234
  ]
235
  try:
236
- subprocess.run(cmd, check=True, capture_output=True)
237
- return os.path.exists(out_path)
238
- except Exception as e:
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
- audio_path = os.path.join(tmp, f"pf_audio_{uid}.mp3")
249
- concat_file = os.path.join(tmp, f"pf_concat_{uid}.txt")
250
- slideshow = os.path.join(tmp, f"pf_slide_{uid}.mp4")
251
- video_out = os.path.join(tmp, f"pf_out_{uid}.mp4")
252
- temp_files = [audio_path, concat_file, slideshow]
253
 
254
- propre = texte.replace("'", " ").replace('"', " ").replace(":", " ").replace("&", "et")
255
- joueur_up = escape_drawtext(joueur.upper()[:30])
256
- titre_esc = escape_drawtext(propre[:55] + ("..." if len(propre) > 55 else ""))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
  try:
259
- # 1. Audio
260
- if not generer_audio(propre, audio_path):
 
 
 
 
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
- # 2. Images
266
- images = telecharger_images(joueur, n=4)
267
- temp_files.extend(images)
268
- clips: List[str] = []
 
 
 
 
269
 
270
- if not images:
271
- clip_bg = os.path.join(tmp, f"pf_bg_{uid}.mp4")
272
- temp_files.append(clip_bg)
273
- if fond_colore_clip(duration, clip_bg):
274
- clips.append(clip_bg)
275
- else:
 
 
 
 
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
- temp_files.append(cp)
280
- if image_en_clip(img, seg, cp):
281
  clips.append(cp)
 
 
 
282
 
283
  if not clips:
284
- st.error("❌ Aucun clip généré.")
285
- return None
 
 
 
 
 
 
 
 
 
 
 
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
- subprocess.run([
293
- "ffmpeg", "-y", "-f", "concat", "-safe", "0",
 
294
  "-i", concat_file,
295
- "-c:v", "libx264", "-preset", "ultrafast",
296
- "-c:a", "aac", "-pix_fmt", "yuv420p",
297
  slideshow,
298
- ], check=True, capture_output=True)
 
 
 
 
 
 
 
 
 
 
 
299
 
300
- # 4. Overlay texte + audio
301
  vf = (
302
- f"drawbox=y=ih/2-110:color=black@0.65:width=iw:height=300:t=fill,"
303
- f"drawtext=text='PRISME FOOT':fontcolor=yellow:fontsize=42:x=(w-text_w)/2:y=160,"
304
- f"drawtext=text='{joueur_up}':fontcolor=white:fontsize=55"
305
- f":x=(w-text_w)/2:y=305:box=1:boxcolor=red@0.8,"
306
- f"drawtext=text='{titre_esc}':fontcolor=white:fontsize=28"
307
- f":x=(w-text_w)/2:y=(h-text_h)/2+55"
 
 
 
 
 
 
 
 
 
 
308
  )
309
- subprocess.run([
 
310
  "ffmpeg", "-y",
311
- "-i", slideshow, "-i", audio_path,
 
312
  "-vf", vf,
313
- "-c:v", "libx264", "-c:a", "aac",
314
- "-t", str(duration), "-shortest",
 
 
 
315
  video_out,
316
- ], check=True, capture_output=True)
 
 
 
 
317
 
318
- return video_out if os.path.exists(video_out) else None
 
 
 
 
 
 
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
- st.error(f"Erreur : {e}")
325
  return None
 
326
  finally:
327
- supprimer_fichiers(temp_files)
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
- # ── SIDEBAR ──────────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
  with st.sidebar:
335
- st.header("⚙️ Configuration")
336
- st.caption("Les clés saisies ici écrasent les variables d'environnement.")
337
 
338
- st.subheader("🎙️ ElevenLabs — voix masculine FR")
339
- el_key = st.text_input(
340
- "Clé API ElevenLabs (sk_...)",
 
341
  value=st.session_state["el_api_key"],
342
  type="password",
343
- placeholder="sk_xxxxxxxxxxxxxxxx",
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["el_voice_id"] = choix_voix[1]
 
365
 
366
- if not st.session_state["el_api_key"]:
367
- st.warning("Sans clé ElevenLabs → voix gTTS (moins réaliste).")
 
 
 
 
 
 
 
 
368
  else:
369
- st.success("✅ Clé ElevenLabs enregistrée.")
370
 
371
  st.divider()
372
 
373
- st.subheader("🖼️ Unsplash — images")
374
- k1 = st.text_input("Clé Unsplash #1", type="password",
375
- value=st.session_state["unsplash_keys"][0] if st.session_state["unsplash_keys"] else "")
376
- k2 = st.text_input("Clé Unsplash #2 (optionnelle)", type="password",
377
- value=st.session_state["unsplash_keys"][1] if len(st.session_state["unsplash_keys"]) > 1 else "")
378
- nouvelles = [k.strip() for k in [k1, k2] if k.strip()]
379
- if nouvelles != st.session_state["unsplash_keys"]:
380
- st.session_state["unsplash_keys"] = nouvelles
381
-
382
- if not st.session_state["unsplash_keys"]:
383
- st.warning("Sans clé Unsplash → fond coloré.")
 
 
 
 
 
 
 
 
 
 
 
 
384
  else:
385
- st.success(f"✅ {len(st.session_state['unsplash_keys'])} clé(s) Unsplash.")
386
-
387
- # ── ZONE PRINCIPALE ───────────────────────────────────────────────────────────
388
- nom = st.text_input("👤 Nom du joueur", "Vinicius Junior", key="nom_joueur")
389
-
390
- if st.button("🔍 1. Chercher l'actu et générer le script", use_container_width=True):
391
- with st.spinner("Recherche en cours…"):
392
- titre = recuperer_news(nom)
393
- script = enrichir_script(nom, titre)
394
- # Double stockage : génération + édition
395
- st.session_state["script_genere"] = script
396
- st.session_state["script_edite"] = script
397
- nb = len(script.split())
398
- duree = round(nb * WPM_FACTOR)
399
- st.success(f"✅ Script généré — {nb} mots ≈ {duree}s de vidéo")
400
-
401
- # Champ script — toujours pré-rempli depuis session_state
402
- script_val = st.text_area(
403
- "📝 Script (modifiable avant création vidéo)",
404
- value=st.session_state["script_edite"],
405
- height=220,
406
- )
407
- # Persister les modifications manuelles
408
- if script_val != st.session_state["script_edite"]:
409
- st.session_state["script_edite"] = script_val
410
-
411
- # Métriques
412
- col1, col2 = st.columns(2)
413
- nb_mots = len(script_val.split()) if script_val.strip() else 0
414
- duree_est = round(nb_mots * WPM_FACTOR)
415
- with col1:
416
- st.metric("Mots dans le script", nb_mots)
417
- with col2:
418
- delta = max(0, MIN_DURATION - duree_est)
419
- st.metric("Durée estimée", f"{duree_est}s",
420
- delta=f"trop court de {delta}s" if delta else "OK ✅",
421
- delta_color="inverse" if delta else "normal")
422
-
423
- # Bouton création vidéo
424
- if st.button("🎬 2. Créer la vidéo", disabled=not script_val.strip(), use_container_width=True):
425
- with st.spinner("Montage en cours… (30 à 90s selon la connexion)"):
426
- video_path = fabriquer_video(nom, script_val)
427
-
428
- if video_path and os.path.exists(video_path):
429
- st.success("✅ Vidéo prête !")
430
- st.video(video_path)
431
- with open(video_path, "rb") as fv:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432
  st.download_button(
433
- "⬇️ Télécharger la vidéo MP4",
434
- data=fv,
435
- file_name=f"prisme_{nom.replace(' ', '_')}.mp4",
436
  mime="video/mp4",
437
  use_container_width=True,
 
438
  )
439
- try:
440
- os.remove(video_path)
441
- except OSError:
442
- pass
443
  else:
444
- st.error("❌ Échec de la création vidéo. Consultez les messages d'erreur ci-dessus.")
 
 
 
 
 
 
 
 
 
 
 
 
 
445
 
446
- st.divider()
447
- st.caption("Prisme Foot Studio v6 — Compatible Replit · Hugging Face · Local")
 
 
 
 
 
 
 
 
 
 
 
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
+ """)