Shengyi Zhou commited on
Commit
a70ddee
·
1 Parent(s): 1093add

feat: connect web demo to SAMI backend

Browse files
Files changed (8) hide show
  1. README.md +24 -10
  2. app.js +224 -107
  3. index.html +15 -20
  4. requirements-dev.txt +2 -0
  5. requirements.txt +3 -0
  6. server.py +505 -2
  7. style.css +3 -2
  8. tests/test_server.py +198 -0
README.md CHANGED
@@ -6,30 +6,33 @@ colorTo: indigo
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
- short_description: Browser-based prototype for 3D medical image interaction
10
  ---
11
 
12
  # SAMI Web Demo
13
 
14
- A Docker-hosted browser prototype demonstrating a lightweight 3D medical image workflow without 3D Slicer or an inference backend.
 
 
15
 
16
  ## Features
17
 
18
- - Loads the included brain MRI example by default.
19
- - Loads local 3D `.nrrd` volumes.
20
  - Displays axial, coronal, and sagittal slices.
21
- - Supports positive and negative point prompts.
22
- - Generates a simple local mask immediately after each point.
23
- - Keeps all image processing inside the browser.
 
24
 
25
- The generated mask is an intensity-based demonstration. It does not call the SAMI inference backend and is not intended for medical use.
26
 
27
  ## Run locally
28
 
29
  Install the server dependencies and start FastAPI:
30
 
31
  ```bash
32
- pip install -r requirements.txt
 
33
  uvicorn server:app --host 127.0.0.1 --port 7860
34
  ```
35
 
@@ -39,11 +42,22 @@ Alternatively, run the Docker image:
39
 
40
  ```bash
41
  docker build -t sami-web-demo .
42
- docker run --rm -p 7860:7860 sami-web-demo
43
  ```
44
 
45
  A modern browser with `DecompressionStream` support is required for gzip-compressed NRRD files.
46
 
 
 
 
 
 
 
 
 
 
 
 
47
  ## Example data
48
 
49
  The files in `examples/` come from [3D Slicer Sample Data](https://www.slicer.org/wiki/SampleData):
 
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
+ short_description: Browser demo for SAMI 3D medical image segmentation
10
  ---
11
 
12
  # SAMI Web Demo
13
 
14
+ A Docker-hosted browser demo that securely connects two fixed test cases to the
15
+ SAMI inference backend. The backend token stays inside the FastAPI container and
16
+ is never sent to the browser.
17
 
18
  ## Features
19
 
20
+ - Provides two included test volumes; arbitrary uploads are intentionally disabled.
 
21
  - Displays axial, coronal, and sagittal slices.
22
+ - Supports positive and negative Point prompts.
23
+ - Renders the packed segmentation mask returned by ITK-DW-backend.
24
+ - Clears model interactions without re-uploading the selected volume.
25
+ - Limits each browser to 10 prompt requests per rolling minute.
26
 
27
+ This public demonstration is not intended for medical use.
28
 
29
  ## Run locally
30
 
31
  Install the server dependencies and start FastAPI:
32
 
33
  ```bash
34
+ pip install -r requirements-dev.txt
35
+ $env:DemoSecret = "your-rotated-backend-token"
36
  uvicorn server:app --host 127.0.0.1 --port 7860
37
  ```
38
 
 
42
 
43
  ```bash
44
  docker build -t sami-web-demo .
45
+ docker run --rm -p 7860:7860 -e DemoSecret="your-rotated-backend-token" sami-web-demo
46
  ```
47
 
48
  A modern browser with `DecompressionStream` support is required for gzip-compressed NRRD files.
49
 
50
+ The backend URL defaults to
51
+ `https://harrybangbang-itk-dw-backend.hf.space` and can be overridden with
52
+ `ITK_BACKEND_URL`. On Hugging Face, configure `DemoSecret` as a Space secret,
53
+ not as a Docker build argument or repository variable.
54
+
55
+ Run the server tests without contacting the live inference backend:
56
+
57
+ ```bash
58
+ pytest -q
59
+ ```
60
+
61
  ## Example data
62
 
63
  The files in `examples/` come from [3D Slicer Sample Data](https://www.slicer.org/wiki/SampleData):
app.js CHANGED
@@ -17,6 +17,8 @@ const state = {
17
  coronal: 48,
18
  sagittal: 48,
19
  },
 
 
20
  polarity: "positive",
21
  prompts: [],
22
  promptsVisible: true,
@@ -52,7 +54,6 @@ const backendMessageEl = document.getElementById("backend-message");
52
  const togglePromptsButton = document.getElementById("toggle-prompts");
53
  const toggleMaskButton = document.getElementById("toggle-mask");
54
  const clearAllButton = document.getElementById("clear-all");
55
- const volumeFileInput = document.getElementById("volume-file");
56
  const loadExampleBrainButton = document.getElementById("load-example-brain");
57
  const loadExamplePanoramixButton = document.getElementById("load-example-panoramix");
58
 
@@ -60,8 +61,10 @@ init();
60
 
61
  function init() {
62
  bindUI();
63
- setBackendStatus("Local demo");
64
- loadExampleVolume(EXAMPLE_VOLUMES.brain);
 
 
65
  }
66
 
67
  function bindUI() {
@@ -103,66 +106,98 @@ function bindUI() {
103
  }
104
 
105
  if (clearAllButton) {
106
- clearAllButton.addEventListener("click", () => {
107
- state.prompts = [];
108
- state.mask = new Uint8Array(totalVoxelCount());
109
- renderPromptLog();
110
- updateSegSummary();
111
- drawAll();
112
- setBackendMessage("Prompts and mask cleared.");
113
- });
114
  }
115
 
116
  if (loadExampleBrainButton) {
117
  loadExampleBrainButton.addEventListener("click", () => {
118
- loadExampleVolume(EXAMPLE_VOLUMES.brain);
119
  });
120
  }
121
 
122
  if (loadExamplePanoramixButton) {
123
  loadExamplePanoramixButton.addEventListener("click", () => {
124
- loadExampleVolume(EXAMPLE_VOLUMES.panoramix);
125
  });
126
  }
127
 
128
- if (volumeFileInput) {
129
- volumeFileInput.addEventListener("change", handleVolumeUpload);
130
- }
 
 
131
  }
132
 
133
  function bindCanvas(viewName, canvas) {
134
- canvas.addEventListener("mousedown", (event) => {
135
  onPointerDown(viewName, canvas, event);
136
  });
137
  }
138
 
139
- async function loadExampleVolume(example) {
140
- if (!example) {
 
141
  return;
142
  }
143
 
 
144
  try {
145
- setBusy(true, `Loading ${example.label}...`);
146
- const response = await fetch(example.path);
147
- await ensureOk(response, example.label);
148
- const bytes = new Uint8Array(await response.arrayBuffer());
149
- const parsed = await parseNrrdBytes(bytes);
 
 
 
 
 
 
 
 
 
150
 
151
  setVolume({
152
  name: example.label,
153
  data: normalizeToUint8(parsed.data),
154
  dims: parsed.sizes,
155
  });
156
- setBackendMessage(`${example.label} loaded from the examples folder.`);
 
 
 
157
  } catch (error) {
158
  console.error(error);
159
- alert(`Failed to load example volume: ${error.message}`);
160
- setBackendMessage(`Failed to load ${example?.label ?? "example volume"}.`);
161
  } finally {
162
  setBusy(false);
163
  }
164
  }
165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  function setVolume({ name, data, dims }) {
167
  state.volume = data;
168
  state.dims = dims;
@@ -203,52 +238,88 @@ function setVolume({ name, data, dims }) {
203
  drawAll();
204
  }
205
 
206
- async function handleVolumeUpload(event) {
207
- const file = event.target.files?.[0];
208
- if (!file) {
209
  return;
210
  }
211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  try {
213
- setBusy(true, `Loading ${file.name}...`);
214
- const parsed = await parseNrrdFile(file);
215
- setVolume({
216
- name: file.name,
217
- data: normalizeToUint8(parsed.data),
218
- dims: parsed.sizes,
 
 
 
 
219
  });
220
- setBackendMessage(`Loaded ${file.name}. Ready for mock or live segmentation.`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  } catch (error) {
222
  console.error(error);
223
- alert(`Failed to load NRRD: ${error.message}`);
224
- setBackendMessage(`Failed to load ${file.name}.`);
 
 
 
225
  } finally {
226
- event.target.value = "";
227
  setBusy(false);
228
  }
229
  }
230
 
231
- function onPointerDown(viewName, canvas, event) {
232
- if (!state.volume || state.busy) {
233
  return;
234
  }
235
-
236
- const voxel = canvasEventToVoxel(viewName, canvas, event);
237
- if (!voxel) {
238
- return;
 
 
 
 
 
 
 
 
 
 
239
  }
240
-
241
- const prompt = {
242
- type: "point",
243
- polarity: state.polarity,
244
- view: viewName,
245
- xyz: voxel,
246
- };
247
- pushPrompt(prompt);
248
- applyPointPrompt(state.mask, prompt);
249
- updateSegSummary();
250
- drawAll();
251
- setBackendMessage("Point prompt applied immediately (Slicer-like flow).");
252
  }
253
 
254
  function pushPrompt(prompt) {
@@ -409,37 +480,6 @@ function extractSlice(viewName, sliceIndex) {
409
  return { width, height, gray, mask };
410
  }
411
 
412
- function applyPointPrompt(mask, prompt) {
413
- const [cx, cy, cz] = prompt.xyz;
414
- const radius = prompt.polarity === "positive" ? 7 : 6;
415
-
416
- for (let z = Math.max(0, cz - radius); z <= Math.min(state.dims[2] - 1, cz + radius); z += 1) {
417
- for (let y = Math.max(0, cy - radius); y <= Math.min(state.dims[1] - 1, cy + radius); y += 1) {
418
- for (
419
- let x = Math.max(0, cx - radius);
420
- x <= Math.min(state.dims[0] - 1, cx + radius);
421
- x += 1
422
- ) {
423
- const dx = x - cx;
424
- const dy = y - cy;
425
- const dz = (z - cz) * 1.4;
426
- if (Math.sqrt(dx * dx + dy * dy + dz * dz) > radius) {
427
- continue;
428
- }
429
-
430
- const idx = xyzToIndex(x, y, z);
431
- if (prompt.polarity === "positive") {
432
- if (Math.abs(state.volume[idx] - state.volume[xyzToIndex(cx, cy, cz)]) <= 36) {
433
- mask[idx] = 1;
434
- }
435
- } else {
436
- mask[idx] = 0;
437
- }
438
- }
439
- }
440
- }
441
- }
442
-
443
  function updateSegSummary() {
444
  let count = 0;
445
  for (let i = 0; i < state.mask.length; i += 1) {
@@ -494,11 +534,6 @@ function voxelToViewCoords(viewName, xyz) {
494
  return [xyz[1], state.dims[2] - 1 - xyz[2]];
495
  }
496
 
497
- async function parseNrrdFile(file) {
498
- const bytes = new Uint8Array(await file.arrayBuffer());
499
- return parseNrrdBytes(bytes);
500
- }
501
-
502
  async function parseNrrdBytes(bytes) {
503
  const delimiter = findHeaderDelimiter(bytes);
504
  if (delimiter < 0) {
@@ -708,6 +743,80 @@ function createTypedArray(type, count) {
708
  }
709
  }
710
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
711
  async function ensureOk(response, endpointName) {
712
  if (response.ok) {
713
  return;
@@ -720,23 +829,22 @@ async function ensureOk(response, endpointName) {
720
 
721
  function setBusy(busy, message = "") {
722
  state.busy = busy;
723
- const buttons = [
724
- loadExampleBrainButton,
725
- loadExamplePanoramixButton,
726
- togglePromptsButton,
727
- toggleMaskButton,
728
- clearAllButton,
729
- ];
730
-
731
- buttons.forEach((button) => {
732
  if (button) {
733
  button.disabled = busy;
734
  }
735
  });
736
-
737
- if (volumeFileInput) {
738
- volumeFileInput.disabled = busy;
739
- }
 
 
 
 
 
 
 
740
 
741
  if (message) {
742
  setBackendMessage(message);
@@ -766,3 +874,12 @@ function clamp(value, min, max) {
766
  function clampToByte(value) {
767
  return clamp(Math.round(value), 0, 255);
768
  }
 
 
 
 
 
 
 
 
 
 
17
  coronal: 48,
18
  sagittal: 48,
19
  },
20
+ currentCase: null,
21
+ sessionReady: false,
22
  polarity: "positive",
23
  prompts: [],
24
  promptsVisible: true,
 
54
  const togglePromptsButton = document.getElementById("toggle-prompts");
55
  const toggleMaskButton = document.getElementById("toggle-mask");
56
  const clearAllButton = document.getElementById("clear-all");
 
57
  const loadExampleBrainButton = document.getElementById("load-example-brain");
58
  const loadExamplePanoramixButton = document.getElementById("load-example-panoramix");
59
 
 
61
 
62
  function init() {
63
  bindUI();
64
+ setBackendStatus("Not connected");
65
+ renderPromptLog();
66
+ drawAll();
67
+ setBusy(false);
68
  }
69
 
70
  function bindUI() {
 
106
  }
107
 
108
  if (clearAllButton) {
109
+ clearAllButton.addEventListener("click", clearSegmentation);
 
 
 
 
 
 
 
110
  }
111
 
112
  if (loadExampleBrainButton) {
113
  loadExampleBrainButton.addEventListener("click", () => {
114
+ startCase("brain");
115
  });
116
  }
117
 
118
  if (loadExamplePanoramixButton) {
119
  loadExamplePanoramixButton.addEventListener("click", () => {
120
+ startCase("panoramix");
121
  });
122
  }
123
 
124
+ window.addEventListener("pagehide", () => {
125
+ if (state.sessionReady) {
126
+ fetch("/api/demo/session", { method: "DELETE", keepalive: true }).catch(() => {});
127
+ }
128
+ });
129
  }
130
 
131
  function bindCanvas(viewName, canvas) {
132
+ canvas.addEventListener("pointerdown", (event) => {
133
  onPointerDown(viewName, canvas, event);
134
  });
135
  }
136
 
137
+ async function startCase(caseId) {
138
+ const example = EXAMPLE_VOLUMES[caseId];
139
+ if (!example || state.busy) {
140
  return;
141
  }
142
 
143
+ state.sessionReady = false;
144
  try {
145
+ setBusy(true, `Waking the backend for ${example.label}...`);
146
+ setBackendStatus("Waking backend");
147
+
148
+ const [parsed] = await Promise.all([loadExampleData(example), waitForBackend()]);
149
+ setBackendMessage(`Uploading ${example.label} to the backend...`);
150
+
151
+ const session = await apiRequest("/api/demo/session", {
152
+ method: "POST",
153
+ headers: { "Content-Type": "application/json" },
154
+ body: JSON.stringify({ case_id: caseId }),
155
+ });
156
+ if (!arraysEqual(parsed.sizes, session.dims)) {
157
+ throw new Error("The browser and backend volume dimensions do not match.");
158
+ }
159
 
160
  setVolume({
161
  name: example.label,
162
  data: normalizeToUint8(parsed.data),
163
  dims: parsed.sizes,
164
  });
165
+ state.currentCase = caseId;
166
+ state.sessionReady = true;
167
+ setBackendStatus("SAMI connected");
168
+ setBackendMessage(`${example.label} is ready. Add a point prompt.`);
169
  } catch (error) {
170
  console.error(error);
171
+ setBackendStatus("Unavailable");
172
+ setBackendMessage(error.message || `Failed to start ${example.label}.`);
173
  } finally {
174
  setBusy(false);
175
  }
176
  }
177
 
178
+ async function loadExampleData(example) {
179
+ const response = await fetch(example.path);
180
+ await ensureOk(response, example.label);
181
+ return parseNrrdBytes(new Uint8Array(await response.arrayBuffer()));
182
+ }
183
+
184
+ async function waitForBackend() {
185
+ const deadline = Date.now() + 180000;
186
+ while (Date.now() < deadline) {
187
+ try {
188
+ const result = await apiRequest("/api/backend/status");
189
+ if (result.status === "ready") {
190
+ return;
191
+ }
192
+ setBackendStatus(result.status === "waking" ? "Waking backend" : "Connecting");
193
+ } catch (_error) {
194
+ setBackendStatus("Connecting");
195
+ }
196
+ await delay(3000);
197
+ }
198
+ throw new Error("The segmentation backend did not become ready. Please try again.");
199
+ }
200
+
201
  function setVolume({ name, data, dims }) {
202
  state.volume = data;
203
  state.dims = dims;
 
238
  drawAll();
239
  }
240
 
241
+ function onPointerDown(viewName, canvas, event) {
242
+ if (!state.volume || !state.sessionReady || state.busy) {
 
243
  return;
244
  }
245
 
246
+ const voxel = canvasEventToVoxel(viewName, canvas, event);
247
+ if (!voxel) {
248
+ return;
249
+ }
250
+
251
+ submitPrompt({
252
+ type: "point",
253
+ polarity: state.polarity,
254
+ view: viewName,
255
+ xyz: voxel,
256
+ });
257
+ }
258
+
259
+ async function submitPrompt(prompt) {
260
+ if (state.busy || !state.sessionReady) {
261
+ return;
262
+ }
263
  try {
264
+ setBusy(true, "Running point segmentation...");
265
+ const backendPrompt = {
266
+ type: "point",
267
+ mode: prompt.polarity === "positive" ? "add" : "remove",
268
+ point: prompt.xyz,
269
+ };
270
+ const result = await apiRequest("/api/demo/session/prompt", {
271
+ method: "POST",
272
+ headers: { "Content-Type": "application/json" },
273
+ body: JSON.stringify(backendPrompt),
274
  });
275
+
276
+ if (result.session_restarted) {
277
+ state.prompts = [];
278
+ state.mask = new Uint8Array(totalVoxelCount());
279
+ }
280
+ state.mask = await decodeBackendMask(result);
281
+ pushPrompt(prompt);
282
+ updateSegSummary();
283
+ drawAll();
284
+
285
+ const seconds = Number(result.timings?.t_total_s);
286
+ const timingText = Number.isFinite(seconds) ? ` in ${seconds.toFixed(2)}s` : "";
287
+ setBackendMessage(
288
+ result.session_restarted
289
+ ? `The expired session was restarted. The latest prompt completed${timingText}.`
290
+ : `Segmentation completed${timingText}.`
291
+ );
292
  } catch (error) {
293
  console.error(error);
294
+ if (error.code === "session_required") {
295
+ state.sessionReady = false;
296
+ setBackendStatus("Session expired");
297
+ }
298
+ setBackendMessage(error.message || "Segmentation failed.");
299
  } finally {
 
300
  setBusy(false);
301
  }
302
  }
303
 
304
+ async function clearSegmentation() {
305
+ if (state.busy || !state.sessionReady) {
306
  return;
307
  }
308
+ try {
309
+ setBusy(true, "Clearing segmentation...");
310
+ await apiRequest("/api/demo/session/mask", { method: "DELETE" });
311
+ state.prompts = [];
312
+ state.mask = new Uint8Array(totalVoxelCount());
313
+ renderPromptLog();
314
+ updateSegSummary();
315
+ drawAll();
316
+ setBackendMessage("Prompts and mask cleared.");
317
+ } catch (error) {
318
+ console.error(error);
319
+ setBackendMessage(error.message || "Failed to clear segmentation.");
320
+ } finally {
321
+ setBusy(false);
322
  }
 
 
 
 
 
 
 
 
 
 
 
 
323
  }
324
 
325
  function pushPrompt(prompt) {
 
480
  return { width, height, gray, mask };
481
  }
482
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
483
  function updateSegSummary() {
484
  let count = 0;
485
  for (let i = 0; i < state.mask.length; i += 1) {
 
534
  return [xyz[1], state.dims[2] - 1 - xyz[2]];
535
  }
536
 
 
 
 
 
 
537
  async function parseNrrdBytes(bytes) {
538
  const delimiter = findHeaderDelimiter(bytes);
539
  if (delimiter < 0) {
 
743
  }
744
  }
745
 
746
+ async function decodeBackendMask(payload) {
747
+ if (payload.encoding !== "bbox_packed_gzip_b64") {
748
+ throw new Error("The backend returned an unsupported mask encoding.");
749
+ }
750
+ const output = new Uint8Array(totalVoxelCount());
751
+ const bbox = payload.bbox;
752
+ const cropShape = payload.crop_shape;
753
+ if (!Array.isArray(bbox) || bbox.length !== 6 || !Array.isArray(cropShape) || cropShape.length !== 3) {
754
+ throw new Error("The backend returned invalid mask metadata.");
755
+ }
756
+ if (cropShape.every((value) => value === 0)) {
757
+ return output;
758
+ }
759
+
760
+ const [z0, y0, x0, z1, y1, x1] = bbox.map(Number);
761
+ const [cropZ, cropY, cropX] = cropShape.map(Number);
762
+ const [dimX, dimY, dimZ] = state.dims;
763
+ const validMetadata =
764
+ [z0, y0, x0, z1, y1, x1, cropZ, cropY, cropX].every(Number.isInteger) &&
765
+ z0 >= 0 && y0 >= 0 && x0 >= 0 &&
766
+ z1 <= dimZ && y1 <= dimY && x1 <= dimX &&
767
+ z1 - z0 === cropZ && y1 - y0 === cropY && x1 - x0 === cropX;
768
+ if (!validMetadata) {
769
+ throw new Error("The backend returned mask bounds outside the volume.");
770
+ }
771
+
772
+ let compressed;
773
+ try {
774
+ const binary = atob(payload.mask);
775
+ compressed = Uint8Array.from(binary, (character) => character.charCodeAt(0));
776
+ } catch (_error) {
777
+ throw new Error("The backend returned invalid mask data.");
778
+ }
779
+ const packed = new Uint8Array(
780
+ await new Response(
781
+ new Blob([compressed]).stream().pipeThrough(new DecompressionStream("gzip"))
782
+ ).arrayBuffer()
783
+ );
784
+ const voxelCount = cropZ * cropY * cropX;
785
+ if (packed.length < Math.ceil(voxelCount / 8)) {
786
+ throw new Error("The backend returned an incomplete mask.");
787
+ }
788
+
789
+ for (let z = 0; z < cropZ; z += 1) {
790
+ for (let y = 0; y < cropY; y += 1) {
791
+ for (let x = 0; x < cropX; x += 1) {
792
+ const cropIndex = (z * cropY + y) * cropX + x;
793
+ const selected = (packed[cropIndex >> 3] >> (7 - (cropIndex & 7))) & 1;
794
+ if (selected) {
795
+ output[xyzToIndex(x0 + x, y0 + y, z0 + z)] = 1;
796
+ }
797
+ }
798
+ }
799
+ }
800
+ return output;
801
+ }
802
+
803
+ async function apiRequest(path, options = {}) {
804
+ const response = await fetch(path, options);
805
+ let payload = null;
806
+ try {
807
+ payload = await response.json();
808
+ } catch (_error) {
809
+ payload = null;
810
+ }
811
+ if (response.ok) {
812
+ return payload;
813
+ }
814
+ const error = new Error(payload?.message || "The demo request failed.");
815
+ error.code = payload?.error || "request_failed";
816
+ error.status = response.status;
817
+ throw error;
818
+ }
819
+
820
  async function ensureOk(response, endpointName) {
821
  if (response.ok) {
822
  return;
 
829
 
830
  function setBusy(busy, message = "") {
831
  state.busy = busy;
832
+ [loadExampleBrainButton, loadExamplePanoramixButton].forEach((button) => {
 
 
 
 
 
 
 
 
833
  if (button) {
834
  button.disabled = busy;
835
  }
836
  });
837
+ document.querySelectorAll("[data-tool], [data-polarity]").forEach((button) => {
838
+ button.disabled = busy || !state.sessionReady;
839
+ });
840
+ [togglePromptsButton, toggleMaskButton, clearAllButton].forEach((button) => {
841
+ if (button) {
842
+ button.disabled = busy || !state.sessionReady;
843
+ }
844
+ });
845
+ Object.values(views).forEach((view) => {
846
+ view.slider.disabled = !state.sessionReady;
847
+ });
848
 
849
  if (message) {
850
  setBackendMessage(message);
 
874
  function clampToByte(value) {
875
  return clamp(Math.round(value), 0, 255);
876
  }
877
+
878
+ function arraysEqual(left, right) {
879
+ return Array.isArray(left) && Array.isArray(right) &&
880
+ left.length === right.length && left.every((value, index) => value === right[index]);
881
+ }
882
+
883
+ function delay(milliseconds) {
884
+ return new Promise((resolve) => window.setTimeout(resolve, milliseconds));
885
+ }
index.html CHANGED
@@ -10,31 +10,26 @@
10
  <div class="app-shell">
11
  <header class="hero">
12
  <div>
13
- <p class="eyebrow">SAMI Web Demo</p>
14
- <h1>3D volume interaction in the browser</h1>
15
  <p class="hero-copy">
16
- This demo proves the web can handle a 3D segmentation workflow shape:
17
- load a volume, browse orthogonal slices, place prompts, and see a local segmentation mask overlay.
18
  </p>
19
  </div>
20
  <div class="hero-actions">
21
- <label class="upload-button">
22
- <input id="volume-file" type="file" accept=".nrrd">
23
- Load NRRD
24
- </label>
25
- <button id="load-example-brain" class="secondary">Example: Brain MRI</button>
26
- <button id="load-example-panoramix" class="secondary">Example: Panoramix CT</button>
27
  </div>
28
  </header>
29
 
30
  <section class="status-bar">
31
  <div>
32
  <span class="status-label">Volume</span>
33
- <strong id="volume-name">Synthetic sample</strong>
34
  </div>
35
  <div>
36
  <span class="status-label">Dimensions</span>
37
- <strong id="volume-shape">96 x 96 x 64</strong>
38
  </div>
39
  <div>
40
  <span class="status-label">Segmentation</span>
@@ -42,7 +37,7 @@
42
  </div>
43
  <div>
44
  <span class="status-label">Backend mode</span>
45
- <strong id="backend-mode">Local demo</strong>
46
  </div>
47
  </section>
48
 
@@ -67,7 +62,7 @@
67
  <button id="clear-all" class="secondary">Clear</button>
68
  </div>
69
  <p id="backend-message" class="hint">
70
- This demo runs fully in the browser. It is a product prototype, not the real SAMI backend.
71
  </p>
72
  </section>
73
 
@@ -86,8 +81,8 @@
86
  <p class="slice-subtitle">Z plane</p>
87
  </div>
88
  <label class="slider-wrap">
89
- <span>Slice <span id="axial-index">32</span></span>
90
- <input id="axial-slider" type="range" min="0" max="63" value="32">
91
  </label>
92
  </div>
93
  <canvas id="axial-canvas" width="320" height="320"></canvas>
@@ -100,8 +95,8 @@
100
  <p class="slice-subtitle">Y plane</p>
101
  </div>
102
  <label class="slider-wrap">
103
- <span>Slice <span id="coronal-index">48</span></span>
104
- <input id="coronal-slider" type="range" min="0" max="95" value="48">
105
  </label>
106
  </div>
107
  <canvas id="coronal-canvas" width="320" height="320"></canvas>
@@ -114,8 +109,8 @@
114
  <p class="slice-subtitle">X plane</p>
115
  </div>
116
  <label class="slider-wrap">
117
- <span>Slice <span id="sagittal-index">48</span></span>
118
- <input id="sagittal-slider" type="range" min="0" max="95" value="48">
119
  </label>
120
  </div>
121
  <canvas id="sagittal-canvas" width="320" height="320"></canvas>
 
10
  <div class="app-shell">
11
  <header class="hero">
12
  <div>
13
+ <p class="eyebrow">Medical Image segmentation helper </p>
14
+ <h1>SAMI web demo</h1>
15
  <p class="hero-copy">
16
+ Select an example, and click on the slices to generate a segmentation mask.
 
17
  </p>
18
  </div>
19
  <div class="hero-actions">
20
+ <button id="load-example-brain">Load Example Image 1</button>
21
+ <button id="load-example-panoramix" class="secondary">Load Example Image 2</button>
 
 
 
 
22
  </div>
23
  </header>
24
 
25
  <section class="status-bar">
26
  <div>
27
  <span class="status-label">Volume</span>
28
+ <strong id="volume-name">Select a test case</strong>
29
  </div>
30
  <div>
31
  <span class="status-label">Dimensions</span>
32
+ <strong id="volume-shape">—</strong>
33
  </div>
34
  <div>
35
  <span class="status-label">Segmentation</span>
 
37
  </div>
38
  <div>
39
  <span class="status-label">Backend mode</span>
40
+ <strong id="backend-mode">Not connected</strong>
41
  </div>
42
  </section>
43
 
 
62
  <button id="clear-all" class="secondary">Clear</button>
63
  </div>
64
  <p id="backend-message" class="hint">
65
+ Select a test case to start the SAMI backend.
66
  </p>
67
  </section>
68
 
 
81
  <p class="slice-subtitle">Z plane</p>
82
  </div>
83
  <label class="slider-wrap">
84
+ <span>Slice <span id="axial-index">0</span></span>
85
+ <input id="axial-slider" type="range" min="0" max="0" value="0" disabled>
86
  </label>
87
  </div>
88
  <canvas id="axial-canvas" width="320" height="320"></canvas>
 
95
  <p class="slice-subtitle">Y plane</p>
96
  </div>
97
  <label class="slider-wrap">
98
+ <span>Slice <span id="coronal-index">0</span></span>
99
+ <input id="coronal-slider" type="range" min="0" max="0" value="0" disabled>
100
  </label>
101
  </div>
102
  <canvas id="coronal-canvas" width="320" height="320"></canvas>
 
109
  <p class="slice-subtitle">X plane</p>
110
  </div>
111
  <label class="slider-wrap">
112
+ <span>Slice <span id="sagittal-index">0</span></span>
113
+ <input id="sagittal-slider" type="range" min="0" max="0" value="0" disabled>
114
  </label>
115
  </div>
116
  <canvas id="sagittal-canvas" width="320" height="320"></canvas>
requirements-dev.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ -r requirements.txt
2
+ pytest>=8,<9
requirements.txt CHANGED
@@ -1,2 +1,5 @@
1
  fastapi>=0.115,<1
 
 
 
2
  uvicorn[standard]>=0.30,<1
 
1
  fastapi>=0.115,<1
2
+ httpx>=0.27,<1
3
+ numpy>=2.0,<3
4
+ SimpleITK>=2.4,<3
5
  uvicorn[standard]>=0.30,<1
server.py CHANGED
@@ -1,20 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from pathlib import Path
 
2
 
3
- from fastapi import FastAPI
4
- from fastapi.responses import FileResponse
 
 
 
5
  from fastapi.staticfiles import StaticFiles
 
6
 
7
 
8
  APP_DIR = Path(__file__).resolve().parent
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  app = FastAPI(
11
  title="SAMI Web Demo",
12
  docs_url=None,
13
  redoc_url=None,
14
  openapi_url=None,
 
15
  )
16
 
17
 
 
 
 
 
 
 
 
 
 
 
18
  @app.get("/", include_in_schema=False)
19
  async def index() -> FileResponse:
20
  return FileResponse(APP_DIR / "index.html", media_type="text/html")
@@ -35,4 +445,97 @@ async def health() -> dict[str, str]:
35
  return {"status": "ok"}
36
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  app.mount("/examples", StaticFiles(directory=APP_DIR / "examples"), name="examples")
 
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import gzip
5
+ import hashlib
6
+ import io
7
+ import json
8
+ import os
9
+ import re
10
+ import secrets
11
+ import time
12
+ from collections import deque
13
+ from contextlib import asynccontextmanager
14
+ from dataclasses import dataclass, field
15
+ from datetime import datetime, timezone
16
  from pathlib import Path
17
+ from typing import Literal
18
 
19
+ import httpx
20
+ import numpy as np
21
+ import SimpleITK as sitk
22
+ from fastapi import FastAPI, Request, Response
23
+ from fastapi.responses import FileResponse, JSONResponse
24
  from fastapi.staticfiles import StaticFiles
25
+ from pydantic import BaseModel
26
 
27
 
28
  APP_DIR = Path(__file__).resolve().parent
29
+ BACKEND_URL = os.environ.get(
30
+ "ITK_BACKEND_URL", "https://harrybangbang-itk-dw-backend.hf.space"
31
+ ).rstrip("/")
32
+ COOKIE_NAME = "sami_demo_client"
33
+ COOKIE_PATTERN = re.compile(r"^[A-Za-z0-9_-]{32,64}$")
34
+ PROMPT_LIMIT = 10
35
+ PROMPT_WINDOW_SECONDS = 60.0
36
+ SESSION_IDLE_SECONDS = 30 * 60
37
+ UPLOAD_PART_COUNT = 5
38
+
39
+ CASES = {
40
+ "brain": APP_DIR / "examples" / "MRBrainTumor2.nrrd",
41
+ "panoramix": APP_DIR / "examples" / "Panoramix-cropped.nrrd",
42
+ }
43
+
44
+
45
+ class SessionRequest(BaseModel):
46
+ case_id: Literal["brain", "panoramix"]
47
+
48
+
49
+ class PromptRequest(BaseModel):
50
+ type: Literal["point"]
51
+ mode: Literal["add", "remove"]
52
+ point: list[int]
53
+
54
+ def backend_payload(self) -> dict[str, object]:
55
+ return {"type": "point", "mode": self.mode, "point": self.point}
56
+
57
+
58
+ class DemoAPIError(Exception):
59
+ def __init__(
60
+ self,
61
+ status_code: int,
62
+ code: str,
63
+ message: str,
64
+ *,
65
+ retry_after: int | None = None,
66
+ ) -> None:
67
+ super().__init__(message)
68
+ self.status_code = status_code
69
+ self.code = code
70
+ self.message = message
71
+ self.retry_after = retry_after
72
+
73
+
74
+ class BackendError(Exception):
75
+ def __init__(self, status_code: int, code: str, message: str) -> None:
76
+ super().__init__(message)
77
+ self.status_code = status_code
78
+ self.code = code
79
+ self.message = message
80
+
81
+
82
+ @dataclass(frozen=True)
83
+ class PreparedVolume:
84
+ payload: bytes
85
+ sha256: str
86
+ dims_xyz: tuple[int, int, int]
87
+
88
+
89
+ @dataclass
90
+ class DemoSession:
91
+ backend_session_id: str
92
+ case_id: str
93
+ dims_xyz: tuple[int, int, int]
94
+
95
+
96
+ @dataclass
97
+ class ClientState:
98
+ session: DemoSession | None = None
99
+ prompt_times: deque[float] = field(default_factory=deque)
100
+ operation_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
101
+ last_seen: float = field(default_factory=time.monotonic)
102
+
103
+
104
+ class BackendGateway:
105
+ def __init__(self, client: httpx.AsyncClient, secret: str | None) -> None:
106
+ self.client = client
107
+ self.secret = (secret or "").strip()
108
+ self._volume_cache: dict[str, PreparedVolume] = {}
109
+ self._volume_locks = {case_id: asyncio.Lock() for case_id in CASES}
110
+
111
+ def auth_headers(self) -> dict[str, str]:
112
+ if not self.secret:
113
+ raise BackendError(
114
+ 503,
115
+ "credentials_missing",
116
+ "The demo backend credentials are not configured.",
117
+ )
118
+ req_time = datetime.now(timezone.utc).strftime("%Y%m%d%H%M")
119
+ signature = hashlib.md5(
120
+ f"{self.secret}{req_time}".encode("utf-8")
121
+ ).hexdigest()
122
+ return {"X-Req-Time": req_time, "X-Req-Sign": signature}
123
+
124
+ async def status(self) -> str:
125
+ try:
126
+ response = await self.client.get("/v2/status", timeout=10.0)
127
+ except (httpx.TimeoutException, httpx.NetworkError):
128
+ return "unavailable"
129
+ if response.status_code == 200:
130
+ try:
131
+ payload = response.json()
132
+ except ValueError:
133
+ return "unavailable"
134
+ return "ready" if payload.get("status") == "ok" else "waking"
135
+ if response.status_code in {502, 503, 504}:
136
+ return "waking"
137
+ return "unavailable"
138
+
139
+ async def _request(self, method: str, path: str, **kwargs) -> httpx.Response:
140
+ headers = dict(kwargs.pop("headers", {}))
141
+ headers.update(self.auth_headers())
142
+ try:
143
+ response = await self.client.request(method, path, headers=headers, **kwargs)
144
+ except httpx.TimeoutException as exc:
145
+ raise BackendError(
146
+ 504, "backend_timeout", "The segmentation backend timed out."
147
+ ) from exc
148
+ except httpx.NetworkError as exc:
149
+ raise BackendError(
150
+ 503, "backend_unavailable", "The segmentation backend is unavailable."
151
+ ) from exc
152
+ if response.is_success:
153
+ return response
154
+ raise self._response_error(response.status_code)
155
+
156
+ @staticmethod
157
+ def _response_error(status_code: int) -> BackendError:
158
+ if status_code in {401, 403}:
159
+ return BackendError(
160
+ 503,
161
+ "credentials_rejected",
162
+ "The demo backend credentials were rejected.",
163
+ )
164
+ if status_code == 404:
165
+ return BackendError(404, "session_expired", "The backend session expired.")
166
+ if status_code == 429:
167
+ return BackendError(
168
+ 429,
169
+ "daily_quota_reached",
170
+ "The shared demo quota has been reached for today.",
171
+ )
172
+ if status_code == 504:
173
+ return BackendError(
174
+ 504, "backend_timeout", "The segmentation backend timed out."
175
+ )
176
+ if status_code >= 500:
177
+ return BackendError(
178
+ 503, "backend_unavailable", "The segmentation backend is unavailable."
179
+ )
180
+ return BackendError(502, "backend_error", "The segmentation request failed.")
181
+
182
+ async def prepared_volume(self, case_id: str) -> PreparedVolume:
183
+ cached = self._volume_cache.get(case_id)
184
+ if cached is not None:
185
+ return cached
186
+ async with self._volume_locks[case_id]:
187
+ cached = self._volume_cache.get(case_id)
188
+ if cached is None:
189
+ cached = await asyncio.to_thread(self._prepare_volume, case_id)
190
+ self._volume_cache[case_id] = cached
191
+ return cached
192
+
193
+ @staticmethod
194
+ def _prepare_volume(case_id: str) -> PreparedVolume:
195
+ image = sitk.ReadImage(str(CASES[case_id]))
196
+ array = np.asarray(sitk.GetArrayFromImage(image))
197
+ buffer = io.BytesIO()
198
+ np.save(buffer, array, allow_pickle=False)
199
+ payload = gzip.compress(buffer.getvalue(), compresslevel=1)
200
+ return PreparedVolume(
201
+ payload=payload,
202
+ sha256=hashlib.sha256(payload).hexdigest(),
203
+ dims_xyz=tuple(int(value) for value in image.GetSize()),
204
+ )
205
+
206
+ async def create_session(self, case_id: str) -> DemoSession:
207
+ prepared = await self.prepared_volume(case_id)
208
+ response = await self._request("POST", "/v2/sessions")
209
+ try:
210
+ backend_session_id = str(response.json()["session_id"])
211
+ except (ValueError, KeyError, TypeError) as exc:
212
+ raise BackendError(
213
+ 502, "backend_error", "The backend returned an invalid session response."
214
+ ) from exc
215
+ try:
216
+ await self._upload_volume(backend_session_id, prepared)
217
+ except Exception:
218
+ try:
219
+ await self.delete_session(backend_session_id, ignore_missing=True)
220
+ except BackendError:
221
+ pass
222
+ raise
223
+ return DemoSession(backend_session_id, case_id, prepared.dims_xyz)
224
+
225
+ async def _upload_volume(
226
+ self, backend_session_id: str, prepared: PreparedVolume
227
+ ) -> None:
228
+ init_response = await self._request(
229
+ "POST",
230
+ "/v2/sessions/image/uploads",
231
+ json={
232
+ "session_id": backend_session_id,
233
+ "total_parts": UPLOAD_PART_COUNT,
234
+ "total_bytes": len(prepared.payload),
235
+ "content_encoding": "gzip_npy",
236
+ "sha256": prepared.sha256,
237
+ },
238
+ )
239
+ try:
240
+ upload_id = str(init_response.json()["upload_id"])
241
+ except (ValueError, KeyError, TypeError) as exc:
242
+ raise BackendError(
243
+ 502, "backend_error", "The backend returned an invalid upload response."
244
+ ) from exc
245
+
246
+ length = len(prepared.payload)
247
+ boundaries = [length * index // UPLOAD_PART_COUNT for index in range(6)]
248
+ await asyncio.gather(
249
+ *(
250
+ self._request(
251
+ "PUT",
252
+ f"/v2/sessions/image/uploads/{upload_id}/parts/{part_index}",
253
+ content=prepared.payload[boundaries[part_index] : boundaries[part_index + 1]],
254
+ )
255
+ for part_index in range(UPLOAD_PART_COUNT)
256
+ )
257
+ )
258
+ await self._request(
259
+ "POST",
260
+ f"/v2/sessions/image/uploads/{upload_id}/complete",
261
+ json={"session_id": backend_session_id},
262
+ )
263
+
264
+ async def prompt(self, session: DemoSession, prompt: PromptRequest) -> dict:
265
+ response = await self._request(
266
+ "POST",
267
+ "/v2/sessions/prompt",
268
+ data={
269
+ "session_id": session.backend_session_id,
270
+ "prompt": json.dumps(prompt.backend_payload(), separators=(",", ":")),
271
+ },
272
+ )
273
+ try:
274
+ payload = response.json()
275
+ timings = {
276
+ key: value
277
+ for key, value in payload.get("timings", {}).items()
278
+ if isinstance(key, str)
279
+ and key.startswith("t_")
280
+ and isinstance(value, (int, float))
281
+ and not isinstance(value, bool)
282
+ }
283
+ return {
284
+ "encoding": payload["encoding"],
285
+ "mask": payload["mask"],
286
+ "bbox": payload["bbox"],
287
+ "crop_shape": payload["crop_shape"],
288
+ "timings": timings,
289
+ }
290
+ except (ValueError, KeyError, TypeError) as exc:
291
+ raise BackendError(
292
+ 502, "backend_error", "The backend returned an invalid mask response."
293
+ ) from exc
294
+
295
+ async def clear_mask(self, session: DemoSession) -> None:
296
+ await self._request(
297
+ "DELETE",
298
+ "/v2/sessions/mask",
299
+ json={"session_id": session.backend_session_id},
300
+ )
301
+
302
+ async def delete_session(
303
+ self, backend_session_id: str, *, ignore_missing: bool = False
304
+ ) -> None:
305
+ try:
306
+ await self._request(
307
+ "DELETE", "/v2/sessions", json={"session_id": backend_session_id}
308
+ )
309
+ except BackendError as exc:
310
+ if not (ignore_missing and exc.status_code == 404):
311
+ raise
312
+
313
+
314
+ clients: dict[str, ClientState] = {}
315
+
316
+
317
+ def _client_identity(request: Request, response: Response) -> tuple[str, ClientState]:
318
+ client_id = request.cookies.get(COOKIE_NAME, "")
319
+ if not COOKIE_PATTERN.fullmatch(client_id):
320
+ client_id = secrets.token_urlsafe(32)
321
+ forwarded_proto = request.headers.get("x-forwarded-proto", "")
322
+ response.set_cookie(
323
+ COOKIE_NAME,
324
+ client_id,
325
+ max_age=24 * 60 * 60,
326
+ httponly=True,
327
+ samesite="lax",
328
+ secure=request.url.scheme == "https" or forwarded_proto == "https",
329
+ )
330
+ state = clients.setdefault(client_id, ClientState())
331
+ state.last_seen = time.monotonic()
332
+ return client_id, state
333
+
334
+
335
+ def _validate_prompt(prompt: PromptRequest, dims_xyz: tuple[int, int, int]) -> None:
336
+ if len(prompt.point) != 3:
337
+ raise DemoAPIError(
338
+ 422, "invalid_prompt", "Point prompts require three coordinates."
339
+ )
340
+ for value, dimension in zip(prompt.point, dims_xyz):
341
+ if value < 0 or value >= dimension:
342
+ raise DemoAPIError(
343
+ 422,
344
+ "invalid_prompt",
345
+ "Prompt coordinates are outside the volume.",
346
+ )
347
+
348
+
349
+ def _check_rate_limit(state: ClientState) -> None:
350
+ now = time.monotonic()
351
+ while state.prompt_times and now - state.prompt_times[0] >= PROMPT_WINDOW_SECONDS:
352
+ state.prompt_times.popleft()
353
+ if len(state.prompt_times) >= PROMPT_LIMIT:
354
+ retry_after = max(
355
+ 1, int(PROMPT_WINDOW_SECONDS - (now - state.prompt_times[0])) + 1
356
+ )
357
+ raise DemoAPIError(
358
+ 429,
359
+ "rate_limited",
360
+ "Too many prompts. Please wait a moment and try again.",
361
+ retry_after=retry_after,
362
+ )
363
+ state.prompt_times.append(now)
364
+
365
+
366
+ def _gateway(request: Request) -> BackendGateway:
367
+ return request.app.state.gateway
368
+
369
+
370
+ def _translate_backend_error(error: BackendError) -> DemoAPIError:
371
+ return DemoAPIError(error.status_code, error.code, error.message)
372
+
373
+
374
+ async def _session_reaper(app: FastAPI) -> None:
375
+ while True:
376
+ await asyncio.sleep(60)
377
+ cutoff = time.monotonic() - SESSION_IDLE_SECONDS
378
+ expired = [
379
+ client_id for client_id, state in clients.items() if state.last_seen < cutoff
380
+ ]
381
+ for client_id in expired:
382
+ state = clients.pop(client_id, None)
383
+ if state is None or state.session is None:
384
+ continue
385
+ try:
386
+ await app.state.gateway.delete_session(
387
+ state.session.backend_session_id, ignore_missing=True
388
+ )
389
+ except BackendError:
390
+ pass
391
+
392
+
393
+ @asynccontextmanager
394
+ async def lifespan(app: FastAPI):
395
+ timeout = httpx.Timeout(connect=30.0, read=600.0, write=600.0, pool=30.0)
396
+ async with httpx.AsyncClient(base_url=BACKEND_URL, timeout=timeout) as client:
397
+ app.state.gateway = BackendGateway(client, os.environ.get("DemoSecret"))
398
+ reaper = asyncio.create_task(_session_reaper(app))
399
+ try:
400
+ yield
401
+ finally:
402
+ reaper.cancel()
403
+ try:
404
+ await reaper
405
+ except asyncio.CancelledError:
406
+ pass
407
+
408
 
409
  app = FastAPI(
410
  title="SAMI Web Demo",
411
  docs_url=None,
412
  redoc_url=None,
413
  openapi_url=None,
414
+ lifespan=lifespan,
415
  )
416
 
417
 
418
+ @app.exception_handler(DemoAPIError)
419
+ async def demo_error_handler(_request: Request, error: DemoAPIError) -> JSONResponse:
420
+ headers = {"Retry-After": str(error.retry_after)} if error.retry_after else None
421
+ return JSONResponse(
422
+ status_code=error.status_code,
423
+ content={"error": error.code, "message": error.message},
424
+ headers=headers,
425
+ )
426
+
427
+
428
  @app.get("/", include_in_schema=False)
429
  async def index() -> FileResponse:
430
  return FileResponse(APP_DIR / "index.html", media_type="text/html")
 
445
  return {"status": "ok"}
446
 
447
 
448
+ @app.get("/api/backend/status")
449
+ async def backend_status(request: Request) -> dict[str, str]:
450
+ return {"status": await _gateway(request).status()}
451
+
452
+
453
+ @app.post("/api/demo/session")
454
+ async def create_demo_session(
455
+ body: SessionRequest, request: Request, response: Response
456
+ ) -> dict[str, object]:
457
+ _client_id, state = _client_identity(request, response)
458
+ async with state.operation_lock:
459
+ gateway = _gateway(request)
460
+ old_session = state.session
461
+ state.session = None
462
+ if old_session is not None:
463
+ try:
464
+ await gateway.delete_session(
465
+ old_session.backend_session_id, ignore_missing=True
466
+ )
467
+ except BackendError:
468
+ pass
469
+ try:
470
+ state.session = await gateway.create_session(body.case_id)
471
+ except BackendError as exc:
472
+ raise _translate_backend_error(exc) from exc
473
+ return {"case_id": body.case_id, "dims": list(state.session.dims_xyz)}
474
+
475
+
476
+ @app.post("/api/demo/session/prompt")
477
+ async def demo_prompt(
478
+ body: PromptRequest, request: Request, response: Response
479
+ ) -> dict[str, object]:
480
+ _client_id, state = _client_identity(request, response)
481
+ if state.operation_lock.locked():
482
+ raise DemoAPIError(
483
+ 409, "prompt_in_progress", "Please wait for the current request to finish."
484
+ )
485
+ await state.operation_lock.acquire()
486
+ try:
487
+ if state.session is None:
488
+ raise DemoAPIError(409, "session_required", "Select a demo case first.")
489
+ _validate_prompt(body, state.session.dims_xyz)
490
+ _check_rate_limit(state)
491
+ gateway = _gateway(request)
492
+ restarted = False
493
+ try:
494
+ payload = await gateway.prompt(state.session, body)
495
+ except BackendError as exc:
496
+ if exc.code != "session_expired":
497
+ raise _translate_backend_error(exc) from exc
498
+ case_id = state.session.case_id
499
+ try:
500
+ state.session = await gateway.create_session(case_id)
501
+ payload = await gateway.prompt(state.session, body)
502
+ except BackendError as retry_error:
503
+ raise _translate_backend_error(retry_error) from retry_error
504
+ restarted = True
505
+ return {**payload, "session_restarted": restarted}
506
+ finally:
507
+ state.operation_lock.release()
508
+
509
+
510
+ @app.delete("/api/demo/session/mask")
511
+ async def clear_demo_mask(request: Request, response: Response) -> dict[str, bool]:
512
+ _client_id, state = _client_identity(request, response)
513
+ async with state.operation_lock:
514
+ if state.session is None:
515
+ raise DemoAPIError(409, "session_required", "Select a demo case first.")
516
+ try:
517
+ await _gateway(request).clear_mask(state.session)
518
+ except BackendError as exc:
519
+ if exc.code == "session_expired":
520
+ state.session = None
521
+ raise _translate_backend_error(exc) from exc
522
+ return {"ok": True}
523
+
524
+
525
+ @app.delete("/api/demo/session")
526
+ async def delete_demo_session(request: Request, response: Response) -> dict[str, bool]:
527
+ _client_id, state = _client_identity(request, response)
528
+ async with state.operation_lock:
529
+ session = state.session
530
+ state.session = None
531
+ if session is not None:
532
+ try:
533
+ await _gateway(request).delete_session(
534
+ session.backend_session_id, ignore_missing=True
535
+ )
536
+ except BackendError as exc:
537
+ raise _translate_backend_error(exc) from exc
538
+ return {"ok": True}
539
+
540
+
541
  app.mount("/examples", StaticFiles(directory=APP_DIR / "examples"), name="examples")
style.css CHANGED
@@ -129,7 +129,7 @@ button.secondary {
129
  }
130
 
131
  button:disabled {
132
- cursor: wait;
133
  opacity: 0.7;
134
  transform: none;
135
  }
@@ -167,7 +167,7 @@ button:disabled {
167
 
168
  .tool-grid {
169
  display: grid;
170
- grid-template-columns: repeat(3, minmax(0, 1fr));
171
  gap: 10px;
172
  margin-top: 12px;
173
  }
@@ -268,6 +268,7 @@ button:disabled {
268
  canvas {
269
  width: 100%;
270
  aspect-ratio: 1;
 
271
  border-radius: 20px;
272
  background: #10151d;
273
  border: 1px solid rgba(255, 255, 255, 0.05);
 
129
  }
130
 
131
  button:disabled {
132
+ cursor: not-allowed;
133
  opacity: 0.7;
134
  transform: none;
135
  }
 
167
 
168
  .tool-grid {
169
  display: grid;
170
+ grid-template-columns: 1fr;
171
  gap: 10px;
172
  margin-top: 12px;
173
  }
 
268
  canvas {
269
  width: 100%;
270
  aspect-ratio: 1;
271
+ touch-action: none;
272
  border-radius: 20px;
273
  background: #10151d;
274
  border: 1px solid rgba(255, 255, 255, 0.05);
tests/test_server.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import gzip
3
+ import hashlib
4
+ import io
5
+
6
+ import httpx
7
+ import numpy as np
8
+ import pytest
9
+ from fastapi.testclient import TestClient
10
+
11
+ import server
12
+
13
+
14
+ EMPTY_MASK = {
15
+ "encoding": "bbox_packed_gzip_b64",
16
+ "mask": "H4sIAAAAAAACAwMAAAAAAAAAAAA=",
17
+ "bbox": [0, 0, 0, 0, 0, 0],
18
+ "crop_shape": [0, 0, 0],
19
+ "timings": {"t_total_s": 0.1},
20
+ }
21
+
22
+
23
+ class FakeGateway:
24
+ def __init__(self) -> None:
25
+ self.created = []
26
+ self.deleted = []
27
+ self.prompt_calls = 0
28
+ self.clear_calls = 0
29
+ self.expire_once = False
30
+ self.prompt_error = None
31
+
32
+ async def status(self):
33
+ return "ready"
34
+
35
+ async def create_session(self, case_id):
36
+ session = server.DemoSession(
37
+ f"private-backend-id-{len(self.created)}", case_id, (20, 30, 40)
38
+ )
39
+ self.created.append(session)
40
+ return session
41
+
42
+ async def prompt(self, _session, _prompt):
43
+ self.prompt_calls += 1
44
+ if self.expire_once:
45
+ self.expire_once = False
46
+ raise server.BackendError(404, "session_expired", "expired")
47
+ if self.prompt_error is not None:
48
+ raise self.prompt_error
49
+ return dict(EMPTY_MASK)
50
+
51
+ async def clear_mask(self, _session):
52
+ self.clear_calls += 1
53
+
54
+ async def delete_session(self, backend_session_id, *, ignore_missing=False):
55
+ self.deleted.append((backend_session_id, ignore_missing))
56
+
57
+
58
+ @pytest.fixture
59
+ def api():
60
+ server.clients.clear()
61
+ with TestClient(server.app) as client:
62
+ gateway = FakeGateway()
63
+ server.app.state.gateway = gateway
64
+ yield client, gateway
65
+ server.clients.clear()
66
+
67
+
68
+ def start_session(client, case_id="brain"):
69
+ response = client.post("/api/demo/session", json={"case_id": case_id})
70
+ assert response.status_code == 200
71
+ return response
72
+
73
+
74
+ def test_auth_header_matches_backend_protocol():
75
+ gateway = server.BackendGateway(None, "unit-test-secret")
76
+ headers = gateway.auth_headers()
77
+ assert headers["X-Req-Time"].isdigit()
78
+ assert len(headers["X-Req-Time"]) == 12
79
+ expected = hashlib.md5(
80
+ f"unit-test-secret{headers['X-Req-Time']}".encode()
81
+ ).hexdigest()
82
+ assert headers["X-Req-Sign"] == expected
83
+ assert "unit-test-secret" not in repr(headers)
84
+
85
+
86
+ @pytest.mark.parametrize("case_id", ["brain", "panoramix"])
87
+ def test_fixed_volume_serialization_round_trip(case_id):
88
+ prepared = server.BackendGateway._prepare_volume(case_id)
89
+ array = np.load(io.BytesIO(gzip.decompress(prepared.payload)), allow_pickle=False)
90
+ assert array.ndim == 3
91
+ assert tuple(reversed(array.shape)) == prepared.dims_xyz
92
+ assert hashlib.sha256(prepared.payload).hexdigest() == prepared.sha256
93
+
94
+
95
+ def test_upload_is_split_into_exactly_five_parts():
96
+ class CaptureGateway(server.BackendGateway):
97
+ def __init__(self):
98
+ super().__init__(None, "secret")
99
+ self.calls = []
100
+
101
+ async def _request(self, method, path, **kwargs):
102
+ self.calls.append((method, path, kwargs))
103
+ payload = {"upload_id": "upload-1"} if path.endswith("/uploads") else {"ok": True}
104
+ return httpx.Response(200, json=payload)
105
+
106
+ gateway = CaptureGateway()
107
+ prepared = server.PreparedVolume(b"0123456789abcdef", "sha", (1, 1, 1))
108
+ asyncio.run(gateway._upload_volume("backend-session", prepared))
109
+ part_calls = [call for call in gateway.calls if "/parts/" in call[1]]
110
+ assert len(part_calls) == 5
111
+ assert b"".join(call[2]["content"] for call in part_calls) == prepared.payload
112
+
113
+
114
+ def test_unknown_case_is_rejected(api):
115
+ client, _gateway = api
116
+ response = client.post("/api/demo/session", json={"case_id": "user-file"})
117
+ assert response.status_code == 422
118
+
119
+
120
+ def test_backend_session_id_is_not_exposed_and_case_switch_deletes_old(api):
121
+ client, gateway = api
122
+ first = start_session(client)
123
+ second = start_session(client, "panoramix")
124
+ assert "private-backend-id" not in first.text + second.text
125
+ assert second.json() == {"case_id": "panoramix", "dims": [20, 30, 40]}
126
+ assert gateway.deleted == [("private-backend-id-0", True)]
127
+
128
+
129
+ def test_prompt_validation_clear_and_recovery(api):
130
+ client, gateway = api
131
+ start_session(client)
132
+
133
+ invalid = client.post(
134
+ "/api/demo/session/prompt",
135
+ json={"type": "point", "mode": "add", "point": [20, 0, 0]},
136
+ )
137
+ assert invalid.status_code == 422
138
+
139
+ invalid_box = client.post(
140
+ "/api/demo/session/prompt",
141
+ json={
142
+ "type": "bbox",
143
+ "mode": "add",
144
+ "corner1": [1, 1, 1],
145
+ "corner2": [5, 5, 5],
146
+ },
147
+ )
148
+ assert invalid_box.status_code == 422
149
+
150
+ gateway.expire_once = True
151
+ recovered = client.post(
152
+ "/api/demo/session/prompt",
153
+ json={"type": "point", "mode": "remove", "point": [2, 3, 4]},
154
+ )
155
+ assert recovered.status_code == 200
156
+ assert recovered.json()["session_restarted"] is True
157
+ assert len(gateway.created) == 2
158
+ assert gateway.prompt_calls == 2
159
+
160
+ cleared = client.delete("/api/demo/session/mask")
161
+ assert cleared.status_code == 200
162
+ assert gateway.clear_calls == 1
163
+
164
+
165
+ def test_rate_limit_survives_case_switch(api):
166
+ client, _gateway = api
167
+ start_session(client)
168
+ prompt = {"type": "point", "mode": "add", "point": [2, 3, 4]}
169
+ for _ in range(5):
170
+ assert client.post("/api/demo/session/prompt", json=prompt).status_code == 200
171
+ start_session(client, "panoramix")
172
+ for _ in range(5):
173
+ assert client.post("/api/demo/session/prompt", json=prompt).status_code == 200
174
+ limited = client.post("/api/demo/session/prompt", json=prompt)
175
+ assert limited.status_code == 429
176
+ assert limited.json()["error"] == "rate_limited"
177
+ assert int(limited.headers["Retry-After"]) >= 1
178
+
179
+
180
+ @pytest.mark.parametrize(
181
+ ("backend_error", "expected_status", "expected_code"),
182
+ [
183
+ (server.BackendError(503, "credentials_rejected", "safe"), 503, "credentials_rejected"),
184
+ (server.BackendError(429, "daily_quota_reached", "safe"), 429, "daily_quota_reached"),
185
+ (server.BackendError(503, "backend_unavailable", "safe"), 503, "backend_unavailable"),
186
+ (server.BackendError(504, "backend_timeout", "safe"), 504, "backend_timeout"),
187
+ ],
188
+ )
189
+ def test_safe_backend_error_mapping(api, backend_error, expected_status, expected_code):
190
+ client, gateway = api
191
+ start_session(client)
192
+ gateway.prompt_error = backend_error
193
+ response = client.post(
194
+ "/api/demo/session/prompt",
195
+ json={"type": "point", "mode": "add", "point": [1, 1, 1]},
196
+ )
197
+ assert response.status_code == expected_status
198
+ assert response.json() == {"error": expected_code, "message": "safe"}