Download frontend/src/lib/api.ts from StillWorking/sentinel-face-recognition: direct link, hf CLI and curl.
- Browser
- Download file 6.33 kB
-
https://huggingface.co/StillWorking/sentinel-face-recognition/resolve/main/frontend/src/lib/api.ts
- Command line
-
hf download hf://StillWorking/sentinel-face-recognition/frontend/src/lib/api.ts
-
curl -L -o api.ts https://huggingface.co/StillWorking/sentinel-face-recognition/resolve/main/frontend/src/lib/api.ts
6.33 kB
| /** | |
| * 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<T>( | |
| path: string, | |
| init: RequestInit, | |
| timeoutMs: number, | |
| timeoutMessage: string, | |
| ): Promise<T> { | |
| 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<T>; | |
| } | |
| // βββ health ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| export async function getHealth(): Promise<HealthResponse> { | |
| return requestJson<HealthResponse>( | |
| "/health", | |
| { method: "GET" }, | |
| 5_000, | |
| "Health check timed out.", | |
| ); | |
| } | |
| // βββ analyzeFrame βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| export async function analyzeFrame(file: File): Promise<AnalyzeFrameResponse> { | |
| const body = new FormData(); | |
| body.append("file", file); | |
| return requestJson<AnalyzeFrameResponse>( | |
| "/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<SemanticSearchResponse> { | |
| return requestJson<SemanticSearchResponse>( | |
| "/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<GeneratePersonResponse> { | |
| return requestJson<GeneratePersonResponse>( | |
| "/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.", | |
| ); | |
| } | |