juliusriel commited on
Commit
b44dfb0
·
verified ·
1 Parent(s): 7072b10

Upload HASSL SingleCellBench zipped dataset folders

Browse files
Dataloader_example.ipynb ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "2c71cd29-819f-4c17-a40a-fa05c5a1d162",
7
+ "metadata": {},
8
+ "outputs": [
9
+ {
10
+ "name": "stderr",
11
+ "output_type": "stream",
12
+ "text": [
13
+ "/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",
14
+ " warnings.warn(\n"
15
+ ]
16
+ }
17
+ ],
18
+ "source": [
19
+ "# hyper_manifest_dataset.py\n",
20
+ "# Minimal + robust:\n",
21
+ "# - build_manifest_csv(): guarantees correct labels by parsing every file path\n",
22
+ "# - ManifestSegDataset: fast init from manifest; lazy mask lookup; optional relabel fallback\n",
23
+ "#\n",
24
+ "# No resizing/channel forcing. No shape changes.\n",
25
+ "\n",
26
+ "import os\n",
27
+ "import csv\n",
28
+ "import gzip\n",
29
+ "import math\n",
30
+ "import random\n",
31
+ "import platform\n",
32
+ "from pathlib import Path\n",
33
+ "from typing import Optional, Tuple, List, Dict, Any, Union\n",
34
+ "from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor\n",
35
+ "\n",
36
+ "import numpy as np\n",
37
+ "import torch\n",
38
+ "from torch.utils.data import Dataset\n",
39
+ "\n",
40
+ "\n",
41
+ "# ------------------------- low-level utils -------------------------\n",
42
+ "\n",
43
+ "def _read_shape_area(npy_path: str) -> Tuple[Optional[int], Optional[int], Optional[int]]:\n",
44
+ " \"\"\"Header-only read of .npy -> (H, W, H*W). Returns (None, None, None) on failure.\"\"\"\n",
45
+ " try:\n",
46
+ " mm = np.load(npy_path, allow_pickle=False, mmap_mode=\"r\")\n",
47
+ " h, w = int(mm.shape[0]), int(mm.shape[1])\n",
48
+ " return h, w, h * w\n",
49
+ " except Exception:\n",
50
+ " return None, None, None\n",
51
+ "\n",
52
+ "# picklable worker\n",
53
+ "def _read_shape_area_job(img_path: str) -> Tuple[Optional[int], Optional[int], Optional[int]]:\n",
54
+ " return _read_shape_area(img_path)\n",
55
+ "\n",
56
+ "def _mask_guess_paths(mask_dir: Path, stem: str) -> List[Path]:\n",
57
+ " return [\n",
58
+ " mask_dir / f\"{stem}.npy\",\n",
59
+ " mask_dir / f\"{stem}_mask.npy\",\n",
60
+ " mask_dir / f\"{stem}_masks.npy\",\n",
61
+ " mask_dir / f\"{stem}-mask.npy\",\n",
62
+ " mask_dir / f\"{stem}-masks.npy\",\n",
63
+ " ]\n",
64
+ "\n",
65
+ "def _to_tensor_img(arr: np.ndarray) -> torch.Tensor:\n",
66
+ " if arr.ndim == 2:\n",
67
+ " arr = arr[:, :, None]\n",
68
+ " t = torch.from_numpy(arr)\n",
69
+ " if t.dtype != torch.float32:\n",
70
+ " t = t.to(torch.float32)\n",
71
+ " if float(t.max()) > 1.0:\n",
72
+ " t = t / 255.0\n",
73
+ " return t.permute(2, 0, 1).contiguous()\n",
74
+ "\n",
75
+ "def _to_tensor_mask(arr: Optional[np.ndarray]) -> Optional[torch.Tensor]:\n",
76
+ " if arr is None:\n",
77
+ " return None\n",
78
+ " if arr.ndim > 2:\n",
79
+ " arr = arr.squeeze()\n",
80
+ " t = torch.from_numpy(arr)\n",
81
+ " if t.dtype != torch.uint8:\n",
82
+ " t = t.to(torch.uint8)\n",
83
+ " return (t != 0).to(torch.uint8)\n",
84
+ "\n",
85
+ "def _subset_size(raw, n: int) -> Optional[int]:\n",
86
+ " \"\"\"-1->n, 0<p<=1 -> ceil(p*n), int>=0 -> min(k,n), float>1 -> min(int(raw),n), None->None.\"\"\"\n",
87
+ " if raw is None:\n",
88
+ " return None\n",
89
+ " if isinstance(raw, (int, np.integer)):\n",
90
+ " return n if raw < 0 else min(int(raw), n)\n",
91
+ " if isinstance(raw, float):\n",
92
+ " if raw < 0:\n",
93
+ " return n\n",
94
+ " if 0 < raw <= 1:\n",
95
+ " return max(1, math.ceil(raw * n))\n",
96
+ " return min(int(raw), n)\n",
97
+ " return None\n",
98
+ "\n",
99
+ "\n",
100
+ "# ------------------------- robust path parsing -------------------------\n",
101
+ "\n",
102
+ "def _iter_original_dirs(root: Path, split: str, allowed: Optional[set]) -> List[Tuple[Path, str]]:\n",
103
+ " \"\"\"\n",
104
+ " Find every '.../<split>/**/original' under selected origins.\n",
105
+ " Returns list: (original_dir_path, origin_name)\n",
106
+ " \"\"\"\n",
107
+ " origins = [p for p in root.iterdir() if p.is_dir() and (allowed is None or p.name in allowed)]\n",
108
+ " if allowed is not None:\n",
109
+ " name2path = {p.name: p for p in origins}\n",
110
+ " origins = [name2path[n] for n in allowed if n in name2path]\n",
111
+ "\n",
112
+ " out: List[Tuple[Path, str]] = []\n",
113
+ " for origin in origins:\n",
114
+ " for dirpath, _, _ in os.walk(origin):\n",
115
+ " if os.path.basename(dirpath) != \"original\":\n",
116
+ " continue\n",
117
+ " parts = Path(dirpath).relative_to(root).parts\n",
118
+ " if split in parts[:-1]:\n",
119
+ " out.append((Path(dirpath), origin.name))\n",
120
+ " return out\n",
121
+ "\n",
122
+ "def _derive_label_from_path(img_path: str, root: Path, split: str, origin: str) -> str:\n",
123
+ " \"\"\"\n",
124
+ " Parse labels from absolute img_path.\n",
125
+ " Supports:\n",
126
+ " origin/<labels...>/<split>/original/file.npy\n",
127
+ " origin/<split>/<labels...>/original/file.npy\n",
128
+ " Returns \"\" if no labels found.\n",
129
+ " \"\"\"\n",
130
+ " parts = Path(img_path).resolve().relative_to(root).parts\n",
131
+ " # locate origin\n",
132
+ " try:\n",
133
+ " i0 = parts.index(origin)\n",
134
+ " except ValueError:\n",
135
+ " return \"\"\n",
136
+ " # locate split after origin\n",
137
+ " j = None\n",
138
+ " for k in range(i0 + 1, len(parts)):\n",
139
+ " if parts[k] == split:\n",
140
+ " j = k\n",
141
+ " break\n",
142
+ " if j is None:\n",
143
+ " return \"\"\n",
144
+ " # locate 'original' after split\n",
145
+ " try:\n",
146
+ " k_orig = parts.index(\"original\", j + 1)\n",
147
+ " except ValueError:\n",
148
+ " return \"\"\n",
149
+ " pre = list(parts[i0 + 1 : j])\n",
150
+ " post = list(parts[j + 1 : k_orig])\n",
151
+ " label_parts = pre + post\n",
152
+ " return \"__\".join(label_parts) if label_parts else \"\"\n",
153
+ "\n",
154
+ "\n",
155
+ "# ------------------------- 1) MANIFEST BUILDER (guaranteed labels) -------------------------\n",
156
+ "\n",
157
+ "def build_manifest_csv(\n",
158
+ " root: Union[str, Path],\n",
159
+ " split: str,\n",
160
+ " out_csv_gz: Union[str, Path],\n",
161
+ " *,\n",
162
+ " datasets: Optional[Union[str, List[str]]] = None, # filter top-level origins (N_*)\n",
163
+ " min_area_px: int = 0, # early filter by H*W\n",
164
+ " workers: int = 16, # parallel header reads\n",
165
+ " force_threads: Optional[bool] = None, # True -> ThreadPool; default True on macOS\n",
166
+ " chunk_size: int = 100_000,\n",
167
+ ") -> None:\n",
168
+ " \"\"\"\n",
169
+ " ONE-TIME scan -> compressed manifest CSV with correct labels for every file.\n",
170
+ " Writes rows:\n",
171
+ " img_path,origin,label,mask_dir,has_empty,stem,h,w,area\n",
172
+ " - 'label' is derived per-file from path; \"\" only if there truly are no label folders.\n",
173
+ " \"\"\"\n",
174
+ " root = Path(root).expanduser().resolve()\n",
175
+ " allowed = None if datasets is None else ({datasets} if isinstance(datasets, str) else set(datasets))\n",
176
+ " original_dirs = _iter_original_dirs(root, split, allowed)\n",
177
+ "\n",
178
+ " # Build candidate list\n",
179
+ " candidates: List[tuple] = []\n",
180
+ " for orig_dir, origin_name in original_dirs:\n",
181
+ " with os.scandir(orig_dir) as it:\n",
182
+ " for e in it:\n",
183
+ " if not e.is_file() or not e.name.endswith(\".npy\"):\n",
184
+ " continue\n",
185
+ " img_path = Path(e.path).resolve()\n",
186
+ " stem = img_path.stem\n",
187
+ " base_dir = img_path.parent.parent # parent of 'original'\n",
188
+ " mask_dir = base_dir / \"mask\"\n",
189
+ " empty_mask_dir = base_dir / \"empty_mask\"\n",
190
+ " has_empty = 1 if empty_mask_dir.exists() else 0\n",
191
+ " label = _derive_label_from_path(str(img_path), root, split, origin_name)\n",
192
+ " candidates.append((str(img_path), origin_name, label, str(mask_dir), has_empty, stem))\n",
193
+ "\n",
194
+ " # Choose executor type\n",
195
+ " if force_threads is None:\n",
196
+ " use_threads = (platform.system() == \"Darwin\")\n",
197
+ " else:\n",
198
+ " use_threads = bool(force_threads)\n",
199
+ " Executor = ThreadPoolExecutor if use_threads else ProcessPoolExecutor\n",
200
+ " map_kwargs = {} if use_threads else {\"chunksize\": 64}\n",
201
+ "\n",
202
+ " # Stream to gz CSV\n",
203
+ " out_csv_gz = Path(out_csv_gz)\n",
204
+ " out_csv_gz.parent.mkdir(parents=True, exist_ok=True)\n",
205
+ " with gzip.open(out_csv_gz, \"wt\", newline=\"\") as gz, Executor(max_workers=max(1, workers)) as ex:\n",
206
+ " writer = csv.writer(gz)\n",
207
+ " writer.writerow([\"img_path\", \"origin\", \"label\", \"mask_dir\", \"has_empty\", \"stem\", \"h\", \"w\", \"area\"])\n",
208
+ "\n",
209
+ " for start in range(0, len(candidates), chunk_size):\n",
210
+ " batch = candidates[start:start + chunk_size]\n",
211
+ " paths = [t[0] for t in batch]\n",
212
+ " metas = [t[1:] for t in batch] # (origin,label,mask_dir,has_empty,stem)\n",
213
+ "\n",
214
+ " for (h, w, area), (origin,label,mask_dir,has_empty,stem), path in zip(\n",
215
+ " ex.map(_read_shape_area_job, paths, **map_kwargs), metas, paths\n",
216
+ " ):\n",
217
+ " if h is None or w is None or area is None:\n",
218
+ " continue\n",
219
+ " if min_area_px > 0 and area < min_area_px:\n",
220
+ " continue\n",
221
+ " # write exactly what we derived; empty string only when truly no label dirs\n",
222
+ " writer.writerow([path, origin, label, mask_dir, has_empty, stem, h, w, area])\n",
223
+ "\n",
224
+ "\n",
225
+ "# ------------------------- 2) DATASET FROM MANIFEST (fast; with relabel fallback) -------------------------\n",
226
+ "\n",
227
+ "class ManifestSegDataset(Dataset):\n",
228
+ " \"\"\"\n",
229
+ " Ultra-fast dataset backed by the manifest.\n",
230
+ " - per_dataset_limits supports {-1, k, 0<p<=1}\n",
231
+ " - mask path resolved lazily on access\n",
232
+ " - area filter uses manifest's H*W\n",
233
+ " - If some rows in a legacy manifest had empty labels, you can pass root_for_relabel+split_for_relabel\n",
234
+ " and it will fix labels on the fly.\n",
235
+ " \"\"\"\n",
236
+ " def __init__(\n",
237
+ " self,\n",
238
+ " manifest_csv_gz: Union[str, Path],\n",
239
+ " *,\n",
240
+ " datasets: Optional[Union[str, List[str]]] = None, # filter by origin(s)\n",
241
+ " per_dataset_limits: Optional[Dict[str, Union[int, float]]] = None,\n",
242
+ " max_per_dataset: Optional[Union[int, float]] = None,\n",
243
+ " seed: Optional[int] = None,\n",
244
+ " min_area_px: int = 0, # optional stricter filter\n",
245
+ " strict_match: bool = False, # True: error on missing mask\n",
246
+ " mmap_images: bool = True,\n",
247
+ " return_paths: bool = False,\n",
248
+ " # optional fallback to repair labels if your CSV is old\n",
249
+ " root_for_relabel: Optional[Union[str, Path]] = None,\n",
250
+ " split_for_relabel: Optional[str] = None, # \"train\" or \"test\"\n",
251
+ " ):\n",
252
+ " self.manifest_csv_gz = str(Path(manifest_csv_gz).expanduser())\n",
253
+ " self.strict_match = strict_match\n",
254
+ " self.mmap_images = mmap_images\n",
255
+ " self.return_paths = return_paths\n",
256
+ " self._rng = random.Random(seed) if seed is not None else random\n",
257
+ "\n",
258
+ " allowed = None if datasets is None else ({datasets} if isinstance(datasets, str) else set(datasets))\n",
259
+ "\n",
260
+ " # Load manifest rows\n",
261
+ " rows = []\n",
262
+ " with gzip.open(self.manifest_csv_gz, \"rt\", newline=\"\") as gz:\n",
263
+ " reader = csv.DictReader(gz)\n",
264
+ " for r in reader:\n",
265
+ " origin = r[\"origin\"]\n",
266
+ " if allowed is not None and origin not in allowed:\n",
267
+ " continue\n",
268
+ " area = int(r[\"area\"]) if r[\"area\"] else 0\n",
269
+ " if min_area_px > 0 and area < min_area_px:\n",
270
+ " continue\n",
271
+ " rows.append((\n",
272
+ " r[\"img_path\"],\n",
273
+ " origin,\n",
274
+ " r[\"label\"], # may be \"\" only when dataset actually has no label dirs\n",
275
+ " r[\"mask_dir\"],\n",
276
+ " int(r[\"has_empty\"]),\n",
277
+ " r[\"stem\"],\n",
278
+ " int(r[\"h\"]),\n",
279
+ " int(r[\"w\"]),\n",
280
+ " area,\n",
281
+ " ))\n",
282
+ "\n",
283
+ " if not rows:\n",
284
+ " raise RuntimeError(\"Manifest filter produced 0 rows.\")\n",
285
+ "\n",
286
+ " # Per-origin subsampling BEFORE storing\n",
287
+ " by_origin: Dict[str, List[tuple]] = {}\n",
288
+ " for t in rows:\n",
289
+ " by_origin.setdefault(t[1], []).append(t)\n",
290
+ "\n",
291
+ " sel_rows: List[tuple] = []\n",
292
+ " for origin, items in by_origin.items():\n",
293
+ " raw = per_dataset_limits.get(origin) if per_dataset_limits else None\n",
294
+ " if raw is None and max_per_dataset is not None:\n",
295
+ " raw = max_per_dataset\n",
296
+ " n_keep = _subset_size(raw, len(items))\n",
297
+ " if n_keep is None or n_keep >= len(items):\n",
298
+ " sel_rows.extend(items)\n",
299
+ " elif n_keep > 0:\n",
300
+ " items_copy = items[:]\n",
301
+ " self._rng.shuffle(items_copy)\n",
302
+ " sel_rows.extend(items_copy[:n_keep])\n",
303
+ "\n",
304
+ " if not sel_rows:\n",
305
+ " raise RuntimeError(\"All rows filtered out by per_dataset_limits/max_per_dataset.\")\n",
306
+ "\n",
307
+ " # Optional on-the-fly relabel for legacy CSVs\n",
308
+ " if root_for_relabel is not None and split_for_relabel is not None:\n",
309
+ " root_fix = Path(root_for_relabel).expanduser().resolve()\n",
310
+ " fixed_rows = []\n",
311
+ " for (img_path, origin, label, mask_dir, has_empty, stem, h, w, area) in sel_rows:\n",
312
+ " if (label or \"\").strip() == \"\":\n",
313
+ " label = _derive_label_from_path(img_path, root_fix, split_for_relabel, origin)\n",
314
+ " fixed_rows.append((img_path, origin, label, mask_dir, has_empty, stem, h, w, area))\n",
315
+ " sel_rows = fixed_rows\n",
316
+ "\n",
317
+ " # store\n",
318
+ " # idx: 0=img_path,1=origin,2=label,3=mask_dir,4=has_empty,5=stem,6=h,7=w,8=area\n",
319
+ " self._rows = sel_rows\n",
320
+ "\n",
321
+ " def __len__(self) -> int:\n",
322
+ " return len(self._rows)\n",
323
+ "\n",
324
+ " def _resolve_mask_path(self, mask_dir: str, has_empty: int, stem: str) -> Optional[str]:\n",
325
+ " if has_empty:\n",
326
+ " return None\n",
327
+ " mdir = Path(mask_dir)\n",
328
+ " for cand in _mask_guess_paths(mdir, stem):\n",
329
+ " if cand.exists():\n",
330
+ " return str(cand)\n",
331
+ " if self.strict_match:\n",
332
+ " raise FileNotFoundError(f\"Mask for stem='{stem}' not found under {mdir}\")\n",
333
+ " return None\n",
334
+ "\n",
335
+ " def __getitem__(self, idx: int) -> Dict[str, Any]:\n",
336
+ " img_path, origin, label, mask_dir, has_empty, stem, h, w, area = self._rows[idx]\n",
337
+ " mmap = \"r\" if self.mmap_images else None\n",
338
+ " img = np.load(img_path, allow_pickle=False, mmap_mode=mmap)\n",
339
+ " mask_path = self._resolve_mask_path(mask_dir, has_empty, stem)\n",
340
+ " msk = None if mask_path is None else np.load(mask_path, allow_pickle=False, mmap_mode=mmap)\n",
341
+ "\n",
342
+ " out = {\n",
343
+ " \"image\": _to_tensor_img(img), # C,H,W (original channels)\n",
344
+ " \"mask\": _to_tensor_mask(msk), # H,W or None\n",
345
+ " \"origin\": origin,\n",
346
+ " \"label\": (label if (label or \"\").strip() != \"\" else None),\n",
347
+ " }\n",
348
+ " if self.return_paths:\n",
349
+ " out[\"paths\"] = (img_path, mask_path)\n",
350
+ " return out\n",
351
+ "\n",
352
+ "\n",
353
+ "# ------------------------- mini sanity check helpers -------------------------\n",
354
+ "\n",
355
+ "def debug_count_empty_labels(manifest_gz: str, origins: Optional[List[str]] = None):\n",
356
+ " \"\"\"Quick check: show how many rows have empty label per origin in the CSV.\"\"\"\n",
357
+ " by_origin = {}\n",
358
+ " with gzip.open(manifest_gz, \"rt\", newline=\"\") as gz:\n",
359
+ " r = csv.DictReader(gz)\n",
360
+ " for row in r:\n",
361
+ " o = row[\"origin\"]\n",
362
+ " if origins is not None and o not in origins:\n",
363
+ " continue\n",
364
+ " by_origin.setdefault(o, {\"total\": 0, \"empty\": 0})\n",
365
+ " by_origin[o][\"total\"] += 1\n",
366
+ " if (row[\"label\"] or \"\").strip() == \"\":\n",
367
+ " by_origin[o][\"empty\"] += 1\n",
368
+ " for o in sorted(by_origin.keys()):\n",
369
+ " t, e = by_origin[o][\"total\"], by_origin[o][\"empty\"]\n",
370
+ " print(f\"{o:20s} empty={e:7d} / total={t:7d} ({(e/t*100):6.2f}% empty)\")\n"
371
+ ]
372
+ },
373
+ {
374
+ "cell_type": "markdown",
375
+ "id": "19ef8e1b-d568-4dec-8cf9-88c679e02814",
376
+ "metadata": {},
377
+ "source": [
378
+ "# RUN ONCE"
379
+ ]
380
+ },
381
+ {
382
+ "cell_type": "code",
383
+ "execution_count": null,
384
+ "id": "e3b2cf29-6492-4400-9d1a-5eaf94712b88",
385
+ "metadata": {},
386
+ "outputs": [],
387
+ "source": [
388
+ "ALL_DATASETS = [\n",
389
+ " 'N_MoNuSAC',\n",
390
+ " 'N_DynamicNuclearNet',\n",
391
+ " 'N_omnipose',\n",
392
+ " 'N_iPSC_Morpologies',\n",
393
+ " 'N_PanNuke','N_MoNuSeg',\n",
394
+ " 'N_databowl',\n",
395
+ " 'N_cyto2',\n",
396
+ " 'N_tissuenet',\n",
397
+ " 'N_BCCD',\n",
398
+ " 'N_CoNIC',\n",
399
+ " 'N_lynsec13',\n",
400
+ " 'N_NuInsSeg',\n",
401
+ " 'N_iPSC_QCData',\n",
402
+ " 'N_Satorious'\n",
403
+ "]\n",
404
+ "\n",
405
+ "\n",
406
+ "'''\n",
407
+ "Had to remove some datasets due to liscencing isues\n",
408
+ "[\n",
409
+ " \"N_BCCD\",\n",
410
+ " \"N_CMP_15_17_and_TNBC\"\n",
411
+ " \"N_CoNIC\",\n",
412
+ " \"N_CryoNuSeg\",\n",
413
+ " \"N_DynamicNuclearNet\",\n",
414
+ " \"N_IHC_TMA\",\n",
415
+ " \"N_MoNuSAC\",\n",
416
+ " \"N_MoNuSeg\",\n",
417
+ " \"N_Neurips\",\n",
418
+ " \"N_NuInsSeg\",\n",
419
+ " \"N_PanNuke\",\n",
420
+ " \"N_Phenoplex\",\n",
421
+ " \"N_cyto2\",\n",
422
+ " \"N_databowl\",\n",
423
+ " \"N_iPSC_Morpologies\",\n",
424
+ " \"N_iPSC_QCData\",\n",
425
+ " \"N_lynsec13\",\n",
426
+ " \"N_omnipose\",\n",
427
+ " \"N_tissuenet\",\n",
428
+ " \"N_yeaz\",\n",
429
+ " \"N_Satorious\",\n",
430
+ " \"N_Helmholtz\"\n",
431
+ "]'''\n",
432
+ "\n",
433
+ "# 1) REBUILD the manifest with guaranteed labels\n",
434
+ "build_manifest_csv(\n",
435
+ " root=\".\", # your root that contains the N_* folders\n",
436
+ " split=\"train\",\n",
437
+ " out_csv_gz=\"./manifest_train_fixed.csv.gz\",\n",
438
+ " datasets=ALL_DATASETS, # restrict scanning to exactly these origins\n",
439
+ " min_area_px=20*18,\n",
440
+ " workers=32,\n",
441
+ " force_threads=None, # threads on macOS, processes elsewhere\n",
442
+ ")"
443
+ ]
444
+ },
445
+ {
446
+ "cell_type": "markdown",
447
+ "id": "87ab3b2f-0da0-469c-a93f-b19cbe2c8292",
448
+ "metadata": {},
449
+ "source": [
450
+ "# Data Loader"
451
+ ]
452
+ },
453
+ {
454
+ "cell_type": "code",
455
+ "execution_count": 4,
456
+ "id": "3aa5e541-6290-46d1-838e-e6df6ca5aaf1",
457
+ "metadata": {},
458
+ "outputs": [
459
+ {
460
+ "name": "stdout",
461
+ "output_type": "stream",
462
+ "text": [
463
+ "N_BCCD empty= 81732 / total= 81732 (100.00% empty)\n",
464
+ "N_CMP_15_17_and_TNBC empty= 0 / total= 10462 ( 0.00% empty)\n",
465
+ "N_CoNIC empty= 0 / total= 6927 ( 0.00% empty)\n",
466
+ "N_CryoNuSeg empty= 0 / total= 2046 ( 0.00% empty)\n",
467
+ "N_DynamicNuclearNet empty= 312815 / total= 312815 (100.00% empty)\n",
468
+ "N_Helmholtz empty= 0 / total= 31159 ( 0.00% empty)\n",
469
+ "N_IHC_TMA empty= 0 / total= 6439 ( 0.00% empty)\n",
470
+ "N_MoNuSAC empty= 0 / total= 25870 ( 0.00% empty)\n",
471
+ "N_MoNuSeg empty= 14428 / total= 14428 (100.00% empty)\n",
472
+ "N_Neurips empty= 88619 / total= 88619 (100.00% empty)\n",
473
+ "N_NuInsSeg empty= 0 / total= 22764 ( 0.00% empty)\n",
474
+ "N_PanNuke empty= 0 / total= 94135 ( 0.00% empty)\n",
475
+ "N_Phenoplex empty= 0 / total= 447820 ( 0.00% empty)\n",
476
+ "N_cyto2 empty= 64605 / total= 64605 (100.00% empty)\n",
477
+ "N_databowl empty= 13412 / total= 13412 (100.00% empty)\n",
478
+ "N_iPSC_Morpologies empty= 0 / total= 5131 ( 0.00% empty)\n",
479
+ "N_iPSC_QCData empty= 0 / total= 26647 ( 0.00% empty)\n",
480
+ "N_lynsec13 empty= 0 / total= 63609 ( 0.00% empty)\n",
481
+ "N_omnipose empty= 0 / total= 33335 ( 0.00% empty)\n",
482
+ "N_tissuenet empty= 780196 / total= 780196 (100.00% empty)\n",
483
+ "N_yeaz empty= 19606 / total= 19606 (100.00% empty)\n"
484
+ ]
485
+ }
486
+ ],
487
+ "source": [
488
+ "debug_count_empty_labels(\"./manifest_train_fixed.csv.gz\", origins=ALL_DATASETS)\n",
489
+ "\n",
490
+ "# 3) Load dataset (no resizing/channel forcing, as requested)\n",
491
+ "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",
492
+ "ds = ManifestSegDataset(\n",
493
+ " manifest_csv_gz=\"./manifest_train_fixed.csv.gz\",\n",
494
+ " datasets=ALL_DATASETS,\n",
495
+ " per_dataset_limits=PER_DATASET_LIMITS,\n",
496
+ " min_area_px=20*18,\n",
497
+ " seed=42,\n",
498
+ " mmap_images=True,\n",
499
+ " strict_match=False,\n",
500
+ " return_paths=True,\n",
501
+ "\n",
502
+ " # If for some reason you still have an *old* CSV with empties, uncomment these two:\n",
503
+ " # root_for_relabel=\".\", # absolute/relative path to root\n",
504
+ " # split_for_relabel=\"train\",\n",
505
+ ")"
506
+ ]
507
+ },
508
+ {
509
+ "cell_type": "code",
510
+ "execution_count": null,
511
+ "id": "bf202508-d4b5-43be-a111-883f0a025d51",
512
+ "metadata": {},
513
+ "outputs": [],
514
+ "source": []
515
+ }
516
+ ],
517
+ "metadata": {
518
+ "kernelspec": {
519
+ "display_name": "Python 3 (ipykernel)",
520
+ "language": "python",
521
+ "name": "python3"
522
+ },
523
+ "language_info": {
524
+ "codemirror_mode": {
525
+ "name": "ipython",
526
+ "version": 3
527
+ },
528
+ "file_extension": ".py",
529
+ "mimetype": "text/x-python",
530
+ "name": "python",
531
+ "nbconvert_exporter": "python",
532
+ "pygments_lexer": "ipython3",
533
+ "version": "3.11.9"
534
+ }
535
+ },
536
+ "nbformat": 4,
537
+ "nbformat_minor": 5
538
+ }
N_BCCD.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:091cbd8b1735347d104aa0001b292f543b205cde11d5d1034e7a63ab59fc3463
3
+ size 4065714280
N_CoNIC.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d5cb48d2f70ef1628c142bde879321a0bec0880a186da69a9c16b7721c0dad8
3
+ size 620547108
N_DynamicNuclearNet.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5f26b3ee22dda7705181f7bb560d52e997648ac950a258ea993834217e404ce
3
+ size 2481715060
N_MoNuSAC.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca78db52c6428f6a164a49753aa623aa9975c84a9a55855289575d28bad3b9ef
3
+ size 170947730
N_MoNuSeg.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c9b840413dbe8608e9f460998bacfcd9f915ba2849a0ba9dc825ac0d0eba6226
3
+ size 72227948
N_NuInsSeg.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c328ed340405abbede85b61b200a0f8a019a1a5ffdd84100776200cb2944f17
3
+ size 162222112
N_PanNuke.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3285903c2dd8846d8561b485c9439de932a6405e4b851a581bc524c260539327
3
+ size 705216638
N_Satorious.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ca7affd9b3281500fbd0bb58b74aa2d70930f70d60627852bc7f774cbc12bae
3
+ size 323635855
N_cyto2.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:520505179d558b07f6abfacad6b2af569b2d7ed16dbd7a59a5940f9f8374d920
3
+ size 651080692
N_databowl.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8961e28c80815f415720e187dae7317a31bb53efd798dec59ce4b96d525a284c
3
+ size 87506406
N_iPSC_Morpologies.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c91d412e03153a69fd1fd8c98b60eaca3f929ae672f5218a29d8a30f7fe51bd
3
+ size 31606222
N_iPSC_QCData.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:40a073dbb9a74ef47263ad43e2bbab94b89b8829bf3a70b7317159f7c5bc169e
3
+ size 899372689
N_lynsec13.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf5101d122d22fd3e18e70b66511aa08c5c2ecc7fa1f0a49d2aa3a5d8f5cc143
3
+ size 264993544
N_omnipose.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7d09ae8b0139cbcebb04bdb06f07bd8f885f990cfc3ed7bc3ec1b6b929a54921
3
+ size 519908238
N_tissuenet.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84eec0607c5110cc398a68ad8e97496a3d997caa181c28870df35aa06ecdfe3c
3
+ size 25317691211