Spaces:
Runtime error

PrismeFoot commited on
Commit
854873b
·
verified ·
1 Parent(s): b217aa1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -57
app.py CHANGED
@@ -1,103 +1,106 @@
1
- import os, random, uuid, json, subprocess, asyncio, requests
2
- import edge_tts
3
  import streamlit as st
4
  from gtts import gTTS
5
 
6
  # --- CONFIGURATION ---
7
  PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
8
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
9
- VOIX_FR = "fr-FR-RemyNeural"
10
 
11
- # Initialisation du session_state pour éviter les erreurs au premier chargement
12
- if 'actu' not in st.session_state:
13
- st.session_state['actu'] = ""
14
-
15
- # --- FONCTIONS ---
16
  def generer_actu_ia(joueur):
17
- # Note: L'URL de l'API Groq est https://groq.com
18
  url = "https://groq.com"
19
  headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
20
- prompt = f"Écris une news de foot ultra-virale sur {joueur}. Maximum 2 phrases."
21
-
22
  data = {
23
  "model": "mixtral-8x7b-32768",
24
- "messages": [{"role": "user", "content": prompt}],
25
  "temperature": 0.7
26
  }
27
-
28
  try:
29
  r = requests.post(url, headers=headers, json=data, timeout=10)
 
30
  return r.json()['choices'][0]['message']['content']
31
  except:
32
- return f"{joueur} vient de réaliser une performance incroyable ! ⚽"
33
 
34
  def obtenir_image_fond(sujet):
35
- if not os.path.exists("images_actu"): os.makedirs("images_actu")
36
- # Correction de l'URL Pexels
37
  url = f"https://pexels.com{sujet}+football&per_page=1"
38
  headers = {"Authorization": PEXELS_API_KEY}
39
  try:
40
  r = requests.get(url, headers=headers, timeout=10)
41
  if r.status_code == 200 and r.json().get('photos'):
42
  img_url = r.json()['photos'][0]['src']['large2x']
43
- nom_image = f"images_actu/fond_{uuid.uuid4().hex[:4]}.jpg"
44
- with open(nom_image, 'wb') as f: f.write(requests.get(img_url).content)
45
- return nom_image
46
  except: pass
47
- return "color=black@0.5:s=720x1280"
48
 
49
- async def creer_video_expert(joueur, news_brute):
50
  uid = uuid.uuid4().hex[:6]
51
  audio_file = f"audio_{uid}.mp3"
52
  video_final = f"PRISME_{uid}.mp4"
53
- script = f"Alerte Info ! {news_brute} Abonne-toi à Prisme Foot !"
54
-
55
- # Utilisation de edge_tts (plus qualitatif que gTTS)
56
- communicate = edge_tts.Communicate(script, VOIX_FR)
57
- await communicate.save(audio_file)
58
 
59
- image_path = obtenir_image_fond(joueur)
60
-
61
- # Construction de la commande FFmpeg
62
- if image_path.startswith("color"):
63
- input_cmd = f"-f lavfi -i \"{image_path}\""
 
 
 
 
 
 
 
 
 
64
  else:
65
- input_cmd = f"-loop 1 -i \"{image_path}\""
66
 
 
67
  cmd = (
68
- f'ffmpeg {input_cmd} -i {audio_file} '
69
  f'-vf "scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,'
70
- f'zoompan=z=\'min(zoom+0.0015,1.5)\':d=125:s=720x1280,'
71
- f'drawtext=text=\'PRISME FOOT\':fontcolor=yellow:fontsize=45:x=(w-text_w)/2:y=150:box=1:boxcolor=black@0.6,'
72
- f'drawtext=text=\'{joueur.upper()}\':fontcolor=white:fontsize=60:x=(w-text_w)/2:y=(h-text_h)/2:box=1:boxcolor=red@0.8" '
73
- f'-c:v libx264 -preset superfast -tune stillimage -c:a aac -shortest {video_final} -y'
74
  )
75
 
76
  subprocess.run(cmd, shell=True)
 
 
77
  if os.path.exists(audio_file): os.remove(audio_file)
78
- return video_final
 
 
 
 
 
 
79
 
80
- # --- INTERFACE ---
81
- st.set_page_config(page_title="Prisme Foot AI", page_icon="⚽")
82
- st.title("⚽ Prisme Foot : Studio IA")
83
 
84
- joueur = st.text_input("👤 Nom du Joueur")
85
- col1, col2 = st.columns(2)
86
 
87
- with col1:
88
- if st.button("🤖 IA : ÉCRIRE"):
89
- if joueur:
90
- with st.spinner("L'IA réfléchit..."):
91
- st.session_state['actu'] = generer_actu_ia(joueur)
92
- else: st.warning("Mets un nom !")
93
 
94
- actu_finale = st.text_area("📝 News", value=st.session_state['actu'])
95
 
96
- if st.button("🎬 GÉNÉRER LA VIDÉO"):
97
  if joueur and actu_finale:
98
- with st.spinner("🛠️ Montage en cours..."):
99
- fichier = asyncio.run(creer_video_expert(joueur, actu_finale))
100
- if fichier and os.path.exists(fichier):
101
- st.video(fichier)
102
- with open(fichier, "rb") as f:
103
- st.download_button("📥 Télécharger", f, file_name=fichier)
 
 
 
 
 
 
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 !")
106
+ Utilisez