215 lines
7.7 KiB
Python
215 lines
7.7 KiB
Python
"""
|
|
User settings endpoint — persists API keys and preferences server-side.
|
|
|
|
Sensitive values (hf_token) are stored in settings.json on the server and
|
|
never returned to the frontend in plain text. The frontend receives a
|
|
boolean `hf_token_set` flag instead so the UI can show a "configured" state
|
|
without ever exposing the token value.
|
|
|
|
Non-sensitive preferences (whisper_model, sep_power, etc.) are stored here
|
|
so they sync across devices without relying on per-browser localStorage.
|
|
"""
|
|
import json
|
|
import os
|
|
from typing import Any, Optional
|
|
|
|
from fastapi import APIRouter, HTTPException
|
|
from pydantic import BaseModel, field_validator
|
|
|
|
from ..config import SETTINGS_PATH
|
|
from ..services.auto_presets_catalog import (
|
|
load_builtin_auto_presets,
|
|
merge_auto_presets,
|
|
normalize_auto_presets,
|
|
)
|
|
|
|
router = APIRouter(prefix="/api/settings", tags=["settings"])
|
|
|
|
# Keys that are redacted from GET responses (store-only, never echoed back)
|
|
_REDACTED = {"hf_token", "pixabay_api_key"}
|
|
|
|
# Valid enumerated values — used for validation
|
|
_VALID_SEP_POWER = {"standard", "high", "max", "ultra"}
|
|
_VALID_WHISPER_MODELS = {
|
|
"tiny", "tiny.en",
|
|
"base", "base.en",
|
|
"small", "small.en",
|
|
"medium", "medium.en",
|
|
"large", "large-v1", "large-v2", "large-v3",
|
|
"large-v3-turbo", "turbo",
|
|
}
|
|
_VALID_KARAOKE_SOURCE_MODE = {"projects", "sek-folder"}
|
|
_VALID_SINGUI_PROCESS_MODE = {"auto", "separate_only", "pipeline", "preset"}
|
|
|
|
# Default values for all known preference keys
|
|
_DEFAULTS: dict[str, Any] = {
|
|
"whisper_model": "medium",
|
|
"sep_power": "eco",
|
|
"whisper_word_ts": True,
|
|
"whisper_condition_prev": False,
|
|
"whisper_phoneme_align": False,
|
|
"auto_steps": [],
|
|
"auto_model": "htdemucs",
|
|
"auto_format": "mp3",
|
|
"auto_presets": [],
|
|
"karaoke_source_mode": "sek-folder",
|
|
"karaoke_sek_folder": "",
|
|
"singui_process_mode": "auto",
|
|
"singui_process_preset": "",
|
|
"pixabay_api_key": "",
|
|
"pixabay_cache_enabled": True,
|
|
"pixabay_min_clip_duration": 15,
|
|
"pixabay_max_clip_duration": 20,
|
|
}
|
|
|
|
|
|
def _load() -> dict:
|
|
"""Read settings.json, merging with defaults."""
|
|
if not SETTINGS_PATH.exists():
|
|
return dict(_DEFAULTS)
|
|
try:
|
|
stored = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
|
|
return {**_DEFAULTS, **stored}
|
|
except Exception:
|
|
return dict(_DEFAULTS)
|
|
|
|
|
|
def _save(data: dict) -> None:
|
|
SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
SETTINGS_PATH.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
|
|
|
|
def get_hf_token() -> Optional[str]:
|
|
"""Return the HF token from settings (or env var as fallback)."""
|
|
stored = _load()
|
|
token = stored.get("hf_token") or os.environ.get("HF_TOKEN") or None
|
|
return token or None
|
|
|
|
|
|
@router.get("")
|
|
def get_settings():
|
|
"""Return all non-sensitive settings. Redacted keys return a boolean flag."""
|
|
data = _load()
|
|
user_auto_presets = normalize_auto_presets(data.get("auto_presets"))
|
|
builtin_auto_presets = load_builtin_auto_presets()
|
|
effective_auto_presets = merge_auto_presets(builtin_auto_presets, user_auto_presets)
|
|
|
|
result = {}
|
|
for k, v in data.items():
|
|
if k in _REDACTED:
|
|
result[f"{k}_set"] = bool(v)
|
|
else:
|
|
result[k] = v
|
|
# Always include redacted flags even if key is absent
|
|
for k in _REDACTED:
|
|
if f"{k}_set" not in result:
|
|
# Check env var fallback
|
|
env_val = os.environ.get(k.upper())
|
|
result[f"{k}_set"] = bool(env_val)
|
|
|
|
# Preserve user-editable presets separately while exposing built-in and
|
|
# effective merged presets for UI/runtime consumption.
|
|
result["auto_presets"] = user_auto_presets
|
|
result["auto_presets_user"] = user_auto_presets
|
|
result["auto_presets_builtin"] = builtin_auto_presets
|
|
result["auto_presets_effective"] = effective_auto_presets
|
|
return result
|
|
|
|
|
|
class SettingsPatch(BaseModel):
|
|
hf_token: Optional[str] = None
|
|
whisper_model: Optional[str] = None
|
|
sep_power: Optional[str] = None
|
|
whisper_word_ts: Optional[bool] = None
|
|
whisper_condition_prev: Optional[bool] = None
|
|
whisper_phoneme_align: Optional[bool] = None
|
|
auto_steps: Optional[list] = None
|
|
auto_model: Optional[str] = None
|
|
auto_format: Optional[str] = None
|
|
auto_presets: Optional[list] = None
|
|
karaoke_source_mode: Optional[str] = None
|
|
karaoke_sek_folder: Optional[str] = None
|
|
singui_process_mode: Optional[str] = None
|
|
singui_process_preset: Optional[str] = None
|
|
pixabay_api_key: Optional[str] = None
|
|
pixabay_cache_enabled: Optional[bool] = None
|
|
pixabay_min_clip_duration: Optional[float] = None
|
|
pixabay_max_clip_duration: Optional[float] = None
|
|
|
|
@field_validator("sep_power")
|
|
@classmethod
|
|
def _validate_sep_power(cls, v: Optional[str]) -> Optional[str]:
|
|
if v is not None and v not in _VALID_SEP_POWER:
|
|
raise ValueError(
|
|
f"Unknown sep_power '{v}'. Valid values: {sorted(_VALID_SEP_POWER)}"
|
|
)
|
|
return v
|
|
|
|
@field_validator("whisper_model")
|
|
@classmethod
|
|
def _validate_whisper_model(cls, v: Optional[str]) -> Optional[str]:
|
|
if v is not None and v not in _VALID_WHISPER_MODELS:
|
|
raise ValueError(
|
|
f"Unknown whisper_model '{v}'. Valid values: {sorted(_VALID_WHISPER_MODELS)}"
|
|
)
|
|
return v
|
|
|
|
@field_validator("karaoke_source_mode")
|
|
@classmethod
|
|
def _validate_karaoke_source_mode(cls, v: Optional[str]) -> Optional[str]:
|
|
if v is not None and v not in _VALID_KARAOKE_SOURCE_MODE:
|
|
raise ValueError(
|
|
f"Unknown karaoke_source_mode '{v}'. Valid values: {sorted(_VALID_KARAOKE_SOURCE_MODE)}"
|
|
)
|
|
return v
|
|
|
|
@field_validator("singui_process_mode")
|
|
@classmethod
|
|
def _validate_singui_process_mode(cls, v: Optional[str]) -> Optional[str]:
|
|
if v is not None and v not in _VALID_SINGUI_PROCESS_MODE:
|
|
raise ValueError(
|
|
f"Unknown singui_process_mode '{v}'. Valid values: {sorted(_VALID_SINGUI_PROCESS_MODE)}"
|
|
)
|
|
return v
|
|
|
|
@field_validator("pixabay_min_clip_duration", "pixabay_max_clip_duration")
|
|
@classmethod
|
|
def _validate_pixabay_clip_duration(cls, v: Optional[float]) -> Optional[float]:
|
|
if v is not None and (v < 1 or v > 300):
|
|
raise ValueError("Pixabay clip duration must be between 1 and 300 seconds.")
|
|
return v
|
|
|
|
|
|
@router.patch("")
|
|
def patch_settings(body: SettingsPatch):
|
|
"""Update one or more settings. Only provided (non-None) fields are changed."""
|
|
data = _load()
|
|
update = body.model_dump(exclude_none=True)
|
|
data.update(update)
|
|
|
|
min_clip = data.get("pixabay_min_clip_duration")
|
|
max_clip = data.get("pixabay_max_clip_duration")
|
|
if isinstance(min_clip, (int, float)) and isinstance(max_clip, (int, float)) and max_clip < min_clip:
|
|
data["pixabay_max_clip_duration"] = min_clip
|
|
|
|
_save(data)
|
|
return get_settings()
|
|
|
|
|
|
@router.delete("/hf-token")
|
|
def delete_hf_token():
|
|
"""Remove a stored HF token (reverts to env-var fallback or unset)."""
|
|
data = _load()
|
|
data.pop("hf_token", None)
|
|
_save(data)
|
|
return {"hf_token_set": bool(os.environ.get("HF_TOKEN"))}
|
|
|
|
|
|
@router.delete("/pixabay-key")
|
|
def delete_pixabay_key():
|
|
"""Remove the stored Pixabay API key (reverts to PIXABAY_API_KEY env var or unset)."""
|
|
data = _load()
|
|
data.pop("pixabay_api_key", None)
|
|
_save(data)
|
|
return {"pixabay_api_key_set": bool(os.environ.get("PIXABAY_API_KEY"))}
|