File size: 6,716 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
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
"""Runtime settings: `.env` / environment variables plus the typed `config.yaml`."""

from __future__ import annotations

from functools import lru_cache
from pathlib import Path
from typing import Literal

import yaml
from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings, SettingsConfigDict

PROJECT_ROOT = Path(__file__).resolve().parents[2]

Precision = Literal["fp32", "fp16", "autocast"]


class ModelStep(BaseModel):
    model: str
    precision: Precision = "fp32"
    overlap: int = 2
    shifts: int = 1
    rtf: float = 1.0


class QualityProfile(BaseModel):
    label: str
    description: str
    vocals: ModelStep
    karaoke: ModelStep
    instruments: ModelStep


class ExtractorConfig(ModelStep):
    label: str
    source_stem: str
    outputs: dict[str, str]
    # "audio-separator" (catalog models) or "mega" (MVSep 53-stem BS-RoFormer subset, see pipeline/mega.py).
    engine: Literal["audio-separator", "mega"] = "audio-separator"
    # Keep an output only when it holds at least this share of the source's energy and this RMS level
    # (multi-instrument models return every head, most of them near-silent for a given song).
    min_share: float = 0.0
    min_rms_db: float = -200.0
    note: str | None = None


class SamAudioConfig(BaseModel):
    python: str = "spikes/.sam-venv/Scripts/python.exe"
    model_size: str = "small"
    dtype: str = "float16"
    chunk_sec: float = 10.0
    ode_step_size: float = 0.25  # 4 midpoint steps; SAM's own default 0.0625 is ~3x slower, same quality here
    rtf: float = 2.2  # processing time / audio length at the chosen step size (for ETA)


class PublicLimits(BaseModel):
    """Limits for the public site (STEMDECK_PUBLIC=1). Running locally, none of these apply."""

    keep_songs_hours: float = 48.0  # songs (and their stems and mixes) are deleted this long after upload
    max_songs_per_visitor: int = 6
    max_active_jobs_per_visitor: int = 1  # queued or running, per visitor and per network address
    jobs_per_visitor_per_day: int = 10  # splits + extractions + retries, per visitor and per network address
    jobs_per_day: int = 60  # whole site: keeps the free GPU credit from running out
    max_queued_jobs: int = 12  # whole site: beyond this the queue would take too long anyway


class AppConfig(BaseModel):
    max_duration_sec: int = 900
    max_upload_mb: int = 500
    silence_threshold_db: float = -50.0
    peaks_points: int = 3000
    default_quality: str = "fast"
    qualities: dict[str, QualityProfile]
    extractors: dict[str, ExtractorConfig] = Field(default_factory=dict)
    sam_audio: SamAudioConfig = Field(default_factory=SamAudioConfig)
    public: PublicLimits = Field(default_factory=PublicLimits)


class Settings(BaseSettings):
    """Environment-level settings (prefix STEMDECK_), e.g. STEMDECK_DATA_DIR in `.env`."""

    model_config = SettingsConfigDict(env_prefix="STEMDECK_", env_file=PROJECT_ROOT / ".env", extra="ignore")

    data_dir: Path = PROJECT_ROOT / "data"
    config_file: Path = PROJECT_ROOT / "config.yaml"
    port: int = 8000
    log_level: str = "INFO"
    # Public site mode (the cloud deployment in deploy/modal_app.py): every visitor gets a private library
    # (anonymous browser cookie), visitor limits apply, old songs are deleted and YouTube sign-in is site-wide.
    public: bool = False
    # Host names the server answers to (comma-separated; "*.example.com" allowed). Locally only this machine.
    allowed_hosts: str = "127.0.0.1,localhost"
    # SQLite file; defaults to <data_dir>/app.db. The cloud keeps it on local disk (see deploy/modal_app.py).
    db_file: Path | None = None
    # Model cache (STEMDECK_MODELS_DIR); defaults to <data_dir>/models. The public site on this PC shares your
    # own app's models.
    models_dir_override: Path | None = Field(default=None, validation_alias="STEMDECK_MODELS_DIR")
    # Lock file shared by every StemDeck server on this computer, so only one job uses the GPU at a time.
    gpu_lock_file: Path = PROJECT_ROOT / "data" / "gpu.lock"
    # Header holding the visitor's address when a trusted proxy sets it (Cloudflare: "cf-connecting-ip").
    # Unset: the last X-Forwarded-For entry. Never set it without that proxy in front: clients could forge it.
    client_ip_header: str | None = None
    # Live job updates (Server-Sent Events). Cloudflare quick tunnels don't pass them; the page then polls.
    live_updates: bool = True

    @property
    def host(self) -> str:
        return "127.0.0.1"  # `python -m stemdeck` is local-only by design; never bind publicly

    @property
    def allowed_host_list(self) -> list[str]:
        return [h.strip() for h in self.allowed_hosts.split(",") if h.strip()]

    @property
    def songs_dir(self) -> Path:
        return self.data_dir / "songs"

    @property
    def models_dir(self) -> Path:
        return self.models_dir_override or self.data_dir / "models"

    @property
    def logs_dir(self) -> Path:
        return self.data_dir / "logs"

    @property
    def db_path(self) -> Path:
        return self.db_file or self.data_dir / "app.db"

    def resolve(self, path: str | Path) -> Path:
        p = Path(path)
        return p if p.is_absolute() else PROJECT_ROOT / p

    def ensure_dirs(self) -> None:
        for d in (self.data_dir, self.songs_dir, self.models_dir, self.logs_dir, self.db_path.parent):
            d.mkdir(parents=True, exist_ok=True)


@lru_cache
def get_settings() -> Settings:
    settings = Settings()
    if not settings.data_dir.is_absolute():
        settings.data_dir = PROJECT_ROOT / settings.data_dir
    if settings.db_file is not None and not settings.db_file.is_absolute():
        settings.db_file = PROJECT_ROOT / settings.db_file
    if settings.models_dir_override is not None and not settings.models_dir_override.is_absolute():
        settings.models_dir_override = PROJECT_ROOT / settings.models_dir_override
    settings.ensure_dirs()
    return settings


def details_hint(log_name: str) -> str:
    """Where to find a failure's details, for messages shown to the user. Visitors of the public site can't

    read the server's logs, so they are not pointed at them."""
    if get_settings().public:
        return "If it keeps happening, tell the site owner."
    return f"Details are in data/logs/{log_name}."


@lru_cache
def get_config() -> AppConfig:
    path = get_settings().config_file
    with open(path, encoding="utf-8") as fh:
        raw = yaml.safe_load(fh) or {}
    return AppConfig.model_validate(raw)