Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,50 +1,164 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
try:
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
# 2. Devuelve un video de prueba (eliminar en producci贸n)
|
| 17 |
-
return "video_prueba.mp4"
|
| 18 |
-
|
| 19 |
except Exception as e:
|
| 20 |
-
|
| 21 |
-
|
|
|
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
| 28 |
)
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
with gr.Row():
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
btn.click(
|
| 39 |
-
fn=
|
| 40 |
-
inputs=[prompt,
|
| 41 |
outputs=output
|
| 42 |
)
|
| 43 |
|
| 44 |
if __name__ == "__main__":
|
| 45 |
-
app.launch(
|
| 46 |
-
server_name="0.0.0.0",
|
| 47 |
-
server_port=7860,
|
| 48 |
-
# 鈿狅笍 Configuraci贸n CLAVE para el timeout
|
| 49 |
-
app_kwargs={"timeout": GRADIO_TIMEOUT}
|
| 50 |
-
)
|
|
|
|
| 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 |
+
import random
|
| 14 |
+
from transformers import pipeline
|
| 15 |
+
import torch
|
| 16 |
+
import asyncio
|
| 17 |
+
import nest_asyncio
|
| 18 |
+
from nltk.tokenize import sent_tokenize
|
| 19 |
|
| 20 |
+
# Setup
|
| 21 |
+
nltk.download('punkt', quiet=True)
|
| 22 |
+
nest_asyncio.apply()
|
| 23 |
|
| 24 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
PEXELS_API_KEY = os.getenv("PEXELS_API_KEY")
|
| 28 |
+
MODEL_NAME = "DeepESP/gpt2-spanish"
|
| 29 |
+
|
| 30 |
+
VOICE_NAMES, VOICES = [], []
|
| 31 |
+
|
| 32 |
+
async def get_voices():
|
| 33 |
+
voces = await edge_tts.list_voices()
|
| 34 |
+
voice_names = [f"{v['Name']} ({v['Gender']}, {v['LocaleName']})" for v in voces]
|
| 35 |
+
return voice_names, voces
|
| 36 |
+
|
| 37 |
+
async def get_and_set_voices():
|
| 38 |
+
global VOICE_NAMES, VOICES
|
| 39 |
try:
|
| 40 |
+
VOICE_NAMES, VOICES = await get_voices()
|
| 41 |
+
if not VOICES:
|
| 42 |
+
raise Exception("No se encontraron voces.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
except Exception as e:
|
| 44 |
+
logger.warning(f"Fallo al cargar voces: {e}")
|
| 45 |
+
VOICE_NAMES = ["Voz Predeterminada (Femenino, es-ES)"]
|
| 46 |
+
VOICES = [{'ShortName': 'es-ES-ElviraNeural'}]
|
| 47 |
|
| 48 |
+
asyncio.get_event_loop().run_until_complete(get_and_set_voices())
|
| 49 |
+
|
| 50 |
+
def generar_guion_profesional(prompt):
|
| 51 |
+
try:
|
| 52 |
+
generator = pipeline(
|
| 53 |
+
"text-generation",
|
| 54 |
+
model=MODEL_NAME,
|
| 55 |
+
device=0 if torch.cuda.is_available() else -1
|
| 56 |
)
|
| 57 |
+
response = generator(
|
| 58 |
+
f"Escribe un guion profesional para un video de YouTube sobre '{prompt}'. "
|
| 59 |
+
"Incluye introducci贸n, desarrollo en 3 secciones y conclusi贸n:",
|
| 60 |
+
max_length=1000,
|
| 61 |
+
temperature=0.7,
|
| 62 |
+
top_k=50,
|
| 63 |
+
top_p=0.95,
|
| 64 |
+
num_return_sequences=1
|
| 65 |
+
)
|
| 66 |
+
guion = response[0]['generated_text']
|
| 67 |
+
if len(guion.split()) < 100:
|
| 68 |
+
raise ValueError("Guion demasiado breve")
|
| 69 |
+
return guion
|
| 70 |
+
except Exception as e:
|
| 71 |
+
logger.error(f"Error generando guion: {e}")
|
| 72 |
+
return f"""Introducci贸n sobre {prompt}.
|
| 73 |
+
Secci贸n 1: Or铆genes e historia.
|
| 74 |
+
Secci贸n 2: Estado actual.
|
| 75 |
+
Secci贸n 3: Futuro e impacto.
|
| 76 |
+
Conclusi贸n reflexiva."""
|
| 77 |
|
| 78 |
+
def buscar_videos_avanzado(prompt, guion, num_videos=5):
|
| 79 |
+
try:
|
| 80 |
+
oraciones = sent_tokenize(guion)
|
| 81 |
+
vectorizer = TfidfVectorizer(stop_words='spanish')
|
| 82 |
+
tfidf = vectorizer.fit_transform(oraciones)
|
| 83 |
+
palabras = vectorizer.get_feature_names_out()
|
| 84 |
+
scores = np.asarray(tfidf.sum(axis=0)).ravel()
|
| 85 |
+
top_indices = np.argsort(scores)[-5:]
|
| 86 |
+
palabras_clave = [palabras[i] for i in top_indices]
|
| 87 |
+
|
| 88 |
+
palabras_prompt = re.findall(r'\b\w{4,}\b', prompt.lower())
|
| 89 |
+
todas = list(set(palabras_clave + palabras_prompt))[:5]
|
| 90 |
+
|
| 91 |
+
headers = {"Authorization": PEXELS_API_KEY}
|
| 92 |
+
response = requests.get(
|
| 93 |
+
f"https://api.pexels.com/videos/search?query={'+'.join(todas)}&per_page={num_videos}",
|
| 94 |
+
headers=headers,
|
| 95 |
+
timeout=15
|
| 96 |
+
)
|
| 97 |
+
return response.json().get('videos', [])
|
| 98 |
+
except Exception as e:
|
| 99 |
+
logger.error(f"Error buscando videos: {e}")
|
| 100 |
+
return []
|
| 101 |
+
|
| 102 |
+
async def crear_video_profesional(prompt, custom_script, voz_index, musica=None):
|
| 103 |
+
voz_archivo = "voz.mp3"
|
| 104 |
+
try:
|
| 105 |
+
guion = custom_script if custom_script.strip() else generar_guion_profesional(prompt)
|
| 106 |
+
voz_seleccionada = VOICES[voz_index]['ShortName'] if VOICES else 'es-ES-ElviraNeural'
|
| 107 |
+
|
| 108 |
+
# Generar audio
|
| 109 |
+
await edge_tts.Communicate(guion, voz_seleccionada).save(voz_archivo)
|
| 110 |
+
audio = AudioFileClip(voz_archivo)
|
| 111 |
+
|
| 112 |
+
# Obtener videos
|
| 113 |
+
videos_data = buscar_videos_avanzado(prompt, guion)
|
| 114 |
+
if not videos_data:
|
| 115 |
+
raise Exception("No se encontraron videos")
|
| 116 |
+
|
| 117 |
+
# Procesar videos
|
| 118 |
+
clips = []
|
| 119 |
+
for video in videos_data[:3]:
|
| 120 |
+
video_file = next((vf for vf in video['video_files'] if vf['quality'] == 'sd'), video['video_files'][0])
|
| 121 |
+
with tempfile.NamedTemporaryFile(suffix='.mp4', delete=False) as temp_video:
|
| 122 |
+
response = requests.get(video_file['link'], stream=True)
|
| 123 |
+
for chunk in response.iter_content(chunk_size=1024 * 1024):
|
| 124 |
+
temp_video.write(chunk)
|
| 125 |
+
clip = VideoFileClip(temp_video.name).subclip(0, min(10, video['duration']))
|
| 126 |
+
clips.append(clip)
|
| 127 |
+
|
| 128 |
+
# Crear video final
|
| 129 |
+
video_final = concatenate_videoclips(clips)
|
| 130 |
+
video_final = video_final.set_audio(audio)
|
| 131 |
+
|
| 132 |
+
output_path = f"video_output_{datetime.now().strftime('%Y%m%d_%H%M%S')}.mp4"
|
| 133 |
+
video_final.write_videofile(output_path, fps=24, threads=2)
|
| 134 |
+
return output_path
|
| 135 |
+
|
| 136 |
+
except Exception as e:
|
| 137 |
+
logger.error(f"Error cr铆tico: {e}")
|
| 138 |
+
return None
|
| 139 |
+
finally:
|
| 140 |
+
if os.path.exists(voz_archivo):
|
| 141 |
+
os.remove(voz_archivo)
|
| 142 |
+
|
| 143 |
+
# Gradio app
|
| 144 |
+
with gr.Blocks(title="Generador de Videos") as app:
|
| 145 |
with gr.Row():
|
| 146 |
+
with gr.Column():
|
| 147 |
+
prompt = gr.Textbox(label="Tema del video")
|
| 148 |
+
custom_script = gr.TextArea(label="Gui贸n personalizado (opcional)")
|
| 149 |
+
voz = gr.Dropdown(VOICE_NAMES, label="Voz", value=VOICE_NAMES[0])
|
| 150 |
+
btn = gr.Button("Generar Video", variant="primary")
|
| 151 |
+
with gr.Column():
|
| 152 |
+
output = gr.Video(label="Resultado", format="mp4")
|
| 153 |
+
|
| 154 |
+
async def wrapper(p, cs, v):
|
| 155 |
+
return await crear_video_profesional(p, cs, VOICE_NAMES.index(v))
|
| 156 |
+
|
| 157 |
btn.click(
|
| 158 |
+
fn=wrapper,
|
| 159 |
+
inputs=[prompt, custom_script, voz],
|
| 160 |
outputs=output
|
| 161 |
)
|
| 162 |
|
| 163 |
if __name__ == "__main__":
|
| 164 |
+
app.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|