Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,8 @@
|
|
1 |
-
import gradio as gr
|
2 |
import os
|
|
|
3 |
import torch
|
|
|
|
|
4 |
from transformers import (
|
5 |
AutoTokenizer,
|
6 |
AutoModelForCausalLM,
|
@@ -29,6 +31,7 @@ MUSICGEN_MODELS = {}
|
|
29 |
TTS_MODELS = {}
|
30 |
|
31 |
def get_llama_pipeline(model_id: str, token: str):
|
|
|
32 |
if model_id in LLAMA_PIPELINES:
|
33 |
return LLAMA_PIPELINES[model_id]
|
34 |
|
@@ -45,6 +48,7 @@ def get_llama_pipeline(model_id: str, token: str):
|
|
45 |
return text_pipeline
|
46 |
|
47 |
def get_musicgen_model(model_key: str = "facebook/musicgen-large"):
|
|
|
48 |
if model_key in MUSICGEN_MODELS:
|
49 |
return MUSICGEN_MODELS[model_key]
|
50 |
|
@@ -56,6 +60,7 @@ def get_musicgen_model(model_key: str = "facebook/musicgen-large"):
|
|
56 |
return model, processor
|
57 |
|
58 |
def get_tts_model(model_name: str = "tts_models/en/ljspeech/tacotron2-DDC"):
|
|
|
59 |
if model_name in TTS_MODELS:
|
60 |
return TTS_MODELS[model_name]
|
61 |
tts_model = TTS(model_name)
|
@@ -67,12 +72,21 @@ def get_tts_model(model_name: str = "tts_models/en/ljspeech/tacotron2-DDC"):
|
|
67 |
# -----------------------------------------------------------
|
68 |
@spaces.GPU(duration=100)
|
69 |
def generate_script(user_prompt: str, model_id: str, token: str, duration: int):
|
|
|
|
|
|
|
|
|
70 |
try:
|
71 |
text_pipeline = get_llama_pipeline(model_id, token)
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
|
|
|
|
|
|
|
|
|
|
76 |
|
77 |
full_prompt = f"{system_prompt}\nClient brief: {user_prompt}\nOutput:"
|
78 |
|
@@ -87,7 +101,7 @@ def generate_script(user_prompt: str, model_id: str, token: str, duration: int):
|
|
87 |
|
88 |
generated_text = result[0]["generated_text"].split("Output:")[-1].strip()
|
89 |
|
90 |
-
# Parse sections
|
91 |
sections = {
|
92 |
"Voice-Over Script:": "",
|
93 |
"Sound Design Suggestions:": "",
|
@@ -99,7 +113,9 @@ def generate_script(user_prompt: str, model_id: str, token: str, duration: int):
|
|
99 |
for section in sections:
|
100 |
if section in line:
|
101 |
current_section = section
|
|
|
102 |
line = line.replace(section, '').strip()
|
|
|
103 |
if current_section:
|
104 |
sections[current_section] += line + '\n'
|
105 |
|
@@ -114,19 +130,41 @@ def generate_script(user_prompt: str, model_id: str, token: str, duration: int):
|
|
114 |
|
115 |
@spaces.GPU(duration=100)
|
116 |
def generate_voice(script: str, tts_model_name: str):
|
|
|
|
|
|
|
117 |
try:
|
118 |
if not script.strip():
|
119 |
return None
|
120 |
tts_model = get_tts_model(tts_model_name)
|
121 |
-
|
|
|
122 |
tts_model.tts_to_file(text=script, file_path=output_path)
|
123 |
return output_path
|
124 |
except Exception as e:
|
125 |
print(f"Voice generation error: {e}")
|
126 |
return None
|
127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
@spaces.GPU(duration=100)
|
129 |
def generate_music(prompt: str, audio_length: int):
|
|
|
|
|
|
|
130 |
try:
|
131 |
model, processor = get_musicgen_model()
|
132 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
@@ -135,9 +173,15 @@ def generate_music(prompt: str, audio_length: int):
|
|
135 |
with torch.inference_mode():
|
136 |
outputs = model.generate(**inputs, max_new_tokens=audio_length)
|
137 |
|
|
|
138 |
audio_data = outputs[0, 0].cpu().numpy()
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
|
|
|
|
141 |
write(output_path, 44100, normalized_audio)
|
142 |
return output_path
|
143 |
except Exception as e:
|
@@ -146,24 +190,27 @@ def generate_music(prompt: str, audio_length: int):
|
|
146 |
|
147 |
@spaces.GPU(duration=100)
|
148 |
def blend_audio(voice_path: str, music_path: str, ducking: bool, duck_level: int):
|
|
|
|
|
|
|
|
|
149 |
try:
|
150 |
voice = AudioSegment.from_wav(voice_path)
|
151 |
music = AudioSegment.from_wav(music_path)
|
152 |
|
153 |
-
#
|
154 |
if len(music) < len(voice):
|
155 |
loops_needed = (len(voice) // len(music)) + 1
|
156 |
music = music * loops_needed
|
157 |
music = music[:len(voice)]
|
158 |
|
159 |
-
# Ducking effect
|
160 |
if ducking:
|
161 |
ducked_music = music - duck_level
|
162 |
final_audio = ducked_music.overlay(voice)
|
163 |
else:
|
164 |
final_audio = music.overlay(voice)
|
165 |
|
166 |
-
output_path = f"{
|
167 |
final_audio.export(output_path, format="wav")
|
168 |
return output_path
|
169 |
except Exception as e:
|
@@ -268,7 +315,7 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
268 |
|
269 |
# Main Workflow Tabs
|
270 |
with gr.Tabs(elem_classes="tab-nav"):
|
271 |
-
# Script Generation
|
272 |
with gr.Tab("π Script Design", elem_classes="tab-button"):
|
273 |
with gr.Row(equal_height=False):
|
274 |
with gr.Column(scale=2):
|
@@ -301,7 +348,7 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
301 |
sound_design_output = gr.Textbox(label="Sound Design", lines=3)
|
302 |
music_suggestion_output = gr.Textbox(label="Music Style", lines=3)
|
303 |
|
304 |
-
# Voice Production
|
305 |
with gr.Tab("ποΈ Voice Production", elem_classes="tab-button"):
|
306 |
with gr.Row():
|
307 |
with gr.Column(scale=1):
|
@@ -327,7 +374,7 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
327 |
waveform_options={"show_controls": True}
|
328 |
)
|
329 |
|
330 |
-
# Music Production
|
331 |
with gr.Tab("π΅ Music Design", elem_classes="tab-button"):
|
332 |
with gr.Row():
|
333 |
with gr.Column(scale=1):
|
@@ -349,7 +396,7 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
349 |
waveform_options={"show_controls": True}
|
350 |
)
|
351 |
|
352 |
-
# Final Mix
|
353 |
with gr.Tab("π Final Mix", elem_classes="tab-button"):
|
354 |
with gr.Row():
|
355 |
with gr.Column(scale=1):
|
@@ -375,7 +422,7 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
375 |
waveform_options={"show_controls": True}
|
376 |
)
|
377 |
|
378 |
-
# Footer
|
379 |
with gr.Column(elem_classes="output-card"):
|
380 |
gr.Markdown("""
|
381 |
<div style="text-align: center; padding: 1.5em 0;">
|
@@ -391,13 +438,26 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
391 |
</p>
|
392 |
""")
|
393 |
|
|
|
394 |
# Event Handling
|
|
|
|
|
|
|
|
|
395 |
generate_btn.click(
|
396 |
generate_script,
|
397 |
-
inputs=[user_prompt, llama_model_id,
|
398 |
outputs=[script_output, sound_design_output, music_suggestion_output]
|
399 |
)
|
400 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
401 |
voice_generate_btn.click(
|
402 |
generate_voice,
|
403 |
inputs=[script_output, tts_model],
|
@@ -417,4 +477,4 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
417 |
)
|
418 |
|
419 |
if __name__ == "__main__":
|
420 |
-
demo.launch(debug=True)
|
|
|
|
|
1 |
import os
|
2 |
+
import uuid
|
3 |
import torch
|
4 |
+
import numpy as np
|
5 |
+
import gradio as gr
|
6 |
from transformers import (
|
7 |
AutoTokenizer,
|
8 |
AutoModelForCausalLM,
|
|
|
31 |
TTS_MODELS = {}
|
32 |
|
33 |
def get_llama_pipeline(model_id: str, token: str):
|
34 |
+
"""Load and cache the LLaMA text-generation pipeline."""
|
35 |
if model_id in LLAMA_PIPELINES:
|
36 |
return LLAMA_PIPELINES[model_id]
|
37 |
|
|
|
48 |
return text_pipeline
|
49 |
|
50 |
def get_musicgen_model(model_key: str = "facebook/musicgen-large"):
|
51 |
+
"""Load and cache the MusicGen model and processor."""
|
52 |
if model_key in MUSICGEN_MODELS:
|
53 |
return MUSICGEN_MODELS[model_key]
|
54 |
|
|
|
60 |
return model, processor
|
61 |
|
62 |
def get_tts_model(model_name: str = "tts_models/en/ljspeech/tacotron2-DDC"):
|
63 |
+
"""Load and cache the TTS model."""
|
64 |
if model_name in TTS_MODELS:
|
65 |
return TTS_MODELS[model_name]
|
66 |
tts_model = TTS(model_name)
|
|
|
72 |
# -----------------------------------------------------------
|
73 |
@spaces.GPU(duration=100)
|
74 |
def generate_script(user_prompt: str, model_id: str, token: str, duration: int):
|
75 |
+
"""
|
76 |
+
Generate a professional promo script including a voice-over script,
|
77 |
+
sound design suggestions, and music recommendations.
|
78 |
+
"""
|
79 |
try:
|
80 |
text_pipeline = get_llama_pipeline(model_id, token)
|
81 |
+
# Updated prompt to instruct the model to output sections with explicit headers.
|
82 |
+
system_prompt = (
|
83 |
+
f"You are a professional audio producer creating {duration}-second content. "
|
84 |
+
"Please generate the following three sections exactly as shown:\n\n"
|
85 |
+
"Voice-Over Script: [A clear and concise script for the voiceover.]\n"
|
86 |
+
"Sound Design Suggestions: [Specific ideas, effects, and ambience recommendations.]\n"
|
87 |
+
"Music Suggestions: [Recommendations for music style, genre, and tempo.]\n\n"
|
88 |
+
"Make sure each section starts with its header exactly."
|
89 |
+
)
|
90 |
|
91 |
full_prompt = f"{system_prompt}\nClient brief: {user_prompt}\nOutput:"
|
92 |
|
|
|
101 |
|
102 |
generated_text = result[0]["generated_text"].split("Output:")[-1].strip()
|
103 |
|
104 |
+
# Parse the output into the three expected sections.
|
105 |
sections = {
|
106 |
"Voice-Over Script:": "",
|
107 |
"Sound Design Suggestions:": "",
|
|
|
113 |
for section in sections:
|
114 |
if section in line:
|
115 |
current_section = section
|
116 |
+
# Remove header from the line.
|
117 |
line = line.replace(section, '').strip()
|
118 |
+
break
|
119 |
if current_section:
|
120 |
sections[current_section] += line + '\n'
|
121 |
|
|
|
130 |
|
131 |
@spaces.GPU(duration=100)
|
132 |
def generate_voice(script: str, tts_model_name: str):
|
133 |
+
"""
|
134 |
+
Generate full voice-over audio from the provided script using a TTS model.
|
135 |
+
"""
|
136 |
try:
|
137 |
if not script.strip():
|
138 |
return None
|
139 |
tts_model = get_tts_model(tts_model_name)
|
140 |
+
# Create a unique temporary file name for the output.
|
141 |
+
output_path = os.path.join(tempfile.gettempdir(), f"voice_{uuid.uuid4().hex}.wav")
|
142 |
tts_model.tts_to_file(text=script, file_path=output_path)
|
143 |
return output_path
|
144 |
except Exception as e:
|
145 |
print(f"Voice generation error: {e}")
|
146 |
return None
|
147 |
|
148 |
+
@spaces.GPU(duration=100)
|
149 |
+
def generate_voice_preview(script: str, tts_model_name: str):
|
150 |
+
"""
|
151 |
+
Generate a short preview of the voice-over by taking the first 100 words.
|
152 |
+
"""
|
153 |
+
try:
|
154 |
+
if not script.strip():
|
155 |
+
return None
|
156 |
+
words = script.split()
|
157 |
+
preview_text = ' '.join(words[:100]) if len(words) > 100 else script
|
158 |
+
return generate_voice(preview_text, tts_model_name)
|
159 |
+
except Exception as e:
|
160 |
+
print(f"Voice preview error: {e}")
|
161 |
+
return None
|
162 |
+
|
163 |
@spaces.GPU(duration=100)
|
164 |
def generate_music(prompt: str, audio_length: int):
|
165 |
+
"""
|
166 |
+
Generate music audio from a text prompt using the MusicGen model.
|
167 |
+
"""
|
168 |
try:
|
169 |
model, processor = get_musicgen_model()
|
170 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
173 |
with torch.inference_mode():
|
174 |
outputs = model.generate(**inputs, max_new_tokens=audio_length)
|
175 |
|
176 |
+
# Assuming outputs[0, 0] holds the generated audio waveform.
|
177 |
audio_data = outputs[0, 0].cpu().numpy()
|
178 |
+
# Prevent division by zero during normalization.
|
179 |
+
max_val = np.max(np.abs(audio_data))
|
180 |
+
if max_val == 0:
|
181 |
+
normalized_audio = audio_data.astype("int16")
|
182 |
+
else:
|
183 |
+
normalized_audio = (audio_data / max_val * 32767).astype("int16")
|
184 |
+
output_path = os.path.join(tempfile.gettempdir(), f"music_{uuid.uuid4().hex}.wav")
|
185 |
write(output_path, 44100, normalized_audio)
|
186 |
return output_path
|
187 |
except Exception as e:
|
|
|
190 |
|
191 |
@spaces.GPU(duration=100)
|
192 |
def blend_audio(voice_path: str, music_path: str, ducking: bool, duck_level: int):
|
193 |
+
"""
|
194 |
+
Blend the generated voice and music audio files.
|
195 |
+
If ducking is enabled, lower the music volume during the voice segments.
|
196 |
+
"""
|
197 |
try:
|
198 |
voice = AudioSegment.from_wav(voice_path)
|
199 |
music = AudioSegment.from_wav(music_path)
|
200 |
|
201 |
+
# Loop the music track if it's shorter than the voice track.
|
202 |
if len(music) < len(voice):
|
203 |
loops_needed = (len(voice) // len(music)) + 1
|
204 |
music = music * loops_needed
|
205 |
music = music[:len(voice)]
|
206 |
|
|
|
207 |
if ducking:
|
208 |
ducked_music = music - duck_level
|
209 |
final_audio = ducked_music.overlay(voice)
|
210 |
else:
|
211 |
final_audio = music.overlay(voice)
|
212 |
|
213 |
+
output_path = os.path.join(tempfile.gettempdir(), f"final_mix_{uuid.uuid4().hex}.wav")
|
214 |
final_audio.export(output_path, format="wav")
|
215 |
return output_path
|
216 |
except Exception as e:
|
|
|
315 |
|
316 |
# Main Workflow Tabs
|
317 |
with gr.Tabs(elem_classes="tab-nav"):
|
318 |
+
# Script Generation Tab
|
319 |
with gr.Tab("π Script Design", elem_classes="tab-button"):
|
320 |
with gr.Row(equal_height=False):
|
321 |
with gr.Column(scale=2):
|
|
|
348 |
sound_design_output = gr.Textbox(label="Sound Design", lines=3)
|
349 |
music_suggestion_output = gr.Textbox(label="Music Style", lines=3)
|
350 |
|
351 |
+
# Voice Production Tab
|
352 |
with gr.Tab("ποΈ Voice Production", elem_classes="tab-button"):
|
353 |
with gr.Row():
|
354 |
with gr.Column(scale=1):
|
|
|
374 |
waveform_options={"show_controls": True}
|
375 |
)
|
376 |
|
377 |
+
# Music Production Tab
|
378 |
with gr.Tab("π΅ Music Design", elem_classes="tab-button"):
|
379 |
with gr.Row():
|
380 |
with gr.Column(scale=1):
|
|
|
396 |
waveform_options={"show_controls": True}
|
397 |
)
|
398 |
|
399 |
+
# Final Mix Tab
|
400 |
with gr.Tab("π Final Mix", elem_classes="tab-button"):
|
401 |
with gr.Row():
|
402 |
with gr.Column(scale=1):
|
|
|
422 |
waveform_options={"show_controls": True}
|
423 |
)
|
424 |
|
425 |
+
# Footer Section
|
426 |
with gr.Column(elem_classes="output-card"):
|
427 |
gr.Markdown("""
|
428 |
<div style="text-align: center; padding: 1.5em 0;">
|
|
|
438 |
</p>
|
439 |
""")
|
440 |
|
441 |
+
# -----------------------------------------------------------
|
442 |
# Event Handling
|
443 |
+
# -----------------------------------------------------------
|
444 |
+
# Hidden textbox for HF_TOKEN (its value is set via the environment variable).
|
445 |
+
hf_token_hidden = gr.Textbox(value=HF_TOKEN, visible=False)
|
446 |
+
|
447 |
generate_btn.click(
|
448 |
generate_script,
|
449 |
+
inputs=[user_prompt, llama_model_id, hf_token_hidden, duration],
|
450 |
outputs=[script_output, sound_design_output, music_suggestion_output]
|
451 |
)
|
452 |
|
453 |
+
# Voice preview: generates a trimmed version of the script.
|
454 |
+
voice_preview_btn.click(
|
455 |
+
generate_voice_preview,
|
456 |
+
inputs=[script_output, tts_model],
|
457 |
+
outputs=voice_audio
|
458 |
+
)
|
459 |
+
|
460 |
+
# Full voice generation using the complete script.
|
461 |
voice_generate_btn.click(
|
462 |
generate_voice,
|
463 |
inputs=[script_output, tts_model],
|
|
|
477 |
)
|
478 |
|
479 |
if __name__ == "__main__":
|
480 |
+
demo.launch(debug=True)
|