Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,436 +14,153 @@ 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
|
| 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
|
| 40 |
kw_model = None
|
| 41 |
|
| 42 |
-
|
|
|
|
| 43 |
if not tokenizer or not model:
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
logger.info("Generando guion con GPT-2...")
|
| 48 |
try:
|
| 49 |
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
|
| 50 |
-
|
| 51 |
-
|
| 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
|
| 70 |
-
return "
|
| 71 |
|
| 72 |
-
async def text_to_speech(text, voice="es-ES-ElviraNeural"
|
| 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 |
-
|
| 78 |
except Exception as e:
|
| 79 |
-
logger.error(f"Error
|
| 80 |
-
|
| 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,
|
| 156 |
if not PEXELS_API_KEY:
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 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 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 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
|
| 206 |
-
|
| 207 |
-
|
| 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 |
-
|
| 235 |
-
|
| 236 |
-
|
| 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 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
logger.
|
| 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 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 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 |
-
|
| 312 |
-
|
| 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 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
threads=4,
|
| 323 |
-
logger=None,
|
| 324 |
-
preset="medium",
|
| 325 |
codec="libx264",
|
| 326 |
audio_codec="aac",
|
| 327 |
-
|
| 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
|
| 335 |
-
|
| 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.
|
| 389 |
-
|
| 390 |
-
|
| 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 |
-
|
| 424 |
-
|
| 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 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 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 |
-
|
| 449 |
-
app.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
|
|
|
| 14 |
import re
|
| 15 |
import math
|
| 16 |
from pydub import AudioSegment
|
| 17 |
+
from pexelsapi.pexels import Pexels
|
| 18 |
|
| 19 |
+
# Configuración inicial
|
| 20 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
| 23 |
+
PEXELS_API_KEY = os.environ.get("PEXELS_API_KEY")
|
| 24 |
|
| 25 |
+
# Inicialización de modelos
|
| 26 |
MODEL_NAME = "gpt2"
|
| 27 |
try:
|
| 28 |
tokenizer = GPT2Tokenizer.from_pretrained(MODEL_NAME)
|
| 29 |
model = GPT2LMHeadModel.from_pretrained(MODEL_NAME).eval()
|
| 30 |
if tokenizer.pad_token is None:
|
| 31 |
tokenizer.pad_token = tokenizer.eos_token
|
|
|
|
| 32 |
except Exception as e:
|
| 33 |
+
logger.error(f"Error al cargar modelo GPT-2: {e}")
|
| 34 |
+
tokenizer = model = None
|
|
|
|
| 35 |
|
| 36 |
try:
|
| 37 |
+
kw_model = KeyBERT('multi-qa-MiniLM-L6-cos-v1')
|
|
|
|
| 38 |
except Exception as e:
|
| 39 |
+
logger.error(f"Error al cargar KeyBERT: {e}")
|
| 40 |
kw_model = None
|
| 41 |
|
| 42 |
+
# Funciones principales
|
| 43 |
+
def generate_script(prompt, max_length=250):
|
| 44 |
if not tokenizer or not model:
|
| 45 |
+
return "Error: Modelo no disponible"
|
| 46 |
+
|
|
|
|
|
|
|
| 47 |
try:
|
| 48 |
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
|
| 49 |
+
outputs = model.generate(**inputs, max_length=max_length)
|
| 50 |
+
return tokenizer.decode(outputs[0], skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
except Exception as e:
|
| 52 |
+
logger.error(f"Error generando guión: {e}")
|
| 53 |
+
return "Error al generar guión"
|
| 54 |
|
| 55 |
+
async def text_to_speech(text, output_path, voice="es-ES-ElviraNeural"):
|
|
|
|
| 56 |
try:
|
| 57 |
communicate = edge_tts.Communicate(text, voice)
|
| 58 |
await communicate.save(output_path)
|
| 59 |
+
return True
|
| 60 |
except Exception as e:
|
| 61 |
+
logger.error(f"Error en TTS: {e}")
|
| 62 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
+
def search_pexels_videos(query_list, num_videos=3):
|
| 65 |
if not PEXELS_API_KEY:
|
| 66 |
+
raise ValueError("API key no configurada")
|
| 67 |
+
|
| 68 |
+
pexel = Pexels(PEXELS_API_KEY)
|
| 69 |
+
video_urls = []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
for query in query_list:
|
|
|
|
| 72 |
try:
|
| 73 |
+
results = pexel.search_videos(query=query, per_page=num_videos)
|
| 74 |
+
for video in results.get('videos', []):
|
| 75 |
+
best = max(video['video_files'], key=lambda x: x['width']*x['height'])
|
| 76 |
+
video_urls.append(best['link'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
except Exception as e:
|
| 78 |
+
logger.error(f"Error buscando videos: {e}")
|
| 79 |
+
|
| 80 |
+
return video_urls
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
def download_video(url, temp_dir):
|
| 83 |
try:
|
| 84 |
+
response = requests.get(url, stream=True, timeout=30)
|
| 85 |
+
filename = f"video_{datetime.now().strftime('%Y%m%d%H%M%S')}.mp4"
|
| 86 |
+
filepath = os.path.join(temp_dir, filename)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
+
with open(filepath, 'wb') as f:
|
| 89 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 90 |
+
f.write(chunk)
|
| 91 |
+
return filepath
|
| 92 |
+
except Exception as e:
|
| 93 |
+
logger.error(f"Error descargando video: {e}")
|
| 94 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
def create_video(audio_path, video_paths, output_path):
|
| 97 |
+
try:
|
| 98 |
+
clips = [VideoFileClip(path) for path in video_paths]
|
| 99 |
+
final_clip = concatenate_videoclips(clips)
|
| 100 |
+
audio = AudioFileClip(audio_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
if final_clip.duration < audio.duration:
|
| 103 |
+
final_clip = final_clip.loop(duration=audio.duration)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
final_clip = final_clip.set_audio(audio)
|
| 106 |
+
final_clip.write_videofile(
|
| 107 |
+
output_path,
|
|
|
|
|
|
|
|
|
|
| 108 |
codec="libx264",
|
| 109 |
audio_codec="aac",
|
| 110 |
+
fps=24
|
| 111 |
)
|
| 112 |
+
return True
|
|
|
|
|
|
|
|
|
|
| 113 |
except Exception as e:
|
| 114 |
+
logger.error(f"Error creando video: {e}")
|
| 115 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
+
# Interfaz de Gradio
|
| 118 |
with gr.Blocks() as app:
|
| 119 |
+
with gr.Row():
|
| 120 |
+
with gr.Column():
|
| 121 |
+
prompt_type = gr.Radio(["Generar Guion", "Usar Guion Existente"], label="Tipo de Entrada")
|
| 122 |
+
text_input = gr.Textbox(label="Texto", lines=5)
|
| 123 |
+
generate_btn = gr.Button("Generar Video")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
with gr.Column():
|
| 126 |
+
video_output = gr.Video()
|
| 127 |
+
status_output = gr.Textbox(label="Estado")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
@generate_btn.click(inputs=[prompt_type, text_input], outputs=[video_output, status_output])
|
| 130 |
+
async def generate_video(prompt_type, text):
|
| 131 |
+
temp_dir = tempfile.mkdtemp()
|
| 132 |
+
try:
|
| 133 |
+
if prompt_type == "Generar Guion":
|
| 134 |
+
script = generate_script(text)
|
| 135 |
+
else:
|
| 136 |
+
script = text
|
| 137 |
+
|
| 138 |
+
tts_path = os.path.join(temp_dir, "audio.mp3")
|
| 139 |
+
if not await text_to_speech(script, tts_path):
|
| 140 |
+
return None, "Error generando voz"
|
| 141 |
+
|
| 142 |
+
keywords = extract_keywords(script) if kw_model else [text.split()[0]]
|
| 143 |
+
video_urls = search_pexels_videos(keywords)
|
| 144 |
+
|
| 145 |
+
video_paths = []
|
| 146 |
+
for url in video_urls:
|
| 147 |
+
path = download_video(url, temp_dir)
|
| 148 |
+
if path:
|
| 149 |
+
video_paths.append(path)
|
| 150 |
+
|
| 151 |
+
if not video_paths:
|
| 152 |
+
return None, "Error descargando videos"
|
| 153 |
+
|
| 154 |
+
output_path = os.path.join(temp_dir, "final.mp4")
|
| 155 |
+
if create_video(tts_path, video_paths, output_path):
|
| 156 |
+
return output_path, "Video generado"
|
| 157 |
+
else:
|
| 158 |
+
return None, "Error creando video"
|
| 159 |
+
except Exception as e:
|
| 160 |
+
logger.error(f"Error: {str(e)}")
|
| 161 |
+
return None, f"Error: {str(e)}"
|
| 162 |
+
finally:
|
| 163 |
+
pass # Hugging Face limpia automáticamente
|
| 164 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
if __name__ == "__main__":
|
| 166 |
+
app.launch(server_name="0.0.0.0", server_port=7860)
|
|
|