|
import tempfile |
|
import logging |
|
import os |
|
import asyncio |
|
from moviepy.editor import * |
|
import edge_tts |
|
import gradio as gr |
|
from pydub import AudioSegment |
|
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") |
|
|
|
|
|
INTRO_VIDEO = "introvideo.mp4" |
|
OUTRO_VIDEO = "outrovideo.mp4" |
|
MUSIC_BG = "musicafondo.mp3" |
|
FX_GLITCH = "glitch.mp4" |
|
EJEMPLO_VIDEO = "ejemplo.mp4" |
|
|
|
|
|
for file in [INTRO_VIDEO, OUTRO_VIDEO, MUSIC_BG, FX_GLITCH, 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): |
|
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}") |
|
from threading import Timer |
|
Timer(delay, eliminar).start() |
|
|
|
async def procesar_audio(texto, voz, duracion_video): |
|
temp_files = [] |
|
try: |
|
|
|
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) |
|
|
|
|
|
if tts_audio.duration > duracion_video: |
|
tts_audio = tts_audio.subclip(0, duracion_video) |
|
|
|
|
|
bg_music = AudioSegment.from_mp3(MUSIC_BG) |
|
needed_ms = int(duracion_video * 1000) |
|
repeticiones = needed_ms // len(bg_music) + 1 |
|
bg_music = bg_music * repeticiones |
|
bg_music = bg_music[:needed_ms].fade_out(1000) |
|
|
|
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.2) |
|
temp_files.append(tmp_bg.name) |
|
|
|
|
|
audio_final = CompositeAudioClip([ |
|
bg_audio.set_duration(duracion_video), |
|
tts_audio.volumex(0.8).set_start(0) |
|
]).set_duration(duracion_video) |
|
|
|
return audio_final |
|
|
|
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_glitch(video, intervalo=40): |
|
"""Agrega glitch cada X segundos sin alterar el video""" |
|
duracion = video.duration |
|
glitch = VideoFileClip(FX_GLITCH).set_duration(0.5) |
|
|
|
|
|
glitches = [] |
|
for t in range(intervalo, math.ceil(duracion), intervalo): |
|
glitches.append(glitch.set_start(t).set_pos("center")) |
|
|
|
return CompositeVideoClip([video] + glitches) |
|
|
|
async def procesar_video(video_input, texto_tts, voz_seleccionada): |
|
try: |
|
|
|
intro = VideoFileClip(INTRO_VIDEO) |
|
outro = VideoFileClip(OUTRO_VIDEO) |
|
video_original = VideoFileClip(video_input) |
|
|
|
|
|
duracion_video = video_original.duration |
|
|
|
|
|
audio_final = await procesar_audio(texto_tts, voz_seleccionada, duracion_video) |
|
|
|
|
|
video_con_glitch = agregar_glitch(video_original, intervalo=40) |
|
|
|
|
|
video_final = concatenate_videoclips( |
|
[intro, video_con_glitch, outro], |
|
method="chain" |
|
) |
|
|
|
|
|
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 |
|
|
|
|
|
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.Accordion("Ejemplos de Uso", open=False): |
|
gr.Examples( |
|
examples=[[EJEMPLO_VIDEO, "¡Hola! Esto es una prueba. Suscríbete al canal."]], |
|
inputs=[video_input, texto_tts], |
|
label="Ejemplos" |
|
) |
|
|
|
procesar_btn.click( |
|
procesar_video, |
|
inputs=[video_input, texto_tts, voz_seleccionada], |
|
outputs=video_output |
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.queue().launch() |