StillWorking commited on
Commit
187abfc
Β·
verified Β·
1 Parent(s): 9693607

Upload frontend/src/lib/api.ts with huggingface_hub

Browse files
Files changed (1) hide show
  1. frontend/src/lib/api.ts +206 -0
frontend/src/lib/api.ts ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * api.ts β€” Sentinel-AI typed API client
3
+ *
4
+ * All calls go to the FastAPI backend. Set VITE_API_BASE_URL to override the
5
+ * default (e.g. when the backend is not on localhost:8000).
6
+ */
7
+
8
+ const configuredBase = (
9
+ import.meta.env.VITE_API_BASE_URL as string | undefined
10
+ )?.trim();
11
+
12
+ // Optional shared-deployment key. Leave unset for the local demo: the backend
13
+ // only enforces auth when SENTINEL_API_KEY is configured there.
14
+ const configuredApiKey = (
15
+ import.meta.env.VITE_API_KEY as string | undefined
16
+ )?.trim();
17
+
18
+ export const API_BASE = (
19
+ configuredBase && configuredBase.length > 0
20
+ ? configuredBase
21
+ : "http://localhost:8000"
22
+ ).replace(/\/+$/, "");
23
+
24
+ /** Build the URL for a CelebA image served by the backend. */
25
+ export function imageUrl(imageId: string | number): string {
26
+ return `${API_BASE}/api/v1/images/${encodeURIComponent(String(imageId))}`;
27
+ }
28
+
29
+ // ─── Response shapes (mirroring api/schemas.py) ──────────────────────────────
30
+
31
+ export interface CascadeflowMetrics {
32
+ latency_ms: number;
33
+ cost_usd: number;
34
+ }
35
+
36
+ export interface HealthResponse {
37
+ status: string;
38
+ index_ready: boolean;
39
+ index_vectors: number | null;
40
+ detector_ready: boolean;
41
+ embedder_ready: boolean;
42
+ model: string;
43
+ }
44
+
45
+ export interface AnalyzeFrameResponse {
46
+ status: string; // "success" | "no_face_detected" | "no_match_found"
47
+ faces_detected: number;
48
+ match_confidence: number | null;
49
+ matched_attributes: string[];
50
+ agent_report: string | null;
51
+ cascadeflow_metrics: CascadeflowMetrics | null;
52
+ }
53
+
54
+ export interface SemanticSearchMatch {
55
+ image_id: string;
56
+ attributes: string[];
57
+ faiss_id: number;
58
+ }
59
+
60
+ export interface SemanticSearchResponse {
61
+ status: string;
62
+ query: string;
63
+ extracted_attrs: string[];
64
+ excluded_attrs: string[];
65
+ matches: SemanticSearchMatch[];
66
+ cascadeflow_metrics: CascadeflowMetrics | null;
67
+ }
68
+
69
+ export interface GeneratePersonResponse {
70
+ status: string;
71
+ prompt: string;
72
+ enhanced_prompt: string;
73
+ image_base64: string;
74
+ file_path: string | null;
75
+ width: number | null;
76
+ height: number | null;
77
+ error: string | null;
78
+ cascadeflow_metrics: CascadeflowMetrics;
79
+ }
80
+
81
+ // ─── Error types ─────────────────────────────────────────────────────────────
82
+
83
+ export class ApiError extends Error {
84
+ constructor(
85
+ public readonly kind: "connection" | "timeout" | "http" | "unknown",
86
+ message: string,
87
+ public readonly httpStatus?: number,
88
+ ) {
89
+ super(message);
90
+ this.name = "ApiError";
91
+ }
92
+ }
93
+
94
+ // ─── Shared fetch helper ─────────────────────────────────────────────────────
95
+
96
+ function withAuth(init: RequestInit): RequestInit {
97
+ if (!configuredApiKey) return init;
98
+
99
+ const headers = new Headers(init.headers);
100
+ headers.set("Authorization", `Bearer ${configuredApiKey}`);
101
+ return { ...init, headers };
102
+ }
103
+
104
+ async function requestJson<T>(
105
+ path: string,
106
+ init: RequestInit,
107
+ timeoutMs: number,
108
+ timeoutMessage: string,
109
+ ): Promise<T> {
110
+ const controller = new AbortController();
111
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
112
+
113
+ let response: Response;
114
+ try {
115
+ response = await fetch(`${API_BASE}${path}`, {
116
+ ...withAuth(init),
117
+ signal: controller.signal,
118
+ });
119
+ } catch (err) {
120
+ if (
121
+ controller.signal.aborted ||
122
+ (err instanceof DOMException && err.name === "AbortError")
123
+ ) {
124
+ throw new ApiError("timeout", timeoutMessage);
125
+ }
126
+ throw new ApiError(
127
+ "connection",
128
+ "Connection refused β€” is the FastAPI backend running?",
129
+ );
130
+ } finally {
131
+ // Always clear the timer, including when fetch rejects.
132
+ clearTimeout(timer);
133
+ }
134
+
135
+ if (!response.ok) {
136
+ const text = await response.text().catch(() => "");
137
+ throw new ApiError(
138
+ "http",
139
+ `HTTP ${response.status}: ${text}`,
140
+ response.status,
141
+ );
142
+ }
143
+
144
+ return response.json() as Promise<T>;
145
+ }
146
+
147
+ // ─── health ──────────────────────────────────────────────────────────────────
148
+
149
+ export async function getHealth(): Promise<HealthResponse> {
150
+ return requestJson<HealthResponse>(
151
+ "/health",
152
+ { method: "GET" },
153
+ 5_000,
154
+ "Health check timed out.",
155
+ );
156
+ }
157
+
158
+ // ─── analyzeFrame ─────────────────────────────────────────────────────────────
159
+
160
+ export async function analyzeFrame(file: File): Promise<AnalyzeFrameResponse> {
161
+ const body = new FormData();
162
+ body.append("file", file);
163
+
164
+ return requestJson<AnalyzeFrameResponse>(
165
+ "/api/v1/analyze-frame",
166
+ { method: "POST", body },
167
+ 60_000,
168
+ "Request timed out β€” the GPU or Gemini API took too long.",
169
+ );
170
+ }
171
+
172
+ // ─── semanticSearch ───────────────────────────────────────────────────────────
173
+
174
+ export async function semanticSearch(
175
+ query: string,
176
+ top_k = 12,
177
+ ): Promise<SemanticSearchResponse> {
178
+ return requestJson<SemanticSearchResponse>(
179
+ "/api/v1/semantic-search",
180
+ {
181
+ method: "POST",
182
+ headers: { "Content-Type": "application/json" },
183
+ body: JSON.stringify({ query, top_k }),
184
+ },
185
+ 30_000,
186
+ "Request timed out β€” Gemini attribute extraction took too long.",
187
+ );
188
+ }
189
+
190
+ // ─── generatePerson ───────────────────────────────────────────────────────────
191
+
192
+ export async function generatePerson(
193
+ prompt: string,
194
+ saveToPath?: boolean,
195
+ ): Promise<GeneratePersonResponse> {
196
+ return requestJson<GeneratePersonResponse>(
197
+ "/api/v1/generate-person",
198
+ {
199
+ method: "POST",
200
+ headers: { "Content-Type": "application/json" },
201
+ body: JSON.stringify({ prompt, save_to_disk: saveToPath ?? false }),
202
+ },
203
+ 60_000,
204
+ "Request timed out β€” the image generation API took too long.",
205
+ );
206
+ }