Spaces:
Sleeping
Sleeping
File size: 4,301 Bytes
ff0c106 | 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 | # SAMI API integration guide
This repository contains two different interfaces:
- `demo_api` is the website proxy. It owns fixed cases, browser cookies, rate
limits, and `/api/demo/...` routes.
- `sami_client` is the reusable Python integration layer for the private SAMI
`/v2` API.
Applications integrating SAMI should use `sami_client`. They should not copy
the browser-session behavior from `demo_api`.
## Complete request sequence
```text
Check status
→ Create session
→ Read and compress image
→ Upload image parts
→ Complete image upload
→ Send prompts
→ Decode returned mask
→ Delete session
```
| Step | SAMI endpoint |
| --- | --- |
| Status | `GET /v2/status` |
| Create session | `POST /v2/sessions` |
| Begin upload | `POST /v2/sessions/image/uploads` |
| Upload each part | `PUT /v2/sessions/image/uploads/{upload_id}/parts/{index}` |
| Complete upload | `POST /v2/sessions/image/uploads/{upload_id}/complete` |
| Apply prompt | `POST /v2/sessions/prompt` |
| Clear current mask | `DELETE /v2/sessions/mask` |
| Close session | `DELETE /v2/sessions` |
## Python client
`SAMIClient` accepts an `httpx.AsyncClient`, a secret, and an optional upload
part count. `create_session` reads any medical image format supported by
SimpleITK, converts it to a NumPy array, and performs the complete chunked
upload.
```python
import asyncio
import os
import httpx
from sami_client import SAMIClient, PointPrompt, decode_bbox_packed_mask
async def segment(volume_path: str):
async with httpx.AsyncClient(base_url=os.environ["SAMI_URL"]) as http:
sami = SAMIClient(http, os.environ["SAMI_SECRET"])
session = await sami.create_session(volume_path)
try:
result = await sami.prompt(
session,
PointPrompt(mode="add", point=(80, 96, 42)),
)
return decode_bbox_packed_mask(
result["mask"],
result["bbox"],
result["crop_shape"],
volume_shape_zyx=tuple(reversed(session.dims_xyz)),
)
finally:
await sami.delete_session(session.session_id, ignore_missing=True)
mask = asyncio.run(segment("patient-volume.nii.gz"))
```
The secret must stay on a trusted server. Never put it in browser JavaScript.
## Authentication
Authenticated requests include:
```text
X-Req-Time: YYYYMMDDHHMM
X-Req-Sign: md5(secret + X-Req-Time)
```
The time is the current UTC minute. `/v2/status` does not require these headers.
`sami_client/auth.py` contains the implementation.
## Image upload format
The client reads the image with SimpleITK and converts it to a NumPy array in
`z, y, x` order. It then:
1. serializes the array with `numpy.save`;
2. compresses it with gzip;
3. calculates SHA-256 over the compressed bytes;
4. uploads the bytes in numbered parts using `content_encoding: gzip_npy`.
The upload initialization body contains:
```json
{
"session_id": "private-session-id",
"total_parts": 5,
"total_bytes": 123456,
"content_encoding": "gzip_npy",
"sha256": "compressed-payload-sha256"
}
```
## Point prompts
Points use voxel coordinates in `[x, y, z]` order:
```json
{
"type": "point",
"mode": "add",
"point": [80, 96, 42]
}
```
Use `mode: "add"` for a positive point and `mode: "remove"` for a negative
point. The prompt is sent as a JSON string together with the private session ID.
## Mask response
The supported response encoding is `bbox_packed_gzip_b64`:
```json
{
"encoding": "bbox_packed_gzip_b64",
"mask": "base64-encoded-gzip-data",
"bbox": [12, 20, 30, 70, 120, 150],
"crop_shape": [58, 100, 120]
}
```
The bounding box and crop shape use `z, y, x` array order. Mask bits use
big-endian bit order. `decode_bbox_packed_mask` validates the metadata,
decompresses the packed crop, and places it into a full-volume `uint8` NumPy
array.
## Error handling
`SAMIClient` converts connection, authentication, quota, timeout, session, and
backend failures into `SAMIError`. Inspect its `status_code` and stable `code`.
Do not show raw backend responses or secrets to end users.
If a request returns `session_expired`, create a new session, upload the image
again, and retry the latest prompt once. `demo_api/routes.py` demonstrates this
recovery policy.
|