basyx commited on
Commit
ed66b6f
·
verified ·
1 Parent(s): cdf4d7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -53
app.py CHANGED
@@ -1,65 +1,25 @@
1
- import torch
2
  import gradio as gr
3
  from fastapi import FastAPI, HTTPException, Query
4
  from fastapi.responses import Response
5
- from transformers import AutoProcessor, MusicgenForConditionalGeneration
6
  import scipy.io.wavfile
7
  import io
8
- import numpy as np
9
 
10
- # --- INITIALIZATION ---
11
- MODEL_ID = "facebook/musicgen-small"
12
- device = "cpu"
13
 
14
- print(f"DEBUG: System boot. Loading {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 successfully.")
19
-
20
- def generate_core(prompt, duration):
21
- print(f"!!! TRIGGERED !!! Prompt: {prompt} | Duration: {duration}")
22
- if not prompt:
23
- return None
24
-
25
  try:
26
- duration = min(int(duration), 30)
27
- inputs = processor(text=[prompt], padding=True, return_tensors="pt").to(device)
28
-
29
- # 50 tokens/sec. Reducing guidance for CPU speed.
30
- max_tokens = int(duration * 50)
31
 
32
- with torch.no_grad():
33
- audio_values = model.generate(
34
- **inputs,
35
- max_new_tokens=max_tokens,
36
- do_sample=True,
37
- guidance_scale=3.0
38
- )
39
-
40
- sampling_rate = model.config.audio_encoder.sampling_rate
41
- audio_data = audio_values[0, 0].cpu().numpy()
42
- print("DEBUG: Generation successful.")
43
- return sampling_rate, audio_data
44
  except Exception as e:
45
- print(f"ERROR: {str(e)}")
46
- return None
47
-
48
- # --- FASTAPI FOR N8N ---
49
- app = FastAPI()
50
-
51
- @app.post("/generate")
52
- async def api_generate(prompt: str = Query(...), duration: int = Query(10)):
53
- res = generate_core(prompt, duration)
54
- if res is None:
55
- raise HTTPException(status_code=500, detail="Generation failed")
56
-
57
- sr, audio = res
58
- byte_io = io.BytesIO()
59
- scipy.io.wavfile.write(byte_io, rate=sr, data=audio)
60
- return Response(content=byte_io.getvalue(), media_type="audio/wav")
61
 
62
- # --- GRADIO UI ---
63
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
64
  gr.Markdown("# 🎵 MusicGen Automation Hub")
65
  with gr.Row():
@@ -70,8 +30,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
70
  with gr.Column():
71
  a_out = gr.Audio(label="Output")
72
 
73
- run_btn.click(fn=generate_core, inputs=[p_in, d_in], outputs=a_out)
74
 
75
- # Enable the queue and mount
76
  demo.queue()
77
  app = gr.mount_gradio_app(app, demo, path="/")
 
 
1
  import gradio as gr
2
  from fastapi import FastAPI, HTTPException, Query
3
  from fastapi.responses import Response
 
4
  import scipy.io.wavfile
5
  import io
6
+ from generate import generate_music
7
 
8
+ app = FastAPI(title="Basyx MusicGen Hub")
 
 
9
 
10
+ @app.post("/generate")
11
+ async def api_generate(prompt: str = Query(...), duration: int = Query(10)):
 
 
 
 
 
 
 
 
 
12
  try:
13
+ sr, audio = generate_music(prompt, duration)
14
+ if audio is None:
15
+ raise HTTPException(status_code=500, detail="Generation failed")
 
 
16
 
17
+ byte_io = io.BytesIO()
18
+ scipy.io.wavfile.write(byte_io, rate=sr, data=audio)
19
+ return Response(content=byte_io.getvalue(), media_type="audio/wav")
 
 
 
 
 
 
 
 
 
20
  except Exception as e:
21
+ raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
 
23
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
24
  gr.Markdown("# 🎵 MusicGen Automation Hub")
25
  with gr.Row():
 
30
  with gr.Column():
31
  a_out = gr.Audio(label="Output")
32
 
33
+ run_btn.click(fn=generate_music, inputs=[p_in, d_in], outputs=a_out)
34
 
 
35
  demo.queue()
36
  app = gr.mount_gradio_app(app, demo, path="/")