from pathlib import Path from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse, JSONResponse from fastapi import HTTPException from . import database as db, config from .logging_config import setup_logging, get_logger from .errors import PipelineError from .routers import settings as settings_router from .routers import sessions as sessions_router from .routers import speakers as speakers_router from .routers import notes as notes_router from .routers import jobs as jobs_router from .routers import models as models_router from .routers import diagnostics as diagnostics_router from .routers import files as files_router from .routers import campaigns as campaigns_router setup_logging() log = get_logger(__name__) app = FastAPI(title="Nat20 Notes") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) @app.exception_handler(PipelineError) async def pipeline_error_handler(request: Request, exc: PipelineError): log.error("Pipeline error in %s: %s", exc.stage, exc.message, exc_info=exc.cause or exc) return JSONResponse(status_code=502, content={"stage": exc.stage, "message": exc.message}) @app.exception_handler(Exception) async def unhandled_error_handler(request: Request, exc: Exception): log.exception("Unhandled error on %s %s", request.method, request.url.path) return JSONResponse(status_code=500, content={"stage": "unknown", "message": f"Unexpected error: {exc}"}) @app.on_event("startup") def on_startup(): db.init_db() log.info("Database initialized at %s", config.DB_PATH) app.include_router(settings_router.router) app.include_router(sessions_router.router) app.include_router(speakers_router.router) app.include_router(notes_router.router) app.include_router(jobs_router.router) app.include_router(models_router.router) app.include_router(diagnostics_router.router) app.include_router(files_router.router) app.include_router(campaigns_router.router) MEDIA_TYPES = { ".mp3": "audio/mpeg", ".mp4": "audio/mp4", ".m4a": "audio/mp4", ".m4b": "audio/mp4", ".ogg": "audio/ogg", ".opus": "audio/ogg", ".wav": "audio/wav", ".flac": "audio/flac", ".aac": "audio/aac", ".webm": "audio/webm", } AUDIO_EXTS = frozenset(MEDIA_TYPES.keys()) @app.get("/api/sessions/{session_id}/audio") def get_audio(session_id: str): row = db.get_conn().execute( "SELECT video_path, audio_path FROM sessions WHERE id = ?", (session_id,) ).fetchone() if not row: raise HTTPException(404, "Session not found") # Prefer the original uploaded file — it's a compressed format the browser # can seek in efficiently. Fall back to the extracted WAV. candidates = [] if row["video_path"]: p = Path(row["video_path"]) if p.exists(): candidates.append(p) if row["audio_path"]: p = Path(row["audio_path"]) if p.exists(): candidates.append(p) if not candidates: raise HTTPException(404, "No audio file available for this session") chosen = candidates[0] ext = chosen.suffix.lower() media_type = MEDIA_TYPES.get(ext, "application/octet-stream") return FileResponse(chosen, media_type=media_type) @app.get("/api/health") def health(): return {"ok": True}