Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,126 +1,11 @@
|
|
1 |
import os
|
2 |
-
import re
|
3 |
-
import requests
|
4 |
-
import gradio as gr
|
5 |
-
from moviepy.editor import *
|
6 |
-
import edge_tts
|
7 |
-
import tempfile
|
8 |
-
import logging
|
9 |
-
from datetime import datetime
|
10 |
-
import numpy as np
|
11 |
-
from sklearn.feature_extraction.text import TfidfVectorizer
|
12 |
-
import nltk
|
13 |
-
from nltk.tokenize import sent_tokenize
|
14 |
-
from transformers import pipeline
|
15 |
-
import torch
|
16 |
-
import asyncio
|
17 |
-
|
18 |
-
# Configuraci贸n inicial
|
19 |
-
nltk.download('punkt', quiet=True)
|
20 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
21 |
-
logger = logging.getLogger(__name__)
|
22 |
-
|
23 |
-
# Configuraci贸n de modelos
|
24 |
-
PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
|
25 |
-
MODEL_NAME = "DeepESP/gpt2-spanish"
|
26 |
-
|
27 |
-
# Soluci贸n robusta para obtener voces
|
28 |
-
async def get_voices():
|
29 |
-
try:
|
30 |
-
voices = await edge_tts.list_voices()
|
31 |
-
voice_names = []
|
32 |
-
for v in voices:
|
33 |
-
try:
|
34 |
-
name = v.get('Name', v.get('ShortName', 'Desconocido'))
|
35 |
-
gender = v.get('Gender', 'Desconocido')
|
36 |
-
locale = v.get('Locale', v.get('Language', 'Desconocido'))
|
37 |
-
voice_names.append(f"{name} ({gender}, {locale})")
|
38 |
-
except Exception as e:
|
39 |
-
logger.warning(f"Error procesando voz: {v} - {str(e)}")
|
40 |
-
continue
|
41 |
-
return voice_names, voices
|
42 |
-
except Exception as e:
|
43 |
-
logger.error(f"Error al obtener voces: {str(e)}")
|
44 |
-
return [], []
|
45 |
-
|
46 |
-
# Obtener voces de forma s铆ncrona para la inicializaci贸n
|
47 |
-
import nest_asyncio
|
48 |
-
nest_asyncio.apply()
|
49 |
-
|
50 |
-
VOICE_NAMES, VOICES = [], []
|
51 |
-
|
52 |
-
async def get_voices():
|
53 |
-
voces = await edge_tts.list_voices()
|
54 |
-
voice_names = [f"{v['Name']} ({v['Gender']}, {v['LocaleName']})" for v in voces]
|
55 |
-
return voice_names, voces
|
56 |
-
|
57 |
-
async def get_and_set_voices():
|
58 |
-
global VOICE_NAMES, VOICES
|
59 |
-
try:
|
60 |
-
VOICE_NAMES, VOICES = await get_voices()
|
61 |
-
if not VOICES:
|
62 |
-
raise Exception("No se obtuvieron voces.")
|
63 |
-
except Exception as e:
|
64 |
-
logging.warning(f"No se pudieron cargar voces din谩micamente: {e}")
|
65 |
-
VOICE_NAMES = ["Voz Predeterminada (Femenino, es-ES)"]
|
66 |
-
VOICES = [{'ShortName': 'es-ES-ElviraNeural'}]
|
67 |
-
|
68 |
-
asyncio.get_event_loop().run_until_complete(get_and_set_voices())
|
69 |
-
|
70 |
-
def generar_guion_profesional(prompt):
|
71 |
-
"""Genera guiones con respaldo robusto"""
|
72 |
-
try:
|
73 |
-
generator = pipeline(
|
74 |
-
"text-generation",
|
75 |
-
model=MODEL_NAME,
|
76 |
-
device=0 if torch.cuda.is_available() else -1
|
77 |
-
)
|
78 |
-
|
79 |
-
response = generator(
|
80 |
-
f"Escribe un guion profesional para un video de YouTube sobre '{prompt}':\n\n1. Introducci贸n\n2. Desarrollo\n3. Conclusi贸n\n\n",
|
81 |
-
max_length=800,
|
82 |
-
temperature=0.7,
|
83 |
-
num_return_sequences=1
|
84 |
-
)
|
85 |
-
|
86 |
-
return response[0]['generated_text']
|
87 |
-
|
88 |
-
except Exception as e:
|
89 |
-
logger.error(f"Error generando guion: {str(e)}")
|
90 |
-
return f"""Gui贸n de respaldo sobre {prompt}:
|
91 |
-
|
92 |
-
1. INTRODUCCI脫N: Hoy exploraremos {prompt}
|
93 |
-
2. DESARROLLO: Aspectos clave sobre el tema
|
94 |
-
3. CONCLUSI脫N: Resumen y cierre"""
|
95 |
-
|
96 |
-
def buscar_videos_avanzado(prompt, guion, num_videos=3):
|
97 |
-
"""B煤squeda con m煤ltiples respaldos"""
|
98 |
-
try:
|
99 |
-
palabras = re.findall(r'\b\w{4,}\b', prompt.lower())[:5]
|
100 |
-
response = requests.get(
|
101 |
-
f"https://api.pexels.com/videos/search?query={'+'.join(palabras)}&per_page={num_videos}",
|
102 |
-
headers={"Authorization": PEXELS_API_KEY},
|
103 |
-
timeout=10
|
104 |
-
)
|
105 |
-
return response.json().get('videos', [])[:num_videos]
|
106 |
-
except Exception as e:
|
107 |
-
logger.error(f"Error buscando videos: {str(e)}")
|
108 |
-
return []
|
109 |
-
|
110 |
-
async def crear_video_profesional(prompt, custom_script, voz_index, musica=None):
|
111 |
-
try:
|
112 |
-
# 1. Generar gui贸n
|
113 |
-
guion = custom_script if custom_script else generar_guion_profesional(prompt)
|
114 |
-
|
115 |
-
# 2. Configurar voz
|
116 |
-
voz_seleccionada = VOICES[voz_indimport os
|
117 |
import asyncio
|
118 |
from concurrent.futures import ThreadPoolExecutor
|
119 |
import gradio as gr
|
120 |
|
121 |
# Configuraci贸n CR脥TICA para evitar timeouts
|
122 |
-
GRADIO_TIMEOUT =
|
123 |
-
MAX_VIDEO_DURATION =
|
124 |
|
125 |
async def crear_video_profesional(prompt, custom_script, voz_index, musica=None):
|
126 |
try:
|
|
|
1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import asyncio
|
3 |
from concurrent.futures import ThreadPoolExecutor
|
4 |
import gradio as gr
|
5 |
|
6 |
# Configuraci贸n CR脥TICA para evitar timeouts
|
7 |
+
GRADIO_TIMEOUT = 6000 # 10 minutos (en segundos)
|
8 |
+
MAX_VIDEO_DURATION = 1000 # 2 minutos (evita procesos eternos)
|
9 |
|
10 |
async def crear_video_profesional(prompt, custom_script, voz_index, musica=None):
|
11 |
try:
|