PrismeFoot commited on
Commit
09d74a8
·
verified ·
1 Parent(s): d3a216f

Update app.py

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