File size: 6,329 Bytes
187abfc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | /**
* 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.",
);
}
|