Spaces:
Sleeping
Sleeping
File size: 7,754 Bytes
1f72b0c b808439 1088ad0 c7d476a 1f72b0c 0f64582 beea2cf 17d6357 1088ad0 1f72b0c 17d6357 1088ad0 0f64582 1f72b0c c7d476a 1f72b0c 17d6357 0f64582 1f72b0c 1088ad0 c7d476a 1f72b0c 02e97a3 17d6357 02e97a3 c7d476a 02e97a3 f8ec5f8 17d6357 f8ec5f8 615a9e3 f8ec5f8 615a9e3 f8ec5f8 617df9d 02e97a3 1088ad0 d446056 4123c9b 17d6357 f8ec5f8 617df9d d446056 617df9d 4123c9b f8ec5f8 02e97a3 c7d476a f8ec5f8 1f72b0c 17d6357 beea2cf f8ec5f8 c7d476a 1f72b0c c7d476a beea2cf c7d476a f8ec5f8 c7d476a beea2cf c7d476a 1f72b0c 1088ad0 beea2cf 17d6357 c7d476a f8ec5f8 c7d476a 17d6357 c7d476a 4123c9b c7d476a 17d6357 beea2cf 17d6357 beea2cf 0f64582 4123c9b 617df9d 57af5e5 0f64582 f8ec5f8 0f64582 f8ec5f8 0f64582 c7d476a 17d6357 ced4e6e 0f64582 ced4e6e c7d476a 4123c9b ced4e6e c7d476a beea2cf f8ec5f8 beea2cf 1f72b0c 17d6357 1f72b0c c7d476a 1088ad0 1f72b0c d446056 1088ad0 d446056 1088ad0 1f72b0c c7d476a ee5aeee 1f72b0c 1088ad0 c7d476a 1088ad0 1f72b0c c7d476a 1f72b0c 1088ad0 c7d476a 1088ad0 1f72b0c d446056 4123c9b d446056 1f72b0c 4123c9b 1f72b0c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
import math
import tempfile
import logging
import os
import asyncio
from moviepy.editor import *
import edge_tts
import gradio as gr
from pydub import AudioSegment
# Configuración de Logs
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
# CONSTANTES DE ARCHIVOS
INTRO_VIDEO = "introvideo.mp4"
OUTRO_VIDEO = "outrovideo.mp4"
MUSIC_BG = "musicafondo.mp3"
FX_SOUND = "fxsound.mp3"
WATERMARK = "watermark.png"
EJEMPLO_VIDEO = "ejemplo.mp4"
# Validar existencia de archivos
for file in [INTRO_VIDEO, OUTRO_VIDEO, MUSIC_BG, FX_SOUND, WATERMARK, EJEMPLO_VIDEO]:
if not os.path.exists(file):
logging.error(f"Falta archivo necesario: {file}")
raise FileNotFoundError(f"Falta: {file}")
def eliminar_archivo_tiempo(ruta, delay=1800):
"""Elimina archivos temporales después de 30 minutos"""
def eliminar():
try:
if os.path.exists(ruta):
os.remove(ruta)
logging.info(f"Archivo eliminado: {ruta}")
except Exception as e:
logging.error(f"Error al eliminar {ruta}: {e}")
Timer(delay, eliminar).start()
def validar_texto(texto):
"""Valida el texto para evitar errores en TTS"""
texto_limpio = texto.strip()
if len(texto_limpio) < 3:
raise gr.Error("⚠️ El texto debe tener al menos 3 caracteres")
if any(c in texto_limpio for c in ["|", "\n", "\r"]):
raise gr.Error("⚠️ Caracteres no permitidos detectados")
async def procesar_audio(texto, voz, duracion_maxima):
"""Genera TTS y lo limita a la duración máxima disponible"""
temp_files = []
try:
validar_texto(texto)
# Generar TTS
communicate = edge_tts.Communicate(texto, voz)
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_tts:
await communicate.save(tmp_tts.name)
tts_audio = AudioFileClip(tmp_tts.name)
temp_files.append(tmp_tts.name)
# Limitar TTS a la duración máxima
if tts_audio.duration > duracion_maxima:
tts_audio = tts_audio.subclip(0, duracion_maxima)
return tts_audio
except Exception as e:
logging.error(f" fallo en audio: {str(e)}")
raise
finally:
for file in temp_files:
try:
os.remove(file)
except Exception as e:
logging.warning(f"Error limpiando {file}: {e}")
def agregar_transiciones(clips):
"""Agrega transiciones visuales cada 40 segundos"""
try:
fx_audio = AudioFileClip(FX_SOUND).subclip(0, 0.5)
watermark = (ImageClip(WATERMARK)
.set_duration(0.5)
.resize(height=50)
.set_pos(("right", "bottom")))
clips_finales = []
for i, clip in enumerate(clips):
clip_watermarked = CompositeVideoClip([clip, watermark])
if i > 0 and i % 40 == 0:
transicion = CompositeVideoClip([watermark.set_duration(0.5)]).set_audio(fx_audio)
clips_finales.append(transicion)
clips_finales.append(clip_watermarked)
return concatenate_videoclips(clips_finales, method="compose")
except Exception as e:
logging.error(f"Error en transiciones: {e}")
return concatenate_videoclips(clips)
async def procesar_video(video_input, texto_tts, voz_seleccionada, metodo_corte, duracion_corte):
try:
# Cargar video original
video_original = VideoFileClip(video_input)
audio_original = video_original.audio.volumex(0.7) if video_original.audio else None
# Cortar video según método
clips = []
if metodo_corte == "manual":
for i in range(math.ceil(video_original.duration / duracion_corte)):
clips.append(video_original.subclip(i*duracion_corte, (i+1)*duracion_corte))
else:
clips = [video_original.subclip(i, min(i+40, video_original.duration))
for i in range(0, math.ceil(video_original.duration), 40)]
# Procesar transiciones visuales
video_editado = agregar_transiciones(clips)
video_editado_duration = video_editado.duration
# Combinar con intro/outro
intro = VideoFileClip(INTRO_VIDEO)
outro = VideoFileClip(OUTRO_VIDEO)
# Música de fondo solo para el video editado
bg_music = AudioSegment.from_mp3(MUSIC_BG)
needed_ms = int(video_editado_duration * 1000)
repeticiones = needed_ms // len(bg_music) + 1
bg_music = bg_music * repeticiones
bg_music = bg_music[:needed_ms].fade_out(5000)
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_bg:
bg_music.export(tmp_bg.name, format="mp3")
bg_audio = AudioFileClip(tmp_bg.name).volumex(0.15)
# Duración máxima para el TTS (después de la intro)
max_tts_time = video_editado_duration
# Procesar TTS
tts_audio = await procesar_audio(texto_tts, voz_seleccionada, max_tts_time)
# Combinar audios para el video editado
audios_editado = [bg_audio]
if audio_original:
audios_editado.append(audio_original.set_duration(video_editado_duration))
audios_editado.append(tts_audio.set_start(0))
audio_editado = CompositeAudioClip(audios_editado).set_duration(video_editado_duration)
video_editado = video_editado.set_audio(audio_editado)
# Concatenar intro, video editado y outro
video_final = concatenate_videoclips([intro, video_editado, outro])
duracion_total = video_final.duration
# Renderizar video final
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp:
video_final.write_videofile(
tmp.name,
codec="libx264",
audio_codec="aac",
fps=24,
threads=4,
verbose=False
)
eliminar_archivo_tiempo(tmp.name)
return tmp.name
except Exception as e:
logging.error(f" fallo general: {str(e)}")
raise
# Interfaz Gradio
with gr.Blocks() as demo:
gr.Markdown("# Editor de Video con IA")
with gr.Tab("Principal"):
video_input = gr.Video(label="Subir video")
texto_tts = gr.Textbox(
label="Texto para TTS",
lines=3,
placeholder="Escribe aquí tu texto..."
)
voz_seleccionada = gr.Dropdown(
label="Voz",
choices=["es-ES-AlvaroNeural", "es-MX-BeatrizNeural"],
value="es-ES-AlvaroNeural"
)
procesar_btn = gr.Button("Generar Video")
video_output = gr.Video(label="Video Procesado")
with gr.Tab("Ajustes"):
metodo_corte = gr.Radio(
["inteligente", "manual"],
label="Método de corte",
value="inteligente"
)
duracion_corte = gr.Slider(
1, 60, 10,
label="Segundos por corte (manual)"
)
with gr.Accordion("Ejemplos de Uso", open=False):
gr.Examples(
examples=[[EJEMPLO_VIDEO, "¡Hola! Esto es una prueba. Suscríbete al canal y activa la campanita."]],
inputs=[video_input, texto_tts],
label="Ejemplos"
)
procesar_btn.click(
procesar_video,
inputs=[video_input, texto_tts, voz_seleccionada, metodo_corte, duracion_corte],
outputs=video_output
)
if __name__ == "__main__":
demo.queue().launch() |