Spaces:
Runtime error
Runtime error
Update app.py
Browse files12 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546471 unmodified line4950515253545556575859606162636465666768697071727374757677782 unmodified lines8182838485868788899091929394959697989910010125 unmodified lines1271281291301311321331341351361371381391405 unmodified lines1461471481491501511521531541551561571581591601611622 unmodified lines1651661671681691701711721731741751761771781791801811821831841851861871881891901911921934 unmodified lines19819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627712 unmodified lines)# ------------------- Configuración & Globals -------------------logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")logger = logging.getLogger(__name__)PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")if not PEXELS_API_KEY:raise RuntimeError("Debes definir PEXELS_API_KEY en 'Settings' -> 'Variables & secrets'")# --- Modelos inicializados como None para Carga Perezosa (Lazy Loading) ---tokenizer = Nonegpt2_model = Nonekw_model = None# ---RESULTS_DIR = "video_results"os.makedirs(RESULTS_DIR, exist_ok=True)TASKS = {}# --- Lista de Voces Fija para un Arranque Instantáneo ---SPANISH_VOICES = ["es-ES-ElviraNeural", "es-ES-AlvaroNeural", "es-MX-DaliaNeural", "es-MX-JorgeNeural","es-AR-ElenaNeural", "es-AR-TomasNeural", "es-CO-SalomeNeural", "es-CO-GonzaloNeural","es-US-PalomaNeural", "es-US-AlonsoNeural"]# ------------------- Funciones para cargar modelos bajo demanda -------------------def get_tokenizer():global tokenizerif tokenizer is None:logger.info("Cargando tokenizer por primera vez...")tokenizer = GPT2Tokenizer.from_pretrained("datificate/gpt2-small-spanish")if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_tokenreturn tokenizer1 unmodified linedef get_gpt2_model():global gpt2_modelif gpt2_model is None:logger.info("Cargando modelo GPT-2 por primera vez...")gpt2_model = GPT2LMHeadModel.from_pretrained("datificate/gpt2-small-spanish").eval()return gpt2_modeldef get_kw_model():global kw_modelif kw_model is None:logger.info("Cargando modelo KeyBERT por primera vez...")kw_model = KeyBERT("distilbert-base-multilingual-cased")return kw_model# ------------------- Funciones del Pipeline de Vídeo -------------------def gpt2_script(prompt: str, max_len: int = 160) -> str:local_tokenizer = get_tokenizer()local_gpt2_model = get_gpt2_model()instruction = f"Escribe un guion corto y coherente sobre: {prompt}"inputs = local_tokenizer(instruction, return_tensors="pt", truncation=True, max_length=512)outputs = local_gpt2_model.generate(**inputs, max_length=max_len + inputs["input_ids"].shape[1], do_sample=True,top_p=0.9, top_k=40, temperature=0.7, no_repeat_ngram_size=3,pad_token_id=local_tokenizer.pad_token_id, eos_token_id=local_tokenizer.eos_token_id,)text = local_tokenizer.decode(outputs[0], skip_special_tokens=True)return text.split("sobre:")[-1].strip()[:max_len]async def edge_tts_synth(text: str, voice: str, path: str):communicate = edge_tts.Communicate(text, voice)2 unmodified linesdef keywords(text: str) -> list[str]:local_kw_model = get_kw_model()clean_text = re.sub(r"[^\w\sáéíóúñÁÉÍÓÚÑ]", "", text.lower())try:kws = local_kw_model.extract_keywords(clean_text, stop_words="spanish", top_n=5)return [k.replace(" ", "+") for k, _ in kws if k]except Exception as e:logger.warning(f"KeyBERT falló, usando método simple. Error: {e}")words = [w for w in clean_text.split() if len(w) > 4]return [w for w, _ in Counter(words).most_common(5)] or ["naturaleza"]def pexels_search(query: str, count: int) -> list[dict]:res = requests.get("https://api.pexels.com/videos/search",headers={"Authorization": PEXELS_API_KEY},params={"query": query, "per_page": count, "orientation": "landscape"},timeout=20,)res.raise_for_status()return res.json().get("videos", [])25 unmodified linesnum_words = len(sentence.split())sentence_duration = num_words * time_per_wordif sentence_duration < 0.1: continuetxt_clip = (TextClip(sentence, fontsize=int(video_h * 0.05), color="white",stroke_color="black", stroke_width=1.5, method="caption",size=(int(video_w * 0.9), None), font="Arial-Bold").set_start(current_time).set_duration(sentence_duration).set_position(("center", "bottom")))clips.append(txt_clip)current_time += sentence_durationreturn clips5 unmodified linesreturn np.repeat(noise, 3, axis=2)return VideoClip(make_frame, duration=duration).set_opacity(0.15)def build_video(script_text: str, generate_script_flag: bool, voice: str, music_path: str | None) -> str:tmp_dir = tempfile.mkdtemp()try:script = gpt2_script(script_text) if generate_script_flag else script_text.strip()voice_path = os.path.join(tmp_dir, "voice.mp3")asyncio.run(edge_tts_synth(script, voice, voice_path))voice_clip = AudioFileClip(voice_path)video_duration = voice_clip.durationif video_duration < 1: raise ValueError("El audio generado es demasiado corto.")video_paths = []for kw in keywords(script):if len(video_paths) >= 8: breakfor video_data in pexels_search(kw, 2):best_file = max(video_data.get("video_files", []), key=lambda f: f.get("width", 0))2 unmodified linesif path: video_paths.append(path)if len(video_paths) >= 8: breakif not video_paths: raise RuntimeError("No se encontraron vídeos en Pexels.")segments = []for path in video_paths:try: segments.append(VideoFileClip(path))except Exception as e: logger.warning(f"No se pudo cargar el clip {path}: {e}")if not segments: raise RuntimeError("Los clips descargados no son válidos.")final_segments = [s.subclip(0, min(8, s.duration)) for s in segments]base_video = concatenate_videoclips(final_segments, method="chain")if base_video.duration < video_duration:num_loops = math.ceil(video_duration / base_video.duration)base_video = concatenate_videoclips([base_video] * num_loops, method="chain")base_video = base_video.subclip(0, video_duration)if music_path:music_clip = loop_audio(AudioFileClip(music_path), video_duration).volumex(0.20)final_audio = CompositeAudioClip([music_clip, voice_clip])else: final_audio = voice_clipsubtitles = make_subtitle_clips(script, base_video.w, base_video.h, video_duration)grain_effect = make_grain_clip(base_video.size, video_duration)final_video = CompositeVideoClip([base_video, grain_effect, *subtitles]).set_audio(final_audio)output_path = os.path.join(tmp_dir, "final_video.mp4")final_video.write_videofile(output_path, fps=24, codec="libx264", audio_codec="aac", threads=2, logger=None)return output_pathfinally:# Intenta cerrar todos los clips de MoviePy para liberar memoriaif 'voice_clip' in locals(): voice_clip.close()if 'music_clip' in locals(): music_clip.close()if 'base_video' in locals(): base_video.close()4 unmodified linesdef worker(task_id: str, mode: str, topic: str, user_script: str, voice: str, music: str | None):try:text = topic if mode == "Generar Guion con IA" else user_scriptresult_tmp_path = build_video(text, mode == "Generar Guion con IA", voice, music)final_path = os.path.join(RESULTS_DIR, f"{task_id}.mp4")shutil.copy2(result_tmp_path, final_path)TASKS[task_id] = {"status": "done", "result": final_path, "timestamp": datetime.utcnow()}shutil.rmtree(os.path.dirname(result_tmp_path))except Exception as e:logger.error(f"Error en la tarea {task_id}: {e}", exc_info=True)TASKS[task_id] = {"status": "error", "error": str(e), "timestamp": datetime.utcnow()}def submit_task(mode, topic, user_script, voice, music):content = topic if mode == "Generar Guion con IA" else user_scriptif not content.strip(): return "", "Por favor, ingresa un tema o guion."task_id = uuid.uuid4().hex[:8]TASKS[task_id] = {"status": "processing", "timestamp": datetime.utcnow()}threading.Thread(target=worker, args=(task_id, mode, topic, user_script, voice, music), daemon=True).start()return task_id, f"✅ Tarea creada con ID: {task_id}. Comprueba el estado en unos minutos."def check_task_status(task_id):if not task_id or task_id not in TASKS: return None, None, "ID de tarea no válido o no encontrado."task_info = TASKS[task_id]status = task_info["status"]if status == "processing": return None, None, "⏳ La tarea se está procesando..."if status == "error": return None, None, f"❌ Error: {task_info['error']}"if status == "done": return task_info["result"], task_info["result"], "✅ ¡Vídeo listo!"return None, None, "Estado desconocido."def janitor_thread():while True:time.sleep(3600)now = datetime.utcnow()for task_id, info in list(TASKS.items()):if now - info["timestamp"] > timedelta(hours=24):if info.get("result") and os.path.exists(info["result"]):try:os.remove(info["result"])logger.info(f"Limpiado vídeo antiguo: {info['result']}")except Exception as e:logger.error(f"Error al limpiar {info['result']}: {e}")del TASKS[task_id]threading.Thread(target=janitor_thread, daemon=True).start()with gr.Blocks(title="Generador de Vídeos IA", theme=gr.themes.Soft()) as demo:gr.Markdown("# 🎬 Generador de Vídeos con IA")gr.Markdown("Crea vídeos a partir de texto, con voz, música y efectos visuales.")with gr.Tabs():with gr.TabItem("1. Crear Vídeo"):with gr.Row():with gr.Column(scale=2):mode_radio = gr.Radio(["Generar Guion con IA", "Usar Mi Guion"], value="Generar Guion con IA", label="Elige el método")topic_textbox = gr.Textbox(label="Tema para la IA", placeholder="Ej: La historia de la Vía Láctea")script_textbox = gr.Textbox(label="Tu Guion Completo", lines=5, visible=False, placeholder="Pega aquí tu guion...")voice_dropdown = gr.Dropdown(SPANISH_VOICES, value=SPANISH_VOICES[0], label="Elige una voz")music_upload = gr.Audio(type="filepath", label="Música de fondo (opcional)")submit_button = gr.Button("✨ Generar Vídeo", variant="primary")with gr.Column(scale=1):task_id_output = gr.Textbox(label="ID de tu Tarea (Guárdalo)", interactive=False)status_output = gr.Textbox(label="Estado", interactive=False)gr.Markdown("---")gr.Markdown("### ¿Cómo funciona?\n1. Elige un método y rellena el texto.\n2. **Copia el ID** que aparecerá.\n3. Ve a la pestaña **'2. Revisar Estado'**.")with gr.TabItem("2. Revisar Estado"):gr.Markdown("### Consulta el estado de tu vídeo")with gr.Row():task_id_input = gr.Textbox(label="Pega aquí el ID de tu tarea", scale=3)check_button = gr.Button("🔍 Verificar", scale=1)status_check_output = gr.Textbox(label="Estado Actual", interactive=False)video_output = gr.Video(label="Resultado del Vídeo")download_file_output = gr.File(label="Descargar Fichero")def toggle_textboxes(mode):is_ai_mode = mode == "Generar Guion con IA"return gr.update(visible=is_ai_mode), gr.update(visible=not is_ai_mode)mode_radio.change(toggle_textboxes, inputs=mode_radio, outputs=[topic_textbox, script_textbox])submit_button.click(submit_task, inputs=[mode_radio, topic_textbox, script_textbox, voice_dropdown, music_upload], outputs=[task_id_output, status_output])check_button.click(check_task_status, inputs=task_id_input, outputs=[video_output, download_file_output, status_check_output])if __name__ == "__main__":demo.launch()12 unmodified lines131415161718192021222324252627282930313233343536373839401 unmodified line4243444546474849505152535455565758596061626364656667686970717273747576772 unmodified lines80818283848586878889909125 unmodified lines1171181191201211221231241251265 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541552 unmodified lines1581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871884 unmodified lines19319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327412 unmodified lines)# ------------------- Configuración & Globals -------------------logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")logger = logging.getLogger(__name__)PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")if not PEXELS_API_KEY:raise RuntimeError("Debes definir PEXELS_API_KEY en 'Settings' -> 'Variables & secrets'")tokenizer, gpt2_model, kw_model = None, None, NoneRESULTS_DIR = "video_results"os.makedirs(RESULTS_DIR, exist_ok=True)TASKS = {} # Diccionario para almacenar estado y progreso de tareasSPANISH_VOICES = ["es-ES-ElviraNeural", "es-ES-AlvaroNeural", "es-MX-DaliaNeural", "es-MX-JorgeNeural","es-AR-ElenaNeural", "es-AR-TomasNeural", "es-CO-SalomeNeural", "es-CO-GonzaloNeural"]# ------------------- Carga Perezosa de Modelos -------------------def get_tokenizer():global tokenizerif tokenizer is None:logger.info("Cargando tokenizer (primera vez)...")tokenizer = GPT2Tokenizer.from_pretrained("datificate/gpt2-small-spanish")if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_tokenreturn tokenizer1 unmodified linedef get_gpt2_model():global gpt2_modelif gpt2_model is None:logger.info("Cargando modelo GPT-2 (primera vez)...")gpt2_model = GPT2LMHeadModel.from_pretrained("datificate/gpt2-small-spanish").eval()return gpt2_modeldef get_kw_model():global kw_modelif kw_model is None:logger.info("Cargando modelo KeyBERT (primera vez)...")kw_model = KeyBERT("distilbert-base-multilingual-cased")return kw_model# ------------------- Funciones del Pipeline de Vídeo -------------------def update_task_progress(task_id, message):"""Actualiza el log de progreso para una tarea."""if task_id in TASKS:TASKS[task_id]['progress_log'] = messagelogger.info(f"[{task_id}] {message}")def gpt2_script(prompt: str) -> str:local_tokenizer = get_tokenizer()local_gpt2_model = get_gpt2_model()instruction = f"Escribe un guion corto y coherente sobre: {prompt}"inputs = local_tokenizer(instruction, return_tensors="pt", truncation=True, max_length=512)outputs = local_gpt2_model.generate(**inputs, max_length=160 + inputs["input_ids"].shape[1], do_sample=True,top_p=0.9, top_k=40, temperature=0.7, no_repeat_ngram_size=3,pad_token_id=local_tokenizer.pad_token_id, eos_token_id=local_tokenizer.eos_token_id,)text = local_tokenizer.decode(outputs[0], skip_special_tokens=True)return text.split("sobre:")[-1].strip()async def edge_tts_synth(text: str, voice: str, path: str):communicate = edge_tts.Communicate(text, voice)2 unmodified linesdef keywords(text: str) -> list[str]:local_kw_model = get_kw_model()clean_text = re.sub(r"[^\w\sáéíóúñÁÉÍÓÚÑ]", "", text.lower())kws = local_kw_model.extract_keywords(clean_text, stop_words="spanish", top_n=5)return [k.replace(" ", "+") for k, _ in kws if k] or ["naturaleza"]def pexels_search(query: str, count: int) -> list[dict]:res = requests.get("https://api.pexels.com/videos/search", headers={"Authorization": PEXELS_API_KEY},params={"query": query, "per_page": count, "orientation": "landscape"}, timeout=20)res.raise_for_status()return res.json().get("videos", [])25 unmodified linesnum_words = len(sentence.split())sentence_duration = num_words * time_per_wordif sentence_duration < 0.1: continuetxt_clip = (TextClip(sentence, fontsize=int(video_h * 0.05), color="white",stroke_color="black", stroke_width=1.5, method="caption",size=(int(video_w * 0.9), None), font="Arial-Bold").set_start(current_time).set_duration(sentence_duration).set_position(("center", "bottom")))clips.append(txt_clip)current_time += sentence_durationreturn clips5 unmodified linesreturn np.repeat(noise, 3, axis=2)return VideoClip(make_frame, duration=duration).set_opacity(0.15)def build_video(script_text: str, generate_script_flag: bool, voice: str, music_path: str | None, task_id: str) -> str:tmp_dir = tempfile.mkdtemp()try:update_task_progress(task_id, "Paso 1/7: Generando guion...")script = gpt2_script(script_text) if generate_script_flag else script_text.strip()update_task_progress(task_id, f"Paso 2/7: Creando audio con voz '{voice}'...")voice_path = os.path.join(tmp_dir, "voice.mp3")asyncio.run(edge_tts_synth(script, voice, voice_path))voice_clip = AudioFileClip(voice_path)video_duration = voice_clip.durationif video_duration < 1: raise ValueError("El audio generado es demasiado corto.")update_task_progress(task_id, "Paso 3/7: Buscando clips de vídeo en Pexels...")video_paths = []kws = keywords(script)for i, kw in enumerate(kws):update_task_progress(task_id, f"Paso 3/7: Buscando clips... (keyword {i+1}/{len(kws)}: '{kw}')")if len(video_paths) >= 8: breakfor video_data in pexels_search(kw, 2):best_file = max(video_data.get("video_files", []), key=lambda f: f.get("width", 0))2 unmodified linesif path: video_paths.append(path)if len(video_paths) >= 8: breakif not video_paths: raise RuntimeError("No se encontraron vídeos en Pexels.")update_task_progress(task_id, f"Paso 4/7: Ensamblando {len(video_paths)} clips de vídeo...")segments = [VideoFileClip(p).subclip(0, min(8, VideoFileClip(p).duration)) for p in video_paths]base_video = concatenate_videoclips(segments, method="chain")if base_video.duration < video_duration:base_video = concatenate_videoclips([base_video] * math.ceil(video_duration / base_video.duration))base_video = base_video.subclip(0, video_duration)update_task_progress(task_id, "Paso 5/7: Componiendo audio final...")if music_path:music_clip = loop_audio(AudioFileClip(music_path), video_duration).volumex(0.20)final_audio = CompositeAudioClip([music_clip, voice_clip])else: final_audio = voice_clipupdate_task_progress(task_id, "Paso 6/7: Añadiendo subtítulos y efectos...")subtitles = make_subtitle_clips(script, base_video.w, base_video.h, video_duration)grain_effect = make_grain_clip(base_video.size, video_duration)update_task_progress(task_id, "Paso 7/7: Renderizando vídeo final (esto puede tardar varios minutos)...")final_video = CompositeVideoClip([base_video, grain_effect, *subtitles]).set_audio(final_audio)output_path = os.path.join(tmp_dir, "final_video.mp4")final_video.write_videofile(output_path, fps=24, codec="libx64", audio_codec="aac", threads=2, logger=None)return output_pathfinally:if 'voice_clip' in locals(): voice_clip.close()if 'music_clip' in locals(): music_clip.close()if 'base_video' in locals(): base_video.close()4 unmodified linesdef worker(task_id: str, mode: str, topic: str, user_script: str, voice: str, music: str | None):try:text = topic if mode == "Generar Guion con IA" else user_scriptresult_tmp_path = build_video(text, mode == "Generar Guion con IA", voice, music, task_id)final_path = os.path.join(RESULTS_DIR, f"{task_id}.mp4")shutil.copy2(result_tmp_path, final_path)TASKS[task_id].update({"status": "done", "result": final_path})shutil.rmtree(os.path.dirname(result_tmp_path))except Exception as e:logger.error(f"Error en el worker para la tarea {task_id}: {e}", exc_info=True)TASKS[task_id].update({"status": "error", "error": str(e)})def janitor_thread():while True:time.sleep(3600)now = datetime.utcnow()logger.info("[JANITOR] Realizando limpieza de vídeos antiguos...")for task_id, info in list(TASKS.items()):if "timestamp" in info and now - info["timestamp"] > timedelta(hours=24):if info.get("result") and os.path.exists(info.get("result")):try:os.remove(info["result"])logger.info(f"[JANITOR] Eliminado: {info['result']}")except Exception as e:logger.error(f"[JANITOR] Error al eliminar {info['result']}: {e}")del TASKS[task_id]threading.Thread(target=janitor_thread, daemon=True).start()def generate_and_monitor(mode, topic, user_script, voice, music):content = topic if mode == "Generar Guion con IA" else user_scriptif not content.strip():yield "Por favor, ingresa un tema o guion.", None, Nonereturntask_id = uuid.uuid4().hex[:8]TASKS[task_id] = {"status": "processing", "progress_log": "Iniciando tarea...", "timestamp": datetime.utcnow()}worker_thread = threading.Thread(target=worker, args=(task_id, mode, topic, user_script, voice, music), daemon=True)worker_thread.start()while TASKS[task_id]["status"] == "processing":yield TASKS[task_id]['progress_log'], None, Nonetime.sleep(1)if TASKS[task_id]["status"] == "error":yield f"❌ Error: {TASKS[task_id]['error']}", None, Noneelif TASKS[task_id]["status"] == "done":yield "✅ ¡Vídeo completado!", TASKS[task_id]['result'], TASKS[task_id]['result']with gr.Blocks(title="Generador de Vídeos IA", theme=gr.themes.Soft()) as demo:gr.Markdown("# 🎬 Generador de Vídeos con IA")gr.Markdown("Crea vídeos a partir de texto con voz, música y efectos visuales. El progreso se mostrará en tiempo real.")with gr.Row():with gr.Column(scale=2):mode_radio = gr.Radio(["Generar Guion con IA", "Usar Mi Guion"], value="Generar Guion con IA", label="Elige el método")topic_textbox = gr.Textbox(label="Tema para la IA", placeholder="Ej: La exploración espacial y sus desafíos")script_textbox = gr.Textbox(label="Tu Guion Completo", lines=5, visible=False, placeholder="Pega aquí tu guion...")voice_dropdown = gr.Dropdown(SPANISH_VOICES, value=SPANISH_VOICES[0], label="Elige una voz")music_upload = gr.Audio(type="filepath", label="Música de fondo (opcional)")submit_button = gr.Button("✨ Generar Vídeo", variant="primary")with gr.Column(scale=2):gr.Markdown("## Progreso y Resultados")progress_log = gr.Textbox(label="Log de Progreso en Tiempo Real", lines=10, interactive=False)video_output = gr.Video(label="Resultado del Vídeo")download_file_output = gr.File(label="Descargar Fichero")def toggle_textboxes(mode):return gr.update(visible=mode == "Generar Guion con IA"), gr.update(visible=mode != "Generar Guion con IA")mode_radio.change(toggle_textboxes, inputs=mode_radio, outputs=[topic_textbox, script_textbox])submit_button.click(fn=generate_and_monitor,inputs=[mode_radio, topic_textbox, script_textbox, voice_dropdown, music_upload],outputs=[progress_log, video_output, download_file_output])if __name__ == "__main__":demo.launch()
app.py+100-103