56 lines
1.7 KiB
Python
56 lines
1.7 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
from typing import Dict, Optional
|
|
|
|
from ..config import ALL_MODEL_IDS, INSTRUMENT_MODEL_KEYS
|
|
|
|
|
|
def parse_instrument_models_json(raw: Optional[str]) -> Optional[Dict[str, str]]:
|
|
"""
|
|
Parse and validate optional `instrument_models` JSON form payload.
|
|
|
|
Expected shape:
|
|
{"vocals": "model_id", "drums": "model_id", ...}
|
|
|
|
Returns:
|
|
Normalized dict with lowercase canonical stem keys, or None.
|
|
|
|
Raises:
|
|
ValueError for invalid JSON, invalid keys, invalid values, or unknown models.
|
|
"""
|
|
if not raw:
|
|
return None
|
|
|
|
try:
|
|
payload = json.loads(raw)
|
|
except json.JSONDecodeError as exc:
|
|
raise ValueError("Invalid instrument_models JSON") from exc
|
|
|
|
if not isinstance(payload, dict):
|
|
raise ValueError("instrument_models must be a JSON object")
|
|
|
|
normalized: Dict[str, str] = {}
|
|
|
|
for raw_key, raw_model in payload.items():
|
|
if not isinstance(raw_key, str):
|
|
raise ValueError("instrument_models keys must be strings")
|
|
|
|
key = raw_key.strip().lower().replace(" ", "_")
|
|
if key not in INSTRUMENT_MODEL_KEYS:
|
|
raise ValueError(
|
|
f"Unsupported instrument key '{raw_key}'. "
|
|
f"Allowed: {', '.join(INSTRUMENT_MODEL_KEYS)}"
|
|
)
|
|
|
|
if not isinstance(raw_model, str) or not raw_model.strip():
|
|
raise ValueError(f"instrument_models['{key}'] must be a non-empty model id string")
|
|
|
|
model_id = raw_model.strip()
|
|
if model_id not in ALL_MODEL_IDS:
|
|
raise ValueError(f"Unknown model for '{key}': {model_id}")
|
|
|
|
normalized[key] = model_id
|
|
|
|
return normalized or None
|