{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# MRI-one quickstart\n",
    "\n",
    "This notebook walks through the researcher workflow with the `mrione_client` package:\n",
    "\n",
    "1. connect and read the service capabilities,\n",
    "2. add scans with their scanner details,\n",
    "3. check them and plan an **augment** run (keep originals, add up to 50 copies of 1.5 T training slices edited toward 3.0 T),\n",
    "4. preview one edit,\n",
    "5. run the batch, review reader verdicts, and download the dataset with its run record.\n",
    "\n",
    "Outputs are synthetic research images for robustness and augmentation experiments. They are not for diagnosis.\n",
    "\n",
    "Install the client first: `pip install mrione_client-1.0.0-py3-none-any.whl numpy matplotlib`."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import os, zipfile, io, json\n",
    "from pathlib import Path\n",
    "from mrione_client import Client, MRIoneError\n",
    "\n",
    "# Set these to your service and workspace token (or export MRIONE_URL / MRIONE_TOKEN).\n",
    "os.environ.setdefault(\"MRIONE_URL\", \"https://mri-one.namankundra.com\")\n",
    "mr = Client.from_env(client_name=\"notebook\")\n",
    "caps = mr.capabilities()\n",
    "print(\"model:\", caps.model_version)\n",
    "print(\"presets:\", caps.preset_ids)\n",
    "print(\"limits:\", caps.limits)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Get example scans\n",
    "\n",
    "The import example kit has de-identified Duke breast MRI axial T1 slices (PNG), one DICOM file and a `scans.csv` with two rows that are deliberately wrong, so you can see how the check reports them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import urllib.request\n",
    "kit = Path(\"mri-one-import-example\")\n",
    "if not kit.exists():\n",
    "    data = urllib.request.urlopen(os.environ[\"MRIONE_URL\"].rstrip(\"/\") + \"/samples/mri-one-import-example.zip\").read()\n",
    "    zipfile.ZipFile(io.BytesIO(data)).extractall(kit)\n",
    "sorted(p.name for p in kit.rglob(\"*\") if p.is_file())[:10]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Create a dataset and add the scans"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "ds = mr.create_dataset(\"Notebook quickstart\")\n",
    "res = mr.add_files(ds.id, kit / \"scans\", csv=kit / \"scans.csv\")\n",
    "print(len(res[\"added\"]), \"added;\", len(res[\"failed\"]), \"failed\")\n",
    "for f in res[\"failed\"]:\n",
    "    print(\"  \", f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Check the scans"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "check = mr.validate(ds.id)\n",
    "print(check.eligibility_counts)\n",
    "for issue in check.issues:\n",
    "    print(issue)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Plan: keep originals, add up to 50 copies of 1.5 T training slices that look like 3.0 T\n",
    "\n",
    "In **augment** mode the plan edits only training-split slices; validation and test slices are kept as originals (`held_out_split`)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "plan = mr.plan(ds.id, validation_id=check.id, recipe=\"augment\", target={\"field_strength_t\": 3.0}, max_edits=50)\n",
    "print(plan.counts)\n",
    "edits = mr.plan_items(plan.id, action=\"edit\")\n",
    "print(len(edits), \"slices will be edited\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Preview one edit"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "preview = mr.start_job(plan.id, mode=\"preview\", item_id=edits[0].item_id)\n",
    "preview = mr.wait_for_job(preview.id)\n",
    "item = mr.job_items(preview.id)[0]\n",
    "orig = mr.load_array(preview.id, item.id, \"original_npy\")\n",
    "edit = mr.load_array(preview.id, item.id, \"edited_npy\")\n",
    "fig, ax = plt.subplots(1, 3, figsize=(10, 3.5))\n",
    "ax[0].imshow(orig, cmap=\"gray\"); ax[0].set_title(\"original\")\n",
    "ax[1].imshow(edit, cmap=\"gray\"); ax[1].set_title(\"edited toward 3.0 T\")\n",
    "ax[2].imshow(np.abs(edit - orig), cmap=\"magma\"); ax[2].set_title(\"|difference|\")\n",
    "for a in ax: a.axis(\"off\")\n",
    "for v in item.reader_verdicts:\n",
    "    print(f\"{v['reader_name']:<38} independent={v['independent']!s:<5} sees target: {v['agrees']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The original predictor was trained on the same split as the editor; the three held-out ResNet-18 readers were not. Treat agreement from the original predictor alone as weak evidence."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Run the batch and download"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "job = mr.start_job(plan.id, mode=\"batch\")\n",
    "job = mr.wait_for_job(job.id)\n",
    "print(job.status, job.counts)\n",
    "out = mr.export(job.id, \"mri-one-quickstart.zip\", allow_partial=True)\n",
    "print(\"saved\", out)"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "with zipfile.ZipFile(out) as z:\n",
    "    manifest = json.loads(z.read(\"manifest.json\"))\n",
    "    print(manifest[\"model_version\"], manifest[\"counts\"])\n",
    "    print(z.read(\"items.csv\").decode().splitlines()[:5])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`items.csv` lists every output (original copies as `src_*`, edited copies as `syn_*`), with the source item, action, preset, seed and reader verdicts. `manifest.json` is the run record: dataset revision, plan, model version and counts. Skipped and failed items are listed with their reasons."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}