|
| 1 | +# Quick start |
| 2 | + |
| 3 | +## Sync vs Async clients |
| 4 | + |
| 5 | +This SDK provides two clients: |
| 6 | + |
| 7 | +- `rationai.Client` (sync): Uses blocking HTTP requests. Best for scripts, notebooks, CLIs, or when your code is already synchronous. |
| 8 | +- `rationai.AsyncClient` (async): Uses non-blocking HTTP requests (`await`). Best when you already have an `asyncio` event loop (FastAPI, async workers) or you want to run many requests concurrently. |
| 9 | + |
| 10 | +Both clients expose the same high-level resources: |
| 11 | + |
| 12 | +- `client.models` for image classification/segmentation |
| 13 | +- `client.qc` for quality control endpoints |
| 14 | + |
| 15 | +### What’s the actual difference? |
| 16 | + |
| 17 | +- **Sync** calls (e.g. `client.models.classify_image(...)`) block the current thread until the request completes. |
| 18 | +- **Async** calls (e.g. `await client.models.classify_image(...)`) yield control back to the event loop while the network request is in flight, so other tasks can run. |
| 19 | + |
| 20 | +### Lifecycle (important) |
| 21 | + |
| 22 | +- Prefer using context managers so connections are closed: |
| 23 | + - sync: `with rationai.Client(...) as client: ...` |
| 24 | + - async: `async with rationai.AsyncClient(...) as client: ...` |
| 25 | +- If you don’t use `with`, call `client.close()` (sync) / `await client.aclose()` (async). |
| 26 | + |
| 27 | +For details on what is sent over the wire (compression, payloads), see: [How it works](../how-it-works.md). |
| 28 | + |
| 29 | +## API at a glance |
| 30 | + |
| 31 | +### Models |
| 32 | + |
| 33 | +#### `client.models.classify_image` |
| 34 | + |
| 35 | +Signature: |
| 36 | + |
| 37 | +`classify_image(model: str, image: PIL.Image.Image | numpy.typing.NDArray[numpy.uint8], timeout=...) -> float | dict[str, float]` |
| 38 | + |
| 39 | +- `model`: Model name / path appended to `models_base_url`. |
| 40 | +- `image`: **uint8 RGB** image (PIL or NumPy array of shape `(H, W, 3)`). |
| 41 | +- `timeout`: Optional request timeout (defaults to the client’s timeout). |
| 42 | +- Returns: classification result from JSON (often `float` for binary, or `dict[class, prob]`). |
| 43 | + |
| 44 | +#### `client.models.segment_image` |
| 45 | + |
| 46 | +Signature: |
| 47 | + |
| 48 | +`segment_image(model: str, image: PIL.Image.Image | numpy.typing.NDArray[numpy.uint8], timeout=...) -> numpy.typing.NDArray[numpy.float16]` |
| 49 | + |
| 50 | +- `model`: Model name / path appended to `models_base_url`. |
| 51 | +- `image`: **uint8 RGB** image (PIL or NumPy array of shape `(H, W, 3)`). |
| 52 | +- `timeout`: Optional request timeout (defaults to the client’s timeout). |
| 53 | +- Returns: `float16` NumPy array with shape `(num_classes, height, width)`. |
| 54 | + |
| 55 | +### Quality control (QC) |
| 56 | + |
| 57 | +#### `client.qc.check_slide` |
| 58 | + |
| 59 | +Signature: |
| 60 | + |
| 61 | +`check_slide(wsi_path: os.PathLike[str] | str, output_path: os.PathLike[str] | str, config: SlideCheckConfig | None = None, timeout=3600) -> str` |
| 62 | + |
| 63 | +- `wsi_path`: Path to a whole-slide image (evaluated by the QC service). |
| 64 | +- `output_path`: Directory where the QC service should write masks (evaluated by the QC service). |
| 65 | +- `config`: Optional `SlideCheckConfig` (see reference types). |
| 66 | +- `timeout`: Request timeout (default is 3600 seconds). |
| 67 | +- Returns: xOpat URL as plain text. |
| 68 | + |
| 69 | +#### `client.qc.generate_report` |
| 70 | + |
| 71 | +Signature: |
| 72 | + |
| 73 | +`generate_report(backgrounds: Iterable[os.PathLike[str] | str], mask_dir: os.PathLike[str] | str, save_location: os.PathLike[str] | str, compute_metrics: bool = True, timeout=...) -> None` |
| 74 | + |
| 75 | +- `backgrounds`: Iterable of slide/background image paths. |
| 76 | +- `mask_dir`: Directory containing generated masks. |
| 77 | +- `save_location`: Path where the report HTML should be written. |
| 78 | +- `compute_metrics`: Whether to compute aggregated metrics (default: `True`). |
| 79 | +- Returns: nothing. |
| 80 | + |
| 81 | +## Synchronous client |
| 82 | + |
| 83 | +```python |
| 84 | +from PIL import Image |
| 85 | +import rationai |
| 86 | + |
| 87 | +image = Image.open("path/to/image.jpg").convert("RGB") |
| 88 | + |
| 89 | +with rationai.Client() as client: |
| 90 | + result = client.models.classify_image("model-name", image) |
| 91 | + print(result) |
| 92 | +``` |
| 93 | + |
| 94 | +## Asynchronous client |
| 95 | + |
| 96 | +```python |
| 97 | +import asyncio |
| 98 | +from PIL import Image |
| 99 | +import rationai |
| 100 | + |
| 101 | +image = Image.open("path/to/image.jpg").convert("RGB") |
| 102 | + |
| 103 | +async def main(): |
| 104 | + async with rationai.AsyncClient() as client: |
| 105 | + result = await client.models.classify_image("model-name", image) |
| 106 | + print(result) |
| 107 | + |
| 108 | +asyncio.run(main()) |
| 109 | +``` |
| 110 | + |
| 111 | +### Concurrency with the async client |
| 112 | + |
| 113 | +Use `asyncio` concurrency when you need to process many images. A semaphore is the simplest way to cap concurrency so you don’t overload the server. |
| 114 | + |
| 115 | +```python |
| 116 | +import asyncio |
| 117 | +from PIL import Image |
| 118 | +import rationai |
| 119 | + |
| 120 | +async def classify_many(paths: list[str], model: str, *, max_concurrent: int = 8) -> list[float | dict[str, float]]: |
| 121 | + sem = asyncio.Semaphore(max_concurrent) |
| 122 | + |
| 123 | + async def one(client: rationai.AsyncClient, path: str) -> float | dict[str, float]: |
| 124 | + async with sem: |
| 125 | + image = Image.open(path).convert("RGB") |
| 126 | + return await client.models.classify_image(model, image) |
| 127 | + |
| 128 | + async with rationai.AsyncClient() as client: |
| 129 | + return await asyncio.gather(*(one(client, p) for p in paths)) |
| 130 | +``` |
| 131 | + |
| 132 | +## Common pitfalls |
| 133 | + |
| 134 | +- **PIL image mode**: ensure RGB. |
| 135 | + |
| 136 | +```python |
| 137 | +image = Image.open(path).convert("RGB") |
| 138 | +``` |
| 139 | + |
| 140 | +- **NumPy dtype/shape**: the services expect `uint8` RGB images. |
| 141 | + |
| 142 | +```python |
| 143 | +import numpy as np |
| 144 | + |
| 145 | +assert arr.dtype == np.uint8 |
| 146 | +assert arr.ndim == 3 and arr.shape[2] == 3 |
| 147 | +``` |
| 148 | + |
| 149 | +- **Forgetting to close clients**: prefer `with ...` / `async with ...`. |
| 150 | + |
| 151 | +- **Too much async concurrency**: cap with a semaphore (start small like 4–16) to avoid server overload/timeouts. |
| 152 | + |
| 153 | +- **Timeouts**: segmentation/QC can take longer. Increase per-request timeout if needed. |
| 154 | + |
| 155 | +```python |
| 156 | +result = client.models.segment_image("model", image, timeout=300) |
| 157 | +``` |
| 158 | + |
| 159 | +- **QC paths are server-side**: `wsi_path` / `output_path` must exist where the QC service runs. |
| 160 | + |
| 161 | +## Configuration |
| 162 | + |
| 163 | +You can override service URLs and timeouts: |
| 164 | + |
| 165 | +```python |
| 166 | +from rationai import Client |
| 167 | + |
| 168 | +client = Client( |
| 169 | + models_base_url="http://localhost:8000", |
| 170 | + qc_base_url="http://localhost:8001", |
| 171 | + timeout=300, |
| 172 | +) |
| 173 | +``` |
0 commit comments