Files
photoanalyzer/photo_pipeline/api/routes/safety.py
domverse 457dd5bd90 US02-06: Deliver Workflow, Safety, Library, Analysis, and Stats Views
Ports the safety review and the Photo Analyzer Library/Analyze/Stats
experiences onto the shared API + service layer, and adds the Workflow
home, enforcing the pipeline gates and the one-mutating-job policy.

Backend
- migration 0005 + models: safety_reviews (append-only, latest row is the
  current decision) and analysis_results (donor photos schema re-keyed to
  asset_id).
- SafetyService: persist scores/decisions, review queue with filters, and
  the EXIF safety checkpoint (mutually-exclusive sfw/nsfw keyword written,
  read back, current_sha256 refreshed) that upload eligibility depends on.
- AnalysisService: the privacy gate — the vision provider is called ONLY for
  canonical, confirmed-SFW assets; nsfw/undecided are recorded skipped without
  a request. Provider is an injected adapter (real OpenAI-compatible Gemini
  call extracted from photo_analyzer.analyze_image; a fake in tests).
- LibraryService: Library search + Stats read model ported from webapp/query.py
  (LIKE search in place of FTS5; facets, top tags, years, albums, people).
- WorkflowService + GET /api/v1/workflow: per-stage readiness derived from the
  source tables — counts, blockers, last-run, action, and an active_job that
  drives read-only-during-jobs. Safety scoring and analysis run as durable jobs
  under the library_write lock via new domain handlers, so a second mutating
  job is refused.
- routes: workflow, safety (queue/counts/decisions/jobs), analysis
  (counts/results/jobs), library (assets/facets/stats).

Frontend
- five views (frontend/js/views.js) on the US02-05 shell: Workflow stepper
  (status text+icon, not colour alone; actions disabled with a reason while a
  job runs), Safety review (filter tabs, decide, persists across reload),
  Library (search + cards), Analyze (counts + live job log via the SSE
  adapter), Stats. Shared DOM helpers extracted to dom.js; Workflow is the home
  route.

Tests
- integration: provider-call privacy (nsfw never reaches the provider),
  sfw→nsfw flip drops analysis eligibility, decision persistence, one-mutating-
  job rejection, workflow counts, and the exiftool safety-keyword write/verify.
- e2e: Workflow cards, actions disabled+explained during a job, safety
  decide-persists-across-reload, Library search, Stats, Analyze counts.
- traceability map updated for US02-05 and US02-06.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-06 16:52:01 +02:00

61 lines
2.0 KiB
Python

"""Safety review, decisions, and scoring-job API.
Decisions are synchronous commands (persist + EXIF checkpoint). Scoring is a durable
job under the ``library_write`` lock, so only one mutating job runs at a time.
"""
from __future__ import annotations
from fastapi import APIRouter, Query, Request
from fastapi.responses import JSONResponse
from photo_pipeline.jobs.domain_handlers import LIBRARY_WRITE_LOCK, SAFETY_SCORE
from photo_pipeline.schemas import SafetyDecisionRequest
from photo_pipeline.services.jobs import JobBlocked, JobService
from photo_pipeline.services.safety import SafetyError, SafetyService
router = APIRouter(tags=["safety"])
def _service(request: Request) -> SafetyService:
return SafetyService(request.app.state.session_factory)
def _error(status: int, code: str, message: str) -> JSONResponse:
return JSONResponse(status_code=status, content={"error": {"code": code, "message": message}})
@router.get("/safety/queue")
def review_queue(
request: Request,
state: str = "",
limit: int = Query(100, ge=1, le=500),
offset: int = Query(0, ge=0),
) -> dict:
return _service(request).review_queue(state=state, limit=limit, offset=offset)
@router.get("/safety/counts")
def counts(request: Request) -> dict:
return _service(request).counts()
@router.post("/safety/decisions")
def decide(body: SafetyDecisionRequest, request: Request):
try:
return _service(request).decide(body.asset_id, body.decision)
except SafetyError as error:
return _error(404, "not_found", str(error))
@router.post("/safety/jobs")
def enqueue_scoring(request: Request):
ids = _service(request).scorable_asset_ids()
if not ids:
return _error(409, "nothing_to_score", "no eligible assets to score")
jobs = JobService(request.app.state.session_factory)
try:
return jobs.enqueue(SAFETY_SCORE, lock=LIBRARY_WRITE_LOCK, items=ids)
except JobBlocked as error:
return _error(409, error.code, str(error))