Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -9,14 +9,13 @@ import re
|
|
9 |
import torch
|
10 |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
11 |
import warnings
|
12 |
-
import time
|
13 |
|
14 |
# Configuraci贸n inicial
|
15 |
logging.basicConfig(level=logging.INFO)
|
16 |
logger = logging.getLogger(__name__)
|
17 |
|
18 |
-
# Suprimir warnings
|
19 |
-
warnings.filterwarnings("ignore", category=UserWarning
|
20 |
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
21 |
|
22 |
PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
|
@@ -25,51 +24,51 @@ PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
|
|
25 |
VOICES = [
|
26 |
"es-MX-DaliaNeural", "es-ES-ElviraNeural", "es-AR-ElenaNeural",
|
27 |
"es-MX-JorgeNeural", "es-ES-AlvaroNeural", "es-AR-TomasNeural",
|
28 |
-
"en-US-JennyNeural", "fr-FR-DeniseNeural", "de-DE-KatjaNeural"
|
29 |
-
"it-IT-ElsaNeural", "pt-BR-FranciscaNeural", "ja-JP-NanamiNeural"
|
30 |
]
|
31 |
|
32 |
-
# Cargar modelo GPT-2 con
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
return None, None
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
def generar_guion(tema, custom_script=None):
|
46 |
-
"""Genera texto basado en el tema sin estructuras predefinidas"""
|
47 |
-
if custom_script:
|
48 |
-
return custom_script
|
49 |
-
|
50 |
if model is None or tokenizer is None:
|
51 |
-
return f"
|
52 |
|
53 |
try:
|
54 |
-
|
|
|
55 |
|
|
|
|
|
|
|
|
|
56 |
outputs = model.generate(
|
57 |
inputs.input_ids,
|
58 |
-
max_length=
|
59 |
do_sample=True,
|
60 |
temperature=0.7,
|
61 |
-
top_k=
|
62 |
num_return_sequences=1,
|
63 |
pad_token_id=tokenizer.eos_token_id
|
64 |
)
|
65 |
|
66 |
-
|
|
|
|
|
67 |
except Exception as e:
|
68 |
logger.error(f"Error generando texto: {str(e)}")
|
69 |
-
return f"
|
70 |
|
71 |
-
def
|
72 |
-
"""
|
73 |
try:
|
74 |
headers = {"Authorization": PEXELS_API_KEY}
|
75 |
response = requests.get(
|
@@ -79,47 +78,49 @@ def buscar_videos(tema):
|
|
79 |
)
|
80 |
return response.json().get("videos", [])[:3]
|
81 |
except Exception as e:
|
82 |
-
logger.error(f"Error
|
83 |
return []
|
84 |
|
85 |
-
def crear_video(prompt,
|
86 |
try:
|
87 |
-
|
|
|
|
|
88 |
|
89 |
-
#
|
90 |
-
guion = generar_guion(prompt, custom_script)
|
91 |
-
logger.info(f"Guion generado ({len(guion)} caracteres)")
|
92 |
-
|
93 |
-
# 2. Generar voz
|
94 |
voz_file = "narracion.mp3"
|
95 |
subprocess.run([
|
96 |
'edge-tts',
|
97 |
'--voice', voz_seleccionada,
|
98 |
-
'--text',
|
99 |
'--write-media', voz_file
|
100 |
], check=True)
|
101 |
|
102 |
audio = AudioFileClip(voz_file)
|
103 |
duracion = audio.duration
|
104 |
|
105 |
-
# 3.
|
106 |
-
videos =
|
107 |
clips = []
|
108 |
|
109 |
for i, video in enumerate(videos):
|
110 |
try:
|
|
|
111 |
video_file = max(video['video_files'], key=lambda x: x.get('width', 0))
|
112 |
-
temp_file = f"
|
113 |
|
|
|
114 |
with requests.get(video_file['link'], stream=True) as r:
|
115 |
r.raise_for_status()
|
116 |
with open(temp_file, 'wb') as f:
|
117 |
for chunk in r.iter_content(chunk_size=8192):
|
118 |
f.write(chunk)
|
119 |
|
|
|
120 |
clip = VideoFileClip(temp_file)
|
121 |
-
|
122 |
-
clips.append(clip)
|
|
|
123 |
except Exception as e:
|
124 |
logger.error(f"Error procesando video {i}: {str(e)}")
|
125 |
|
@@ -131,6 +132,7 @@ def crear_video(prompt, custom_script, voz_seleccionada, musica=None):
|
|
131 |
|
132 |
final_clip = final_clip.set_audio(audio)
|
133 |
|
|
|
134 |
output_file = f"video_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
|
135 |
final_clip.write_videofile(
|
136 |
output_file,
|
@@ -141,39 +143,40 @@ def crear_video(prompt, custom_script, voz_seleccionada, musica=None):
|
|
141 |
preset='fast'
|
142 |
)
|
143 |
|
144 |
-
logger.info(f"Video creado en {time.time()-start_time:.2f} segundos")
|
145 |
return output_file
|
146 |
|
147 |
except Exception as e:
|
148 |
logger.error(f"Error cr铆tico: {str(e)}")
|
149 |
return None
|
150 |
finally:
|
151 |
-
# Limpieza
|
152 |
-
for f in [voz_file, *[f"
|
153 |
if os.path.exists(f):
|
154 |
-
|
|
|
|
|
|
|
155 |
|
156 |
-
# Interfaz
|
157 |
-
with gr.Blocks(
|
158 |
with gr.Row():
|
159 |
with gr.Column():
|
160 |
tema = gr.Textbox(label="Tema del video")
|
161 |
-
guion = gr.TextArea(label="Guion personalizado (opcional)", lines=5)
|
162 |
voz = gr.Dropdown(label="Voz", choices=VOICES, value=VOICES[0])
|
163 |
btn = gr.Button("Generar Video")
|
164 |
|
165 |
with gr.Column():
|
166 |
-
|
167 |
|
168 |
btn.click(
|
169 |
fn=crear_video,
|
170 |
-
inputs=[tema,
|
171 |
-
outputs=
|
172 |
)
|
173 |
|
174 |
if __name__ == "__main__":
|
175 |
app.launch(
|
176 |
server_name="0.0.0.0",
|
177 |
server_port=7860,
|
178 |
-
share=False
|
179 |
)
|
|
|
9 |
import torch
|
10 |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
11 |
import warnings
|
|
|
12 |
|
13 |
# Configuraci贸n inicial
|
14 |
logging.basicConfig(level=logging.INFO)
|
15 |
logger = logging.getLogger(__name__)
|
16 |
|
17 |
+
# Suprimir warnings no deseados
|
18 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
19 |
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
20 |
|
21 |
PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
|
|
|
24 |
VOICES = [
|
25 |
"es-MX-DaliaNeural", "es-ES-ElviraNeural", "es-AR-ElenaNeural",
|
26 |
"es-MX-JorgeNeural", "es-ES-AlvaroNeural", "es-AR-TomasNeural",
|
27 |
+
"en-US-JennyNeural", "fr-FR-DeniseNeural", "de-DE-KatjaNeural"
|
|
|
28 |
]
|
29 |
|
30 |
+
# Cargar modelo GPT-2 con configuraci贸n optimizada
|
31 |
+
try:
|
32 |
+
tokenizer = GPT2Tokenizer.from_pretrained("datificate/gpt2-small-spanish")
|
33 |
+
model = GPT2LMHeadModel.from_pretrained("datificate/gpt2-small-spanish")
|
34 |
+
logger.info("Modelo GPT-2 cargado correctamente")
|
35 |
+
except Exception as e:
|
36 |
+
logger.error(f"Error cargando modelo: {str(e)}")
|
37 |
+
model = None
|
38 |
+
tokenizer = None
|
|
|
39 |
|
40 |
+
def generar_texto(tema):
|
41 |
+
"""Genera texto largo sobre el tema sin estructuras predefinidas"""
|
|
|
|
|
|
|
|
|
|
|
42 |
if model is None or tokenizer is None:
|
43 |
+
return f"Contenido sobre {tema}. " * 50
|
44 |
|
45 |
try:
|
46 |
+
# Prompt directo y simple
|
47 |
+
prompt = f"Describe detalladamente {tema}"
|
48 |
|
49 |
+
# Codificar el texto con truncamiento
|
50 |
+
inputs = tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True)
|
51 |
+
|
52 |
+
# Generar texto con par谩metros optimizados
|
53 |
outputs = model.generate(
|
54 |
inputs.input_ids,
|
55 |
+
max_length=800,
|
56 |
do_sample=True,
|
57 |
temperature=0.7,
|
58 |
+
top_k=40,
|
59 |
num_return_sequences=1,
|
60 |
pad_token_id=tokenizer.eos_token_id
|
61 |
)
|
62 |
|
63 |
+
texto = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
64 |
+
return re.sub(r'\s+', ' ', texto).strip()
|
65 |
+
|
66 |
except Exception as e:
|
67 |
logger.error(f"Error generando texto: {str(e)}")
|
68 |
+
return f"Texto generado sobre {tema}. " * 50
|
69 |
|
70 |
+
def obtener_videos(tema):
|
71 |
+
"""Obtiene videos de Pexels con manejo robusto de errores"""
|
72 |
try:
|
73 |
headers = {"Authorization": PEXELS_API_KEY}
|
74 |
response = requests.get(
|
|
|
78 |
)
|
79 |
return response.json().get("videos", [])[:3]
|
80 |
except Exception as e:
|
81 |
+
logger.error(f"Error obteniendo videos: {str(e)}")
|
82 |
return []
|
83 |
|
84 |
+
def crear_video(prompt, voz_seleccionada):
|
85 |
try:
|
86 |
+
# 1. Generar texto
|
87 |
+
texto = generar_texto(prompt)
|
88 |
+
logger.info(f"Texto generado: {len(texto)} caracteres")
|
89 |
|
90 |
+
# 2. Crear narraci贸n de voz
|
|
|
|
|
|
|
|
|
91 |
voz_file = "narracion.mp3"
|
92 |
subprocess.run([
|
93 |
'edge-tts',
|
94 |
'--voice', voz_seleccionada,
|
95 |
+
'--text', texto,
|
96 |
'--write-media', voz_file
|
97 |
], check=True)
|
98 |
|
99 |
audio = AudioFileClip(voz_file)
|
100 |
duracion = audio.duration
|
101 |
|
102 |
+
# 3. Obtener y procesar videos
|
103 |
+
videos = obtener_videos(prompt) or obtener_videos("nature")
|
104 |
clips = []
|
105 |
|
106 |
for i, video in enumerate(videos):
|
107 |
try:
|
108 |
+
# Seleccionar video de mayor calidad
|
109 |
video_file = max(video['video_files'], key=lambda x: x.get('width', 0))
|
110 |
+
temp_file = f"temp_{i}.mp4"
|
111 |
|
112 |
+
# Descargar video
|
113 |
with requests.get(video_file['link'], stream=True) as r:
|
114 |
r.raise_for_status()
|
115 |
with open(temp_file, 'wb') as f:
|
116 |
for chunk in r.iter_content(chunk_size=8192):
|
117 |
f.write(chunk)
|
118 |
|
119 |
+
# Procesar clip
|
120 |
clip = VideoFileClip(temp_file)
|
121 |
+
clip_duration = min(duracion/len(videos), clip.duration)
|
122 |
+
clips.append(clip.subclip(0, clip_duration))
|
123 |
+
|
124 |
except Exception as e:
|
125 |
logger.error(f"Error procesando video {i}: {str(e)}")
|
126 |
|
|
|
132 |
|
133 |
final_clip = final_clip.set_audio(audio)
|
134 |
|
135 |
+
# 5. Exportar video
|
136 |
output_file = f"video_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
|
137 |
final_clip.write_videofile(
|
138 |
output_file,
|
|
|
143 |
preset='fast'
|
144 |
)
|
145 |
|
|
|
146 |
return output_file
|
147 |
|
148 |
except Exception as e:
|
149 |
logger.error(f"Error cr铆tico: {str(e)}")
|
150 |
return None
|
151 |
finally:
|
152 |
+
# Limpieza de archivos temporales
|
153 |
+
for f in [voz_file, *[f"temp_{i}.mp4" for i in range(3)]]:
|
154 |
if os.path.exists(f):
|
155 |
+
try:
|
156 |
+
os.remove(f)
|
157 |
+
except:
|
158 |
+
pass
|
159 |
|
160 |
+
# Interfaz minimalista
|
161 |
+
with gr.Blocks() as app:
|
162 |
with gr.Row():
|
163 |
with gr.Column():
|
164 |
tema = gr.Textbox(label="Tema del video")
|
|
|
165 |
voz = gr.Dropdown(label="Voz", choices=VOICES, value=VOICES[0])
|
166 |
btn = gr.Button("Generar Video")
|
167 |
|
168 |
with gr.Column():
|
169 |
+
video = gr.Video(label="Resultado")
|
170 |
|
171 |
btn.click(
|
172 |
fn=crear_video,
|
173 |
+
inputs=[tema, voz],
|
174 |
+
outputs=video
|
175 |
)
|
176 |
|
177 |
if __name__ == "__main__":
|
178 |
app.launch(
|
179 |
server_name="0.0.0.0",
|
180 |
server_port=7860,
|
181 |
+
share=False
|
182 |
)
|