|
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 googleapiclient.discovery import build |
|
from google.oauth2 import service_account |
|
from googleapiclient.http import MediaFileUpload |
|
from io import BytesIO |
|
|
|
|
|
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) |
|
|
|
|
|
output_folder = "outputs" |
|
temp_dir = "temp_files" |
|
os.makedirs(output_folder, exist_ok=True) |
|
os.makedirs(temp_dir, exist_ok=True) |
|
|
|
|
|
FOLDER_ID = "12S6adpanAXjf71pKKGRRPqpzbJa5XEh3" |
|
|
|
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_and_blur_video(clip, target_width=1920, target_height=1080): |
|
"""Redimensiona el video al tama帽o 1080p (16:9) y aplica desenfoque si es necesario.""" |
|
|
|
|
|
def download_video(link): |
|
"""Descarga un video desde un enlace y lo guarda en la carpeta temporal.""" |
|
|
|
|
|
def concatenate_pixabay_videos(keywords, num_videos_per_keyword=1): |
|
"""Concatena videos de Pixabay basados en palabras clave.""" |
|
|
|
|
|
def adjust_background_music(video_duration, music_file): |
|
"""Ajusta la m煤sica de fondo para que coincida con la duraci贸n del video.""" |
|
|
|
|
|
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 |
|
|
|
|
|
video_clip = video_clip.loop(duration=total_duration) |
|
video_clip = video_clip.set_duration(total_duration).fadeout(2) |
|
|
|
|
|
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])) |
|
|
|
|
|
output_filename = f"final_video_{int(time.time())}.mp4" |
|
output_path = os.path.join(output_folder, output_filename) |
|
|
|
|
|
final_clip.write_videofile(output_path, codec="libx264", audio_codec="aac", fps=24) |
|
|
|
|
|
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}") |
|
if 'final_clip' in locals(): |
|
final_clip.close() |
|
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: |
|
|
|
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") |
|
|
|
|
|
audio_file = asyncio.run(text_to_speech(final_text, selected_voice, rate, pitch)) |
|
if not audio_file: |
|
raise ValueError("Failed to generate audio") |
|
|
|
|
|
video_clip = concatenate_pixabay_videos(keywords, num_videos_per_keyword=1) |
|
if not video_clip: |
|
raise ValueError("Failed to generate video") |
|
|
|
|
|
music_clip = None |
|
if mp3_file is not None: |
|
music_clip = adjust_background_music(video_clip.duration, mp3_file.name) |
|
|
|
|
|
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") |
|
|
|
download_link = upload_to_google_drive(final_video_path, folder_id=FOLDER_ID) |
|
if download_link: |
|
print(f"Video subido a Google Drive. Enlace de descarga: {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() |
|
|
|
|
|
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 (e.g., universe, galaxy, forest, cat)", |
|
value="fear, religion, god, demons, aliens, possession, galaxy, mysterious, dystopian, astral, warfare, space, space, galaxy, moon, fear, astral, god, evil, mystery, cosmos, stars, paranormal, inexplicable, hidden, enigma, unknown, unusual, intriguing, curious, strange, supernatural, esoteric, arcane, occultism, supernatural, mystery, phenomenon, rare, unusual, enigmatic, sinister, gloomy, dark, shadowy, macabre, eerie, chilling, cursed, fantastic, unreal, unknown, mysterious, enigmatic, inexplicable, unusual, strange, unusual, arcane, esoteric, hidden, shadowy, dark, gloomy, sinister, macabre, eerie, chilling, cursed, fantastic, unreal, paranormal, supernatural, occultism, phenomenon, rare, intriguing, curious" |
|
) |
|
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("") |
|
|
|
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 |
|
) |
|
|
|
|
|
port = int(os.getenv("PORT", 7860)) |
|
|
|
|
|
demo.launch(server_name="0.0.0.0", server_port=port, share=True, show_error=True) |
|
|