PrismeFoot commited on
Commit
9d643b9
·
verified ·
1 Parent(s): 05d6449

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -61
app.py CHANGED
@@ -2,103 +2,96 @@ import os, random, uuid, json, subprocess, asyncio, requests
2
  import edge_tts
3
  import streamlit as st
4
 
5
- # --- CONFIGURATION ---
6
- = "TA_CLE_PEXELS_ICI"
 
7
  VOIX_FR = "fr-FR-RemyNeural"
8
- DB_FILE = "memoire_prisme.json"
9
 
10
- # --- RECHERCHE D'IMAGE DYNAMIQUE (PEXELS CORRECT) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def obtenir_image_fond(sujet):
12
  if not os.path.exists("images_actu"): os.makedirs("images_actu")
13
-
14
- # Correction de l'URL API
15
  url = f"https://pexels.com{sujet}+football&per_page=1"
16
  headers = {"Authorization": PEXELS_API_KEY}
17
-
18
  try:
19
  r = requests.get(url, headers=headers, timeout=10)
20
  if r.status_code == 200 and r.json().get('photos'):
21
  img_url = r.json()['photos'][0]['src']['large2x']
22
  nom_image = f"images_actu/fond_{uuid.uuid4().hex[:4]}.jpg"
23
- img_data = requests.get(img_url).content
24
- with open(nom_image, 'wb') as f:
25
- f.write(img_data)
26
  return nom_image
27
- except Exception as e:
28
- print(f"Erreur Pexels: {e}")
29
-
30
- # Secours : Couleur unie si rien n'est trouvé
31
  return "color=black@0.5:s=720x1280"
32
 
33
  # --- MOTEUR DE PRODUCTION ---
34
  async def creer_video_expert(joueur, news_brute):
35
  uid = uuid.uuid4().hex[:6]
36
- audio_file = f"audio_{uid}.mp3"
37
- srt_file = f"subs_{uid}.srt"
38
- video_final = f"PRISME_{uid}.mp4"
39
 
40
- # 1. Script et Génération Audio avec Timestamps
41
- hooks = ["ALERTE INFO ! 🚨", "INCROYABLE ! 😱", "DERNIÈRE MINUTE ! 🔥"]
42
- script = f"{random.choice(hooks)} On parle de {joueur}. {news_brute} Abonne-toi à Prisme Foot ! ⚽"
43
-
44
  communicate = edge_tts.Communicate(script, VOIX_FR)
45
- submaker = edge_tts.SubMaker() # Initialise le créateur de sous-titres
46
 
47
  with open(audio_file, "wb") as f:
48
  async for chunk in communicate.stream():
49
- if chunk["type"] == "audio":
50
- f.write(chunk["data"])
51
- elif chunk["type"] == "WordBoundary":
52
- submaker.feed(chunk)
53
 
54
- # Création du fichier SRT (Sous-titres)
55
- with open(srt_file, "w", encoding="utf-8") as f:
56
- f.write(submaker.generate())
57
 
58
- # 2. Image de fond
59
  image_path = obtenir_image_fond(joueur)
60
  input_source = f'-i "{image_path}"' if not image_path.startswith("color") else f'-f lavfi -i "{image_path}"'
61
-
62
- # 3. Montage FFmpeg avec Incrustation des Sous-titres
63
- # On utilise 'force_style' pour mettre les mots en gros, jaune, au milieu
64
- style = "Alignment=10,FontSize=24,PrimaryColour=&H00FFFF,OutlineColour=&H000000,BorderStyle=3"
65
 
66
  cmd = (
67
  f'ffmpeg -loop 1 {input_source} -i {audio_file} '
68
  f'-vf "scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,'
69
  f'zoompan=z=\'min(zoom+0.0015,1.5)\':d=125:s=720x1280,'
70
- f'subtitles={srt_file}:force_style=\'{style}\',' # LA MAGIE EST ICI
71
- f'drawtext=text=\'PRISME FOOT\':fontcolor=white:fontsize=40:x=(w-text_w)/2:y=150:box=1:boxcolor=black@0.6" '
72
  f'-c:v libx264 -preset superfast -tune stillimage -c:a aac -shortest {video_final} -y'
73
  )
74
-
75
  subprocess.run(cmd, shell=True)
76
-
77
- # Nettoyage
78
- for f in [audio_file, srt_file]:
79
- if os.path.exists(f): os.remove(f)
80
-
81
  return video_final
82
 
83
  # --- INTERFACE STREAMLIT ---
84
- st.set_page_config(page_title="Prisme Foot V2", page_icon="⚽")
85
- st.title("⚽ Studio Prisme Foot V2")
86
- st.subheader("Générateur de News Originales")
 
 
 
 
 
 
 
 
 
 
87
 
88
- nom_joueur = st.text_input("Nom du Joueur")
89
- actu_texte = st.text_area("L'actualité")
90
 
91
- if st.button("🔥 GÉNÉRER LA VIDÉO VIRALE"):
92
- if nom_joueur and actu_texte:
93
- with st.spinner("🛠️ Création du chef-d'œuvre..."):
94
- fichier_genere = asyncio.run(creer_video_expert(nom_joueur, actu_texte))
95
-
96
- if os.path.exists(fichier_genere):
97
- st.success("✅ Vidéo générée avec succès !")
98
- with open(fichier_genere, "rb") as f:
99
- st.video(f) # Affiche la vidéo directement
100
- st.download_button("📥 Télécharger la vidéo", f, file_name=fichier_genere)
101
- else:
102
- st.error("Erreur lors de la génération FFmpeg.")
103
- else:
104
- st.warning("Remplis tous les champs, Champion !")
 
2
  import edge_tts
3
  import streamlit as st
4
 
5
+ # --- CONFIGURATION DES SECRETS ---
6
+ PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
7
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
8
  VOIX_FR = "fr-FR-RemyNeural"
 
9
 
10
+ # --- FONCTION CERVEAU (GROQ IA) ---
11
+ def generer_actu_ia(joueur):
12
+ url = "https://groq.com"
13
+ headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
14
+
15
+ prompt = f"Écris une news de foot ultra-virale et sensationnelle sur {joueur}. Maximum 2 phrases. Sois percutant comme un titre de journal."
16
+
17
+ data = {
18
+ "model": "mixtral-8x7b-32768",
19
+ "messages": [{"role": "user", "content": prompt}],
20
+ "temperature": 0.7
21
+ }
22
+
23
+ try:
24
+ r = requests.post(url, headers=headers, json=data, timeout=10)
25
+ return r.json()['choices'][0]['message']['content']
26
+ except Exception as e:
27
+ return f"Vient de réaliser une performance incroyable qui choque le monde du football ! ⚽"
28
+
29
+ # --- RECHERCHE D'IMAGE ---
30
  def obtenir_image_fond(sujet):
31
  if not os.path.exists("images_actu"): os.makedirs("images_actu")
 
 
32
  url = f"https://pexels.com{sujet}+football&per_page=1"
33
  headers = {"Authorization": PEXELS_API_KEY}
 
34
  try:
35
  r = requests.get(url, headers=headers, timeout=10)
36
  if r.status_code == 200 and r.json().get('photos'):
37
  img_url = r.json()['photos'][0]['src']['large2x']
38
  nom_image = f"images_actu/fond_{uuid.uuid4().hex[:4]}.jpg"
39
+ with open(nom_image, 'wb') as f: f.write(requests.get(img_url).content)
 
 
40
  return nom_image
41
+ except: pass
 
 
 
42
  return "color=black@0.5:s=720x1280"
43
 
44
  # --- MOTEUR DE PRODUCTION ---
45
  async def creer_video_expert(joueur, news_brute):
46
  uid = uuid.uuid4().hex[:6]
47
+ audio_file, srt_file, video_final = f"audio_{uid}.mp3", f"subs_{uid}.srt", f"PRISME_{uid}.mp4"
 
 
48
 
49
+ script = f"Alerte Info ! {news_brute} Abonne-toi à Prisme Foot !"
 
 
 
50
  communicate = edge_tts.Communicate(script, VOIX_FR)
51
+ submaker = edge_tts.SubMaker()
52
 
53
  with open(audio_file, "wb") as f:
54
  async for chunk in communicate.stream():
55
+ if chunk["type"] == "audio": f.write(chunk["data"])
56
+ elif chunk["type"] == "WordBoundary": submaker.feed(chunk)
 
 
57
 
58
+ with open(srt_file, "w", encoding="utf-8") as f: f.write(submaker.generate())
 
 
59
 
 
60
  image_path = obtenir_image_fond(joueur)
61
  input_source = f'-i "{image_path}"' if not image_path.startswith("color") else f'-f lavfi -i "{image_path}"'
62
+ style = "Alignment=10,FontSize=28,PrimaryColour=&H00FFFF,OutlineColour=&H000000,BorderStyle=3"
 
 
 
63
 
64
  cmd = (
65
  f'ffmpeg -loop 1 {input_source} -i {audio_file} '
66
  f'-vf "scale=720:1280:force_original_aspect_ratio=increase,crop=720:1280,'
67
  f'zoompan=z=\'min(zoom+0.0015,1.5)\':d=125:s=720x1280,'
68
+ f'subtitles={srt_file}:force_style=\'{style}\'" '
 
69
  f'-c:v libx264 -preset superfast -tune stillimage -c:a aac -shortest {video_final} -y'
70
  )
 
71
  subprocess.run(cmd, shell=True)
 
 
 
 
 
72
  return video_final
73
 
74
  # --- INTERFACE STREAMLIT ---
75
+ st.set_page_config(page_title="Prisme Foot AI", page_icon="⚽")
76
+ st.title("⚽ Prisme Foot : Studio IA")
77
+
78
+ joueur = st.text_input("👤 Nom du Joueur")
79
+ col1, col2 = st.columns(2)
80
+
81
+ with col1:
82
+ if st.button("🤖 LAISSER L'IA ÉCRIRE"):
83
+ if joueur:
84
+ with st.spinner("L'IA réfléchit..."):
85
+ actu = generer_actu_ia(joueur)
86
+ st.session_state['actu'] = actu
87
+ else: st.warning("Mets un nom !")
88
 
89
+ with col2:
90
+ actu_finale = st.text_area("📝 News (Modifier ici si besoin)", value=st.session_state.get('actu', ''))
91
 
92
+ if st.button("🎬 GÉNÉRER LA VIDÉO"):
93
+ if joueur and actu_finale:
94
+ with st.spinner("🛠️ Montage en cours..."):
95
+ fichier = asyncio.run(creer_video_expert(joueur, actu_finale))
96
+ st.video(fichier)
97
+ with open(fichier, "rb") as f: st.download_button("📥 Télécharger", f, file_name=fichier)