File size: 4,223 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""GET /api/system: device, tools, qualities, extractors and YouTube sign-in status."""

from __future__ import annotations

import importlib.metadata
import os
import shutil
from pathlib import Path
from typing import Any

from fastapi import APIRouter
from fastapi.concurrency import run_in_threadpool

from stemdeck import youtube
from stemdeck.device import probe
from stemdeck.settings import ExtractorConfig, get_config, get_settings

router = APIRouter(tags=["system"])

ACCEPTED_EXTENSIONS = (".mp3", ".mp4", ".m4a", ".wav", ".flac", ".ogg", ".webm", ".mov", ".aac", ".opus")


def sam_audio_status() -> tuple[bool, str | None]:
    settings, cfg = get_settings(), get_config()
    if not settings.resolve(cfg.sam_audio.python).exists():
        return False, "SAM Audio is not installed (see README, 'Isolate anything')."
    has_token = bool(os.environ.get("HF_TOKEN")) or (Path.home() / ".cache" / "huggingface" / "token").exists()
    weights_cached = any((settings.models_dir / "sam-audio").glob("models--facebook--sam-audio-*"))
    if not (has_token or weights_cached):
        return False, "Needs Hugging Face access to facebook/sam-audio-small, then `hf auth login` (see README)."
    return True, None


def _extractor_note(ext: ExtractorConfig) -> str | None:
    if ext.engine != "mega":
        return ext.note
    from stemdeck.pipeline.mega import needs_download

    if not needs_download(get_settings().models_dir / ext.model, list(ext.outputs)):
        return ext.note
    return " ".join(filter(None, [ext.note, "Downloads a 1.4 GB model the first time."]))


def extractors_payload() -> list[dict[str, Any]]:
    cfg = get_config()
    items: list[dict[str, Any]] = [
        {"id": ext_id, "label": ext.label, "source_stem": ext.source_stem, "outputs": list(ext.outputs.values()),
         "available": True, "reason": None, "needs_prompt": False, "note": _extractor_note(ext)}
        for ext_id, ext in cfg.extractors.items()
    ]
    if get_settings().public:
        return items  # SAM Audio needs its own environment and a gated model; the public site doesn't offer it
    sam_ok, sam_reason = sam_audio_status()
    items.append({"id": "prompt", "label": "Isolate anything (text prompt, SAM Audio)", "source_stem": "other",
                  "outputs": [], "available": sam_ok, "reason": sam_reason, "needs_prompt": True,
                  "note": "Experimental: quality varies a lot by sound and song."})
    return items


@router.get("/system")
async def system_info() -> dict[str, Any]:
    info = await run_in_threadpool(probe)
    cfg = get_config()
    settings = get_settings()
    limits = cfg.public
    try:
        audio_separator_version = importlib.metadata.version("audio-separator")
    except importlib.metadata.PackageNotFoundError:
        audio_separator_version = None
    if settings.public:  # visitors don't need the server's software versions
        audio_separator_version = None
    return {
        "device": info.device,
        "gpu_name": info.gpu_name,
        "vram_gb": info.vram_gb,
        "torch_version": None if settings.public else info.torch_version,
        "audio_separator_version": audio_separator_version,
        "ffmpeg": shutil.which("ffmpeg") is not None,
        "sam_audio_available": False if settings.public else sam_audio_status()[0],
        "max_duration_sec": cfg.max_duration_sec,
        "max_upload_mb": cfg.max_upload_mb,
        # Public site: what visitors need to know about the free service (null when running locally).
        "public": {"keep_songs_hours": limits.keep_songs_hours, "max_songs": limits.max_songs_per_visitor,
                   "jobs_per_day": limits.jobs_per_visitor_per_day} if settings.public else None,
        "qualities": [{"id": q_id, "label": q.label, "description": q.description}
                      for q_id, q in cfg.qualities.items()],
        "extractors": extractors_payload(),
        "accepted_extensions": list(ACCEPTED_EXTENSIONS),
        "youtube": {"signed_in": youtube.has_cookies(settings), "js_runtime": youtube.js_runtime(),
                    "managed": settings.public},
    }