Xander Labide
Claude Opus 4.7 (1M context)
Initial commit β€” Farient DeckCheck
fdfe81a
Raw History Blame Contribute Delete
29.9 kB
"""FastAPI entrypoint for the Farient Brand Review API.
Endpoints (PRD Β§API Requirements):
* ``GET /health`` β†’ liveness probe
* ``POST /api/audits`` β†’ upload, schedule pipeline
* ``GET /api/audits/{job_id}`` β†’ poll status / stage
* ``GET /api/audits/{job_id}/slides`` β†’ extended findings + image URLs
* ``GET /api/audits/{job_id}/slides/{n}/image`` β†’ stream rendered PNG
* ``GET /api/audits/{job_id}/export?fmt=md|json|pdf|pptx`` β†’ downloadable report
The audit identifier is named ``job_id`` everywhere on the wire, matching the
PRD ``:jobId`` URL parameter.
"""
# ruff: noqa: E402
from __future__ import annotations
import asyncio
import json
import logging
import os
import zipfile
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any
# Load apps/api/.env (gitignored) before anything reads OPENAI_API_KEY etc.
# override=False keeps real shell env winning when both are set.
from dotenv import load_dotenv as _load_dotenv
_load_dotenv(Path(__file__).parent / ".env", override=True)
from fastapi import FastAPI, File, HTTPException, Query, Request, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import (
FileResponse,
JSONResponse,
PlainTextResponse,
Response,
StreamingResponse,
)
from schemas.api import (
AuditCreateResponse,
AuditExportJson,
AuditListEntry,
AuditListResponse,
AuditSlidesResponse,
AuditStatusResponse,
FindingExtended,
FindingMeta,
PreflightResponse,
SeverityCounts,
SlideEnvelope,
SlideEnvelopeExtended,
)
from services.event_log import read_events_since
from services.export import to_markdown
from services.export_pdf import render_audit_pdf
from services.export_pptx import annotate_pptx
from services.jobs import JobNotFoundError, JobStore
from services.orchestrator import run_audit_pipeline
from services.preflight import audit_preflight
from services.renderer import warmup as renderer_warmup
logger = logging.getLogger(__name__)
_TERMINAL_STATUSES = {"reviewed", "partial", "failed"}
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
def _parse_origins(raw: str) -> list[str]:
"""Split a comma-separated origin list, trimming whitespace + blanks."""
return [origin.strip() for origin in raw.split(",") if origin.strip()]
def _max_upload_bytes() -> int:
"""Resolve the max upload size in bytes from ``MAX_UPLOAD_MB`` (default 60)."""
raw = os.getenv("MAX_UPLOAD_MB", "60")
try:
mb = int(raw)
except ValueError:
mb = 60
return mb * 1024 * 1024
def _jobs_root() -> Path:
"""Root directory for audit job state. ``AUDIT_JOBS_ROOT`` overrides default."""
return Path(os.getenv("AUDIT_JOBS_ROOT", "/tmp/audits"))
def _auto_worker_enabled() -> bool:
"""Whether this process should run the in-process audit worker."""
return os.getenv("AUDIT_AUTO_WORKER", "1").strip().lower() not in {
"0",
"false",
"no",
"off",
}
# ---------------------------------------------------------------------------
# Application factory
# ---------------------------------------------------------------------------
def create_app() -> FastAPI:
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.audit_queue = asyncio.Queue()
app.state.audit_enqueued = set()
app.state.audit_worker_task = None
app.state.renderer_warmup_task = None
# Track the in-flight audit so DELETE can cancel it mid-pipeline.
app.state.audit_running_job_id = None
app.state.audit_running_task = None
if _auto_worker_enabled():
app.state.audit_worker_task = asyncio.create_task(
_audit_worker(app), name="audit-worker"
)
_recover_pending_jobs(app)
# Pre-warm LibreOffice without blocking API readiness.
app.state.renderer_warmup_task = asyncio.create_task(
asyncio.to_thread(renderer_warmup), name="renderer-warmup"
)
yield
for task_name in ("audit_worker_task", "renderer_warmup_task"):
task = getattr(app.state, task_name, None)
if task is None or task.done():
continue
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
except Exception: # noqa: BLE001
logger.exception("%s shutdown failed", task_name)
app = FastAPI(
title="Farient Brand Review API",
version="0.1.0",
lifespan=lifespan,
)
# `WEB_ORIGINS` (plural) is canonical; fall back to legacy `WEB_ORIGIN`.
raw_origins = (
os.getenv("WEB_ORIGINS")
or os.getenv("WEB_ORIGIN")
or "http://localhost:3000"
)
origins = _parse_origins(raw_origins)
origin_regex = os.getenv("WEB_ORIGIN_REGEX") or None
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_origin_regex=origin_regex,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Inject a JobStore on the app state so tests can swap roots cleanly.
app.state.job_store = JobStore(_jobs_root())
_register_routes(app)
return app
async def _audit_worker(app: FastAPI) -> None:
"""Single in-process queue worker.
Serializing audit execution prevents multiple uploads from stampeding
LibreOffice and OpenAI TPM at the same time. It is still a lightweight
process-local worker; a deployed multi-instance setup should replace this
with an external queue.
"""
queue: asyncio.Queue[str] = app.state.audit_queue
while True:
job_id = await queue.get()
try:
store: JobStore = app.state.job_store
if not store.exists(job_id):
continue
rec = store.read(job_id)
if rec.status in _TERMINAL_STATUSES:
continue
runner_override = getattr(app.state, "agent_runner_override", None)
# Wrap the pipeline call in a Task so DELETE can cancel it.
pipeline_task = asyncio.create_task(
run_audit_pipeline(job_id, store=store, runner=runner_override),
name=f"audit-pipeline-{job_id}",
)
app.state.audit_running_job_id = job_id
app.state.audit_running_task = pipeline_task
try:
await pipeline_task
except asyncio.CancelledError:
# Pipeline was cancelled (most likely by DELETE). The job dir is
# already gone; just swallow and move on to the next queue item.
logger.info("audit pipeline cancelled for job %s", job_id)
continue
except asyncio.CancelledError:
# Worker itself is being shut down β€” propagate.
raise
except Exception as exc: # noqa: BLE001
logger.exception("audit worker failed for job %s", job_id)
try:
store = app.state.job_store
if store.exists(job_id):
store.append_error(job_id, f"worker error: {exc}")
store.set_status(job_id, "failed")
except Exception: # noqa: BLE001
logger.exception("failed to persist worker failure for %s", job_id)
finally:
app.state.audit_running_job_id = None
app.state.audit_running_task = None
app.state.audit_enqueued.discard(job_id)
queue.task_done()
def _enqueue_audit(app: FastAPI, job_id: str) -> bool:
"""Queue a job once. Returns False when the in-process worker is disabled."""
queue = getattr(app.state, "audit_queue", None)
enqueued = getattr(app.state, "audit_enqueued", None)
if queue is None or enqueued is None:
return False
if job_id in enqueued:
return True
enqueued.add(job_id)
queue.put_nowait(job_id)
return True
def _recover_pending_jobs(app: FastAPI) -> None:
"""Re-enqueue jobs left non-terminal by reloads/crashes."""
store: JobStore = app.state.job_store
for rec in reversed(store.list_jobs()):
if rec.status not in _TERMINAL_STATUSES:
_enqueue_audit(app, rec.job_id)
# ---------------------------------------------------------------------------
# Route registration
# ---------------------------------------------------------------------------
def _register_routes(app: FastAPI) -> None: # noqa: C901 β€” single readable surface
@app.get("/health")
def health() -> dict[str, bool]:
return {"ok": True}
@app.get("/health/preflight", response_model=PreflightResponse)
def preflight(request: Request) -> PreflightResponse:
store: JobStore = request.app.state.job_store
return audit_preflight(store.root)
# ---- GET /api/audits --------------------------------------------------
@app.get(
"/api/audits",
response_model=AuditListResponse,
)
def list_audits(request: Request) -> AuditListResponse:
store: JobStore = request.app.state.job_store
records = store.list_jobs()
entries = [
AuditListEntry(
job_id=rec.job_id,
file_name=rec.file_name,
status=rec.status,
slide_count=rec.slide_count,
summary=rec.summary,
created_at=rec.created_at,
completed_at=rec.completed_at,
errors_count=len(rec.errors),
)
for rec in records
]
return AuditListResponse(jobs=entries)
# ---- POST /api/audits -------------------------------------------------
@app.post(
"/api/audits",
response_model=AuditCreateResponse,
status_code=200,
)
async def create_audit(
request: Request, file: UploadFile = File(...)
) -> AuditCreateResponse:
store: JobStore = request.app.state.job_store
max_bytes = _max_upload_bytes()
# 1. Extension check.
filename = file.filename or "deck.pptx"
if not filename.lower().endswith(".pptx"):
raise HTTPException(
status_code=400,
detail="Only .pptx files are accepted (got {!r}).".format(filename),
)
# 2. Content-Length pre-check (header may lie β€” streaming counter below).
cl_header = request.headers.get("content-length")
if cl_header:
try:
if int(cl_header) > max_bytes:
raise HTTPException(
status_code=413,
detail=(
f"File too large: Content-Length exceeds "
f"MAX_UPLOAD_MB={max_bytes // (1024 * 1024)}."
),
)
except ValueError:
pass # malformed header β€” fall through to streaming check
# 3. Stream into a temp file in the (yet-to-be-created) job dir.
record = store.create(file_name=filename)
source_path = store.source_path(record.job_id)
bytes_written = 0
try:
with source_path.open("wb") as out:
while True:
chunk = await file.read(1024 * 1024)
if not chunk:
break
bytes_written += len(chunk)
if bytes_written > max_bytes:
out.close()
source_path.unlink(missing_ok=True)
store.append_error(
record.job_id,
f"Upload exceeded MAX_UPLOAD_MB={max_bytes // (1024 * 1024)}",
)
store.set_status(record.job_id, "failed")
raise HTTPException(
status_code=413,
detail=(
f"File too large: streamed bytes exceed "
f"MAX_UPLOAD_MB={max_bytes // (1024 * 1024)}."
),
)
out.write(chunk)
finally:
await file.close()
# 4. Magic-bytes check (a .pptx is a zip archive).
if not zipfile.is_zipfile(source_path):
source_path.unlink(missing_ok=True)
store.append_error(
record.job_id, "Uploaded file is not a valid PPTX (zip)."
)
store.set_status(record.job_id, "failed")
raise HTTPException(
status_code=400,
detail="Uploaded file is not a valid PPTX (zip magic bytes missing).",
)
# 5. Schedule the pipeline; do NOT block the response on it. Prefer
# the single worker queue to avoid upload bursts stampeding the LLM.
queued = _enqueue_audit(request.app, record.job_id)
if not queued:
runner_override = getattr(request.app.state, "agent_runner_override", None)
asyncio.create_task(
run_audit_pipeline(
record.job_id, store=store, runner=runner_override
)
)
return AuditCreateResponse(job_id=record.job_id, status="queued")
# ---- GET /api/audits/{job_id} ----------------------------------------
@app.get(
"/api/audits/{job_id}",
response_model=AuditStatusResponse,
)
def get_audit(request: Request, job_id: str) -> AuditStatusResponse:
store: JobStore = request.app.state.job_store
try:
rec = store.read(job_id)
except JobNotFoundError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
return rec.to_status_response()
# ---- DELETE /api/audits/{job_id} -------------------------------------
# Remove the entire on-disk job directory. Idempotent β€” returns 204 even
# if the job was already gone, so the UI can do an optimistic delete and
# not need to handle a 404 specially. Returns 404 only if the job_id has
# never existed in this store.
@app.delete("/api/audits/{job_id}", status_code=204)
def delete_audit(request: Request, job_id: str) -> Response:
store: JobStore = request.app.state.job_store
if not store.exists(job_id):
raise HTTPException(status_code=404, detail=f"No job at {job_id}")
# Cancel the in-flight pipeline if this is the currently-running job.
# Worker catches CancelledError and moves on to the next queued item.
running_id = getattr(request.app.state, "audit_running_job_id", None)
running_task = getattr(request.app.state, "audit_running_task", None)
if running_id == job_id and running_task is not None and not running_task.done():
running_task.cancel()
# Also remove from the enqueued set so the worker skips it cleanly if
# it gets popped before the cancel propagates (existence check in
# _audit_worker handles the race too β€” both are belt-and-suspenders).
enqueued = getattr(request.app.state, "audit_enqueued", None)
if enqueued is not None:
enqueued.discard(job_id)
store.delete(job_id)
return Response(status_code=204)
# ---- GET /api/audits/{job_id}/events ---------------------------------
# Server-Sent Events stream of status snapshots. Sends an initial event
# immediately on connection, then re-emits whenever the on-disk JSON
# changes. Closes when the job reaches a terminal state.
@app.get("/api/audits/{job_id}/events")
async def audit_events(request: Request, job_id: str) -> StreamingResponse:
store: JobStore = request.app.state.job_store
# Verify the job exists before opening the stream so misses still
# return 404 rather than an empty event-stream.
if not store.exists(job_id):
raise HTTPException(status_code=404, detail=f"No job at {job_id}")
async def event_generator():
poll_interval = 0.1 # 100ms β€” invisible to client; pushes on change
heartbeat_every = 15.0 # seconds
last_payload: str | None = None
last_heartbeat = asyncio.get_event_loop().time()
# Byte offset into events.jsonl. On first read we replay the
# whole file (offset 0) so a client connecting mid-audit catches
# up on every slide that has already finished.
event_offset: int = 0
job_dir = store.job_dir(job_id)
try:
while True:
# Client disconnect detection.
if await request.is_disconnected():
break
try:
rec = store.read(job_id)
except JobNotFoundError:
# Job vanished mid-stream β€” emit an error event and stop.
yield "event: error\ndata: {\"detail\":\"job not found\"}\n\n"
return
# Drain new per-slide events (also runs the initial replay).
new_events, event_offset = read_events_since(
job_dir, event_offset
)
for ev in new_events:
ev_type = ev.get("event") or "message"
ev_data = ev.get("data", {})
try:
data_str = json.dumps(ev_data, ensure_ascii=False)
except (TypeError, ValueError):
continue
# SSE: event-name lines must precede the data line.
yield f"event: {ev_type}\ndata: {data_str}\n\n"
payload = rec.to_status_response().model_dump_json()
if payload != last_payload:
yield f"data: {payload}\n\n"
last_payload = payload
# Heartbeat to keep proxies / browsers from killing the
# connection during long idle stretches.
now = asyncio.get_event_loop().time()
if now - last_heartbeat >= heartbeat_every:
yield ": keepalive\n\n"
last_heartbeat = now
# If terminal, drain any final events one more time then
# send the 'done' event and close.
if rec.status in {"reviewed", "partial", "failed"}:
new_events, event_offset = read_events_since(
job_dir, event_offset
)
for ev in new_events:
ev_type = ev.get("event") or "message"
ev_data = ev.get("data", {})
try:
data_str = json.dumps(ev_data, ensure_ascii=False)
except (TypeError, ValueError):
continue
yield f"event: {ev_type}\ndata: {data_str}\n\n"
yield f"event: done\ndata: {payload}\n\n"
return
await asyncio.sleep(poll_interval)
except asyncio.CancelledError:
# Connection cancelled β€” propagate cleanly.
raise
except Exception: # noqa: BLE001
logger.exception("SSE generator failed for job %s", job_id)
# Best-effort error event; if the connection is broken it
# will just be dropped.
try:
yield "event: error\ndata: {\"detail\":\"stream error\"}\n\n"
except Exception: # noqa: BLE001
pass
headers = {
"Cache-Control": "no-cache, no-transform",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
}
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers=headers,
)
# ---- GET /api/audits/{job_id}/slides ---------------------------------
@app.get(
"/api/audits/{job_id}/slides",
response_model=AuditSlidesResponse,
)
def get_audit_slides(
request: Request, job_id: str
) -> AuditSlidesResponse:
store: JobStore = request.app.state.job_store
try:
rec = store.read(job_id)
except JobNotFoundError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
export = _read_export_or_empty(store, job_id, rec.file_name, rec.slide_count)
# Convert strict slides β†’ extended slides; tag a default finding_meta
# for any finding that came in without one (the runner already tags
# source/must_flag β€” but the strict export wipes that, so we re-hydrate
# from the raw findings.json).
extended_slides: list[SlideEnvelopeExtended] = []
raw_extended = _read_extended_slides(store, job_id)
for env in export.slides:
ext_findings: list[FindingExtended] = []
raw_for_slide = raw_extended.get(env.slide_number, [])
for idx, f in enumerate(env.findings):
meta = (
raw_for_slide[idx]
if idx < len(raw_for_slide)
else FindingMeta(source="merged", must_flag=False)
)
ext_findings.append(
FindingExtended(**f.model_dump(), finding_meta=meta)
)
extended_slides.append(
SlideEnvelopeExtended(
slide_number=env.slide_number,
image_url=_image_url_if_rendered(store, job_id, env.slide_number),
findings=ext_findings,
)
)
return AuditSlidesResponse(
job_id=job_id,
file_name=rec.file_name,
slide_count=export.slide_count,
summary=export.summary,
slides=extended_slides,
)
# ---- GET /api/audits/{job_id}/slides/{n}/image -----------------------
@app.get("/api/audits/{job_id}/slides/{n}/image")
def get_slide_image(
request: Request, job_id: str, n: int
) -> FileResponse:
store: JobStore = request.app.state.job_store
if not store.exists(job_id):
raise HTTPException(status_code=404, detail="job not found")
path = store.slide_image_path(job_id, n)
if not path.exists():
raise HTTPException(
status_code=404, detail=f"slide {n} not rendered"
)
return FileResponse(
path,
media_type="image/png",
headers={"Cache-Control": "public, max-age=86400"},
)
# ---- GET /api/audits/{job_id}/export?fmt=md|json|pdf|pptx ------------
@app.get("/api/audits/{job_id}/export")
def get_audit_export(
request: Request,
job_id: str,
fmt: str = Query(default="json", pattern="^(md|json|pdf|pptx)$"),
) -> Response:
store: JobStore = request.app.state.job_store
try:
rec = store.read(job_id)
except JobNotFoundError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
export = _read_export_or_empty(store, job_id, rec.file_name, rec.slide_count)
base = Path(rec.file_name).stem or "audit"
if fmt == "json":
payload = export.model_dump()
return JSONResponse(
content=payload,
headers={
"Content-Disposition": (
f'attachment; filename="{base}-audit-{job_id}.json"'
)
},
)
if fmt == "pdf":
try:
pdf_bytes = render_audit_pdf(export)
except Exception as exc: # noqa: BLE001
logger.exception("pdf export failed for job %s", job_id)
raise HTTPException(
status_code=500,
detail=f"PDF render failed: {exc}",
) from exc
return Response(
content=pdf_bytes,
media_type="application/pdf",
headers={
"Content-Disposition": (
f'attachment; filename="{base}-audit-{job_id}.pdf"'
)
},
)
if fmt == "pptx":
source = store.source_path(job_id)
if not source.exists():
# Old jobs (pre-source-preservation) cannot be annotated.
raise HTTPException(
status_code=501,
detail=(
"Annotated PPTX export is unavailable for this audit: "
"the original deck was not preserved on the server. "
"Re-upload the deck to enable annotated export."
),
)
try:
pptx_bytes = annotate_pptx(source, export)
except FileNotFoundError as exc:
raise HTTPException(
status_code=501,
detail=str(exc),
) from exc
except Exception as exc: # noqa: BLE001
logger.exception("pptx export failed for job %s", job_id)
raise HTTPException(
status_code=500,
detail=f"PPTX annotation failed: {exc}",
) from exc
# Build a safe filename derived from the original deck name.
original = Path(rec.file_name).name or f"deck-{job_id}.pptx"
if not original.lower().endswith(".pptx"):
original = f"{original}.pptx"
out_name = f"annotated-{original}"
return Response(
content=pptx_bytes,
media_type=(
"application/vnd.openxmlformats-"
"officedocument.presentationml.presentation"
),
headers={
"Content-Disposition": (
f'attachment; filename="{out_name}"'
)
},
)
# fmt == "md"
body = to_markdown(export)
return PlainTextResponse(
content=body,
media_type="text/markdown",
headers={
"Content-Disposition": (
f'attachment; filename="{base}-audit-{job_id}.md"'
)
},
)
# ---------------------------------------------------------------------------
# Internal helpers (used by routes)
# ---------------------------------------------------------------------------
def _read_export_or_empty(
store: JobStore, job_id: str, file_name: str, slide_count: int
) -> AuditExportJson:
"""Read findings.json into ``AuditExportJson``; empty result if not yet written."""
path = store.findings_path(job_id)
if not path.exists():
return AuditExportJson(
job_id=job_id,
file_name=file_name,
slide_count=slide_count,
summary=SeverityCounts(),
slides=[
SlideEnvelope(slide_number=n, findings=[])
for n in range(1, slide_count + 1)
],
)
try:
data: Any = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return AuditExportJson(
job_id=job_id,
file_name=file_name,
slide_count=slide_count,
summary=SeverityCounts(),
slides=[],
)
return AuditExportJson.model_validate(data)
def _read_extended_slides(
store: JobStore, job_id: str
) -> dict[int, list[FindingMeta]]:
"""Load per-slide finding_meta lists from a sidecar file (if present).
Currently the orchestrator only persists the strict shape β€” the
``/slides`` endpoint synthesises a default ``FindingMeta(source='merged',
must_flag=False)`` per finding. This helper exists so a future
enhancement can persist the extended shape without changing the route.
"""
sidecar = store.job_dir(job_id) / "findings_extended.json"
if not sidecar.exists():
return {}
try:
data = json.loads(sidecar.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return {}
out: dict[int, list[FindingMeta]] = {}
for slide in data.get("slides", []):
n = int(slide["slide_number"])
metas: list[FindingMeta] = []
for f in slide.get("findings", []):
meta = f.get("finding_meta")
if meta is None:
continue
metas.append(FindingMeta.model_validate(meta))
out[n] = metas
return out
def _image_url_if_rendered(
store: JobStore, job_id: str, slide_number: int
) -> str | None:
if store.slide_image_path(job_id, slide_number).exists():
return f"/api/audits/{job_id}/slides/{slide_number}/image"
return None
# ---------------------------------------------------------------------------
# Module-level app instance (uvicorn entrypoint)
# ---------------------------------------------------------------------------
app = create_app()