Files
stemengine_old/backend/main.py
T
2026-07-09 10:58:09 +09:00

236 lines
8.4 KiB
Python
Executable File

"""
StemEngine — FastAPI application entry point.
Mounts API routers and optionally serves legacy static WebUI when explicitly enabled.
"""
import json
import logging
import logging.config
import os
import warnings
from contextlib import asynccontextmanager
from pathlib import Path
from urllib.parse import urlparse
# 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.middleware.gzip import GZipMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from . import job_manager as jm
from .routers import separate, transcribe, abc_convert, pipeline, jobs, lrc, subsonic, projects, models, lyric_transcribe, system, settings, karaoke_sek, pixabay, room, local_library, gloss, sloppak_converter, midi_editor
from .config import SUBSONIC_CONFIG_PATH
from .app_settings import settings as app_settings
from .db import init_db
from .services.local_library_service import seed_music_library_path_from_env
from .services.gloss_service import initialize_gloss_runtime
from .services import sloppak_converter_service
_log = logging.getLogger(__name__)
def _build_frame_src_csp() -> str:
"""Build a narrow CSP policy for iframe sources.
The policy is intentionally scoped to `frame-src` to avoid changing other
fetch directives during this rollout.
"""
sources = ["'self'"]
raw = (os.environ.get("MUON_IFRAME_URL") or "").strip()
if raw:
parsed = urlparse(raw)
if parsed.scheme in {"http", "https"} and parsed.netloc:
origin = f"{parsed.scheme}://{parsed.netloc}"
if origin not in sources:
sources.append(origin)
return f"frame-src {' '.join(sources)}"
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)
try:
result = jm.prune_old_non_project_jobs(force=True)
if result.get("deleted", 0) > 0:
_log.info(
"Startup retention prune deleted %d old non-project jobs",
result["deleted"],
)
except Exception:
_log.exception("Startup retention prune failed")
_purge_legacy_subsonic_config()
if seed_music_library_path_from_env():
_log.info(
"Startup: seeded music_library_path from MUSIC_LIBRARY_PATH env var into settings.json"
)
try:
initialize_gloss_runtime()
except Exception:
_log.exception("Startup gloss runtime initialization failed")
try:
hydrate = sloppak_converter_service.ensure_queue_hydrated()
if hydrate.get("resubmitted", 0) or hydrate.get("requeued_running", 0):
_log.info(
"Startup sloppak queue hydrate: resubmitted=%s requeued_running=%s",
hydrate.get("resubmitted", 0),
hydrate.get("requeued_running", 0),
)
except Exception:
_log.exception("Startup sloppak queue hydration failed")
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(gloss.router)
app.include_router(models.router)
app.include_router(lyric_transcribe.router)
app.include_router(system.router)
app.include_router(settings.router)
app.include_router(local_library.router)
app.include_router(karaoke_sek.router)
app.include_router(pixabay.router)
app.include_router(room.router)
app.include_router(sloppak_converter.router)
app.include_router(midi_editor.router)
def _mount_static(app: FastAPI) -> None:
# Legacy behavior (backend-served frontend) is opt-in only.
# Default runtime is API-only with separate WebUI/SingUI services.
if os.environ.get("BACKEND_SERVE_LEGACY_WEBUI", "false").lower() != "true":
return
# 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)
frame_src_csp = _build_frame_src_csp()
app.add_middleware(
CORSMiddleware,
# Open CORS mode: accept requests from any origin.
allow_origins=["*"],
allow_origin_regex=None,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=6)
@app.middleware("http")
async def _allow_private_network_access(request, call_next):
"""Add Access-Control-Allow-Private-Network for Chromium PNA preflights.
Browsers may block requests from secure/public origins to private/Tailscale
addresses unless this response header is present when requested.
"""
response = await call_next(request)
if request.headers.get("access-control-request-private-network", "").lower() == "true":
response.headers["access-control-allow-private-network"] = "true"
return response
@app.middleware("http")
async def _static_cache_control(request, call_next):
response = await call_next(request)
if request.method not in {"GET", "HEAD"}:
return response
path = request.url.path
if response.status_code == 200 and path.startswith('/assets/'):
response.headers.setdefault('Cache-Control', 'public, max-age=31536000, immutable')
return response
if path in {'/sw.js', '/manifest.webmanifest'}:
response.headers.setdefault('Cache-Control', 'no-cache')
return response
content_type = response.headers.get('content-type', '')
if 'text/html' in content_type:
response.headers.setdefault('Cache-Control', 'no-cache')
response.headers.setdefault('Content-Security-Policy', frame_src_csp)
return response
_include_routers(app)
_mount_static(app)
return app
app = create_app()