Update app.py
Browse files
app.py
CHANGED
|
@@ -7,50 +7,70 @@ import scipy.io.wavfile
|
|
| 7 |
import io
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
-
# 1. Model Loading
|
| 11 |
MODEL_ID = "facebook/musicgen-small"
|
| 12 |
device = "cpu"
|
| 13 |
|
| 14 |
-
print(f"Loading model {MODEL_ID}...")
|
| 15 |
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
| 16 |
model = MusicgenForConditionalGeneration.from_pretrained(MODEL_ID, torch_dtype=torch.float32)
|
| 17 |
model.to(device)
|
| 18 |
-
print("Model loaded
|
| 19 |
|
| 20 |
def generate_core(prompt, duration):
|
| 21 |
if not prompt:
|
|
|
|
| 22 |
return None
|
| 23 |
|
| 24 |
-
|
| 25 |
-
inputs = processor(text=[prompt], padding=True, return_tensors="pt").to(device)
|
| 26 |
-
max_tokens = int(duration * 50)
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
# 2. FastAPI
|
| 36 |
app = FastAPI()
|
| 37 |
|
| 38 |
@app.post("/generate")
|
| 39 |
async def api_generate(prompt: str = Query(...), duration: int = Query(10)):
|
| 40 |
try:
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
byte_io = io.BytesIO()
|
| 43 |
scipy.io.wavfile.write(byte_io, rate=sr, data=audio)
|
| 44 |
return Response(content=byte_io.getvalue(), media_type="audio/wav")
|
| 45 |
except Exception as e:
|
| 46 |
raise HTTPException(status_code=500, detail=str(e))
|
| 47 |
|
| 48 |
-
# 3. Gradio Interface
|
| 49 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 50 |
gr.Markdown("# 🎵 MusicGen Automation Hub")
|
| 51 |
with gr.Row():
|
| 52 |
with gr.Column():
|
| 53 |
-
p_in = gr.Textbox(label="Prompt", placeholder="
|
| 54 |
d_in = gr.Slider(1, 30, value=10, label="Duration (sec)")
|
| 55 |
run_btn = gr.Button("Generate", variant="primary")
|
| 56 |
with gr.Column():
|
|
@@ -58,7 +78,9 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 58 |
|
| 59 |
run_btn.click(generate_core, [p_in, d_in], a_out)
|
| 60 |
|
| 61 |
-
# 4.
|
| 62 |
-
#
|
| 63 |
-
|
|
|
|
|
|
|
| 64 |
app = gr.mount_gradio_app(app, demo, path="/")
|
|
|
|
| 7 |
import io
|
| 8 |
import numpy as np
|
| 9 |
|
| 10 |
+
# 1. Resource-Optimized Model Loading
|
| 11 |
MODEL_ID = "facebook/musicgen-small"
|
| 12 |
device = "cpu"
|
| 13 |
|
| 14 |
+
print(f"DEBUG: Loading model {MODEL_ID}...")
|
| 15 |
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
| 16 |
model = MusicgenForConditionalGeneration.from_pretrained(MODEL_ID, torch_dtype=torch.float32)
|
| 17 |
model.to(device)
|
| 18 |
+
print("DEBUG: Model loaded and ready on CPU.")
|
| 19 |
|
| 20 |
def generate_core(prompt, duration):
|
| 21 |
if not prompt:
|
| 22 |
+
print("DEBUG: Request received with no prompt.")
|
| 23 |
return None
|
| 24 |
|
| 25 |
+
print(f"DEBUG: Starting generation for: '{prompt}' ({duration}s)")
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
try:
|
| 28 |
+
duration = min(int(duration), 30)
|
| 29 |
+
inputs = processor(text=[prompt], padding=True, return_tensors="pt").to(device)
|
| 30 |
+
|
| 31 |
+
# 50 tokens = 1 second of audio
|
| 32 |
+
max_tokens = int(duration * 50)
|
| 33 |
+
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
audio_values = model.generate(
|
| 36 |
+
**inputs,
|
| 37 |
+
max_new_tokens=max_tokens,
|
| 38 |
+
do_sample=True,
|
| 39 |
+
guidance_scale=3.0
|
| 40 |
+
)
|
| 41 |
|
| 42 |
+
sampling_rate = model.config.audio_encoder.sampling_rate
|
| 43 |
+
audio_data = audio_values[0, 0].cpu().numpy()
|
| 44 |
+
|
| 45 |
+
print("DEBUG: Generation successful.")
|
| 46 |
+
return sampling_rate, audio_data
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"DEBUG ERROR: {str(e)}")
|
| 49 |
+
return None
|
| 50 |
|
| 51 |
+
# 2. FastAPI Engine
|
| 52 |
app = FastAPI()
|
| 53 |
|
| 54 |
@app.post("/generate")
|
| 55 |
async def api_generate(prompt: str = Query(...), duration: int = Query(10)):
|
| 56 |
try:
|
| 57 |
+
res = generate_core(prompt, duration)
|
| 58 |
+
if res is None:
|
| 59 |
+
raise HTTPException(status_code=400, detail="Generation failed or prompt empty")
|
| 60 |
+
|
| 61 |
+
sr, audio = res
|
| 62 |
byte_io = io.BytesIO()
|
| 63 |
scipy.io.wavfile.write(byte_io, rate=sr, data=audio)
|
| 64 |
return Response(content=byte_io.getvalue(), media_type="audio/wav")
|
| 65 |
except Exception as e:
|
| 66 |
raise HTTPException(status_code=500, detail=str(e))
|
| 67 |
|
| 68 |
+
# 3. Gradio Interface with Queue enabled
|
| 69 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 70 |
gr.Markdown("# 🎵 MusicGen Automation Hub")
|
| 71 |
with gr.Row():
|
| 72 |
with gr.Column():
|
| 73 |
+
p_in = gr.Textbox(label="Prompt", placeholder="Enter music description...")
|
| 74 |
d_in = gr.Slider(1, 30, value=10, label="Duration (sec)")
|
| 75 |
run_btn = gr.Button("Generate", variant="primary")
|
| 76 |
with gr.Column():
|
|
|
|
| 78 |
|
| 79 |
run_btn.click(generate_core, [p_in, d_in], a_out)
|
| 80 |
|
| 81 |
+
# 4. Mandatory: Enable Queuing
|
| 82 |
+
# This prevents the UI from "hanging" during the 60-120s CPU generation time.
|
| 83 |
+
demo.queue()
|
| 84 |
+
|
| 85 |
+
# Mount Gradio
|
| 86 |
app = gr.mount_gradio_app(app, demo, path="/")
|