Tu Nombre commited on
Commit
3d4021b
·
1 Parent(s): 3bd74ab

boton Como usar con guia rapida desplegable

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