Spaces:
Running
on
Zero
Running
on
Zero
File size: 14,972 Bytes
17d10a7 a15d204 d448add db46bfb 1c1b50f db46bfb 1c1b50f db8ba25 db46bfb cf3593c d9bf0f0 b950350 6aba99a 3168a3e 019c404 3168a3e cbc01c8 cf3593c 3e34a93 5607a62 cbc01c8 3e34a93 0105281 3e34a93 cbc01c8 3e34a93 dfa5d3e 3e34a93 cbc01c8 3e34a93 cbc01c8 3e34a93 cbc01c8 3e34a93 cbc01c8 2de59b3 b950350 cbc01c8 0105281 3e34a93 cbc01c8 b950350 559ca26 cbc01c8 3e34a93 cbc01c8 3e34a93 dfa5d3e cbc01c8 0105281 3e34a93 17d10a7 cbc01c8 3e34a93 cbc01c8 3e34a93 cbc01c8 3e34a93 cbc01c8 3e34a93 cf3593c cbc01c8 0105281 3e34a93 cbc01c8 ecc69bf 559ca26 cbc01c8 559ca26 3e34a93 cbc01c8 3e34a93 d9bf0f0 cbc01c8 ab6cd42 cbc01c8 3fe530b cbc01c8 |
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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
import gradio as gr
import os
import torch
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
pipeline,
AutoProcessor,
MusicgenForConditionalGeneration,
)
from scipy.io.wavfile import write
from pydub import AudioSegment
from dotenv import load_dotenv
import tempfile
import spaces
from TTS.api import TTS
# -----------------------------------------------------------
# Initialization & Environment Setup
# -----------------------------------------------------------
load_dotenv()
HF_TOKEN = os.getenv("HF_TOKEN")
# -----------------------------------------------------------
# Model Cache Management
# -----------------------------------------------------------
LLAMA_PIPELINES = {}
MUSICGEN_MODELS = {}
TTS_MODELS = {}
def get_llama_pipeline(model_id: str, token: str):
if model_id in LLAMA_PIPELINES:
return LLAMA_PIPELINES[model_id]
tokenizer = AutoTokenizer.from_pretrained(model_id, use_auth_token=token)
model = AutoModelForCausalLM.from_pretrained(
model_id,
use_auth_token=token,
torch_dtype=torch.float16,
device_map="auto",
trust_remote_code=True,
)
text_pipeline = pipeline("text-generation", model=model, tokenizer=tokenizer)
LLAMA_PIPELINES[model_id] = text_pipeline
return text_pipeline
def get_musicgen_model(model_key: str = "facebook/musicgen-large"):
if model_key in MUSICGEN_MODELS:
return MUSICGEN_MODELS[model_key]
model = MusicgenForConditionalGeneration.from_pretrained(model_key)
processor = AutoProcessor.from_pretrained(model_key)
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
MUSICGEN_MODELS[model_key] = (model, processor)
return model, processor
def get_tts_model(model_name: str = "tts_models/en/ljspeech/tacotron2-DDC"):
if model_name in TTS_MODELS:
return TTS_MODELS[model_name]
tts_model = TTS(model_name)
TTS_MODELS[model_name] = tts_model
return tts_model
# -----------------------------------------------------------
# Core Functionality
# -----------------------------------------------------------
@spaces.GPU(duration=100)
def generate_script(user_prompt: str, model_id: str, token: str, duration: int):
try:
text_pipeline = get_llama_pipeline(model_id, token)
system_prompt = f"""You are a professional audio producer creating {duration}-second content. Generate:
1. Voice script (clear and concise)
2. Sound design suggestions (specific effects)
3. Music style recommendations (genre, tempo)"""
full_prompt = f"{system_prompt}\nClient brief: {user_prompt}\nOutput:"
with torch.inference_mode():
result = text_pipeline(
full_prompt,
max_new_tokens=400,
do_sample=True,
temperature=0.7,
top_p=0.9
)
generated_text = result[0]["generated_text"].split("Output:")[-1].strip()
# Parse sections
sections = {
"Voice-Over Script:": "",
"Sound Design Suggestions:": "",
"Music Suggestions:": ""
}
current_section = None
for line in generated_text.split('\n'):
for section in sections:
if section in line:
current_section = section
line = line.replace(section, '').strip()
if current_section:
sections[current_section] += line + '\n'
return (
sections["Voice-Over Script:"].strip() or "No script generated",
sections["Sound Design Suggestions:"].strip() or "No sound design suggestions",
sections["Music Suggestions:"].strip() or "No music suggestions"
)
except Exception as e:
return f"Error: {str(e)}", "", ""
@spaces.GPU(duration=100)
def generate_voice(script: str, tts_model_name: str):
try:
if not script.strip():
return None
tts_model = get_tts_model(tts_model_name)
output_path = f"{tempfile.gettempdir()}/voice_temp.wav"
tts_model.tts_to_file(text=script, file_path=output_path)
return output_path
except Exception as e:
print(f"Voice generation error: {e}")
return None
@spaces.GPU(duration=100)
def generate_music(prompt: str, audio_length: int):
try:
model, processor = get_musicgen_model()
device = "cuda" if torch.cuda.is_available() else "cpu"
inputs = processor(text=[prompt], padding=True, return_tensors="pt").to(device)
with torch.inference_mode():
outputs = model.generate(**inputs, max_new_tokens=audio_length)
audio_data = outputs[0, 0].cpu().numpy()
normalized_audio = (audio_data / max(abs(audio_data)) * 32767).astype("int16")
output_path = f"{tempfile.gettempdir()}/music_temp.wav"
write(output_path, 44100, normalized_audio)
return output_path
except Exception as e:
print(f"Music generation error: {e}")
return None
@spaces.GPU(duration=100)
def blend_audio(voice_path: str, music_path: str, ducking: bool, duck_level: int):
try:
voice = AudioSegment.from_wav(voice_path)
music = AudioSegment.from_wav(music_path)
# Adjust music length
if len(music) < len(voice):
loops_needed = (len(voice) // len(music)) + 1
music = music * loops_needed
music = music[:len(voice)]
# Ducking effect
if ducking:
ducked_music = music - duck_level
final_audio = ducked_music.overlay(voice)
else:
final_audio = music.overlay(voice)
output_path = f"{tempfile.gettempdir()}/final_mix.wav"
final_audio.export(output_path, format="wav")
return output_path
except Exception as e:
print(f"Mixing error: {e}")
return None
# -----------------------------------------------------------
# Enhanced UI Components
# -----------------------------------------------------------
custom_css = """
#main-container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background: #f5f5f5;
border-radius: 15px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.header {
text-align: center;
padding: 2em;
background: linear-gradient(135deg, #2b5876 0%, #4e4376 100%);
color: white;
border-radius: 15px;
margin-bottom: 2em;
}
.tab-nav {
background: none !important;
border: none !important;
}
.tab-button {
padding: 1em 2em !important;
border-radius: 8px !important;
margin: 0 5px !important;
transition: all 0.3s ease !important;
}
.tab-button:hover {
transform: translateY(-2px);
box-shadow: 0 3px 6px rgba(0,0,0,0.1);
}
.dark-btn {
background: linear-gradient(135deg, #434343 0%, #000000 100%) !important;
color: white !important;
border: none !important;
padding: 12px 24px !important;
border-radius: 8px !important;
}
.output-card {
background: white !important;
border-radius: 10px !important;
padding: 20px !important;
box-shadow: 0 2px 4px rgba(0,0,0,0.05) !important;
}
.progress-indicator {
color: #666;
font-style: italic;
margin-top: 10px;
}
"""
with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
with gr.Column(elem_id="main-container"):
# Header Section
with gr.Column(elem_classes="header"):
gr.Markdown("""
# ποΈ AI Promo Studio
**Professional Audio Production Suite Powered by AI**
""")
# Main Workflow Tabs
with gr.Tabs(elem_classes="tab-nav"):
# Script Generation
with gr.Tab("π Script Design", elem_classes="tab-button"):
with gr.Row(equal_height=False):
with gr.Column(scale=2):
gr.Markdown("### π― Project Brief")
user_prompt = gr.Textbox(
label="Describe your promo concept",
placeholder="e.g., 'An intense 30-second movie trailer intro with epic orchestral music and dramatic sound effects...'",
lines=4
)
with gr.Row():
duration = gr.Slider(
label="Duration (seconds)",
minimum=15,
maximum=120,
step=15,
value=30,
interactive=True
)
llama_model_id = gr.Dropdown(
label="AI Model",
choices=["meta-llama/Meta-Llama-3-8B-Instruct"],
value="meta-llama/Meta-Llama-3-8B-Instruct",
interactive=True
)
generate_btn = gr.Button("Generate Script π", elem_classes="dark-btn")
with gr.Column(scale=1, elem_classes="output-card"):
gr.Markdown("### π Generated Content")
script_output = gr.Textbox(label="Voice Script", lines=6)
sound_design_output = gr.Textbox(label="Sound Design", lines=3)
music_suggestion_output = gr.Textbox(label="Music Style", lines=3)
# Voice Production
with gr.Tab("ποΈ Voice Production", elem_classes="tab-button"):
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### π Voice Settings")
tts_model = gr.Dropdown(
label="Voice Model",
choices=[
"tts_models/en/ljspeech/tacotron2-DDC",
"tts_models/en/ljspeech/vits",
"tts_models/en/sam/tacotron-DDC"
],
value="tts_models/en/ljspeech/tacotron2-DDC",
interactive=True
)
with gr.Row():
voice_preview_btn = gr.Button("Preview Sample", elem_classes="dark-btn")
voice_generate_btn = gr.Button("Generate Full Voiceover", elem_classes="dark-btn")
with gr.Column(scale=1, elem_classes="output-card"):
gr.Markdown("### π§ Voice Preview")
voice_audio = gr.Audio(
label="Generated Voice",
interactive=False,
waveform_options={"show_controls": True}
)
# Music Production
with gr.Tab("π΅ Music Design", elem_classes="tab-button"):
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### πΉ Music Parameters")
audio_length = gr.Slider(
label="Generation Length",
minimum=256,
maximum=1024,
step=64,
value=512,
info="Higher values = longer generation time"
)
music_generate_btn = gr.Button("Generate Music Track", elem_classes="dark-btn")
with gr.Column(scale=1, elem_classes="output-card"):
gr.Markdown("### πΆ Music Preview")
music_output = gr.Audio(
label="Generated Music",
interactive=False,
waveform_options={"show_controls": True}
)
# Final Mix
with gr.Tab("π Final Mix", elem_classes="tab-button"):
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### ποΈ Mixing Console")
ducking_enabled = gr.Checkbox(
label="Enable Voice Ducking",
value=True,
info="Automatically lower music during voice segments"
)
duck_level = gr.Slider(
label="Ducking Intensity (dB)",
minimum=3,
maximum=20,
step=1,
value=10
)
mix_btn = gr.Button("Generate Final Mix", elem_classes="dark-btn")
with gr.Column(scale=1, elem_classes="output-card"):
gr.Markdown("### π§ Final Production")
final_mix = gr.Audio(
label="Mixed Output",
interactive=False,
waveform_options={"show_controls": True}
)
# Footer
with gr.Column(elem_classes="output-card"):
gr.Markdown("""
<div style="text-align: center; padding: 1.5em 0;">
<a href="https://bilsimaging.com" target="_blank">
<img src="https://bilsimaging.com/logo.png" alt="Bils Imaging" style="height: 35px; margin-right: 15px;">
</a>
<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FBils%2Fradiogold">
<img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FBils%2Fradiogold&countColor=%23263759" />
</a>
</div>
<p style="text-align: center; color: #666; font-size: 0.9em;">
Professional Audio Production Suite v2.1 Β© 2024 | Bils Imaging
</p>
""")
# Event Handling
generate_btn.click(
generate_script,
inputs=[user_prompt, llama_model_id, gr.Textbox(HF_TOKEN, visible=False), duration],
outputs=[script_output, sound_design_output, music_suggestion_output]
)
voice_generate_btn.click(
generate_voice,
inputs=[script_output, tts_model],
outputs=voice_audio
)
music_generate_btn.click(
generate_music,
inputs=[music_suggestion_output, audio_length],
outputs=music_output
)
mix_btn.click(
blend_audio,
inputs=[voice_audio, music_output, ducking_enabled, duck_level],
outputs=final_mix
)
if __name__ == "__main__":
demo.launch(debug=True) |