Local AI BGM and sound effects for Claude Code and any MCP client. Stable Audio 3 on Apple Silicon (MLX) and Windows NVIDIA GPUs (PyTorch). No cloud, no API key.
Python apple-siliconaudio-generationclaude-codecudagame-audiomcpmcp-servermlxmusic-generationpytorchsound-effectsstable-audiowindows
Web API: queue edit/process with inputs limited to OUTPUT_DIR, waveform peaks, cancel (GAME-224)
Kana3d840d1c16c8
diff --git a/src/audio_studio_mcp/web.py b/src/audio_studio_mcp/web.pyindex 9cb3b51..4f8864d 100644--- a/src/audio_studio_mcp/web.py+++ b/src/audio_studio_mcp/web.py@@ -22,12 +22,14 @@ import jsonimport osimport secretsimport stat+import threadingimport timefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Anyfrom urllib.parse import urlsplit+import numpy as npfrom mcp.server.mcpserver.exceptions import ToolErrorfrom pydantic import ValidationErrorfrom starlette.applications import Starlette@@ -36,15 +38,17 @@ from starlette.responses import FileResponse, JSONResponse, Responsefrom starlette.routing import Mount, Routefrom starlette.staticfiles import StaticFiles-from . import __version__, server+from . import __version__, post, serverfrom .prompts import DEFAULT_SECONDSSTATIC_DIR = Path(__file__).with_name("static")AUDIO_EXTS = {".wav": "audio/wav", ".ogg": "audio/ogg", ".flac": "audio/flac", ".mp3": "audio/mpeg"}-# Tools the page may queue. edit/process take arbitrary input paths; they come-# with the editing page (W2) and an input check limited to OUTPUT_DIR.-JOB_TOOLS = {"generate_audio"}+# Tools the page may queue. edit/process read `input_audio`; from the page that+# must be an audio file directly inside OUTPUT_DIR (see resolve_input).+JOB_TOOLS = {"generate_audio", "edit_audio", "process_audio"}+INPUT_TOOLS = {"edit_audio", "process_audio"}MAX_FINISHED_JOBS = 200+MAX_PEAKS = 20000# ── jobs ─────────────────────────────────────────────────────────────────────@@ -54,7 +58,7 @@ class Job:tool: strarguments: dictseq: int- status: str = "queued" # queued | running | done | error+ status: str = "queued" # queued | running | done | error | cancelledcreated: float = field(default_factory=time.time)started: float | None = Nonefinished: float | None = None@@ -124,12 +128,19 @@ class JobQueue:def view(self, job: Job) -> dict:return job.view(self.position(job))+ def cancel(self, job: Job) -> bool:+ """Drop a job that has not started yet (a running model call cannot stop)."""+ if job.status != "queued":+ return False+ job.status, job.finished = "cancelled", time.time()+ return True+def counts(self) -> dict:st = [j.status for j in self.jobs.values()]return {"queued": st.count("queued"), "running": st.count("running")}def _prune(self) -> None:- done = [j for j in self.jobs.values() if j.status in ("done", "error")]+ done = [j for j in self.jobs.values() if j.status in ("done", "error", "cancelled")]for j in sorted(done, key=lambda j: j.seq)[:max(0, len(done) - MAX_FINISHED_JOBS)]:del self.jobs[j.id]@@ -138,6 +149,9 @@ class JobQueue:assert queue is not Nonewhile True:job = await queue.get()+ if job.status == "cancelled":+ queue.task_done()+ continuejob.status, job.started = "running", time.time()try:job.result = _tool_result(await server.server.call_tool(job.tool, job.arguments))@@ -191,6 +205,30 @@ def _safe_audio_path(name: str) -> Path | None:return resolved+def resolve_input(value: Any) -> Path | None:+ """`input_audio` from the page: a file name in OUTPUT_DIR, or an absolute+ path whose folder is OUTPUT_DIR (what the library and results show).+ Anything else (other folders, traversal, symlinks out) is None."""+ if not isinstance(value, str) or not value:+ return None+ name = value+ if "/" in value or "\\" in value:+ p = Path(value)+ if not p.is_absolute():+ return None+ try:+ if p.parent.resolve(strict=True) != _output_dir().resolve():+ return None+ except (OSError, RuntimeError):+ return None+ name = p.name+ path = _safe_audio_path(name)+ try:+ return path if path is not None and path.stat().st_size > 0 else None+ except OSError:+ return None++def _read_meta(side: Path) -> dict | None:try:meta = json.loads(side.read_text(encoding="utf-8"))@@ -264,6 +302,48 @@ def list_library(query: str = "", offset: int = 0, limit: int = 100) -> dict:return {"output_dir": str(root), "total": len(entries), "items": entries[offset:offset + limit]}+# ── waveform peaks ───────────────────────────────────────────────────────────+# Decoded on the server so every format the tools read draws in every browser+# (Safari cannot decode OGG Vorbis). A few decoded clips are kept for zooming.+_decoded: dict[tuple, tuple] = {}+_decoded_lock = threading.Lock()+_DECODED_KEEP = 4+++def _decode(path: Path) -> tuple:+ st = path.stat()+ key = (str(path), st.st_mtime_ns, st.st_size)+ with _decoded_lock:+ hit = _decoded.pop(key, None)+ if hit is None:+ hit = post.read(path)+ with _decoded_lock:+ _decoded[key] = hit # most recent last+ while len(_decoded) > _DECODED_KEEP:+ del _decoded[next(iter(_decoded))]+ return hit+++def peaks(path: Path, n: int, start: float | None = None, end: float | None = None) -> dict:+ """Min/max of all channels in n equal buckets over [start, end] seconds."""+ audio, sr = _decode(path)+ total = audio.shape[-1]+ seconds = total / sr+ s = 0 if start is None else min(total, max(0, int(start * sr)))+ e = total if end is None else min(total, max(s, int(end * sr)))+ seg = audio[:, s:e]+ lo = hi = np.zeros(0, dtype=np.float32)+ if seg.shape[-1] and n:+ # reduceat over bucket starts; a bucket narrower than one sample+ # (zoomed past sample level) repeats the sample it starts on+ idx = (np.arange(n) * seg.shape[-1]) // n+ lo = np.minimum.reduceat(seg.min(axis=0), idx)+ hi = np.maximum.reduceat(seg.max(axis=0), idx)+ return {"seconds": round(seconds, 4), "sample_rate": sr, "channels": int(audio.shape[0]),+ "start": round(s / sr, 4), "end": round(e / sr, 4),+ "min": [round(float(v), 4) for v in lo], "max": [round(float(v), 4) for v in hi]}++# ── HTTP ─────────────────────────────────────────────────────────────────────def _err(status: int, message: str, **extra) -> JSONResponse:return JSONResponse({"error": message, **extra}, status_code=status)@@ -359,6 +439,12 @@ async def api_jobs_create(request: Request) -> Response:return _err(400, f"tool not available from the web UI: {tool!r}")if not isinstance(arguments, dict):return _err(400, "arguments must be an object")+ if tool in INPUT_TOOLS:+ src = resolve_input(arguments.get("input_audio"))+ if src is None:+ return _err(422, "input_audio must be an audio file in the output folder",+ fields=[{"field": "input_audio", "message": "not a file in the output folder"}])+ arguments = {**arguments, "input_audio": str(src)}errors = validate_arguments(tool, arguments)if errors:msg = "; ".join(f"{e['field']}: {e['message']}" for e in errors)@@ -369,7 +455,18 @@ async def api_jobs_create(request: Request) -> Response:async def api_jobs_list(_: Request) -> Response:items = sorted(jobs.jobs.values(), key=lambda j: j.seq, reverse=True)- return JSONResponse({"items": [jobs.view(j) for j in items], **jobs.counts()})+ # `loaded` lets the page tell "loading the model" from "generating"+ return JSONResponse({"items": [jobs.view(j) for j in items], **jobs.counts(),+ "loaded": bool(server.get_backend().loaded())})+++async def api_job_cancel(request: Request) -> Response:+ job = jobs.jobs.get(request.path_params["job_id"])+ if job is None:+ return _err(404, "no such job")+ if not jobs.cancel(job):+ return _err(409, f"job is {job.status}, only waiting jobs can be cancelled")+ return JSONResponse(jobs.view(job))async def api_job(request: Request) -> Response:@@ -389,6 +486,13 @@ async def api_library(request: Request) -> Response:return JSONResponse(await asyncio.to_thread(list_library, q.get("q", ""), offset, limit))+async def api_library_item(request: Request) -> Response:+ path = _safe_audio_path(request.path_params["name"])+ if path is None:+ return _err(404, "not found")+ return JSONResponse(await asyncio.to_thread(lambda: _entry(path, path.stat())))++async def api_audio(request: Request) -> Response:path = _safe_audio_path(request.path_params["name"])if path is None:@@ -400,6 +504,23 @@ async def api_audio(request: Request) -> Response:headers={"Cache-Control": "no-cache"})+async def api_peaks(request: Request) -> Response:+ path = _safe_audio_path(request.path_params["name"])+ if path is None:+ return _err(404, "not found")+ q = request.query_params+ try:+ n = min(MAX_PEAKS, max(1, int(q.get("n", 2000))))+ start = float(q["start"]) if q.get("start") else None+ end = float(q["end"]) if q.get("end") else None+ except ValueError:+ return _err(400, "n/start/end must be numbers")+ try:+ return JSONResponse(await asyncio.to_thread(peaks, path, n, start, end))+ except Exception as e: # unreadable or truncated file+ return _err(422, f"cannot read audio: {e}")++async def index(_: Request) -> Response:return FileResponse(STATIC_DIR / "index.html", headers={"Cache-Control": "no-cache"})@@ -410,8 +531,11 @@ API_ROUTES = [Route("/api/jobs", api_jobs_create, methods=["POST"]),Route("/api/jobs", api_jobs_list, methods=["GET"]),Route("/api/jobs/{job_id}", api_job, methods=["GET"]),+ Route("/api/jobs/{job_id}/cancel", api_job_cancel, methods=["POST"]),Route("/api/library", api_library, methods=["GET"]),+ Route("/api/library/{name:path}", api_library_item, methods=["GET"]),Route("/api/audio/{name:path}", api_audio, methods=["GET", "HEAD"]),+ Route("/api/peaks/{name:path}", api_peaks, methods=["GET"]),]@@ -430,7 +554,6 @@ def create_app(port: int | None = None) -> Starlette:def serve(port: int, open_browser: bool = True) -> None:- import threadingimport webbrowserimport uvicorndiff --git a/tests/test_web.py b/tests/test_web.pyindex 739e35c..8ea1475 100644--- a/tests/test_web.py+++ b/tests/test_web.py@@ -107,13 +107,109 @@ def test_error_text_identical_to_mcp(client, fake):def test_only_whitelisted_tools(client, tmp_path):- for tool in ("process_audio", "edit_audio", "unload_models", "nope"):- r = client.post("/api/jobs", json={"tool": tool, "arguments": {"input_audio": str(tmp_path)}})+ for tool in ("unload_models", "nope"):+ r = client.post("/api/jobs", json={"tool": tool, "arguments": {}})assert r.status_code == 400, toolassert client.post("/api/jobs", json={"arguments": []}).status_code == 400assert client.post("/api/jobs", content=b"{", headers={"Content-Type": "application/json"}).status_code == 400+def _input_cases(out: Path) -> list:+ """input_audio values the page must not be able to use, plus setup."""+ secret = out.parent / "secret.wav"+ post.write(secret, sine(0.1), 44100, "wav")+ (out / "sub").mkdir()+ post.write(out / "sub" / "x.wav", sine(0.1), 44100, "wav")+ cases = [str(secret), "../secret.wav", "..\\secret.wav", "sub/x.wav", str(out / "sub" / "x.wav"),+ str(out / ".." / "secret.wav"), "notes.txt", str(out / "notes.txt"), "a.wav.json",+ "missing.wav", "reserved.wav", "", ".", "..", "secret.wav", "/etc/passwd", None, 3, ["a.wav"]]+ try:+ (out / "link.wav").symlink_to(secret)+ (out.parent / "linkdir").symlink_to(out.parent, target_is_directory=True)+ cases += ["link.wav", str(out.parent / "linkdir" / "secret.wav")]+ except OSError: # Windows without symlink privilege+ pass+ return cases++[email protected]("tool", ["edit_audio", "process_audio"])+def test_input_audio_must_be_in_the_output_folder(client, fake, tool):+ out = _make_library(fake)+ for value in _input_cases(out):+ args = {"input_audio": value, "mode": "variation"}+ r = client.post("/api/jobs", json={"tool": tool, "arguments": args})+ assert r.status_code == 422, (value, r.status_code)+ assert r.json()["fields"][0]["field"] == "input_audio"+ assert client.get("/api/jobs").json()["items"] == []+ assert fake.requests == []+++def test_edit_job_from_the_library(client, fake):+ out = _make_library(fake)+ for value in ("a.wav", str(out / "a.wav")): # name or the path the library shows+ r = client.post("/api/jobs", json={"tool": "edit_audio", "arguments": {+ "input_audio": value, "mode": "inpaint", "prompt": "thunder", "audio_type": "sfx",+ "start_seconds": 0.25, "end_seconds": 0.5, "variations": 2, "seed": 5}})+ assert r.status_code == 202, r.json()+ assert r.json()["arguments"]["input_audio"] == str(out / "a.wav")+ job = wait_job(client, r.json()["id"])+ assert job["status"] == "done", job+ assert job["result"]["mode"] == "inpaint" and job["result"]["region"] == [0.25, 0.5]+ assert [c["seed"] for c in job["result"]["candidates"]] == [5, 6]+ req = fake.requests[-1][1]+ assert req.inpaint_audio == str(out / "a.wav") and req.inpaint_range == (0.25, 0.5)+ names = {i["file"] for i in client.get("/api/library?q=inpaint").json()["items"]}+ assert len(names) == 4 and all(n.startswith("a_inpaint") for n in names)+++def test_process_job_exports_into_the_library(client, fake):+ _make_library(fake)+ r = client.post("/api/jobs", json={"tool": "process_audio", "arguments": {+ "input_audio": "a.wav", "start_seconds": 0.2, "end_seconds": 0.8, "mono": True,+ "fade_out_ms": 50, "format": "flac", "sample_rate": 44100, "title": "cut"}})+ assert r.status_code == 202, r.json()+ job = wait_job(client, r.json()["id"])+ assert job["status"] == "done", job+ res = job["result"]+ assert res["format"] == "flac" and res["channels"] == 1 and res["seconds"] == pytest.approx(0.6, abs=0.01)+ item = client.get("/api/library?q=cut").json()["items"][0]+ assert item["file"] == "cut.flac" and item["meta"]["kind"] == "process"+ assert fake.requests == [] # no model involved+++def test_edit_arguments_validated_before_queueing(client, fake):+ _make_library(fake)+ r = client.post("/api/jobs", json={"tool": "edit_audio", "arguments": {+ "input_audio": "a.wav", "mode": "remix", "strength": 2}})+ assert r.status_code == 422+ assert {f["field"] for f in r.json()["fields"]} == {"mode", "strength"}+++def test_peaks(client, fake):+ out = _make_library(fake)+ audio = sine(1.0, freq=5.0, amp=0.5)+ audio[1] *= -0.5 # channels differ: peaks cover both+ post.write(out / "p.wav", audio, 44100, "wav")+ r = client.get("/api/peaks/p.wav?n=100").json()+ assert r["channels"] == 2 and r["sample_rate"] == 44100+ assert r["seconds"] == pytest.approx(1.0) and (r["start"], r["end"]) == (0, 1.0)+ assert len(r["min"]) == len(r["max"]) == 100+ assert max(r["max"]) == pytest.approx(0.5, abs=1e-3) and min(r["min"]) == pytest.approx(-0.5, abs=1e-3)+ assert all(lo <= hi for lo, hi in zip(r["min"], r["max"]))+ # a zoomed window narrower than n samples still returns n buckets+ z = client.get("/api/peaks/p.wav?n=500&start=0.5&end=0.501").json()+ assert len(z["min"]) == 500 and z["start"] == 0.5 and z["end"] == pytest.approx(0.501, abs=1e-4)+ # out-of-range windows are clamped, not errors+ e = client.get("/api/peaks/p.wav?n=10&start=5&end=9").json()+ assert e["min"] == [] and e["start"] == e["end"] == 1.0+ assert client.get("/api/peaks/p.wav?n=x").status_code == 400+ assert client.get("/api/peaks/b.flac?n=10").json()["seconds"] == pytest.approx(0.5, abs=0.01)+ for bad in ("../secret.wav", "notes.txt", "missing.wav"):+ assert client.get(f"/api/peaks/{bad}").status_code == 404+ (out / "broken.wav").write_bytes(b"RIFF....not audio")+ assert client.get("/api/peaks/broken.wav").status_code == 422++def test_queue_runs_in_order_with_positions(client, fake):gate = threading.Event()orig = fake._generate@@ -143,6 +239,35 @@ def test_queue_runs_in_order_with_positions(client, fake):assert [j["id"] for j in listed] == ids[::-1]+def test_cancel_waiting_job(client, fake):+ gate = threading.Event()+ orig = fake._generate+ fake._generate = lambda seeds, req: (gate.wait(10), orig(seeds, req))[1]+ a, b, c = (client.post("/api/jobs", json={"arguments": {"prompt": f"p{i}", "duration_seconds": 1}}).json()["id"]+ for i in range(3))+ end = time.time() + 5+ while client.get(f"/api/jobs/{a}").json()["status"] != "running" and time.time() < end:+ time.sleep(0.02)+ assert client.post(f"/api/jobs/{a}/cancel", json={}).status_code == 409 # running+ r = client.post(f"/api/jobs/{b}/cancel", json={})+ assert r.status_code == 200 and r.json()["status"] == "cancelled"+ assert client.get(f"/api/jobs/{c}").json()["position"] == 1+ assert client.post("/api/jobs/nope/cancel", json={}).status_code == 404+ gate.set()+ assert wait_job(client, c)["status"] == "done"+ assert client.get(f"/api/jobs/{b}").json()["status"] == "cancelled"+ assert [r[1].prompt for r in fake.requests] == [f"TrackType: Music, VocalType: Instrumental, p{i}." for i in (0, 2)]+ assert client.get("/api/jobs").json()["loaded"] is True+++def test_library_item(client, fake):+ _make_library(fake)+ item = client.get("/api/library/a.wav").json()+ assert item["file"] == "a.wav" and item["meta"]["seed"] == 42+ for bad in ("../secret.wav", "notes.txt", "missing.wav"):+ assert client.get(f"/api/library/{bad}").status_code == 404++def test_unload(client, fake):assert client.post("/api/unload", json={}).json() == {"unloaded": False}fake._loaded = True