Files
stemengine_old/backend/main.py
T

135 lines
4.2 KiB
Python
Executable File

"""
StemEngine — FastAPI application entry point.
Mounts all API routers and serves the built React frontend as static files.
"""
import json
import logging
import logging.config
import warnings
from contextlib import asynccontextmanager
from pathlib import Path
# Suppress FutureWarnings from third-party libraries that use deprecated
# PyTorch APIs (torch.cuda.amp.autocast, torch.backends.cuda.sdp_kernel).
# These are upstream issues in rotary_embedding_torch and similar packages;
# the warnings are harmless and clutter the logs.
warnings.filterwarnings(
"ignore",
message=r".*torch\.cuda\.amp\.autocast.*",
category=FutureWarning,
)
warnings.filterwarnings(
"ignore",
message=r".*torch\.backends\.cuda\.sdp_kernel.*",
category=FutureWarning,
)
from fastapi import FastAPI
# Load logging config from the discrete YAML file next to this package.
# Edit backend/logging.yaml to change log levels without touching code.
_log_cfg = Path(__file__).parent / "logging.yaml"
if _log_cfg.exists():
import yaml
with open(_log_cfg) as _f:
logging.config.dictConfig(yaml.safe_load(_f))
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from .routers import separate, transcribe, abc_convert, pipeline, jobs, lrc, subsonic, projects, models, lyric_transcribe, system, settings
from .config import SUBSONIC_CONFIG_PATH
from .app_settings import settings as app_settings
from .db import init_db
_log = logging.getLogger(__name__)
def _purge_legacy_subsonic_config() -> None:
"""Delete subsonic.json if it is in the legacy plaintext format.
Encrypted configs (_enc=True) are kept. Any file that lacks the _enc
flag stored the password in cleartext and must be removed so it is never
served again.
"""
if not SUBSONIC_CONFIG_PATH.exists():
return
try:
stored = json.loads(SUBSONIC_CONFIG_PATH.read_text())
except Exception:
stored = {}
if not stored.get('_enc'):
SUBSONIC_CONFIG_PATH.unlink()
_log.warning(
"Deleted legacy plaintext Subsonic config at %s — "
"re-enter credentials via the Settings UI.",
SUBSONIC_CONFIG_PATH,
)
@asynccontextmanager
async def lifespan(app):
init_db(_log)
_purge_legacy_subsonic_config()
for issue in app_settings.validate_startup():
_log.warning("Startup check: %s", issue)
yield
def _include_routers(app: FastAPI) -> None:
app.include_router(jobs.router)
app.include_router(separate.router)
app.include_router(transcribe.router)
app.include_router(abc_convert.router)
app.include_router(pipeline.router)
app.include_router(lrc.router)
app.include_router(subsonic.router)
app.include_router(projects.router)
app.include_router(models.router)
app.include_router(lyric_transcribe.router)
app.include_router(system.router)
app.include_router(settings.router)
def _mount_static(app: FastAPI) -> None:
# Serve built React frontend from /app/backend/static
# Mount order matters: API routes always win over static assets.
_static_dir = Path(__file__).parent / "static"
_assets_dir = _static_dir / "assets"
if not _static_dir.exists():
return
if _assets_dir.exists():
app.mount("/assets", StaticFiles(directory=str(_assets_dir)), name="assets")
@app.get("/", include_in_schema=False)
async def root():
return FileResponse(str(_static_dir / "index.html"))
@app.get("/{full_path:path}", include_in_schema=False)
async def spa_fallback(full_path: str):
"""Serve index.html for all non-API routes to support SPA client-side routing."""
candidate = _static_dir / full_path
if candidate.is_file():
return FileResponse(str(candidate))
return FileResponse(str(_static_dir / "index.html"))
def create_app() -> FastAPI:
app = FastAPI(title="StemEngine", version="1.0.0", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=app_settings.cors_origins_resolved,
allow_methods=["*"],
allow_headers=["*"],
)
_include_routers(app)
_mount_static(app)
return app
app = create_app()