Tu Nombre commited on
Commit
a1ae7a8
·
1 Parent(s): 4c813af

fix: sin negro al final, video dura lo que suman las imagenes

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