Metadata-Version: 2.4
Name: forithmus
Version: 2.0.0
Summary: Python client and command-line tool for the Forithmus API (FORA on CT and chest X-ray) and the Forithmus Research Hub
Author-email: Forithmus <contact@forithmus.com>
License-Expression: MIT
Project-URL: Homepage, https://api.forithmus.com
Project-URL: API documentation, https://api.forithmus.com/docs/reference/python
Project-URL: Research Hub, https://research.forithmus.com
Project-URL: Research Hub guide, https://research.forithmus.com/getting-started
Project-URL: Repository, https://github.com/forithmus/cli
Keywords: medical-imaging,radiology,ct,chest-x-ray,api,ai,challenges,benchmarks,docker
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: typer<0.26,>=0.9.0
Requires-Dist: click>=8.0
Requires-Dist: httpx>=0.25.0
Requires-Dist: numpy>=1.24.0
Requires-Dist: rich>=13.0.0
Provides-Extra: medical
Requires-Dist: nibabel>=5.0.0; extra == "medical"
Requires-Dist: Pillow>=10.0.0; extra == "medical"
Provides-Extra: docker
Requires-Dist: docker>=7.0.0; extra == "docker"

# Forithmus CLI

Command-line tools for testing and submitting challenge entries to the
[Forithmus Research Hub](https://research.forithmus.com).

## Install

```bash
python -m pip install --upgrade "forithmus[docker]"
```

## Test a Docker image locally

```bash
forithmus test your-image:latest --timeout 600
```

The CLI creates sample input data and mounts the input and output directories
into the container as `/input` and `/output`. On Windows, use Docker Desktop
and a current CLI release; version 0.1.11 and newer resolve bind mounts to
absolute Windows host paths.

## Submit

```bash
forithmus login
forithmus submit submission.tar.gz
```

Run `forithmus --help` for all commands and options.

## FORA benchmarks

FORA is a continuous CT benchmark whose submissions carry parameters: the tasks
(`classification`, `report_generation`), the CT protocols (`ct01` to `ct29`), whether the
clinical judge scores generated reports, and how the result is published. `forithmus init`
recognises a FORA benchmark and stores its public configuration; the usual commands then
work with FORA:

```bash
forithmus init <benchmark-slug>        # prints tasks, enabled protocols, release and submit defaults
forithmus generate                     # synthetic input, FORA_REQUEST and example output files
forithmus test my-model:1 --timeout 1800 [--task classification] [--protocol ct06,ct07]
forithmus submit submission.tar.gz --tier gpu-l4-xl --time-budget 240 --weights weights.zip \
    -d "My model v1" [--task ...] [--protocol ...|all] [--no-judge] \
    [--publication pseudonym|named|private] [--retry-of <failed-id>] [--max-charge <USD>]
forithmus status <submission-id> --wait
forithmus results <submission-id>
forithmus leaderboard --task classification --protocol all
```

- `generate` writes `.forithmus/test_data/input/` (`fora_manifest.json`, `fora_labels.json`
  with synthetic label names, small synthetic phantom volumes: one study per requested
  protocol and one of another protocol that the container must skip),
  `.forithmus/test_data/fora_request.json` and `.forithmus/test_data/expected_output/`.
- `test` runs the image with `FORA_REQUEST` set (uid 1000, no network, `/input` read-only)
  and checks the output files against the FORA output contract of the public example
  ([VLM3D-Dockers/fora_benchmark](https://github.com/forithmus/VLM3D-Dockers/tree/main/fora_benchmark)).
  `validate <dir>` runs the same check on files you produced yourself. JSON files must be
  UTF-8 without a byte-order mark. The check warns when the report file is larger than the
  evaluator's size budget (1 MiB plus 18,432 bytes, one 16,384-character text plus 2 KiB, per
  study of the report task's enabled protocols; on the local test set, per requested study),
  when a `findings_text` is longer than 16,384 characters or cannot be encoded as UTF-8 (an
  unpaired surrogate, which JSON can carry only as an escape such as `\ud800`; in both cases the
  evaluator scores that study as a failed report) and when a `generated_token_count` is outside
  0 to 1,048,576 (the evaluator leaves it out of its token statistics), and reports when the
  optional `fora_runtime.json` would be ignored and why. An integer of more than 4,300 digits
  makes a file invalid, as it does for the evaluator, whatever Python runs the check. Rows for
  studies of protocols that were not requested are an error: the contract allows rows only for
  requested studies.
- `submit` checks the parameters against the benchmark version before uploading anything
  and sends them in the `fora_parameters` field, as the web form does. Defaults: every
  enabled task, every protocol enabled for every selected task, the clinical judge on,
  publication under your pseudonym. On a benchmark version without a clinical judge, `submit`
  says so in one line (a warning, so under `--json` on stderr) and sends the judge off;
  `--judge` is then refused (exit code 4). With
  `--retry-of`, the failed run's tasks, protocols, judge and publication choices, compute
  tier, time budget and description are reused unless given; a run whose error says it
  cannot be retried is refused before the upload.
- **Charges.** Before uploading, `submit` reads the benchmark's current configuration (if
  that fails, nothing is sent) and shows the full pre-charge: the inference estimate (tier
  price times time budget) plus the evaluation charge the platform states for the phase
  (0 when the platform pays for the evaluation). The evaluation charge is kept when the
  run is scored and refunded when it is not. When the platform cannot bill the phase's
  evaluation, or refuses submissions to the phase, `submit` stops with its reason. Nothing
  is sent until you confirm at the prompt or pass `--max-charge` (a finite amount of at least
  0), which is compared with the total to the 4 decimals billing keeps; without a terminal
  (scripts, agents) `--max-charge` is required. `--time-budget` is at least 5 minutes, the
  platform's minimum. When the platform refuses the upload itself, for example because your
  balance does not cover the evaluation share, `submit` shows the platform's sentence and stops
  with exit code 7, saying whether a weights file had already been uploaded.
- `status` and `results` show the stages, the error with what to do, and every metric with
  its interval, in its unit: proportions and scores as percentages, the clinical judge's
  counts per judged report (for example significant errors per report) as plain numbers;
  values that are not requested, not defined or withheld are stated as such, never shown as
  0. When the evaluator set studies aside (a report longer than the limit, or with invalid
  characters; each is scored as a failed report), they say how many and why; under `--json`
  the task's `coverage` carries `n_set_aside` and `set_aside_reasons`.

FORA options are refused on other benchmarks (exit code 4), whose commands behave as before.

## Machine-readable output (`--json`)

`init`, `generate`, `test`, `submit`, `status`, `results`, `leaderboard`, `whoami` and
`tiers` accept `--json`. The command then prints exactly one JSON object on stdout and
nothing else (no progress, tables or animation) apart from warnings on stderr, for example
that `status --wait` could not reach the platform and tries again; it never prompts:

```json
{"ok": true, "command": "status", "data": {"submission_id": "...", "status": "running", "terminal": false, "fora": {"stages": [...], "error": null, "tasks": null}}}
{"ok": false, "command": "submit", "error": {"code": "confirmation_required", "message": "...", "details": [], "charge": {...}}}
```

| Exit code | Meaning |
|---|---|
| 0 | Success (`status`: scored or still running) |
| 1 | Any other failure |
| 2 | Invalid command line |
| 3 | Not logged in or session ended: run `forithmus login` |
| 4 | Invalid FORA parameters (including a `--max-charge` that is not a finite amount of at least 0, a `--time-budget` below 5 minutes, a compute tier that is not offered, or `--judge` on a benchmark version without a clinical judge), FORA options on another benchmark, or a local configuration without the FORA settings of a FORA benchmark (run `forithmus init` again); nothing uploaded |
| 5 | The run ended without a score (failed, timed out, cancelled) |
| 6 | The run has not finished (`results`), or `status --wait --wait-timeout` gave up |
| 7 | FORA submit stopped at the charge: not confirmed (no `--max-charge`, or above it), or the platform cannot bill the phase's evaluation or refuses its submissions, also when it refuses the upload itself (error `payment_required` with the platform's sentence); the Docker image was not uploaded, and `weights_uploaded` says whether a weights file was |
| 130 | Interrupted (Ctrl+C); `--json` prints the error `interrupted`, or `submission_unconfirmed` when the final submit call was under way |

A command line that Click rejects before the command starts (an unknown option, a value of
the wrong type or out of range: exit code 2) and `--help` print no JSON object. A refusal of
the final submit call, after the upload, is the error `submission_rejected` with the
platform's message, `http_status` and `uploaded: true`; an answer of 500 or more is a refusal
only when it is the platform's own, a JSON body whose `detail` gives the reason (for example
that submissions to the benchmark are closed).

`submit` and `leaderboard` stop with exit code 1 when the phase cannot be chosen:
`phase_not_found` (the phase given with `--phase` or stored by `init` does not exist, or the
benchmark has no phases), `phase_not_current` (`submit` only: the phase belongs to an earlier
edition than the benchmark's current one) or `phase_ambiguous` (the current edition has several
phases and none was chosen). `details` lists the phases to choose from, or what to do; pass
`--phase <slug-or-id>` or run `forithmus init` again.

**`submission_unconfirmed` (exit code 1, or 130 after Ctrl+C): the run may exist.** The image
was uploaded and the final submit call was sent, but its answer was lost: a dropped connection,
a read timeout, an answer of 500 or more that is not the platform's own (a proxy's or gateway's,
for example HTTP 502, 504, 520 or 524, or the plain text of an unhandled error; `http_status`
gives the code), or Ctrl+C while the call was under way. So it is not known whether the platform
created the run. Do not submit again until you have looked: a second submission would start and
charge a second run. With `--weights` the platform reserves the run's id before the call and
`submission_id` names it; after a lost answer (not after Ctrl+C) `submit` looks that run up
itself and reports it as the result when it exists; otherwise run
`forithmus status <submission_id>` a few minutes later. Without `--weights` there is no id
to look up: look for the run on the benchmark's Submissions page (`submissions_url`). When the
call never reached the platform (the connection could not be made), no run exists and the error
is `connection_error`, with `uploaded: true`. When the platform answers that the uploaded image
already produced a run (HTTP 409 with its id), `submit` reports that run as its result, with a
`note` saying so; `note` is null for an ordinary submission.

Authentication is the browser login: a person runs `forithmus login` once and the stored
session in `~/.forithmus/credentials.json` renews itself while it is used. The benchmark
commands accept no API keys or personal access tokens, so a CI job without a person cannot
use them (the keys of the model interface, below, work only for its commands).

## Model interface (`predict`, `predictions`, `studies`, `batches`, `usage`)

The FORA models read a CT or chest X-ray study and return a report, findings with their
probabilities, and measurements. `pip install forithmus` installs these commands and the Python
client `forithmus`. Both talk to `https://api.forithmus.com/v1` (another address goes in the
environment variable `FORITHMUS_BASE_URL`) with an API key, which you create at
https://api.forithmus.com/console/keys; a key is shown once, when it is created.

| Model | Takes |
|---|---|
| `fora` | a CT study (the default; the same model as `fora-ct`) |
| `fora-ct` | a CT study |
| `fora-cxr` | a chest X-ray study |

A study is a DICOM file, a folder of DICOM files (sent as one zip), a zip or tar archive, or a
NIfTI file (`.nii`, `.nii.gz`). A study of the kind the model does not take fails and is refunded
in full. The prices are on https://api.forithmus.com/console/billing, where credit is added, and
in `client.models.list()`; every command that costs money shows the price before it uploads or
sends anything.

### Python

```python
import forithmus

client = forithmus.Client("your-api-key")
result = client.analyze(model="fora", image="path/to/scan.dcm")
print(result.report)
for finding in result.findings:
    print(finding.name, finding.probability, finding.tier)   # tier: confident, possible or none
```

`analyze` uploads the study, creates the prediction, waits until it has finished and returns the
result: `report` (the report text), `findings`, `measurements`, `warnings`, `model`, `modality`,
`release` (the model release that answered) and `cost`; `raw` is the whole document as received.
`client.batches.create(["ct_0001", "ct_0002.zip"], model="fora")` sends several studies as one
batch, `client.predictions.get("pred_…")` reads a prediction again, and `client.models.list()`
lists the models with their prices. Keep the key out of the code, for example in
`FORITHMUS_API_KEY`.

### Command line

```bash
export FORITHMUS_API_KEY=...                  # or --api-key on each command
forithmus predict ./ct_study_0042             # a file, or a folder (sent as one uncompressed zip)
forithmus predict chest.dcm --model fora-cxr
forithmus predict study.zip --study-type ct_chest --json --max-charge <USD>
forithmus predictions list [--status succeeded] [--limit 50] [--after <prediction-id>]
forithmus predictions get|result|cancel|delete <prediction-id>
forithmus studies list [--after <study-id>]
forithmus studies upload ./ct_study_0043      # upload only, for an entry of a batch
forithmus studies get|delete <study-id>
forithmus batches create --entries entries.json [--max-charge 20.00] [--yes] [--metadata KEY=VALUE]
forithmus batches list [--limit 20] [--after <batch-id>]
forithmus batches get|cancel <batch-id>
forithmus batches results <batch-id> [--output results.jsonl] [--force]
forithmus batches delete <batch-id> [--yes]
forithmus usage [--days 7]
```

- **Key.** `--api-key`, otherwise the environment variable `FORITHMUS_API_KEY`; without one the
  command stops with `api_key_required` (exit code 3) before it sends anything. The login of the
  commands above is not used here. The key is never printed or written to a file.
  `FORITHMUS_BASE_URL` must be https (plain http only for localhost).
- **A refused key or account** is told in the tool's own words, with what to do:
  `invalid_api_key` (a key is shown only once; a lost one is replaced by a new one at
  https://api.forithmus.com/console/keys), `key_revoked` and `key_expired` (create a new key
  there and set it in `FORITHMUS_API_KEY`), `account_disabled` (it can still read
  what is its own and cancel, delete and revoke, but not create or spend; ask Forithmus) and
  `scope_not_allowed` (the command needs a key with the scope `predict`). Under `--json` the
  interface's own sentence is the error's `server_message`.
- **Lists.** `predictions list`, `studies list` and `batches list` show one page, newest first;
  when more follow, they name the `--after` that lists the next page.
- **Price.** `predict` shows the model's price of one study and your balance, and uploads nothing until you accept the price at the prompt, with `--yes`, or with
  `--max-charge` (at most that many US dollars). Without a terminal, or with `--json`, one of
  the two options is required. The `--max-charge` amount also goes with the request that
  creates the prediction, and the server refuses it (`price_above_max_charge`) if the price is
  higher by then. Before anything is uploaded, `predict` also stops when your balance is below
  the price (`insufficient_credit`, exit code 7; add credit at
  https://api.forithmus.com/console/billing), and when `--metadata` or
  `--study-type` break the interface's documented limits (exit code 2); the server checks both
  again at the creation.
- **Upload and result.** The study goes to storage in pieces of 64 MiB; after a failed piece the
  upload continues from where it stopped. `predict` then follows the prediction while it is
  queued, preparing or running (`--no-wait` stops once it is created; `--timeout`, default 120
  minutes) and saves the result as received, by default beside the study as
  `<name>.prediction.json` (`--output`, `--force`): the report text, the findings with their
  probabilities and tiers, and the measurements. It shows how many findings the result holds and
  how many of them are confident and possible, how many measurements and lesion sizes, and
  whether it holds a report; it names no finding. `predictions get` shows the model with its
  modality and, once the model has answered, its release. When
  it ends without the result once the prediction is created (a refusal while waiting,
  `--timeout`, a failed request for the result, Ctrl+C), the message names the prediction
  (`--json`: `prediction_id`) and the commands that follow it and fetch its result; running
  `predict` again would create and charge a new one.
- **Batches.** `batches create` predicts several studies that are already uploaded and ready
  (`studies upload` uploads one without predicting it, and prints its identifier),
  all or nothing. `entries.json` is a JSON array of the entries, sent as written:
  `[{"custom_id": "case-0042", "study": "study_…", "study_type": "ct_chest"}, …]` (`custom_id`
  is your own name of the entry, unique in the batch; `study_type` and `metadata` are
  optional). The total (the model's price of one study times the entries) and your balance are
  shown, and nothing is sent until you accept it, as for `predict`; `--max-charge`
  is the most the whole batch may cost. Once `batches get` shows the status `ended`,
  `batches results` fetches one JSON object per line, one line per entry in the order of the
  file, and prints how the entries ended; `batches delete` deletes the results of every entry.
- **Usage.** `usage` shows your predictions per UTC day (batch entries included), the oldest
  first: how many were created, succeeded, failed and were cancelled, what they were charged
  and refunded, and the totals (`--days`, default the server's 30).
- **`--json` and exit codes.** Every one of these commands accepts `--json`, with the rule of
  the other commands: one JSON object on stdout and nothing else but warnings on stderr (a
  request or a piece of the upload sent again, a warning of the result, a result of a batch's
  entry that could not be read now). Under `--json`, `predictions result` without `--output`
  returns the result in the data's field `result`, and `batches results` returns the lines as
  the list `results`. Exit codes: 3 no valid API key; 5 the prediction failed or was cancelled;
  6 still running after `--timeout`; 7 stopped at the price (not accepted, above `--max-charge`
  here or at the server: `price_above_max_charge`, or not covered by the balance:
  `insufficient_credit`); 130 Ctrl+C, which ends the command without a result (`--json`: the
  error `interrupted`, or `prediction_unconfirmed` or `batch_unconfirmed` while the creation was
  under way). At a question (the price, a deletion) Ctrl+C ends the command as a refusal
  instead, with exit code 1. A study the command announced and no prediction used is left on
  the server until it expires, at no charge. An error of the interface keeps its `code` and
  adds `request_id`, `http_status`, `type` and `param`. `prediction_unconfirmed` (or
  `batch_unconfirmed`) means that an answer to the request that creates the prediction (or the
  batch) was lost and no repeat with the same idempotency key (named in the message and in
  `idempotency_key`) brought a success, also when a repeat was refused: look with
  `forithmus predictions list` (or `forithmus batches list`) before running the command again.
