Download scripts/v2build.py from KeremTT/hemato: direct link, hf CLI and curl.
- Browser
- Download file 17.4 kB
-
https://huggingface.co/datasets/KeremTT/hemato/resolve/main/scripts/v2build.py
- Command line
-
hf download hf://datasets/KeremTT/hemato/scripts/v2build.py
-
curl -L -o v2build.py https://huggingface.co/datasets/KeremTT/hemato/resolve/main/scripts/v2build.py
17.4 kB
| """HEMATO v2.0 source processors. Usage: python3 v2build.py <source> [...] | |
| Each processor writes standardized images to dataset2/<config>/<split>/<class>/<file> and rows to manifest2/<source>.csv. | |
| Splits for new sources are 70/15/15 at the patient / smear / image level (see KARARLAR.md); v1.0 is never touched.""" | |
| import csv, glob, io, os, random, re, sys, zipfile | |
| from collections import defaultdict | |
| from PIL import Image | |
| RAW = '/home/user/hemato/raw2' | |
| OUT = '/home/user/hemato/dataset2' | |
| MAN = '/home/user/hemato/manifest2' | |
| SEED = 42 | |
| os.makedirs(MAN, exist_ok=True) | |
| def split_groups(groups_by_strat): | |
| """groups (patients/smears/images) shuffled per stratum and assigned 70/15/15""" | |
| out = {} | |
| for strat in sorted(groups_by_strat): | |
| gs = sorted(groups_by_strat[strat]); random.Random(f'{SEED}-{strat}').shuffle(gs) | |
| n = len(gs); a = round(n * .70); b = a + round(n * .15) | |
| if n >= 3 and b >= n: b = n - 1 # keep at least one group for test when possible | |
| if n >= 3 and a == b: a = b - 1 | |
| for i, g in enumerate(gs): out[g] = 'train' if i < a else 'val' if i < b else 'test' | |
| return out | |
| def save_cls_image(img, path, max_side=400): | |
| """RGB JPEG q95; images larger than max_side are downscaled (v1.0 cells are 250-363 px)""" | |
| im = img.convert('RGB') | |
| if max(im.size) > max_side: | |
| im.thumbnail((max_side, max_side), Image.LANCZOS) | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| im.save(path, 'JPEG', quality=95) | |
| return im.size | |
| class Writer: | |
| def __init__(self, source, license_, citation, url): | |
| self.source, self.lic, self.cit, self.url = source, license_, citation, url | |
| self.rows = [] | |
| def add(self, config, split, label, fname, group, original_label, original_file, size, extra=''): | |
| self.rows.append(dict(config=config, split=split, label=label, file=f'{config}/{split}/{label}/{fname}' if label else fname, | |
| source=self.source, group_id=group, original_label=original_label, original_file=original_file, | |
| width=size[0], height=size[1], source_license=self.lic, source_citation=self.cit, source_url=self.url, note=extra)) | |
| def close(self): | |
| with open(f'{MAN}/{self.source}.csv', 'w', newline='') as f: | |
| w = csv.DictWriter(f, fieldnames=list(self.rows[0])); w.writeheader(); w.writerows(self.rows) | |
| print(self.source, len(self.rows), 'rows') | |
| # ------------------------------------------------------------------------------------------------ CLS | |
| def ku_optofil(): | |
| MAP = {'Band Neutrophil': 'Band_neutrophil', 'Segmented Neutrophil': 'Segmented_neutrophil', 'Basophil': 'Basophil', 'Eosinophil': 'Eosinophil', | |
| 'Lymphocyte': 'Lymphocyte', 'Monocyte': 'Monocyte', 'Metamyelocyte': 'Metamyelocyte', 'Myelocyte': 'Myelocyte', | |
| 'Erythroblast': 'Erythroblast', 'Blast': 'Blast'} | |
| w = Writer('ku_optofil_pbc', 'CC BY 4.0', 'KU-Optofil PBC: KU-Optofil Peripheral Blood Cell Dataset (Koç University / Optofil), Zenodo 2025', 'https://doi.org/10.5281/zenodo.17333317') | |
| meta = {r['image_name']: r for r in csv.DictReader(open(f'{RAW}/kuopt/metadata_with_patient_level_splits.csv'))} | |
| z = zipfile.ZipFile(f'{RAW}/kuopt/dataset.zip') | |
| items = [] | |
| for n in z.namelist(): | |
| if not n.lower().endswith(('.jpg', '.png')): continue | |
| cls_src = n.split('/')[-2]; fn = n.split('/')[-1] | |
| if cls_src not in MAP: continue | |
| pid = meta[fn]['patient_id'] if fn in meta else fn.split('_')[0] | |
| items.append((n, fn, MAP[cls_src], cls_src, pid)) | |
| groups = defaultdict(set) | |
| for _, _, _, _, pid in items: groups['all'].add(pid) # patients hold many classes: split patients as a whole | |
| sp = split_groups(groups) | |
| for n, fn, lab, src_lab, pid in items: | |
| s = sp[pid]; out = f'KUO_{fn.rsplit(".", 1)[0]}.jpg' | |
| size = save_cls_image(Image.open(io.BytesIO(z.read(n))), f'{OUT}/cls/{s}/{lab}/{out}') | |
| w.add('cls', s, lab, out, f'KUO_{pid}', src_lab, n, size) | |
| w.close() | |
| # ------------------------------------------------------------------------------------------------ ALL | |
| def cnmc_test(): | |
| import pyarrow.parquet as pq | |
| w = Writer('c_nmc_2019_prelim_test', 'CC BY 3.0', 'Gupta A., Gupta R. (2019) ALL Challenge dataset of ISBI 2019 (C-NMC 2019), preliminary test set. The Cancer Imaging Archive', 'https://doi.org/10.7937/tcia.2019.dc64i46r') | |
| files = sorted(glob.glob(f'{RAW}/cnmc_test/data/*.parquet')) | |
| t = pq.read_table(files, columns=['subject_id', 'label']).to_pydict() | |
| groups = defaultdict(set) | |
| for sid, lab in zip(t['subject_id'], t['label']): groups[lab].add(sid) | |
| sp = split_groups(groups) | |
| for f in files: | |
| for b in pq.ParquetFile(f).iter_batches(batch_size=200, columns=['subject_id', 'label', 'image', 'source_patient_id']): | |
| d = b.to_pydict() | |
| for sid, lab, im, name in zip(d['subject_id'], d['label'], d['image'], d['source_patient_id']): | |
| L = 'ALL' if lab == 'all' else 'Normal'; s = sp[sid] | |
| try: img = Image.open(io.BytesIO(im['bytes'])); img.load() | |
| except Exception: | |
| w.add('all', 'excluded', L, name, f'CNMC_{sid}', lab, name, (0, 0), 'corrupt'); continue | |
| out = f'CNMCT_{os.path.splitext(name)[0]}.png' | |
| p = f'{OUT}/all/{s}/{L}/{out}'; os.makedirs(os.path.dirname(p), exist_ok=True) | |
| img.convert('RGB').save(p, 'PNG', optimize=True) | |
| w.add('all', s, L, out, f'CNMC_{sid}', lab, name, img.size) | |
| w.close() | |
| # ------------------------------------------------------------------------------------------------ DET | |
| def txl_pbc(): | |
| REMAP = {'0': '2', '1': '1', '2': '0'} # TXL: 0 WBC,1 RBC,2 Platelets -> v1.0: 0 Platelets,1 RBC,2 WBC | |
| w = Writer('txl_pbc', 'CC BY 4.0', 'Lu et al. (2024) TXL-PBC: a curated and re-annotated peripheral blood cell dataset (BCCD, BCDD, PBC, Raabin-WBC). Figshare', 'https://figshare.com/articles/dataset/TXL-PBC_Dataset/27073186') | |
| z = zipfile.ZipFile(f'{RAW}/txl/TXL-PBC.zip') | |
| imgs = [n for n in z.namelist() if '/images/' in n and not n.endswith('/')] | |
| sp = split_groups({'all': {n.split('/')[-1] for n in imgs}}) # no patient/smear info: image-level split | |
| for n in imgs: | |
| fn = n.split('/')[-1]; stem = fn.rsplit('.', 1)[0] | |
| lbl_name = n.replace('/images/', '/labels/').rsplit('.', 1)[0] + '.txt' | |
| try: lines = z.read(lbl_name).decode().split('\n') | |
| except KeyError: lines = [] | |
| out_lines = [] | |
| for l in lines: | |
| p = l.split() | |
| if len(p) == 5 and p[0] in REMAP: out_lines.append(' '.join([REMAP[p[0]]] + p[1:])) | |
| img = Image.open(io.BytesIO(z.read(n))); img.load() | |
| s = sp[fn]; out = f'TXL_{stem}.jpg' | |
| for sub, data in (('images', None), ('labels', '\n'.join(out_lines) + ('\n' if out_lines else ''))): | |
| d = f'{OUT}/det/{sub}/{s}'; os.makedirs(d, exist_ok=True) | |
| if data is None: img.convert('RGB').save(f'{d}/{out}', 'JPEG', quality=95) | |
| else: open(f'{d}/TXL_{stem}.txt', 'w').write(data) | |
| w.add('det', s, '', f'det/images/{s}/{out}', f'TXL_{stem}', '', n, img.size, f'{len(out_lines)} boxes') | |
| w.close() | |
| def _crop(img, cx, cy, side): | |
| W, H = img.size; side = int(min(side, W, H)); x0 = int(round(cx - side / 2)); y0 = int(round(cy - side / 2)) | |
| x0 = max(0, min(W - side, x0)); y0 = max(0, min(H - side, y0)) | |
| return img.crop((x0, y0, x0 + side, y0 + side)), (x0, y0, x0 + side, y0 + side) | |
| def _overlap(a, b): | |
| ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1])) | |
| return ix * iy / float((a[2] - a[0]) * (a[3] - a[1])) | |
| def bcdd_sust(): | |
| NAMES = ['Band_Neutrophil', 'Giant_Platelet', 'Monocyte', 'Normal_Lymphocyte', 'Platelet', 'Reactive_Lymphocyte', 'Segmented_Neutrophil'] | |
| MAP = {'Band_Neutrophil': 'Band_neutrophil', 'Segmented_Neutrophil': 'Segmented_neutrophil', 'Monocyte': 'Monocyte', | |
| 'Normal_Lymphocyte': 'Lymphocyte', 'Platelet': 'Platelet'} | |
| w = Writer('bcdd_sust', 'CC BY 4.0', 'BCDD-SUST: An Annotated Peripheral Blood Cell Dataset for AI-Based Dengue Diagnosis (Shahjalal University of Science and Technology), Figshare 2026', 'https://doi.org/10.6084/m9.figshare.33951064.v1') | |
| z = zipfile.ZipFile(f'{RAW}/bcdd_sust/BCDD_SUST.zip') | |
| imgs = [n for n in z.namelist() if '/images/' in n and n.lower().endswith(('.jpg', '.png'))] | |
| sample = lambda n: n.split('/')[-1].split('_100X')[0] | |
| sp = split_groups({'all': {sample(n) for n in imgs}}) # 50 patient samples -> patient-level split | |
| for n in imgs: | |
| lbl = n.replace('/images/', '/labels/').rsplit('.', 1)[0] + '.txt' | |
| try: lines = [l.split() for l in z.read(lbl).decode().split('\n') if len(l.split()) == 5] | |
| except KeyError: continue | |
| img = None; taken = [] | |
| lines.sort(key=lambda p: NAMES[int(p[0])] == 'Platelet') # WBCs first | |
| for k, p in enumerate(lines): | |
| src = NAMES[int(p[0])] | |
| if src not in MAP: continue | |
| if img is None: img = Image.open(io.BytesIO(z.read(n))).convert('RGB') | |
| W, H = img.size; cx, cy, bw, bh = float(p[1]) * W, float(p[2]) * H, float(p[3]) * W, float(p[4]) * H | |
| # WBCs: window 1.6x the cell (cell fills ~60% like PBC crops); platelets: fixed 300 px field like PBC platelet images | |
| side = max(1.6 * max(bw, bh), 300) if src != 'Platelet' else 300 | |
| crop, box = _crop(img, cx, cy, side) | |
| if src == 'Platelet' and any(_overlap(box, t) > 0.25 for t in taken): continue # avoid near-identical overlapping fields | |
| taken.append(box) | |
| crop = crop.resize((360, 360), Image.LANCZOS) | |
| lab = MAP[src]; s = sp[sample(n)]; stem = n.split('/')[-1].rsplit('.', 1)[0]; out = f'SUST_{stem}_{k:03d}.jpg' | |
| size = save_cls_image(crop, f'{OUT}/cls/{s}/{lab}/{out}') | |
| w.add('cls', s, lab, out, f'SUST_{sample(n)}', src, f'{n}#box{k}', size) | |
| w.close() | |
| def bbbc041(): | |
| import json | |
| INF = {'trophozoite', 'ring', 'schizont', 'gametocyte'} | |
| w = Writer('bbbc041', 'CC BY-NC-SA 3.0', 'Hung J. et al. (2018) P. vivax (malaria) infected human blood smears, BBBC041v1, Broad Bioimage Benchmark Collection (Ljosa et al., Nature Methods 2012)', 'https://bbbc.broadinstitute.org/BBBC041') | |
| z = zipfile.ZipFile(f'{RAW}/bbbc041/malaria.zip') | |
| recs = json.loads(z.read('malaria/training.json')) + json.loads(z.read('malaria/test.json')) | |
| sp = split_groups({'all': {r['image']['pathname'] for r in recs}}) # no patient/slide info: image (field) level split | |
| for r in recs: | |
| path = r['image']['pathname']; img = Image.open(io.BytesIO(z.read('malaria' + path))).convert('RGB'); W, H = img.size | |
| stem = path.split('/')[-1].rsplit('.', 1)[0]; s = sp[path] | |
| objs = [o for o in r['objects'] if o['category'] in INF or o['category'] == 'red blood cell'] | |
| rnd = random.Random(f'{SEED}-{stem}'); unin = [o for o in objs if o['category'] == 'red blood cell']; rnd.shuffle(unin) | |
| keep = [o for o in objs if o['category'] in INF] + unin[:25] # all infected cells, at most 25 uninfected per field | |
| for k, o in enumerate(keep): | |
| bb = o['bounding_box']; r0, c0, r1, c1 = bb['minimum']['r'], bb['minimum']['c'], bb['maximum']['r'], bb['maximum']['c'] | |
| pad = 0.08 * max(r1 - r0, c1 - c0) | |
| crop = img.crop((max(0, c0 - pad), max(0, r0 - pad), min(W, c1 + pad), min(H, r1 + pad))) | |
| lab = 'Parasitized' if o['category'] in INF else 'Uninfected'; out = f'BBBC041_{stem[:13]}_{k:03d}.png' | |
| p = f'{OUT}/malaria/{s}/{lab}/{out}'; os.makedirs(os.path.dirname(p), exist_ok=True); crop.save(p, 'PNG', optimize=True) | |
| w.add('malaria', s, lab, out, f'BBBC041_{stem}', o['category'], f'{path}#obj{k}', crop.size) | |
| w.close() | |
| def multifocus(): | |
| import numpy as np | |
| MAP = {'seg_neutrophil': 'Segmented_neutrophil', 'band_neutrophil': 'Band_neutrophil', 'lymphocyte': 'Lymphocyte', 'blast': 'Blast', | |
| 'myelocyte': 'Myelocyte', 'metamyelocyte': 'Metamyelocyte', 'promyelocyte': 'Promyelocyte', 'eosinophil': 'Eosinophil', | |
| 'basophil': 'Basophil', 'monocyte': 'Monocyte', 'n_rbc': 'Erythroblast', 'artifact': 'Artefact'} | |
| w = Writer('multifocus_wbc', 'CC0', 'Park J. et al. (2024) A large multi-focus dataset for white blood cell classification. Scientific Data. Figshare', 'https://doi.org/10.6084/m9.figshare.26781052.v1') | |
| z = zipfile.ZipFile(f'{RAW}/multifocus/mf.zip'); P = 'multi-focus-wbc-dataset/' | |
| lab = {l.split(',')[0]: l.split(',')[5] for l in z.read(P + 'labels.csv').decode().splitlines()[1:]} | |
| sl = {l.split(',')[0]: l.split(',')[1] for l in z.read(P + 'slide_number.csv').decode().splitlines()[1:]} | |
| sp = split_groups({'all': set(sl.values())}) # 214 smears -> smear-level split | |
| def sharp(im): | |
| g = np.asarray(im.convert('L'), dtype=np.float32) | |
| return float((g[1:-1, 1:-1] * 4 - g[:-2, 1:-1] - g[2:, 1:-1] - g[1:-1, :-2] - g[1:-1, 2:]).var()) | |
| for num, src in lab.items(): | |
| if src not in MAP: continue | |
| best = None | |
| for k in range(10): | |
| try: im = Image.open(io.BytesIO(z.read(f'{P}{num}_{k}.jpg'))); im.load() | |
| except Exception: continue | |
| v = sharp(im) | |
| if best is None or v > best[0]: best = (v, k, im) | |
| if best is None: continue | |
| s = sp[sl[num]]; L = MAP[src]; out = f'MF_{num}_z{best[1]}.jpg' | |
| size = save_cls_image(best[2], f'{OUT}/cls/{s}/{L}/{out}') | |
| w.add('cls', s, L, out, f'MF_slide{sl[num]}', src, f'{P}{num}_{best[1]}.jpg', size, f'sharpest of 10 focal planes (lapvar {best[0]:.0f})') | |
| w.close() | |
| def mll23(): | |
| import subprocess | |
| MAP = {'neutrophil_band': 'Band_neutrophil', 'neutrophil_segmented': 'Segmented_neutrophil', 'myelocyte': 'Myelocyte', 'metamyelocyte': 'Metamyelocyte', | |
| 'promyelocyte': 'Promyelocyte', 'myeloblast': 'Blast', 'basophil': 'Basophil', 'eosinophil': 'Eosinophil', 'monocyte': 'Monocyte', | |
| 'lymphocyte': 'Lymphocyte', 'hairy_cell': 'Hairy_cell', 'plasma_cell': 'Plasma_cell', 'normoblast': 'Erythroblast'} | |
| w = Writer('mll23', 'CC BY 4.0', 'Shetab Boushehri S., Gruber A., Sun X. et al. (2024) A large publicly available single-cell peripheral blood dataset (MLL23). Zenodo', 'https://doi.org/10.5281/zenodo.14277609') | |
| items = [] | |
| for src, L in MAP.items(): | |
| zp = f'{RAW}/mll23/{src}.zip' | |
| subprocess.run(['curl', '-sL', '-o', zp, f'https://zenodo.org/records/14277609/files/{src}.zip?download=1'], check=True) | |
| z = zipfile.ZipFile(zp) | |
| names = sorted(n for n in z.namelist() if not n.startswith('__MACOSX') and n.lower().endswith(('.tif', '.tiff', '.png', '.jpg'))) | |
| sp = split_groups({src: set(names)}) # no patient IDs in MLL23: image-level split per class | |
| for n in names: | |
| try: im = Image.open(io.BytesIO(z.read(n))); im.load() | |
| except Exception: | |
| w.add('cls', 'excluded', L, n, '', src, n, (0, 0), 'corrupt'); continue | |
| s = sp[n]; out = f'MLL23_{n.split("/")[-1].rsplit(".", 1)[0]}.jpg' | |
| size = save_cls_image(im, f'{OUT}/cls/{s}/{L}/{out}') | |
| w.add('cls', s, L, out, f'MLL23_{out}', src, n, size) | |
| z.close(); os.remove(zp); print(src, len(names), flush=True) | |
| w.close() | |
| def aml_lmu(): | |
| from remotezip import RemoteZip | |
| MAP = {'NGS': 'Segmented_neutrophil', 'NGB': 'Band_neutrophil', 'LYT': 'Lymphocyte', 'MON': 'Monocyte', 'EOS': 'Eosinophil', 'BAS': 'Basophil', | |
| 'EBO': 'Erythroblast', 'PMO': 'Promyelocyte', 'MYB': 'Myelocyte', 'MMZ': 'Metamyelocyte', 'MYO': 'Blast', 'MOB': 'Blast'} | |
| w = Writer('aml_cytomorphology_lmu', 'CC BY 3.0', 'Matek C., Schwarz S., Spiekermann K., Marr C. (2019) Human-level recognition of blast cells in acute myeloid leukaemia with convolutional neural networks. Nature Machine Intelligence 1:538-544. Data: AML-Cytomorphology_LMU, TCIA (images obtained via the CC BY 4.0 curated multi-source collection, Zenodo 10.5281/zenodo.19126698)', 'https://doi.org/10.7937/tcia.2019.36f5o9ld') | |
| with zipfile.ZipFile(f'{RAW}/curated/WBC_Our_dataset_extended.zip') as z: | |
| infos = [i for i in z.infolist() if not i.is_dir() and re.match(r'^[A-Z]{3}_\d+', i.filename.split('/')[-1])] | |
| infos = [i for i in infos if i.filename.split('/')[-1][:3] in MAP] | |
| sp = {} | |
| by = defaultdict(set) | |
| for i in infos: by[i.filename.split('/')[-1][:3]].add(i.filename.split('/')[-1]) | |
| for code, names in by.items(): sp.update(split_groups({code: names})) # no patient IDs: image-level split per class | |
| for i in infos: | |
| fn = i.filename.split('/')[-1]; code = fn[:3]; L = MAP[code] | |
| try: im = Image.open(io.BytesIO(z.read(i.filename))); im.load() | |
| except Exception: | |
| w.add('cls', 'excluded', L, fn, '', code, i.filename, (0, 0), 'corrupt'); continue | |
| s = sp[fn]; out = f'LMU_{fn.rsplit(".", 1)[0]}.jpg' | |
| size = save_cls_image(im, f'{OUT}/cls/{s}/{L}/{out}') | |
| w.add('cls', s, L, out, f'LMU_{out}', code, i.filename, size) | |
| w.close() | |
| if __name__ == '__main__': | |
| for name in sys.argv[1:]: globals()[name]() | |