{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "2c71cd29-819f-4c17-a40a-fa05c5a1d162", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/opt/homebrew/lib/python3.11/site-packages/torch/utils/_pytree.py:185: FutureWarning: optree is installed but the version is too old to support PyTorch Dynamo in C++ pytree. C++ pytree support is disabled. Please consider upgrading optree using `python3 -m pip install --upgrade 'optree>=0.13.0'`.\n", " warnings.warn(\n" ] } ], "source": [ "# hyper_manifest_dataset.py\n", "# Minimal + robust:\n", "# - build_manifest_csv(): guarantees correct labels by parsing every file path\n", "# - ManifestSegDataset: fast init from manifest; lazy mask lookup; optional relabel fallback\n", "#\n", "# No resizing/channel forcing. No shape changes.\n", "\n", "import os\n", "import csv\n", "import gzip\n", "import math\n", "import random\n", "import platform\n", "from pathlib import Path\n", "from typing import Optional, Tuple, List, Dict, Any, Union\n", "from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n", "\n", "import numpy as np\n", "import torch\n", "from torch.utils.data import Dataset\n", "\n", "\n", "# ------------------------- low-level utils -------------------------\n", "\n", "def _read_shape_area(npy_path: str) -> Tuple[Optional[int], Optional[int], Optional[int]]:\n", " \"\"\"Header-only read of .npy -> (H, W, H*W). Returns (None, None, None) on failure.\"\"\"\n", " try:\n", " mm = np.load(npy_path, allow_pickle=False, mmap_mode=\"r\")\n", " h, w = int(mm.shape[0]), int(mm.shape[1])\n", " return h, w, h * w\n", " except Exception:\n", " return None, None, None\n", "\n", "# picklable worker\n", "def _read_shape_area_job(img_path: str) -> Tuple[Optional[int], Optional[int], Optional[int]]:\n", " return _read_shape_area(img_path)\n", "\n", "def _mask_guess_paths(mask_dir: Path, stem: str) -> List[Path]:\n", " return [\n", " mask_dir / f\"{stem}.npy\",\n", " mask_dir / f\"{stem}_mask.npy\",\n", " mask_dir / f\"{stem}_masks.npy\",\n", " mask_dir / f\"{stem}-mask.npy\",\n", " mask_dir / f\"{stem}-masks.npy\",\n", " ]\n", "\n", "def _to_tensor_img(arr: np.ndarray) -> torch.Tensor:\n", " if arr.ndim == 2:\n", " arr = arr[:, :, None]\n", " t = torch.from_numpy(arr)\n", " if t.dtype != torch.float32:\n", " t = t.to(torch.float32)\n", " if float(t.max()) > 1.0:\n", " t = t / 255.0\n", " return t.permute(2, 0, 1).contiguous()\n", "\n", "def _to_tensor_mask(arr: Optional[np.ndarray]) -> Optional[torch.Tensor]:\n", " if arr is None:\n", " return None\n", " if arr.ndim > 2:\n", " arr = arr.squeeze()\n", " t = torch.from_numpy(arr)\n", " if t.dtype != torch.uint8:\n", " t = t.to(torch.uint8)\n", " return (t != 0).to(torch.uint8)\n", "\n", "def _subset_size(raw, n: int) -> Optional[int]:\n", " \"\"\"-1->n, 0
ceil(p*n), int>=0 -> min(k,n), float>1 -> min(int(raw),n), None->None.\"\"\"\n",
" if raw is None:\n",
" return None\n",
" if isinstance(raw, (int, np.integer)):\n",
" return n if raw < 0 else min(int(raw), n)\n",
" if isinstance(raw, float):\n",
" if raw < 0:\n",
" return n\n",
" if 0 < raw <= 1:\n",
" return max(1, math.ceil(raw * n))\n",
" return min(int(raw), n)\n",
" return None\n",
"\n",
"\n",
"# ------------------------- robust path parsing -------------------------\n",
"\n",
"def _iter_original_dirs(root: Path, split: str, allowed: Optional[set]) -> List[Tuple[Path, str]]:\n",
" \"\"\"\n",
" Find every '.../ 0 and area < min_area_px:\n",
" continue\n",
" rows.append((\n",
" r[\"img_path\"],\n",
" origin,\n",
" r[\"label\"], # may be \"\" only when dataset actually has no label dirs\n",
" r[\"mask_dir\"],\n",
" int(r[\"has_empty\"]),\n",
" r[\"stem\"],\n",
" int(r[\"h\"]),\n",
" int(r[\"w\"]),\n",
" area,\n",
" ))\n",
"\n",
" if not rows:\n",
" raise RuntimeError(\"Manifest filter produced 0 rows.\")\n",
"\n",
" # Per-origin subsampling BEFORE storing\n",
" by_origin: Dict[str, List[tuple]] = {}\n",
" for t in rows:\n",
" by_origin.setdefault(t[1], []).append(t)\n",
"\n",
" sel_rows: List[tuple] = []\n",
" for origin, items in by_origin.items():\n",
" raw = per_dataset_limits.get(origin) if per_dataset_limits else None\n",
" if raw is None and max_per_dataset is not None:\n",
" raw = max_per_dataset\n",
" n_keep = _subset_size(raw, len(items))\n",
" if n_keep is None or n_keep >= len(items):\n",
" sel_rows.extend(items)\n",
" elif n_keep > 0:\n",
" items_copy = items[:]\n",
" self._rng.shuffle(items_copy)\n",
" sel_rows.extend(items_copy[:n_keep])\n",
"\n",
" if not sel_rows:\n",
" raise RuntimeError(\"All rows filtered out by per_dataset_limits/max_per_dataset.\")\n",
"\n",
" # Optional on-the-fly relabel for legacy CSVs\n",
" if root_for_relabel is not None and split_for_relabel is not None:\n",
" root_fix = Path(root_for_relabel).expanduser().resolve()\n",
" fixed_rows = []\n",
" for (img_path, origin, label, mask_dir, has_empty, stem, h, w, area) in sel_rows:\n",
" if (label or \"\").strip() == \"\":\n",
" label = _derive_label_from_path(img_path, root_fix, split_for_relabel, origin)\n",
" fixed_rows.append((img_path, origin, label, mask_dir, has_empty, stem, h, w, area))\n",
" sel_rows = fixed_rows\n",
"\n",
" # store\n",
" # idx: 0=img_path,1=origin,2=label,3=mask_dir,4=has_empty,5=stem,6=h,7=w,8=area\n",
" self._rows = sel_rows\n",
"\n",
" def __len__(self) -> int:\n",
" return len(self._rows)\n",
"\n",
" def _resolve_mask_path(self, mask_dir: str, has_empty: int, stem: str) -> Optional[str]:\n",
" if has_empty:\n",
" return None\n",
" mdir = Path(mask_dir)\n",
" for cand in _mask_guess_paths(mdir, stem):\n",
" if cand.exists():\n",
" return str(cand)\n",
" if self.strict_match:\n",
" raise FileNotFoundError(f\"Mask for stem='{stem}' not found under {mdir}\")\n",
" return None\n",
"\n",
" def __getitem__(self, idx: int) -> Dict[str, Any]:\n",
" img_path, origin, label, mask_dir, has_empty, stem, h, w, area = self._rows[idx]\n",
" mmap = \"r\" if self.mmap_images else None\n",
" img = np.load(img_path, allow_pickle=False, mmap_mode=mmap)\n",
" mask_path = self._resolve_mask_path(mask_dir, has_empty, stem)\n",
" msk = None if mask_path is None else np.load(mask_path, allow_pickle=False, mmap_mode=mmap)\n",
"\n",
" out = {\n",
" \"image\": _to_tensor_img(img), # C,H,W (original channels)\n",
" \"mask\": _to_tensor_mask(msk), # H,W or None\n",
" \"origin\": origin,\n",
" \"label\": (label if (label or \"\").strip() != \"\" else None),\n",
" }\n",
" if self.return_paths:\n",
" out[\"paths\"] = (img_path, mask_path)\n",
" return out\n",
"\n",
"\n",
"# ------------------------- mini sanity check helpers -------------------------\n",
"\n",
"def debug_count_empty_labels(manifest_gz: str, origins: Optional[List[str]] = None):\n",
" \"\"\"Quick check: show how many rows have empty label per origin in the CSV.\"\"\"\n",
" by_origin = {}\n",
" with gzip.open(manifest_gz, \"rt\", newline=\"\") as gz:\n",
" r = csv.DictReader(gz)\n",
" for row in r:\n",
" o = row[\"origin\"]\n",
" if origins is not None and o not in origins:\n",
" continue\n",
" by_origin.setdefault(o, {\"total\": 0, \"empty\": 0})\n",
" by_origin[o][\"total\"] += 1\n",
" if (row[\"label\"] or \"\").strip() == \"\":\n",
" by_origin[o][\"empty\"] += 1\n",
" for o in sorted(by_origin.keys()):\n",
" t, e = by_origin[o][\"total\"], by_origin[o][\"empty\"]\n",
" print(f\"{o:20s} empty={e:7d} / total={t:7d} ({(e/t*100):6.2f}% empty)\")\n"
]
},
{
"cell_type": "markdown",
"id": "19ef8e1b-d568-4dec-8cf9-88c679e02814",
"metadata": {},
"source": [
"# RUN ONCE"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e3b2cf29-6492-4400-9d1a-5eaf94712b88",
"metadata": {},
"outputs": [],
"source": [
"ALL_DATASETS = [\n",
" 'N_MoNuSAC',\n",
" 'N_DynamicNuclearNet',\n",
" 'N_omnipose',\n",
" 'N_iPSC_Morpologies',\n",
" 'N_PanNuke','N_MoNuSeg',\n",
" 'N_databowl',\n",
" 'N_cyto2',\n",
" 'N_tissuenet',\n",
" 'N_BCCD',\n",
" 'N_CoNIC',\n",
" 'N_lynsec13',\n",
" 'N_NuInsSeg',\n",
" 'N_iPSC_QCData',\n",
" 'N_Satorious'\n",
"]\n",
"\n",
"\n",
"'''\n",
"Had to remove some datasets due to liscencing isues\n",
"[\n",
" \"N_BCCD\",\n",
" \"N_CMP_15_17_and_TNBC\"\n",
" \"N_CoNIC\",\n",
" \"N_CryoNuSeg\",\n",
" \"N_DynamicNuclearNet\",\n",
" \"N_IHC_TMA\",\n",
" \"N_MoNuSAC\",\n",
" \"N_MoNuSeg\",\n",
" \"N_Neurips\",\n",
" \"N_NuInsSeg\",\n",
" \"N_PanNuke\",\n",
" \"N_Phenoplex\",\n",
" \"N_cyto2\",\n",
" \"N_databowl\",\n",
" \"N_iPSC_Morpologies\",\n",
" \"N_iPSC_QCData\",\n",
" \"N_lynsec13\",\n",
" \"N_omnipose\",\n",
" \"N_tissuenet\",\n",
" \"N_yeaz\",\n",
" \"N_Satorious\",\n",
" \"N_Helmholtz\"\n",
"]'''\n",
"\n",
"# 1) REBUILD the manifest with guaranteed labels\n",
"build_manifest_csv(\n",
" root=\".\", # your root that contains the N_* folders\n",
" split=\"train\",\n",
" out_csv_gz=\"./manifest_train_fixed.csv.gz\",\n",
" datasets=ALL_DATASETS, # restrict scanning to exactly these origins\n",
" min_area_px=20*18,\n",
" workers=32,\n",
" force_threads=None, # threads on macOS, processes elsewhere\n",
")"
]
},
{
"cell_type": "markdown",
"id": "87ab3b2f-0da0-469c-a93f-b19cbe2c8292",
"metadata": {},
"source": [
"# Data Loader"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "3aa5e541-6290-46d1-838e-e6df6ca5aaf1",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"N_BCCD empty= 81732 / total= 81732 (100.00% empty)\n",
"N_CMP_15_17_and_TNBC empty= 0 / total= 10462 ( 0.00% empty)\n",
"N_CoNIC empty= 0 / total= 6927 ( 0.00% empty)\n",
"N_CryoNuSeg empty= 0 / total= 2046 ( 0.00% empty)\n",
"N_DynamicNuclearNet empty= 312815 / total= 312815 (100.00% empty)\n",
"N_Helmholtz empty= 0 / total= 31159 ( 0.00% empty)\n",
"N_IHC_TMA empty= 0 / total= 6439 ( 0.00% empty)\n",
"N_MoNuSAC empty= 0 / total= 25870 ( 0.00% empty)\n",
"N_MoNuSeg empty= 14428 / total= 14428 (100.00% empty)\n",
"N_Neurips empty= 88619 / total= 88619 (100.00% empty)\n",
"N_NuInsSeg empty= 0 / total= 22764 ( 0.00% empty)\n",
"N_PanNuke empty= 0 / total= 94135 ( 0.00% empty)\n",
"N_Phenoplex empty= 0 / total= 447820 ( 0.00% empty)\n",
"N_cyto2 empty= 64605 / total= 64605 (100.00% empty)\n",
"N_databowl empty= 13412 / total= 13412 (100.00% empty)\n",
"N_iPSC_Morpologies empty= 0 / total= 5131 ( 0.00% empty)\n",
"N_iPSC_QCData empty= 0 / total= 26647 ( 0.00% empty)\n",
"N_lynsec13 empty= 0 / total= 63609 ( 0.00% empty)\n",
"N_omnipose empty= 0 / total= 33335 ( 0.00% empty)\n",
"N_tissuenet empty= 780196 / total= 780196 (100.00% empty)\n",
"N_yeaz empty= 19606 / total= 19606 (100.00% empty)\n"
]
}
],
"source": [
"debug_count_empty_labels(\"./manifest_train_fixed.csv.gz\", origins=ALL_DATASETS)\n",
"\n",
"# 3) Load dataset (no resizing/channel forcing, as requested)\n",
"PER_DATASET_LIMITS = {k: -1 for k in ALL_DATASETS} #-1 = Load all, can put in int for hard number, and float 0-1 for % of dataset\n",
"ds = ManifestSegDataset(\n",
" manifest_csv_gz=\"./manifest_train_fixed.csv.gz\",\n",
" datasets=ALL_DATASETS,\n",
" per_dataset_limits=PER_DATASET_LIMITS,\n",
" min_area_px=20*18,\n",
" seed=42,\n",
" mmap_images=True,\n",
" strict_match=False,\n",
" return_paths=True,\n",
"\n",
" # If for some reason you still have an *old* CSV with empties, uncomment these two:\n",
" # root_for_relabel=\".\", # absolute/relative path to root\n",
" # split_for_relabel=\"train\",\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bf202508-d4b5-43be-a111-883f0a025d51",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}