Files
Nat20-Notes/backend/app/main.py
KansaiGaijin 6c760b5e2e
Some checks failed
Build and Push / build (push) Has been cancelled
Preload audio as Blob for instant seeking; generate Opus playback file; delete original upload after extraction
- Download full audio as Blob on mount so seeking is instant (no network range-requests)
- Remove readyState guard from playAt() that was silently blocking seek attempts
- Add disabled/ready state to SessionReel for reliable click-to-seek
- Generate 48kbps Opus playback file during extraction (~65MB for 3hrs vs 1.5GB lossless)
- Serve Opus first in audio endpoint, then original upload, then extracted WAV
- Delete original upload after successful transcription to reclaim storage
- Reorder extract_audio checks so retry works without the original file
- Fix Back links on Speakers and Notes pages to go to home
2026-07-30 10:38:10 +12:00

118 lines
3.5 KiB
Python

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")
# Priority: Opus playback > original upload > extracted WAV.
# The Opus file is tiny (~65 MB for 3 hours) so the frontend's Blob
# download completes in seconds on any modern connection.
candidates = []
if row["audio_path"]:
opus = Path(row["audio_path"]).with_suffix(".opus")
if opus.exists():
candidates.append(opus)
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}