Spaces:
Runtime error
Runtime error
Update app.py
#1
by PrismeFoot - opened
app.py
CHANGED
|
@@ -1,105 +1,190 @@
|
|
| 1 |
-
import os, uuid, subprocess, requests
|
| 2 |
import streamlit as st
|
| 3 |
from gtts import gTTS
|
|
|
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
"
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
try:
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
joueur_clean = joueur.replace("'", " ").replace('"', " ")
|
| 45 |
|
| 46 |
-
# 1. Génération Audio
|
| 47 |
try:
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
st.set_page_config(page_title="Prisme Foot Studio", page_icon="⚽")
|
| 78 |
-
st.title("⚽ Prisme Foot Studio")
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
st.
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, uuid, subprocess, math, requests, urllib.parse
|
| 2 |
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())
|
| 29 |
+
if mots >= target:
|
| 30 |
+
break
|
| 31 |
+
return texte.strip()
|
| 32 |
+
|
| 33 |
+
# ─── 2. RECHERCHE NEWS ───────────────────────────────────────────────────────
|
| 34 |
+
def recuperer_news_reelle(joueur: str) -> str:
|
| 35 |
try:
|
| 36 |
+
import feedparser
|
| 37 |
+
q = urllib.parse.quote(f"{joueur} football")
|
| 38 |
+
url = f"https://news.google.com/rss/search?q={q}&hl=fr&gl=FR&ceid=FR:fr"
|
| 39 |
+
fx = feedparser.parse(url)
|
| 40 |
+
return fx.entries[0].title if fx.entries else ""
|
| 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"] = ""
|
| 165 |
+
|
| 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")
|