PrismeFoot commited on
Commit
f75f164
·
verified ·
1 Parent(s): 1670cec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -64
app.py CHANGED
@@ -1,105 +1,112 @@
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, requests, shlex
2
  import streamlit as st
3
  from gtts import gTTS
4
+ from tenacity import retry, stop_after_attempt, wait_exponential
5
 
6
+ # --- CONFIGURATION (Via Variables d'Environnement) ---
7
  PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
8
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
9
+ GROQ_URL = "https://groq.com"
10
 
11
+ # --- SERVICES DE DONNÉES ---
12
+
13
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
14
  def generer_actu_ia(joueur):
15
+ """Génère du contenu via Groq avec gestion d'erreurs et retries."""
16
  headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
17
+ payload = {
18
  "model": "mixtral-8x7b-32768",
19
+ "messages": [{"role": "user", "content": f"Écris une news foot virale, fun et très courte (1 phrase) sur {joueur}. Sans hashtags."}],
20
  "temperature": 0.7
21
  }
22
+ r = requests.post(GROQ_URL, headers=headers, json=payload, timeout=10)
23
+ r.raise_for_status()
24
+ return r.json()['choices'][0]['message']['content'].strip()
 
 
 
25
 
26
  def obtenir_image_fond(sujet):
27
+ """Récupère une image de sport sur Pexels via l'API officielle."""
28
+ url = f"https://pexels.com{sujet}+football&per_page=1&orientation=portrait"
29
  headers = {"Authorization": PEXELS_API_KEY}
30
  try:
31
  r = requests.get(url, headers=headers, timeout=10)
32
  if r.status_code == 200 and r.json().get('photos'):
33
  img_url = r.json()['photos'][0]['src']['large2x']
34
+ path = f"img_{uuid.uuid4().hex[:6]}.jpg"
35
  with open(path, 'wb') as f: f.write(requests.get(img_url).content)
36
  return path
37
+ except Exception as e:
38
+ st.error(f"Erreur Pexels: {e}")
39
  return None
40
 
41
+ # --- MOTEUR DE RENDU VIDÉO ---
42
+
43
  def creer_video_expert(joueur, news):
44
+ """Génère une vidéo sécurisée via FFmpeg (Arguments en liste)."""
45
  uid = uuid.uuid4().hex[:6]
46
  audio_file = f"audio_{uid}.mp3"
47
  video_final = f"PRISME_{uid}.mp4"
48
+
49
+ # Nettoyage strict pour éviter les erreurs de rendu texte
50
+ news_clean = news.replace("'", " ").replace('"', " ").replace(":", " ")
51
+ joueur_clean = joueur.upper().replace("'", " ")
52
 
 
 
 
 
 
53
  try:
54
+ # 1. Synthèse Vocale
55
  tts = gTTS(text=f"Alerte Info ! {news_clean}", lang='fr')
56
  tts.save(audio_file)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ # 2. Image de fond
59
+ img = obtenir_image_fond(joueur)
60
+ input_source = ["-loop", "1", "-i", img] if img else ["-f", "lavfi", "-i", "color=c=black:s=720x1280"]
61
+
62
+ # 3. Commande FFmpeg (Passage en liste = Protection Injection)
63
+ # Filtres : Scale/Crop portrait + Overlay texte pro
64
+ vf_filters = (
65
+ f"scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,"
66
+ f"drawtext=text='PRISME FOOT':fontcolor=yellow:fontsize=45:x=(w-text_w)/2:y=150:box=1:boxcolor=black@0.6,"
67
+ f"drawtext=text='{joueur_clean}':fontcolor=white:fontsize=60:x=(w-text_w)/2:y=(h-text_h)/2:box=1:boxcolor=red@0.8,"
68
+ f"drawtext=text='{news_clean[:40]}...':fontcolor=white:fontsize=35:x=(w-text_w)/2:y=h-200:box=1:boxcolor=black@0.5"
69
+ )
70
+
71
+ cmd = [
72
+ "ffmpeg", "-y"
73
+ ] + input_source + [
74
+ "-i", audio_file,
75
+ "-vf", vf_filters,
76
+ "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest",
77
+ video_final
78
+ ]
79
+
80
+ subprocess.run(cmd, check=True)
81
+
82
+ # Nettoyage immédiat des assets
83
+ if img: os.remove(img)
84
+ os.remove(audio_file)
85
+
86
+ return video_final
87
+ except Exception as e:
88
+ st.error(f"Erreur rendu: {e}")
89
+ return None
90
 
91
+ # --- INTERFACE ---
92
+ st.set_page_config(page_title="Prisme Foot Studio v2", page_icon="⚽")
93
+ st.title("🚀 Prisme Foot Studio - Pro")
94
 
95
+ joueur = st.text_input("👤 Nom du Joueur", placeholder="Ex: Kylian Mbappé")
96
 
97
+ if st.button("🤖 1. GÉNÉRER NEWS"):
98
  if joueur:
99
+ with st.spinner("L'IA analyse le mercato..."):
100
  st.session_state['actu'] = generer_actu_ia(joueur)
101
+ else: st.warning("Entrez un nom.")
 
102
 
103
+ actu_finale = st.text_area("📝 Script (Vérifiez le texte)", value=st.session_state.get('actu', ''), height=100)
104
 
105
+ if st.button("🎬 2. PRODUIRE VIDÉO"):
106
  if joueur and actu_finale:
107
+ with st.spinner("Moteur de rendu FFmpeg en action..."):
108
  video = creer_video_expert(joueur, actu_finale)
109
+ if video:
110
  st.video(video)
111
+ st.success("Vidéo prête !")
112
+ else: st.error("Données manquantes.")