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

selector duracion: groq genera guion segun minutos

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