PrismeFoot commited on
Commit
4957161
·
verified ·
1 Parent(s): 435c11c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +189 -118
app.py CHANGED
@@ -3,26 +3,24 @@ import streamlit as st
3
  from gtts import gTTS
4
  from mutagen.mp3 import MP3
5
 
6
- # ─── CONFIG ──────────────────────────────────────────────────────────────────
7
- UNSPLASH_KEY = os.getenv("UNSPLASH_ACCESS_KEY", "") # Clé gratuite unsplash.com
8
- MIN_DURATION = 30 # secondes minimum
9
- WPM_FACTOR = 0.38 # secondes par mot (débit gTTS français)
10
 
11
- # ─── 1. ENRICHISSEMENT DU SCRIPT ────────────────────────────────────────────
12
  def enrichir_script(joueur: str, titre: str) -> str:
13
- """Gonfle le script jusqu'à ~30 s de lecture."""
14
  phrases = [
15
  f"Bienvenue sur Prisme Foot, votre chaîne d'actualité football.",
16
- f"Aujourd'hui, focus sur {joueur}.",
17
- titre,
18
- f"{joueur} est l'un des joueurs les plus suivis de sa génération.",
19
- f"Sa technique, sa vitesse et son sens du but en font un atout majeur.",
20
- f"Les supporters du monde entier retiennent leur souffle à chaque match.",
21
- f"Restez connectés pour ne rater aucune actualité sur {joueur} et toute l'actu football.",
22
- f"Abonnez-vous à Prisme Foot pour vos analyses et résumés quotidiens.",
23
  ]
24
- texte, mots = "", 0
25
- target = int(MIN_DURATION / WPM_FACTOR)
26
  for p in phrases:
27
  texte += " " + p
28
  mots += len(p.split())
@@ -30,7 +28,7 @@ def enrichir_script(joueur: str, titre: str) -> str:
30
  break
31
  return texte.strip()
32
 
33
- # ─── 2. RECHERCHE NEWS ───────────────────────────────────────────────────────
34
  def recuperer_news_reelle(joueur: str) -> str:
35
  try:
36
  import feedparser
@@ -41,124 +39,189 @@ def recuperer_news_reelle(joueur: str) -> str:
41
  except Exception:
42
  return ""
43
 
44
- # ─── 3. TÉLÉCHARGEMENT D'IMAGES ─────────────────────────────────────────────
45
- def telecharger_images(joueur: str, n: int = 4) -> list[str]:
46
- """Retourne des chemins d'images locales via Unsplash (ou fallback couleurs)."""
47
  paths = []
48
- if UNSPLASH_KEY:
49
- try:
50
- r = requests.get(
51
- "https://api.unsplash.com/search/photos",
52
- params={"query": f"{joueur} football", "per_page": n, "orientation": "portrait"},
53
- headers={"Authorization": f"Client-ID {UNSPLASH_KEY}"},
54
- timeout=8,
55
- )
56
- for item in r.json().get("results", [])[:n]:
57
- img_url = item["urls"]["regular"]
58
- img_data = requests.get(img_url, timeout=10).content
59
- p = f"/tmp/img_{uuid.uuid4().hex[:6]}.jpg"
60
- with open(p, "wb") as f:
61
- f.write(img_data)
 
 
 
62
  paths.append(p)
63
- except Exception as e:
64
- st.warning(f"Unsplash indisponible : {e}")
65
  return paths
66
 
67
- # ─── 4. MOTEUR VIDÉO ─────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  def fabriquer_video(joueur: str, texte: str) -> str | None:
69
- uid = uuid.uuid4().hex[:6]
70
- audio = f"/tmp/a_{uid}.mp3"
71
- video = f"/tmp/v_{uid}.mp4"
 
 
72
 
73
- texte_clean = texte.replace("'", " ").replace('"', " ")
74
- joueur_up = joueur.upper()
75
 
76
  try:
77
- # ── Audio ──────────────────────────────────────────────────────────
78
- gTTS(text=texte_clean, lang="fr").save(audio)
79
- duration = max(MIN_DURATION, math.ceil(MP3(audio).info.length) + 1)
 
80
 
81
- # ── Images ─────────────────────────────────────────────────────────
82
  images = telecharger_images(joueur, n=4)
83
  n_img = len(images)
84
 
 
85
  if n_img == 0:
86
- # Fallback : fond dégradé pur FFmpeg
87
- inputs = ["-f", "lavfi", "-i", f"color=c=0x001a33:s=720x1280:d={duration}"]
88
- video_label = "[0:v]"
 
 
89
  else:
90
- # Chaque image occupe duration/n_img secondes
91
  seg = round(duration / n_img, 2)
92
- inputs = []
93
- for p in images:
94
- inputs += [
95
- "-loop", "1", "-t", str(seg),
96
- "-i", p,
97
- ]
98
- # concat + scale
99
- concat_filter = "".join(f"[{i}:v]scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,setsar=1[v{i}];" for i in range(n_img))
100
- concat_filter += "".join(f"[v{i}]" for i in range(n_img))
101
- concat_filter += f"concat=n={n_img}:v=1:a=0[slideshow]"
102
- video_label = "[slideshow]"
103
-
104
- # ── Filtre texte ───────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  titre_court = texte_clean[:55] + ("..." if len(texte_clean) > 55 else "")
106
- overlay = (
107
- f"{video_label},"
108
- f"drawbox=y=ih/2-110:color=black@0.65:width=iw:height=320:t=fill,"
109
  f"drawtext=text='PRISME FOOT':fontcolor=yellow:fontsize=42:x=(w-text_w)/2:y=160,"
110
- f"drawtext=text='{joueur_up}':fontcolor=white:fontsize=58:x=(w-text_w)/2:y=310"
111
- f":box=1:boxcolor=red@0.8,"
112
- f"drawtext=text='{titre_court}':fontcolor=white:fontsize=30"
113
- f":x=(w-text_w)/2:y=(h-text_h)/2+60[out]"
114
  )
 
 
 
 
 
 
 
 
 
 
 
115
 
116
- # ── Commande FFmpeg ────────────────────────────────────────────────
117
- if n_img == 0:
118
- cmd = (
119
- ["ffmpeg", "-y"]
120
- + inputs
121
- + ["-i", audio,
122
- "-vf", overlay.replace(f"{video_label},", "").replace("[out]", ""),
123
- "-c:v", "libx264", "-c:a", "aac",
124
- "-t", str(duration), video]
125
- )
126
- else:
127
- cmd = (
128
- ["ffmpeg", "-y"]
129
- + inputs
130
- + ["-i", audio,
131
- "-filter_complex", concat_filter + ";" + overlay,
132
- "-map", "[out]", "-map", f"{n_img}:a",
133
- "-c:v", "libx264", "-c:a", "aac",
134
- "-t", str(duration), "-shortest", video]
135
- )
136
-
137
- subprocess.run(cmd, check=True, capture_output=True)
138
-
139
- # ── Nettoyage ──────────────────────────────────────────────────────
140
- for f in [audio] + images:
141
- if os.path.exists(f):
142
  os.remove(f)
143
 
144
- return video
145
 
146
  except subprocess.CalledProcessError as e:
147
- st.error(f"FFmpeg : {e.stderr.decode()[-500:]}")
148
  except Exception as e:
149
- st.error(f"Erreur : {e}")
150
  return None
151
 
152
- # ─── INTERFACE ────────────────────────────────────────────────────────────────
153
  st.set_page_config(page_title="Prisme Foot Studio", page_icon="⚽")
154
- st.title("⚽ Prisme Foot Studio v2")
155
 
156
  with st.sidebar:
157
  st.header("⚙️ Configuration")
158
- unsplash_key = st.text_input("Clé Unsplash (gratuite)", type="password",
159
- help="api.unsplash.com → Developer → New Application")
160
- if unsplash_key:
161
- os.environ["UNSPLASH_ACCESS_KEY"] = unsplash_key
 
 
 
 
 
 
162
 
163
  if "script" not in st.session_state:
164
  st.session_state["script"] = ""
@@ -166,25 +229,33 @@ if "script" not in st.session_state:
166
  nom = st.text_input("👤 Nom du joueur", "Vinicius Junior")
167
 
168
  if st.button("🔍 1. CHERCHER L'ACTU"):
169
- with st.spinner("Recherche en cours..."):
170
  titre = recuperer_news_reelle(nom)
171
  st.session_state["script"] = enrichir_script(nom, titre)
172
- st.success(f"Script enrichi ({len(st.session_state['script'].split())} mots ≈ 30 s)")
 
173
 
174
- script_final = st.text_area("📝 Script (modifiable)", value=st.session_state["script"], height=200)
 
 
175
 
176
  col1, col2 = st.columns(2)
177
  with col1:
178
  nb_mots = len(script_final.split()) if script_final else 0
179
  duree_est = round(nb_mots * WPM_FACTOR)
180
- st.metric("⏱ Durée estimée", f"{duree_est} s", delta=f"{max(0, 30-duree_est)} s manquantes")
181
-
182
- if st.button("🎬 2. CRÉER LA VIDÉO", disabled=not script_final):
183
- if nom and script_final:
184
- with st.spinner("Montage en cours (30–60 s)…"):
185
- v = fabriquer_video(nom, script_final)
186
- if v and os.path.exists(v):
187
- st.success("✅ Vidéo prête !")
188
- st.video(v)
189
- with open(v, "rb") as fv:
190
- st.download_button("⬇️ Télécharger MP4", fv, file_name=f"prisme_{nom.replace(' ','_')}.mp4")
 
 
 
 
 
 
3
  from gtts import gTTS
4
  from mutagen.mp3 import MP3
5
 
6
+ # ─── CONFIG ───────────────────────────────────────────────────────────────────
7
+ UNSPLASH_KEY = os.getenv("UNSPLASH_ACCESS_KEY", "")
8
+ MIN_DURATION = 30
9
+ WPM_FACTOR = 0.38
10
 
11
+ # ─── ENRICHISSEMENT SCRIPT ────────────────────────────────────────────────────
12
  def enrichir_script(joueur: str, titre: str) -> str:
 
13
  phrases = [
14
  f"Bienvenue sur Prisme Foot, votre chaîne d'actualité football.",
15
+ f"Aujourd'hui, zoom sur {joueur}, l'un des joueurs les plus suivis.",
16
+ titre if titre else f"{joueur} fait parler de lui cette semaine.",
17
+ f"Sa technique, sa vitesse et son sens du but en font un joueur exceptionnel.",
18
+ f"Chaque match est une nouvelle occasion de s'illustrer au plus haut niveau.",
19
+ f"Les supporters du monde entier sont suspendus à ses performances.",
20
+ f"Restez connectés sur Prisme Foot pour toute l'actualité de {joueur}.",
21
+ f"Abonnez-vous et activez la cloche pour ne rien manquer.",
22
  ]
23
+ texte, mots, target = "", 0, int(MIN_DURATION / WPM_FACTOR)
 
24
  for p in phrases:
25
  texte += " " + p
26
  mots += len(p.split())
 
28
  break
29
  return texte.strip()
30
 
31
+ # ─── RECHERCHE NEWS ───────────────────────────────────────────────────────────
32
  def recuperer_news_reelle(joueur: str) -> str:
33
  try:
34
  import feedparser
 
39
  except Exception:
40
  return ""
41
 
42
+ # ─── TÉLÉCHARGEMENT D'IMAGES ─────────────────────────────────────────────────
43
+ def telecharger_images(joueur: str, n: int = 4) -> list:
 
44
  paths = []
45
+ if not UNSPLASH_KEY:
46
+ return paths
47
+ try:
48
+ r = requests.get(
49
+ "https://api.unsplash.com/search/photos",
50
+ params={"query": f"{joueur} football", "per_page": n, "orientation": "portrait"},
51
+ headers={"Authorization": f"Client-ID {UNSPLASH_KEY}"},
52
+ timeout=10,
53
+ )
54
+ r.raise_for_status()
55
+ for item in r.json().get("results", [])[:n]:
56
+ img_url = item["urls"]["regular"]
57
+ img_data = requests.get(img_url, timeout=15).content
58
+ p = f"/tmp/src_img_{uuid.uuid4().hex[:6]}.jpg"
59
+ with open(p, "wb") as f:
60
+ f.write(img_data)
61
+ if os.path.getsize(p) > 5000: # fichier non vide
62
  paths.append(p)
63
+ except Exception as e:
64
+ st.warning(f"Unsplash : {e}")
65
  return paths
66
 
67
+ # ─── CONVERTIR UNE IMAGE EN CLIP .MP4 ────────────────────────────────────────
68
+ def image_en_clip(img_path: str, duration: float, uid: str, idx: int) -> str | None:
69
+ """
70
+ Convertit une image JPEG en clip MP4 720x1280 de `duration` secondes.
71
+ Utilise -r 25 + -frames:v pour garantir les timestamps corrects.
72
+ Retourne le chemin du clip, ou None si échec.
73
+ """
74
+ out = f"/tmp/clip_{uid}_{idx}.mp4"
75
+ nb_frames = max(1, int(duration * 25))
76
+ cmd = [
77
+ "ffmpeg", "-y",
78
+ "-loop", "1",
79
+ "-i", img_path,
80
+ "-vf", (
81
+ "scale=720:1280:force_original_aspect_ratio=increase,"
82
+ "crop=720:1280,"
83
+ "setsar=1,"
84
+ "setpts=PTS-STARTPTS" # timestamps propres
85
+ ),
86
+ "-r", "25",
87
+ "-frames:v", str(nb_frames),
88
+ "-c:v", "libx264",
89
+ "-preset", "ultrafast",
90
+ "-pix_fmt", "yuv420p",
91
+ out
92
+ ]
93
+ try:
94
+ subprocess.run(cmd, check=True, capture_output=True)
95
+ return out if os.path.exists(out) and os.path.getsize(out) > 1000 else None
96
+ except subprocess.CalledProcessError as e:
97
+ st.warning(f"Clip {idx} KO : {e.stderr.decode()[-200:]}")
98
+ return None
99
+
100
+ # ─── FOND COLORÉ DE SECOURS ──────────────────────────────────────────────────
101
+ def fond_colore_clip(duration: float, uid: str) -> str:
102
+ """Génère un clip fond bleu marine si aucune image disponible."""
103
+ out = f"/tmp/clip_{uid}_bg.mp4"
104
+ nb_frames = max(1, int(duration * 25))
105
+ cmd = [
106
+ "ffmpeg", "-y",
107
+ "-f", "lavfi",
108
+ "-i", f"color=c=0x001a33:s=720x1280:r=25",
109
+ "-frames:v", str(nb_frames),
110
+ "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
111
+ out
112
+ ]
113
+ subprocess.run(cmd, check=True, capture_output=True)
114
+ return out
115
+
116
+ # ─── MOTEUR VIDÉO PRINCIPAL ───────────────────────────────────────────────────
117
  def fabriquer_video(joueur: str, texte: str) -> str | None:
118
+ uid = uuid.uuid4().hex[:6]
119
+ audio_path = f"/tmp/a_{uid}.mp3"
120
+ concat_list = f"/tmp/list_{uid}.txt"
121
+ video_out = f"/tmp/v_{uid}.mp4"
122
+ temp_files = [audio_path, concat_list]
123
 
124
+ texte_clean = texte.replace("'", " ").replace('"', " ").replace(":", " ")
125
+ joueur_up = joueur.upper().replace("'", " ")
126
 
127
  try:
128
+ # ── 1. Génération audio ────────────────────────────────────────────
129
+ gTTS(text=texte_clean, lang="fr").save(audio_path)
130
+ duration = max(MIN_DURATION, math.ceil(MP3(audio_path).info.length) + 1)
131
+ st.info(f"Durée audio mesurée : {duration}s")
132
 
133
+ # ── 2. Images (Unsplash ou fond) ───────────────────────────────────
134
  images = telecharger_images(joueur, n=4)
135
  n_img = len(images)
136
 
137
+ clips = []
138
  if n_img == 0:
139
+ # Fallback : 1 seul clip fond coloré
140
+ st.warning("Aucune image trouvée → fond coloré utilisé. Ajoutez une clé Unsplash dans la sidebar.")
141
+ c = fond_colore_clip(duration, uid)
142
+ clips.append(c)
143
+ temp_files.append(c)
144
  else:
 
145
  seg = round(duration / n_img, 2)
146
+ st.info(f"{n_img} image(s) téléchargée(s) → {seg}s chacune")
147
+ for i, img in enumerate(images):
148
+ c = image_en_clip(img, seg, uid, i)
149
+ if c:
150
+ clips.append(c)
151
+ temp_files.append(c)
152
+ temp_files.append(img)
153
+
154
+ if not clips:
155
+ st.error("Aucun clip vidéo généré.")
156
+ return None
157
+
158
+ # ── 3. Concat des clips via fichier liste ──────────────────────────
159
+ with open(concat_list, "w") as f:
160
+ for c in clips:
161
+ f.write(f"file '{c}'\n")
162
+
163
+ slideshow = f"/tmp/slide_{uid}.mp4"
164
+ temp_files.append(slideshow)
165
+ cmd_concat = [
166
+ "ffmpeg", "-y",
167
+ "-f", "concat", "-safe", "0",
168
+ "-i", concat_list,
169
+ "-c", "copy",
170
+ slideshow
171
+ ]
172
+ subprocess.run(cmd_concat, check=True, capture_output=True)
173
+
174
+ # ── 4. Overlay texte + audio sur le slideshow ──────────────────────
175
  titre_court = texte_clean[:55] + ("..." if len(texte_clean) > 55 else "")
176
+ vf = (
177
+ f"drawbox=y=ih/2-110:color=black@0.65:width=iw:height=300:t=fill,"
 
178
  f"drawtext=text='PRISME FOOT':fontcolor=yellow:fontsize=42:x=(w-text_w)/2:y=160,"
179
+ f"drawtext=text='{joueur_up}':fontcolor=white:fontsize=55"
180
+ f":x=(w-text_w)/2:y=305:box=1:boxcolor=red@0.8,"
181
+ f"drawtext=text='{titre_court}':fontcolor=white:fontsize=28"
182
+ f":x=(w-text_w)/2:y=(h-text_h)/2+55"
183
  )
184
+ cmd_final = [
185
+ "ffmpeg", "-y",
186
+ "-i", slideshow,
187
+ "-i", audio_path,
188
+ "-vf", vf,
189
+ "-c:v", "libx264", "-c:a", "aac",
190
+ "-t", str(duration),
191
+ "-shortest",
192
+ video_out
193
+ ]
194
+ subprocess.run(cmd_final, check=True, capture_output=True)
195
 
196
+ # ── 5. Nettoyage ───────────────────────────────────────────────────
197
+ for f in temp_files:
198
+ if f and os.path.exists(f):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  os.remove(f)
200
 
201
+ return video_out if os.path.exists(video_out) else None
202
 
203
  except subprocess.CalledProcessError as e:
204
+ st.error(f"FFmpeg erreur :\n{e.stderr.decode()[-600:]}")
205
  except Exception as e:
206
+ st.error(f"Erreur générale : {e}")
207
  return None
208
 
209
+ # ─── INTERFACE STREAMLIT ──────────────────────────────────────────────────────
210
  st.set_page_config(page_title="Prisme Foot Studio", page_icon="⚽")
211
+ st.title("⚽ Prisme Foot Studio v3")
212
 
213
  with st.sidebar:
214
  st.header("⚙️ Configuration")
215
+ key_input = st.text_input(
216
+ "Clé Unsplash (gratuite)",
217
+ type="password",
218
+ help="Créer un compte sur unsplash.com/developers → New Application → Access Key",
219
+ )
220
+ if key_input:
221
+ os.environ["UNSPLASH_ACCESS_KEY"] = key_input
222
+ UNSPLASH_KEY = key_input
223
+ if not UNSPLASH_KEY:
224
+ st.warning("Sans clé Unsplash, la vidéo aura un fond coloré sans image.")
225
 
226
  if "script" not in st.session_state:
227
  st.session_state["script"] = ""
 
229
  nom = st.text_input("👤 Nom du joueur", "Vinicius Junior")
230
 
231
  if st.button("🔍 1. CHERCHER L'ACTU"):
232
+ with st.spinner("Recherche RSS en cours..."):
233
  titre = recuperer_news_reelle(nom)
234
  st.session_state["script"] = enrichir_script(nom, titre)
235
+ nb = len(st.session_state["script"].split())
236
+ st.success(f"Script prêt — {nb} mots ≈ {round(nb * WPM_FACTOR)}s")
237
 
238
+ script_final = st.text_area(
239
+ "📝 Script (modifiable)", value=st.session_state["script"], height=200
240
+ )
241
 
242
  col1, col2 = st.columns(2)
243
  with col1:
244
  nb_mots = len(script_final.split()) if script_final else 0
245
  duree_est = round(nb_mots * WPM_FACTOR)
246
+ delta = max(0, 30 - duree_est)
247
+ st.metric("⏱ Durée estimée", f"{duree_est}s", delta=f"-{delta}s" if delta else "OK")
248
+
249
+ if st.button("🎬 2. CRÉER LA VIDÉO", disabled=not script_final.strip()):
250
+ with st.spinner("Montage en cours…"):
251
+ v = fabriquer_video(nom, script_final)
252
+ if v and os.path.exists(v):
253
+ st.success("✅ Vidéo prête !")
254
+ st.video(v)
255
+ with open(v, "rb") as fv:
256
+ st.download_button(
257
+ "⬇️ Télécharger MP4",
258
+ fv,
259
+ file_name=f"prisme_{nom.replace(' ', '_')}.mp4",
260
+ mime="video/mp4",
261
+ )