Tu Nombre commited on
Commit
cd27d2e
·
1 Parent(s): fcebd65

añadir muchos mas colores a subtitulos

Browse files
Files changed (2) hide show
  1. app.py +1 -1
  2. app_backup_antes_colores_sub_1032.py +807 -0
app.py CHANGED
@@ -585,7 +585,7 @@ async function hacerLogin(){
585
  </div>
586
  <div class="row">
587
  <select id="subPosicion"><option value="arriba">Arriba</option><option value="centro">Centro</option><option value="abajo" selected>Abajo</option></select>
588
- <select id="subColor"><option value="#FFFFFF">Blanco</option><option value="#FFD700">Dorado</option><option value="#FFFF00">Amarillo</option><option value="#00E5FF">Cian</option><option value="#FF4081">Rosa</option><option value="#76FF03">Verde</option></select>
589
  </div>
590
  <span class="lbl">Efecto de video:</span>
591
  <select id="efecto">
 
585
  </div>
586
  <div class="row">
587
  <select id="subPosicion"><option value="arriba">Arriba</option><option value="centro">Centro</option><option value="abajo" selected>Abajo</option></select>
588
+ <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>
589
  </div>
590
  <span class="lbl">Efecto de video:</span>
591
  <select id="efecto">
app_backup_antes_colores_sub_1032.py ADDED
@@ -0,0 +1,807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, time, json, glob, random, asyncio, base64
2
+ from fastapi import FastAPI, Request, UploadFile, File
3
+ from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
4
+ from groq import Groq
5
+ import edge_tts, requests
6
+
7
+ app = FastAPI()
8
+
9
+ 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]
10
+
11
+ CLAVE_ACCESO = os.environ.get("CLAVE_ACCESO", "demo2026")
12
+
13
+ def verificar_clave(clave):
14
+ return clave == CLAVE_ACCESO
15
+
16
+ PEXELS_KEY = os.environ.get("PEXELS_KEY","")
17
+
18
+ # Estado de la sesion (guarda guion editado y material entre pasos)
19
+ ESTADO = {
20
+ "guion": "",
21
+ "archivos": [],
22
+ "voz_lista": False,
23
+ "video_listo": False,
24
+ }
25
+
26
+ ESTILOS = {
27
+ "narrativo": "narrativo y emocional, como contando una historia",
28
+ "educativo": "educativo y claro, explicando con autoridad",
29
+ "motivador": "motivador e inspirador, que mueva a la accion",
30
+ "publicitario": "publicitario y persuasivo, vendiendo sin parecer venta",
31
+ "misterio": "intrigante y de misterio, con ganchos de curiosidad",
32
+ }
33
+
34
+ VOCES = {
35
+ "es": {
36
+ "masculina": ["es-ES-AlvaroNeural","es-MX-JorgeNeural","es-AR-TomasNeural","es-CO-GonzaloNeural"],
37
+ "femenina": ["es-ES-ElviraNeural","es-MX-DaliaNeural","es-AR-ElenaNeural","es-CO-SalomeNeural"],
38
+ },
39
+ "en": {"masculina":["en-US-GuyNeural","en-GB-RyanNeural"],"femenina":["en-US-JennyNeural","en-GB-SoniaNeural"]},
40
+ }
41
+
42
+ def log(m): print(m, flush=True)
43
+
44
+ # ========== GUION ==========
45
+ def generar_guion(texto_base, estilo, duracion=60):
46
+ estilo_desc = ESTILOS.get(estilo, ESTILOS["narrativo"])
47
+ palabras = int(duracion * 2.4)
48
+ last_err = None
49
+ MODELOS = ["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "openai/gpt-oss-120b", "openai/gpt-oss-20b"]
50
+ 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."
51
+ # Probar cada modelo con cada key hasta que uno funcione
52
+ for modelo in MODELOS:
53
+ for k in GROQ_KEYS:
54
+ try:
55
+ client = Groq(api_key=k)
56
+ res = client.chat.completions.create(
57
+ messages=[{"role":"user","content":prompt}],
58
+ model=modelo, temperature=0.85
59
+ )
60
+ return res.choices[0].message.content.strip()
61
+ except Exception as e:
62
+ last_err = e
63
+ if "rate_limit" in str(e).lower() or "429" in str(e): continue
64
+ if "model" in str(e).lower() or "decommission" in str(e).lower(): break
65
+ continue
66
+ raise last_err if last_err else Exception("Sin keys Groq")
67
+
68
+ # ========== VOZ ==========
69
+ async def generar_voz(guion, idioma="es", genero="masculina", pais=""):
70
+ voces = VOCES.get(idioma, VOCES["es"]).get(genero, ["es-ES-AlvaroNeural"])
71
+ if pais:
72
+ cods = {"españa":"ES","mexico":"MX","argentina":"AR","colombia":"CO","usa":"US","uk":"GB","australia":"AU"}
73
+ cod = cods.get(pais.lower(),"")
74
+ if cod:
75
+ filt = [v for v in voces if f"-{cod}-" in v]
76
+ if filt: voces = filt
77
+ voz_sel = random.choice(voces)
78
+ await edge_tts.Communicate(guion, voz_sel).save("voz.mp3")
79
+ return voz_sel
80
+
81
+ # ========== VIDEO ==========
82
+ def montar_video(guion, archivos, subs=None, efecto="ninguno", material_escenas=None, escenas_data=None):
83
+ subs = subs or {}
84
+ material_escenas = material_escenas or []
85
+ escenas_data = escenas_data or []
86
+ from moviepy.editor import AudioFileClip as AC, VideoFileClip as VC, ImageClip as IC, TextClip, CompositeVideoClip, concatenate_videoclips
87
+ from PIL import Image as PILImage, ImageFilter as PIF, ImageFile
88
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
89
+
90
+ voz = AC("voz.mp3")
91
+ # Si el usuario asigno material por escena, usar ESE orden; si no, los archivos normales
92
+ if material_escenas:
93
+ fondos = [m for m in material_escenas if os.path.exists(m)]
94
+ else:
95
+ fondos = []
96
+ # Respaldo: si no hay fondos de escenas validos, usar el material general
97
+ if not fondos:
98
+ fondos = archivos[:8] if archivos else []
99
+
100
+ # Si no hay material propio, fondo de Pexels
101
+ if not fondos:
102
+ try:
103
+ h = {"Authorization": PEXELS_KEY}
104
+ r = requests.get("https://api.pexels.com/videos/search?query=abstract&per_page=8", headers=h)
105
+ for i, v in enumerate(r.json().get("videos", [])[:6]):
106
+ u = v["video_files"][0]["link"]
107
+ with open(f"fondo{i}.mp4","wb") as f: f.write(requests.get(u, timeout=30).content)
108
+ fondos.append(f"fondo{i}.mp4")
109
+ except Exception as e:
110
+ log(f"Error pexels: {e}")
111
+
112
+ # Duracion: si hay escenas con segundos definidos, usar la SUMA; si no, la voz
113
+ if escenas_data:
114
+ suma_seg = sum(s for m,s in escenas_data)
115
+ dur_total = min(suma_seg, 1200) if suma_seg > 0 else min(voz.duration, 1200)
116
+ else:
117
+ dur_total = min(voz.duration, 1200)
118
+
119
+ # Si el material son SOLO videos, usar el video entero de fondo (no trocear)
120
+ solo_videos = fondos and all(str(f).lower().endswith((".mp4",".mov",".webm",".avi",".mkv")) for f in fondos)
121
+ if solo_videos:
122
+ from moviepy.editor import concatenate_videoclips as _ccv
123
+ vclips = []
124
+ for fp in fondos:
125
+ try:
126
+ vc = VC(fp).without_audio()
127
+ vc = vc.resize(height=1920) if vc.w/vc.h > 1080/1920 else vc.resize(width=1080)
128
+ vc = vc.crop(x_center=vc.w/2, y_center=vc.h/2, width=1080, height=1920)
129
+ vclips.append(vc)
130
+ except Exception as e:
131
+ log(f"Error video {fp}: {e}")
132
+ if vclips:
133
+ base = _ccv(vclips, method="compose") if len(vclips) > 1 else vclips[0]
134
+ # Repetir el video en bucle hasta cubrir toda la voz
135
+ if base.duration < dur_total:
136
+ base = base.loop(duration=dur_total)
137
+ else:
138
+ base = base.subclip(0, dur_total)
139
+ clip = base.set_duration(dur_total)
140
+ voz = voz.subclip(0, min(dur_total, voz.duration))
141
+ _USAR_VIDEO_ENTERO = True
142
+ else:
143
+ _USAR_VIDEO_ENTERO = False
144
+ else:
145
+ _USAR_VIDEO_ENTERO = False
146
+
147
+ num_planos = max(int(dur_total / 4) + 1, len(fondos))
148
+ fondos_loop = (fondos * ((num_planos // max(len(fondos),1)) + 1))[:num_planos]
149
+ dur_clip = dur_total / num_planos
150
+ # Si hay escenas con segundos, cada clip dura SUS segundos
151
+ # Solo usar segundos por escena si hay material asignado en las escenas
152
+ material_en_escenas = [(m,s) for m,s in escenas_data if m and os.path.exists(m)]
153
+ usar_seg_escena = bool(material_en_escenas) and not _USAR_VIDEO_ENTERO
154
+ if usar_seg_escena:
155
+ fondos_loop = [m for m,s in material_en_escenas]
156
+ segundos_loop = [s for m,s in material_en_escenas]
157
+ clips = []
158
+ idx_clip = -1
159
+ for fp in (fondos_loop if not _USAR_VIDEO_ENTERO else []):
160
+ idx_clip += 1
161
+ d_este = segundos_loop[idx_clip] if usar_seg_escena and idx_clip < len(segundos_loop) else dur_clip
162
+ try:
163
+ if fp.lower().endswith((".jpg",".jpeg",".png",".webp")):
164
+ img = PILImage.open(fp).convert("RGB")
165
+ w, h = img.size
166
+ bg = img.resize((1080,1920), PILImage.LANCZOS).filter(PIF.GaussianBlur(40))
167
+ ratio = min(1080/w, 1920/h)
168
+ fg = img.resize((int(w*ratio), int(h*ratio)), PILImage.LANCZOS)
169
+ bg.paste(fg, ((1080-fg.width)//2, (1920-fg.height)//2))
170
+ bg.save(fp+"_r.jpg","JPEG",quality=90)
171
+ ic = IC(fp+"_r.jpg").set_duration(d_este)
172
+ if efecto in ("zoom","zoom_fundido"):
173
+ ic = ic.resize(lambda t: 1 + 0.04*t).set_duration(d_este)
174
+ ic = ic.set_duration(d_este)
175
+ clips.append(ic)
176
+ else:
177
+ vclip = VC(fp).without_audio()
178
+ vclip = vclip.resize(height=1920) if vclip.w/vclip.h > 1080/1920 else vclip.resize(width=1080)
179
+ vclip = vclip.crop(x_center=vclip.w/2, y_center=vclip.h/2, width=1080, height=1920)
180
+ vclip = vclip.loop(duration=d_este).set_duration(d_este)
181
+ clips.append(vclip)
182
+ except Exception as e:
183
+ log(f"Error clip {fp}: {e}")
184
+
185
+ if not _USAR_VIDEO_ENTERO:
186
+ hay_video = any(str(f).lower().endswith((".mp4",".mov",".webm",".avi")) for f in fondos_loop)
187
+ if efecto in ("fundido","zoom_fundido") and len(clips) > 1 and not hay_video:
188
+ from moviepy.editor import concatenate_videoclips as _cc
189
+ clips_fx = [clips[0]] + [c2.crossfadein(0.5) for c2 in clips[1:]]
190
+ clip = _cc(clips_fx, method="compose", padding=-0.5)
191
+ else:
192
+ clip = concatenate_videoclips(clips, method="compose")
193
+ # MANUAL (material asignado a escenas): forzar duracion = suma de segundos exacta
194
+ _es_manual = bool([m for m,s in escenas_data if m and os.path.exists(m)]) if escenas_data else False
195
+ if _es_manual:
196
+ suma = sum(s for m,s in escenas_data if m and os.path.exists(m))
197
+ if clip.duration < suma:
198
+ clip = clip.set_duration(suma)
199
+ else:
200
+ clip = clip.subclip(0, suma)
201
+ dur_total = suma
202
+ else:
203
+ # AUTOMATICO: dura lo que suman los clips (va de lujo, no tocar)
204
+ dur_total = clip.duration
205
+ voz = voz.subclip(0, min(dur_total, voz.duration))
206
+
207
+ palabras = guion.split()
208
+ frases = [" ".join(palabras[i:i+6]) for i in range(0,len(palabras),6)]
209
+ t_f = voz.duration / max(len(frases),1)
210
+ sub_color = subs.get("color","#FFFFFF")
211
+ sub_size = {"pequeno":48,"mediano":64,"grande":80}.get(subs.get("tamano","mediano"),64)
212
+ sub_pos = {"arriba":0.15,"centro":0.5,"abajo":0.78}.get(subs.get("posicion","abajo"),0.78)
213
+ sub_activo = subs.get("activo",True)
214
+ if sub_activo:
215
+ txts = [TextClip(t.upper(), fontsize=sub_size, color=sub_color, font="/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
216
+ stroke_color="black", stroke_width=2, method="caption", size=(int(clip.w*0.8),None)
217
+ ).set_start(i*t_f).set_duration(t_f).set_pos(("center",sub_pos), relative=True)
218
+ for i,t in enumerate(frases)]
219
+ else:
220
+ txts = []
221
+
222
+ # Mezclar musica de fondo si el cliente la subio
223
+ import os as _os
224
+ audio_final = voz
225
+ if _os.path.exists("musica.mp3"):
226
+ try:
227
+ from moviepy.editor import CompositeAudioClip, AudioFileClip as _AC
228
+ musica = _AC("musica.mp3").volumex(0.18) # musica bajita para no tapar la voz
229
+ if musica.duration > voz.duration:
230
+ musica = musica.subclip(0, voz.duration)
231
+ else:
232
+ musica = musica.audio_loop(duration=voz.duration)
233
+ audio_final = CompositeAudioClip([voz.volumex(1.0), musica])
234
+ except Exception as _em:
235
+ log(f"Error mezcla musica: {_em}")
236
+ audio_final = voz
237
+ final = CompositeVideoClip([clip]+txts).set_audio(audio_final)
238
+ import os as _os2
239
+ if _os2.path.exists("preview.mp4"):
240
+ _os2.remove("preview.mp4")
241
+ final.write_videofile("preview_tmp.mp4", fps=20, codec="libx264", preset="ultrafast", logger=None, threads=4, audio_codec="aac")
242
+ # Renombrar solo cuando esta 100% terminado (evita cargar video a medias)
243
+ _os2.rename("preview_tmp.mp4", "preview.mp4")
244
+ return "preview.mp4"
245
+
246
+ # ========== ENDPOINTS ==========
247
+ @app.post("/login")
248
+ async def ep_login(request: Request):
249
+ d = await request.json()
250
+ clave = d.get("clave","").strip()
251
+ if verificar_clave(clave):
252
+ return {"ok": True}
253
+ return JSONResponse({"error":"Clave incorrecta"}, status_code=401)
254
+
255
+ @app.post("/generar-guion")
256
+ async def ep_guion(request: Request):
257
+ d = await request.json()
258
+ texto = d.get("texto","").strip()
259
+ estilo = d.get("estilo","narrativo")
260
+ duracion = int(d.get("duracion", 60) or 60)
261
+ parte = d.get("parte","auto")
262
+ # Si hay PDF completo cargado y el usuario no edito el texto a mano, usar el trozo elegido
263
+ completo = ESTADO.get("texto_completo","")
264
+ if completo and len(completo) > 6000:
265
+ if parte == "principio":
266
+ texto = completo[:6000]
267
+ elif parte == "mitad":
268
+ m = len(completo)//2
269
+ texto = completo[m-3000:m+3000]
270
+ elif parte == "final":
271
+ texto = completo[-6000:]
272
+ else: # auto = trozo al azar
273
+ import random as _r
274
+ ini = _r.randint(0, max(0, len(completo)-6000))
275
+ texto = completo[ini:ini+6000]
276
+ if not texto:
277
+ return JSONResponse({"error":"Pega tu contenido base primero"}, status_code=400)
278
+ try:
279
+ guion = generar_guion(texto, estilo, duracion)
280
+ ESTADO["guion"] = guion
281
+ return {"guion": guion}
282
+ except Exception as e:
283
+ return JSONResponse({"error": str(e)[:100]}, status_code=500)
284
+
285
+ @app.post("/subir-material")
286
+ async def ep_material(file: UploadFile = File(...)):
287
+ try:
288
+ import subprocess as _sp, os as _os
289
+ ext = file.filename.split(".")[-1].lower()
290
+ idx = len(ESTADO['archivos'])
291
+ if ext in ("mp4","mov","webm","avi","mkv","m4v"):
292
+ crudo = f"crudo_{idx}.{ext}"
293
+ with open(crudo,"wb") as f:
294
+ f.write(await file.read())
295
+ nombre = f"media_{idx}.mp4"
296
+ # Re-encodear a h264 estandar y fps fijo (arregla grabaciones de pantalla y formatos raros)
297
+ r = _sp.run(["ffmpeg","-y","-i",crudo,"-r","30","-c:v","libx264","-preset","ultrafast","-pix_fmt","yuv420p","-an",nombre], capture_output=True)
298
+ if _os.path.exists(nombre) and _os.path.getsize(nombre) > 1000:
299
+ try: _os.remove(crudo)
300
+ except: pass
301
+ else:
302
+ nombre = crudo
303
+ else:
304
+ nombre = f"media_{idx}.{ext}"
305
+ with open(nombre,"wb") as f:
306
+ f.write(await file.read())
307
+ ESTADO["archivos"].append(nombre)
308
+ return {"ok": True, "total": len(ESTADO["archivos"]), "nombre": nombre}
309
+ except Exception as e:
310
+ return JSONResponse({"error": str(e)[:100]}, status_code=500)
311
+
312
+ @app.post("/generar-voz")
313
+ async def ep_voz(request: Request):
314
+ d = await request.json()
315
+ guion = d.get("guion","").strip()
316
+ if not guion:
317
+ return JSONResponse({"error":"No hay guion"}, status_code=400)
318
+ ESTADO["guion"] = guion
319
+ try:
320
+ await generar_voz(guion, d.get("idioma","es"), d.get("genero","masculina"), d.get("pais",""))
321
+ ESTADO["voz_lista"] = True
322
+ return {"ok": True}
323
+ except Exception as e:
324
+ return JSONResponse({"error": str(e)[:100]}, status_code=500)
325
+
326
+
327
+ @app.post("/subir-voz-grabada")
328
+ async def ep_voz_grabada(file: UploadFile = File(...)):
329
+ try:
330
+ import subprocess
331
+ contenido = await file.read()
332
+ with open("voz_grabada_raw","wb") as f:
333
+ f.write(contenido)
334
+ # Convertir a mp3 con ffmpeg (el navegador graba en webm/ogg)
335
+ subprocess.run(["ffmpeg","-y","-i","voz_grabada_raw","-acodec","libmp3lame","voz.mp3"], capture_output=True)
336
+ import os as _os
337
+ if _os.path.exists("voz.mp3") and _os.path.getsize("voz.mp3") > 1000:
338
+ ESTADO["voz_lista"] = True
339
+ return {"ok": True}
340
+ return JSONResponse({"error":"No se pudo procesar el audio"}, status_code=500)
341
+ except Exception as e:
342
+ return JSONResponse({"error": str(e)[:120]}, status_code=500)
343
+
344
+
345
+ @app.post("/subir-musica")
346
+ async def ep_musica(file: UploadFile = File(...)):
347
+ try:
348
+ import subprocess, os as _os
349
+ contenido = await file.read()
350
+ with open("musica_raw","wb") as f:
351
+ f.write(contenido)
352
+ subprocess.run(["ffmpeg","-y","-i","musica_raw","-acodec","libmp3lame","musica.mp3"], capture_output=True)
353
+ if _os.path.exists("musica.mp3") and _os.path.getsize("musica.mp3") > 1000:
354
+ ESTADO["musica"] = True
355
+ return {"ok": True}
356
+ return JSONResponse({"error":"No se pudo procesar la musica"}, status_code=500)
357
+ except Exception as e:
358
+ return JSONResponse({"error": str(e)[:120]}, status_code=500)
359
+
360
+ @app.get("/audio")
361
+ def ep_audio():
362
+ if os.path.exists("voz.mp3"):
363
+ return FileResponse("voz.mp3", media_type="audio/mpeg")
364
+ return JSONResponse({"error":"sin audio"}, status_code=404)
365
+
366
+ @app.post("/generar-video")
367
+ async def ep_video(request: Request):
368
+ d = await request.json()
369
+ guion = d.get("guion","").strip() or ESTADO["guion"]
370
+ if not os.path.exists("voz.mp3"):
371
+ return JSONResponse({"error":"Genera la voz primero"}, status_code=400)
372
+ subs = {
373
+ "color": d.get("sub_color","#FFFFFF"),
374
+ "tamano": d.get("sub_tamano","mediano"),
375
+ "posicion": d.get("sub_posicion","abajo"),
376
+ "activo": d.get("sub_activo", True),
377
+ }
378
+ efecto = d.get("efecto","ninguno")
379
+ escenas = d.get("escenas", [])
380
+ # Lista de (material, segundos) de cada escena, en orden
381
+ escenas_data = [(e.get("material",""), int(e.get("segundos",5) or 5)) for e in escenas]
382
+ material_escenas = [m for m,s in escenas_data if m]
383
+ try:
384
+ loop = asyncio.get_event_loop()
385
+ await loop.run_in_executor(None, montar_video, guion, ESTADO["archivos"], subs, efecto, material_escenas, escenas_data)
386
+ ESTADO["video_listo"] = True
387
+ return {"ok": True}
388
+ except Exception as e:
389
+ import traceback
390
+ tb = traceback.format_exc()
391
+ print("ERROR VIDEO:", tb, flush=True)
392
+ return JSONResponse({"error": str(e)[:300]}, status_code=500)
393
+
394
+
395
+ @app.get("/video-listo")
396
+ def ep_video_listo():
397
+ import os as _os
398
+ if _os.path.exists("preview.mp4") and _os.path.getsize("preview.mp4") > 5000:
399
+ return {"listo": True, "mtime": _os.path.getmtime("preview.mp4")}
400
+ return {"listo": False}
401
+
402
+ @app.get("/video")
403
+ def ep_video_file():
404
+ if os.path.exists("preview.mp4"):
405
+ return FileResponse("preview.mp4", media_type="video/mp4")
406
+ return JSONResponse({"error":"sin video"}, status_code=404)
407
+
408
+ @app.post("/reset")
409
+ def ep_reset():
410
+ for f in glob.glob("media_*")+glob.glob("fondo*")+["voz.mp3","preview.mp4"]:
411
+ try: os.remove(f)
412
+ except: pass
413
+ ESTADO["guion"]=""; ESTADO["archivos"]=[]; ESTADO["voz_lista"]=False; ESTADO["video_listo"]=False
414
+ return {"ok": True}
415
+
416
+ @app.post("/subir-pdf")
417
+ async def ep_pdf(file: UploadFile = File(...)):
418
+ try:
419
+ contenido = await file.read()
420
+ with open("temp.pdf","wb") as f:
421
+ f.write(contenido)
422
+ from pypdf import PdfReader
423
+ reader = PdfReader("temp.pdf")
424
+ texto = ""
425
+ for pagina in reader.pages:
426
+ texto += (pagina.extract_text() or "") + "\n"
427
+ texto = texto.strip()
428
+ if not texto:
429
+ return JSONResponse({"error":"El PDF no tiene texto extraible (puede ser escaneado)"}, status_code=400)
430
+ ESTADO["texto_completo"] = texto
431
+ # Mostrar preview de los primeros 6000 al usuario
432
+ return {"ok": True, "texto": texto[:6000], "caracteres": len(texto)}
433
+ except Exception as e:
434
+ return JSONResponse({"error": str(e)[:120]}, status_code=500)
435
+
436
+ # ========== INTERFAZ ==========
437
+ @app.get("/", response_class=HTMLResponse)
438
+ def home():
439
+ return """<!DOCTYPE html>
440
+ <html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
441
+ <title>Fenix Hybrid Engine</title>
442
+ <style>
443
+ *{box-sizing:border-box;margin:0;padding:0}
444
+ body{background:#0a0a0a;color:#fff;font-family:system-ui,sans-serif;padding:20px;max-width:780px;margin:0 auto;line-height:1.5}
445
+ h1{font-size:1.8rem;background:linear-gradient(90deg,#ff6b00,#ffb700);-webkit-background-clip:text;-webkit-text-fill-color:transparent;margin-bottom:4px}
446
+ .sub{color:#888;margin-bottom:24px;font-size:.95rem}
447
+ .fase{background:#111;border:1px solid #222;border-radius:14px;padding:20px;margin-bottom:16px}
448
+ .fase-t{font-size:.8rem;color:#ff8c00;font-weight:700;text-transform:uppercase;letter-spacing:1px;margin-bottom:12px}
449
+ 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}
450
+ textarea{min-height:90px;resize:vertical}
451
+ 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}
452
+ button:disabled{opacity:.4}
453
+ .btn2{background:#222;color:#fff;border:1px solid #444}
454
+ .msg{font-size:.85rem;margin-top:8px;min-height:18px}
455
+ audio,video{width:100%;margin-top:10px;border-radius:8px}
456
+ .lbl{font-size:.85rem;color:#aaa;margin-bottom:6px;display:block}
457
+ .row{display:flex;gap:8px}.row>*{flex:1}
458
+ .tag{display:inline-block;background:#1a1a1a;color:#ff8c00;padding:2px 10px;border-radius:20px;font-size:.75rem;margin-left:6px}
459
+
460
+ .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}
461
+ @keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}
462
+ .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}
463
+ </style></head><body>
464
+ <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">
465
+ <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>
466
+ <p style="color:#888;margin-bottom:24px;font-size:.95rem">Introduce tu clave de acceso</p>
467
+ <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()">
468
+ <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>
469
+ <div id="loginMsg" style="color:#ff5252;margin-top:12px;font-size:.9rem;min-height:18px"></div>
470
+ </div>
471
+ <script>
472
+ async function hacerLogin(){
473
+ var clave=document.getElementById("claveInput").value;
474
+ var msg=document.getElementById("loginMsg");
475
+ msg.textContent="Comprobando...";msg.style.color="#ffb700";
476
+ try{
477
+ var r=await fetch("/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clave:clave})});
478
+ var d=await r.json();
479
+ if(d.ok){document.getElementById("loginOverlay").style.display="none";}
480
+ else{msg.textContent="Clave incorrecta";msg.style.color="#ff5252";}
481
+ }catch(e){msg.textContent="Error";msg.style.color="#ff5252";}
482
+ }
483
+ </script>
484
+
485
+ <h1>Fenix Hybrid Engine</h1>
486
+ <div class="sub">Motor de produccion asistida. La IA acelera, tu tienes el control.</div>
487
+ <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>
488
+ <div id="panelAyuda" style="display:none;background:#1a1a1a;border:1px solid #ff6b00;border-radius:10px;padding:16px;margin:10px 0;line-height:1.6">
489
+ <b>COMO HACER TU VIDEO (paso a paso):</b><br><br>
490
+ <b>1.</b> Sube un PDF o pega tu texto.<br>
491
+ <b>2.</b> Elige la duracion (15s, 30s, 45s, 1 o 2 min) y el estilo. Pulsa Generar Guion.<br>
492
+ <b>3.</b> Si quieres, edita el guion a tu gusto.<br>
493
+ <b>4.</b> Pulsa Dividir en escenas.<br>
494
+ <b>5.</b> Sube tus imagenes o videos.<br>
495
+ <b>6.</b> Genera la voz y escuchala.<br>
496
+ <b>7.</b> Pulsa Generar Video y descargalo.<br><br>
497
+ <b>DOS MODOS DE MONTAR:</b><br>
498
+ - <b>AUTOMATICO (facil):</b> deja el material en automatico. El sistema reparte las imagenes solo. Ideal para ir rapido.<br>
499
+ - <b>MANUAL (control total):</b> asigna una imagen a cada escena y pon los segundos de cada una. El video dura lo que tu pongas.<br><br>
500
+ <b>TRUCOS:</b><br>
501
+ - En la ULTIMA escena pon 4 o 5 segundos de mas, asi el video no termina en negro.<br>
502
+ - Si la voz dura mas que el video, acorta el guion o anade segundos para que cuadre.<br>
503
+ - Para videos cortos (redes) va rapido. Videos muy largos tardan mas.<br>
504
+ </div>
505
+
506
+ <div class="fase">
507
+ <div class="fase-t">1. Ingesta de conocimiento</div>
508
+ <span class="lbl">Sube un PDF (extrae el texto solo) o pega tu contenido:</span>
509
+ <input type="file" id="pdf" accept=".pdf" onchange="subirPdf()">
510
+ <div class="msg" id="msgPdf"></div>
511
+ <textarea id="texto" placeholder="Pega aqui tu base de conocimiento, o sube un PDF arriba..."></textarea>
512
+ <span class="lbl">Duracion del video:</span>
513
+ <select id="duracion">
514
+ <option value="15">15 segundos</option>
515
+ <option value="30">30 segundos</option>
516
+ <option value="45">45 segundos</option>
517
+ <option value="60">1 minuto</option>
518
+ <option value="120">2 minutos</option>
519
+ </select>
520
+ <span class="lbl">Estilo de narrativa:</span>
521
+ <select id="estilo">
522
+ <option value="narrativo">Narrativo y emocional</option>
523
+ <option value="educativo">Educativo y claro</option>
524
+ <option value="motivador">Motivador e inspirador</option>
525
+ <option value="publicitario">Publicitario y persuasivo</option>
526
+ <option value="misterio">Misterio e intriga</option>
527
+ </select>
528
+ <span class="lbl">Que parte del documento usar (si subiste PDF largo):</span>
529
+ <select id="parte">
530
+ <option value="auto">Automatico (trozos al azar, mas variedad)</option>
531
+ <option value="principio">Principio del documento</option>
532
+ <option value="mitad">Mitad del documento</option>
533
+ <option value="final">Final del documento</option>
534
+ </select>
535
+ <button onclick="genGuion()">Generar Propuesta de Guion</button>
536
+ <div class="msg" id="msgGuion"></div>
537
+ </div>
538
+
539
+ <div class="fase">
540
+ <div class="fase-t">2. Edicion del guion <span class="tag">control humano</span></div>
541
+ <span class="lbl">Edita el guion a tu gusto antes de continuar:</span>
542
+ <textarea id="guion" placeholder="Aqui aparecera el guion generado, editable..."></textarea>
543
+ <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>
544
+ <div id="escenas" style="margin-top:12px"></div>
545
+ </div>
546
+
547
+ <div class="fase">
548
+ <div class="fase-t">3. Tu material</div>
549
+ <span class="lbl">Sube tus imagenes o videos (uno a uno):</span>
550
+ <input type="file" id="material" accept="image/*,video/*" multiple onchange="subirMaterial()">
551
+ <div class="msg" id="msgMaterial">Sin material aun (usara fondos automaticos)</div>
552
+ </div>
553
+
554
+ <div class="fase">
555
+ <div class="fase-t">4. Voz</div>
556
+ <select id="tipoVoz" onchange="cambioVoz()">
557
+ <option value="ia">Voz IA (automatica)</option>
558
+ <option value="grabada">Mi voz grabada (con microfono)</option>
559
+ </select>
560
+ <div id="vozIA">
561
+ <div class="row">
562
+ <select id="genero"><option value="masculina">Voz masculina</option><option value="femenina">Voz femenina</option></select>
563
+ <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>
564
+ </div>
565
+ <button class="btn2" onclick="genVoz()">Generar y Pre-escuchar Voz</button>
566
+ </div>
567
+ <div id="vozGrabada" style="display:none">
568
+ <p style="color:#aaa;font-size:.85rem;margin-bottom:8px">Lee el guion de arriba en voz alta y grabate:</p>
569
+ <button class="btn2" id="btnRec" onclick="toggleRec()">Empezar a grabar</button>
570
+ </div>
571
+ <div class="msg" id="msgVoz"></div>
572
+ <audio id="player" controls style="display:none"></audio>
573
+ <div style="margin-top:14px;padding-top:14px;border-top:1px solid #222">
574
+ <span class="lbl">Musica de fondo (opcional, sonara bajita bajo la voz):</span>
575
+ <input type="file" id="musica" accept="audio/*" onchange="subirMusica()">
576
+ <div class="msg" id="msgMusica"></div>
577
+ </div>
578
+ </div>
579
+
580
+ <div class="fase">
581
+ <div class="fase-t">5. Subtitulos y Montaje</div>
582
+ <div class="row">
583
+ <select id="subActivo"><option value="si">Con subtitulos</option><option value="no">Sin subtitulos</option></select>
584
+ <select id="subTamano"><option value="pequeno">Pequenos</option><option value="mediano" selected>Medianos</option><option value="grande">Grandes</option></select>
585
+ </div>
586
+ <div class="row">
587
+ <select id="subPosicion"><option value="arriba">Arriba</option><option value="centro">Centro</option><option value="abajo" selected>Abajo</option></select>
588
+ <select id="subColor"><option value="#FFFFFF">Blanco</option><option value="#FFD700">Dorado</option><option value="#FFFF00">Amarillo</option><option value="#00E5FF">Cian</option><option value="#FF4081">Rosa</option><option value="#76FF03">Verde</option></select>
589
+ </div>
590
+ <span class="lbl">Efecto de video:</span>
591
+ <select id="efecto">
592
+ <option value="ninguno">Sin efecto (estatico)</option>
593
+ <option value="zoom">Zoom lento (Ken Burns)</option>
594
+ <option value="fundido">Fundido suave entre planos</option>
595
+ <option value="zoom_fundido">Zoom + Fundido (cinematografico)</option>
596
+ </select>
597
+ <button onclick="genVideo()">Generar Vista Previa del Video</button>
598
+ <button class="btn2" onclick="cargarVideo()" style="margin-top:8px">Cargar Video (cuando termine)</button>
599
+ <div class="msg" id="msgVideo"></div>
600
+ <video id="vid" controls playsinline webkit-playsinline preload="metadata" style="display:none"></video>
601
+ </div>
602
+
603
+ <div class="fase">
604
+ <div class="fase-t">6. Publicacion</div>
605
+ <button onclick="descargar()" style="background:linear-gradient(90deg,#00c853,#64dd17)">Descargar Video</button>
606
+ <button onclick="nuevoVideo()" style="background:#222;color:#fff;border:1px solid #444;margin-top:8px">Nuevo Video (limpiar todo)</button>
607
+ <button class="btn2" onclick="subirYt()" style="margin-top:8px">Conectar YouTube y Subir</button>
608
+ <div class="msg" id="msgPub"></div>
609
+ </div>
610
+
611
+ <script>
612
+ var ARCHIVOS_SUBIDOS=[];
613
+ async function subirPdf(){
614
+ var f=document.getElementById("pdf").files[0]; if(!f)return;
615
+ var m=document.getElementById("msgPdf"); m.textContent="Extrayendo texto...";m.style.color="#ffb700";
616
+ var fd=new FormData(); fd.append("file",f);
617
+ var r=await fetch("/subir-pdf",{method:"POST",body:fd}); var d=await r.json();
618
+ if(d.ok){document.getElementById("texto").value=d.texto;m.textContent="PDF leido: "+d.caracteres+" caracteres";m.style.color="#00c853";}
619
+ else{m.textContent=d.error;m.style.color="#ff5252";}
620
+ }
621
+ async function genGuion(){
622
+ var m=document.getElementById("msgGuion");m.textContent="Generando...";m.style.color="#ffb700";
623
+ 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})});
624
+ var d=await r.json();
625
+ if(d.guion){document.getElementById("guion").value=d.guion;m.textContent="Guion listo. Editalo abajo si quieres.";m.style.color="#00c853";}
626
+ else{m.textContent=d.error;m.style.color="#ff5252";}
627
+ }
628
+ async function subirMaterial(){
629
+ var files=document.getElementById("material").files; if(!files.length)return;
630
+ var m=document.getElementById("msgMaterial");
631
+ var total=0;
632
+ for(var i=0;i<files.length;i++){
633
+ m.textContent="Subiendo "+(i+1)+" de "+files.length+"...";m.style.color="#ffb700";
634
+ var fd=new FormData(); fd.append("file",files[i]);
635
+ var r=await fetch("/subir-material",{method:"POST",body:fd}); var d=await r.json();
636
+ if(d.ok){total=d.total; if(d.nombre){ARCHIVOS_SUBIDOS.push(d.nombre);}}
637
+ }
638
+ m.textContent=total+" archivo(s) subido(s) en total";m.style.color="#00c853";
639
+ }
640
+ async function genVoz(){
641
+ var m=document.getElementById("msgVoz");m.textContent="Generando voz...";m.style.color="#ffb700";
642
+ var guionFinal=document.getElementById("guion").value;
643
+ var esc=recolectarEscenas();
644
+ if(esc.length>0){
645
+ var textos=[];
646
+ for(var k=0;k<esc.length;k++){ if(esc[k].texto){textos.push(esc[k].texto);} }
647
+ if(textos.length>0){guionFinal=textos.join(". ");}
648
+ }
649
+ 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})});
650
+ var d=await r.json();
651
+ 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";
652
+ p.onloadedmetadata=function(){ sugerirSegundos(p.duration); };
653
+ }
654
+ else{m.textContent=d.error;m.style.color="#ff5252";}
655
+ }
656
+ function sugerirSegundos(durVoz){
657
+ if(!durVoz||durVoz<1){return;}
658
+ var items=document.getElementsByClassName("escenaItem");
659
+ if(items.length==0){return;}
660
+ // Contar palabras de cada escena y el total
661
+ var palabrasEsc=[]; var total=0;
662
+ for(var i=0;i<items.length;i++){
663
+ var t=items[i].getElementsByClassName("txtEscena")[0];
664
+ var np=t?t.value.trim().split(" ").filter(function(x){return x.length>0;}).length:1;
665
+ palabrasEsc.push(np); total+=np;
666
+ }
667
+ // Repartir la duracion de la voz segun palabras y rellenar
668
+ var sumaSeg=0;
669
+ for(var i=0;i<items.length;i++){
670
+ var seg=Math.max(1, Math.round(durVoz*(palabrasEsc[i]/total)));
671
+ // A la ultima escena le sumamos 1 segundo extra para que no salga negro al final
672
+ if(i==items.length-1){seg=seg+1;}
673
+ sumaSeg+=seg;
674
+ var campo=items[i].getElementsByClassName("segEscena")[0];
675
+ if(campo){campo.value=seg;}
676
+ }
677
+ // Mostrar total abajo
678
+ var tot=document.getElementById("totalSeg");
679
+ if(!tot){
680
+ tot=document.createElement("div");
681
+ tot.id="totalSeg";
682
+ tot.style.cssText="background:#1565c0;color:#fff;padding:10px;border-radius:8px;margin-top:10px;font-weight:700;text-align:center";
683
+ var cont=document.getElementById("escenas");
684
+ if(cont){cont.appendChild(tot);}
685
+ }
686
+ tot.textContent="Total del video: "+sumaSeg+" segundos (voz: "+Math.round(durVoz)+"s). Ajusta si quieres.";
687
+ }
688
+ var pollTimer=null;
689
+ function recolectarEscenas(){
690
+ var items=document.getElementsByClassName("escenaItem");
691
+ var lista=[];
692
+ for(var i=0;i<items.length;i++){
693
+ var sel=items[i].getElementsByClassName("selMaterial")[0];
694
+ var mat=sel?sel.value:"";
695
+ var seg=items[i].getElementsByClassName("segEscena")[0];
696
+ var segs=seg?parseInt(seg.value):5;
697
+ if(!segs||segs<1){segs=5;}
698
+ var txt=items[i].getElementsByClassName("txtEscena")[0];
699
+ var texto=txt?txt.value:"";
700
+ lista.push({material:mat,segundos:segs,texto:texto});
701
+ }
702
+ return lista;
703
+ }
704
+ async function genVideo(){
705
+ var m=document.getElementById("msgVideo");
706
+ m.innerHTML="<span class=\'spinner\'></span> Montando video...";m.style.color="#ffb700";
707
+ // Lanzar el render sin esperar la respuesta (evita timeout)
708
+ fetch("/generar-video",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({
709
+ guion:document.getElementById("guion").value,
710
+ sub_activo:document.getElementById("subActivo").value==="si",
711
+ sub_tamano:document.getElementById("subTamano").value,
712
+ sub_posicion:document.getElementById("subPosicion").value,
713
+ sub_color:document.getElementById("subColor").value,
714
+ efecto:document.getElementById("efecto").value,
715
+ escenas:recolectarEscenas()
716
+ })}).catch(e=>{});
717
+ // Comprobar cada 4 segundos si el video esta listo
718
+ var inicio=Date.now();
719
+ if(pollTimer)clearInterval(pollTimer);
720
+ pollTimer=setInterval(async()=>{
721
+ try{
722
+ var r=await fetch("/video-listo?t="+Date.now());var d=await r.json();
723
+ if(d.listo && d.mtime*1000 > inicio){
724
+ clearInterval(pollTimer);
725
+ var u="/video?t="+Date.now();
726
+ var v=document.getElementById("vid");v.src=u;v.style.display="block";v.load();
727
+ 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>";
728
+ m.style.color="#00c853";
729
+ }
730
+ }catch(e){}
731
+ },4000);
732
+ }
733
+ async function subirMusica(){
734
+ var f=document.getElementById("musica").files[0]; if(!f)return;
735
+ var m=document.getElementById("msgMusica");m.textContent="Subiendo musica...";m.style.color="#ffb700";
736
+ var fd=new FormData(); fd.append("file",f);
737
+ var r=await fetch("/subir-musica",{method:"POST",body:fd}); var d=await r.json();
738
+ if(d.ok){m.textContent="✅ Musica anadida, sonara de fondo";m.style.color="#00c853";}
739
+ else{m.textContent="❌ "+(d.error||"Error");m.style.color="#ff5252";}
740
+ }
741
+ function cargarVideo(){
742
+ var u="/video?t="+Date.now();
743
+ var v=document.getElementById("vid");v.src=u;v.style.display="block";v.load();
744
+ var m=document.getElementById("msgVideo");
745
+ m.innerHTML="▶ <a href=\'"+u+"\' target=\'_blank\' style=\'color:#00E5FF;font-weight:800\'>VER VIDEO EN PANTALLA COMPLETA</a>";
746
+ m.style.color="#00c853";
747
+ }
748
+ async function nuevoVideo(){
749
+ if(!confirm("Esto borra el material, la voz y el video actual para empezar de cero. Continuar?"))return;
750
+ try{
751
+ await fetch("/reset",{method:"POST"});
752
+ location.reload();
753
+ }catch(e){alert("Error al limpiar");}
754
+ }
755
+ function descargar(){var a=document.createElement("a");a.href="/video?t="+Date.now();a.download="video_fenix.mp4";a.click();}
756
+ function dividirEscenas(){
757
+ var t=document.getElementById("guion").value;
758
+ var sep=String.fromCharCode(10)+String.fromCharCode(10);
759
+ var bloques=t.split(sep);
760
+ var cont=document.getElementById("escenas");
761
+ var html="";
762
+ var n=0;
763
+ for(var i=0;i<bloques.length;i++){
764
+ var b=bloques[i].trim();
765
+ if(b==""){continue;}
766
+ n++;
767
+ var opciones="<option value=>-- material automatico --</option>";
768
+ for(var j=0;j<ARCHIVOS_SUBIDOS.length;j++){ opciones+="<option value="+ARCHIVOS_SUBIDOS[j]+">"+ARCHIVOS_SUBIDOS[j]+"</option>"; }
769
+ html+="<div class=escenaItem><b>Escena "+n+"</b><br><textarea class=txtEscena style=width:100%;min-height:50px;background:#111;color:#fff;border:1px solid #333;border-radius:6px;padding:6px>"+b+"</textarea><br><select class=selMaterial>"+opciones+"</select> <input type=number class=segEscena min=1 value=5 style=width:70px> seg</div>";
770
+ }
771
+ if(n==0){html="<div style=color:#888>Separa los parrafos con una linea en blanco</div>";}
772
+ cont.innerHTML=html;
773
+ }
774
+ async function subirYt(){var m=document.getElementById("msgPub");m.textContent="Conecta tu canal de YouTube para activar la subida automatica";m.style.color="#ffb700";}
775
+
776
+ function cambioVoz(){
777
+ var t=document.getElementById("tipoVoz").value;
778
+ document.getElementById("vozIA").style.display=t==="ia"?"block":"none";
779
+ document.getElementById("vozGrabada").style.display=t==="grabada"?"block":"none";
780
+ }
781
+ var mediaRec=null, chunks=[], grabando=false;
782
+ async function toggleRec(){
783
+ var btn=document.getElementById("btnRec"); var m=document.getElementById("msgVoz");
784
+ if(!grabando){
785
+ try{
786
+ var stream=await navigator.mediaDevices.getUserMedia({audio:true});
787
+ mediaRec=new MediaRecorder(stream); chunks=[];
788
+ mediaRec.ondataavailable=e=>chunks.push(e.data);
789
+ mediaRec.onstop=async()=>{
790
+ var blob=new Blob(chunks,{type:"audio/webm"});
791
+ m.textContent="Subiendo tu voz...";m.style.color="#ffb700";
792
+ var fd=new FormData(); fd.append("file",blob,"voz.webm");
793
+ var r=await fetch("/subir-voz-grabada",{method:"POST",body:fd}); var d=await r.json();
794
+ 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";}
795
+ else{m.textContent="❌ "+(d.error||"Error");m.style.color="#ff5252";}
796
+ };
797
+ mediaRec.start(); grabando=true;
798
+ btn.textContent="⏹ Detener grabacion"; btn.style.background="#ff4444";
799
+ m.textContent="Grabando... lee el guion";m.style.color="#ff4444";
800
+ }catch(e){m.textContent="❌ No se pudo acceder al microfono";m.style.color="#ff5252";}
801
+ }else{
802
+ mediaRec.stop(); grabando=false;
803
+ btn.textContent="Empezar a grabar"; btn.style.background="";
804
+ }
805
+ }
806
+ </script>
807
+ </body></html>"""