Spaces:
Running on Zero
Running on Zero
Deploy the StemDeck GPU service
Browse files- app.py +83 -0
- requirements.txt +2 -0
- stemdeck/youtube.py +12 -5
app.py
CHANGED
|
@@ -322,6 +322,80 @@ def _parse_stems(raw: str) -> list[dict[str, Any]]:
|
|
| 322 |
return stems
|
| 323 |
|
| 324 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
def _qualities() -> list[str]:
|
| 326 |
from stemdeck.settings import get_config
|
| 327 |
|
|
@@ -358,6 +432,15 @@ with gr.Blocks(title="StemDeck GPU service", delete_cache=(3600, 3600)) as demo:
|
|
| 358 |
extract_btn.click(extract, [stem_in, source_in, existing_in, extractor_in], [extract_meta, extract_files],
|
| 359 |
api_name="extract")
|
| 360 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
demo.queue(default_concurrency_limit=1, max_size=20)
|
| 362 |
|
| 363 |
if __name__ == "__main__":
|
|
|
|
| 322 |
return stems
|
| 323 |
|
| 324 |
|
| 325 |
+
# ---------------------------------------------------------------------- YouTube links (CPU only: no GPU time)
|
| 326 |
+
YOUTUBE_DIR = WORK / "youtube"
|
| 327 |
+
# Optional: a cookies.txt export of a YouTube account, kept as a private secret of this Space. YouTube asks
|
| 328 |
+
# servers like this one to "confirm you're not a bot"; a signed-in session gets past that.
|
| 329 |
+
YOUTUBE_COOKIES_SECRET = "STEMDECK_YOUTUBE_COOKIES"
|
| 330 |
+
YOUTUBE_BLOCKED = "youtube-blocked" # the website then gets the song through the visitor's own browser
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _load_youtube_sign_in() -> None:
|
| 334 |
+
from stemdeck import youtube as yt
|
| 335 |
+
from stemdeck.settings import get_settings
|
| 336 |
+
|
| 337 |
+
raw = os.environ.pop(YOUTUBE_COOKIES_SECRET, "") # not left in the environment of anything started later
|
| 338 |
+
if not raw.strip():
|
| 339 |
+
return
|
| 340 |
+
settings = get_settings()
|
| 341 |
+
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
| 342 |
+
try:
|
| 343 |
+
log.info("YouTube sign-in loaded (%d youtube.com cookies)", yt.save_cookies(settings, raw.encode()))
|
| 344 |
+
except yt.YouTubeError as exc:
|
| 345 |
+
log.warning("YouTube sign-in not loaded: %s", exc)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
_load_youtube_sign_in()
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def _clean_old_downloads() -> None:
|
| 352 |
+
if not YOUTUBE_DIR.is_dir():
|
| 353 |
+
return
|
| 354 |
+
cutoff = time.time() - KEEP_JOB_FOLDERS_SEC
|
| 355 |
+
for folder in YOUTUBE_DIR.iterdir():
|
| 356 |
+
try:
|
| 357 |
+
if folder.is_dir() and folder.stat().st_mtime < cutoff:
|
| 358 |
+
shutil.rmtree(folder, ignore_errors=True)
|
| 359 |
+
except OSError:
|
| 360 |
+
continue
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
def _is_blocked(exc: BaseException) -> bool:
|
| 364 |
+
"""YouTube refused this server ("confirm you're not a bot", a sign-in wall, or too many requests)."""
|
| 365 |
+
text = f"{exc} {exc.__cause__ or ''}".lower()
|
| 366 |
+
return any(needle in text for needle in ("not a bot", "sign in to confirm", "sign-in before", "http error 429",
|
| 367 |
+
"too many requests", "limiting downloads", "blocking downloads"))
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def youtube(url: str) -> tuple[dict[str, Any], list[str]]:
|
| 371 |
+
"""A YouTube link -> the song's original audio (no GPU time). Failures come back as {"error", "reason"}."""
|
| 372 |
+
import uuid
|
| 373 |
+
|
| 374 |
+
from stemdeck import youtube as yt
|
| 375 |
+
from stemdeck.settings import get_config, get_settings
|
| 376 |
+
|
| 377 |
+
cfg, settings = get_config(), get_settings()
|
| 378 |
+
_clean_old_downloads()
|
| 379 |
+
try:
|
| 380 |
+
canonical = yt.canonical_url(url or "")
|
| 381 |
+
folder = YOUTUBE_DIR / uuid.uuid4().hex
|
| 382 |
+
path, info = yt.download_song(canonical, folder, settings, cfg.max_duration_sec,
|
| 383 |
+
cfg.max_upload_mb * 1024 * 1024, lambda _done, _text: None)
|
| 384 |
+
except yt.YouTubeError as exc:
|
| 385 |
+
if _is_blocked(exc):
|
| 386 |
+
log.warning("YouTube blocked a download: %s", exc.__cause__ or exc)
|
| 387 |
+
return {"error": "YouTube is blocking downloads from this server right now.",
|
| 388 |
+
"reason": YOUTUBE_BLOCKED}, []
|
| 389 |
+
return {"error": str(exc)}, []
|
| 390 |
+
except Exception: # noqa: BLE001 - logged in full here, summarised for the visitor
|
| 391 |
+
log.exception("YouTube download failed")
|
| 392 |
+
return {"error": "Couldn't get this song from YouTube. Try again, or upload the file."}, []
|
| 393 |
+
log.info("YouTube song ready: %s (%.0f s, %.1f MB)", info.video_id, info.duration_sec or 0,
|
| 394 |
+
path.stat().st_size / 1e6)
|
| 395 |
+
return {"title": info.title, "artist": info.artist, "duration_sec": info.duration_sec, "url": canonical,
|
| 396 |
+
"file": path.name}, [str(path)]
|
| 397 |
+
|
| 398 |
+
|
| 399 |
def _qualities() -> list[str]:
|
| 400 |
from stemdeck.settings import get_config
|
| 401 |
|
|
|
|
| 432 |
extract_btn.click(extract, [stem_in, source_in, existing_in, extractor_in], [extract_meta, extract_files],
|
| 433 |
api_name="extract")
|
| 434 |
|
| 435 |
+
with gr.Accordion("Get a song from a YouTube link (used by the website)", open=False):
|
| 436 |
+
link_in = gr.Textbox(label="YouTube link", placeholder="https://www.youtube.com/watch?v=…")
|
| 437 |
+
link_btn = gr.Button("Get the song")
|
| 438 |
+
link_meta = gr.JSON(label="Details")
|
| 439 |
+
link_files = gr.File(file_count="multiple", label="Song")
|
| 440 |
+
# Its own queue lane: a download never waits behind a GPU job, and uses no GPU time.
|
| 441 |
+
link_btn.click(youtube, [link_in], [link_meta, link_files], api_name="youtube", concurrency_limit=4,
|
| 442 |
+
concurrency_id="youtube")
|
| 443 |
+
|
| 444 |
demo.queue(default_concurrency_limit=1, max_size=20)
|
| 445 |
|
| 446 |
if __name__ == "__main__":
|
requirements.txt
CHANGED
|
@@ -12,3 +12,5 @@ sqlmodel>=0.0.22
|
|
| 12 |
pydantic-settings>=2.6
|
| 13 |
psutil>=6
|
| 14 |
truststore>=0.10
|
|
|
|
|
|
|
|
|
| 12 |
pydantic-settings>=2.6
|
| 13 |
psutil>=6
|
| 14 |
truststore>=0.10
|
| 15 |
+
yt-dlp[default]>=2026.10.26 # YouTube links (includes yt-dlp-ejs for YouTube's player challenges)
|
| 16 |
+
deno>=2.5 # the JavaScript runtime yt-dlp uses for those challenges
|
stemdeck/youtube.py
CHANGED
|
@@ -301,9 +301,15 @@ def probe(url: str, settings: Settings | None = None) -> VideoInfo:
|
|
| 301 |
|
| 302 |
def download_audio(url: str, dest_dir: Path, settings: Settings, max_duration_sec: float,
|
| 303 |
max_bytes: int, on_progress: Callable[[float, str], None]) -> Path:
|
| 304 |
-
"""Download the best audio-only stream of `url` into `dest_dir` and return the file path.
|
| 305 |
-
|
| 306 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
dest_dir.mkdir(parents=True, exist_ok=True)
|
| 308 |
for leftover in dest_dir.glob("audio.*"):
|
| 309 |
if leftover.suffix not in _PARTIAL_SUFFIXES:
|
|
@@ -321,7 +327,8 @@ def download_audio(url: str, dest_dir: Path, settings: Settings, max_duration_se
|
|
| 321 |
paths={"home": str(dest_dir), "temp": str(dest_dir)}, progress_hooks=[hook],
|
| 322 |
max_filesize=max_bytes, overwrites=True) as ydl:
|
| 323 |
raw = ydl.extract_info(url, download=False) or {}
|
| 324 |
-
|
|
|
|
| 325 |
result = ydl.process_ie_result(raw, download=True) or {}
|
| 326 |
downloads = result.get("requested_downloads") or []
|
| 327 |
path = Path(downloads[0]["filepath"]) if downloads and downloads[0].get("filepath") else None
|
|
@@ -330,7 +337,7 @@ def download_audio(url: str, dest_dir: Path, settings: Settings, max_duration_se
|
|
| 330 |
if path is None or path.stat().st_size == 0:
|
| 331 |
raise YouTubeError("YouTube didn't send any audio for this video (it may be too big or "
|
| 332 |
"region-locked). Try another link.")
|
| 333 |
-
return path
|
| 334 |
|
| 335 |
|
| 336 |
# ------------------------------------------------------------------ error messages
|
|
|
|
| 301 |
|
| 302 |
def download_audio(url: str, dest_dir: Path, settings: Settings, max_duration_sec: float,
|
| 303 |
max_bytes: int, on_progress: Callable[[float, str], None]) -> Path:
|
| 304 |
+
"""Download the best audio-only stream of `url` into `dest_dir` and return the file path."""
|
| 305 |
+
return download_song(url, dest_dir, settings, max_duration_sec, max_bytes, on_progress)[0]
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def download_song(url: str, dest_dir: Path, settings: Settings, max_duration_sec: float,
|
| 309 |
+
max_bytes: int, on_progress: Callable[[float, str], None]) -> tuple[Path, VideoInfo]:
|
| 310 |
+
"""Download the best audio-only stream of `url` into `dest_dir`; returns the file and the video's details.
|
| 311 |
+
Partial files from an interrupted try are kept (yt-dlp resumes them); finished leftovers are removed so they
|
| 312 |
+
can't be mistaken for this run's download."""
|
| 313 |
dest_dir.mkdir(parents=True, exist_ok=True)
|
| 314 |
for leftover in dest_dir.glob("audio.*"):
|
| 315 |
if leftover.suffix not in _PARTIAL_SUFFIXES:
|
|
|
|
| 327 |
paths={"home": str(dest_dir), "temp": str(dest_dir)}, progress_hooks=[hook],
|
| 328 |
max_filesize=max_bytes, overwrites=True) as ydl:
|
| 329 |
raw = ydl.extract_info(url, download=False) or {}
|
| 330 |
+
info = _info_from(raw, url)
|
| 331 |
+
check_video(info, max_duration_sec)
|
| 332 |
result = ydl.process_ie_result(raw, download=True) or {}
|
| 333 |
downloads = result.get("requested_downloads") or []
|
| 334 |
path = Path(downloads[0]["filepath"]) if downloads and downloads[0].get("filepath") else None
|
|
|
|
| 337 |
if path is None or path.stat().st_size == 0:
|
| 338 |
raise YouTubeError("YouTube didn't send any audio for this video (it may be too big or "
|
| 339 |
"region-locked). Try another link.")
|
| 340 |
+
return path, info
|
| 341 |
|
| 342 |
|
| 343 |
# ------------------------------------------------------------------ error messages
|