Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,289 +3,447 @@ import asyncio
|
|
| 3 |
import logging
|
| 4 |
import tempfile
|
| 5 |
import requests
|
| 6 |
-
import
|
| 7 |
-
import math
|
| 8 |
import edge_tts
|
| 9 |
import gradio as gr
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
| 11 |
import subprocess
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
# Configuración básica de logging
|
| 14 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
def
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
"un", "una", "con", "se", "del", "al", "lo", "como", "para", "su", "sus"
|
| 32 |
-
}
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
| 43 |
|
| 44 |
-
def
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
return []
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
for
|
|
|
|
| 53 |
try:
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
params = {
|
| 56 |
"query": query,
|
| 57 |
-
"per_page":
|
| 58 |
"orientation": "landscape",
|
| 59 |
-
"
|
| 60 |
}
|
| 61 |
|
| 62 |
-
response = requests.get(
|
| 63 |
-
|
| 64 |
-
headers=headers,
|
| 65 |
-
params=params,
|
| 66 |
-
timeout=20
|
| 67 |
-
)
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
for
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
except Exception as e:
|
| 86 |
-
logger.error(f"Error
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
| 89 |
|
| 90 |
-
|
| 91 |
-
"
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
-
def download_video(url, temp_dir):
|
| 102 |
-
"""Descarga videos con manejo robusto de errores"""
|
| 103 |
try:
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
logger.error(f"Error descargando video: {str(e)}")
|
| 119 |
-
return None
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
# 2. Preparar comando FFmpeg
|
| 131 |
-
cmd = [
|
| 132 |
-
"ffmpeg", "-y",
|
| 133 |
-
"-f", "concat",
|
| 134 |
-
"-safe", "0",
|
| 135 |
-
"-i", list_file_path,
|
| 136 |
-
"-i", audio_path,
|
| 137 |
-
"-c:v", "libx264", # Codificar video en lugar de copiar
|
| 138 |
-
"-preset", "fast",
|
| 139 |
-
"-crf", "23",
|
| 140 |
-
"-c:a", "aac",
|
| 141 |
-
"-b:a", "192k",
|
| 142 |
-
"-shortest",
|
| 143 |
-
"-movflags", "+faststart",
|
| 144 |
-
output_path
|
| 145 |
-
]
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
except Exception as e:
|
| 164 |
-
logger.error(f"Error
|
| 165 |
-
|
| 166 |
finally:
|
| 167 |
-
|
| 168 |
-
if os.path.exists(
|
| 169 |
-
os.
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
logger.info(f"Directorio temporal creado: {temp_dir}")
|
| 177 |
-
|
| 178 |
-
try:
|
| 179 |
-
# 1. Generar audio TTS
|
| 180 |
-
tts_path = os.path.join(temp_dir, "audio.mp3")
|
| 181 |
-
if not await generate_tts(text, tts_path):
|
| 182 |
-
return None, "❌ Error generando voz"
|
| 183 |
-
|
| 184 |
-
# 2. Extraer palabras clave
|
| 185 |
-
keywords = extract_keywords(text)
|
| 186 |
-
if not keywords:
|
| 187 |
-
return None, "❌ No se pudieron extraer palabras clave del texto"
|
| 188 |
-
logger.info(f"Palabras clave identificadas: {keywords}")
|
| 189 |
-
|
| 190 |
-
# 3. Buscar y descargar videos
|
| 191 |
-
video_urls = search_pexels_videos(keywords)
|
| 192 |
-
if not video_urls:
|
| 193 |
-
return None, "❌ No se encontraron videos para las palabras clave"
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
except Exception as e:
|
| 212 |
-
logger.
|
| 213 |
-
return None, f"
|
| 214 |
-
finally:
|
| 215 |
-
# Espacios maneja la limpieza automática
|
| 216 |
-
pass
|
| 217 |
|
| 218 |
-
|
| 219 |
-
with gr.Blocks(title="Generador Automático de Videos", theme=gr.themes.Soft(), css=".gradio-container {max-width: 800px}") as demo:
|
| 220 |
gr.Markdown("""
|
| 221 |
-
|
| 222 |
-
|
| 223 |
""")
|
| 224 |
|
| 225 |
-
with gr.
|
| 226 |
-
with gr.
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
max_lines=10
|
| 232 |
)
|
| 233 |
-
generate_btn = gr.Button("✨ Generar Video", variant="primary")
|
| 234 |
-
|
| 235 |
-
with gr.Accordion("Configuración avanzada", open=False):
|
| 236 |
-
voice_select = gr.Dropdown(
|
| 237 |
-
["es-ES-ElviraNeural", "es-MX-DaliaNeural", "es-US-AlonsoNeural"],
|
| 238 |
-
label="Voz",
|
| 239 |
-
value="es-ES-ElviraNeural"
|
| 240 |
-
)
|
| 241 |
|
| 242 |
-
with gr.Column(
|
| 243 |
-
|
| 244 |
-
label="
|
| 245 |
-
|
| 246 |
-
|
| 247 |
)
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
|
|
|
| 253 |
)
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
queue=False
|
| 259 |
).then(
|
| 260 |
-
fn=
|
| 261 |
-
inputs=[
|
| 262 |
-
outputs=[
|
| 263 |
-
)
|
| 264 |
-
|
| 265 |
-
gr.Markdown("### Instrucciones:")
|
| 266 |
-
gr.Markdown("""
|
| 267 |
-
1. Describe el video que deseas crear (mínimo 20 palabras)
|
| 268 |
-
2. Haz clic en "Generar Video"
|
| 269 |
-
3. El sistema buscará videos relevantes en Pexels
|
| 270 |
-
4. Creará un video con narración automática
|
| 271 |
-
""")
|
| 272 |
-
|
| 273 |
-
gr.Markdown("### Ejemplos:")
|
| 274 |
-
examples = gr.Examples(
|
| 275 |
-
examples=[
|
| 276 |
-
["Un atardecer en la playa con palmeras y olas suaves"],
|
| 277 |
-
["Un bosque otoñal con hojas de colores y senderos naturales"],
|
| 278 |
-
["La ciudad de noche con rascacielos iluminados y tráfico"]
|
| 279 |
-
],
|
| 280 |
-
inputs=[text_input],
|
| 281 |
-
label="Ejemplos para probar"
|
| 282 |
)
|
| 283 |
|
| 284 |
-
|
|
|
|
|
|
|
|
|
|
| 285 |
if __name__ == "__main__":
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
server_port=7860,
|
| 289 |
-
share=False,
|
| 290 |
-
show_error=True
|
| 291 |
-
)
|
|
|
|
| 3 |
import logging
|
| 4 |
import tempfile
|
| 5 |
import requests
|
| 6 |
+
from datetime import datetime
|
|
|
|
| 7 |
import edge_tts
|
| 8 |
import gradio as gr
|
| 9 |
+
import torch
|
| 10 |
+
from transformers import GPT2Tokenizer, GPT2LMHeadModel
|
| 11 |
+
from keybert import KeyBERT
|
| 12 |
+
from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip
|
| 13 |
import subprocess
|
| 14 |
+
import re
|
| 15 |
+
import math
|
| 16 |
+
from pydub import AudioSegment
|
| 17 |
|
|
|
|
| 18 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
| 21 |
+
PEXELS_API_KEY = os.environ.get("PEXELS_API_KEY")
|
| 22 |
+
|
| 23 |
+
MODEL_NAME = "gpt2"
|
| 24 |
+
try:
|
| 25 |
+
tokenizer = GPT2Tokenizer.from_pretrained(MODEL_NAME)
|
| 26 |
+
model = GPT2LMHeadModel.from_pretrained(MODEL_NAME).eval()
|
| 27 |
+
if tokenizer.pad_token is None:
|
| 28 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 29 |
+
logger.info(f"Modelo GPT-2 '{MODEL_NAME}' cargado exitosamente.")
|
| 30 |
+
except Exception as e:
|
| 31 |
+
logger.error(f"Error al cargar el modelo GPT-2 '{MODEL_NAME}': {e}")
|
| 32 |
+
tokenizer = None
|
| 33 |
+
model = None
|
| 34 |
|
| 35 |
+
try:
|
| 36 |
+
kw_model = KeyBERT('multi-qa-MiniLM-L6-cos-v1')
|
| 37 |
+
logger.info("Modelo KeyBERT cargado exitosamente.")
|
| 38 |
+
except Exception as e:
|
| 39 |
+
logger.error(f"Error al cargar el modelo KeyBERT: {e}")
|
| 40 |
+
kw_model = None
|
| 41 |
|
| 42 |
+
def generate_script(prompt, max_length=250):
|
| 43 |
+
if not tokenizer or not model:
|
| 44 |
+
logger.error("Modelo GPT-2 no disponible para generar guion.")
|
| 45 |
+
return "Lo siento, el generador de guiones no está disponible en este momento."
|
| 46 |
+
|
| 47 |
+
logger.info("Generando guion con GPT-2...")
|
| 48 |
+
try:
|
| 49 |
+
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
|
| 50 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 51 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 52 |
+
model.to(device)
|
| 53 |
+
|
| 54 |
+
with torch.no_grad():
|
| 55 |
+
outputs = model.generate(
|
| 56 |
+
**inputs,
|
| 57 |
+
max_length=max_length,
|
| 58 |
+
do_sample=True,
|
| 59 |
+
top_p=0.95,
|
| 60 |
+
top_k=60,
|
| 61 |
+
temperature=0.9,
|
| 62 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 63 |
+
eos_token_id=tokenizer.eos_token_id
|
| 64 |
+
)
|
| 65 |
+
text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 66 |
+
logger.info(f"Guion generado (longitud: {len(text)} caracteres): {text[:200]}...")
|
| 67 |
+
return text
|
| 68 |
+
except Exception as e:
|
| 69 |
+
logger.error(f"Error durante la generación del guion: {e}")
|
| 70 |
+
return "No se pudo generar el guion. Intenta con otro prompt o un guion propio."
|
| 71 |
+
|
| 72 |
+
async def text_to_speech(text, voice="es-ES-ElviraNeural", output_path="voz.mp3"):
|
| 73 |
+
logger.info(f"Generando audio TTS para: '{text[:100]}...'")
|
| 74 |
+
try:
|
| 75 |
+
communicate = edge_tts.Communicate(text, voice)
|
| 76 |
+
await communicate.save(output_path)
|
| 77 |
+
logger.info(f"Audio TTS guardado en {output_path}")
|
| 78 |
+
except Exception as e:
|
| 79 |
+
logger.error(f"Error al generar audio TTS: {e}")
|
| 80 |
+
raise
|
| 81 |
+
|
| 82 |
+
def download_video_file(url, temp_dir):
|
| 83 |
+
if not url:
|
| 84 |
+
return None
|
| 85 |
|
| 86 |
+
file_name = url.split('/')[-1].split('?')[0]
|
| 87 |
+
if not file_name.endswith('.mp4'):
|
| 88 |
+
file_name = f"video_temp_{os.getpid()}_{datetime.now().strftime('%f')}.mp4"
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
output_path = os.path.join(temp_dir, file_name)
|
| 91 |
+
logger.info(f"Intentando descargar video de: {url} a {output_path}")
|
| 92 |
+
try:
|
| 93 |
+
response = requests.get(url, stream=True, timeout=30)
|
| 94 |
+
response.raise_for_status()
|
| 95 |
+
|
| 96 |
+
with open(output_path, 'wb') as f:
|
| 97 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 98 |
+
if chunk:
|
| 99 |
+
f.write(chunk)
|
| 100 |
+
logger.info(f"Video descargado a: {output_path}")
|
| 101 |
+
return output_path
|
| 102 |
+
except requests.exceptions.RequestException as e:
|
| 103 |
+
logger.error(f"Error de red/HTTP al descargar el video {url}: {e}")
|
| 104 |
+
if os.path.exists(output_path):
|
| 105 |
+
os.remove(output_path)
|
| 106 |
+
return None
|
| 107 |
+
except Exception as e:
|
| 108 |
+
logger.error(f"Error inesperado al descargar video {url}: {e}")
|
| 109 |
+
if os.path.exists(output_path):
|
| 110 |
+
os.remove(output_path)
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
def loop_audio_to_length(audio_clip, target_duration):
|
| 114 |
+
if audio_clip.duration >= target_duration:
|
| 115 |
+
return audio_clip.subclip(0, target_duration)
|
| 116 |
|
| 117 |
+
loops = int(target_duration / audio_clip.duration) + 1
|
| 118 |
+
audios = [audio_clip] * loops
|
| 119 |
+
concatenated = concatenate_videoclips(audios)
|
| 120 |
+
return concatenated.subclip(0, target_duration)
|
| 121 |
|
| 122 |
+
def extract_visual_keywords_from_script(script_text, max_keywords_per_segment=2):
|
| 123 |
+
if not kw_model:
|
| 124 |
+
logger.warning("Modelo KeyBERT no disponible. La extracción de palabras clave será limitada.")
|
| 125 |
+
return [script_text.split('.')[0].strip().replace(" ", "+")] if script_text.strip() else []
|
| 126 |
+
|
| 127 |
+
logger.info("Extrayendo palabras clave visuales del guion.")
|
| 128 |
|
| 129 |
+
segments = [s.strip() for s in script_text.split('\n') if s.strip()]
|
| 130 |
+
if not segments:
|
| 131 |
+
segments = [script_text]
|
| 132 |
+
|
| 133 |
+
all_keywords = set()
|
| 134 |
|
| 135 |
+
for segment in segments:
|
| 136 |
+
if not segment: continue
|
| 137 |
try:
|
| 138 |
+
keywords_with_scores = kw_model.extract_keywords(
|
| 139 |
+
segment,
|
| 140 |
+
keyphrase_ngram_range=(1, 2),
|
| 141 |
+
stop_words='spanish',
|
| 142 |
+
top_n=max_keywords_per_segment,
|
| 143 |
+
use_mmr=True,
|
| 144 |
+
diversity=0.7
|
| 145 |
+
)
|
| 146 |
+
for kw, score in keywords_with_scores:
|
| 147 |
+
all_keywords.add(kw.replace(" ", "+"))
|
| 148 |
+
except Exception as e:
|
| 149 |
+
logger.warning(f"Error al extraer palabras clave de un segmento: {e}")
|
| 150 |
+
all_keywords.add(segment.split(' ')[0].strip().replace(" ", "+"))
|
| 151 |
+
|
| 152 |
+
logger.info(f"Palabras clave visuales extraídas del guion: {list(all_keywords)}")
|
| 153 |
+
return list(all_keywords)
|
| 154 |
+
|
| 155 |
+
def search_pexels_videos(query_list, num_videos_per_query=5, min_duration_sec=7):
|
| 156 |
+
if not PEXELS_API_KEY:
|
| 157 |
+
logger.error("ERROR: PEXELS_API_KEY no está configurada. No se pueden buscar videos en Pexels.")
|
| 158 |
+
raise ValueError("PEXELS_API_KEY no está configurada. Por favor, configúrala como un secreto en Hugging Face Spaces.")
|
| 159 |
+
|
| 160 |
+
if not query_list:
|
| 161 |
+
logger.warning("Lista de queries para Pexels vacía. No se buscarán videos.")
|
| 162 |
+
return []
|
| 163 |
+
|
| 164 |
+
all_video_urls = set()
|
| 165 |
+
|
| 166 |
+
for query in query_list:
|
| 167 |
+
logger.info(f"Buscando {num_videos_per_query} videos en Pexels para la query: '{query}'")
|
| 168 |
+
try:
|
| 169 |
+
api_url = "https://api.pexels.com/videos/search"
|
| 170 |
+
headers = {"Authorization": PEXELS_API_KEY}
|
| 171 |
params = {
|
| 172 |
"query": query,
|
| 173 |
+
"per_page": num_videos_per_query * 2,
|
| 174 |
"orientation": "landscape",
|
| 175 |
+
"min_duration": min_duration_sec
|
| 176 |
}
|
| 177 |
|
| 178 |
+
response = requests.get(api_url, headers=headers, params=params, timeout=15)
|
| 179 |
+
response.raise_for_status()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
+
data = response.json()
|
| 182 |
+
videos = data.get('videos', [])
|
| 183 |
+
|
| 184 |
+
if not videos:
|
| 185 |
+
logger.info(f"No se encontraron videos en Pexels para la query: '{query}'")
|
| 186 |
+
continue
|
| 187 |
+
|
| 188 |
+
for video in videos:
|
| 189 |
+
best_quality_url = None
|
| 190 |
+
video_files = sorted(video.get('video_files', []), key=lambda x: x.get('width', 0) * x.get('height', 0), reverse=True)
|
| 191 |
|
| 192 |
+
for file in video_files:
|
| 193 |
+
if file.get('link'):
|
| 194 |
+
best_quality_url = file['link']
|
| 195 |
+
break
|
| 196 |
+
|
| 197 |
+
if best_quality_url:
|
| 198 |
+
all_video_urls.add(best_quality_url)
|
| 199 |
+
else:
|
| 200 |
+
logger.warning(f"No se encontró URL de descarga válida para el video Pexels ID: {video.get('id')}")
|
| 201 |
+
|
| 202 |
+
except requests.exceptions.RequestException as e:
|
| 203 |
+
logger.error(f"Error de HTTP/red al buscar videos en Pexels para '{query}': {e}", exc_info=True)
|
| 204 |
except Exception as e:
|
| 205 |
+
logger.error(f"Error inesperado al buscar videos en Pexels para '{query}': {e}", exc_info=True)
|
| 206 |
+
|
| 207 |
+
final_urls = list(all_video_urls)
|
| 208 |
+
logger.info(f"Total de {len(final_urls)} URLs de video únicas obtenidas de Pexels.")
|
| 209 |
+
return final_urls
|
| 210 |
|
| 211 |
+
def crear_video(prompt_type, input_text, musica_url=None):
|
| 212 |
+
logger.info(f"Iniciando creación de video. Tipo de prompt: {prompt_type}")
|
| 213 |
+
guion = ""
|
| 214 |
+
if prompt_type == "Generar Guion con IA":
|
| 215 |
+
guion = generate_script(input_text)
|
| 216 |
+
if not guion or guion == "No se pudo generar el guion. Intenta con otro prompt o un guion propio.":
|
| 217 |
+
raise ValueError(guion)
|
| 218 |
+
else:
|
| 219 |
+
guion = input_text
|
| 220 |
+
if not guion.strip():
|
| 221 |
+
raise ValueError("Por favor, introduce tu guion.")
|
| 222 |
+
|
| 223 |
+
if not guion.strip():
|
| 224 |
+
raise ValueError("El guion está vacío. No se puede proceder.")
|
| 225 |
+
|
| 226 |
+
temp_files = []
|
| 227 |
+
downloaded_clip_paths = []
|
| 228 |
+
final_clips = []
|
| 229 |
+
|
| 230 |
+
temp_video_dir = tempfile.mkdtemp()
|
| 231 |
+
temp_files.append(temp_video_dir)
|
| 232 |
|
|
|
|
|
|
|
| 233 |
try:
|
| 234 |
+
voz_archivo = os.path.join(tempfile.gettempdir(), f"voz_temp_{os.getpid()}.mp3")
|
| 235 |
+
temp_files.append(voz_archivo)
|
| 236 |
+
asyncio.run(text_to_speech(guion, output_path=voz_archivo))
|
| 237 |
+
audio_tts = AudioFileClip(voz_archivo)
|
| 238 |
+
|
| 239 |
+
search_queries_for_pexels = extract_visual_keywords_from_script(guion, max_keywords_per_segment=2)
|
| 240 |
+
|
| 241 |
+
if not search_queries_for_pexels:
|
| 242 |
+
raise ValueError("No se pudieron extraer palabras clave visuales del guion para buscar videos.")
|
| 243 |
+
|
| 244 |
+
pexels_video_urls_found = search_pexels_videos(search_queries_for_pexels, num_videos_per_query=5, min_duration_sec=7)
|
| 245 |
+
|
| 246 |
+
if not pexels_video_urls_found:
|
| 247 |
+
logger.error("Pexels no devolvió ningún video para las palabras clave extraídas.")
|
| 248 |
+
raise ValueError(f"Pexels no encontró videos adecuados para el guion. Intenta con otro tema o guion más descriptivo. Palabras clave usadas: {search_queries_for_pexels}")
|
| 249 |
+
|
| 250 |
+
logger.info(f"Descargando {len(pexels_video_urls_found)} videos de Pexels...")
|
| 251 |
+
for url in pexels_video_urls_found:
|
| 252 |
+
video_path = download_video_file(url, temp_video_dir)
|
| 253 |
+
if video_path:
|
| 254 |
+
downloaded_clip_paths.append(video_path)
|
| 255 |
+
else:
|
| 256 |
+
logger.warning(f"No se pudo descargar video de Pexels: {url}")
|
| 257 |
|
| 258 |
+
if not downloaded_clip_paths:
|
| 259 |
+
logger.error("No se pudo descargar ningún video válido de Pexels.")
|
| 260 |
+
raise ValueError("No se pudo descargar ningún video válido de Pexels. Revisa la conexión o la calidad de las URLs.")
|
| 261 |
+
|
| 262 |
+
total_desired_video_duration = audio_tts.duration * 1.2
|
| 263 |
+
current_video_clips_duration = 0
|
| 264 |
|
| 265 |
+
for path in downloaded_clip_paths:
|
| 266 |
+
try:
|
| 267 |
+
clip = VideoFileClip(path)
|
| 268 |
+
clip_duration = min(clip.duration, 10)
|
| 269 |
+
if clip_duration > 1:
|
| 270 |
+
final_clips.append(clip.subclip(0, clip_duration))
|
| 271 |
+
current_video_clips_duration += clip_duration
|
| 272 |
+
if current_video_clips_duration >= total_desired_video_duration:
|
| 273 |
+
break
|
| 274 |
+
else:
|
| 275 |
+
logger.warning(f"Clip de video muy corto ({clip_duration:.2f}s) de {path}, omitiendo.")
|
| 276 |
+
clip.close()
|
| 277 |
+
except Exception as e:
|
| 278 |
+
logger.warning(f"No se pudo cargar o procesar el clip de video {path}: {e}. Omitiendo.")
|
| 279 |
+
if 'clip' in locals() and clip: clip.close()
|
| 280 |
|
| 281 |
+
if not final_clips:
|
| 282 |
+
logger.error("No se pudo obtener ningún clip de video usable después de la descarga y procesamiento.")
|
| 283 |
+
raise ValueError("No se pudieron procesar los videos descargados de Pexels.")
|
|
|
|
|
|
|
| 284 |
|
| 285 |
+
video_base = concatenate_videoclips(final_clips, method="compose")
|
| 286 |
+
logger.info(f"Video base concatenado, duración: {video_base.duration:.2f}s")
|
| 287 |
+
|
| 288 |
+
if video_base.duration < audio_tts.duration:
|
| 289 |
+
logger.info(f"Duración del video ({video_base.duration:.2f}s) es menor que la del audio TTS ({audio_tts.duration:.2f}s). Repitiendo video.")
|
| 290 |
+
num_repeats = int(audio_tts.duration / video_base.duration) + 1
|
| 291 |
+
repeated_clips = [video_base] * num_repeats
|
| 292 |
+
video_base = concatenate_videoclips(repeated_clips, method="compose")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
|
| 294 |
+
final_video_duration = audio_tts.duration
|
| 295 |
+
|
| 296 |
+
mezcla_audio = audio_tts
|
| 297 |
+
if musica_url and musica_url.strip():
|
| 298 |
+
musica_path = download_video_file(musica_url, temp_video_dir)
|
| 299 |
+
if musica_path:
|
| 300 |
+
temp_files.append(musica_path)
|
| 301 |
+
try:
|
| 302 |
+
musica_audio = AudioFileClip(musica_path)
|
| 303 |
+
musica_loop = loop_audio_to_length(musica_audio, final_video_duration)
|
| 304 |
+
mezcla_audio = CompositeAudioClip([musica_loop.volumex(0.3), audio_tts.set_duration(final_video_duration).volumex(1.0)])
|
| 305 |
+
logger.info("Música de fondo añadida y mezclada.")
|
| 306 |
+
except Exception as e:
|
| 307 |
+
logger.warning(f"No se pudo procesar la música de fondo de {musica_url}: {e}. Se usará solo la voz.")
|
| 308 |
+
else:
|
| 309 |
+
logger.warning(f"No se pudo descargar la música de {musica_url}. Se usará solo la voz.")
|
| 310 |
|
| 311 |
+
video_final = video_base.set_audio(mezcla_audio).subclip(0, final_video_duration)
|
| 312 |
+
logger.info(f"Video final configurado con audio. Duración final: {video_final.duration:.2f}s")
|
| 313 |
+
|
| 314 |
+
output_dir = "generated_videos"
|
| 315 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 316 |
+
output_path = os.path.join(output_dir, f"video_output_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4")
|
| 317 |
+
logger.info(f"Escribiendo video final a: {output_path}")
|
| 318 |
|
| 319 |
+
video_final.write_videofile(
|
| 320 |
+
output_path,
|
| 321 |
+
fps=24,
|
| 322 |
+
threads=4,
|
| 323 |
+
logger=None,
|
| 324 |
+
preset="medium",
|
| 325 |
+
codec="libx264",
|
| 326 |
+
audio_codec="aac",
|
| 327 |
+
ffmpeg_params=["-movflags", "+faststart"]
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
logger.info(f"Video generado exitosamente en: {output_path}")
|
| 331 |
+
return output_path
|
| 332 |
+
|
| 333 |
except Exception as e:
|
| 334 |
+
logger.error(f"Error general en la creación del video: {e}", exc_info=True)
|
| 335 |
+
raise e
|
| 336 |
finally:
|
| 337 |
+
for f in temp_files:
|
| 338 |
+
if os.path.exists(f):
|
| 339 |
+
if os.path.isdir(f):
|
| 340 |
+
import shutil
|
| 341 |
+
shutil.rmtree(f)
|
| 342 |
+
logger.info(f"Directorio temporal eliminado: {f}")
|
| 343 |
+
else:
|
| 344 |
+
os.remove(f)
|
| 345 |
+
logger.info(f"Archivo temporal eliminado: {f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
|
| 347 |
+
for clip in final_clips:
|
| 348 |
+
if clip and hasattr(clip, 'close') and not clip.is_playing:
|
| 349 |
+
clip.close()
|
| 350 |
+
if 'audio_tts' in locals() and audio_tts and hasattr(audio_tts, 'close') and not audio_tts.is_playing:
|
| 351 |
+
audio_tts.close()
|
| 352 |
+
if 'musica_audio' in locals() and musica_audio and hasattr(musica_audio, 'close') and not musica_audio.is_playing:
|
| 353 |
+
musica_audio.close()
|
| 354 |
+
if 'video_final' in locals() and video_final and hasattr(video_final, 'close') and not video_final.is_playing:
|
| 355 |
+
video_final.close()
|
| 356 |
+
if 'video_base' in locals() and video_base and hasattr(video_base, 'close') and not video_base.is_playing:
|
| 357 |
+
video_base.close()
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def run_app(prompt_type, prompt_ia, prompt_manual, musica_url):
|
| 361 |
+
input_text = ""
|
| 362 |
+
if prompt_type == "Generar Guion con IA":
|
| 363 |
+
input_text = prompt_ia
|
| 364 |
+
if not input_text.strip():
|
| 365 |
+
raise gr.Error("Por favor, introduce un tema para generar el guion.")
|
| 366 |
+
else:
|
| 367 |
+
input_text = prompt_manual
|
| 368 |
+
if not input_text.strip():
|
| 369 |
+
raise gr.Error("Por favor, introduce tu guion.")
|
| 370 |
+
|
| 371 |
+
logger.info(f"Solicitud recibida: Tipo='{prompt_type}', Input='{input_text[:50]}...', Música='{musica_url}'")
|
| 372 |
+
|
| 373 |
+
try:
|
| 374 |
+
video_path = crear_video(prompt_type, input_text, musica_url if musica_url.strip() else None)
|
| 375 |
+
if video_path:
|
| 376 |
+
logger.info(f"Proceso completado. Video disponible en: {video_path}")
|
| 377 |
+
return video_path, gr.update(value="¡Video generado exitosamente!")
|
| 378 |
+
else:
|
| 379 |
+
raise gr.Error("Hubo un problema desconocido al generar el video. Revisa los logs.")
|
| 380 |
+
except ValueError as ve:
|
| 381 |
+
logger.error(f"Error de validación o búsqueda de Pexels: {ve}")
|
| 382 |
+
return None, gr.update(value=f"Error: {ve}", text_color="red")
|
| 383 |
except Exception as e:
|
| 384 |
+
logger.error(f"Error inesperado al ejecutar la aplicación: {e}", exc_info=True)
|
| 385 |
+
return None, gr.update(value=f"Ocurrió un error grave: {e}. Por favor, inténtalo de nuevo.", text_color="red")
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
+
with gr.Blocks() as app:
|
|
|
|
| 388 |
gr.Markdown("""
|
| 389 |
+
### 🎬 Generador de Video Inteligente con Pexels 🚀
|
| 390 |
+
Crea videos con guiones generados por IA o propios, voz automática y **videos de stock relevantes de Pexels**.
|
| 391 |
""")
|
| 392 |
|
| 393 |
+
with gr.Tab("Generar Video"):
|
| 394 |
+
with gr.Row():
|
| 395 |
+
prompt_type = gr.Radio(
|
| 396 |
+
["Generar Guion con IA", "Usar Mi Guion"],
|
| 397 |
+
label="Método de Guion",
|
| 398 |
+
value="Generar Guion con IA"
|
|
|
|
| 399 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
|
| 401 |
+
with gr.Column(visible=True) as ia_guion_column:
|
| 402 |
+
prompt_ia = gr.Textbox(
|
| 403 |
+
label="Tema para Generar Guion (con IA)",
|
| 404 |
+
lines=2,
|
| 405 |
+
placeholder="Ej: Las maravillas del universo y las estrellas."
|
| 406 |
)
|
| 407 |
+
|
| 408 |
+
with gr.Column(visible=False) as manual_guion_column:
|
| 409 |
+
prompt_manual = gr.Textbox(
|
| 410 |
+
label="Introduce Tu Guion Propio",
|
| 411 |
+
lines=5,
|
| 412 |
+
placeholder="Ej: Hola a todos, hoy hablaremos de un tema fascinante..."
|
| 413 |
)
|
| 414 |
+
|
| 415 |
+
musica_input = gr.Textbox(
|
| 416 |
+
label="URL de Música de Fondo (opcional, MP3 recomendado)",
|
| 417 |
+
placeholder="Ej: https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
boton = gr.Button("✨ Generar Video")
|
| 421 |
+
|
| 422 |
+
with gr.Column():
|
| 423 |
+
salida_video = gr.Video(label="Video Generado", interactive=False)
|
| 424 |
+
estado_mensaje = gr.Textbox(label="Estado del Proceso", interactive=False, value="")
|
| 425 |
+
|
| 426 |
+
prompt_type.change(
|
| 427 |
+
fn=lambda value: (gr.update(visible=value == "Generar Guion con IA"),
|
| 428 |
+
gr.update(visible=value == "Usar Mi Guion")),
|
| 429 |
+
inputs=prompt_type,
|
| 430 |
+
outputs=[ia_guion_column, manual_guion_column]
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
boton.click(
|
| 434 |
+
fn=lambda: (None, gr.update(value="Iniciando generación... Esto puede tardar varios minutos (descarga de videos).")),
|
| 435 |
+
outputs=[salida_video, estado_mensaje],
|
| 436 |
queue=False
|
| 437 |
).then(
|
| 438 |
+
fn=run_app,
|
| 439 |
+
inputs=[prompt_type, prompt_ia, prompt_manual, musica_input],
|
| 440 |
+
outputs=[salida_video, estado_mensaje]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 441 |
)
|
| 442 |
|
| 443 |
+
prompt_ia.change(fn=lambda: gr.update(value=""), outputs=estado_mensaje, queue=False)
|
| 444 |
+
prompt_manual.change(fn=lambda: gr.update(value=""), outputs=estado_mensaje, queue=False)
|
| 445 |
+
musica_input.change(fn=lambda: gr.update(value=""), outputs=estado_mensaje, queue=False)
|
| 446 |
+
|
| 447 |
if __name__ == "__main__":
|
| 448 |
+
logger.info("Iniciando aplicación Gradio para Hugging Face Spaces...")
|
| 449 |
+
app.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
|
|
|
|
|
|
|
|
|
|
|