{"slug": "wrapping-demucs-in-fastapi-building-a-music-stem-separation-web-app", "title": "Wrapping Demucs in FastAPI: Building a Music Stem Separation Web App", "summary": "A two-person team built MusicSpliter, a prototype web app that wraps Meta AI's Demucs stem-separation model in a FastAPI backend and React frontend, letting users upload an MP3 and download isolated vocal and accompaniment WAV files. The backend invokes the Demucs CLI via Python's subprocess module and serves output stems by mounting Demucs' predictable output directory as FastAPI static files, avoiding custom streaming endpoints.", "body_md": "Audio stem separation has improved dramatically over the past few years, largely driven by open-source deep learning architectures like Demucs from Meta AI. If you want to isolate clean vocals from a track or strip them away to create an instrumental backing, the results from models like `htdemucs` (Hybrid Transformer Demucs) are genuinely impressive. However, running these tools out of the box is strictly a terminal-bound workflow. You have to clone a repository, set up a Python virtual environment, configure PyTorch and CUDA drivers, and run terminal commands with custom parameter flags.\n\nFor non-technical musicians, producers, or colleagues who just need an isolated vocal track for a demo, the terminal is an unnecessary barrier. At the same time, commercial online stem splitters often gate their services behind steep subscription paywalls, intrusive advertisements, or strict file size limits.\n\nAs a two-person team, we built MusicSpliter as a lightweight prototype to explore how to wrap an open-source deep learning CLI tool into a straightforward web application. The concept is simple: drop an MP3 into a browser window, click a button, let the model process the audio on the backend, and download the isolated vocal and accompaniment stems as WAV files.\n\nHere is how we structured the application between FastAPI and React, how we handled the CLI process execution, and the practical challenges you run into when serving heavy machine learning workloads over standard HTTP endpoints.\n\nWhen building a prototype around a deep learning CLI tool, simplicity helps you validate the core experience quickly. We chose a two-tier architecture:\n\n`subprocess` module, and serves the generated audio files back to the client using static file mounting.\nInstead of writing custom audio streaming endpoints or dealing with temporary memory buffers, we leveraged Demucs' predictable directory conventions. When Demucs processes an audio track, it writes its output to a structured directory hierarchy based on the model name and track title. By mounting that output folder as a static directory in FastAPI, the frontend can download the processed stems directly via URL.\n\nLet us walk through how this is implemented step by step.\n\nIn `backend/main.py`, we initialize FastAPI, enable Cross-Origin Resource Sharing (CORS) so our Vite development server can communicate with the backend, and set up our path variables.\n\n``` python\nfrom fastapi import FastAPI, UploadFile, File\nfrom fastapi.responses import JSONResponse\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.staticfiles import StaticFiles\nimport subprocess\nimport os\n\napp = FastAPI()\n\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=[\"http://localhost:5173\"],\n    allow_credentials=True,\n    allow_methods=[\"*\"],\n    allow_headers=[\"*\"],\n)\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nOUTPUT_FOLDER = os.path.join(BASE_DIR, \"demucs_output\")\nMODEL = \"htdemucs\"\n\nos.makedirs(OUTPUT_FOLDER, exist_ok=True)\n\n# Serve demucs_output as static files\napp.mount(\"/files\", StaticFiles(directory=OUTPUT_FOLDER), name=\"files\")\n```\n\nSetting up `OUTPUT_FOLDER` at the project root ensures all processed files live in a single predictable location. Mounting `StaticFiles` at `/files` allows any file written inside `demucs_output` to be downloaded directly by the browser without writing dedicated file-streaming routes.\n\nNext, in `backend/main.py`, we define our `/split` endpoint. When a user uploads a track, FastAPI receives it as an `UploadFile` object.\n\n``` python\n@app.post(\"/split\")\nasync def split_song(file: UploadFile = File(...)):\n    # Save uploaded file\n    input_path = os.path.join(BASE_DIR, file.filename)\n    with open(input_path, \"wb\") as f:\n        f.write(await file.read())\n```\n\nFastAPI handles multipart form uploads efficiently. By reading the file asynchronously and writing it to disk at `input_path`, we ensure the file is fully persisted before we invoke the Demucs command-line tool.\n\nOnce the MP3 is saved to disk, we trigger the separation process using Python's `subprocess.run`. We specify the model, the output directory, and the separation target.\n\n```\n    # Run demucs\n    try:\n        subprocess.run([\n            \"demucs\",\n            input_path,\n            \"-o\", OUTPUT_FOLDER,\n            \"-n\", MODEL,\n            \"--two-stems=vocals\"\n        ], check=True)\n    except subprocess.CalledProcessError as e:\n        return JSONResponse(status_code=500, content={\"error\": str(e)})\n\n    song_name = os.path.splitext(os.path.basename(input_path))[0]\n    vocals_url = f\"/files/{MODEL}/{song_name}/vocals.wav\"\n    karaoke_url = f\"/files/{MODEL}/{song_name}/no_vocals.wav\"\n\n    return {\"vocals\": vocals_url, \"karaoke\": karaoke_url}\n```\n\nA few important details are happening here:\n\n`--two-stems=vocals` flag`htdemucs` model with `vocals.wav` and `no_vocals.wav`.` OUTPUT_FOLDER` to `/files`, we construct the client-accessible URLs directly using the model name and track name, returning them in a JSON payload.\nOn the frontend, we built a React component in `frontend/src/App.tsx` that manages the user interaction: file selection, uploading, progress indication, and downloading the resulting files.\n\n``` python\nimport React, { useState } from \"react\";\n\nconst API_URL = \"http://127.0.0.1:8000/split\";\n\nfunction App() {\n  const [file, setFile] = useState<File | null>(null);\n  const [loading, setLoading] = useState(false);\n  const [result, setResult] = useState<{ vocals: string; karaoke: string } | null>(null);\n\n  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setFile(e.target.files?.[0] || null);\n    setResult(null);\n  };\n\n  const handleUpload = async () => {\n    if (!file) return;\n    setLoading(true);\n    setResult(null);\n\n    const formData = new FormData();\n    formData.append(\"file\", file);\n\n    try {\n      const res = await fetch(API_URL, {\n        method: \"POST\",\n        body: formData,\n      });\n      const data = await res.json();\n      setResult(data);\n    } catch (err) {\n      alert(\"Error splitting music!\");\n    }\n    setLoading(false);\n  };\n\n  return (\n    <div style={{ maxWidth: 400, margin: \"40px auto\", padding: 20, border: \"1px solid #ccc\", borderRadius: 8 }}>\n      <h2>Music Spliter</h2>\n      <input type=\"file\" accept=\".mp3\" onChange={handleFileChange} />\n      <br /><br />\n      <button onClick={handleUpload} disabled={!file || loading}>\n        {loading ? \"Splitting...\" : \"Split Music\"}\n      </button>\n      {loading && (\n        <div style={{ margin: \"20px 0\" }}>\n          <div style={{ width: \"100%\", background: \"#eee\", height: 10, borderRadius: 5 }}>\n            <div style={{ width: \"80%\", background: \"#007bff\", height: 10, borderRadius: 5, transition: \"width 0.5s\" }} />\n          </div>\n          <p>Processing...</p>\n        </div>\n      )}\n      {result && (\n        <div style={{ marginTop: 30 }}>\n          <h4>Download Options:</h4>\n          <div>\n            <a href={`http://127.0.0.1:8000${result.vocals}`} download>\n              <button>Download Vocals</button>\n            </a>\n          </div>\n          <div style={{ marginTop: 10 }}>\n            <a href={`http://127.0.0.1:8000${result.karaoke}`} download>\n              <button>Download Karaoke</button>\n            </a>\n          </div>\n        </div>\n      )}\n    </div>\n  );\n}\n\nexport default App;\n```\n\nBecause audio stem separation takes anywhere from 15 seconds to over a minute depending on track length and hardware, the user interface disables the submission button immediately on click and displays an active progress indicator. When the response arrives, the user receives separate download buttons for the vocal track and the karaoke backing track.\n\nWhile wrapping a CLI tool in FastAPI works quickly for a local proof-of-concept, taking this pattern further reveals several operational gotchas you have to address in production.\n\nIn `backend/main.py`, `subprocess.run` is a synchronous, blocking call executed directly inside an `async def` route. In Python's asynchronous event model, if a synchronous function runs for 45 seconds inside the event loop, the entire FastAPI server is blocked from processing any other incoming HTTP requests during that time.\n\nFor a local single-user prototype, this goes unnoticed. But in any shared environment, you should offload the subprocess execution to a worker thread using `asyncio.to_thread` or move the task entirely to a background worker queue.\n\nDemucs depends heavily on external libraries like FFmpeg to decode MP3 files into raw audio buffers. If FFmpeg is not installed on the server, or if the uploaded audio file has an uncommon sample rate or corrupted ID3 tags, Demucs exits with a non-zero status code.\n\nCatching `subprocess.CalledProcessError` prevents the API process from crashing, but returning just `str(e)` often omits the actual cause. Capturing `stderr` (via `capture_output=True`) is essential to see whether Demucs failed due to a missing binary, an unsupported codec, or a CUDA out-of-memory error.\n\nIn our prototype code, we used `file.filename` directly:\n\n```\ninput_path = os.path.join(BASE_DIR, file.filename)\n```\n\nIn production, relying on raw client filenames introduces two significant risks:\n\n`../`) can break shell arguments or create unexpected paths.` track.mp3`, the second upload will overwrite the first input file and overwrite the files in the output directory.\nA safer pattern is to generate a unique identifier (such as a UUID) for each job, store the file under that ID, and maintain the original filename only as metadata for the eventual download header.\n\nDemucs outputs uncompressed WAV audio files (often 24-bit or 32-bit float). A standard 4-minute MP3 that starts at 8 MB can easily expand into two 40 MB WAV files once separated.\n\nIf you process twenty songs, your server quickly accumulates gigabytes of static audio files in `demucs_output`. Without an automated cleanup routine (such as a cron job or background task that deletes folders older than 60 minutes), local storage will fill up fast.\n\nBecause machine learning inference is compute-intensive, processing longer audio files can easily exceed standard HTTP timeout thresholds. If your backend sits behind a reverse proxy like Nginx or a cloud proxy like Cloudflare, any request taking longer than 60 to 100 seconds will be terminated with a 504 Gateway Timeout, even if Demucs is still happily crunching away on the GPU.\n\nReflecting on the prototype, here is how we would evolve the architecture for a multi-user environment:\n\n`/split` endpoint would immediately return a `job_id`, and a dedicated worker process would handle the Demucs execution.`/status/{job_id}` endpoint or listen over a WebSocket. Demucs outputs progress percentage to `stdout`, which can be parsed and streamed back to the frontend in real time.`<audio>` player or waveform visualizer would let users audition the separated vocals and instrumental tracks immediately before deciding to download.`subprocess.run` block FastAPI's async event loop unless offloaded to a thread pool or an external queue.\nHave you wrapped deep learning or audio CLI tools in web services before? How do you prefer to handle long-running ML tasks and progress feedback between FastAPI and your frontend?\n\nThe full write-up of this project is on our site: [https://sanedevs.com/projects/musicspliter.html](https://sanedevs.com/projects/musicspliter.html)", "url": "https://wpnews.pro/news/wrapping-demucs-in-fastapi-building-a-music-stem-separation-web-app", "canonical_source": "https://dev.to/sanedevs/wrapping-demucs-in-fastapi-building-a-music-stem-separation-web-app-3oc0", "published_at": "2026-11-16 12:10:17+00:00", "updated_at": "2026-11-16 12:21:11.010804+00:00", "lang": "en", "topics": ["artificial-intelligence", "ai-tools", "developer-tools", "machine-learning"], "entities": ["Demucs", "Meta AI", "FastAPI", "React", "MusicSpliter", "PyTorch", "htdemucs"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/wrapping-demucs-in-fastapi-building-a-music-stem-separation-web-app", "markdown": "https://wpnews.pro/news/wrapping-demucs-in-fastapi-building-a-music-stem-separation-web-app.md", "text": "https://wpnews.pro/news/wrapping-demucs-in-fastapi-building-a-music-stem-separation-web-app.txt", "jsonld": "https://wpnews.pro/news/wrapping-demucs-in-fastapi-building-a-music-stem-separation-web-app.jsonld"}}