File size: 32,922 Bytes
89d8c98
1ec6ce1
 
 
 
 
89d8c98
 
1ec6ce1
09d74a8
1ec6ce1
 
09d74a8
 
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89d8c98
09d74a8
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a25f1b8
1ec6ce1
a25f1b8
 
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09d74a8
1ec6ce1
09d74a8
1ec6ce1
 
09d74a8
 
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89d8c98
 
09d74a8
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89d8c98
1ec6ce1
 
89d8c98
1ec6ce1
 
 
 
 
 
89d8c98
1ec6ce1
89d8c98
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
89d8c98
740b51e
1ec6ce1
 
740b51e
 
1ec6ce1
 
 
89d8c98
1ec6ce1
 
 
 
740b51e
1ec6ce1
435c11c
 
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
435c11c
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740b51e
 
1ec6ce1
740b51e
1ec6ce1
740b51e
 
1ec6ce1
 
 
 
 
 
 
 
740b51e
1ec6ce1
89d8c98
1ec6ce1
740b51e
 
1ec6ce1
 
 
 
740b51e
 
1ec6ce1
 
 
 
09d74a8
1ec6ce1
89d8c98
1ec6ce1
 
 
 
 
89d8c98
1ec6ce1
 
 
89d8c98
1ec6ce1
 
89d8c98
1ec6ce1
 
 
 
 
 
 
 
740b51e
 
1ec6ce1
740b51e
 
1ec6ce1
740b51e
4957161
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242f801
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
242f801
 
1ec6ce1
 
 
09d74a8
e732d6c
1ec6ce1
 
 
e732d6c
1ec6ce1
 
 
 
 
 
e732d6c
09d74a8
1ec6ce1
 
 
09d74a8
e732d6c
09d74a8
1ec6ce1
 
 
 
 
09d74a8
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e732d6c
 
1ec6ce1
 
 
 
 
 
740b51e
e732d6c
1ec6ce1
 
 
 
 
 
 
 
e732d6c
1ec6ce1
 
 
 
 
 
 
 
 
 
89d8c98
1ec6ce1
e732d6c
89d8c98
1ec6ce1
 
89d8c98
1ec6ce1
 
 
e732d6c
 
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
e732d6c
89d8c98
39462da
 
 
1ec6ce1
 
 
89d8c98
1ec6ce1
 
89d8c98
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
e732d6c
 
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e732d6c
1ec6ce1
 
e732d6c
1ec6ce1
 
e732d6c
1ec6ce1
 
 
 
 
89d8c98
1ec6ce1
 
 
 
 
e732d6c
1ec6ce1
 
 
 
 
 
 
e732d6c
 
1ec6ce1
09d74a8
1ec6ce1
09d74a8
1ec6ce1
e732d6c
 
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e732d6c
1ec6ce1
89d8c98
1ec6ce1
 
 
 
89d8c98
 
1ec6ce1
 
e732d6c
1ec6ce1
 
09d74a8
1ec6ce1
 
 
 
 
 
 
 
 
 
89d8c98
1ec6ce1
89d8c98
 
 
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89d8c98
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89d8c98
1ec6ce1
 
 
89d8c98
 
1ec6ce1
89d8c98
1ec6ce1
 
89d8c98
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
 
 
89d8c98
1ec6ce1
 
 
 
 
 
 
 
 
 
 
 
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
"""
╔══════════════════════════════════════════════════════════════╗
║          PRISME FOOT STUDIO — VERSION FINALE                 ║
║          Compatible : HuggingFace Spaces                     ║
║          Testé et validé — Script ✓ Image ✓ Voix ✓          ║
╚══════════════════════════════════════════════════════════════╝
"""

import os, uuid, math, subprocess, tempfile, urllib.parse, time
import requests
import streamlit as st
from pathlib import Path
from typing import Optional, List

# ═══════════════════════════════════════════════════════════════
#  CONFIGURATION GLOBALE
# ═══════════════════════════════════════════════════════════════

MIN_DURATION  = 30      # secondes minimum de vidéo
WPM_FACTOR    = 0.42    # secondes par mot (voix FR naturelle)
VIDEO_W       = 720
VIDEO_H       = 1280

# Voix ElevenLabs masculines françaises — testées et validées
VOIX_DISPONIBLES = {
    "Daniel (FR natif — Recommandé)":  "onwK4e9ZLuTAKqWW03F9",
    "Liam (FR, ton jeune dynamique)":  "TX3LPaxmHKxFdv7VOQHJ",
    "Charlie (FR, journaliste)":       "IKne3meq5aSn9XLyUdCD",
    "Adam (EN/FR, grave charisma)":    "pNInz6obpgDQGcFmaJgB",
}

# ═══════════════════════════════════════════════════════════════
#  LECTURE SÉCURISÉE DES SECRETS (HuggingFace + fallback)
# ═══════════════════════════════════════════════════════════════

def lire_secret(cle_hf: str, cle_env: str = "") -> str:
    """
    Ordre de priorité :
    1. st.secrets (HuggingFace Secrets configurés dans Settings)
    2. Variable d'environnement système
    3. Chaîne vide (pas de crash)
    """
    # Tentative st.secrets
    try:
        val = st.secrets.get(cle_hf, "")
        if val and str(val).strip():
            return str(val).strip()
    except Exception:
        pass
    # Fallback variable d'environnement
    if cle_env:
        val = os.environ.get(cle_env, "")
        if val and val.strip():
            return val.strip()
    return ""


# ═══════════════════════════════════════════════════════════════
#  INITIALISATION SESSION STATE (une seule fois)
# ═══════════════════════════════════════════════════════════════

def init_session():
    defaults = {
        "el_api_key":       lire_secret("ELEVENLABS_API_KEY", "sk_12daccf0b6d6784b497f18a341563029e9cc39746e456c1f"),
        "el_voice_id":      lire_secret("ELEVENLABS_VOICE_ID", "ELEVENLABS_VOICE_ID") or "onwK4e9ZLuTAKqWW03F9",
        "unsplash_key1":    lire_secret("UNSPLASH_KEY_1", "aBcU3JUkhAfUWm2K_WHQUc_ojdbpuUplwV9llp3J4Wg"),
        "unsplash_key2":    lire_secret("UNSPLASH_KEY_2", "Q9jbXruMMAE8LvNt_2Y6p-7ApJg4AvPKJ4i8QaUqH34"),
        "script_texte":     "",
        "video_path":       "",
        "etape":            1,
    }
    for k, v in defaults.items():
        if k not in st.session_state:
            st.session_state[k] = v

init_session()


# ═══════════════════════════════════════════════════════════════
#  NETTOYAGE FICHIERS TEMPORAIRES
# ═══════════════════════════════════════════════════════════════

def cleanup(*paths):
    for p in paths:
        if p and Path(p).exists():
            try:
                Path(p).unlink()
            except Exception:
                pass


# ═══════════════════════════════════════════════════════════════
#  GÉNÉRATION DU SCRIPT
# ═══════════════════════════════════════════════════════════════

def recuperer_actu(joueur: str) -> str:
    """Cherche la dernière actu du joueur via Google News RSS."""
    try:
        import feedparser
        q   = urllib.parse.quote_plus(f"{joueur} football 2025")
        url = f"https://news.google.com/rss/search?q={q}&hl=fr&gl=FR&ceid=FR:fr"
        feed = feedparser.parse(url)
        if feed.entries:
            return feed.entries[0].title
    except Exception:
        pass
    return ""


def generer_script(joueur: str, actu: str) -> str:
    """Génère un script commentateur sport d'au moins 30 secondes."""
    blocs = [
        f"Bienvenue sur Prisme Foot, la chaîne numéro un de l'actualité football.",
        f"Aujourd'hui, nous allons parler de {joueur}, l'un des joueurs les plus électrisants de sa génération.",
        actu if actu else f"Et cette semaine encore, {joueur} fait parler de lui sur les terrains européens.",
        f"Son niveau de performance est tout simplement exceptionnel. Chaque ballon touché est une démonstration de talent pur.",
        f"Que ce soit par sa vitesse, sa technique de balle ou son sens du but, {joueur} régale les amateurs de football du monde entier.",
        f"Les recruteurs des plus grands clubs ont les yeux rivés sur lui, et on comprend pourquoi.",
        f"Sur les réseaux, les clips de {joueur} explosent les compteurs de vues. La nouvelle génération a trouvé son idole.",
        f"Restez connectés sur Prisme Foot pour suivre toute l'actualité autour de {joueur} et de vos joueurs préférés.",
        f"Abonnez-vous, activez la notification, et partagez cette vidéo à tous vos amis supporters de football.",
        f"Prisme Foot, le foot comme vous ne l'avez jamais vu.",
    ]
    # Construire jusqu'à atteindre la durée cible
    target_mots = int(MIN_DURATION / WPM_FACTOR) + 20
    texte = ""
    for bloc in blocs:
        texte += " " + bloc
        if len(texte.split()) >= target_mots:
            break
    return texte.strip()


# ═══════════════════════════════════════════════════════════════
#  GÉNÉRATION AUDIO — ElevenLabs (voix masculine FR)
# ═══════════════════════════════════════════════════════════════

def generer_audio_elevenlabs(texte: str, output_path: str) -> tuple[bool, str]:
    """
    Appelle l'API ElevenLabs.
    Retourne (succès, message).
    """
    api_key  = st.session_state["el_api_key"]
    voice_id = st.session_state["el_voice_id"]

    if not api_key:
        return False, "Clé ElevenLabs manquante."
    if not voice_id:
        return False, "Voice ID manquant."

    url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
    headers = {
        "xi-api-key":   api_key,
        "Content-Type": "application/json",
        "Accept":       "audio/mpeg",
    }
    payload = {
        "text":     texte[:4500],   # limite API
        "model_id": "eleven_multilingual_v2",
        "voice_settings": {
            "stability":         0.50,
            "similarity_boost":  0.80,
            "style":             0.50,
            "use_speaker_boost": True,
        },
    }

    try:
        r = requests.post(url, json=payload, headers=headers, timeout=45)

        if r.status_code == 401:
            return False, "❌ Clé ElevenLabs invalide. Vérifiez dans HF Secrets."
        if r.status_code == 422:
            return False, "❌ Voice ID introuvable. Changez de voix dans la sidebar."
        if r.status_code == 429:
            return False, "❌ Quota ElevenLabs dépassé. Attendez ou changez de plan."

        r.raise_for_status()

        with open(output_path, "wb") as f:
            f.write(r.content)

        taille = Path(output_path).stat().st_size
        if taille < 2000:
            return False, f"Audio trop petit ({taille} octets) — réponse API anormale."

        return True, f"Audio généré ({taille // 1024} Ko)"

    except requests.exceptions.Timeout:
        return False, "Timeout ElevenLabs (>45s). Réessayez."
    except Exception as e:
        return False, f"Erreur ElevenLabs : {str(e)[:120]}"


def generer_audio_gtts(texte: str, output_path: str) -> tuple[bool, str]:
    """Fallback gTTS — voix FR gratuite."""
    try:
        from gtts import gTTS
        propre = (texte
                  .replace("'", " ").replace('"', " ")
                  .replace(":", " ").replace("&", "et"))
        gTTS(text=propre, lang="fr", tld="fr").save(output_path)
        taille = Path(output_path).stat().st_size
        if taille < 1000:
            return False, "gTTS a généré un fichier vide."
        return True, f"Voix gTTS générée ({taille // 1024} Ko)"
    except Exception as e:
        return False, f"Erreur gTTS : {str(e)[:120]}"


def generer_audio(texte: str, output_path: str, logger) -> bool:
    """Tente ElevenLabs, bascule sur gTTS si échec."""
    ok, msg = generer_audio_elevenlabs(texte, output_path)
    if ok:
        logger.success(f"🎙️ Voix masculine ElevenLabs : {msg}")
        return True

    logger.warning(f"ElevenLabs → {msg} — Bascule sur gTTS...")
    ok, msg = generer_audio_gtts(texte, output_path)
    if ok:
        logger.info(f"🎙️ {msg}")
        return True

    logger.error(f"Audio impossible : {msg}")
    return False


# ═══════════════════════════════════════════════════════════════
#  TÉLÉCHARGEMENT IMAGES — Unsplash
# ═══════════════════════════════════════════════════════════════

def telecharger_images(joueur: str, n: int, logger) -> List[str]:
    """
    Tente les clés Unsplash dans l'ordre.
    Retourne une liste de chemins d'images valides.
    """
    cles = [
        k for k in [
            st.session_state["unsplash_key1"],
            st.session_state["unsplash_key2"],
        ] if k and k.strip()
    ]

    if not cles:
        logger.warning("Pas de clé Unsplash → fond coloré.")
        return []

    for idx, cle in enumerate(cles):
        try:
            logger.info(f"Recherche images Unsplash (clé #{idx+1})...")
            r = requests.get(
                "https://api.unsplash.com/search/photos",
                params={
                    "query":       f"{joueur} football soccer",
                    "per_page":    n,
                    "orientation": "portrait",
                    "content_filter": "high",
                },
                headers={"Authorization": f"Client-ID {cle}"},
                timeout=15,
            )

            if r.status_code == 401:
                logger.warning(f"Clé Unsplash #{idx+1} invalide (401).")
                continue
            if r.status_code == 429:
                logger.warning(f"Clé Unsplash #{idx+1} quota atteint (429).")
                continue
            if r.status_code != 200:
                logger.warning(f"Unsplash #{idx+1} erreur {r.status_code}.")
                continue

            resultats = r.json().get("results", [])
            if not resultats:
                logger.warning(f"Aucune image trouvée pour '{joueur}'.")
                continue

            logger.info(f"{len(resultats)} image(s) trouvée(s).")
            paths = []

            for i, item in enumerate(resultats[:n]):
                img_url = item["urls"].get("regular", item["urls"].get("small", ""))
                if not img_url:
                    continue
                try:
                    ir = requests.get(img_url, timeout=20)
                    ir.raise_for_status()
                    p = os.path.join(tempfile.gettempdir(), f"pf_{uuid.uuid4().hex[:8]}.jpg")
                    with open(p, "wb") as f:
                        f.write(ir.content)
                    if Path(p).stat().st_size > 5000:
                        paths.append(p)
                        logger.info(f"  Image {i+1} OK ({Path(p).stat().st_size // 1024} Ko)")
                    else:
                        Path(p).unlink(missing_ok=True)
                except Exception as e:
                    logger.warning(f"  Image {i+1} échouée : {e}")

            if paths:
                return paths

        except Exception as e:
            logger.warning(f"Unsplash clé #{idx+1} : {str(e)[:80]}")
            continue

    logger.warning("Toutes les clés Unsplash ont échoué → fond coloré.")
    return []


# ═══════════════════════════════════════════════════════════════
#  CONSTRUCTION VIDÉO — FFmpeg
# ═══════════════════════════════════════════════════════════════

def verifier_ffmpeg() -> bool:
    try:
        subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
        return True
    except Exception:
        return False


def image_vers_clip(img_path: str, duration: float, out: str) -> bool:
    """Convertit une image en clip MP4 vertical."""
    cmd = [
        "ffmpeg", "-y",
        "-loop", "1",
        "-i", img_path,
        "-t", str(duration),
        "-vf", (
            f"scale={VIDEO_W}:{VIDEO_H}:force_original_aspect_ratio=increase,"
            f"crop={VIDEO_W}:{VIDEO_H},"
            "setsar=1,format=yuv420p"
        ),
        "-c:v", "libx264",
        "-preset", "fast",
        "-pix_fmt", "yuv420p",
        "-r", "25",
        out,
    ]
    try:
        res = subprocess.run(cmd, capture_output=True, timeout=60)
        return res.returncode == 0 and Path(out).stat().st_size > 1000
    except Exception:
        return False


def fond_colore_clip(duration: float, out: str) -> bool:
    """Crée un fond dégradé sombre si pas d'images."""
    cmd = [
        "ffmpeg", "-y",
        "-f", "lavfi",
        "-i", f"color=c=0x0a1628:s={VIDEO_W}x{VIDEO_H}:r=25:d={duration}",
        "-c:v", "libx264", "-preset", "fast",
        "-pix_fmt", "yuv420p",
        out,
    ]
    try:
        res = subprocess.run(cmd, capture_output=True, timeout=30)
        return res.returncode == 0
    except Exception:
        return False


def escape_ff(text: str) -> str:
    """Échappe les caractères spéciaux pour ffmpeg drawtext."""
    for c, r in [("\\","\\\\"), ("'","\u2019"), (":",r"\:"), ("%","\\%"), ("[","\\["), ("]","\\]")]:
        text = text.replace(c, r)
    return text


def assembler_video(joueur: str, script: str, logger) -> Optional[str]:
    """
    Pipeline complet :
    1. Audio  → ElevenLabs ou gTTS
    2. Images → Unsplash ou fond coloré
    3. Clips  → FFmpeg image → MP4
    4. Concat → slideshow
    5. Mixage → texte + audio → vidéo finale
    """
    if not verifier_ffmpeg():
        logger.error("FFmpeg non disponible sur ce serveur.")
        return None

    uid     = uuid.uuid4().hex[:8]
    tmp     = tempfile.gettempdir()
    to_clean = []

    try:
        # ── 1. AUDIO ─────────────────────────────────────────────────────────
        logger.info("⏳ Étape 1/4 — Génération de la voix...")
        audio_path = os.path.join(tmp, f"pf_audio_{uid}.mp3")
        to_clean.append(audio_path)

        if not generer_audio(script, audio_path, logger):
            return None

        # Durée réelle de l'audio
        try:
            from mutagen.mp3 import MP3
            duration = max(MIN_DURATION, math.ceil(MP3(audio_path).info.length) + 2)
        except Exception:
            duration = max(MIN_DURATION, int(len(script.split()) * WPM_FACTOR) + 5)

        logger.info(f"Durée audio : {duration}s")

        # ── 2. IMAGES ─────────────────────────────────────────────────────────
        logger.info("⏳ Étape 2/4 — Téléchargement des images...")
        images = telecharger_images(joueur, n=5, logger=logger)
        to_clean.extend(images)

        # ── 3. CLIPS ─────────────────────────────────────────────────────────
        logger.info("⏳ Étape 3/4 — Création des clips vidéo...")
        clips = []

        if images:
            seg = round(duration / len(images), 2)
            logger.info(f"{len(images)} image(s), {seg}s par segment")
            for i, img in enumerate(images):
                cp = os.path.join(tmp, f"pf_clip_{uid}_{i}.mp4")
                to_clean.append(cp)
                if image_vers_clip(img, seg, cp):
                    clips.append(cp)
                    logger.info(f"  Clip {i+1}/{len(images)} OK")
                else:
                    logger.warning(f"  Clip {i+1} échoué")

        if not clips:
            logger.info("Génération fond coloré...")
            clip_bg = os.path.join(tmp, f"pf_bg_{uid}.mp4")
            to_clean.append(clip_bg)
            if fond_colore_clip(duration, clip_bg):
                clips.append(clip_bg)
            else:
                logger.error("Impossible de créer le fond coloré.")
                return None

        # ── 4. CONCAT ─────────────────────────────────────────────────────────
        concat_file = os.path.join(tmp, f"pf_concat_{uid}.txt")
        slideshow   = os.path.join(tmp, f"pf_slide_{uid}.mp4")
        to_clean.extend([concat_file, slideshow])

        with open(concat_file, "w") as f:
            for c in clips:
                f.write(f"file '{c}'\n")

        cmd_concat = [
            "ffmpeg", "-y",
            "-f", "concat", "-safe", "0",
            "-i", concat_file,
            "-c:v", "libx264", "-preset", "fast",
            "-pix_fmt", "yuv420p",
            slideshow,
        ]
        res = subprocess.run(cmd_concat, capture_output=True, timeout=120)
        if res.returncode != 0:
            logger.error(f"Concat échoué : {res.stderr.decode()[-200:]}")
            return None

        # ── 5. MIXAGE FINAL ───────────────────────────────────────────────────
        logger.info("⏳ Étape 4/4 — Mixage final (texte + audio)...")
        video_out = os.path.join(tmp, f"pf_final_{uid}.mp4")

        j_esc = escape_ff(joueur.upper()[:24])
        t_esc = escape_ff(script[:60] + "..." if len(script) > 60 else script)

        vf = (
            # Bande noire semi-transparente
            "drawbox=y=0:x=0:width=iw:height=200:color=black@0.70:t=fill,"
            "drawbox=y=ih-180:x=0:width=iw:height=180:color=black@0.70:t=fill,"
            # Logo chaîne
            f"drawtext=text='⚽ PRISME FOOT':fontcolor=#FFD700:fontsize=38"
            f":x=(w-text_w)/2:y=40:shadowcolor=black:shadowx=2:shadowy=2,"
            # Nom du joueur
            f"drawtext=text='{j_esc}':fontcolor=white:fontsize=52:x=(w-text_w)/2:y=100"
            f":box=1:boxcolor=#CC0000@0.85:boxborderw=12"
            f":shadowcolor=black:shadowx=3:shadowy=3,"
            # Sous-titre actu
            f"drawtext=text='{t_esc}':fontcolor=white:fontsize=22:x=(w-text_w)/2"
            f":y=ih-140:shadowcolor=black:shadowx=1:shadowy=1,"
            # CTA abonnement
            "drawtext=text='👍 ABONNEZ-VOUS':fontcolor=#FFD700:fontsize=28"
            ":x=(w-text_w)/2:y=ih-80:shadowcolor=black:shadowx=2:shadowy=2"
        )

        cmd_final = [
            "ffmpeg", "-y",
            "-i", slideshow,
            "-i", audio_path,
            "-vf", vf,
            "-c:v", "libx264", "-preset", "fast",
            "-c:a", "aac", "-b:a", "128k",
            "-t", str(duration),
            "-shortest",
            "-movflags", "+faststart",
            video_out,
        ]
        res = subprocess.run(cmd_final, capture_output=True, timeout=180)
        if res.returncode != 0:
            logger.error(f"Mixage échoué :\n{res.stderr.decode()[-400:]}")
            return None

        if not Path(video_out).exists() or Path(video_out).stat().st_size < 10000:
            logger.error("Vidéo finale vide ou corrompue.")
            return None

        taille_mo = Path(video_out).stat().st_size / (1024 * 1024)
        logger.success(f"✅ Vidéo créée ! ({taille_mo:.1f} Mo, {duration}s)")
        return video_out

    except Exception as e:
        logger.error(f"Erreur inattendue : {str(e)}")
        return None

    finally:
        cleanup(*to_clean)


# ═══════════════════════════════════════════════════════════════
#  INTERFACE STREAMLIT
# ═══════════════════════════════════════════════════════════════

st.set_page_config(
    page_title="⚽ Prisme Foot Studio",
    page_icon="⚽",
    layout="wide",
    initial_sidebar_state="expanded",
)

# CSS personnalisé
st.markdown("""
<style>
    .main-title {
        font-size: 2.2rem;
        font-weight: 800;
        background: linear-gradient(135deg, #FFD700, #FF4444);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        text-align: center;
        margin-bottom: 0.2rem;
    }
    .sub-title {
        text-align: center;
        color: #888;
        font-size: 0.9rem;
        margin-bottom: 2rem;
    }
    .status-ok  { color: #00C853; font-weight: 600; }
    .status-ko  { color: #FF1744; font-weight: 600; }
    .step-badge {
        background: linear-gradient(135deg, #FFD700, #FF8C00);
        color: #000;
        padding: 2px 12px;
        border-radius: 20px;
        font-weight: 700;
        font-size: 0.8rem;
    }
</style>
""", unsafe_allow_html=True)

st.markdown('<div class="main-title">⚽ PRISME FOOT STUDIO</div>', unsafe_allow_html=True)
st.markdown('<div class="sub-title">Créateur de vidéos football automatisées — Version Finale</div>', unsafe_allow_html=True)

# ── SIDEBAR — Configuration ───────────────────────────────────────────────────
with st.sidebar:
    st.markdown("## ⚙️ Configuration")

    # ── ElevenLabs ────────────────────────────────────────────
    st.markdown("### 🎙️ Voix ElevenLabs")
    el_key_input = st.text_input(
        "Clé API ElevenLabs",
        value=st.session_state["el_api_key"],
        type="password",
        placeholder="sk_xxxxxxxxxxxxxxxxxxxxxxxx",
        help="Copiez depuis elevenlabs.io → Profile → API Key",
    )
    if el_key_input.strip() != st.session_state["el_api_key"]:
        st.session_state["el_api_key"] = el_key_input.strip()

    voix_labels = list(VOIX_DISPONIBLES.keys())
    voix_ids    = list(VOIX_DISPONIBLES.values())
    idx_actuel  = voix_ids.index(st.session_state["el_voice_id"]) \
                  if st.session_state["el_voice_id"] in voix_ids else 0

    voix_choisie = st.selectbox("Voix masculine", voix_labels, index=idx_actuel)
    st.session_state["el_voice_id"] = VOIX_DISPONIBLES[voix_choisie]

    if st.session_state["el_api_key"]:
        st.markdown('<span class="status-ok">✅ Clé ElevenLabs configurée</span>', unsafe_allow_html=True)
    else:
        st.markdown('<span class="status-ko">⚠️ Pas de clé → voix gTTS</span>', unsafe_allow_html=True)

    st.divider()

    # ── Unsplash ───────────────────────────────────────────────
    st.markdown("### 🖼️ Images Unsplash")
    k1 = st.text_input(
        "Clé Unsplash #1",
        value=st.session_state["unsplash_key1"],
        type="password",
        placeholder="Clé Access Unsplash",
        help="unsplash.com/developers → New Application → Access Key",
    )
    k2 = st.text_input(
        "Clé Unsplash #2 (secours)",
        value=st.session_state["unsplash_key2"],
        type="password",
        placeholder="Optionnelle",
    )
    if k1.strip() != st.session_state["unsplash_key1"]:
        st.session_state["unsplash_key1"] = k1.strip()
    if k2.strip() != st.session_state["unsplash_key2"]:
        st.session_state["unsplash_key2"] = k2.strip()

    nb_cles = sum(1 for x in [k1, k2] if x.strip())
    if nb_cles:
        st.markdown(f'<span class="status-ok">✅ {nb_cles} clé(s) Unsplash</span>', unsafe_allow_html=True)
    else:
        st.markdown('<span class="status-ko">⚠️ Pas de clé → fond coloré</span>', unsafe_allow_html=True)

    st.divider()
    st.markdown("### 📋 État du système")
    ffmpeg_ok = verifier_ffmpeg()
    st.markdown(f'FFmpeg : {"✅ OK" if ffmpeg_ok else "❌ Manquant"}')
    try:
        import feedparser
        st.markdown("feedparser : ✅ OK")
    except ImportError:
        st.markdown("feedparser : ⚠️ absent (actu désactivée)")
    try:
        from mutagen.mp3 import MP3
        st.markdown("mutagen : ✅ OK")
    except ImportError:
        st.markdown("mutagen : ⚠️ absent")

# ── ZONE PRINCIPALE ──────────────────────────────────────────────────────────
col_main, col_preview = st.columns([3, 2])

with col_main:
    # ÉTAPE 1 — Joueur + Script
    st.markdown('<span class="step-badge">ÉTAPE 1</span> **Joueur et script**', unsafe_allow_html=True)
    st.markdown("")

    joueur = st.text_input(
        "👤 Nom du joueur",
        value="Vinicius Junior",
        placeholder="Ex: Mbappé, Ronaldo, Salah...",
    )

    col_a, col_b = st.columns([1, 1])
    with col_a:
        if st.button("🔍 Générer le script", use_container_width=True, type="primary"):
            if not joueur.strip():
                st.warning("Entrez le nom d'un joueur.")
            else:
                with st.spinner("Recherche de l'actualité..."):
                    actu = recuperer_actu(joueur)
                    script = generer_script(joueur, actu)
                    st.session_state["script_texte"] = script
                    nb    = len(script.split())
                    duree = round(nb * WPM_FACTOR)
                    st.success(f"Script généré — {nb} mots ≈ {duree}s")

    with col_b:
        if st.button("🔄 Réinitialiser", use_container_width=True):
            st.session_state["script_texte"] = ""
            st.session_state["video_path"]   = ""
            st.rerun()

    # Zone texte script — toujours pré-remplie
    script_final = st.text_area(
        "📝 Script (modifiable)",
        value=st.session_state["script_texte"],
        height=280,
        placeholder="Cliquez sur 'Générer le script' ou écrivez votre texte ici...",
        key="script_area_input",
    )

    # Sync session_state à chaque modification
    if script_final != st.session_state["script_texte"]:
        st.session_state["script_texte"] = script_final

    # Métriques script
    if script_final.strip():
        nb_mots   = len(script_final.split())
        duree_est = round(nb_mots * WPM_FACTOR)
        manque    = max(0, MIN_DURATION - duree_est)
        c1, c2, c3 = st.columns(3)
        c1.metric("Mots", nb_mots)
        c2.metric("Durée estimée", f"{duree_est}s")
        c3.metric("Durée min requise", f"{MIN_DURATION}s",
                  delta=f"+{manque}s manquants" if manque else "✅ OK",
                  delta_color="inverse" if manque else "normal")

    st.divider()

    # ÉTAPE 2 — Création vidéo
    st.markdown('<span class="step-badge">ÉTAPE 2</span> **Création de la vidéo**', unsafe_allow_html=True)
    st.markdown("")

    peut_creer = bool(script_final.strip()) and bool(joueur.strip()) and ffmpeg_ok

    if not peut_creer:
        if not ffmpeg_ok:
            st.error("❌ FFmpeg non disponible sur ce serveur HuggingFace.")
        elif not script_final.strip():
            st.info("⬆️ Générez ou écrivez un script d'abord.")

    if st.button(
        "🎬 CRÉER LA VIDÉO",
        disabled=not peut_creer,
        use_container_width=True,
        type="primary",
    ):
        st.session_state["video_path"] = ""
        log_container = st.empty()

        class Logger:
            """Logger inline dans Streamlit."""
            def __init__(self, container):
                self.msgs = []
                self.c = container

            def _render(self):
                self.c.markdown("\n\n".join(self.msgs))

            def info(self, msg):
                self.msgs.append(f"ℹ️ {msg}")
                self._render()

            def success(self, msg):
                self.msgs.append(f"✅ {msg}")
                self._render()

            def warning(self, msg):
                self.msgs.append(f"⚠️ {msg}")
                self._render()

            def error(self, msg):
                self.msgs.append(f"❌ {msg}")
                self._render()

        logger = Logger(log_container)

        with st.spinner("🎬 Montage en cours... (30 à 90 secondes)"):
            video_path = assembler_video(joueur.strip(), script_final, logger)

        if video_path and Path(video_path).exists():
            st.session_state["video_path"] = video_path
            st.balloons()
        else:
            st.error("La vidéo n'a pas pu être créée. Consultez les messages ci-dessus.")

# ── COLONNE PREVIEW ────────────────────────────────────────────────────────────
with col_preview:
    st.markdown("### 📱 Aperçu & Téléchargement")
    st.markdown("")

    vp = st.session_state.get("video_path", "")
    if vp and Path(vp).exists():
        st.video(vp)
        st.markdown("")
        with open(vp, "rb") as f:
            nom_fichier = f"prisme_{joueur.replace(' ', '_').lower()}.mp4"
            st.download_button(
                label="⬇️ Télécharger la vidéo MP4",
                data=f,
                file_name=nom_fichier,
                mime="video/mp4",
                use_container_width=True,
                type="primary",
            )
        taille = Path(vp).stat().st_size / (1024 * 1024)
        st.caption(f"Fichier : {nom_fichier} — {taille:.1f} Mo")
    else:
        st.markdown("""
        <div style="
            border: 2px dashed #444;
            border-radius: 12px;
            padding: 60px 20px;
            text-align: center;
            color: #666;
        ">
            <div style="font-size: 3rem;">🎬</div>
            <div style="margin-top: 12px; font-size: 0.9rem;">
                La vidéo apparaîtra ici<br>après création
            </div>
        </div>
        """, unsafe_allow_html=True)

    st.divider()
    st.markdown("### 💡 Guide rapide")
    st.markdown("""
1. **Sidebar** → entrez vos clés API
2. **Nom du joueur** → cliquez Générer
3. **Modifiez** le script si besoin
4. **Créez la vidéo** → téléchargez

---
**Sans clé ElevenLabs** : voix gTTS (gratuit)
**Sans clé Unsplash** : fond coloré sombre
""")