File size: 23,581 Bytes
b44dfb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
{
 "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<p<=1 -> 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 '.../<split>/**/original' under selected origins.\n",
    "    Returns list: (original_dir_path, origin_name)\n",
    "    \"\"\"\n",
    "    origins = [p for p in root.iterdir() if p.is_dir() and (allowed is None or p.name in allowed)]\n",
    "    if allowed is not None:\n",
    "        name2path = {p.name: p for p in origins}\n",
    "        origins = [name2path[n] for n in allowed if n in name2path]\n",
    "\n",
    "    out: List[Tuple[Path, str]] = []\n",
    "    for origin in origins:\n",
    "        for dirpath, _, _ in os.walk(origin):\n",
    "            if os.path.basename(dirpath) != \"original\":\n",
    "                continue\n",
    "            parts = Path(dirpath).relative_to(root).parts\n",
    "            if split in parts[:-1]:\n",
    "                out.append((Path(dirpath), origin.name))\n",
    "    return out\n",
    "\n",
    "def _derive_label_from_path(img_path: str, root: Path, split: str, origin: str) -> str:\n",
    "    \"\"\"\n",
    "    Parse labels from absolute img_path.\n",
    "    Supports:\n",
    "      origin/<labels...>/<split>/original/file.npy\n",
    "      origin/<split>/<labels...>/original/file.npy\n",
    "    Returns \"\" if no labels found.\n",
    "    \"\"\"\n",
    "    parts = Path(img_path).resolve().relative_to(root).parts\n",
    "    # locate origin\n",
    "    try:\n",
    "        i0 = parts.index(origin)\n",
    "    except ValueError:\n",
    "        return \"\"\n",
    "    # locate split after origin\n",
    "    j = None\n",
    "    for k in range(i0 + 1, len(parts)):\n",
    "        if parts[k] == split:\n",
    "            j = k\n",
    "            break\n",
    "    if j is None:\n",
    "        return \"\"\n",
    "    # locate 'original' after split\n",
    "    try:\n",
    "        k_orig = parts.index(\"original\", j + 1)\n",
    "    except ValueError:\n",
    "        return \"\"\n",
    "    pre = list(parts[i0 + 1 : j])\n",
    "    post = list(parts[j + 1 : k_orig])\n",
    "    label_parts = pre + post\n",
    "    return \"__\".join(label_parts) if label_parts else \"\"\n",
    "\n",
    "\n",
    "# ------------------------- 1) MANIFEST BUILDER (guaranteed labels) -------------------------\n",
    "\n",
    "def build_manifest_csv(\n",
    "    root: Union[str, Path],\n",
    "    split: str,\n",
    "    out_csv_gz: Union[str, Path],\n",
    "    *,\n",
    "    datasets: Optional[Union[str, List[str]]] = None,   # filter top-level origins (N_*)\n",
    "    min_area_px: int = 0,                                # early filter by H*W\n",
    "    workers: int = 16,                                   # parallel header reads\n",
    "    force_threads: Optional[bool] = None,                # True -> ThreadPool; default True on macOS\n",
    "    chunk_size: int = 100_000,\n",
    ") -> None:\n",
    "    \"\"\"\n",
    "    ONE-TIME scan -> compressed manifest CSV with correct labels for every file.\n",
    "    Writes rows:\n",
    "        img_path,origin,label,mask_dir,has_empty,stem,h,w,area\n",
    "    - 'label' is derived per-file from path; \"\" only if there truly are no label folders.\n",
    "    \"\"\"\n",
    "    root = Path(root).expanduser().resolve()\n",
    "    allowed = None if datasets is None else ({datasets} if isinstance(datasets, str) else set(datasets))\n",
    "    original_dirs = _iter_original_dirs(root, split, allowed)\n",
    "\n",
    "    # Build candidate list\n",
    "    candidates: List[tuple] = []\n",
    "    for orig_dir, origin_name in original_dirs:\n",
    "        with os.scandir(orig_dir) as it:\n",
    "            for e in it:\n",
    "                if not e.is_file() or not e.name.endswith(\".npy\"):\n",
    "                    continue\n",
    "                img_path = Path(e.path).resolve()\n",
    "                stem = img_path.stem\n",
    "                base_dir = img_path.parent.parent  # parent of 'original'\n",
    "                mask_dir = base_dir / \"mask\"\n",
    "                empty_mask_dir = base_dir / \"empty_mask\"\n",
    "                has_empty = 1 if empty_mask_dir.exists() else 0\n",
    "                label = _derive_label_from_path(str(img_path), root, split, origin_name)\n",
    "                candidates.append((str(img_path), origin_name, label, str(mask_dir), has_empty, stem))\n",
    "\n",
    "    # Choose executor type\n",
    "    if force_threads is None:\n",
    "        use_threads = (platform.system() == \"Darwin\")\n",
    "    else:\n",
    "        use_threads = bool(force_threads)\n",
    "    Executor = ThreadPoolExecutor if use_threads else ProcessPoolExecutor\n",
    "    map_kwargs = {} if use_threads else {\"chunksize\": 64}\n",
    "\n",
    "    # Stream to gz CSV\n",
    "    out_csv_gz = Path(out_csv_gz)\n",
    "    out_csv_gz.parent.mkdir(parents=True, exist_ok=True)\n",
    "    with gzip.open(out_csv_gz, \"wt\", newline=\"\") as gz, Executor(max_workers=max(1, workers)) as ex:\n",
    "        writer = csv.writer(gz)\n",
    "        writer.writerow([\"img_path\", \"origin\", \"label\", \"mask_dir\", \"has_empty\", \"stem\", \"h\", \"w\", \"area\"])\n",
    "\n",
    "        for start in range(0, len(candidates), chunk_size):\n",
    "            batch = candidates[start:start + chunk_size]\n",
    "            paths  = [t[0] for t in batch]\n",
    "            metas  = [t[1:] for t in batch]  # (origin,label,mask_dir,has_empty,stem)\n",
    "\n",
    "            for (h, w, area), (origin,label,mask_dir,has_empty,stem), path in zip(\n",
    "                ex.map(_read_shape_area_job, paths, **map_kwargs), metas, paths\n",
    "            ):\n",
    "                if h is None or w is None or area is None:\n",
    "                    continue\n",
    "                if min_area_px > 0 and area < min_area_px:\n",
    "                    continue\n",
    "                # write exactly what we derived; empty string only when truly no label dirs\n",
    "                writer.writerow([path, origin, label, mask_dir, has_empty, stem, h, w, area])\n",
    "\n",
    "\n",
    "# ------------------------- 2) DATASET FROM MANIFEST (fast; with relabel fallback) -------------------------\n",
    "\n",
    "class ManifestSegDataset(Dataset):\n",
    "    \"\"\"\n",
    "    Ultra-fast dataset backed by the manifest.\n",
    "    - per_dataset_limits supports {-1, k, 0<p<=1}\n",
    "    - mask path resolved lazily on access\n",
    "    - area filter uses manifest's H*W\n",
    "    - If some rows in a legacy manifest had empty labels, you can pass root_for_relabel+split_for_relabel\n",
    "      and it will fix labels on the fly.\n",
    "    \"\"\"\n",
    "    def __init__(\n",
    "        self,\n",
    "        manifest_csv_gz: Union[str, Path],\n",
    "        *,\n",
    "        datasets: Optional[Union[str, List[str]]] = None,     # filter by origin(s)\n",
    "        per_dataset_limits: Optional[Dict[str, Union[int, float]]] = None,\n",
    "        max_per_dataset: Optional[Union[int, float]] = None,\n",
    "        seed: Optional[int] = None,\n",
    "        min_area_px: int = 0,                                  # optional stricter filter\n",
    "        strict_match: bool = False,                            # True: error on missing mask\n",
    "        mmap_images: bool = True,\n",
    "        return_paths: bool = False,\n",
    "        # optional fallback to repair labels if your CSV is old\n",
    "        root_for_relabel: Optional[Union[str, Path]] = None,\n",
    "        split_for_relabel: Optional[str] = None,               # \"train\" or \"test\"\n",
    "    ):\n",
    "        self.manifest_csv_gz = str(Path(manifest_csv_gz).expanduser())\n",
    "        self.strict_match = strict_match\n",
    "        self.mmap_images = mmap_images\n",
    "        self.return_paths = return_paths\n",
    "        self._rng = random.Random(seed) if seed is not None else random\n",
    "\n",
    "        allowed = None if datasets is None else ({datasets} if isinstance(datasets, str) else set(datasets))\n",
    "\n",
    "        # Load manifest rows\n",
    "        rows = []\n",
    "        with gzip.open(self.manifest_csv_gz, \"rt\", newline=\"\") as gz:\n",
    "            reader = csv.DictReader(gz)\n",
    "            for r in reader:\n",
    "                origin = r[\"origin\"]\n",
    "                if allowed is not None and origin not in allowed:\n",
    "                    continue\n",
    "                area = int(r[\"area\"]) if r[\"area\"] else 0\n",
    "                if min_area_px > 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
}