Spaces:
Building
Building
File size: 11,171 Bytes
c94aadc 306cc5c 1caaaa3 c94aadc 306cc5c 319260b c94aadc abed2e9 c94aadc 6065fb3 c94aadc f24aa65 c94aadc f24aa65 c94aadc 6065fb3 bdb3cfa f24aa65 2acde19 f24aa65 6065fb3 306cc5c 4cf7ad9 84bda60 2acde19 4cf7ad9 2acde19 4cf7ad9 84bda60 4cf7ad9 6065fb3 4cf7ad9 9ea2009 f24aa65 2acde19 4cf7ad9 f24aa65 c94aadc 2acde19 4cf7ad9 2acde19 4cf7ad9 2acde19 4cf7ad9 6065fb3 4cf7ad9 2acde19 4cf7ad9 2acde19 4cf7ad9 9ea2009 c94aadc 2acde19 4cf7ad9 9ea2009 c94aadc 2acde19 c94aadc 2acde19 abed2e9 2acde19 c94aadc abed2e9 2acde19 c94aadc abed2e9 2acde19 78a3857 2acde19 78a3857 2acde19 78a3857 2acde19 78a3857 9ea2009 319260b 2acde19 319260b 2acde19 319260b 2acde19 319260b 2acde19 319260b c94aadc 2acde19 c94aadc 6065fb3 c94aadc 6065fb3 c94aadc 6065fb3 c94aadc 6065fb3 c94aadc 6065fb3 c94aadc 6065fb3 78a3857 6065fb3 0a28283 6065fb3 c94aadc 59b95fb c94aadc 6065fb3 c94aadc 319260b c94aadc 6065fb3 c94aadc 6065fb3 78a3857 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
import gradio as gr
from tts_module import get_voices, text_to_speech
from pixabay_api import search_pixabay
from moviepy.editor import (
AudioFileClip, VideoFileClip, CompositeAudioClip,
concatenate_audioclips, concatenate_videoclips, vfx, CompositeVideoClip,
ColorClip
)
import asyncio
import os
import json
import time
import requests
import random
from PIL import Image # Para manejar imágenes correctamente
from googleapiclient.discovery import build
from google.oauth2 import service_account
from googleapiclient.http import MediaFileUpload
# Crear el archivo de credenciales de servicio desde los secretos
service_account_info = json.loads(os.getenv('GOOGLE_SERVICE_ACCOUNT', '{}'))
if service_account_info:
with open('service-account.json', 'w') as f:
json.dump(service_account_info, f)
# Define la carpeta de salida y la carpeta temporal
output_folder = "outputs"
temp_dir = "temp_files"
os.makedirs(output_folder, exist_ok=True)
os.makedirs(temp_dir, exist_ok=True)
# ID de la carpeta de destino en Google Drive
FOLDER_ID = "12S6adpanAXjf71pKKGRRPqpzbJa5XEh3" # Reemplaza con tu ID de carpeta
def cleanup_temp_files():
"""Elimina todos los archivos temporales de la carpeta temp_files."""
for filename in os.listdir(temp_dir):
file_path = os.path.join(temp_dir, filename)
try:
if os.path.isfile(file_path):
os.remove(file_path)
except Exception as e:
print(f"Error deleting {file_path}: {e}")
def resize_video(clip, target_width=1920, target_height=1080):
"""Redimensiona el video al tamaño 1080p (16:9)."""
try:
w, h = clip.size
current_aspect_ratio = w / h
target_aspect_ratio = target_width / target_height
if abs(current_aspect_ratio - target_aspect_ratio) < 0.1:
return clip.resize((target_width, target_height))
# Crear un fondo negro con las dimensiones objetivo
background = ColorClip(size=(target_width, target_height), color=[0, 0, 0]).set_duration(clip.duration)
# Redimensionar el video original para mantener su proporción
if current_aspect_ratio < target_aspect_ratio: # Video vertical
new_height = target_height
new_width = int(new_height * current_aspect_ratio)
x_center = (target_width - new_width) / 2
resized_clip = clip.resize(width=new_width).set_position((x_center, 0))
else: # Video horizontal
new_width = target_width
new_height = int(new_width / current_aspect_ratio)
y_center = (target_height - new_height) / 2
resized_clip = clip.resize(height=new_height).set_position((0, y_center))
# Combinar el fondo negro con el video redimensionado
return CompositeVideoClip([background, resized_clip], size=(target_width, target_height))
except Exception as e:
print(f"Error en resize_video: {e}")
return clip
def download_video(link):
"""Descarga un video desde un enlace y lo guarda en la carpeta temporal."""
try:
video_response = requests.get(link)
if video_response.status_code != 200:
return None
temp_video_path = os.path.join(temp_dir, f"temp_video_{int(time.time())}.mp4")
with open(temp_video_path, "wb") as f:
f.write(video_response.content)
return temp_video_path
except Exception as e:
print(f"Error downloading video: {e}")
return None
def concatenate_pixabay_videos(keywords, num_videos_per_keyword=1):
"""Concatena videos de Pixabay basados en palabras clave."""
keyword_list = [keyword.strip() for keyword in keywords.split(",") if keyword.strip()]
if not keyword_list:
keyword_list = ["nature"] # Palabra clave por defecto
video_clips = []
for keyword in keyword_list:
try:
print(f"Buscando videos para la palabra clave '{keyword}'...")
links = search_pixabay(keyword, num_results=num_videos_per_keyword)
if not links:
print(f"No se encontraron videos para '{keyword}', probando con 'nature'")
links = search_pixabay("nature", num_results=num_videos_per_keyword)
if not links:
continue
temp_video_path = download_video(links[0])
if temp_video_path:
clip = VideoFileClip(temp_video_path)
processed_clip = resize_video(clip)
video_clips.append(processed_clip)
os.remove(temp_video_path) # Eliminar archivo temporal después de usarlo
except Exception as e:
print(f"Error procesando palabra clave '{keyword}': {e}")
continue
if not video_clips:
# Si no hay videos, creamos un clip negro de 5 segundos
return ColorClip(size=(1920, 1080), color=[0, 0, 0], duration=5)
random.shuffle(video_clips)
return concatenate_videoclips(video_clips, method="compose")
def adjust_background_music(video_duration, music_file):
"""Ajusta la música de fondo para que coincida con la duración del video."""
try:
music = AudioFileClip(music_file)
if music.duration < video_duration:
repetitions = int(video_duration / music.duration) + 1
music_clips = [music] * repetitions
music = concatenate_audioclips(music_clips)
music = music.subclip(0, video_duration)
return music.volumex(0.2)
except Exception as e:
print(f"Error ajustando música: {e}")
return None
def combine_audio_video(audio_file, video_clip, music_clip=None):
"""Combina el audio y el video en un archivo final."""
try:
audio_clip = AudioFileClip(audio_file)
total_duration = audio_clip.duration + 2 # Añadimos 2 segundos extra
# Aseguramos que el video tenga la duración correcta
video_clip = video_clip.loop(duration=total_duration)
video_clip = video_clip.set_duration(total_duration).fadeout(2)
# Combinamos el audio principal
final_clip = video_clip.set_audio(audio_clip)
if music_clip:
music_clip = music_clip.set_duration(total_duration).audio_fadeout(2)
final_clip = final_clip.set_audio(CompositeAudioClip([audio_clip, music_clip]))
# Generamos el nombre del archivo y la ruta
output_filename = f"final_video_{int(time.time())}.mp4"
output_path = os.path.join(output_folder, output_filename)
# Guardamos el video
final_clip.write_videofile(output_path, codec="libx264", audio_codec="aac", fps=24)
# Limpiamos los clips
final_clip.close()
video_clip.close()
audio_clip.close()
if music_clip:
music_clip.close()
return output_path
except Exception as e:
print(f"Error combinando audio y video: {e}")
return None
def upload_to_google_drive(file_path, folder_id):
"""Sube un archivo a Google Drive y devuelve el enlace público."""
try:
creds = service_account.Credentials.from_service_account_file(
'service-account.json', scopes=['https://www.googleapis.com/auth/drive']
)
service = build('drive', 'v3', credentials=creds)
file_metadata = {
'name': os.path.basename(file_path),
'parents': [folder_id]
}
media = MediaFileUpload(file_path, resumable=True)
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
permission = {
'type': 'anyone',
'role': 'reader'
}
service.permissions().create(fileId=file['id'], body=permission).execute()
file_id = file['id']
download_link = f"https://drive.google.com/uc?export=download&id={file_id}"
return download_link
except Exception as e:
print(f"Error subiendo a Google Drive: {e}")
return None
def process_input(text, txt_file, mp3_file, selected_voice, rate, pitch, keywords):
"""Procesa la entrada del usuario y genera el video final."""
try:
# Determinamos el texto a usar
if text.strip():
final_text = text
elif txt_file is not None:
final_text = txt_file.decode("utf-8")
else:
raise ValueError("No text input provided")
# Generamos el audio
audio_file = asyncio.run(text_to_speech(final_text, selected_voice, rate, pitch))
if not audio_file:
raise ValueError("Failed to generate audio")
# Generamos el video
video_clip = concatenate_pixabay_videos(keywords, num_videos_per_keyword=1)
if not video_clip:
raise ValueError("Failed to generate video")
# Procesamos la música de fondo si existe
music_clip = None
if mp3_file is not None:
music_clip = adjust_background_music(video_clip.duration, mp3_file.name)
# Combinamos todo
final_video_path = combine_audio_video(audio_file, video_clip, music_clip)
if not final_video_path:
raise ValueError("Failed to combine audio and video")
# Subimos a Google Drive y obtenemos el enlace
download_link = upload_to_google_drive(final_video_path, folder_id=FOLDER_ID)
if download_link:
return f"[Descargar video]({download_link})"
else:
raise ValueError("Error subiendo el video a Google Drive")
except Exception as e:
print(f"Error durante el procesamiento: {e}")
return None
finally:
cleanup_temp_files() # Limpiar archivos temporales al finalizar
# Interfaz Gradio
with gr.Blocks() as demo:
gr.Markdown("# Text-to-Video Generator")
with gr.Row():
with gr.Column():
text_input = gr.Textbox(label="Write your text here", lines=5)
txt_file_input = gr.File(label="Or upload a .txt file", file_types=[".txt"])
mp3_file_input = gr.File(label="Upload background music (.mp3)", file_types=[".mp3"])
keyword_input = gr.Textbox(
label="Enter keywords separated by commas",
value="fear,religion,god,demons,aliens,possession"
)
voices = asyncio.run(get_voices())
voice_dropdown = gr.Dropdown(choices=list(voices.keys()), label="Select Voice")
rate_slider = gr.Slider(minimum=-50, maximum=50, value=0, label="Speech Rate Adjustment (%)", step=1)
pitch_slider = gr.Slider(minimum=-20, maximum=20, value=0, label="Pitch Adjustment (Hz)", step=1)
with gr.Column():
output_link = gr.Markdown("") # Mostrar el enlace de descarga
btn = gr.Button("Generate Video")
btn.click(
process_input,
inputs=[text_input, txt_file_input, mp3_file_input, voice_dropdown, rate_slider, pitch_slider, keyword_input],
outputs=output_link
)
# Leer el puerto asignado por Hugging Face
port = int(os.getenv("PORT", 7860))
# Lanzar la aplicación
demo.launch(server_name="0.0.0.0", server_port=port, share=True, show_error=True) |