Spaces:
No application file
No application file
File size: 8,378 Bytes
5ef8189 | 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 | import gradio as gr
import torch
from transformers import AutoProcessor, MusicgenForConditionalGeneration
import scipy.io.wavfile
import numpy as np
import base64
import io
import json
import os
from datetime import datetime
print("=" * 50)
print("AI Music Studio API - Starting up...")
print("=" * 50)
# Model cache
models = {}
PROCESSOR = None
MODEL = None
DEVICE = None
def load_model(model_name="facebook/musicgen-medium"):
"""Load or retrieve cached model"""
global PROCESSOR, MODEL, DEVICE
if MODEL is not None:
return True
try:
print(f"Loading {model_name}...")
PROCESSOR = AutoProcessor.from_pretrained(model_name)
MODEL = MusicgenForConditionalGeneration.from_pretrained(model_name)
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
MODEL = MODEL.to(DEVICE)
MODEL.eval()
param_count = sum(p.numel() for p in MODEL.parameters()) / 1e9
print(f"β
Model loaded: {param_count:.1f}B parameters on {DEVICE}")
return True
except Exception as e:
print(f"β Model load failed: {e}")
return False
def generate_section(prompt, duration, guidance=3.0, temperature=1.0, prev_audio=None):
"""Generate a single section of music"""
global PROCESSOR, MODEL, DEVICE
max_tokens = int(duration) * 50
# Build conditioning if previous audio exists
if prev_audio is not None:
inputs = PROCESSOR(
audio=prev_audio,
text=[prompt],
padding=True,
return_tensors="pt",
).to(DEVICE)
else:
inputs = PROCESSOR(
text=[prompt],
padding=True,
return_tensors="pt",
).to(DEVICE)
with torch.no_grad():
audio_values = MODEL.generate(
**inputs,
max_new_tokens=max_tokens,
guidance_scale=guidance,
temperature=temperature,
do_sample=True,
)
audio_data = audio_values[0, 0].cpu().numpy()
sr = MODEL.config.audio_encoder.sampling_rate
return np.clip(audio_data, -1.0, 1.0), sr
def crossfade(audio1, audio2, sr, overlap_seconds=2):
"""Smooth crossfade between two audio segments"""
overlap_samples = int(overlap_seconds * sr)
if len(audio1) < overlap_samples or len(audio2) < overlap_samples:
return np.concatenate([audio1, audio2])
fade_out = np.linspace(1, 0, overlap_samples)
fade_in = np.linspace(0, 1, overlap_samples)
combined = np.concatenate([
audio1[:-overlap_samples],
audio1[-overlap_samples:] * fade_out + audio2[:overlap_samples] * fade_in,
audio2[overlap_samples:]
])
return combined
def generate_music(prompt, duration, model_choice, structure_json, guidance, temperature):
"""
Main generation function with structure support
Returns base64 encoded audio
"""
try:
# Load model
if not load_model(model_choice):
return "Error: Failed to load model", None
# Parse structure
try:
structure = json.loads(structure_json) if structure_json else [{"name": "Full", "duration": int(duration), "desc": ""}]
except:
structure = [{"name": "Full", "duration": int(duration), "desc": ""}]
print(f"Generating with structure: {[s['name'] for s in structure]}")
# Generate each section
all_audio = []
sr = None
for i, section in enumerate(structure):
print(f"Generating section {i+1}/{len(structure)}: {section['name']}")
# Build full prompt
full_prompt = f"{prompt}. {section['desc']}".strip()
section_duration = section['duration']
# Add overlap for crossfade (except first)
gen_duration = section_duration + (2 if i > 0 else 0)
# Generate
audio, sr = generate_section(full_prompt, gen_duration, guidance, temperature,
all_audio[-1] if all_audio else None)
# Crossfade with previous
if all_audio:
audio = crossfade(all_audio[-1], audio, sr, 2)
all_audio[-1] = audio # Replace with crossfaded version
else:
all_audio.append(audio)
# Final audio is the last (fully crossfaded) segment
final_audio = all_audio[-1]
# Trim to exact total duration
total_duration = sum(s['duration'] for s in structure)
target_samples = int(total_duration * sr)
if len(final_audio) > target_samples:
final_audio = final_audio[:target_samples]
# Normalize
final_audio = np.clip(final_audio, -1.0, 1.0)
if np.max(np.abs(final_audio)) > 0:
final_audio = final_audio / np.max(np.abs(final_audio)) * 0.95
# Convert to WAV bytes then base64
buffer = io.BytesIO()
scipy.io.wavfile.write(buffer, sr, (final_audio * 32767).astype(np.int16))
buffer.seek(0)
audio_b64 = base64.b64encode(buffer.read()).decode('utf-8')
# Also create file for Gradio audio output
output_path = "/tmp/generated_music.wav"
scipy.io.wavfile.write(output_path, sr, (final_audio * 32767).astype(np.int16))
print(f"β
Generation complete: {total_duration}s @ {sr}Hz")
return audio_b64, output_path
except Exception as e:
print(f"β Generation error: {e}")
import traceback
traceback.print_exc()
return f"Error: {str(e)}", None
# Load model on startup
print("Pre-loading model...")
load_model()
# Create Gradio interface
with gr.Blocks(title="AI Music Studio API") as demo:
gr.Markdown("""
# π΅ AI Music Studio API
Backend service for web music generation. Use the API endpoint for programmatic access.
**API Endpoint:** `/api/predict`
""")
with gr.Row():
with gr.Column():
prompt = gr.Textbox(
label="Music Prompt",
placeholder="e.g., Epic orchestral soundtrack with thunderous drums",
lines=2
)
duration = gr.Slider(5, 30, 10, step=1, label="Duration per section (seconds)")
model = gr.Dropdown(
choices=[
"facebook/musicgen-small",
"facebook/musicgen-medium",
"facebook/musicgen-large",
"facebook/musicgen-melody"
],
value="facebook/musicgen-medium",
label="Model"
)
structure = gr.Textbox(
label="Structure JSON",
placeholder='[{"name": "Intro", "duration": 10, "desc": "quiet start"}]',
value="",
visible=False # Hidden, used via API
)
guidance = gr.Slider(1.0, 10.0, 3.0, step=0.5, label="Guidance Scale")
temperature = gr.Slider(0.1, 2.0, 1.0, step=0.1, label="Temperature")
generate_btn = gr.Button("π Generate", variant="primary")
with gr.Column():
audio_output = gr.Audio(label="Generated Music", type="filepath")
base64_output = gr.Textbox(
label="Base64 Output (for API)",
lines=3,
max_lines=5
)
generate_btn.click(
fn=generate_music,
inputs=[prompt, duration, model, structure, guidance, temperature],
outputs=[base64_output, audio_output]
)
gr.Markdown("""
### API Usage Example
```python
import requests
response = requests.post(
"https://your-username-musicgen-api.hf.space/api/predict",
json={
"data": [
"Epic orchestral music",
10,
"facebook/musicgen-medium",
'[{"name": "Full", "duration": 10, "desc": ""}]',
3.0,
1.0
]
}
)
audio_b64 = response.json()["data"][0]
```
""")
if __name__ == "__main__":
demo.launch() |