File size: 59,068 Bytes
55842c9
 
 
 
 
 
dd74709
 
 
 
 
 
 
 
 
 
 
 
 
254bc2a
dd74709
254bc2a
 
 
 
 
 
 
 
 
 
 
dd74709
 
 
 
 
 
 
 
 
55842c9
 
 
8669fff
 
 
 
 
 
55842c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
598630d
 
0bbdd3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf7e429
0bbdd3e
 
ad6678f
cf7e429
dd74709
 
 
 
 
 
 
 
cf7e429
 
dd74709
ad6678f
dd74709
 
 
ad6678f
 
0bbdd3e
dd74709
 
 
0bbdd3e
 
 
 
 
 
 
 
55842c9
4c813af
55842c9
4c813af
55842c9
9699002
15d18fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55842c9
 
85ef151
 
 
 
b72db7e
 
 
 
 
 
 
 
 
 
fb32e8b
 
 
b72db7e
 
85ef151
 
 
 
 
 
 
 
 
 
 
 
 
55842c9
 
 
 
 
 
 
 
 
 
 
 
 
 
702916c
d393436
fed1b0a
702916c
55842c9
dd0f721
 
55842c9
 
fed1b0a
 
78f0cac
fed1b0a
4a8b639
 
 
fed1b0a
55842c9
 
dd74709
55842c9
0bbdd3e
 
 
dd74709
0bbdd3e
dd74709
0bbdd3e
a0c60e5
 
 
ca896f7
702916c
ca896f7
ec835b2
 
e16b6ab
ec835b2
 
 
 
 
 
 
 
 
 
 
 
 
04a64b0
ec835b2
04a64b0
 
 
 
 
 
 
ec835b2
 
04a64b0
3385a4e
ec835b2
 
 
 
 
 
55842c9
 
 
702916c
4a8b639
 
 
702916c
4a8b639
 
55842c9
702916c
cb56d63
 
 
4c5976d
cb56d63
 
 
 
ec835b2
702916c
 
55842c9
 
 
 
 
 
 
 
 
702916c
7119e95
dd74709
702916c
7119e95
55842c9
c227bbf
28d4b58
 
702916c
28d4b58
55842c9
 
 
ec835b2
 
 
 
 
a1ae7a8
ec835b2
a1ae7a8
d537f63
 
 
 
 
9760271
 
 
 
 
d537f63
 
 
 
 
 
 
55842c9
c905e96
d393436
 
 
 
c905e96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d393436
c905e96
 
 
 
 
 
 
 
 
 
55842c9
3bdc3f4
 
 
 
 
 
bfbdd52
 
535cb73
 
 
 
 
 
bfbdd52
 
3bdc3f4
 
 
552e9fd
 
 
 
7c33111
 
 
 
 
 
 
 
 
 
 
 
552e9fd
 
 
 
 
 
 
 
ed98397
552e9fd
 
 
 
 
 
 
 
 
 
ed98397
55842c9
 
 
8669fff
 
 
 
 
 
 
 
55842c9
 
 
 
 
4c813af
4ccfdce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55842c9
 
 
4c813af
55842c9
 
 
 
 
 
 
 
77cd82b
55842c9
4d2d9e5
77cd82b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55842c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ee2075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bdc3f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31b9651
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d53c2e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31b9651
6562dbf
31b9651
 
766dab4
 
 
 
 
 
 
55842c9
 
 
 
 
 
 
 
 
 
 
 
d393436
 
 
 
 
 
7119e95
fed1b0a
dd74709
 
 
 
 
 
 
 
 
 
 
 
85ef151
 
 
 
b7bb9e1
 
 
254bc2a
 
702916c
7512f9d
 
 
 
b9a3174
702916c
55842c9
 
702916c
55842c9
 
 
3c864a9
 
 
 
55842c9
063608f
 
 
 
 
 
 
 
55842c9
 
 
 
 
 
 
 
dd74709
55842c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ccfdce
 
 
55842c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
063608f
 
 
 
55842c9
8669fff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55842c9
 
3d4021b
 
704d280
 
 
 
 
 
9ad9df9
 
 
704d280
 
9ad9df9
fe086d9
3d4021b
55842c9
 
 
 
 
 
 
4c813af
 
28bda50
 
 
3bd74ab
 
4c813af
55842c9
 
254bc2a
55842c9
 
 
 
 
 
254bc2a
 
 
 
 
 
 
 
4ccfdce
 
 
 
 
 
 
55842c9
 
 
 
 
 
 
 
8e5818b
 
55842c9
 
 
 
 
ce80bb9
55842c9
 
 
 
 
9ee2075
 
 
 
 
 
 
 
 
 
 
 
 
 
55842c9
 
 
3bdc3f4
31b9651
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bdc3f4
 
55842c9
 
 
d393436
 
 
 
 
 
 
cd27d2e
d393436
7119e95
 
 
 
 
 
cb56d63
7119e95
55842c9
d3843f6
55842c9
d3a0721
55842c9
 
 
 
 
f50c926
55842c9
 
 
 
 
c7ee5ab
55842c9
 
 
 
 
 
 
 
 
 
4c813af
55842c9
 
 
 
 
ce80bb9
 
 
 
 
 
 
c7ee5ab
ce80bb9
 
55842c9
 
 
adf7c86
 
 
 
 
 
 
 
55842c9
448df69
 
 
55842c9
 
448df69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f512010
448df69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
063608f
6570936
 
 
 
 
 
702916c
8b96b9f
 
adf7c86
 
dd74709
 
 
6570936
 
 
55842c9
063608f
 
714ac6f
 
063608f
 
d393436
 
 
 
7119e95
6570936
254bc2a
6570936
063608f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55842c9
3bdc3f4
 
 
 
 
 
 
 
d3843f6
 
 
 
 
 
 
705d30f
 
 
 
 
 
 
31b9651
 
 
 
 
 
766dab4
31b9651
 
766dab4
 
 
 
 
 
 
 
 
 
 
 
31b9651
55842c9
5831aee
 
 
 
 
 
 
 
 
 
 
9e663ff
 
dd74709
5831aee
 
 
 
55842c9
9ee2075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55842c9
 
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
import os, time, json, glob, random, asyncio, base64
from fastapi import FastAPI, Request, UploadFile, File
from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
from groq import Groq
import edge_tts, requests

# Servicio Veo independiente (con cascada a Leonardo.ai)
try:
    from veo_service import generar_clips_escenas as generar_runway
except Exception:
    def generar_runway(escenas): return None
try:
    from leonardo_service import generar_clips_escenas as generar_leonardo
except Exception:
    def generar_leonardo(escenas): return None
try:
    from ltx_service import generar_clips_escenas as generar_ltx
except Exception:
    def generar_ltx(escenas): return None
def generar_clips_escenas(escenas, nicho="espiritualidad", motor="auto"):
    import copy
    if motor == "ltx":
        res = generar_ltx(copy.deepcopy(escenas), nicho=nicho)
        if res and any(str(e.get("material", "")).startswith("ltx_") for e in res): return res
        print("[Cerebro] LTX elegido pero fallo.", flush=True); return escenas
    if motor == "veo":
        res = generar_runway(copy.deepcopy(escenas))
        if res and any(str(e.get("material", "")).startswith("veo_") for e in res): return res
        print("[Cerebro] Veo elegido pero fallo.", flush=True); return escenas
    if motor == "leonardo":
        res_leo = generar_leonardo(copy.deepcopy(escenas))
        return res_leo if res_leo else escenas
    res = generar_ltx(copy.deepcopy(escenas), nicho=nicho)
    if res and any(str(e.get("material", "")).startswith("ltx_") for e in res): return res
    print("[Cerebro] LTX no disponible. Saltando a Runway...", flush=True)
    res = generar_runway(copy.deepcopy(escenas))
    if res and any(str(e.get("material", "")).startswith("veo_") for e in res): return res
    print("[Cerebro] Saltando a Leonardo.ai...", flush=True)
    res_leo = generar_leonardo(copy.deepcopy(escenas))
    return res_leo if res_leo else escenas

app = FastAPI()

GROQ_KEYS = [k for k in [os.environ.get("GROQ_KEY",""), os.environ.get("GROQ_KEY_2",""), os.environ.get("GROQ_KEY_3","")] if k]

CLAVE_ACCESO = os.environ.get("CLAVE_ACCESO", "demo2026")

def verificar_clave(clave):
    return clave == CLAVE_ACCESO

PEXELS_KEY = os.environ.get("PEXELS_KEY","")

# Estado de la sesion (guarda guion editado y material entre pasos)
ESTADO = {
    "guion": "",
    "archivos": [],
    "voz_lista": False,
    "video_listo": False,
}

ESTILOS = {
    "narrativo": "narrativo y emocional, como contando una historia",
    "educativo": "educativo y claro, explicando con autoridad",
    "motivador": "motivador e inspirador, que mueva a la accion",
    "publicitario": "publicitario y persuasivo, vendiendo sin parecer venta",
    "misterio": "intrigante y de misterio, con ganchos de curiosidad",
}

VOCES = {
    "es": {
        "masculina": ["es-ES-AlvaroNeural","es-MX-JorgeNeural","es-AR-TomasNeural","es-CO-GonzaloNeural"],
        "femenina": ["es-ES-ElviraNeural","es-MX-DaliaNeural","es-AR-ElenaNeural","es-CO-SalomeNeural"],
    },
    "en": {"masculina":["en-US-GuyNeural","en-GB-RyanNeural"],"femenina":["en-US-JennyNeural","en-GB-SoniaNeural"]},
}

def log(m): print(m, flush=True)

# Detecta la marca "Veo" en la esquina abajo-derecha y la tapa con el logo de Teshua.
# Si falla, devuelve el clip original (nunca rompe el montaje).
def quitar_marca_meta(path, _cache={}):
    exts_v = (".mp4",".mov",".webm",".avi",".mkv")
    exts_i = (".jpg",".jpeg",".png",".webp")
    low = str(path).lower()
    if not low.endswith(exts_v + exts_i):
        return path
    if path in _cache:
        return _cache[path]
    try:
        import subprocess
        dims = subprocess.run(
            ["ffprobe","-v","error","-select_streams","v:0",
             "-show_entries","stream=width,height","-of","csv=p=0:s=x", path],
            capture_output=True, text=True).stdout.strip()
        W, H = [int(v) for v in dims.split("x")[:2]]
        # Tapar marca "Veo" (banda negra abajo-derecha) con "Teshua" dorado
        es_video = low.endswith(exts_v)
        salida = path + ("_clean.mp4" if es_video else "_clean.png")
        fs = max(22, int(H * 0.030))
        pad = int(fs * 0.5)
        # Caja: 22% ancho, 6% alto, pegada abajo-derecha con margen de 1%
        bx = W - int(W * 0.23)
        by = H - int(H * 0.065)
        bw = int(W * 0.22)
        bh = int(H * 0.060)
        # Texto centrado dentro de la caja (coordenadas fijas, no variables ffmpeg)
        tx = bx + int(bw * 0.08)
        ty = by + int(bh * 0.20)
        # 1) Caja negra que tapa "Veo" completamente
        # 2) Borde dorado alrededor
        # 3) Texto "Teshua" dorado encima, bien posicionado dentro de la caja
        vf = (
            f"drawbox=x={bx}:y={by}:w={bw}:h={bh}:color=black@1:t=fill,"
            f"drawbox=x={bx}:y={by}:w={bw}:h={bh}:color=0xFFD700@1:t=2,"
            f"drawtext=text='Teshua':fontsize={fs}:fontcolor=0xFFD700:x={tx}:y={ty}:font=serif:borderw=2:bordercolor=black"
        )
        cmd = ["ffmpeg","-y","-v","error","-i",path,"-vf",vf]
        cmd += (["-c:a","copy",salida] if es_video else [salida])
        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode != 0:
            log(f"marca ffmpeg error: {result.stderr[:300]}")
        if os.path.exists(salida) and os.path.getsize(salida) > 0:
            log(f"marca: {os.path.basename(path)} -> {os.path.basename(salida)} (logo={'si' if os.path.exists('logo.png') else 'no'})")
            _cache[path] = salida; return salida
    except Exception as e:
        log(f"marca error: {e}")
    _cache[path] = path
    return path

# ========== GUION ==========
def generar_guion(texto_base, estilo, duracion=60):
    estilo_desc = ESTILOS.get(estilo, ESTILOS["narrativo"])
    palabras = int(duracion * 2.4)
    last_err = None
    MODELOS = ["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "openai/gpt-oss-120b", "openai/gpt-oss-20b"]
    prompt = f"Basandote en este contenido:\n\n{texto_base}\n\nEscribe SOLO el texto a narrar en un video de {duracion} segundos (aproximadamente {palabras} palabras, IMPORTANTE: debe ser largo si la duracion es alta). Estilo: {estilo_desc}. Usa psicologia de retencion: gancho fuerte en los primeros 3 segundos, desarrollo con curiosidad, cierre con llamada a la accion. NO incluyas indicaciones tipo narrador, voz en off, intro, outro. Solo el texto a leer, sin simbolos, sin hashtags, sin emojis."
    # Probar cada modelo con cada key hasta que uno funcione
    for modelo in MODELOS:
        for k in GROQ_KEYS:
            try:
                client = Groq(api_key=k)
                res = client.chat.completions.create(
                    messages=[{"role":"user","content":prompt}],
                    model=modelo, temperature=0.85
                )
                return res.choices[0].message.content.strip()
            except Exception as e:
                last_err = e
                if "rate_limit" in str(e).lower() or "429" in str(e): continue
                if "model" in str(e).lower() or "decommission" in str(e).lower(): break
                continue
    raise last_err if last_err else Exception("Sin keys Groq")


def prompt_visual_auto(texto_escena):
    if not texto_escena or not texto_escena.strip():
        texto_escena = "cinematic atmospheric scene"
    instruccion = (
        "Eres un director de fotografia escribiendo el prompt para un modelo de video por IA (LTX). "
        "Crea UN solo prompt en INGLES, fotorrealista y cinematografico, que ilustre la frase de abajo. "
        "Escribelo como UNA descripcion fluida y en orden cronologico: "
        "primero el plano y el encuadre, luego el sujeto y el entorno con detalle concreto, "
        "luego la luz, el color y la atmosfera, y por ultimo UN movimiento de camara LENTO y SUAVE "
        "(un push-in lento, una deriva suave, un tilt ascendente) mas algun movimiento de la escena "
        "tambien lento y simple (la luz que cambia, particulas que flotan, niebla que se desplaza). "
        "REGLA CLAVE para que el video no se deforme: el movimiento debe ser lento, continuo y simple; "
        "NADA de movimiento rapido, accion compleja, ni personas con gestos detallados de manos o cara. "
        "REGLA DE LUZ: la escena SIEMPRE claramente iluminada, con una fuente de luz visible "
        "(luz de luna, horizonte que brilla, rayos de sol, estrellas, una vela); "
        "NUNCA negro total ni infraexpuesto, el cuadro debe verse con claridad. "
        "Entre 60 y 110 palabras, concreto, sin contradicciones, sin listas, sin numeros, sin comillas. "
        "Solo el prompt en ingles. Frase: " + texto_escena)
    for modelo in ["llama-3.1-8b-instant", "llama-3.3-70b-versatile"]:
        for k in GROQ_KEYS:
            try:
                client = Groq(api_key=k)
                res = client.chat.completions.create(
                    messages=[{"role":"user","content":instruccion}], model=modelo, temperature=0.8)
                return res.choices[0].message.content.strip().strip('"')
            except Exception as e:
                if "rate_limit" in str(e).lower() or "429" in str(e): continue
                if "model" in str(e).lower() or "decommission" in str(e).lower(): break
                continue
    return texto_escena

# ========== VOZ ==========
async def generar_voz(guion, idioma="es", genero="masculina", pais=""):
    voces = VOCES.get(idioma, VOCES["es"]).get(genero, ["es-ES-AlvaroNeural"])
    if pais:
        cods = {"españa":"ES","mexico":"MX","argentina":"AR","colombia":"CO","usa":"US","uk":"GB","australia":"AU"}
        cod = cods.get(pais.lower(),"")
        if cod:
            filt = [v for v in voces if f"-{cod}-" in v]
            if filt: voces = filt
    voz_sel = random.choice(voces)
    await edge_tts.Communicate(guion, voz_sel).save("voz.mp3")
    return voz_sel

# ========== VIDEO ==========
def montar_video(guion, archivos, subs=None, efecto="ninguno", material_escenas=None, escenas_data=None):
    subs = subs or {}
    material_escenas = material_escenas or []
    escenas_data = escenas_data or []
    from moviepy.editor import AudioFileClip as AC, VideoFileClip as VC, ImageClip as IC, TextClip, CompositeVideoClip, concatenate_videoclips
    from PIL import Image as PILImage, ImageFilter as PIF, ImageFile
    ImageFile.LOAD_TRUNCATED_IMAGES = True

    voz = AC("voz.mp3")
    # Si el usuario asigno material por escena, usar ESE orden; si no, los archivos normales
    if material_escenas:
        fondos = [m + "_clean.mp4" if os.path.exists(m + "_clean.mp4") else m for m in material_escenas if os.path.exists(m) or os.path.exists(m + "_clean.mp4")]
    else:
        fondos = []
    # Respaldo: si no hay fondos de escenas validos, usar el material general
    if not fondos:
        fondos = archivos[:8] if archivos else []

    # Si no hay material propio, fondo de Pexels
        raise Exception("[Fenix Error] Leonardo AI fallo o no tiene saldo, y Pexels esta desactivado.")

    # === QUITAR MARCA "Meta AI" de cada clip de video antes de montar ===
    fondos = [quitar_marca_meta(f) for f in fondos]
    if material_escenas:
        material_escenas = [quitar_marca_meta(m) if not str(m).endswith("_norm.mp4") else m for m in material_escenas]
    if escenas_data:
        escenas_data = [(quitar_marca_meta(m) if m and not str(m).endswith("_norm.mp4") else m, s) for m, s in escenas_data]

    # Duracion: si hay escenas con segundos definidos, usar la SUMA; si no, la voz
    if escenas_data:
        suma_seg = sum(s for m,s in escenas_data)
        dur_total = min(suma_seg, 1200) if suma_seg > 0 else min(voz.duration, 1200)
    else:
        dur_total = min(voz.duration, 1200)

    # Si el material son SOLO videos, usar el video entero de fondo (no trocear)
    solo_videos = fondos and all(str(f).lower().endswith((".mp4",".mov",".webm",".avi",".mkv")) for f in fondos)
    if solo_videos:
        from moviepy.editor import concatenate_videoclips as _ccv
        vclips = []
        for fp in fondos:
            try:
                vc = VC(fp).without_audio()
                vc = vc.resize(height=1920) if vc.w/vc.h > 1080/1920 else vc.resize(width=1080)
                vc = vc.crop(x_center=vc.w/2, y_center=vc.h/2, width=1080, height=1920)
                vclips.append(vc)
            except Exception as e:
                log(f"Error video {fp}: {e}")
        if vclips:
            base = _ccv(vclips, method="compose") if len(vclips) > 1 else vclips[0]
            # Repetir el video en bucle hasta cubrir toda la duracion (sin negro)
            if base.duration < dur_total:
                from moviepy.editor import concatenate_videoclips as _ccloop
                repes = []
                acumulado = 0
                while acumulado < dur_total:
                    repes.append(base)
                    acumulado += base.duration
                base = _ccloop(repes, method="compose").subclip(0, dur_total)
            else:
                base = base.subclip(0, dur_total)
            clip = base
            voz = voz.subclip(0, min(dur_total, voz.duration))
            _USAR_VIDEO_ENTERO = True
        else:
            _USAR_VIDEO_ENTERO = False
    else:
        _USAR_VIDEO_ENTERO = False

    num_planos = max(int(dur_total / 4) + 1, len(fondos))
    fondos_loop = (fondos * ((num_planos // max(len(fondos),1)) + 1))[:num_planos]
    dur_clip = dur_total / num_planos
    # Si hay escenas con segundos, cada clip dura SUS segundos
    # Solo usar segundos por escena si hay material asignado en las escenas
    material_en_escenas = [(m,s) for m,s in escenas_data if m and os.path.exists(m)]
    usar_seg_escena = bool(material_en_escenas) and not _USAR_VIDEO_ENTERO
    if usar_seg_escena:
        fondos_loop = [m for m,s in material_en_escenas]
        segundos_loop = [s for m,s in material_en_escenas]
    clips = []
    idx_clip = -1
    # EFECTO RAFAGA: las imagenes pasan rapido (0.6s) y se repiten en bucle hasta llenar la voz
    _es_rafaga = (efecto == "rafaga") and not _USAR_VIDEO_ENTERO
    if _es_rafaga and fondos_loop:
        dur_rafaga = 0.2
        n_necesarias = int(dur_total / dur_rafaga) + 1
        fondos_loop = [fondos_loop[k % len(fondos_loop)] for k in range(n_necesarias)]
        segundos_loop = [dur_rafaga for _ in fondos_loop]
        usar_seg_escena = True
    for fp in (fondos_loop if not _USAR_VIDEO_ENTERO else []):
        idx_clip += 1
        d_este = segundos_loop[idx_clip] if usar_seg_escena and idx_clip < len(segundos_loop) else dur_clip
        try:
            if fp.lower().endswith((".jpg",".jpeg",".png",".webp")):
                img = PILImage.open(fp).convert("RGB")
                w, h = img.size
                bg = img.resize((1080,1920), PILImage.LANCZOS).filter(PIF.GaussianBlur(40))
                ratio = min(1080/w, 1920/h)
                fg = img.resize((int(w*ratio), int(h*ratio)), PILImage.LANCZOS)
                bg.paste(fg, ((1080-fg.width)//2, (1920-fg.height)//2))
                bg.save(fp+"_r.jpg","JPEG",quality=90)
                ic = IC(fp+"_r.jpg").set_duration(d_este)
                if efecto in ("zoom","zoom_fundido"):
                    ic = ic.resize(lambda t: 1 + 0.015*t).set_duration(d_este)
                ic = ic.set_duration(d_este)
                clips.append(ic)
            else:
                vclip = VC(fp).without_audio()
                vclip = vclip.resize(height=1920) if vclip.w/vclip.h > 1080/1920 else vclip.resize(width=1080)
                vclip = vclip.crop(x_center=vclip.w/2, y_center=vclip.h/2, width=1080, height=1920)
                vclip = vclip.loop(duration=d_este).set_duration(d_este)
                clips.append(vclip)
        except Exception as e:
            log(f"Error clip {fp}: {e}")

    if not _USAR_VIDEO_ENTERO:
        hay_video = any(str(f).lower().endswith((".mp4",".mov",".webm",".avi")) for f in fondos_loop)
        if efecto in ("fundido","zoom_fundido") and len(clips) > 1 and not hay_video:
            from moviepy.editor import concatenate_videoclips as _cc
            clips_fx = [clips[0]] + [c2.crossfadein(0.5) for c2 in clips[1:]]
            clip = _cc(clips_fx, method="compose", padding=-0.5)
        else:
            clip = concatenate_videoclips(clips, method="compose")
        # MANUAL (material asignado a escenas): forzar duracion = suma de segundos exacta
        _es_manual = bool([m for m,s in escenas_data if m and os.path.exists(m)]) if escenas_data else False
        if _es_manual:
            suma = sum(s for m,s in escenas_data if m and os.path.exists(m))
            if clip.duration < suma:
                # Congelar el ultimo fotograma hasta llegar a la duracion (NO dejar negro)
                from moviepy.editor import ImageClip as _ICf
                ultimo = clip.to_ImageClip(t=clip.duration-0.1, duration=suma-clip.duration)
                from moviepy.editor import concatenate_videoclips as _ccf
                clip = _ccf([clip, ultimo.set_pos("center")], method="compose")
            else:
                clip = clip.subclip(0, suma)
            dur_total = suma
        else:
            # AUTOMATICO: dura lo que suman los clips (va de lujo, no tocar)
            dur_total = clip.duration
        voz = voz.subclip(0, min(dur_total, voz.duration))

    import re as _re
    sub_color = subs.get("color","#FFFFFF")
    sub_size = {"pequeno":48,"mediano":64,"grande":80}.get(subs.get("tamano","mediano"),64)
    sub_pos = {"arriba":0.15,"centro":0.5,"abajo":0.78}.get(subs.get("posicion","abajo"),0.78)
    sub_activo = subs.get("activo",True)

    # --- SUBTITULOS SINCRONIZADOS POR FRASE ---
    # 1) Cortar respetando frases reales: puntuacion (. ! ? :) y saltos de linea
    crudo = [s.strip() for s in _re.split(r'(?<=[\.\!\?\:])\s+|\n+', guion) if s.strip()]
    # 2) Trocear solo las frases largas (max ~7 palabras) SIN mezclar frases distintas
    segmentos = []
    for fr in crudo:
        pal = fr.split()
        if len(pal) <= 8:
            segmentos.append(fr)
        else:
            for i in range(0, len(pal), 7):
                segmentos.append(" ".join(pal[i:i+7]))
    if not segmentos:
        segmentos = [guion]
    # 3) Repartir el tiempo PROPORCIONAL a las palabras de cada frase (mejor sincronia)
    total_pal = sum(max(len(s.split()), 1) for s in segmentos)
    dur_voz = voz.duration
    txts = []
    if sub_activo:
        t_cursor = 0.0
        for s in segmentos:
            d = dur_voz * (max(len(s.split()), 1) / total_pal)
            txts.append(
                TextClip(s.upper(), fontsize=sub_size, color=sub_color,
                    font="/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
                    stroke_color="black", stroke_width=2, method="caption", size=(int(clip.w*0.8),None)
                ).set_start(t_cursor).set_duration(d).set_pos(("center", sub_pos), relative=True)
            )
            t_cursor += d

    # Mezclar musica de fondo si el cliente la subio
    import os as _os
    audio_final = voz
    if _os.path.exists("musica.mp3"):
        try:
            from moviepy.editor import CompositeAudioClip, AudioFileClip as _AC
            musica = _AC("musica.mp3").volumex(0.18)
            dur = voz.duration
            if musica.duration > dur:
                musica = musica.subclip(0, dur)
            elif musica.duration < dur:
                import math
                reps = math.ceil(dur / musica.duration)
                from moviepy.editor import concatenate_audioclips
                musica = concatenate_audioclips([_AC("musica.mp3").volumex(0.18) for _ in range(reps)]).subclip(0, dur)
            audio_final = CompositeAudioClip([voz.volumex(1.0), musica])
        except Exception as _em:
            log(f"Error mezcla musica: {_em}")
            audio_final = voz
    _vid = CompositeVideoClip([clip]+txts)
    try:
        _vd = getattr(_vid, "duration", None)
        _ad = getattr(audio_final, "duration", None)
        if _vd and _ad:
            if _ad > _vd + 0.05:
                # audio mas largo que el video -> recortar
                audio_final = audio_final.subclip(0, _vd)
                log(f"[Video] audio recortado a {_vd:.1f}s (era {_ad:.1f}s)")
            elif _vd > _ad:
                # video mas largo que el audio -> rellenar con silencio hasta el final
                from moviepy.editor import CompositeAudioClip as _CAC
                audio_final = _CAC([audio_final]).set_duration(_vd)
                log(f"[Video] audio rellenado con silencio a {_vd:.1f}s (era {_ad:.1f}s)")
            # alinear exacto para que ffmpeg nunca lea fuera de rango
            audio_final = audio_final.set_duration(_vd)
    except Exception as _ea:
        log(f"[Video] ajuste audio: {_ea}")
    final = _vid.set_audio(audio_final)
    try:
        if getattr(_vid, "duration", None):
            final = final.set_duration(_vid.duration)
    except Exception:
        pass
    import os as _os2
    for _f in ("preview.mp4", "preview_tmp.mp4"):
        if _os2.path.exists(_f):
            _os2.remove(_f)
    try:
        final.write_videofile("preview_tmp.mp4", fps=24, codec="libx264", preset="fast", logger=None, threads=4, audio_codec="aac", ffmpeg_params=["-pix_fmt", "yuv420p", "-movflags", "+faststart"])
    except Exception as _ew:
        log(f"[Video] write_videofile FALLO: {_ew}")
        raise
    if not _os2.path.exists("preview_tmp.mp4"):
        raise RuntimeError("write_videofile no genero preview_tmp.mp4 (revisa audio/duracion)")
    _os2.rename("preview_tmp.mp4", "preview.mp4")
    return "preview.mp4"

# ========== ENDPOINTS ==========
@app.post("/login")
async def ep_login(request: Request):
    d = await request.json()
    clave = d.get("clave","").strip()
    if verificar_clave(clave):
        return {"ok": True}
    return JSONResponse({"error":"Clave incorrecta"}, status_code=401)

@app.post("/generar-guion")
async def ep_guion(request: Request):
    d = await request.json()
    texto = d.get("texto","").strip()
    estilo = d.get("estilo","narrativo")
    duracion = int(d.get("duracion", 60) or 60)
    parte = d.get("parte","auto")
    # Si hay PDF completo cargado y el usuario no edito el texto a mano, usar el trozo elegido
    completo = ESTADO.get("texto_completo","")
    if completo and len(completo) > 6000:
        if parte == "principio":
            texto = completo[:6000]
        elif parte == "mitad":
            m = len(completo)//2
            texto = completo[m-3000:m+3000]
        elif parte == "final":
            texto = completo[-6000:]
        else:  # auto = trozo al azar
            import random as _r
            ini = _r.randint(0, max(0, len(completo)-6000))
            texto = completo[ini:ini+6000]
    if not texto:
        return JSONResponse({"error":"Pega tu contenido base primero"}, status_code=400)
    try:
        guion = generar_guion(texto, estilo, duracion)
        ESTADO["guion"] = guion
        return {"guion": guion}
    except Exception as e:
        return JSONResponse({"error": str(e)[:100]}, status_code=500)

@app.post("/subir-material")
async def ep_material(file: UploadFile = File(...)):
    try:
        import subprocess as _sp, os as _os
        ext = file.filename.split(".")[-1].lower()
        idx = len(ESTADO['archivos'])
        if ext in ("mp4","mov","webm","avi","mkv","m4v"):
            crudo = f"crudo_{idx}.{ext}"
            with open(crudo,"wb") as f:
                f.write(await file.read())
            nombre = f"media_{idx}.mp4"
            # Re-encodear a h264 estandar y fps fijo (arregla grabaciones de pantalla y formatos raros)
            r = _sp.run(["ffmpeg","-y","-i",crudo,"-r","30","-c:v","libx264","-preset","ultrafast","-pix_fmt","yuv420p","-an",nombre], capture_output=True)
            if _os.path.exists(nombre) and _os.path.getsize(nombre) > 1000:
                try: _os.remove(crudo)
                except: pass
            else:
                nombre = crudo
        else:
            nombre = f"media_{idx}.{ext}"
            with open(nombre,"wb") as f:
                f.write(await file.read())
        ESTADO["archivos"].append(nombre)
        return {"ok": True, "total": len(ESTADO["archivos"]), "nombre": nombre}
    except Exception as e:
        return JSONResponse({"error": str(e)[:100]}, status_code=500)

@app.post("/generar-voz")
async def ep_voz(request: Request):
    d = await request.json()
    guion = d.get("guion","").strip()
    if not guion:
        return JSONResponse({"error":"No hay guion"}, status_code=400)
    ESTADO["guion"] = guion
    try:
        await generar_voz(guion, d.get("idioma","es"), d.get("genero","masculina"), d.get("pais",""))
        ESTADO["voz_lista"] = True
        return {"ok": True}
    except Exception as e:
        return JSONResponse({"error": str(e)[:100]}, status_code=500)


@app.post("/subir-voz-grabada")
async def ep_voz_grabada(file: UploadFile = File(...)):
    try:
        import subprocess
        contenido = await file.read()
        with open("voz_grabada_raw","wb") as f:
            f.write(contenido)
        # Convertir a mp3 con ffmpeg (el navegador graba en webm/ogg)
        subprocess.run(["ffmpeg","-y","-i","voz_grabada_raw","-acodec","libmp3lame","voz.mp3"], capture_output=True)
        import os as _os
        if _os.path.exists("voz.mp3") and _os.path.getsize("voz.mp3") > 1000:
            ESTADO["voz_lista"] = True
            return {"ok": True}
        return JSONResponse({"error":"No se pudo procesar el audio"}, status_code=500)
    except Exception as e:
        return JSONResponse({"error": str(e)[:120]}, status_code=500)


@app.post("/subir-musica")
async def ep_musica(file: UploadFile = File(...)):
    try:
        import subprocess, os as _os
        contenido = await file.read()
        with open("musica_raw","wb") as f:
            f.write(contenido)
        subprocess.run(["ffmpeg","-y","-i","musica_raw","-acodec","libmp3lame","musica.mp3"], capture_output=True)
        if _os.path.exists("musica.mp3") and _os.path.getsize("musica.mp3") > 1000:
            ESTADO["musica"] = True
            return {"ok": True}
        return JSONResponse({"error":"No se pudo procesar la musica"}, status_code=500)
    except Exception as e:
        return JSONResponse({"error": str(e)[:120]}, status_code=500)

@app.post("/generar-musica-ia")
async def ep_musica_ia(request: Request):
    try:
        d = await request.json()
        nicho = d.get("nicho", "espiritual")
        duracion = int(d.get("duracion", 20))
        url_fabrica = os.environ.get("URL_FABRICA_MUSICA", "").rstrip("/")
        if not url_fabrica:
            return JSONResponse({"error": "Secret URL_FABRICA_MUSICA no configurado"}, status_code=500)
        PROMPTS = {
            "espiritual": "mystical ambient music, spiritual journey, ethereal choir, no lyrics",
            "numerologia": "meditative orchestral music, sacred geometry, soft piano and strings",
            "motivacional": "epic cinematic music, uplifting, orchestral, no vocals",
            "terror": "dark atmospheric tension, horror underscore, eerie strings",
            "naturaleza": "peaceful nature sounds, light acoustic guitar, calm",
            "default": "cinematic background music, neutral mood, no vocals",
        }
        prompt = next((v for k, v in PROMPTS.items() if k in nicho.lower()), PROMPTS["default"])
        from gradio_client import Client
        client = Client(url_fabrica)
        ruta = client.predict(prompt, duracion, api_name="/generar_musica")
        if isinstance(ruta, (list, tuple)) and ruta:
            ruta = ruta[0]
        if isinstance(ruta, dict):
            ruta = ruta.get("path") or ruta.get("name") or ""
        if not ruta or not os.path.exists(ruta):
            log(f"[Musica] sin fichero valido: {ruta}")
            return JSONResponse({"error": "La Fabrica no devolvio audio"}, status_code=500)
        with open(ruta, "rb") as fi, open("musica.mp3", "wb") as fo:
            fo.write(fi.read())
        ESTADO["musica"] = True
        log(f"[Musica] OK -> {ruta}")
        return {"ok": True}
    except Exception as e:
        log(f"[Musica] ERROR: {e}")
        return JSONResponse({"error": str(e)[:200]}, status_code=500)

@app.get("/musica-lista")
def ep_musica_lista():
    if os.path.exists("musica.mp3"):
        return {"listo": True, "mtime": os.path.getmtime("musica.mp3")}
    return {"listo": False, "mtime": 0}


@app.get("/audio")
def ep_audio():
    if os.path.exists("voz.mp3"):
        return FileResponse("voz.mp3", media_type="audio/mpeg")
    return JSONResponse({"error":"sin audio"}, status_code=404)

@app.post("/generar-video")
async def ep_video(request: Request):
    d = await request.json()
    guion = d.get("guion","").strip() or ESTADO["guion"]
    if not os.path.exists("voz.mp3"):
        return JSONResponse({"error":"Genera la voz primero"}, status_code=400)
    subs = {
        "color": d.get("sub_color","#FFFFFF"),
        "tamano": d.get("sub_tamano","mediano"),
        "posicion": d.get("sub_posicion","abajo"),
        "activo": d.get("sub_activo", True),
    }
    efecto = d.get("efecto","ninguno")
    escenas = d.get("escenas", [])
    # Modo híbrido: rellenar escenas vacías con clips de Veo
    if ESTADO["archivos"]:
        # Si hay archivos subidos, los asignamos a las escenas automáticas
        for idx, e in enumerate(escenas):
            mat = str(e.get("material", "")).strip()
            if not mat or mat == "automático" or mat == "automatico":
                # Usamos tus archivos de forma circular si hay menos que escenas
                e["material"] = ESTADO["archivos"][idx % len(ESTADO["archivos"])]
    if not ESTADO["archivos"]:
        from nichos import detectar_nicho
        nicho_detectado = detectar_nicho(guion)
        print(f"[Fenix] Nicho detectado: {nicho_detectado}", flush=True)
        for e in escenas:
            if not e.get("prompt","").strip():
                e["prompt"] = prompt_visual_auto(e.get("texto","") or e.get("narracion",""))
                print("[Fenix] Prompt auto generado", flush=True)
        for e in escenas:
            if e.get("prompt","").strip() and not e.get("prompt_manual","").strip():
                e["prompt_manual"] = e["prompt"].strip()
        motor = d.get("motor","auto")
        escenas = generar_clips_escenas(escenas, nicho=nicho_detectado, motor=motor)
    # Lista de (material, segundos) de cada escena, en orden
    # Pasar el prompt visual del usuario a cada escena para que los servicios lo usen
    for e in escenas:
        if e.get("prompt","").strip() and not e.get("prompt_manual","").strip():
            e["prompt_manual"] = e["prompt"].strip()
    escenas_data = [(e.get("material",""), int(e.get("segundos",5) or 5)) for e in escenas]
    material_escenas = [m for m,s in escenas_data if m]
    try:
        loop = asyncio.get_event_loop()
        await loop.run_in_executor(None, montar_video, guion, ESTADO["archivos"], subs, efecto, material_escenas, escenas_data)
        ESTADO["video_listo"] = True
        return {"ok": True}
    except Exception as e:
        import traceback
        tb = traceback.format_exc()
        print("ERROR VIDEO:", tb, flush=True)
        return JSONResponse({"error": str(e)[:300]}, status_code=500)


@app.get("/video-listo")
def ep_video_listo():
    import os as _os
    if _os.path.exists("preview.mp4") and _os.path.getsize("preview.mp4") > 5000:
        return {"listo": True, "mtime": _os.path.getmtime("preview.mp4")}
    return {"listo": False}

@app.get("/video")
def ep_video_file():
    if os.path.exists("preview.mp4"):
        return FileResponse("preview.mp4", media_type="video/mp4")
    return JSONResponse({"error":"sin video"}, status_code=404)

@app.post("/reset")
def ep_reset():
    for f in glob.glob("media_*")+glob.glob("fondo*")+glob.glob("leonardo_*")+["voz.mp3","preview.mp4","musica.mp3","musica_raw"]:
        try: os.remove(f)
        except: pass
    ESTADO["guion"]=""; ESTADO["archivos"]=[]; ESTADO["voz_lista"]=False; ESTADO["video_listo"]=False
    return {"ok": True}

@app.post("/subir-pdf")
async def ep_pdf(file: UploadFile = File(...)):
    try:
        contenido = await file.read()
        with open("temp.pdf","wb") as f:
            f.write(contenido)
        from pypdf import PdfReader
        reader = PdfReader("temp.pdf")
        texto = ""
        for pagina in reader.pages:
            texto += (pagina.extract_text() or "") + "\n"
        texto = texto.strip()
        if not texto:
            return JSONResponse({"error":"El PDF no tiene texto extraible (puede ser escaneado)"}, status_code=400)
        ESTADO["texto_completo"] = texto
        # Mostrar preview de los primeros 6000 al usuario
        return {"ok": True, "texto": texto[:6000], "caracteres": len(texto)}
    except Exception as e:
        return JSONResponse({"error": str(e)[:120]}, status_code=500)

# ========== INTERFAZ ==========
@app.get("/", response_class=HTMLResponse)
def home():
    return """<!DOCTYPE html>
<html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Fenix Hybrid Engine</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0a0a0a;color:#fff;font-family:system-ui,sans-serif;padding:20px;max-width:780px;margin:0 auto;line-height:1.5}
h1{font-size:1.8rem;background:linear-gradient(90deg,#ff6b00,#ffb700);-webkit-background-clip:text;-webkit-text-fill-color:transparent;margin-bottom:4px}
.sub{color:#888;margin-bottom:24px;font-size:.95rem}
.fase{background:#111;border:1px solid #222;border-radius:14px;padding:20px;margin-bottom:16px}
.fase-t{font-size:.8rem;color:#ff8c00;font-weight:700;text-transform:uppercase;letter-spacing:1px;margin-bottom:12px}
textarea,select,input{width:100%;background:#0a0a0a;color:#fff;border:1px solid #333;border-radius:8px;padding:12px;font-size:.95rem;font-family:inherit;margin-bottom:10px}
textarea{min-height:90px;resize:vertical}
button{background:linear-gradient(90deg,#ff6b00,#ffb700);color:#000;border:none;padding:14px 20px;border-radius:8px;font-weight:800;font-size:1rem;cursor:pointer;width:100%;margin-top:6px}
button:disabled{opacity:.4}
.btn2{background:#222;color:#fff;border:1px solid #444}
.msg{font-size:.85rem;margin-top:8px;min-height:18px}
audio,video{width:100%;margin-top:10px;border-radius:8px}
.lbl{font-size:.85rem;color:#aaa;margin-bottom:6px;display:block}
.row{display:flex;gap:8px}.row>*{flex:1}
.tag{display:inline-block;background:#1a1a1a;color:#ff8c00;padding:2px 10px;border-radius:20px;font-size:.75rem;margin-left:6px}

.spinner{display:inline-block;width:24px;height:24px;border:3px solid #333;border-top:3px solid #ffb700;border-radius:50%;animation:spin 1s linear infinite;vertical-align:middle;margin-right:8px}
@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}
.tick{display:inline-block;width:24px;height:24px;background:#00c853;border-radius:50%;color:#fff;text-align:center;line-height:24px;font-weight:900;margin-right:8px;vertical-align:middle}
</style></head><body>
<div id="loginOverlay" style="position:fixed;inset:0;background:#0a0a0a;z-index:9999;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:20px">
  <div style="font-size:2rem;font-weight:800;background:linear-gradient(90deg,#ff6b00,#ffb700);-webkit-background-clip:text;-webkit-text-fill-color:transparent;margin-bottom:8px">Fenix Hybrid Engine</div>
  <p style="color:#888;margin-bottom:24px;font-size:.95rem">Introduce tu clave de acceso</p>
  <input type="password" id="claveInput" placeholder="Clave de acceso" style="width:100%;max-width:300px;background:#111;color:#fff;border:1px solid #333;border-radius:10px;padding:14px;font-size:1rem;margin-bottom:12px" onkeydown="if(event.key==='Enter')hacerLogin()">
  <button onclick="hacerLogin()" style="width:100%;max-width:300px;background:linear-gradient(135deg,#ff6b00,#ff3d00);color:#fff;border:none;padding:14px;border-radius:10px;font-weight:800;font-size:1rem;cursor:pointer">Entrar</button>
  <div id="loginMsg" style="color:#ff5252;margin-top:12px;font-size:.9rem;min-height:18px"></div>
</div>
<script>
async function hacerLogin(){
  var clave=document.getElementById("claveInput").value;
  var msg=document.getElementById("loginMsg");
  msg.textContent="Comprobando...";msg.style.color="#ffb700";
  try{
    var r=await fetch("/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clave:clave})});
    var d=await r.json();
    if(d.ok){document.getElementById("loginOverlay").style.display="none";}
    else{msg.textContent="Clave incorrecta";msg.style.color="#ff5252";}
  }catch(e){msg.textContent="Error";msg.style.color="#ff5252";}
}
</script>

<h1>Fenix Hybrid Engine</h1>
<div class="sub">Motor de produccion asistida. La IA acelera, tu tienes el control.</div>
<button onclick="var p=document.getElementById('panelAyuda');p.style.display=(p.style.display=='none'||!p.style.display)?'block':'none';" style="background:#ff6b00;color:#fff;border:none;padding:10px 18px;border-radius:8px;font-weight:700;cursor:pointer;margin:10px 0">Como usar (pulsa aqui)</button>
<div id="panelAyuda" style="display:none;background:#1a1a1a;border:1px solid #ff6b00;border-radius:10px;padding:16px;margin:10px 0;line-height:1.6">
<b>COMO HACER TU VIDEO (paso a paso):</b><br><br>
<b>1.</b> Sube un PDF o pega tu texto.<br>
<b>2.</b> Elige la duracion (15s, 30s, 45s, 1 o 2 min) y el estilo. Pulsa Generar Guion.<br>
<b>3.</b> Si quieres, edita el guion a tu gusto.<br>
<b>4.</b> Pulsa Dividir en escenas.<br>
<b>5.</b> Sube tus imagenes o videos.<br>
<b>6.</b> Genera la voz. Los segundos de cada escena se ponen SOLOS segun la voz, y abajo veras el total.<br>
<b>7.</b> Elige color de subtitulos y efecto si quieres.<br>
<b>8.</b> Pulsa Generar Video y descargalo. Sale perfecto, sin pantalla negra.<br><br>
<b>DOS MODOS DE MONTAR:</b><br>
- <b>AUTOMATICO (facil):</b> deja el material en automatico. El sistema reparte las imagenes solo. Ideal para ir rapido.<br>
- <b>MANUAL (control total):</b> asigna una imagen a cada escena. Tu decides que imagen va en cada parte.<br><br>
<b>CONSEJO IMPORTANTE:</b> los segundos salen solos al generar la voz, no tienes que calcular nada. Si quieres que una escena dure mas o menos, NO toques los segundos: edita su TEXTO (hazlo mas largo o mas corto) y vuelve a generar la voz. Los segundos se ajustan solos. Asi es mas facil y siempre cuadra.<br>
</div>

<div class="fase">
  <div class="fase-t">1. Ingesta de conocimiento</div>
  <span class="lbl">Sube un PDF (extrae el texto solo) o pega tu contenido:</span>
  <input type="file" id="pdf" accept=".pdf" onchange="subirPdf()">
  <div class="msg" id="msgPdf"></div>
  <textarea id="texto" placeholder="Pega aqui tu base de conocimiento, o sube un PDF arriba..."></textarea>
  <span class="lbl">Duracion del video:</span>
  <select id="duracion">
    <option value="15">15 segundos</option>
    <option value="30">30 segundos</option>
    <option value="45">45 segundos</option>
    <option value="60">1 minuto</option>
    <option value="120">2 minutos</option>
  </select>
  <span class="lbl">Estilo de narrativa:</span>
  <select id="estilo">
  <label style="display:block;margin:10px 0 4px">Motor de video:</label>
    <option value="narrativo">Narrativo y emocional</option>
    <option value="educativo">Educativo y claro</option>
    <option value="motivador">Motivador e inspirador</option>
    <option value="publicitario">Publicitario y persuasivo</option>
    <option value="misterio">Misterio e intriga</option>
  </select>
  <span class="lbl">Motor de video:</span>
  <select id="motorVideo">
    <option value="auto">Automatico (LTX - Veo - Leonardo)</option>
    <option value="ltx">Solo LTX (gratis, mi GPU)</option>
    <option value="veo">Solo Veo (Google, calidad alta)</option>
    <option value="leonardo">Solo Leonardo</option>
  </select>
  
  <span class="lbl">Que parte del documento usar (si subiste PDF largo):</span>
  <select id="parte">
    <option value="auto">Automatico (trozos al azar, mas variedad)</option>
    <option value="principio">Principio del documento</option>
    <option value="mitad">Mitad del documento</option>
    <option value="final">Final del documento</option>
  </select>
  <button onclick="genGuion()">Generar Propuesta de Guion</button>
  <div class="msg" id="msgGuion"></div>
</div>

<div class="fase">
  <div class="fase-t">2. Edicion del guion <span class="tag">control humano</span></div>
  <span class="lbl">Edita el guion a tu gusto antes de continuar:</span>
  <textarea id="guion" placeholder="Aqui aparecera el guion generado, editable..."></textarea>
  <button onclick="dividirEscenas()" style="background:#1565c0;color:#fff;border:none;padding:10px;border-radius:8px;margin-top:8px;width:100%;font-weight:600">Dividir en escenas</button>
  <div id="escenas" style="margin-top:12px"></div>
</div>

<div class="fase">
  <div class="fase-t">3. Tu material</div>
  <span class="lbl">Sube tus imagenes o videos (uno a uno):</span>
  <input type="file" id="material" accept="image/*,video/*" multiple onchange="subirMaterial()">
  <div class="msg" id="msgMaterial">Sin material aun (usara fondos automaticos)</div>
</div>

<div class="fase">
  <div class="fase-t">4. Voz</div>
  <select id="tipoVoz" onchange="cambioVoz()">
    <option value="ia">Voz IA (automatica)</option>
    <option value="grabada">Mi voz grabada (con microfono)</option>
  </select>
  <div id="vozIA">
    <div class="row">
      <select id="genero"><option value="masculina">Voz masculina</option><option value="femenina">Voz femenina</option></select>
      <select id="pais"><option value="">Acento neutro</option><option value="españa">Espana</option><option value="mexico">Mexico</option><option value="argentina">Argentina</option><option value="colombia">Colombia</option></select>
    </div>
    <button class="btn2" onclick="genVoz()">Generar y Pre-escuchar Voz</button>
  </div>
  <div id="vozGrabada" style="display:none">
    <p style="color:#aaa;font-size:.85rem;margin-bottom:8px">Lee el guion de arriba en voz alta y grabate:</p>
    <button class="btn2" id="btnRec" onclick="toggleRec()">Empezar a grabar</button>
  </div>
  <div class="msg" id="msgVoz"></div>
  <audio id="player" controls style="display:none"></audio>
  <div style="margin-top:14px;padding-top:14px;border-top:1px solid #222">
    <span class="lbl">Musica de fondo:</span>
    <div style="display:flex;gap:10px;margin-bottom:10px;flex-wrap:wrap">
      <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:10px 14px;background:#1a1a1a;border-radius:8px;border:2px solid #333;flex:1" onclick="setModoMusica(\'no\')">
        <input type="radio" name="modoMusica" value="no" checked style="width:auto;margin:0"> <span>Sin musica</span>
      </label>
      <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:10px 14px;background:#1a1a1a;border-radius:8px;border:2px solid #333;flex:1" onclick="setModoMusica(\'ia\')">
        <input type="radio" name="modoMusica" value="ia" style="width:auto;margin:0"> <span>🎵 Musica IA</span>
      </label>
      <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:10px 14px;background:#1a1a1a;border-radius:8px;border:2px solid #333;flex:1" onclick="setModoMusica(\'subir\')">
        <input type="radio" name="modoMusica" value="subir" style="width:auto;margin:0"> <span>📁 Subir mi musica</span>
      </label>
    </div>
    <div id="panelMusicaIA" style="display:none">
      <select id="nichoMusica" style="margin-bottom:8px">
        <option value="espiritual">Espiritual / Meditacion</option>
        <option value="motivacional">Motivacional / Epico</option>
        <option value="numerologia">Numerologia / Mistico</option>
        <option value="terror">Tension / Terror</option>
        <option value="naturaleza">Naturaleza / Calma</option>
      </select>
      <button class="btn2" onclick="generarMusicaIA()">🎼 Generar Musica con IA</button>
    </div>
    <div id="panelMusicaSubir" style="display:none">
      <input type="file" id="musica" accept="audio/*" onchange="subirMusica()">
    </div>
    <div class="msg" id="msgMusica"></div>
  </div>
</div>

<div class="fase">
  <div class="fase-t">5. Subtitulos y Montaje</div>
  <div class="row">
    <select id="subActivo"><option value="si">Con subtitulos</option><option value="no">Sin subtitulos</option></select>
    <select id="subTamano"><option value="pequeno">Pequenos</option><option value="mediano" selected>Medianos</option><option value="grande">Grandes</option></select>
  </div>
  <div class="row">
    <select id="subPosicion"><option value="arriba">Arriba</option><option value="centro">Centro</option><option value="abajo" selected>Abajo</option></select>
    <select id="subColor"><option value="#FFFFFF">Blanco</option><option value="#C0C0C0">Plata</option><option value="#000000">Negro</option><option value="#FFD700">Dorado</option><option value="#FFFF00">Amarillo</option><option value="#FFA500">Naranja</option><option value="#FF0000">Rojo</option><option value="#FF4081">Rosa</option><option value="#FF00FF">Magenta</option><option value="#00E5FF">Cian</option><option value="#00BFFF">Azul cielo</option><option value="#1565C0">Azul</option><option value="#76FF03">Verde lima</option><option value="#00C853">Verde</option><option value="#9C27B0">Morado</option><option value="#FF6B00">Naranja fuego</option></select>
  </div>
  <span class="lbl">Efecto de video:</span>
  <select id="efecto">
    <option value="ninguno">Sin efecto (estatico)</option>
    <option value="zoom">Zoom lento (Ken Burns)</option>
    <option value="fundido">Fundido suave entre planos</option>
    <option value="zoom_fundido">Zoom + Fundido (cinematografico)</option>
    <option value="rafaga">Rafaga rapida (videoclip)</option>
  </select>
  <button onclick="genVideo()">Generar Vista Previa del Video</button>
  <button class="btn2" onclick="cargarVideo()" style="margin-top:8px">Cargar Video (cuando termine)</button>
  <div class="msg" id="msgVideo"></div>
  <video id="vid" controls playsinline webkit-playsinline preload="metadata" style="display:none"></video>
</div>

<div class="fase">
  <div class="fase-t">6. Publicacion</div>
  <button onclick="descargar()" style="background:linear-gradient(90deg,#00c853,#64dd17)">Descargar Video</button>
  <button onclick="nuevoVideo()" style="background:#222;color:#fff;border:1px solid #444;margin-top:8px">Nuevo Video (limpiar todo)</button>
  <button class="btn2" onclick="subirYt()" style="margin-top:8px">Conectar YouTube y Subir</button>
  <div class="msg" id="msgPub"></div>
</div>

<script>
var ARCHIVOS_SUBIDOS=[];
async function subirPdf(){
  var f=document.getElementById("pdf").files[0]; if(!f)return;
  var m=document.getElementById("msgPdf"); m.textContent="Extrayendo texto...";m.style.color="#ffb700";
  var fd=new FormData(); fd.append("file",f);
  var r=await fetch("/subir-pdf",{method:"POST",body:fd}); var d=await r.json();
  if(d.ok){document.getElementById("texto").value=d.texto;m.textContent="PDF leido: "+d.caracteres+" caracteres";m.style.color="#00c853";}
  else{m.textContent=d.error;m.style.color="#ff5252";}
}
async function genGuion(){
  var m=document.getElementById("msgGuion");m.textContent="Generando...";m.style.color="#ffb700";
  var r=await fetch("/generar-guion",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({texto:document.getElementById("texto").value,estilo:document.getElementById("estilo").value,parte:document.getElementById("parte").value,duracion:document.getElementById("duracion").value})});
  var d=await r.json();
  if(d.guion){document.getElementById("guion").value=d.guion;m.textContent="Guion listo. Editalo abajo si quieres.";m.style.color="#00c853";}
  else{m.textContent=d.error;m.style.color="#ff5252";}
}
async function subirMaterial(){
  var files=document.getElementById("material").files; if(!files.length)return;
  var m=document.getElementById("msgMaterial");
  var total=0;
  for(var i=0;i<files.length;i++){
    m.textContent="Subiendo "+(i+1)+" de "+files.length+"...";m.style.color="#ffb700";
    var fd=new FormData(); fd.append("file",files[i]);
    var r=await fetch("/subir-material",{method:"POST",body:fd}); var d=await r.json();
    if(d.ok){total=d.total; if(d.nombre){ARCHIVOS_SUBIDOS.push(d.nombre);}}
  }
  m.textContent=total+" archivo(s) subido(s) en total";m.style.color="#00c853";
}
async function genVoz(){
  var m=document.getElementById("msgVoz");m.textContent="Generando voz...";m.style.color="#ffb700";
  var guionFinal=document.getElementById("guion").value;
  var esc=recolectarEscenas();
  if(esc.length>0){
    var textos=[];
    for(var k=0;k<esc.length;k++){ if(esc[k].texto){textos.push(esc[k].texto);} }
    if(textos.length>0){guionFinal=textos.join(". ");}
  }
  var r=await fetch("/generar-voz",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({guion:guionFinal,genero:document.getElementById("genero").value,pais:document.getElementById("pais").value})});
  var d=await r.json();
  if(d.ok){var p=document.getElementById("player");p.src="/audio?t="+Date.now();p.style.display="block";m.textContent="Voz lista, escuchala:";m.style.color="#00c853";
    p.onloadedmetadata=function(){ sugerirSegundos(p.duration); };
  }
  else{m.textContent=d.error;m.style.color="#ff5252";}
}
function sugerirSegundos(durVoz){
  if(!durVoz||durVoz<1){return;}
  var items=document.getElementsByClassName("escenaItem");
  if(items.length==0){return;}
  // Contar palabras de cada escena y el total
  var palabrasEsc=[]; var total=0;
  for(var i=0;i<items.length;i++){
    var t=items[i].getElementsByClassName("txtEscena")[0];
    var np=t?t.value.trim().split(" ").filter(function(x){return x.length>0;}).length:1;
    palabrasEsc.push(np); total+=np;
  }
  // Repartir la duracion de la voz segun palabras y rellenar
  var sumaSeg=0;
  for(var i=0;i<items.length;i++){
    var seg=Math.max(1, Math.round(durVoz*(palabrasEsc[i]/total)));

    sumaSeg+=seg;
    var campo=items[i].getElementsByClassName("segEscena")[0];
    if(campo){campo.value=seg;}
  }
  // Mostrar total abajo
  var tot=document.getElementById("totalSeg");
  if(!tot){
    tot=document.createElement("div");
    tot.id="totalSeg";
    tot.style.cssText="background:#1565c0;color:#fff;padding:10px;border-radius:8px;margin-top:10px;font-weight:700;text-align:center";
    var cont=document.getElementById("escenas");
    if(cont){cont.appendChild(tot);}
  }
  tot.textContent="Total del video: "+sumaSeg+" segundos (voz: "+Math.round(durVoz)+"s). Ajusta si quieres.";
}
var pollTimer=null;
function recolectarEscenas(){
  var items=document.getElementsByClassName("escenaItem");
  var lista=[];
  for(var i=0;i<items.length;i++){
    var sel=items[i].getElementsByClassName("selMaterial")[0];
    var mat=sel?sel.value:"";
    var seg=items[i].getElementsByClassName("segEscena")[0];
    var segs=seg?parseInt(seg.value):5;
    if(!segs||segs<1){segs=5;}
    var txt=items[i].getElementsByClassName("txtEscena")[0];
    var texto=txt?txt.value:"";
    var prEl=items[i].getElementsByClassName("promptEscena")[0];
    var prompt_escena=prEl?prEl.value:"";
    lista.push({material:mat,segundos:segs,texto:texto,prompt:prompt_escena});
  }
  return lista;
}
async function genVideo(){
  var m=document.getElementById("msgVideo");
  m.innerHTML="<span class=\'spinner\'></span> Montando video...";m.style.color="#ffb700";
  // Ocultar y vaciar el reproductor viejo: evita dar a play sobre un preview ya borrado
  var _vold=document.getElementById("vid"); if(_vold){ _vold.pause(); _vold.removeAttribute("src"); _vold.load(); _vold.style.display="none"; }
  // Lanzar el render sin esperar la respuesta (evita timeout)
  fetch("/generar-video",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({
    guion:document.getElementById("guion").value,
    sub_activo:document.getElementById("subActivo").value==="si",
    sub_tamano:document.getElementById("subTamano").value,
    sub_posicion:document.getElementById("subPosicion").value,
    sub_color:document.getElementById("subColor").value,
    efecto:document.getElementById("efecto").value,
    motor:document.getElementById("motorVideo").value,
    escenas:recolectarEscenas()
  })}).catch(e=>{});
  // Comprobar cada 4 segundos si el video esta listo
  var inicio=Date.now();
  if(pollTimer)clearInterval(pollTimer);
  pollTimer=setInterval(async()=>{
    try{
      var r=await fetch("/video-listo?t="+Date.now());var d=await r.json();
      if(d.listo && d.mtime*1000 > inicio){
        clearInterval(pollTimer);
        var u="/video?t="+Date.now();
        var v=document.getElementById("vid");v.src=u;v.style.display="block";v.load();
        m.innerHTML="<span class=\'tick\'>✓</span> Video listo! <a href=\'"+u+"\' target=\'_blank\' style=\'display:inline-block;background:#00E5FF;color:#000;padding:10px 18px;border-radius:8px;text-decoration:none;font-weight:800;margin-top:8px\'>▶ VER VIDEO</a>";
        m.style.color="#00c853";
      }
    }catch(e){}
  },4000);
}
async function subirMusica(){
  var f=document.getElementById("musica").files[0]; if(!f)return;
  var m=document.getElementById("msgMusica");m.textContent="Subiendo musica...";m.style.color="#ffb700";
  var fd=new FormData(); fd.append("file",f);
  var r=await fetch("/subir-musica",{method:"POST",body:fd}); var d=await r.json();
  if(d.ok){m.textContent="✅ Musica anadida, sonara de fondo";m.style.color="#00c853";}
  else{m.textContent="❌ "+(d.error||"Error");m.style.color="#ff5252";}
}
function cargarVideo(){
  var u="/video?t="+Date.now();
  var v=document.getElementById("vid");v.src=u;v.style.display="block";v.load();
  var m=document.getElementById("msgVideo");
  m.innerHTML="▶ <a href=\'"+u+"\' target=\'_blank\' style=\'color:#00E5FF;font-weight:800\'>VER VIDEO EN PANTALLA COMPLETA</a>";
  m.style.color="#00c853";
}
async function nuevoVideo(){
  if(!confirm("Esto borra el material, la voz y el video actual para empezar de cero. Continuar?"))return;
  try{
    await fetch("/reset",{method:"POST"});
    location.reload();
  }catch(e){alert("Error al limpiar");}
}
function setModoMusica(modo){
  document.getElementById("panelMusicaIA").style.display=modo==="ia"?"block":"none";
  document.getElementById("panelMusicaSubir").style.display=modo==="subir"?"block":"none";
}
async function generarMusicaIA(){
  var m=document.getElementById("msgMusica");
  m.innerHTML="<span class='spinner'></span> Generando musica con IA (puede tardar 1-2 min)...";m.style.color="#ffb700";
  var nicho=document.getElementById("nichoMusica").value;
  var dur=parseInt(document.getElementById("duracion").value||"20")+5;
  var inicioMus=Date.now();
  fetch("/generar-musica-ia",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({nicho:nicho,duracion:dur})}).catch(function(e){});
  if(window.musicaTimer)clearInterval(window.musicaTimer);
  window.musicaTimer=setInterval(async()=>{
    try{
      var r=await fetch("/musica-lista?t="+Date.now());var d=await r.json();
      if(d.listo && d.mtime*1000 > inicioMus){
        clearInterval(window.musicaTimer);
        m.textContent="✅ Musica IA lista, sonara de fondo";m.style.color="#00c853";
      }
    }catch(e){}
  },4000);
}
function descargar(){var a=document.createElement("a");a.href="/video?t="+Date.now();a.download="video_fenix.mp4";a.click();}
function dividirEscenas(){
  var t=document.getElementById("guion").value;
  var sep=String.fromCharCode(10)+String.fromCharCode(10);
  var bloques=t.split(sep);
  var cont=document.getElementById("escenas");
  var html="";
  var n=0;
  for(var i=0;i<bloques.length;i++){
    var b=bloques[i].trim();
    if(b==""){continue;}
    n++;
    var opciones="<option value=>-- material automatico --</option>";
    for(var j=0;j<ARCHIVOS_SUBIDOS.length;j++){ opciones+="<option value="+ARCHIVOS_SUBIDOS[j]+">"+ARCHIVOS_SUBIDOS[j]+"</option>"; }
    html+="<div class=escenaItem style='background:#111;border:1px solid #222;border-radius:10px;padding:12px;margin-bottom:10px'><b>Escena "+n+"</b><br><textarea class=txtEscena style='width:100%;min-height:50px;background:#0a0a0a;color:#fff;border:1px solid #333;border-radius:6px;padding:6px;margin-bottom:6px'>"+b+"</textarea><select class=selMaterial style='width:100%;margin-bottom:6px'>"+opciones+"</select><div style='display:flex;align-items:center;gap:8px;margin-bottom:6px'><input type=number class=segEscena min=1 value=5 style='width:70px;background:#0a0a0a;color:#fff;border:1px solid #333;border-radius:6px;padding:6px'> <span style='color:#aaa;font-size:.85rem'>seg</span></div><textarea class=promptEscena placeholder='Prompt visual para esta escena (opcional)...' style='width:100%;min-height:40px;background:#0a0a0a;color:#fff;border:1px solid #ff6b00;border-radius:6px;padding:6px;font-size:.85rem'></textarea></div>";
  }
  if(n==0){html="<div style=color:#888>Separa los parrafos con una linea en blanco</div>";}
  cont.innerHTML=html;
}
async function subirYt(){var m=document.getElementById("msgPub");m.textContent="Conecta tu canal de YouTube para activar la subida automatica";m.style.color="#ffb700";}

function cambioVoz(){
  var t=document.getElementById("tipoVoz").value;
  document.getElementById("vozIA").style.display=t==="ia"?"block":"none";
  document.getElementById("vozGrabada").style.display=t==="grabada"?"block":"none";
}
var mediaRec=null, chunks=[], grabando=false;
async function toggleRec(){
  var btn=document.getElementById("btnRec"); var m=document.getElementById("msgVoz");
  if(!grabando){
    try{
      var stream=await navigator.mediaDevices.getUserMedia({audio:true});
      mediaRec=new MediaRecorder(stream); chunks=[];
      mediaRec.ondataavailable=e=>chunks.push(e.data);
      mediaRec.onstop=async()=>{
        var blob=new Blob(chunks,{type:"audio/webm"});
        m.textContent="Subiendo tu voz...";m.style.color="#ffb700";
        var fd=new FormData(); fd.append("file",blob,"voz.webm");
        var r=await fetch("/subir-voz-grabada",{method:"POST",body:fd}); var d=await r.json();
        if(d.ok){var p=document.getElementById("player");p.src="/audio?t="+Date.now();p.style.display="block";m.textContent="✅ Tu voz lista, escuchala:";m.style.color="#00c853";}
        else{m.textContent="❌ "+(d.error||"Error");m.style.color="#ff5252";}
      };
      mediaRec.start(); grabando=true;
      btn.textContent="⏹ Detener grabacion"; btn.style.background="#ff4444";
      m.textContent="Grabando... lee el guion";m.style.color="#ff4444";
    }catch(e){m.textContent="❌ No se pudo acceder al microfono";m.style.color="#ff5252";}
  }else{
    mediaRec.stop(); grabando=false;
    btn.textContent="Empezar a grabar"; btn.style.background="";
  }
}
</script>
</body></html>"""