Notebooks
Run a first scan, a folder of scans with a budget, or a generation, cell by cell.
notebooks/quickstart.ipynb
Sign in, see the models, run one scan, wait, save the result and open it.
Nalvera.AI quickstart
Sign in, see the models, run one scan, wait, save the result and open it. The scan is anonymized on this computer before upload. Clear the outputs before you share this notebook: its tables hold your scans' original names.
# Install the package into this notebook's kernel once; remove the # to run it.
# %pip install nalveraA key typed into a cell is saved in the notebook file and in IPython's history file; nalvera.login() with no arguments asks for it instead.
import nalvera
nalvera.login("you@university.org", "nvk_...")The models you may run
nalvera.models()What the run costs, before anything is uploaded
SCAN = "ct_scan.nii.gz"
nalvera.estimate_run(
SCAN,
model="totalsegmentator_ct", # required. See: nalvera.models()
)Run it
This spends credits from the budget "personal"; free tasks are used first. Running the cell again returns the same task and charges nothing.
tasks = nalvera.run(
SCAN,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
tasksWait, then save the result under the scan's original name
finished = nalvera.wait(tasks)
finishedpaths = nalvera.download(finished, out="results") # default: "results"
pathsOpen the result
import nibabel as nib
import numpy as np
labels = np.asarray(nib.load(paths[0]).dataobj)
np.unique(labels)After a restart of the kernel, nalvera.tasks(), nalvera.wait() and nalvera.download() find the tasks and results again.
notebooks/many_scans_and_budgets.ipynb
Run every scan in a folder with a cost estimate, a budget and a spending cap.
Many scans, a cost estimate and a budget
Every scan in a folder, one task each. The scans are anonymized on this computer before upload. Clear the outputs before you share this notebook: its tables hold your scans' original names.
# Install the package into this notebook's kernel once; remove the # to run it.
# %pip install nalveraA key typed into a cell is saved in the notebook file and in IPython's history file; nalvera.login() with no arguments asks for it instead.
import nalvera
nalvera.login("you@university.org", "nvk_...")Free tasks, personal credits and labs
nalvera.budgets()What the folder costs, before anything is uploaded
FOLDER = "scans"
nalvera.estimate_run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
)Run every scan, with a spending cap
Free tasks pay first, the budget you name pays the rest. A run that would pass max_credits does not start.
result = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
max_credits=10, # default: None (NALVERA_MAX_CREDITS, else no cap)
)
resultFollow the queue
finished = nalvera.wait(result)
finishedSave every result
nalvera.download(finished, out="results") # default: "results"Where the record is
The record links each platform code to its scan's original name and stays on this computer.
nalvera.scans().pathnotebooks/generate_synthetic_ct.ipynb
Generate a synthetic CT with MAISI-v2 from settings, wait, save it and open it.
A synthetic CT with MAISI-v2
No input scan: the model makes a CT volume from settings.
# Install the package into this notebook's kernel once; remove the # to run it.
# %pip install nalveraA key typed into a cell is saved in the notebook file and in IPython's history file; nalvera.login() with no arguments asks for it instead.
import nalvera
nalvera.login("you@university.org", "nvk_...")The settings the task accepts
ct = next(task for model in nalvera.models() if model["id"] == "nv_generate_ctmr"
for task in model["tasks"] if task["id"] == "rflow-ct")
ct["generation"]Queue the generation
This spends credits from the budget "personal"; free tasks are used first. With a label, running the cell again returns the same task and queues nothing.
task = nalvera.generate(
model="nv_generate_ctmr", # required. See: nalvera.models()
task="rflow-ct", # required. Options: "rflow-ct" | "rflow-mr-brain"
params={
"mode": "image-only", # required. Options: "image-only" | "image-mask"
"output_size": [256, 256, 128], # required. Options: [X, X, Z], X from 128 | 256 |
# 384 | 512, Z from 128 | 256
"spacing": [1.5, 1.5, 2.0], # required. Options: [S, S, Sz] in mm, each 0.5 to 5.0;
# X times S at least 256 mm
"seed": 7, # default: 0. Options: 0 to 2147483647
},
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
label="phantom-01", # default: None (the file name starts with the task id)
)
taskWait and save it
finished = nalvera.wait(task)
finishedpaths = nalvera.download(finished, out="generated") # default: "results"
pathsOpen it
import nibabel as nib
volume = nib.load(paths[0])
volume.shape, volume.header.get_zooms()Sign in
Sign in with the email and the key, have the key asked for, store it, or read it from the environment.
set_api_key.py
Sign in to Nalvera.AI from Python, then check the sign-in.
"""Sign in to Nalvera.AI from Python, then check the sign-in.
Get a key: sign in at https://nalvera.ai, menu (⋮) → Settings → API, switch on API access and
create a key; tick "Run tasks and spend credits" to run tasks. The key is shown once.
Spends nothing. Run: python set_api_key.py
"""
import os
import nalvera
# 1. The email and the key as arguments. A key typed into a notebook cell is saved in the
# .ipynb file and in IPython's history file:
# nalvera.login("you@university.org", "nvk_...")
# 2. No key in the code: asks for the email and the key (hidden) when the notebook or the
# terminal can ask; nothing is saved in the notebook:
# nalvera.login()
# 3. Asked for as in 2, then stored on this computer, so later sessions need neither (the
# system keychain with "nalvera[keyring]" installed, else a file only you can read):
# nalvera.login(remember=True)
# 4. A cluster or a shared script: NALVERA_EMAIL and NALVERA_API_KEY in the environment,
# filled from a secret store; nalvera.login() and every function read them.
EMAIL = os.environ.get("NALVERA_EMAIL")
API_KEY = os.environ.get("NALVERA_API_KEY")
if EMAIL and API_KEY:
nalvera.login(EMAIL, API_KEY) # 1, with the values read at run time
else:
nalvera.login() # 2, or what 3 stored
me = nalvera.me()
expires, days_left = nalvera.key_expiry()
print("Signed in as", me["email"], "with key", me["key"]["prefix"], "until", (expires or "-")[:10])
# Sign out; forget=True also removes what remember=True stored:
# nalvera.logout(forget=True)Start
Check the sign-in, list the models and tasks you may run, and see your free tasks, budgets and limits.
sign_in_and_check_account.py
Check the sign-in and the account: plan, key, permissions, end date, free tasks, budgets.
"""Check the sign-in and the account: plan, key, permissions, end date, free tasks, budgets.
Needs a key (see set_api_key.py). Spends nothing.
Run: python sign_in_and_check_account.py
"""
import nalvera
nalvera.login() # an unknown, expired or revoked key raises here
me = nalvera.me()
key = me["key"]
expires, days_left = nalvera.key_expiry()
print("Account:", me["email"], "on plan", me["plan_label"])
print("Key:", key["prefix"], key["name"], "may:", ", ".join(key["scopes"]))
print("Key ends:", expires, "in", days_left, "days")
if "tasks:write" not in key["scopes"]:
print("This key may not run tasks: create one that may, under Settings → API.")
if me["terms_reaccept_required"]:
print("Accept the new Terms on nalvera.ai before queueing tasks.")
budgets = nalvera.budgets()
print("Free tasks left:", budgets["free"]["free_tasks_left"])
print("Personal credits:", budgets["personal"]["available_credits"])
print("Encrypted uploads:", nalvera.encryption())list_models_and_tasks.py
List the models this account may run, with each task, its price and what it needs.
"""List the models and tasks this account may run, with their prices.
Spends nothing.
Run: python list_models_and_tasks.py
"""
import nalvera
nalvera.login() # asks, or reads the environment
print(nalvera.models()) # a table: one row per task, with its pricecheck_budgets_and_free_tasks.py
Show your free tasks, personal credits and each lab's balance, and the suggested budget.
"""Show your free tasks, plan credits and top-up credits, each lab's balance and the suggested budget.
Free tasks are always used first, then plan credits, then top-up credits. Spends nothing.
Run: python check_budgets_and_free_tasks.py
"""
import nalvera
budgets = nalvera.budgets()
free = budgets["free"]
if free["period_active"]:
print("A free period is on: tasks cost nothing for now.")
print("Free tasks left:", free["free_tasks_left"], '(budget="free" uses only these)')
personal = budgets["personal"]
print('budget="personal":', personal["available_credits"], "credits:",
personal["plan_credits"], "plan credits and", personal["topup_credits"],
"top-up credits (these never expire)")
for lab in budgets["labs"]:
print(f'budget="lab:{lab["id"]}": {lab["name"]},', lab["balance"], "credits,",
lab["member_status"])
print("Suggested:", budgets["suggested"]) # the active lab with the most credits, else personalshow_limits.py
Show the limits of your key. The package stays within them and waits when the platform asks.
"""Show the limits of your key. The package stays within them and waits when the platform asks.
Spends nothing.
Run: python show_limits.py
"""
import nalvera
for name, value in nalvera.limits().items():
print(f"{name}: {value}")One scan
Run one scan, with a label or several tasks, and mix files and folders in one run.
run_one_scan.py
Segment one CT scan with TotalSegmentator, wait for the task and save the result.
"""Segment one CT scan with TotalSegmentator, wait for the task and save the result.
Spends credits: one task, budget "personal" (free tasks are used first).
Sign in first: nalvera.login(email, api_key).
"""
import nalvera
SCAN = "ct_scan.nii.gz"
nalvera.login() # asks for the email and the key, or reads NALVERA_EMAIL and
# NALVERA_API_KEY, or what login(..., remember=True) stored
tasks = nalvera.run(
SCAN, # a .nii or .nii.gz file, a folder of them, a DICOM folder
model="totalsegmentator_ct", # required. See: nalvera.models()
task="total", # default: None (the model's default task).
# Options: the tasks nalvera.models() lists
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
finished = nalvera.wait(tasks) # shows queue position, time waited, time running
paths = nalvera.download(
finished,
out="results", # default: "results"
)
print(paths) # results/ct_scan__totalsegmentator_ct__total.nii.gzrun_uncompressed_nii.py
Run a scan stored as an uncompressed .nii file.
"""Run a scan stored as an uncompressed .nii file.
The anonymized copy is always compressed (.nii.gz) on this computer before upload. Spends
credits: one task, budget "personal". Run: python run_uncompressed_nii.py
"""
import nalvera
SCAN = "ct_scan.nii"
tasks = nalvera.run(
SCAN,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"run_one_scan_with_label.py
Run one scan with a label, which the platform shows in place of the scan's code.
"""Run one scan with a label, which the platform shows in place of the scan's code.
The label leaves this computer: choose one that does not identify a patient. Spends credits:
one task, budget "personal". Run: python run_one_scan_with_label.py
"""
import nalvera
SCAN = "ct_scan.nii.gz"
tasks = nalvera.run(
SCAN,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
label="S012 baseline", # default: None (the platform shows the scan's code).
# 1 to 60 letters, digits, spaces, dots, dashes, underscores
)
print("The platform shows:", tasks[0].name) # S012_baseline.nii.gz
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"run_one_scan_several_tasks.py
Run several tasks of one model on the same scan.
"""Run several tasks of one model on the same scan.
One run per task: an upload serves one task, so the scan is anonymized and uploaded once per
task. Spends credits: one task each, budget "personal". Run: python run_one_scan_several_tasks.py
"""
import nalvera
SCAN = "ct_scan.nii.gz"
MODEL = "totalsegmentator_ct"
TASKS = ["total", "lung_vessels", "body"]
queued = []
for task in TASKS:
queued += nalvera.run(
SCAN,
model=MODEL, # required. See: nalvera.models()
task=task, # default: None (the model's default task).
# Options: the tasks nalvera.models() lists
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
finished = nalvera.wait(queued)
nalvera.download(finished, out="results") # default: "results"run_mixed_inputs.py
Run one model on a mix of inputs at once: NIfTI files, a NIfTI folder, a DICOM folder.
"""Run one model on a mix of inputs at once: NIfTI files, a NIfTI folder, a DICOM folder.
One folder holding both NIfTI and DICOM files is refused (mixed_folder): pass the parts as
separate paths. Spends credits: one task per scan, budget "personal".
Run: python run_mixed_inputs.py
"""
import nalvera
PATHS = ["ct_scan.nii.gz", "ct_scan_2.nii", "scans", "dicom_folder"]
tasks = nalvera.run(
PATHS,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
yes=True, # default: False (asks, or stops, when a DICOM folder holds
# several scans). Options: True | False
)
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"DICOM
Run DICOM folders with one or several series, and see what a folder becomes before anything is uploaded.
run_dicom_folder.py
Run TotalSegmentator on a DICOM folder holding one series.
"""Run TotalSegmentator on a DICOM folder holding one series.
The series is converted to NIfTI and anonymized on this computer: no DICOM tag is uploaded.
Spends credits: one task, budget "personal". Run: python run_dicom_folder.py
"""
import nalvera
FOLDER = "dicom_folder" # its subfolders are searched too
tasks = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
for task in tasks:
print(task.original_name, "is", task.code, "on the platform")
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"
# Saved as results/dicom_folder_<series>__totalsegmentator_ct__total.nii.gzrun_dicom_several_series.py
Run TotalSegmentator on a DICOM folder holding several series: one task per series.
"""Run TotalSegmentator on a DICOM folder holding several series: one task per series.
Spends credits: one task per series, budget "personal". inspect_dicom_before_running.py shows
the series first.
"""
import nalvera
FOLDER = "dicom_study"
tasks = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
yes=True, # default: False (asks, or stops, when a DICOM folder holds
# several scans). Options: True | False
)
print(len(tasks), "series queued")
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"
# Saved as results/dicom_study_<series>__totalsegmentator_ct__total.nii.gzrun_dicom_subjects_in_subfolders.py
Run a folder with one DICOM subfolder per subject, so each result carries its subject.
"""Run a folder with one DICOM subfolder per subject, so each result carries its subject.
Each subfolder is given as its own path: results are named <subfolder>_<series>__... .
Spends credits: one task per series, budget "personal".
Run: python run_dicom_subjects_in_subfolders.py
"""
from pathlib import Path
import nalvera
FOLDER = Path("dicom_subjects") # dicom_subjects/subject_01/, dicom_subjects/subject_02/
subjects = sorted(p for p in FOLDER.iterdir() if p.is_dir())
tasks = nalvera.run(
subjects,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
yes=True, # default: False (asks, or stops, when a DICOM folder holds
# several scans). Options: True | False
)
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"inspect_dicom_before_running.py
See what a DICOM folder would become before anything is uploaded: its scans and shapes.
"""See what a DICOM folder would become before anything is uploaded: its scans and shapes.
Converts in a private temporary folder and removes it. Needs no key; spends nothing.
With prices: nalvera.estimate_run("dicom_study", model="totalsegmentator_ct").
Run: python inspect_dicom_before_running.py
"""
from nalvera.anonymize import inspect
FOLDER = "dicom_study"
found = inspect(
FOLDER,
convert=True, # default: False (counts the DICOM files only). Options: True | False
)
print(found.kind, "folder with", found.dicom_files, "DICOM files and", len(found.scans), "scans")
for scan in found.scans:
print("series", scan.series, "shape", scan.shape, "corrected:", scan.corrections or "-")
for volume in found.dropped:
print("left out: series", volume.series, f"({volume.reason}); used instead:", volume.kept)
if found.left_out:
print(found.left_out, "files are in no scan: screenshots, scouts, derived images")Many scans
Run a folder or a cohort, write a summary file, and queue each new scan once.
run_folder_of_scans.py
Run TotalSegmentator on every NIfTI file at the top level of a folder: one task each.
"""Run TotalSegmentator on every NIfTI file at the top level of a folder: one task each.
Spends credits: one task per scan, budget "personal". A scan that cannot be read is listed in
result.failed and the others go on.
"""
import nalvera
FOLDER = "scans"
result = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
for failure in result.failed:
print("Not queued:", failure.original_name, failure.code)
nalvera.download(nalvera.wait(result), out="results") # default: "results"run_many_scans.py
Run TotalSegmentator on many scans with a named budget and a spending cap.
"""Run TotalSegmentator on many scans with a named budget and a spending cap.
Spends credits from the budget "personal" and queues no task that would pass MAX_CREDITS: a run
whose estimate passes the cap does not start. Two scans upload at a time.
Run: python run_many_scans.py
"""
from pathlib import Path
import nalvera
SCANS = sorted(Path("cohort").glob("**/*.nii.gz")) # any list of paths
MAX_CREDITS = 50
result = nalvera.run(
SCANS,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
max_credits=MAX_CREDITS, # default: None (NALVERA_MAX_CREDITS, else no cap)
)
print(len(result), "queued,", result.charged_credits, "credits charged")
for scan in result.failed + result.not_queued:
print("Not queued:", scan.original_name, scan.code)
nalvera.download(nalvera.wait(result), out="results") # default: "results"
# Two scans with one name are saved with their folder's name in front.run_cohort_with_summary_csv.py
Run a cohort and write summary.csv: original name, code, task id, state, result file.
"""Run a cohort and write summary.csv: original name, code, task id, state, result file.
Spends credits from the budget "personal" and queues no task that would pass MAX_CREDITS. The
codes are what the platform shows; the original names stay on this computer.
Run: python run_cohort_with_summary_csv.py
"""
import csv
import nalvera
FOLDER = "cohort"
MAX_CREDITS = 50
result = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
max_credits=MAX_CREDITS, # default: None (NALVERA_MAX_CREDITS, else no cap)
)
with open("summary.csv", "w", newline="", encoding="utf-8") as fh:
writer = csv.writer(fh)
writer.writerow(["original_name", "code", "task_id", "state", "result_path"])
for task in nalvera.wait(result):
saved = []
if task.state == "completed":
saved = nalvera.download(task, out="results") # default: "results"
writer.writerow([task.original_name, task.code, task.id, task.state,
saved[0] if saved else ""])
for scan in result.failed + result.not_queued:
writer.writerow([scan.original_name, "", "", scan.code, ""])watch_folder_for_new_scans.py
Queue each new scan in a folder once. Run it on a schedule, for example every 10 minutes.
"""Queue each new scan in a folder once. Run it on a schedule, for example every 10 minutes.
Each run spends credits (budget "personal") on at most MAX_TASKS scans and queues no task that
would pass MAX_CREDITS; STATE lists what was queued. A file still being copied fails this run and
is tried in the next. Run: python watch_folder_for_new_scans.py
"""
import json
from pathlib import Path
import nalvera
INBOX = Path("inbox")
STATE = Path("inbox_state.json")
MAX_TASKS = 20
MAX_CREDITS = 25
done = set(json.loads(STATE.read_text())) if STATE.exists() else set()
new = [p for p in sorted(INBOX.glob("*.nii.gz")) if p.name not in done][:MAX_TASKS]
if new:
result = nalvera.run(
new,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
max_credits=MAX_CREDITS, # default: None (NALVERA_MAX_CREDITS, else no cap)
)
done.update(Path(scan.original_path).name for scan in result.skipped)
done.update(task.original_name for task in result)
STATE.write_text(json.dumps(sorted(done)))
print(len(result), "queued. nalvera.wait() follows them.")Each model
Run each model of the platform with its own tasks.
segment_ct_totalsegmentator.py
Segment a CT scan with TotalSegmentator: the full body (default task) and the lung vessels.
"""Segment a CT scan with TotalSegmentator: the full body (default task) and the lung vessels.
Spends credits: two tasks, budget "personal". Lists the model's tasks first.
Run: python segment_ct_totalsegmentator.py
"""
import nalvera
SCAN = "ct_scan.nii.gz"
MODEL = "totalsegmentator_ct"
TASKS = ["total", "lung_vessels"] # "total" is the default task
model = next(m for m in nalvera.models() if m["id"] == MODEL)
for task in model["tasks"]:
print(task["id"], "(default)" if task["default"] else "", task["name"])
for task in TASKS:
tasks = nalvera.run(
SCAN,
model=MODEL, # required. See: nalvera.models()
task=task, # default: None (the model's default task).
# Options: the tasks nalvera.models() lists
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"segment_mr_totalsegmentator.py
Segment an MRI scan with TotalSegmentator MRI: the full body (default task) and the vertebrae.
"""Segment an MRI scan with TotalSegmentator MRI: the full body (default task) and the vertebrae.
Spends credits: two tasks, budget "personal". Lists the model's tasks first.
Run: python segment_mr_totalsegmentator.py
"""
import nalvera
SCAN = "mr_scan.nii.gz"
MODEL = "totalsegmentator_mr"
TASKS = ["total_mr", "vertebrae_mr"] # "total_mr" is the default task
model = next(m for m in nalvera.models() if m["id"] == MODEL)
for task in model["tasks"]:
print(task["id"], "(default)" if task["default"] else "", task["name"])
for task in TASKS:
tasks = nalvera.run(
SCAN,
model=MODEL, # required. See: nalvera.models()
task=task, # default: None (the model's default task).
# Options: the tasks nalvera.models() lists
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"segment_ct_moose.py
Segment a CT scan with MOOSE: the organs (default task) and the lung lobes.
"""Segment a CT scan with MOOSE: the organs (default task) and the lung lobes.
Spends credits: two tasks, budget "personal". Lists the model's tasks first.
Run: python segment_ct_moose.py
"""
import nalvera
SCAN = "ct_scan.nii.gz"
MODEL = "moose_v3_clinical"
TASKS = ["clin_ct_organs", "clin_ct_lungs"] # "clin_ct_organs" is the default task
model = next(m for m in nalvera.models() if m["id"] == MODEL)
for task in model["tasks"]:
print(task["id"], "(default)" if task["default"] else "", task["name"])
for task in TASKS:
tasks = nalvera.run(
SCAN,
model=MODEL, # required. See: nalvera.models()
task=task, # default: None (the model's default task).
# Options: the tasks nalvera.models() lists
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"segment_mr_muscles_musclemap.py
Segment the muscles of a whole-body MRI scan with MuscleMap (one task: wholebody).
"""Segment the muscles of a whole-body MRI scan with MuscleMap (one task: wholebody).
Spends credits: one task, budget "personal".
"""
import nalvera
SCAN = "mr_scan.nii.gz"
tasks = nalvera.run(
SCAN,
model="musclemap", # required. See: nalvera.models()
task="wholebody", # default: None (the model's default task).
# Options: the tasks nalvera.models() lists
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"segment_ct_nv_segment.py
Segment a CT scan with NV-Segment-CT: 117 structures (default task) and the airway.
"""Segment a CT scan with NV-Segment-CT: 117 structures (default task) and the airway.
Spends credits: two tasks, budget "personal". Lists the model's tasks first.
Run: python segment_ct_nv_segment.py
"""
import nalvera
SCAN = "ct_scan.nii.gz"
MODEL = "nv_segment_ct"
TASKS = ["everything", "airway"] # "everything" is the default task
model = next(m for m in nalvera.models() if m["id"] == MODEL)
for task in model["tasks"]:
print(task["id"], "(default)" if task["default"] else "", task["name"])
for task in TASKS:
tasks = nalvera.run(
SCAN,
model=MODEL, # required. See: nalvera.models()
task=task, # default: None (the model's default task).
# Options: the tasks nalvera.models() lists
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"segment_mr_mrsegmentator.py
Segment an MRI scan with MRSegmentator: the anatomy (default task) and the body composition.
"""Segment an MRI scan with MRSegmentator: the anatomy (default task) and the body composition.
Spends credits: two tasks, budget "personal". For a CT scan use the task "anatomy_ct".
Run: python segment_mr_mrsegmentator.py
"""
import nalvera
SCAN = "mr_scan.nii.gz"
MODEL = "mrsegmentator"
TASKS = ["anatomy", "body_comp"] # MRI tasks; "anatomy" is the default task
model = next(m for m in nalvera.models() if m["id"] == MODEL)
for task in model["tasks"]:
print(task["id"], "/".join(task["modality"]), "(default)" if task["default"] else "")
for task in TASKS:
tasks = nalvera.run(
SCAN,
model=MODEL, # required. See: nalvera.models()
task=task, # default: None (the model's default task).
# Options: the tasks nalvera.models() lists
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"ct_findings_and_text_query_merlin.py
Ask Merlin about an abdominal CT: its findings as text, and how well a text query matches.
"""Ask Merlin about an abdominal CT: its findings as text, and how well a text query matches.
Spends credits: two tasks, budget "personal". The query task needs text= (needs_text).
Run: python ct_findings_and_text_query_merlin.py
"""
import numpy as np
import nalvera
SCAN = "ct_scan.nii.gz"
queued = []
for task, text in [("phenotype", None), ("contrastive", "pleural effusion")]:
queued += nalvera.run(
SCAN,
model="merlin", # required. See: nalvera.models()
task=task, # default: None (the model's default task, phenotype).
# Options: the tasks nalvera.models() lists
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
text=text, # default: None. Required by a task with needs_text
)
for path in nalvera.download(nalvera.wait(queued), out="results"): # default: "results"
if path.suffix == ".txt": # phenotype, report, five_year_prediction
print(path.read_text(encoding="utf-8"))
elif path.suffix == ".npy": # contrastive, image_embedding
print("similarity:", np.load(path))ct_report_nv_reason.py
Get structured chest and abdominal reports for a CT scan from NV-Reason-CT, as text.
"""Get structured chest and abdominal reports for a CT scan from NV-Reason-CT, as text.
Spends credits: two tasks, budget "personal". The tasks chest_reasoning and
abdomen_reasoning give reasoning walkthroughs. Run: python ct_report_nv_reason.py
"""
import nalvera
SCAN = "ct_scan.nii.gz"
TASKS = ["chest_report", "abdomen_report"] # "chest_report" is the default task
queued = []
for task in TASKS:
queued += nalvera.run(
SCAN,
model="nv_reason_ct", # required. See: nalvera.models()
task=task, # default: None (the model's default task).
# Options: the tasks nalvera.models() lists
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
for task in nalvera.wait(queued):
if task.state == "completed" and task.output_kind == "text":
for path in nalvera.download(task, out="results"): # default: "results"
print(f"-- {task.task} --")
print(path.read_text(encoding="utf-8"))Generation
Generate synthetic CT and brain MRI, download one file of the result, and learn the cost first.
generate_ct.py
Generate a synthetic CT volume with MAISI-v2 (no input scan), wait and save it.
"""Generate a synthetic CT volume with MAISI-v2 (no input scan), wait and save it.
Spends credits: one task, budget "personal". Every setting with its range:
nalvera.models() (each task's generation). Run: python generate_ct.py
"""
import nalvera
nalvera.login() # asks, or reads the environment
task = nalvera.generate(
model="nv_generate_ctmr", # required. See: nalvera.models()
task="rflow-ct", # required. Options: "rflow-ct" | "rflow-mr-brain"
params={
"mode": "image-only", # required. Options: "image-only" | "image-mask"
"output_size": [256, 256, 128], # required. Options: [X, X, Z], X from 128 | 256 |
# 384 | 512, Z from 128 | 256
"spacing": [1.5, 1.5, 2.0], # required. Options: [S, S, Sz] in mm, each 0.5 to 5.0;
# X times S at least 256 mm
"num_output_samples": 1, # default: 1. Options: 1 to 64
"seed": 7, # default: 0. Options: 0 to 2147483647
"num_inference_steps": 30, # default: 30. Options: 1 to 1000
},
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
label="phantom-01", # default: None (the file name starts with the task id)
)
finished = nalvera.wait([task])
paths = nalvera.download(finished, out="generated") # default: "results"
print(paths) # generated/phantom-01__nv_generate_ctmr__rflow-ct.nii.gzgenerate_ct_with_mask.py
Generate a synthetic CT with its anatomy label map (MAISI-v2, mode image-mask).
"""Generate a synthetic CT with its anatomy label map (MAISI-v2, mode image-mask).
The result has two files, image and mask: download_one_part_of_a_generation.py fetches one.
Spends credits: one task, budget "personal". Run: python generate_ct_with_mask.py
"""
import nalvera
task = nalvera.generate(
model="nv_generate_ctmr", # required. See: nalvera.models()
task="rflow-ct", # required. Options: "rflow-ct" | "rflow-mr-brain"
params={
"mode": "image-mask", # required. Options: "image-only" | "image-mask"
"body_region": ["abdomen"], # required for image-mask, one region. Options: "head" |
# "chest" | "thorax" | "abdomen" | "pelvis" | "lower"
"anatomy_list": [], # default: [] (no tumor). Options: in the abdomen,
# "hepatic tumor" | "pancreatic tumor" |
# "colon cancer primaries" | "bone lesion"
"output_size": [512, 512, 128], # required. Options: [X, X, Z], X from 128 | 256 |
# 384 | 512, Z from 128 | 256
"spacing": [0.781, 0.781, 2.981], # required. Options: [S, S, Sz] in mm, each 0.5
# to 5.0; X times S at least 256 mm
"seed": 11, # default: 0. Options: 0 to 2147483647
},
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
label="abdomen-mask-01", # default: None (the file name starts with the task id)
)
finished = nalvera.wait([task])
print(finished[0].parts) # ['image', 'mask']
print(nalvera.download(finished, out="generated")) # default: "results"generate_mr.py
Generate a synthetic brain MRI volume (T1) with MAISI-v2, wait and save it.
"""Generate a synthetic brain MRI volume (T1) with MAISI-v2, wait and save it.
Spends credits: one task, budget "personal". Settings and ranges as the platform lists them:
nalvera.models() (each task's generation). Run: python generate_mr.py
"""
import nalvera
nalvera.login() # asks, or reads the environment
task = nalvera.generate(
model="nv_generate_ctmr", # required. See: nalvera.models()
task="rflow-mr-brain", # required. Options: "rflow-ct" | "rflow-mr-brain"
params={
"mode": "image-only", # required. Options: "image-only" | "cross-contrast"
"contrasts": ["T1"], # required: one for image-only.
# Options: "T1" | "T2" | "FLAIR" | "SWI"
"skull_stripped": False, # default: False. Options: False | True
"output_size": [256, 256, 256], # required. Options: [X, X, Z], X from 128 | 256 |
# 384 | 512, Z from 128 | 256; Z 256 needs X 256
"spacing": [0.95, 0.95, 0.7], # required. Options: [S, S, Sz] in mm, each 0.5 to 5.0
"cfg_guidance_scale": 2.0, # default: 2.0. Options: 0.0 to 20.0
"num_output_samples": 1, # default: 1. Options: 1 to 64
"seed": 0, # default: 0. Options: 0 to 2147483647
"num_inference_steps": 30, # default: 30. Options: 1 to 1000
},
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
label="brain-t1-01", # default: None (the file name starts with the task id)
)
finished = nalvera.wait([task])
paths = nalvera.download(finished, out="generated") # default: "results"
print(paths) # generated/brain-t1-01__nv_generate_ctmr__rflow-mr-brain.nii.gzgenerate_mr_cross_contrast.py
Generate one synthetic brain MRI in several contrasts (MAISI-v2, mode cross-contrast).
"""Generate one synthetic brain MRI in several contrasts (MAISI-v2, mode cross-contrast).
One volume per contrast, in one task; the result is a .zip of them. Spends credits: one task,
budget "personal", priced per volume. Run: python generate_mr_cross_contrast.py
"""
import nalvera
task = nalvera.generate(
model="nv_generate_ctmr", # required. See: nalvera.models()
task="rflow-mr-brain", # required. Options: "rflow-ct" | "rflow-mr-brain"
params={
"mode": "cross-contrast", # required. Options: "image-only" | "cross-contrast"
"contrasts": ["T1", "T2", "FLAIR"], # required: two or more for cross-contrast.
# Options: "T1" | "T2" | "FLAIR" | "SWI"
"skull_stripped": True, # default: False. Options: False | True
"output_size": [256, 256, 128], # required. Options: [X, X, Z], X from 128 | 256 |
# 384 | 512, Z from 128 | 256; Z 256 needs X 256
"spacing": [0.95, 0.95, 1.4], # required. Options: [S, S, Sz] in mm, each 0.5 to 5.0
},
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
label="brain-set-01", # default: None (the file name starts with the task id)
)
finished = nalvera.wait([task])
print(finished[0].parts) # ['image', 'image2', 'image3']
print(nalvera.download(finished, out="generated")) # default: "results"generate_several_volumes.py
Generate several synthetic CT volumes in one task and unpack them.
"""Generate several synthetic CT volumes in one task and unpack them.
Spends credits: one task, budget "personal", priced per volume. The result is one .zip with a
file per volume. Run: python generate_several_volumes.py
"""
import zipfile
import nalvera
task = nalvera.generate(
model="nv_generate_ctmr", # required. See: nalvera.models()
task="rflow-ct", # required. Options: "rflow-ct" | "rflow-mr-brain"
params={
"mode": "image-only", # required. Options: "image-only" | "image-mask"
"output_size": [256, 256, 128], # required. Options: [X, X, Z], X from 128 | 256 |
# 384 | 512, Z from 128 | 256
"spacing": [1.5, 1.5, 2.0], # required. Options: [S, S, Sz] in mm, each 0.5 to 5.0;
# X times S at least 256 mm
"num_output_samples": 3, # default: 1. Options: 1 to 64
"seed": 100, # default: 0. Options: 0 to 2147483647
},
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
label="phantom-set", # default: None (the file name starts with the task id)
)
finished = nalvera.wait([task])
for archive in nalvera.download(finished, out="generated"): # default: "results"
with zipfile.ZipFile(archive) as files:
files.extractall("generated/phantom-set")
print(files.namelist())download_one_part_of_a_generation.py
Download one file of a generation that made several: here the mask of an image-mask CT.
"""Download one file of a generation that made several: here the mask of an image-mask CT.
Spends credits: one task, budget "personal". task.parts names the files.
"""
import nalvera
task = nalvera.generate(
model="nv_generate_ctmr", # required. See: nalvera.models()
task="rflow-ct", # required. Options: "rflow-ct" | "rflow-mr-brain"
params={
"mode": "image-mask", # required. Options: "image-only" | "image-mask"
"body_region": ["pelvis"], # required for image-mask, one region. Options: "head" |
# "chest" | "thorax" | "abdomen" | "pelvis" | "lower"
"output_size": [512, 512, 128], # required. Options: [X, X, Z], X from 128 | 256 |
# 384 | 512, Z from 128 | 256
"spacing": [0.781, 0.781, 2.981], # required. Options: [S, S, Sz] in mm, each 0.5
# to 5.0; X times S at least 256 mm
},
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
)
finished = nalvera.wait([task])
print("Parts:", finished[0].parts) # ['image', 'mask']
mask = nalvera.download(
finished,
out="generated", # default: "results"
part="mask", # default: None (every file, in one .zip).
# Options: the task's parts, such as "image" | "mask"
)
print(mask) # generated/<task id>__nv_generate_ctmr__rflow-ct__maskestimate_a_generation.py
Ask what a generation would cost, and whether a free task pays for it, before queueing it.
"""Ask what a generation would cost, and whether a free task pays for it, before queueing it.
Needs a key; spends nothing. A setting the platform refuses raises InvalidRequest with its
explanation. Run: python estimate_a_generation.py
"""
import nalvera
estimate = nalvera.estimate(
"nv_generate_ctmr",
"rflow-mr-brain",
params={
"mode": "cross-contrast", # required. Options: "image-only" | "cross-contrast"
"contrasts": ["T1", "FLAIR"], # required: two or more for cross-contrast.
# Options: "T1" | "T2" | "FLAIR" | "SWI"
"output_size": [256, 256, 128], # required. Options: [X, X, Z], X from 128 | 256 |
# 384 | 512, Z from 128 | 256; Z 256 needs X 256
"spacing": [0.95, 0.95, 1.4], # required. Options: [S, S, Sz] in mm, each 0.5 to 5.0
},
)
print("Credits:", estimate["credits"])
print("A free task pays for it:", estimate["free"]["available"])
for option in estimate["budgets"]:
print(option["budget"], option["available_credits"], "enough" if option["sufficient"] else "")Paying
Estimate the cost, use free AI tasks only, pay from personal credits or a lab, and cap what a run may spend.
estimate_before_uploading.py
Learn what a run would cost before anything is uploaded: per scan, in total, per budget.
"""Learn what a run would cost before anything is uploaded: per scan, in total, per budget.
The scans are anonymized in a temporary folder and priced by their size; nothing is uploaded.
Needs a key; spends nothing.
"""
import nalvera
FOLDER = "scans"
estimate = nalvera.estimate_run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
task="total", # default: None (the model's default task).
# Options: the tasks nalvera.models() lists
)
for scan in estimate.scans:
print(scan.original_name, scan.shape, scan.credits, "credits")
print("Total:", estimate.credits, "credits;", estimate.free_count, "paid by free tasks;",
estimate.paid_credits, "credits for the rest")
for option in estimate.budgets:
mark = " (suggested)" if option["budget"] == estimate.suggested else ""
print(f'budget="{option["budget"]}":', option["available_credits"], "credits" + mark)use_free_tasks_only.py
Use free tasks only: queue what they pay for and stop when they run out. Charges nothing.
"""Use free tasks only: queue what they pay for and stop when they run out. Charges nothing.
Scans the free tasks do not cover are in result.not_queued; run them later with a budget.
"""
import sys
import nalvera
FOLDER = "scans"
try:
result = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="free", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
)
except nalvera.NoFreeTasks:
sys.exit("No free task is left: nothing was uploaded or charged.")
print(len(result), "queued for free;", len(result.not_queued), "wait for a budget")
for scan in result.not_queued:
print("Not queued:", scan.original_name)
nalvera.download(nalvera.wait(result), out="results") # default: "results"pay_from_personal_budget.py
Pay from your personal credits. The platform still uses your free tasks first.
"""Pay from your personal credits. The platform still uses your free tasks first.
Spends credits from the budget "personal".
"""
import nalvera
FOLDER = "scans"
result = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
for task in result:
print(task.original_name, "paid by", task.charged["source"], task.charged["credits"])
print(result.charged_credits, "credits charged in all")
nalvera.download(nalvera.wait(result), out="results") # default: "results"pay_from_lab_budget.py
Charge a lab's budget. Free tasks are still used first.
"""Charge a lab's budget. Free tasks are still used first.
Spends credits from the lab's budget; the lab's manager may set a limit per member.
"""
import nalvera
FOLDER = "scans"
LAB = "lab:12" # your labs and their budget names: nalvera.budgets()
for lab in nalvera.budgets()["labs"]:
print(f"lab:{lab['id']}", lab["name"], lab["balance"], "credits,", lab["member_status"])
result = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget=LAB, # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
print(result.charged_credits, "credits charged to", LAB)
nalvera.download(nalvera.wait(result), out="results") # default: "results"run_folder_lab_budget.py
Run a folder and charge the lab the website suggests: your active lab with the most credits.
"""Run a folder and charge the lab the website suggests: your active lab with the most credits.
Free tasks are still used first. Spends credits from that lab; with no active lab it stops
before uploading. Run: python run_folder_lab_budget.py
"""
import sys
import nalvera
FOLDER = "scans"
suggested = nalvera.budgets()["suggested"] # "lab:<id>", or "personal" without a lab
if not suggested.startswith("lab:"):
sys.exit("This account has no active lab: see pay_from_personal_budget.py.")
result = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget=suggested, # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
print(len(result), "queued,", result.charged_credits, "credits charged to", suggested)
nalvera.download(nalvera.wait(result), out="results") # default: "results"stop_at_a_spending_cap.py
Cap what a run may spend: a run whose estimate passes the cap does not start.
"""Cap what a run may spend: a run whose estimate passes the cap does not start.
Spends credits from the budget "personal"; queueing stops before a task would pass MAX_CREDITS.
For every run: NALVERA_MAX_CREDITS. Run: python stop_at_a_spending_cap.py
"""
import sys
import nalvera
FOLDER = "scans"
MAX_CREDITS = 10
try:
result = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
max_credits=MAX_CREDITS, # default: None (NALVERA_MAX_CREDITS, else no cap)
)
except nalvera.CreditCapExceeded as error:
sys.exit(f"Not started: it would cost {error.extra['estimate']} credits, "
f"more than the cap of {error.extra['max_credits']}.")
print(len(result), "queued,", result.charged_credits, "credits charged")
for scan in result.not_queued: # left out to stay under the cap
print("Not queued:", scan.original_name, scan.code)Queue
Queue now and collect later, follow the queue, list and cancel tasks, and run in the background.
queue_now_collect_later.py
Queue scans now and collect the results later, in a new process or on another day.
"""Queue scans now and collect the results later, in a new process or on another day.
The first run uploads, queues and writes the task ids to QUEUED; the next run waits for them
and downloads the results. Spends credits on the first run (budget "personal").
Run: python queue_now_collect_later.py (once now, once later)
"""
import json
from pathlib import Path
import nalvera
FOLDER = "scans"
QUEUED = Path("queued_tasks.json")
if not QUEUED.exists():
tasks = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
)
QUEUED.write_text(json.dumps([task.id for task in tasks]))
print(len(tasks), "queued. Run this script again later to collect the results.")
else:
finished = nalvera.wait(json.loads(QUEUED.read_text())) # ids work as well as tasks
nalvera.download(finished, out="results") # default: "results"
QUEUED.unlink() # names come from the record on this computerfollow_queue.py
Follow your waiting and running tasks: queue position, time waited, time running.
"""Follow your waiting and running tasks: queue position, time waited, time running.
Spends nothing. Checks no faster than your key allows (min_poll_seconds). For tasks you
hold, nalvera.wait(tasks) does the same.
"""
import time
import nalvera
pause = nalvera.limits()["min_poll_seconds"]
tasks = nalvera.tasks(state="active") # default: "all". Options: "active" | "finished" | "all"
while tasks:
for task in tasks:
print(f"{task.display_name}: {task.state}, position {task.queue_position},",
f"waited {task.waited_seconds} s, running {task.running_seconds} s")
time.sleep(pause)
tasks = [task for task in map(nalvera.task, tasks) if not task.finished]
print("No task is waiting or running.")cancel_tasks.py
Cancel every task your scripts queued that is still waiting or running.
"""Cancel every task your scripts queued that is still waiting or running.
A running task stops at the worker's next check. Refunds follow the website's rules. One
task: nalvera.cancel("TASK_ID").
"""
import nalvera
for task in nalvera.tasks(state="active"): # default: "all". Options: "active" | "finished" | "all"
if task.source == "api": # "web" for tasks queued on the website
task = nalvera.cancel(task)
print(task.display_name, "cancelling" if task.cancelling else task.state)list_platform_tasks.py
List every task of the account, queued by scripts and on the website, page by page.
"""List every task of the account, queued by scripts and on the website, page by page.
Spends nothing. Original names come from the record on this computer when it knows a task.
"""
import nalvera
offset = 0
while True:
page = nalvera.tasks(
state="all", # default: "all". Options: "active" | "finished" | "all"
limit=100, # default: 50. Options: 1 to 100
offset=offset, # default: 0
)
for task in page:
print(task.id, task.source, task.model, task.task, task.state, task.display_name)
if len(page) < 100:
break
offset += len(page)run_in_background.py
Start a run in the background and keep working: poll it, read its progress, collect it.
"""Start a run in the background and keep working: poll it, read its progress, collect it.
For a notebook or an app. Nothing is asked in the background, so the budget is named.
Spends credits: one task per scan, budget "personal". Run: python run_in_background.py
"""
import time
import nalvera
FOLDER = "scans"
progress = nalvera.ListReporter() # keeps each message as data; quiet=True drops them
client = nalvera.Client(
reporter=progress, # default: None (prints to the terminal)
)
run = client.run_in_background(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
)
while not run.done(): # run.cancel() stops it at its next pause
time.sleep(0.5)
if progress.events:
print("Latest:", progress.events[-1].text)
result = run.result() # the RunResult, or the run's error raised here
print(len(result), "queued")Results
Download results, see which code is which scan, and measure a result.
download_results.py
Download the results of your finished tasks. Run it again: nothing is downloaded twice.
"""Download the results of your finished tasks. Run it again: nothing is downloaded twice.
Spends nothing. A result is named after its original scan when the record on this computer
knows it; a file is never replaced.
"""
import nalvera
finished = nalvera.tasks(
state="finished", # default: "all". Options: "active" | "finished" | "all"
limit=100, # default: 50. Options: 1 to 100
)
done = [task for task in finished if task.state == "completed"]
paths = nalvera.download(
done,
out="results", # default: "results"
overwrite=False, # default: False (a result saved before is returned, not
# fetched again). Options: True | False
)
print(len(paths), "files saved;", len(paths.skipped), "tasks had no result")list_my_scans_and_tasks.py
List the scans recorded on this computer: which code is which scan, its tasks and results.
"""List the scans recorded on this computer: which code is which scan, its tasks and results.
Reads the record on this computer: no request. In a notebook, nalvera.scans() shows a table.
Run: python list_my_scans_and_tasks.py
"""
import nalvera
record = nalvera.scans()
print("Record:", record.path)
for row in record:
print(row["code"], row["original_name"], row["series"], row["task_id"] or "-",
row["model"], row["task"], row["result_path"])
codes = sorted({row["code"] for row in record if row["original_name"] == "ct_scan.nii.gz"})
print("ct_scan.nii.gz is", codes or "not recorded")organ_volumes_from_result.py
Measure each label of a segmentation result in milliliters and write volumes.csv.
"""Measure each label of a segmentation result in milliliters and write volumes.csv.
Reads a downloaded result with nibabel: no key, no request. Labels are numbers here; their
names are on the model's page at nalvera.ai. Run: python organ_volumes_from_result.py
"""
import csv
import nibabel as nib
import numpy as np
RESULT = "results/ct_scan__totalsegmentator_ct__total.nii.gz"
image = nib.load(RESULT)
labels = np.asarray(image.dataobj).astype(np.int64)
voxel_ml = float(np.prod(image.header.get_zooms()[:3])) / 1000.0 # mm³ to ml
values, counts = np.unique(labels, return_counts=True)
with open("volumes.csv", "w", newline="", encoding="utf-8") as fh:
writer = csv.writer(fh)
writer.writerow(["label", "voxels", "ml"])
for value, count in zip(values, counts):
if value != 0: # 0 is the background
writer.writerow([int(value), int(count), round(count * voxel_ml, 3)])
print(f"label {value}: {count * voxel_ml:.1f} ml")Privacy
Anonymize without uploading, encrypt uploads, keep the record of scans in a file you choose and limit the folders a client may use.
anonymize_only.py
Anonymize a scan without uploading it, then show what was removed and what was kept.
"""Anonymize a scan without uploading it, then show what was removed and what was kept.
No key, no request. OUT receives the copy, named by its code, and nothing else; the record
that links the code to the original stays on this computer. Run: python anonymize_only.py
"""
import nibabel as nib
import numpy as np
import nalvera
SCAN = "ct_scan.nii.gz"
OUT = "anonymized"
copies = nalvera.save_anonymized(SCAN, OUT)
copy = copies[0]
print(copy.original_name, "->", copy.path, "shape", copy.shape)
print("removed:", ", ".join(copy.removed))
before, after = nib.load(SCAN), nib.load(copy.path)
for field in ("descrip", "aux_file", "intent_name", "db_name"):
print(f"{field}: {before.header[field].item()!r} -> {after.header[field].item()!r}")
print("header extensions:", len(before.header.extensions), "->", len(after.header.extensions))
print("voxels unchanged:", np.array_equal(np.asarray(before.dataobj), np.asarray(after.dataobj)))
print("geometry unchanged:", np.array_equal(before.affine, after.affine))
print("record:", copies.record)
# The anonymizer removes nothing from the image: a face in a head scan and text burned in stay.encrypted_upload.py
Encrypt each anonymized scan on this computer before upload, a second layer on top of HTTPS.
"""Encrypt each anonymized scan on this computer before upload, a second layer on top of HTTPS.
The platform decrypts it to run the task. When the package cannot encrypt, nothing is uploaded.
Spends credits: one task, budget "personal".
"""
import nalvera
SCAN = "ct_scan.nii.gz"
print(nalvera.encryption()) # available, required by your account, used by default
tasks = nalvera.run(
SCAN,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
encrypt=True, # default: None (NALVERA_ENCRYPT, else on only when your
# account requires it). Options: True | False
)
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"keep_the_mapping_elsewhere.py
Keep the record, which says whose scan each code is, in a private file you choose.
"""Keep the record, which says whose scan each code is, in a private file you choose.
By default it is in the package's configuration folder; keep it off shared drives. Spends
credits: one task, budget "personal". For every script: set NALVERA_MAPPING.
"""
from pathlib import Path
import nalvera
SCAN = "ct_scan.nii.gz"
MAPPING = Path.home() / "private" / "nalvera_scans.csv"
client = nalvera.Client(
mapping=MAPPING, # default: None (NALVERA_MAPPING, else one file per
# account in the configuration folder)
)
tasks = client.run(
SCAN,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
client.download(client.wait(tasks), out="results") # default: "results"
print("Codes and original names are in", client.mapping_path)limit_to_allowed_folders.py
Let a client read scans and save results only inside folders you allow (a tool, a service).
"""Let a client read scans and save results only inside folders you allow (a tool, a service).
A path outside them is refused before anything is read (error code path_not_allowed).
Spends credits: one task, budget "personal". Run: python limit_to_allowed_folders.py
"""
from pathlib import Path
import nalvera
ALLOWED = [Path("data")]
OUTSIDE = "other/ct_scan.nii.gz"
client = nalvera.Client(
allowed_folders=ALLOWED, # default: None (any folder)
)
tasks = client.run(
"data/ct_scan.nii.gz",
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
)
client.download(client.wait(tasks), out="data/results") # default: "results"
try:
client.estimate_run(OUTSIDE, "totalsegmentator_ct")
except nalvera.ConfigError as error:
print("Refused:", error.code) # path_not_allowedAutomation
Run without a terminal, and start an interrupted run again without paying twice.
run_without_a_terminal.py
Run unattended (a cluster, CI) with an exit status that a scheduler can act on.
"""Run unattended (a cluster, CI) with an exit status that a scheduler can act on.
Credentials come from the environment; statuses: 1 a scan failed, 3 sign-in, 4 credits or
budget, 5 limits or network. Spends credits: one task per scan, budget "personal".
"""
import sys
import nalvera
from nalvera.cli import exit_status
FOLDER = "scans"
try:
# No login call: NALVERA_EMAIL and NALVERA_API_KEY come from a secret store.
result = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal,
# or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
yes=True, # default: False (stops when a DICOM folder holds
# several scans). Options: True | False
)
finished = nalvera.wait(result)
nalvera.download(finished, out="results") # default: "results"
except nalvera.NalveraError as error:
print(error, file=sys.stderr)
sys.exit(exit_status(error)) # 3 sign-in, 4 credits or budget, 5 limits or network
sys.exit(1 if result.failed or any(task.state != "completed" for task in finished) else 0)resume_an_interrupted_run.py
Start a run again after it stopped (Ctrl-C, a lost connection, a reboot).
"""Start a run again after it stopped (Ctrl-C, a lost connection, a reboot).
A scan already queued, running or done comes back as its earlier task, so nothing is queued or
charged twice. Spends credits (budget "personal") for the scans not queued yet.
Run: python resume_an_interrupted_run.py, and the same again after a stop
"""
import nalvera
FOLDER = "scans"
result = nalvera.run(
FOLDER,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or asks).
# Options: "personal" | "lab:<id>" | "free" | "ask"
force=False, # default: False (returns the earlier task of a scan already
# queued, running or done). Options: True | False
)
for task in result:
print(task.original_name, task.id, "queued before" if task.earlier else "queued now")
finished = nalvera.wait(result)
nalvera.download(finished, out="results") # default: "results"Errors
Handle each kind of error a run can meet.
handle_errors.py
Run a scan and react to each kind of error a script should handle differently.
"""Run a scan and react to each kind of error a script should handle differently.
Branch on error.code; the wording can change. Spends credits: one task, budget "personal".
Exit statuses: 1 scan refused, 3 sign-in, 4 credits, 5 try later.
Run: python handle_errors.py
"""
import sys
import nalvera
SCAN = "ct_scan.nii.gz"
try:
tasks = nalvera.run(
SCAN,
model="totalsegmentator_ct", # required. See: nalvera.models()
budget="personal", # default: None (free tasks first, then personal, or
# asks). Options: "personal" | "lab:<id>" | "free" | "ask"
)
except nalvera.RunInterrupted as stop: # Ctrl-C
sys.exit(f"Stopped. Tasks queued: {len(stop.tasks)}. They keep running.")
except nalvera.NalveraError as error:
print(error, file=sys.stderr) # says what to do next
if error.code in ("insufficient_credits", "no_free_tasks", "max_credits_exceeded",
"budget_choice_required"):
sys.exit(4) # buy credits, or name another budget
if error.code in ("no_credentials", "invalid_credentials", "key_expired", "key_revoked",
"scope_missing", "api_disabled", "api_blocked", "client_too_old"):
sys.exit(3) # a new key, a permission, API access on
if error.code in ("scan_rejected", "too_large", "not_a_scan", "unreadable"):
sys.exit(1) # this scan cannot run
if error.code in ("rate_limited", "too_many_active_tasks", "too_many_uploads", "queue_full",
"storage_full", "temporarily_unavailable", "api_unavailable",
"network_error"):
sys.exit(5) # the package waited as long as it may: run again later (retry_after)
raise
nalvera.download(nalvera.wait(tasks), out="results") # default: "results"AI assistants
Set up an assistant's app to use Nalvera.AI on your computer, and list its tools.
mcp/README.md
What each tool of the assistant server does and costs, and how to set it up in an assistant's app.
Nalvera.AI in an AI assistant (MCP)
python -m nalvera.mcp starts a server that an AI assistant's app runs on your computer. Through it the assistant lists models, checks budgets and costs, runs tasks on your scans, generates synthetic scans, follows tasks and saves results. Scans are anonymized on your computer before upload, as everywhere in the package. For research use only.
Set up once
pip install "nalvera[mcp]".- Store your key on this computer once, from Python:
nalvera.login(remember=True), which asks for it. The server finds it there, and no file here holds a key (set_api_key.py shows every way to give one). Keep keys out of an app's settings and out of chats; revoke a key that was written down, on nalvera.ai under Settings → API. - Add the snippet for your app:
| App | Snippet | Where it goes |
|---|---|---|
| Claude Code | claude_code.mcp.json | .mcp.json in the project folder |
| Claude Desktop | claude_desktop_config.json | Settings → Developer → Edit Config; set your scans folder |
| Cursor | cursor_mcp.json | .cursor/mcp.json in the project folder |
| VS Code | vscode_mcp.json | .vscode/mcp.json in the project folder |
| Codex | codex_config.toml | ~/.codex/config.toml; set your scans folder |
| Check that it works | list_tools.py | python list_tools.py lists the tools and your free tasks |
command must be the Python that has the package installed: when the app finds another one, put the full path there (in that Python, import sys; print(sys.executable) shows it).
Folders
The server reads scans and saves results only inside its allowed folders, symbolic links included:
NALVERA_MCP_ALLOWED_DIRS default: unset (the folder the app starts the server in; none when that is the root or the home folder).
Options: folders separated by : (; on Windows)
NALVERA_MAPPING default: unset (one file per account in the configuration folder)Results go to the folder results inside the first allowed folder, unless the assistant names another allowed folder. The record that links each scan code to your file name stays in the package's configuration folder on your computer, outside the allowed folders.
What the assistant is told
NALVERA_MCP_SHOW_NAMES default: unset (scan codes, positions and folders only)
Options: 1 (also the original file names and the paths of saved results; the assistant's provider then sees them)The tools
| Tool | What it does | Cost |
|---|---|---|
list_models | Models and tasks you may run, with prices and generation settings | free |
get_budgets | Free tasks left, personal credits, each lab's balance | free |
estimate_cost | What a task costs: for a scan file or folder, a voxel grid, or generation settings | free |
generate | Queues a synthetic CT or brain MRI volume (MAISI-v2) | spends credits |
list_tasks | Your tasks, newest first, with queue position and times | free |
get_task | One task's state, queue position, times and error | free |
wait_for_task | Waits up to 25 seconds for a task to change | free |
cancel_task | Cancels a waiting or running task | refunds follow the website's rules |
get_text_result | The text of a report task, up to 64 KB, marked as AI model output | free |
run_scan | Anonymizes scans here, uploads them and queues a task per scan, in the background | spends credits |
get_run | Progress of a run_scan: per scan, percent uploaded, task id, reason, credits | free |
download_result | Saves a result in an allowed folder; never replaces a file | free |
Spending
run_scanandgenerateneed a budget (personal,lab:<id>orfree) andmax_credits. Above the cap nothing is uploaded or queued, and the estimate comes back for the assistant to show you.- A repeated call charges once:
generatetakes arequest_id, andrun_scanreturns a scan already queued with the same model and task. - A DICOM folder with several series is listed first, each series with its cost; the assistant then calls again with the series you choose.
mcp/claude_code.mcp.json
Configuration for Claude Code in a project: it starts the assistant server.
{
"mcpServers": {
"nalvera": {
"command": "python",
"args": ["-m", "nalvera.mcp"]
}
}
}mcp/claude_desktop_config.json
Configuration for Claude Desktop, with the folders it may read.
{
"mcpServers": {
"nalvera": {
"command": "python",
"args": ["-m", "nalvera.mcp"],
"env": {
"NALVERA_MCP_ALLOWED_DIRS": "/path/to/scans"
}
}
}
}mcp/cursor_mcp.json
Configuration for Cursor, limited to the workspace folder.
{
"mcpServers": {
"nalvera": {
"type": "stdio",
"command": "python",
"args": ["-m", "nalvera.mcp"],
"env": {
"NALVERA_MCP_ALLOWED_DIRS": "${workspaceFolder}"
}
}
}
}mcp/vscode_mcp.json
Configuration for VS Code, started in the workspace folder.
{
"servers": {
"nalvera": {
"type": "stdio",
"command": "python",
"args": ["-m", "nalvera.mcp"],
"cwd": "${workspaceFolder}"
}
}
}mcp/codex_config.toml
Configuration for Codex in ~/.codex/config.toml, with the folders it may read.
# Codex: the Nalvera.AI MCP server on this computer (add to ~/.codex/config.toml).
# Needs: pip install "nalvera[mcp]" and, once, nalvera.login(remember=True).
[mcp_servers.nalvera]
command = "python"
args = ["-m", "nalvera.mcp"]
# NALVERA_MCP_ALLOWED_DIRS default: unset (the folder Codex starts the server in).
# Options: folders separated by : (; on Windows)
env = { NALVERA_MCP_ALLOWED_DIRS = "/path/to/scans" }mcp/list_tools.py
Start the assistant server as an assistant's app does, list its tools, and read the budgets.
"""Start the local MCP server as an assistant's app does, list its tools, read the budgets.
Needs: pip install "nalvera[mcp]"; once: nalvera.login(remember=True).
Spends nothing. Run: python list_tools.py
"""
import asyncio
import os
import sys
from mcp import Client
from mcp.client.stdio import StdioServerParameters
# The server gets this process's NALVERA_* settings; a key stored by
# nalvera.login(remember=True) is found by the server itself.
SETTINGS = {k: v for k, v in os.environ.items() if k.startswith("NALVERA_")}
SERVER = StdioServerParameters(command=sys.executable, args=["-m", "nalvera.mcp"],
env=SETTINGS)
async def main():
async with Client(SERVER) as client:
listed = await client.list_tools()
for tool in listed.tools:
print(f"{tool.name}: {tool.title}")
budgets = await client.call_tool("get_budgets", {})
print("free tasks left:", budgets.structured_content["free"]["free_tasks_left"])
asyncio.run(main())Research use only. Nalvera.AI is not a medical device.