/** * api.ts — Sentinel-AI typed API client * * All calls go to the FastAPI backend. Set VITE_API_BASE_URL to override the * default (e.g. when the backend is not on localhost:8000). */ const configuredBase = ( import.meta.env.VITE_API_BASE_URL as string | undefined )?.trim(); // Optional shared-deployment key. Leave unset for the local demo: the backend // only enforces auth when SENTINEL_API_KEY is configured there. const configuredApiKey = ( import.meta.env.VITE_API_KEY as string | undefined )?.trim(); export const API_BASE = ( configuredBase && configuredBase.length > 0 ? configuredBase : "http://localhost:8000" ).replace(/\/+$/, ""); /** Build the URL for a CelebA image served by the backend. */ export function imageUrl(imageId: string | number): string { return `${API_BASE}/api/v1/images/${encodeURIComponent(String(imageId))}`; } // ─── Response shapes (mirroring api/schemas.py) ────────────────────────────── export interface CascadeflowMetrics { latency_ms: number; cost_usd: number; } export interface HealthResponse { status: string; index_ready: boolean; index_vectors: number | null; detector_ready: boolean; embedder_ready: boolean; model: string; } export interface AnalyzeFrameResponse { status: string; // "success" | "no_face_detected" | "no_match_found" faces_detected: number; match_confidence: number | null; matched_attributes: string[]; agent_report: string | null; cascadeflow_metrics: CascadeflowMetrics | null; } export interface SemanticSearchMatch { image_id: string; attributes: string[]; faiss_id: number; } export interface SemanticSearchResponse { status: string; query: string; extracted_attrs: string[]; excluded_attrs: string[]; matches: SemanticSearchMatch[]; cascadeflow_metrics: CascadeflowMetrics | null; } export interface GeneratePersonResponse { status: string; prompt: string; enhanced_prompt: string; image_base64: string; file_path: string | null; width: number | null; height: number | null; error: string | null; cascadeflow_metrics: CascadeflowMetrics; } // ─── Error types ───────────────────────────────────────────────────────────── export class ApiError extends Error { constructor( public readonly kind: "connection" | "timeout" | "http" | "unknown", message: string, public readonly httpStatus?: number, ) { super(message); this.name = "ApiError"; } } // ─── Shared fetch helper ───────────────────────────────────────────────────── function withAuth(init: RequestInit): RequestInit { if (!configuredApiKey) return init; const headers = new Headers(init.headers); headers.set("Authorization", `Bearer ${configuredApiKey}`); return { ...init, headers }; } async function requestJson( path: string, init: RequestInit, timeoutMs: number, timeoutMessage: string, ): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); let response: Response; try { response = await fetch(`${API_BASE}${path}`, { ...withAuth(init), signal: controller.signal, }); } catch (err) { if ( controller.signal.aborted || (err instanceof DOMException && err.name === "AbortError") ) { throw new ApiError("timeout", timeoutMessage); } throw new ApiError( "connection", "Connection refused — is the FastAPI backend running?", ); } finally { // Always clear the timer, including when fetch rejects. clearTimeout(timer); } if (!response.ok) { const text = await response.text().catch(() => ""); throw new ApiError( "http", `HTTP ${response.status}: ${text}`, response.status, ); } return response.json() as Promise; } // ─── health ────────────────────────────────────────────────────────────────── export async function getHealth(): Promise { return requestJson( "/health", { method: "GET" }, 5_000, "Health check timed out.", ); } // ─── analyzeFrame ───────────────────────────────────────────────────────────── export async function analyzeFrame(file: File): Promise { const body = new FormData(); body.append("file", file); return requestJson( "/api/v1/analyze-frame", { method: "POST", body }, 60_000, "Request timed out — the GPU or Gemini API took too long.", ); } // ─── semanticSearch ─────────────────────────────────────────────────────────── export async function semanticSearch( query: string, top_k = 12, ): Promise { return requestJson( "/api/v1/semantic-search", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query, top_k }), }, 30_000, "Request timed out — Gemini attribute extraction took too long.", ); } // ─── generatePerson ─────────────────────────────────────────────────────────── export async function generatePerson( prompt: string, saveToPath?: boolean, ): Promise { return requestJson( "/api/v1/generate-person", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt, save_to_disk: saveToPath ?? false }), }, 60_000, "Request timed out — the image generation API took too long.", ); }