File size: 4,918 Bytes
f53d0e4
 
7ec8916
 
 
 
f53d0e4
 
7ec8916
31536a1
 
 
 
7ec8916
 
 
 
 
 
 
 
 
 
 
f53d0e4
 
 
7ec8916
 
f53d0e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ec8916
 
 
 
 
 
f53d0e4
7ec8916
 
c77ac80
 
 
 
7ec8916
 
 
 
f53d0e4
 
 
 
 
 
 
7ec8916
f53d0e4
 
 
 
 
 
7ec8916
f53d0e4
 
 
 
7ec8916
f53d0e4
 
 
 
 
 
 
 
7ec8916
 
 
f53d0e4
 
 
7ec8916
f53d0e4
 
 
 
31536a1
 
f53d0e4
 
 
 
 
 
 
31536a1
 
 
f53d0e4
31536a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f53d0e4
31536a1
f53d0e4
 
31536a1
 
 
f53d0e4
31536a1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
from fastapi import FastAPI, UploadFile, File, BackgroundTasks, HTTPException
from fastapi.responses import FileResponse
import torch
import os
import uuid
import subprocess
import threading
from typing import Dict

import zipfile
import tempfile


app = FastAPI()

UPLOAD_DIR = "uploads"
OUTPUT_DIR = "outputs"

os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

QUALITY_PRESETS = {
    "low": {"shifts": 0, "overlap": 0.25},
    "medium": {"shifts": 1, "overlap": 0.25},
    "high": {"shifts": 2, "overlap": 0.5},
}

# -----------------------------
# In-memory job store
# -----------------------------
jobs: Dict[str, dict] = {}

# -----------------------------
# Worker function
# -----------------------------
def run_demucs(job_id: str, input_path: str, quality: str):
    try:
        jobs[job_id]["status"] = "processing"
        jobs[job_id]["progress"] = 10

        preset = QUALITY_PRESETS[quality]
        output_path = os.path.join(OUTPUT_DIR, job_id)

        cmd = [
            "python3", "-m", "demucs",
            "--device", DEVICE,
            "--shifts", str(preset["shifts"]),
            "--overlap", str(preset["overlap"]),
            "--out", output_path,
            input_path
        ]

        subprocess.run(cmd, check=True)

        base = os.path.splitext(os.path.basename(input_path))[0]
        stems_dir = os.path.join(output_path, "htdemucs", base)

        jobs[job_id]["stems"] = {
            "vocals": f"{stems_dir}/vocals.wav",
            "drums": f"{stems_dir}/drums.wav",
            "bass": f"{stems_dir}/bass.wav",
            "other": f"{stems_dir}/other.wav",
        }

        jobs[job_id]["progress"] = 100
        jobs[job_id]["status"] = "completed"

    except Exception as e:
        jobs[job_id]["status"] = "failed"
        jobs[job_id]["error"] = str(e)

# -----------------------------
# Cleanup helper
# -----------------------------
def cleanup_job(job_id: str):
    job = jobs.get(job_id)
    if not job:
        return

    for path in job.get("stems", {}).values():
        if os.path.exists(path):
            os.remove(path)

    input_file = job.get("input_path")
    if input_file and os.path.exists(input_file):
        os.remove(input_file)

    output_dir = os.path.join(OUTPUT_DIR, job_id)
    if os.path.exists(output_dir):
        subprocess.run(["rm", "-rf", output_dir])

    jobs.pop(job_id, None)

# -----------------------------
# Create job
# -----------------------------
@app.post("/separate")
async def separate_audio(
    file: UploadFile = File(...),
    quality: str = "medium"
):
    if quality not in QUALITY_PRESETS:
        raise HTTPException(400, "quality must be low, medium, or high")

    job_id = uuid.uuid4().hex
    
    safe_name = os.path.basename(file.filename)
    input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{safe_name}")


    with open(input_path, "wb") as f:
        f.write(await file.read())

    jobs[job_id] = {
        "status": "queued",
        "progress": 0,
        "quality": quality,
        "input_path": input_path,
        "stems": None,
    }

    thread = threading.Thread(
        target=run_demucs,
        args=(job_id, input_path, quality),
        daemon=True
    )
    thread.start()

    return {
        "job_id": job_id,
        "status": "queued"
    }

# -----------------------------
# Progress polling
# -----------------------------
@app.get("/status/{job_id}")
def job_status(job_id: str):
    job = jobs.get(job_id)
    if not job:
        raise HTTPException(404, "Job not found")

    return {
        "job_id": job_id,
        "status": job["status"],
        "progress": job["progress"],
        "stems": job.get("stems")
    }

# -----------------------------
# Download stem + auto cleanup
# -----------------------------
@app.get("/download/{job_id}/all")
def download_all_stems(
    job_id: str,
    background_tasks: BackgroundTasks
):
    job = jobs.get(job_id)
    if not job or job["status"] != "completed":
        raise HTTPException(404, "Job not completed")

    stems = job.get("stems")
    if not stems:
        raise HTTPException(404, "No stems found")

    # create temp zip file
    tmp = tempfile.NamedTemporaryFile(
        delete=False,
        suffix=".zip"
    )
    zip_path = tmp.name
    tmp.close()

    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
        for stem_name, stem_path in stems.items():
            if os.path.exists(stem_path):
                zipf.write(
                    stem_path,
                    arcname=f"{stem_name}.wav"
                )

    # cleanup after response is sent
    background_tasks.add_task(cleanup_job, job_id)
    background_tasks.add_task(os.remove, zip_path)

    return FileResponse(
        zip_path,
        media_type="application/zip",
        filename=f"{job_id}_stems.zip"
    )