Update app.py
Browse files
app.py
CHANGED
|
@@ -3,30 +3,50 @@ import torch
|
|
| 3 |
import uuid
|
| 4 |
import os
|
| 5 |
import soundfile as sf
|
| 6 |
-
|
| 7 |
-
from diffusers.pipelines.stable_audio import StableAudioPipeline
|
| 8 |
-
|
| 9 |
|
| 10 |
app = FastAPI()
|
| 11 |
|
| 12 |
OUTPUT_DIR = "outputs"
|
| 13 |
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
@app.post("/generate")
|
| 23 |
async def generate(prompt: str, duration: float = 10.0):
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
filename = f"{uuid.uuid4().hex}.wav"
|
| 32 |
path = os.path.join(OUTPUT_DIR, filename)
|
|
@@ -36,5 +56,5 @@ async def generate(prompt: str, duration: float = 10.0):
|
|
| 36 |
return {
|
| 37 |
"prompt": prompt,
|
| 38 |
"duration": duration,
|
| 39 |
-
"file": filename
|
| 40 |
}
|
|
|
|
| 3 |
import uuid
|
| 4 |
import os
|
| 5 |
import soundfile as sf
|
| 6 |
+
from diffusers import DiffusionPipeline
|
|
|
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
OUTPUT_DIR = "outputs"
|
| 11 |
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 12 |
|
| 13 |
+
# -------- Device & dtype handling (HF-safe) --------
|
| 14 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 15 |
+
DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
|
| 16 |
+
|
| 17 |
+
pipe = None # lazy-loaded
|
| 18 |
+
|
| 19 |
|
| 20 |
+
def load_pipeline():
|
| 21 |
+
global pipe
|
| 22 |
+
if pipe is None:
|
| 23 |
+
print("Loading Stable Audio Open pipeline...")
|
| 24 |
+
pipe = DiffusionPipeline.from_pretrained(
|
| 25 |
+
"stabilityai/stable-audio-open-1.0",
|
| 26 |
+
torch_dtype=DTYPE,
|
| 27 |
+
)
|
| 28 |
+
pipe.to(DEVICE)
|
| 29 |
+
pipe.set_progress_bar_config(disable=True)
|
| 30 |
+
print("Pipeline loaded on", DEVICE)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# -------- API --------
|
| 34 |
@app.post("/generate")
|
| 35 |
async def generate(prompt: str, duration: float = 10.0):
|
| 36 |
+
"""
|
| 37 |
+
Generate music/audio from a text prompt using Stable Audio Open
|
| 38 |
+
"""
|
| 39 |
+
load_pipeline()
|
| 40 |
+
|
| 41 |
+
with torch.no_grad():
|
| 42 |
+
output = pipe(
|
| 43 |
+
prompt=prompt,
|
| 44 |
+
duration=duration,
|
| 45 |
+
guidance_scale=7.5,
|
| 46 |
+
num_inference_steps=150, # safer for HF
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
audio = output.audios[0]
|
| 50 |
|
| 51 |
filename = f"{uuid.uuid4().hex}.wav"
|
| 52 |
path = os.path.join(OUTPUT_DIR, filename)
|
|
|
|
| 56 |
return {
|
| 57 |
"prompt": prompt,
|
| 58 |
"duration": duration,
|
| 59 |
+
"file": filename,
|
| 60 |
}
|