hemato / scripts /build.py
KeremTT's picture
Dataset card, metadata, detection subset and build scripts (part 3)
3e45900 verified
Raw History Blame Contribute Delete
8.8 kB
"""HEMATO v1.0 builder. Reads raw sources (raw/), writes dataset/<config>/<split>/<class>/<file> and manifest.csv.
Configs: cls (bone marrow + peripheral blood cell types), all (C-NMC ALL vs normal), malaria (NIH), det (BCCD, YOLO).
Images are copied byte-for-byte when already JPEG/PNG; BMP (C-NMC) is converted losslessly to PNG."""
import csv, glob, io, os, random, re, shutil, zipfile
from collections import defaultdict
import pyarrow.parquet as pq
from PIL import Image
RAW, OUT = 'raw', 'dataset'
SEED = 42
RATIOS = (('train', .70), ('val', .15), ('test', .15))
# ---- unified cell-type vocabulary (cls) ----------------------------------------------------------
# folder name: (Turkish name, bone-marrow code (Matek 2021), PBC filename prefix (Acevedo 2020))
CLASSES = {
'Blast': ('Blast', 'BLA', None),
'Promyelocyte': ('Promiyelosit', 'PMO', 'PMY'),
'Myelocyte': ('Miyelosit', 'MYB', 'MY'),
'Metamyelocyte': ('Metamiyelosit', 'MMZ', 'MMY'),
'Band_neutrophil': ('Çomak nötrofil', 'NGB', 'BNE'),
'Segmented_neutrophil': ('Segmentli nötrofil', 'NGS', 'SNE'),
'Eosinophil': ('Eozinofil', 'EOS', 'EO'),
'Basophil': ('Bazofil', 'BAS', 'BA'),
'Lymphocyte': ('Lenfosit', 'LYT', 'LY'),
'Monocyte': ('Monosit', 'MON', 'MO'),
'Proerythroblast': ('Proeritroblast', 'PEB', None),
'Erythroblast': ('Eritroblast', 'EBO', 'ERB'),
'Plasma_cell': ('Plazma hücresi', 'PLM', None),
'Hairy_cell': ('Tüylü hücre (hairy cell)', 'HAC', None),
'Platelet': ('Trombosit', None, 'PLATELET'),
'Artefact': ('Artefakt', 'ART', None),
'Not_identifiable': ('Tanımlanamayan hücre', 'NIF', None),
}
BM_NAMES = ['ABE', 'ART', 'BAS', 'BLA', 'EBO', 'EOS', 'FGC', 'HAC', 'KSC', 'LYI', 'LYT', 'MMZ', 'MON', 'MYB', 'NGB', 'NGS', 'NIF', 'OTH', 'PEB', 'PLM', 'PMO']
BM2CLS = {v[1]: k for k, v in CLASSES.items() if v[1]}
PBC2CLS = {v[2]: k for k, v in CLASSES.items() if v[2]}
rows, excluded = [], []
def add(config, split, cls, fname, data, **meta):
d = os.path.join(OUT, config, split, cls); os.makedirs(d, exist_ok=True)
with open(os.path.join(d, fname), 'wb') as f: f.write(data)
rows.append(dict(config=config, split=split, label=cls, file=f'{config}/{split}/{cls}/{fname}', **meta))
def split_items(items, key=lambda x: x):
"""stratified random split of a list (per class) -> dict split->list"""
rnd = random.Random(SEED); items = sorted(items, key=key); rnd.shuffle(items)
n = len(items); a = round(n * .70); b = a + round(n * .15)
return {'train': items[:a], 'val': items[a:b], 'test': items[b:]}
def split_groups(groups_by_label):
"""patient-level split: groups (patients) are shuffled per label and assigned 70/15/15"""
out = {}
for lab, groups in groups_by_label.items():
for s, gs in split_items(sorted(groups)).items():
for g in gs: out[g] = s
return out
# ---- 1. bone marrow (Matek et al. 2021, MLL) -----------------------------------------------------
BM_FILES = sorted(glob.glob(f'{RAW}/bm/data/*.parquet'))
bm = defaultdict(list) # pass 1: labels + paths only (no image bytes -> low memory)
for f in BM_FILES:
pf = pq.ParquetFile(f)
for b in pf.iter_batches(batch_size=2000, columns=['image', 'label']):
d = b.to_pydict()
for im, lab in zip(d['image'], d['label']):
code = BM_NAMES[lab]
if code not in BM2CLS:
excluded.append(('bone_marrow', im['path'], code, 'class too small / heterogeneous')); continue
bm[BM2CLS[code]].append(im['path'])
bm_split = {}
for cls, paths in bm.items():
for split, ps in split_items(paths).items():
for p in ps: bm_split[p] = (split, cls)
for f in BM_FILES: # pass 2: stream image bytes batch by batch
for b in pq.ParquetFile(f).iter_batches(batch_size=500, columns=['image', 'label']):
d = b.to_pydict()
for im, lab in zip(d['image'], d['label']):
if im['path'] not in bm_split: continue
split, cls = bm_split[im['path']]
add('cls', split, cls, f'BM_{im["path"]}', im['bytes'], source='bone_marrow_mll', original_label=BM_NAMES[lab], original_file=im['path'], patient_id='')
print('bone marrow done', len(bm_split))
# ---- 2. peripheral blood (PBC, Acevedo et al. 2020) ----------------------------------------------
z = zipfile.ZipFile(f'{RAW}/pbc/PBC_dataset_normal_DIB.zip')
pbc = defaultdict(list)
for n in z.namelist():
if n.startswith('__MACOSX') or not n.lower().endswith('.jpg'): continue
fn = n.split('/')[-1]; pre = fn.split('_')[0]
if pre not in PBC2CLS:
excluded.append(('pbc', n, pre, 'subtype not specified (IG / NEUTROPHIL)')); continue
pbc[PBC2CLS[pre]].append((n, fn, pre))
for cls, items in pbc.items():
for split, its in split_items(items, key=lambda x: x[0]).items():
for n, fn, pre in its:
add('cls', split, cls, f'PBC_{fn}', z.read(n), source='pbc_acevedo', original_label=pre, original_file=n, patient_id='')
print('pbc done', sum(len(v) for v in pbc.values()))
# ---- 3. C-NMC 2019 ALL vs normal (patient-level split) -------------------------------------------
CN_FILES = sorted(glob.glob(f'{RAW}/cnmc/data/*.parquet'))
g = defaultdict(set)
t = pq.read_table(CN_FILES, columns=['subject_id', 'label']).to_pydict()
for sid, lab in zip(t['subject_id'], t['label']): g['ALL' if lab == 'cancer' else 'Normal'].add(sid)
sp = split_groups(g)
n_cn = 0
for f in CN_FILES:
for b in pq.ParquetFile(f).iter_batches(batch_size=300, columns=['subject_id', 'label', 'image', 'original_image_name']):
d = b.to_pydict()
for sid, lab, im, name in zip(d['subject_id'], d['label'], d['image'], d['original_image_name']):
lab = 'ALL' if lab == 'cancer' else 'Normal'
try:
buf = io.BytesIO(); Image.open(io.BytesIO(im['bytes'])).save(buf, 'PNG', optimize=True)
except Exception as e:
excluded.append(('c_nmc_2019', name, lab, f'corrupt image ({type(e).__name__})')); continue
add('all', sp[sid], lab, f'CNMC_{os.path.splitext(name)[0]}.png', buf.getvalue(), source='c_nmc_2019', original_label=lab, original_file=name, patient_id=f'CNMC_{sid}')
n_cn += 1
print('cnmc done', n_cn)
# ---- 4. NIH malaria (patient-level split) --------------------------------------------------------
z = zipfile.ZipFile(f'{RAW}/malaria/cell_images.zip')
mal = []
for n in z.namelist():
if not n.endswith('.png'): continue
lab = 'Parasitized' if '/Parasitized/' in n else 'Uninfected'
fn = n.split('/')[-1]; pid = re.split(r'[Tt]hin', fn)[0].rstrip('_')
mal.append((pid, lab, n, fn))
pat_lab = defaultdict(set)
for pid, lab, _, _ in mal: pat_lab[pid].add(lab)
g = defaultdict(set)
for pid, labs in pat_lab.items(): g['infected_patient' if 'Parasitized' in labs else 'healthy_patient'].add(pid)
sp = split_groups(g)
for pid, lab, n, fn in mal:
add('malaria', sp[pid], lab, f'NIH_{fn}', z.read(n), source='nih_malaria', original_label=lab, original_file=n, patient_id=f'NIH_{pid}')
print('malaria done', len(mal))
# ---- 5. BCCD detection (YOLO, original split kept) -----------------------------------------------
for s_in, s_out in (('train', 'train'), ('valid', 'val'), ('test', 'test')):
for img in sorted(glob.glob(f'{RAW}/bccd/{s_in}/images/*')):
base = os.path.splitext(os.path.basename(img))[0]
lbl = f'{RAW}/bccd/{s_in}/labels/{base}.txt'
for sub, src in (('images', img), ('labels', lbl)):
d = os.path.join(OUT, 'det', sub, s_out); os.makedirs(d, exist_ok=True)
shutil.copy(src, d)
rows.append(dict(config='det', split=s_out, label='', file=f'det/images/{s_out}/{os.path.basename(img)}', source='bccd',
original_label='', original_file=img.split('/', 2)[-1], patient_id=''))
with open(os.path.join(OUT, 'det', 'data.yaml'), 'w') as f:
f.write('path: .\ntrain: images/train\nval: images/val\ntest: images/test\nnc: 3\nnames: [Platelets, RBC, WBC]\n')
print('bccd done')
with open('manifest.csv', 'w', newline='') as f:
w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)
with open('excluded.csv', 'w', newline='') as f:
w = csv.writer(f); w.writerow(['source', 'file', 'original_label', 'reason']); w.writerows(excluded)
print('rows', len(rows), 'excluded', len(excluded))