File size: 9,312 Bytes
1e33b19
14a289b
b217aa1
1e33b19
f4d3ff1
1e33b19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c1017d
1e33b19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c7dff6
1e33b19
 
 
 
 
f4d3ff1
1e33b19
 
5c1017d
854873b
1e33b19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c1017d
1e33b19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import os, uuid, subprocess, math, requests, urllib.parse
import streamlit as st
from gtts import gTTS
from mutagen.mp3 import MP3

# ─── CONFIG ──────────────────────────────────────────────────────────────────
UNSPLASH_KEY = os.getenv("UNSPLASH_ACCESS_KEY", "")  # Clé gratuite unsplash.com
MIN_DURATION  = 30   # secondes minimum
WPM_FACTOR    = 0.38 # secondes par mot (débit gTTS français)

# ─── 1. ENRICHISSEMENT DU SCRIPT ────────────────────────────────────────────
def enrichir_script(joueur: str, titre: str) -> str:
    """Gonfle le script jusqu'à ~30 s de lecture."""
    phrases = [
        f"Bienvenue sur Prisme Foot, votre chaîne d'actualité football.",
        f"Aujourd'hui, focus sur {joueur}.",
        titre,
        f"{joueur} est l'un des joueurs les plus suivis de sa génération.",
        f"Sa technique, sa vitesse et son sens du but en font un atout majeur.",
        f"Les supporters du monde entier retiennent leur souffle à chaque match.",
        f"Restez connectés pour ne rater aucune actualité sur {joueur} et toute l'actu football.",
        f"Abonnez-vous à Prisme Foot pour vos analyses et résumés quotidiens.",
    ]
    texte, mots = "", 0
    target = int(MIN_DURATION / WPM_FACTOR)
    for p in phrases:
        texte += " " + p
        mots  += len(p.split())
        if mots >= target:
            break
    return texte.strip()

# ─── 2. RECHERCHE NEWS ───────────────────────────────────────────────────────
def recuperer_news_reelle(joueur: str) -> str:
    try:
        import feedparser
        q   = urllib.parse.quote(f"{joueur} football")
        url = f"https://news.google.com/rss/search?q={q}&hl=fr&gl=FR&ceid=FR:fr"
        fx  = feedparser.parse(url)
        return fx.entries[0].title if fx.entries else ""
    except Exception:
        return ""

# ─── 3. TÉLÉCHARGEMENT D'IMAGES ─────────────────────────────────────────────
def telecharger_images(joueur: str, n: int = 4) -> list[str]:
    """Retourne des chemins d'images locales via Unsplash (ou fallback couleurs)."""
    paths = []
    if UNSPLASH_KEY:
        try:
            r = requests.get(
                "https://api.unsplash.com/search/photos",
                params={"query": f"{joueur} football", "per_page": n, "orientation": "portrait"},
                headers={"Authorization": f"Client-ID {UNSPLASH_KEY}"},
                timeout=8,
            )
            for item in r.json().get("results", [])[:n]:
                img_url = item["urls"]["regular"]
                img_data = requests.get(img_url, timeout=10).content
                p = f"/tmp/img_{uuid.uuid4().hex[:6]}.jpg"
                with open(p, "wb") as f:
                    f.write(img_data)
                paths.append(p)
        except Exception as e:
            st.warning(f"Unsplash indisponible : {e}")
    return paths

# ─── 4. MOTEUR VIDÉO ─────────────────────────────────────────────────────────
def fabriquer_video(joueur: str, texte: str) -> str | None:
    uid   = uuid.uuid4().hex[:6]
    audio = f"/tmp/a_{uid}.mp3"
    video = f"/tmp/v_{uid}.mp4"

    texte_clean = texte.replace("'", " ").replace('"', " ")
    joueur_up   = joueur.upper()

    try:
        # ── Audio ──────────────────────────────────────────────────────────
        gTTS(text=texte_clean, lang="fr").save(audio)
        duration = max(MIN_DURATION, math.ceil(MP3(audio).info.length) + 1)

        # ── Images ─────────────────────────────────────────────────────────
        images = telecharger_images(joueur, n=4)
        n_img  = len(images)

        if n_img == 0:
            # Fallback : fond dégradé pur FFmpeg
            inputs      = ["-f", "lavfi", "-i", f"color=c=0x001a33:s=720x1280:d={duration}"]
            video_label = "[0:v]"
        else:
            # Chaque image occupe duration/n_img secondes
            seg = round(duration / n_img, 2)
            inputs = []
            for p in images:
                inputs += [
                    "-loop", "1", "-t", str(seg),
                    "-i", p,
                ]
            # concat + scale
            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))
            concat_filter += "".join(f"[v{i}]" for i in range(n_img))
            concat_filter += f"concat=n={n_img}:v=1:a=0[slideshow]"
            video_label    = "[slideshow]"

        # ── Filtre texte ───────────────────────────────────────────────────
        titre_court = texte_clean[:55] + ("..." if len(texte_clean) > 55 else "")
        overlay = (
            f"{video_label},"
            f"drawbox=y=ih/2-110:color=black@0.65:width=iw:height=320:t=fill,"
            f"drawtext=text='PRISME FOOT':fontcolor=yellow:fontsize=42:x=(w-text_w)/2:y=160,"
            f"drawtext=text='{joueur_up}':fontcolor=white:fontsize=58:x=(w-text_w)/2:y=310"
            f":box=1:boxcolor=red@0.8,"
            f"drawtext=text='{titre_court}':fontcolor=white:fontsize=30"
            f":x=(w-text_w)/2:y=(h-text_h)/2+60[out]"
        )

        # ── Commande FFmpeg ────────────────────────────────────────────────
        if n_img == 0:
            cmd = (
                ["ffmpeg", "-y"]
                + inputs
                + ["-i", audio,
                   "-vf", overlay.replace(f"{video_label},", "").replace("[out]", ""),
                   "-c:v", "libx264", "-c:a", "aac",
                   "-t", str(duration), video]
            )
        else:
            cmd = (
                ["ffmpeg", "-y"]
                + inputs
                + ["-i", audio,
                   "-filter_complex", concat_filter + ";" + overlay,
                   "-map", "[out]", "-map", f"{n_img}:a",
                   "-c:v", "libx264", "-c:a", "aac",
                   "-t", str(duration), "-shortest", video]
            )

        subprocess.run(cmd, check=True, capture_output=True)

        # ── Nettoyage ──────────────────────────────────────────────────────
        for f in [audio] + images:
            if os.path.exists(f):
                os.remove(f)

        return video

    except subprocess.CalledProcessError as e:
        st.error(f"FFmpeg : {e.stderr.decode()[-500:]}")
    except Exception as e:
        st.error(f"Erreur : {e}")
    return None

# ─── INTERFACE ────────────────────────────────────────────────────────────────
st.set_page_config(page_title="Prisme Foot Studio", page_icon="⚽")
st.title("⚽ Prisme Foot Studio v2")

with st.sidebar:
    st.header("⚙️ Configuration")
    unsplash_key = st.text_input("Clé Unsplash (gratuite)", type="password",
                                  help="api.unsplash.com → Developer → New Application")
    if unsplash_key:
        os.environ["UNSPLASH_ACCESS_KEY"] = unsplash_key

if "script" not in st.session_state:
    st.session_state["script"] = ""

nom = st.text_input("👤 Nom du joueur", "Vinicius Junior")

if st.button("🔍 1. CHERCHER L'ACTU"):
    with st.spinner("Recherche en cours..."):
        titre = recuperer_news_reelle(nom)
        st.session_state["script"] = enrichir_script(nom, titre)
        st.success(f"Script enrichi ({len(st.session_state['script'].split())} mots ≈ 30 s)")

script_final = st.text_area("📝 Script (modifiable)", value=st.session_state["script"], height=200)

col1, col2 = st.columns(2)
with col1:
    nb_mots = len(script_final.split()) if script_final else 0
    duree_est = round(nb_mots * WPM_FACTOR)
    st.metric("⏱ Durée estimée", f"{duree_est} s", delta=f"{max(0, 30-duree_est)} s manquantes")

if st.button("🎬 2. CRÉER LA VIDÉO", disabled=not script_final):
    if nom and script_final:
        with st.spinner("Montage en cours (30–60 s)…"):
            v = fabriquer_video(nom, script_final)
            if v and os.path.exists(v):
                st.success("✅ Vidéo prête !")
                st.video(v)
                with open(v, "rb") as fv:
                    st.download_button("⬇️ Télécharger MP4", fv, file_name=f"prisme_{nom.replace(' ','_')}.mp4")