Spaces:
Runtime error
Runtime error
File size: 9,331 Bytes
f84688d a874986 0f97254 a874986 0f97254 a874986 cbd23a5 a874986 cbd23a5 a874986 10ac650 f84688d 10ac650 4e5e939 10ac650 f84688d 10ac650 f84688d 10ac650 f84688d 10ac650 f84688d 4e5e939 10ac650 f84688d 10ac650 f84688d 10ac650 f84688d 10ac650 f84688d 10ac650 4e5e939 10ac650 f84688d 10ac650 4e5e939 10ac650 4e5e939 10ac650 cbd23a5 10ac650 cbd23a5 10ac650 | 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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | const API_BASE = window.location.hostname === 'localhost' ? 'http://localhost:8000' : '';
export interface ClassificationResult {
label: string;
confidence: number;
}
export interface PreprocessingInfo {
type: 'dicom' | 'image';
pipeline: 'full' | 'basic';
steps_applied: string[];
processed_image_base64?: string;
metadata: {
original_size?: [number, number];
processed_size?: [number, number];
pixel_spacing?: number;
fan_size?: [number, number];
original_pixel_spacing?: [number, number];
};
}
export interface ClassificationResponse {
success: boolean;
predictions: ClassificationResult[];
top_prediction: ClassificationResult | null;
preprocessing: PreprocessingInfo;
}
export interface GestationalAgeResponse {
success: boolean;
gestational_age: {
weeks: number;
days: number;
total_days: number;
};
// Biometry - only one will be present based on view
head_circumference?: {
p2_5: number;
p50: number;
p97_5: number;
};
abdominal_circumference?: {
p2_5: number;
p50: number;
p97_5: number;
};
femur_length?: {
p2_5: number;
p50: number;
p97_5: number;
};
preprocessing: PreprocessingInfo;
}
export async function classifyImage(file: File, topK: number = 5): Promise<ClassificationResponse> {
const formData = new FormData();
formData.append('file', file);
const response = await fetch(`${API_BASE}/api/v1/classify/?top_k=${topK}`, {
method: 'POST',
body: formData,
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Classification failed');
}
return response.json();
}
export async function estimateGestationalAge(file: File, pixelSize: number, view?: string): Promise<GestationalAgeResponse> {
const formData = new FormData();
formData.append('file', file);
let url = `${API_BASE}/api/v1/gestational-age/?pixel_size=${pixelSize}`;
if (view) {
url += `&view=${encodeURIComponent(view)}`;
}
const response = await fetch(url, {
method: 'POST',
body: formData,
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Estimation failed');
}
return response.json();
}
export function isDicomFile(filename: string): boolean {
const lower = filename.toLowerCase();
return lower.endsWith('.dcm') || lower.endsWith('.dicom');
}
export function getFileType(filename: string): 'dicom' | 'image' {
return isDicomFile(filename) ? 'dicom' : 'image';
}
export interface PreviewResponse {
success: boolean;
preview: string;
type: 'dicom' | 'image';
mime_type?: string;
}
export async function getFilePreview(file: File): Promise<PreviewResponse> {
const formData = new FormData();
formData.append('file', file);
const response = await fetch(`${API_BASE}/api/v1/classify/preview`, {
method: 'POST',
body: formData,
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Preview failed');
}
return response.json();
}
export async function checkHealth(): Promise<boolean> {
try {
const response = await fetch(`${API_BASE}/health`, { method: 'GET' });
return response.ok;
} catch {
return false;
}
}
// ==================== Feedback API ====================
export interface PredictionDetail {
label: string;
probability: number;
}
export interface FeedbackEntry {
id: string;
session_id: string;
timestamp: string;
filename: string;
file_type: string;
patient_id: string | null;
image_hash: string | null;
predicted_label: string;
predicted_confidence: number;
all_predictions: PredictionDetail[];
is_correct: boolean | null;
correct_label: string | null;
reviewer_notes: string | null;
// GA-specific fields
feedback_type?: string;
estimated_ga_weeks?: number;
estimated_ga_days?: number;
view_type?: string;
biometry_value?: number;
percentile?: number;
correct_ga_weeks?: number;
}
export interface SessionInfo {
session_id: string;
created_at: string;
image_count: number;
feedback_count: number;
correct_count: number;
incorrect_count: number;
}
export interface FeedbackStats {
total_feedback: number;
correct_count: number;
incorrect_count: number;
not_sure_count: number;
accuracy: number;
by_label: Record<string, { total: number; correct: number; incorrect: number; not_sure: number }>;
}
export interface FeedbackCreate {
session_id: string;
filename: string;
file_type: string;
predicted_label: string;
predicted_confidence: number;
all_predictions: PredictionDetail[];
is_correct: boolean | null;
correct_label?: string;
reviewer_notes?: string;
patient_id?: string;
image_hash?: string;
preprocessed_image_base64?: string;
// GA-specific fields
feedback_type?: string; // "classification" or "gestational_age"
estimated_ga_weeks?: number;
estimated_ga_days?: number;
view_type?: string;
biometry_value?: number;
percentile?: number;
correct_ga_weeks?: number;
}
// Create a new session
export async function createSession(): Promise<SessionInfo> {
const response = await fetch(`${API_BASE}/api/v1/feedback/session`, {
method: 'POST',
});
if (!response.ok) {
throw new Error('Failed to create session');
}
return response.json();
}
// Get session info
export async function getSession(sessionId: string): Promise<SessionInfo> {
const response = await fetch(`${API_BASE}/api/v1/feedback/session/${sessionId}`);
if (!response.ok) {
throw new Error('Session not found');
}
return response.json();
}
// Record image analyzed
export async function recordImageAnalyzed(sessionId: string): Promise<void> {
await fetch(`${API_BASE}/api/v1/feedback/session/${sessionId}/image-analyzed`, {
method: 'POST',
});
}
// Submit feedback
export async function submitFeedback(feedback: FeedbackCreate): Promise<FeedbackEntry> {
const response = await fetch(`${API_BASE}/api/v1/feedback/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(feedback),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail || 'Failed to submit feedback');
}
return response.json();
}
// Get all feedback
export async function getFeedback(sessionId?: string): Promise<FeedbackEntry[]> {
const url = sessionId
? `${API_BASE}/api/v1/feedback/?session_id=${sessionId}`
: `${API_BASE}/api/v1/feedback/`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('Failed to get feedback');
}
return response.json();
}
// Get feedback statistics
export async function getFeedbackStats(sessionId?: string): Promise<FeedbackStats> {
const url = sessionId
? `${API_BASE}/api/v1/feedback/statistics?session_id=${sessionId}`
: `${API_BASE}/api/v1/feedback/statistics`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('Failed to get statistics');
}
return response.json();
}
// Export feedback as CSV with save dialog
export async function exportFeedbackCSV(sessionId?: string): Promise<void> {
const url = sessionId
? `${API_BASE}/api/v1/feedback/export/csv?session_id=${sessionId}`
: `${API_BASE}/api/v1/feedback/export/csv`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('No feedback data to export');
}
const blob = await response.blob();
const defaultFilename = `fetalclip_feedback_${new Date().toISOString().slice(0, 10)}.csv`;
// Try to use File System Access API for save dialog (Chromium browsers)
if ('showSaveFilePicker' in window) {
try {
const handle = await (window as unknown as { showSaveFilePicker: (options: object) => Promise<FileSystemFileHandle> }).showSaveFilePicker({
suggestedName: defaultFilename,
types: [
{
description: 'CSV Files',
accept: { 'text/csv': ['.csv'] },
},
],
});
const writable = await handle.createWritable();
await writable.write(blob);
await writable.close();
return;
} catch (err) {
// User cancelled the save dialog or API not fully supported
if ((err as Error).name === 'AbortError') {
return; // User cancelled, don't fallback
}
// Fallback to traditional download for other errors
}
}
// Fallback: Traditional download for unsupported browsers
const downloadUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = downloadUrl;
a.download = defaultFilename;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(downloadUrl);
}
// Delete feedback entry
export async function deleteFeedback(feedbackId: string): Promise<void> {
const response = await fetch(`${API_BASE}/api/v1/feedback/${feedbackId}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error('Failed to delete feedback');
}
}
// List of all fetal view labels (must match keys in prompt_fetal_view.json)
export const FETAL_VIEW_LABELS = [
"abdomen",
"brain",
"femur",
"heart",
"kidney",
"lips_nose",
"profile_patient",
"spine",
"cervix",
"cord",
"diaphragm",
"feet",
"orbit"
];
|