Files changed (1) hide show
  1. app.py +181 -96
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
- # --- CONFIGURATION ---
6
- PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
7
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
8
-
9
- def generer_actu_ia(joueur):
10
- url = "https://groq.com"
11
- headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
12
- data = {
13
- "model": "mixtral-8x7b-32768",
14
- "messages": [{"role": "user", "content": f"Écris une news foot virale et courte sur {joueur}."}],
15
- "temperature": 0.7
16
- }
17
- try:
18
- r = requests.post(url, headers=headers, json=data, timeout=10)
19
- # Correction de l'indexation JSON ici
20
- return r.json()['choices'][0]['message']['content']
21
- except:
22
- return f"{joueur} impressionne tout le monde avec une performance incroyable ! ⚽"
23
-
24
- def obtenir_image_fond(sujet):
25
- url = f"https://pexels.com{sujet}+football&per_page=1"
26
- headers = {"Authorization": PEXELS_API_KEY}
 
 
 
 
 
 
 
27
  try:
28
- r = requests.get(url, headers=headers, timeout=10)
29
- if r.status_code == 200 and r.json().get('photos'):
30
- img_url = r.json()['photos'][0]['src']['large2x']
31
- path = f"fond_{uuid.uuid4().hex[:4]}.jpg"
32
- with open(path, 'wb') as f: f.write(requests.get(img_url).content)
33
- return path
34
- except: pass
35
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- def creer_video_expert(joueur, news):
38
- uid = uuid.uuid4().hex[:6]
39
- audio_file = f"audio_{uid}.mp3"
40
- video_final = f"PRISME_{uid}.mp4"
 
41
 
42
- # NETTOYAGE CRUCIAL DES TEXTES POUR FFMPEG
43
- news_clean = news.replace("'", " ").replace('"', " ").replace("\n", " ")
44
- joueur_clean = joueur.replace("'", " ").replace('"', " ")
45
 
46
- # 1. Génération Audio
47
  try:
48
- tts = gTTS(text=f"Alerte Info ! {news_clean}", lang='fr')
49
- tts.save(audio_file)
50
- except: return None
51
-
52
- # 2. Source Image
53
- img = obtenir_image_fond(joueur)
54
- if img and os.path.exists(img):
55
- input_source = f'-loop 1 -i {img}'
56
- else:
57
- input_source = '-f lavfi -i color=c=black:s=720x1280'
58
-
59
- # 3. Commande FFmpeg Blindée
60
- cmd = (
61
- f'ffmpeg {input_source} -i {audio_file} '
62
- f'-vf "scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,'
63
- f'drawtext=text=\'PRISME FOOT\':fontcolor=yellow:fontsize=40:x=(w-text_w)/2:y=120:box=1:boxcolor=black@0.5,'
64
- f'drawtext=text=\'{joueur_clean.upper()}\':fontcolor=white:fontsize=55:x=(w-text_w)/2:y=(h-text_h)/2:box=1:boxcolor=red@0.7" '
65
- f'-c:v libx264 -preset superfast -c:a aac -shortest {video_final} -y'
66
- )
67
-
68
- subprocess.run(cmd, shell=True)
69
-
70
- # Nettoyage des fichiers temporaires
71
- if os.path.exists(audio_file): os.remove(audio_file)
72
- if img and os.path.exists(img): os.remove(img)
73
-
74
- return video_final if os.path.exists(video_final) else None
75
-
76
- # --- INTERFACE STREAMLIT ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  st.set_page_config(page_title="Prisme Foot Studio", page_icon="⚽")
78
- st.title("⚽ Prisme Foot Studio")
79
-
80
- if 'actu' not in st.session_state:
81
- st.session_state['actu'] = ""
82
-
83
- joueur = st.text_input("👤 Nom du Joueur", placeholder="Ex: Vinicius Junior")
84
-
85
- if st.button("🤖 GÉNÉRER TEXTE IA"):
86
- if joueur:
87
- with st.spinner("L'IA rédige..."):
88
- st.session_state['actu'] = generer_actu_ia(joueur)
89
- else:
90
- st.warning("Veuillez entrer un nom.")
91
-
92
- actu_finale = st.text_area("📝 News (modifiables)", value=st.session_state['actu'], height=100)
93
-
94
- if st.button("🎬 CRÉER LA VIDÉO"):
95
- if joueur and actu_finale:
96
- with st.spinner("Montage vidéo en cours..."):
97
- video = creer_video_expert(joueur, actu_finale)
98
- if video and os.path.exists(video):
99
- st.video(video)
100
- with open(video, "rb") as f:
101
- st.download_button("📥 Télécharger la vidéo", f, file_name=video)
102
- else:
103
- st.error("Erreur technique. Vérifie tes clés API Pexels et Groq dans les Settings.")
104
- else:
105
- st.error("Remplis tous les champs !")
 
 
 
 
 
 
 
 
 
 
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")