Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,14 +10,11 @@ from datetime import datetime
|
|
| 10 |
import numpy as np
|
| 11 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 12 |
import nltk
|
|
|
|
| 13 |
from transformers import pipeline
|
| 14 |
import torch
|
| 15 |
import asyncio
|
| 16 |
from nltk.tokenize import sent_tokenize
|
| 17 |
-
import nest_asyncio # Nueva importaci贸n importante
|
| 18 |
-
|
| 19 |
-
# Aplicar parche para el event loop
|
| 20 |
-
nest_asyncio.apply()
|
| 21 |
|
| 22 |
# Configuraci贸n inicial
|
| 23 |
nltk.download('punkt', quiet=True)
|
|
@@ -28,18 +25,15 @@ logger = logging.getLogger(__name__)
|
|
| 28 |
PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
|
| 29 |
MODEL_NAME = "DeepESP/gpt2-spanish"
|
| 30 |
|
| 31 |
-
# Lista de voces disponibles
|
| 32 |
async def get_voices():
|
| 33 |
voices = await edge_tts.list_voices()
|
| 34 |
return [v['ShortName'] for v in voices]
|
| 35 |
|
| 36 |
-
|
| 37 |
-
loop = asyncio.new_event_loop()
|
| 38 |
-
asyncio.set_event_loop(loop)
|
| 39 |
-
VOICE_NAMES = loop.run_until_complete(get_voices())
|
| 40 |
|
| 41 |
def generar_guion_profesional(prompt):
|
| 42 |
-
"""Genera guiones
|
| 43 |
try:
|
| 44 |
generator = pipeline(
|
| 45 |
"text-generation",
|
|
@@ -48,84 +42,87 @@ def generar_guion_profesional(prompt):
|
|
| 48 |
)
|
| 49 |
|
| 50 |
response = generator(
|
| 51 |
-
f"Escribe un guion
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
temperature=0.7,
|
|
|
|
|
|
|
| 54 |
num_return_sequences=1
|
| 55 |
)
|
| 56 |
|
| 57 |
-
|
|
|
|
|
|
|
| 58 |
except Exception as e:
|
| 59 |
logger.error(f"Error generando guion: {str(e)}")
|
| 60 |
-
return f"Guion de ejemplo sobre {prompt}.
|
| 61 |
|
| 62 |
-
|
| 63 |
-
async def async_video_creation(prompt, custom_script, voz_index, musica=None):
|
| 64 |
try:
|
| 65 |
-
# 1. Generar guion
|
| 66 |
guion = custom_script if custom_script else generar_guion_profesional(prompt)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
# 2. Generar voz
|
| 71 |
voz_archivo = "voz.mp3"
|
| 72 |
-
|
| 73 |
-
await communicate.save(voz_archivo)
|
| 74 |
-
|
| 75 |
-
# 3. Crear clip de audio
|
| 76 |
audio = AudioFileClip(voz_archivo)
|
| 77 |
-
|
| 78 |
|
| 79 |
-
#
|
| 80 |
-
clip = ColorClip(size=(1280, 720), color=(0, 0, 0), duration=
|
| 81 |
-
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
output_path = f"
|
| 85 |
-
|
| 86 |
output_path,
|
| 87 |
fps=24,
|
| 88 |
codec="libx264",
|
| 89 |
-
audio_codec="aac"
|
| 90 |
-
threads=2
|
| 91 |
)
|
| 92 |
|
| 93 |
return output_path
|
| 94 |
|
| 95 |
except Exception as e:
|
| 96 |
-
logger.error(f"
|
| 97 |
return None
|
| 98 |
finally:
|
| 99 |
if os.path.exists(voz_archivo):
|
| 100 |
os.remove(voz_archivo)
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
try:
|
| 105 |
-
return asyncio.run(async_video_creation(prompt, custom_script, voz_index, musica))
|
| 106 |
-
except Exception as e:
|
| 107 |
-
logger.error(f"Error en wrapper: {str(e)}")
|
| 108 |
-
return None
|
| 109 |
|
| 110 |
-
# Interfaz
|
| 111 |
-
with gr.Blocks(title="Generador de Videos") as app:
|
| 112 |
-
gr.Markdown("
|
| 113 |
|
| 114 |
with gr.Row():
|
| 115 |
-
with gr.Column():
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
btn.click(
|
| 124 |
-
fn=
|
| 125 |
-
inputs=[prompt, gr.Textbox(visible=False), voz],
|
| 126 |
-
outputs=output
|
| 127 |
-
timeout=300 # 5 minutos de timeout
|
| 128 |
)
|
| 129 |
|
| 130 |
if __name__ == "__main__":
|
| 131 |
-
app.launch(
|
|
|
|
| 10 |
import numpy as np
|
| 11 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 12 |
import nltk
|
| 13 |
+
import random
|
| 14 |
from transformers import pipeline
|
| 15 |
import torch
|
| 16 |
import asyncio
|
| 17 |
from nltk.tokenize import sent_tokenize
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# Configuraci贸n inicial
|
| 20 |
nltk.download('punkt', quiet=True)
|
|
|
|
| 25 |
PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
|
| 26 |
MODEL_NAME = "DeepESP/gpt2-spanish"
|
| 27 |
|
| 28 |
+
# Lista de voces disponibles
|
| 29 |
async def get_voices():
|
| 30 |
voices = await edge_tts.list_voices()
|
| 31 |
return [v['ShortName'] for v in voices]
|
| 32 |
|
| 33 |
+
VOICE_NAMES = asyncio.run(get_voices())
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
def generar_guion_profesional(prompt):
|
| 36 |
+
"""Genera guiones detallados con sistema de 3 niveles"""
|
| 37 |
try:
|
| 38 |
generator = pipeline(
|
| 39 |
"text-generation",
|
|
|
|
| 42 |
)
|
| 43 |
|
| 44 |
response = generator(
|
| 45 |
+
f"Escribe un guion profesional para un video de YouTube sobre '{prompt}'. "
|
| 46 |
+
"La estructura debe incluir:\n"
|
| 47 |
+
"1. Introducci贸n atractiva\n"
|
| 48 |
+
"2. Tres secciones detalladas con subt铆tulos\n"
|
| 49 |
+
"3. Conclusi贸n impactante\n"
|
| 50 |
+
"Usa un estilo natural para narraci贸n:",
|
| 51 |
+
max_length=1000,
|
| 52 |
temperature=0.7,
|
| 53 |
+
top_k=50,
|
| 54 |
+
top_p=0.95,
|
| 55 |
num_return_sequences=1
|
| 56 |
)
|
| 57 |
|
| 58 |
+
guion = response[0]['generated_text']
|
| 59 |
+
return guion
|
| 60 |
+
|
| 61 |
except Exception as e:
|
| 62 |
logger.error(f"Error generando guion: {str(e)}")
|
| 63 |
+
return f"Guion de ejemplo sobre {prompt}. Introducci贸n. Desarrollo. Conclusi贸n."
|
| 64 |
|
| 65 |
+
async def crear_video_profesional(prompt, custom_script, voz_index, musica=None):
|
|
|
|
| 66 |
try:
|
| 67 |
+
# 1. Generar o usar guion
|
| 68 |
guion = custom_script if custom_script else generar_guion_profesional(prompt)
|
| 69 |
+
logger.info(f"Guion generado ({len(guion.split())} palabras)")
|
| 70 |
+
|
|
|
|
| 71 |
# 2. Generar voz
|
| 72 |
voz_archivo = "voz.mp3"
|
| 73 |
+
await edge_tts.Communicate(guion, VOICE_NAMES[voz_index]).save(voz_archivo)
|
|
|
|
|
|
|
|
|
|
| 74 |
audio = AudioFileClip(voz_archivo)
|
| 75 |
+
duracion_total = audio.duration
|
| 76 |
|
| 77 |
+
# 3. Crear video simple (versi贸n funcional)
|
| 78 |
+
clip = ColorClip(size=(1280, 720), color=(0, 0, 0), duration=duracion_total)
|
| 79 |
+
video_final = clip.set_audio(audio)
|
| 80 |
|
| 81 |
+
# 4. Exportar video
|
| 82 |
+
output_path = f"video_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
|
| 83 |
+
video_final.write_videofile(
|
| 84 |
output_path,
|
| 85 |
fps=24,
|
| 86 |
codec="libx264",
|
| 87 |
+
audio_codec="aac"
|
|
|
|
| 88 |
)
|
| 89 |
|
| 90 |
return output_path
|
| 91 |
|
| 92 |
except Exception as e:
|
| 93 |
+
logger.error(f"ERROR: {str(e)}")
|
| 94 |
return None
|
| 95 |
finally:
|
| 96 |
if os.path.exists(voz_archivo):
|
| 97 |
os.remove(voz_archivo)
|
| 98 |
|
| 99 |
+
def run_async_func(prompt, custom_script, voz_index, musica=None):
|
| 100 |
+
return asyncio.run(crear_video_profesional(prompt, custom_script, voz_index, musica))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
# Interfaz profesional CORREGIDA
|
| 103 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Generador de Videos Profesional") as app:
|
| 104 |
+
gr.Markdown("# 馃幀 GENERADOR DE VIDEOS CON IA")
|
| 105 |
|
| 106 |
with gr.Row():
|
| 107 |
+
with gr.Column(scale=1):
|
| 108 |
+
gr.Markdown("### Configuraci贸n del Contenido")
|
| 109 |
+
prompt = gr.Textbox(label="Tema principal", placeholder="Ej: 'Los misterios de la antigua Grecia'")
|
| 110 |
+
voz = gr.Dropdown(
|
| 111 |
+
label="Selecciona una voz",
|
| 112 |
+
choices=VOICE_NAMES,
|
| 113 |
+
value=VOICE_NAMES[0]
|
| 114 |
+
)
|
| 115 |
+
btn = gr.Button("馃殌 Generar Video", variant="primary", size="lg")
|
| 116 |
+
|
| 117 |
+
with gr.Column(scale=2):
|
| 118 |
+
output = gr.Video(label="Video Resultante", format="mp4")
|
| 119 |
+
|
| 120 |
+
# CORRECCI脫N: Quitar el par谩metro timeout que causaba el error
|
| 121 |
btn.click(
|
| 122 |
+
fn=run_async_func,
|
| 123 |
+
inputs=[prompt, gr.Textbox(visible=False), voz, gr.File(visible=False)],
|
| 124 |
+
outputs=output
|
|
|
|
| 125 |
)
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|
| 128 |
+
app.launch(server_name="0.0.0.0", server_port=7860)
|