File size: 4,119 Bytes
4a04dae 8eb6c1b 4a04dae fc4d759 504becd 6d94854 fc4d759 4a04dae 8eb6c1b 4a04dae 8eb6c1b 4a04dae 8eb6c1b 4a04dae eb21acb 8eb6c1b eb21acb 8eb6c1b eb21acb 4a04dae fc4d759 d97f0d8 8eb6c1b fc4d759 8eb6c1b 504becd 8eb6c1b fc4d759 6d94854 63e5b79 6d94854 |
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 |
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"
EJEMPLO_VIDEO = "ejemplo.mp4"
# Validar existencia de archivos
for file in [INTRO_VIDEO, OUTRO_VIDEO, MUSIC_BG, EJEMPLO_VIDEO]:
if not os.path.exists(file):
logging.error(f"Falta archivo necesario: {file}")
raise FileNotFoundError(f"Falta: {file}")
# Configuraci贸n de chunks
CHUNK_SIZE = 60 # 1 minuto por chunk
MAX_CHUNKS = 50
SEGMENT_DURATION = 18 # Duraci贸n de cada segmento
OVERLAP = 2 # Segundos a eliminar entre segmentos
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 generar_tts(texto, voz, duracion_total):
try:
logging.info("Generando 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)
# Asegurar que el TTS no exceda la duraci贸n del video
if tts_audio.duration > duracion_total:
tts_audio = tts_audio.subclip(0, duracion_total)
return tts_audio, tmp_tts.name
except Exception as e:
logging.error(f"Fallo en TTS: {str(e)}")
raise
def crear_musica_fondo(duracion_total):
bg_music = AudioSegment.from_mp3(MUSIC_BG)
needed_ms = int(duracion_total * 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")
return AudioFileClip(tmp_bg.name).volumex(0.15), tmp_bg.name
async def procesar_video(video_input, texto_tts, voz_seleccionada):
temp_files = []
intro, outro, video_original = None, None, None
try:
logging.info("Iniciando procesamiento")
video_original = VideoFileClip(video_input, target_resolution=(720, 1280))
duracion_video = video_original.duration
# Generar TTS y m煤sica de fondo para todo el video
tts_audio, tts_path = await generar_tts(texto_tts, voz_seleccionada, duracion_video)
bg_audio, bg_path = crear_musica_fondo(duracion_video)
temp_files.extend([tts_path, bg_path])
# Combinar audios
audio_original = video_original.audio.volumex(0.7) if video_original.audio else None
audios = [bg_audio.set_duration(duracion_video)]
if audio_original:
audios.append(audio_original)
audios.append(tts_audio.set_start(0).volumex(0.85))
audio_final = CompositeAudioClip(audios).set_duration(duracion_video)
# Dividir video en segmentos con cortes de 2 segundos
segments = []
current_time = 0
while current_time < duracion_video:
end_time = current_time + SEGMENT_DURATION
if end_time > duracion_video:
break # Terminar si ya no hay suficiente tiempo
# Extraer segmento eliminando 2 segundos al final
full_segment = video_original.subclip(current_time, end_time)
if segments and full_segment.duration >= OVERLAP:
full_segment = full_segment.subclip(0, full_segment.duration - OVERLAP)
segments.append(full_segment)
current_time += (SEGMENT_DURATION - OVERLAP)
# Aseg |