cmvr-visual/backend/app/config.py

122 lines
5.8 KiB
Python

from dataclasses import dataclass
import os
from pathlib import Path
from sqlalchemy.engine import URL, make_url
def boolean(value):
return str(value).lower() in {"1", "true", "yes", "on"}
@dataclass
class Settings:
mode: str = "production"
database_url: str | None = None
mysql_host: str = "192.168.28.10"
mysql_port: int = 3306
mysql_database: str = "cmvr-visual"
mysql_user: str = ""
mysql_password: str = ""
workspace_root: Path = Path("/workspace")
asset_root: Path | None = None
job_work_root: Path | None = None
state_root: Path | None = None
admin_username: str = ""
admin_password: str = ""
admin_display_name: str = "管理员"
cookie_secure: bool = True
session_hours: int = 12
public_access: bool = False
max_interactive_gpu_jobs: int = 8
max_creation_commands_per_minute: int = 6
max_owner_asset_bytes: int = 100 * 1024**3
max_data_bytes: int = 2 * 1024**4
min_free_bytes: int = 50 * 1024**3
max_owner_jobs: int = 500
max_global_jobs: int = 2000
max_owner_runs: int = 100
max_global_runs: int = 1000
max_owner_batches: int = 20
max_global_batches: int = 200
run_coordinator: bool = True
poll_seconds: float = 1.0
event_heartbeat_seconds: float = 15.0
max_upload_bytes: int = 512 * 1024 * 1024
max_output_bytes: int = 2 * 1024 * 1024 * 1024
request_timeout_seconds: float = 30.0
inference_base_url: str = "http://llmuser-workspace:18190"
inference_api_key: str = ""
inference_api_key_file: Path | None = Path("/workspace/projects/llm-services/config/api_key")
gpu_status_path: Path | None = Path("/run/llm-gpu-policy/status.json")
gpu_scheduler_path: Path | None = Path("/workspace/projects/llm-services/state/gpu-scheduler.json")
qwen_base_url: str = "http://192.168.28.10:14081/v1"
qwen_model: str = "Qwen/Qwen3.8-27B-FP8"
qwen_api_key: str = ""
ffmpeg_bin: str = "ffmpeg"
ffprobe_bin: str = "ffprobe"
tts_base_url: str = ""
tts_model: str = "kokoro-82m"
tts_api_key: str = ""
tts_voices: tuple[str, ...] = ("zf_xiaobei", "zm_yunxi")
def __post_init__(self):
if self.mode not in {"production", "preview", "test"}:
raise ValueError("CMVR_MODE must be production, preview or test")
self.workspace_root = Path(self.workspace_root).resolve()
for field, leaf in (("asset_root", "assets"), ("job_work_root", "jobs"), ("state_root", "state")):
value = Path(getattr(self, field) or self.workspace_root / "cmvr-visual" / leaf).resolve()
if not value.is_relative_to(self.workspace_root):
raise ValueError(field + " must stay inside WORKSPACE_ROOT")
setattr(self, field, value)
for field in ("inference_api_key_file", "gpu_status_path", "gpu_scheduler_path"):
if getattr(self, field):
setattr(self, field, Path(getattr(self, field)))
if self.database_url:
url = make_url(self.database_url)
if url.drivername.startswith("sqlite"):
if self.mode not in {"preview", "test"} or url.drivername != "sqlite+aiosqlite":
raise ValueError("SQLite requires explicit test/preview mode and the aiosqlite driver")
elif url.drivername != "mysql+aiomysql":
raise ValueError("Production database must use mysql+aiomysql")
elif self.mode != "production":
raise ValueError("Test/preview mode requires an explicit DATABASE_URL")
elif not self.mysql_user or not self.mysql_password:
raise ValueError("Production MySQL credentials must be configured")
@property
def sqlalchemy_url(self):
if self.database_url:
return make_url(self.database_url)
return URL.create("mysql+aiomysql", username=self.mysql_user, password=self.mysql_password,
host=self.mysql_host, port=self.mysql_port, database=self.mysql_database,
query={"charset": "utf8mb4"})
@classmethod
def from_env(cls):
env = os.environ
values = {}
strings = ("database_url", "mysql_host", "mysql_database", "mysql_user", "mysql_password",
"admin_username", "admin_password", "admin_display_name", "inference_base_url",
"inference_api_key", "qwen_base_url", "qwen_model", "qwen_api_key", "ffmpeg_bin", "ffprobe_bin",
"tts_base_url", "tts_model", "tts_api_key")
for field in strings:
if field.upper() in env:
values[field] = env[field.upper()]
for field in ("workspace_root", "asset_root", "job_work_root", "state_root", "inference_api_key_file",
"gpu_status_path", "gpu_scheduler_path"):
if field.upper() in env:
values[field] = Path(env[field.upper()]) if env[field.upper()] else None
for field in ("mysql_port", "session_hours", "max_upload_bytes", "max_output_bytes", "max_owner_jobs", "max_global_jobs", "max_interactive_gpu_jobs", "max_creation_commands_per_minute", "max_owner_asset_bytes", "max_data_bytes", "min_free_bytes", "max_owner_runs", "max_global_runs", "max_owner_batches", "max_global_batches"):
if field.upper() in env:
values[field] = int(env[field.upper()])
for field in ("poll_seconds", "event_heartbeat_seconds", "request_timeout_seconds"):
if field.upper() in env:
values[field] = float(env[field.upper()])
for field in ("cookie_secure", "run_coordinator", "public_access"):
if field.upper() in env:
values[field] = boolean(env[field.upper()])
values["mode"] = env.get("CMVR_MODE", "production")
if "TTS_VOICES" in env:
values["tts_voices"] = tuple(v.strip() for v in env["TTS_VOICES"].split(",") if v.strip())
return cls(**values)