Fandresenar6 commited on
Commit
df2292e
·
verified ·
1 Parent(s): 6de5a84

Deploy stem separator backend

Browse files
Files changed (1) hide show
  1. app.py +209 -209
app.py CHANGED
@@ -1,209 +1,209 @@
1
- """Séparation voix / instrumental avec Demucs sur un Space Hugging Face (CPU).
2
-
3
- Même contrat d'API que modal_app.py, pour que le front Next.js marche sans changement :
4
- POST /jobs {"audio_url": "..."} -> {"job_id": "..."} (Bearer API_TOKEN)
5
- GET /jobs/{id} -> {"status": ..., "files": {...}} (Bearer API_TOKEN)
6
- GET /files/{id}/{stem}.mp3?exp=...&sig=... (lien signé)
7
-
8
- Les tâches passent une par une dans une file (le CPU gratuit n'en supporte pas plus).
9
- """
10
-
11
- import hashlib
12
- import hmac
13
- import os
14
- import queue
15
- import shutil
16
- import subprocess
17
- import sys
18
- import threading
19
- import time
20
- import urllib.request
21
- import uuid
22
- from pathlib import Path
23
-
24
- from fastapi import Depends, FastAPI, Header, HTTPException, Request
25
- from fastapi.middleware.cors import CORSMiddleware
26
- from fastapi.responses import FileResponse
27
- from pydantic import BaseModel
28
-
29
- MODEL = os.environ.get("DEMUCS_MODEL", "htdemucs")
30
- STEMS = ["vocals", "no_vocals"]
31
- OUTPUT_DIR = Path(os.environ.get("OUTPUT_DIR", "/tmp/stem-outputs"))
32
- MAX_DURATION_S = int(os.environ.get("MAX_DURATION_S", 10 * 60))
33
- MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024
34
- LINK_TTL_S = 3600
35
- RETENTION_S = 24 * 3600
36
-
37
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
38
-
39
- jobs: dict[str, dict] = {}
40
- jobs_lock = threading.Lock()
41
- work_queue: "queue.Queue[str]" = queue.Queue()
42
-
43
-
44
- def _set(job_id: str, **fields) -> None:
45
- with jobs_lock:
46
- jobs[job_id].update(fields, updated_at=time.time())
47
-
48
-
49
- # --------------------------------------------------------------------------- traitement
50
-
51
- def _separate(job_id: str) -> None:
52
- job = jobs[job_id]
53
- started = time.time()
54
- work = OUTPUT_DIR / f"work-{job_id}"
55
- work.mkdir(parents=True, exist_ok=True)
56
- try:
57
- src = work / "input"
58
- with urllib.request.urlopen(job["source_url"], timeout=60) as resp, open(src, "wb") as f:
59
- total = 0
60
- while chunk := resp.read(1 << 20):
61
- total += len(chunk)
62
- if total > MAX_DOWNLOAD_BYTES:
63
- raise ValueError("Fichier trop volumineux")
64
- f.write(chunk)
65
-
66
- probe = subprocess.run(
67
- ["ffprobe", "-v", "error", "-show_entries", "format=duration",
68
- "-of", "default=nw=1:nk=1", str(src)],
69
- capture_output=True, text=True,
70
- )
71
- duration = float(probe.stdout.strip() or 0)
72
- if duration <= 0:
73
- raise ValueError("Fichier audio illisible")
74
- if duration > MAX_DURATION_S:
75
- raise ValueError(f"Morceau trop long ({duration:.0f}s > {MAX_DURATION_S}s)")
76
- _set(job_id, audio_duration=duration)
77
-
78
- proc = subprocess.run(
79
- [sys.executable, "-m", "demucs", "-n", MODEL, "--two-stems=vocals", "-d", "cpu",
80
- "--mp3", "--mp3-bitrate", "320", "-o", str(work / "out"), str(src)],
81
- capture_output=True, text=True,
82
- )
83
- if proc.returncode != 0:
84
- print(f"[error] job={job_id} demucs: {proc.stderr[-2000:]}", flush=True)
85
- raise RuntimeError("Échec de la séparation")
86
-
87
- produced = work / "out" / MODEL / src.stem
88
- dest = OUTPUT_DIR / job_id
89
- dest.mkdir(parents=True, exist_ok=True)
90
- for stem in STEMS:
91
- shutil.move(str(produced / f"{stem}.mp3"), dest / f"{stem}.mp3")
92
-
93
- elapsed = time.time() - started
94
- print(f"[metrics] job={job_id} duration={duration:.1f}s cpu_time={elapsed:.1f}s", flush=True)
95
- _set(job_id, status="done", processing_seconds=elapsed)
96
- except Exception as e: # noqa: BLE001
97
- print(f"[error] job={job_id} {e}", flush=True)
98
- _set(job_id, status="error", error=str(e))
99
- finally:
100
- shutil.rmtree(work, ignore_errors=True)
101
-
102
-
103
- def _worker() -> None:
104
- while True:
105
- job_id = work_queue.get()
106
- _set(job_id, status="running")
107
- _separate(job_id)
108
- work_queue.task_done()
109
-
110
-
111
- def _cleanup() -> None:
112
- while True:
113
- cutoff = time.time() - RETENTION_S
114
- with jobs_lock:
115
- expired = [j for j, st in jobs.items() if st["created_at"] < cutoff]
116
- for j in expired:
117
- jobs.pop(j)
118
- for j in expired:
119
- shutil.rmtree(OUTPUT_DIR / j, ignore_errors=True)
120
- if expired:
121
- print(f"[cleanup] {len(expired)} tâche(s) supprimée(s)", flush=True)
122
- time.sleep(3600)
123
-
124
-
125
- threading.Thread(target=_worker, daemon=True).start()
126
- threading.Thread(target=_cleanup, daemon=True).start()
127
-
128
-
129
- # --------------------------------------------------------------------------- liens signés
130
-
131
- def _sign(job_id: str, stem: str, exp: int) -> str:
132
- key = os.environ["SIGNING_KEY"].encode()
133
- return hmac.new(key, f"{job_id}/{stem}:{exp}".encode(), hashlib.sha256).hexdigest()
134
-
135
-
136
- def _public_base(request: Request) -> str:
137
- if os.environ.get("PUBLIC_URL"):
138
- return os.environ["PUBLIC_URL"].rstrip("/")
139
- base = str(request.base_url).rstrip("/")
140
- # Derri��re le proxy Hugging Face, la requête arrive en http : on force https.
141
- if base.startswith("http://") and request.url.hostname not in ("localhost", "127.0.0.1"):
142
- base = "https://" + base[len("http://"):]
143
- return base
144
-
145
-
146
- # --------------------------------------------------------------------------- API
147
-
148
- app = FastAPI(title="Stem separator API")
149
- # Le mixeur du navigateur lit les stems via fetch() : CORS nécessaire sur les liens signés.
150
- app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"], allow_headers=["*"])
151
-
152
-
153
- def require_token(authorization: str = Header(default="")):
154
- expected = f"Bearer {os.environ['API_TOKEN']}"
155
- if not hmac.compare_digest(authorization, expected):
156
- raise HTTPException(401, "Unauthorized")
157
-
158
-
159
- class JobIn(BaseModel):
160
- audio_url: str
161
-
162
-
163
- @app.get("/")
164
- def health():
165
- return {"ok": True, "model": MODEL, "queue": work_queue.qsize()}
166
-
167
-
168
- @app.post("/jobs", dependencies=[Depends(require_token)])
169
- def create_job(body: JobIn):
170
- if not body.audio_url.startswith("https://"):
171
- raise HTTPException(400, "audio_url doit être en https")
172
- job_id = uuid.uuid4().hex
173
- with jobs_lock:
174
- jobs[job_id] = {"status": "queued", "source_url": body.audio_url, "created_at": time.time()}
175
- work_queue.put(job_id)
176
- return {"job_id": job_id}
177
-
178
-
179
- @app.get("/jobs/{job_id}", dependencies=[Depends(require_token)])
180
- def get_job(job_id: str, request: Request):
181
- with jobs_lock:
182
- st = dict(jobs.get(job_id) or {})
183
- if not st:
184
- raise HTTPException(404, "Tâche inconnue (le Space a peut-être redémarré)")
185
-
186
- out = {k: st.get(k) for k in ("status", "error", "source_url", "audio_duration", "processing_seconds")}
187
- out["job_id"] = job_id
188
- if st["status"] == "queued":
189
- out["queue_position"] = list(work_queue.queue).index(job_id) + 1 if job_id in work_queue.queue else 0
190
- if st["status"] == "done":
191
- exp = int(time.time()) + LINK_TTL_S
192
- base = _public_base(request)
193
- out["files"] = {
194
- stem: f"{base}/files/{job_id}/{stem}.mp3?exp={exp}&sig={_sign(job_id, stem, exp)}"
195
- for stem in STEMS
196
- }
197
- return out
198
-
199
-
200
- @app.get("/files/{job_id}/{stem}.mp3")
201
- def get_file(job_id: str, stem: str, exp: int, sig: str):
202
- if stem not in STEMS or not job_id.isalnum():
203
- raise HTTPException(404)
204
- if exp < time.time() or not hmac.compare_digest(sig, _sign(job_id, stem, exp)):
205
- raise HTTPException(403, "Lien expiré ou invalide")
206
- path = OUTPUT_DIR / job_id / f"{stem}.mp3"
207
- if not path.exists():
208
- raise HTTPException(404)
209
- return FileResponse(path, media_type="audio/mpeg", filename=f"{stem}.mp3")
 
1
+ """Séparation voix / instrumental avec Demucs sur un Space Hugging Face (CPU).
2
+
3
+ Même contrat d'API que modal_app.py, pour que le front Next.js marche sans changement :
4
+ POST /jobs {"audio_url": "..."} -> {"job_id": "..."} (Bearer API_TOKEN)
5
+ GET /jobs/{id} -> {"status": ..., "files": {...}} (Bearer API_TOKEN)
6
+ GET /files/{id}/{stem}.mp3?exp=...&sig=... (lien signé)
7
+
8
+ Les tâches passent une par une dans une file (le CPU gratuit n'en supporte pas plus).
9
+ """
10
+
11
+ import hashlib
12
+ import hmac
13
+ import os
14
+ import queue
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import threading
19
+ import time
20
+ import urllib.request
21
+ import uuid
22
+ from pathlib import Path
23
+
24
+ from fastapi import Depends, FastAPI, Header, HTTPException, Request
25
+ from fastapi.middleware.cors import CORSMiddleware
26
+ from fastapi.responses import FileResponse
27
+ from pydantic import BaseModel
28
+
29
+ MODEL = os.environ.get("DEMUCS_MODEL", "htdemucs")
30
+ STEMS = ["vocals", "no_vocals"]
31
+ OUTPUT_DIR = Path(os.environ.get("OUTPUT_DIR", "/tmp/stem-outputs"))
32
+ MAX_DURATION_S = int(os.environ.get("MAX_DURATION_S", 10 * 60))
33
+ MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024
34
+ LINK_TTL_S = 3600
35
+ RETENTION_S = 24 * 3600
36
+
37
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
38
+
39
+ jobs: dict[str, dict] = {}
40
+ jobs_lock = threading.Lock()
41
+ work_queue: "queue.Queue[str]" = queue.Queue()
42
+
43
+
44
+ def _set(job_id: str, **fields) -> None:
45
+ with jobs_lock:
46
+ jobs[job_id].update(fields, updated_at=time.time())
47
+
48
+
49
+ # --------------------------------------------------------------------------- traitement
50
+
51
+ def _separate(job_id: str) -> None:
52
+ job = jobs[job_id]
53
+ started = time.time()
54
+ work = OUTPUT_DIR / f"work-{job_id}"
55
+ work.mkdir(parents=True, exist_ok=True)
56
+ try:
57
+ src = work / "input"
58
+ with urllib.request.urlopen(urllib.request.Request(job["source_url"], headers={"User-Agent": "stem-separator/1.0"}), timeout=60) as resp, open(src, "wb") as f:
59
+ total = 0
60
+ while chunk := resp.read(1 << 20):
61
+ total += len(chunk)
62
+ if total > MAX_DOWNLOAD_BYTES:
63
+ raise ValueError("Fichier trop volumineux")
64
+ f.write(chunk)
65
+
66
+ probe = subprocess.run(
67
+ ["ffprobe", "-v", "error", "-show_entries", "format=duration",
68
+ "-of", "default=nw=1:nk=1", str(src)],
69
+ capture_output=True, text=True,
70
+ )
71
+ duration = float(probe.stdout.strip() or 0)
72
+ if duration <= 0:
73
+ raise ValueError("Fichier audio illisible")
74
+ if duration > MAX_DURATION_S:
75
+ raise ValueError(f"Morceau trop long ({duration:.0f}s > {MAX_DURATION_S}s)")
76
+ _set(job_id, audio_duration=duration)
77
+
78
+ proc = subprocess.run(
79
+ [sys.executable, "-m", "demucs", "-n", MODEL, "--two-stems=vocals", "-d", "cpu",
80
+ "--mp3", "--mp3-bitrate", "320", "-o", str(work / "out"), str(src)],
81
+ capture_output=True, text=True,
82
+ )
83
+ if proc.returncode != 0:
84
+ print(f"[error] job={job_id} demucs: {proc.stderr[-2000:]}", flush=True)
85
+ raise RuntimeError("Échec de la séparation")
86
+
87
+ produced = work / "out" / MODEL / src.stem
88
+ dest = OUTPUT_DIR / job_id
89
+ dest.mkdir(parents=True, exist_ok=True)
90
+ for stem in STEMS:
91
+ shutil.move(str(produced / f"{stem}.mp3"), dest / f"{stem}.mp3")
92
+
93
+ elapsed = time.time() - started
94
+ print(f"[metrics] job={job_id} duration={duration:.1f}s cpu_time={elapsed:.1f}s", flush=True)
95
+ _set(job_id, status="done", processing_seconds=elapsed)
96
+ except Exception as e: # noqa: BLE001
97
+ print(f"[error] job={job_id} {e}", flush=True)
98
+ _set(job_id, status="error", error=str(e))
99
+ finally:
100
+ shutil.rmtree(work, ignore_errors=True)
101
+
102
+
103
+ def _worker() -> None:
104
+ while True:
105
+ job_id = work_queue.get()
106
+ _set(job_id, status="running")
107
+ _separate(job_id)
108
+ work_queue.task_done()
109
+
110
+
111
+ def _cleanup() -> None:
112
+ while True:
113
+ cutoff = time.time() - RETENTION_S
114
+ with jobs_lock:
115
+ expired = [j for j, st in jobs.items() if st["created_at"] < cutoff]
116
+ for j in expired:
117
+ jobs.pop(j)
118
+ for j in expired:
119
+ shutil.rmtree(OUTPUT_DIR / j, ignore_errors=True)
120
+ if expired:
121
+ print(f"[cleanup] {len(expired)} tâche(s) supprimée(s)", flush=True)
122
+ time.sleep(3600)
123
+
124
+
125
+ threading.Thread(target=_worker, daemon=True).start()
126
+ threading.Thread(target=_cleanup, daemon=True).start()
127
+
128
+
129
+ # --------------------------------------------------------------------------- liens signés
130
+
131
+ def _sign(job_id: str, stem: str, exp: int) -> str:
132
+ key = os.environ["SIGNING_KEY"].encode()
133
+ return hmac.new(key, f"{job_id}/{stem}:{exp}".encode(), hashlib.sha256).hexdigest()
134
+
135
+
136
+ def _public_base(request: Request) -> str:
137
+ if os.environ.get("PUBLIC_URL"):
138
+ return os.environ["PUBLIC_URL"].rstrip("/")
139
+ base = str(request.base_url).rstrip("/")
140
+ # Derrière le proxy Hugging Face, la requête arrive en http : on force https.
141
+ if base.startswith("http://") and request.url.hostname not in ("localhost", "127.0.0.1"):
142
+ base = "https://" + base[len("http://"):]
143
+ return base
144
+
145
+
146
+ # --------------------------------------------------------------------------- API
147
+
148
+ app = FastAPI(title="Stem separator API")
149
+ # Le mixeur du navigateur lit les stems via fetch() : CORS nécessaire sur les liens signés.
150
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"], allow_headers=["*"])
151
+
152
+
153
+ def require_token(authorization: str = Header(default="")):
154
+ expected = f"Bearer {os.environ['API_TOKEN']}"
155
+ if not hmac.compare_digest(authorization, expected):
156
+ raise HTTPException(401, "Unauthorized")
157
+
158
+
159
+ class JobIn(BaseModel):
160
+ audio_url: str
161
+
162
+
163
+ @app.get("/")
164
+ def health():
165
+ return {"ok": True, "model": MODEL, "queue": work_queue.qsize()}
166
+
167
+
168
+ @app.post("/jobs", dependencies=[Depends(require_token)])
169
+ def create_job(body: JobIn):
170
+ if not body.audio_url.startswith("https://"):
171
+ raise HTTPException(400, "audio_url doit être en https")
172
+ job_id = uuid.uuid4().hex
173
+ with jobs_lock:
174
+ jobs[job_id] = {"status": "queued", "source_url": body.audio_url, "created_at": time.time()}
175
+ work_queue.put(job_id)
176
+ return {"job_id": job_id}
177
+
178
+
179
+ @app.get("/jobs/{job_id}", dependencies=[Depends(require_token)])
180
+ def get_job(job_id: str, request: Request):
181
+ with jobs_lock:
182
+ st = dict(jobs.get(job_id) or {})
183
+ if not st:
184
+ raise HTTPException(404, "Tâche inconnue (le Space a peut-être redémarré)")
185
+
186
+ out = {k: st.get(k) for k in ("status", "error", "source_url", "audio_duration", "processing_seconds")}
187
+ out["job_id"] = job_id
188
+ if st["status"] == "queued":
189
+ out["queue_position"] = list(work_queue.queue).index(job_id) + 1 if job_id in work_queue.queue else 0
190
+ if st["status"] == "done":
191
+ exp = int(time.time()) + LINK_TTL_S
192
+ base = _public_base(request)
193
+ out["files"] = {
194
+ stem: f"{base}/files/{job_id}/{stem}.mp3?exp={exp}&sig={_sign(job_id, stem, exp)}"
195
+ for stem in STEMS
196
+ }
197
+ return out
198
+
199
+
200
+ @app.get("/files/{job_id}/{stem}.mp3")
201
+ def get_file(job_id: str, stem: str, exp: int, sig: str):
202
+ if stem not in STEMS or not job_id.isalnum():
203
+ raise HTTPException(404)
204
+ if exp < time.time() or not hmac.compare_digest(sig, _sign(job_id, stem, exp)):
205
+ raise HTTPException(403, "Lien expiré ou invalide")
206
+ path = OUTPUT_DIR / job_id / f"{stem}.mp3"
207
+ if not path.exists():
208
+ raise HTTPException(404)
209
+ return FileResponse(path, media_type="audio/mpeg", filename=f"{stem}.mp3")