| """ |
| ingest_universal.py |
| =================== |
| Universal shard worker β handles ANY HuggingFace image dataset format: |
| |
| β Parquet (.parquet) |
| β WebDataset tar (.tar, .tar.gz, .tgz) |
| β ZIP archives (.zip) |
| β Arrow IPC (.arrow) |
| β JSON Lines (.jsonl, .json) |
| β Image folder (directory of jpg/png + txt sibling files) |
| β HF Streaming (fallback for anything else via datasets library) |
| |
| Auto-detects image field and caption field from the first sample. |
| Can be overridden via --image-field and --caption-field flags. |
| |
| Usage |
| ----- |
| # Auto-detect everything |
| python ingest_universal.py --shard-file train-00001.parquet --shard-idx 1 |
| |
| # WebDataset tar |
| python ingest_universal.py --shard-file 00001.tar --shard-idx 1 |
| |
| # ZIP archive |
| python ingest_universal.py --shard-file images.zip --shard-idx 0 |
| |
| # HF streaming fallback |
| python ingest_universal.py --hf-dataset laion/laion400m --shard-idx 0 |
| |
| # Override detected fields |
| python ingest_universal.py --shard-file f.parquet --image-field pixel_values --caption-field blip_caption |
| """ |
|
|
| import os |
| import io |
| import json |
| import time |
| import fcntl |
| import tarfile |
| import zipfile |
| import argparse |
| import traceback |
| from pathlib import Path |
| from typing import Iterator, Optional |
|
|
| import torch |
| import torchvision.transforms as T |
| from PIL import Image |
| from tqdm import tqdm |
| from diffusers import AutoencoderKL |
|
|
| from format_detector import detect, DatasetInfo, IMAGE_FIELDS, CAPTION_FIELDS |
|
|
|
|
| |
| def parse_args(): |
| p = argparse.ArgumentParser(description="Universal HF image dataset ingest worker") |
|
|
| src = p.add_mutually_exclusive_group(required=True) |
| src.add_argument("--shard-file", help="Path to local shard file or directory") |
| src.add_argument("--hf-dataset", help="HuggingFace dataset name (streaming fallback)") |
|
|
| p.add_argument("--hf-split", default="train") |
| p.add_argument("--shard-idx", type=int, default=0) |
| p.add_argument("--total-shards", type=int, default=1) |
| p.add_argument("--base-dir", default="/workspace/hem/dataset_output") |
| p.add_argument("--vae-model", default="stabilityai/sd-vae-ft-ema") |
| p.add_argument("--resolutions", type=int, nargs="+", default=[256, 512]) |
| p.add_argument("--shard-size", type=int, default=1000) |
| p.add_argument("--no-latents", action="store_true") |
| p.add_argument("--no-originals", action="store_true") |
| p.add_argument("--max-samples", type=int, default=None) |
| p.add_argument("--flush-every", type=int, default=200) |
| p.add_argument("--cuda-device", type=int, default=0) |
| p.add_argument("--image-field", default=None, help="Override auto-detected image field") |
| p.add_argument("--caption-field", default=None, help="Override auto-detected caption field") |
| p.add_argument("--detect-only", action="store_true", help="Print detected format/fields and exit") |
| return p.parse_args() |
|
|
|
|
| |
| class Paths: |
| def __init__(self, base_dir, resolutions): |
| self.base = base_dir |
| self.resols = resolutions |
|
|
| def img_dir(self, res): return os.path.join(self.base, "images", f"{res}x{res}") |
| def orig_dir(self): return os.path.join(self.base, "images", "original") |
| def lat_dir(self, res): return os.path.join(self.base, "latents", f"sd-vae-{res}") |
| def captions_file(self): return os.path.join(self.base, "captions", "captions.json") |
| def shards_dir(self): return os.path.join(self.base, "captions", "shards") |
| def meta_file(self): return os.path.join(self.base, "metadata", "dataset_info.json") |
| def logs_dir(self): return os.path.join(self.base, "metadata", "processing_logs") |
|
|
| def failed_file(self, idx): |
| return os.path.join(self.logs_dir(), f"failed_shard_{idx:06d}.json") |
|
|
| def worker_caps_file(self, idx): |
| return os.path.join(self.logs_dir(), f"captions_shard_{idx:06d}.json") |
|
|
| @staticmethod |
| def bucket(stem): return stem[:3] |
|
|
| def img_path(self, res, stem): |
| return os.path.join(self.img_dir(res), self.bucket(stem), f"{stem}.jpg") |
|
|
| def orig_path(self, stem): |
| return os.path.join(self.orig_dir(), self.bucket(stem), f"{stem}.jpg") |
|
|
| def lat_path(self, res, stem): |
| return os.path.join(self.lat_dir(res), self.bucket(stem), f"{stem}.pt") |
|
|
| def ensure_dirs(self, stem): |
| b = self.bucket(stem) |
| for res in self.resols: |
| os.makedirs(os.path.join(self.img_dir(res), b), exist_ok=True) |
| os.makedirs(os.path.join(self.lat_dir(res), b), exist_ok=True) |
| os.makedirs(os.path.join(self.orig_dir(), b), exist_ok=True) |
|
|
| def ensure_global_dirs(self): |
| os.makedirs(os.path.join(self.base, "captions", "shards"), exist_ok=True) |
| os.makedirs(os.path.join(self.base, "metadata", "processing_logs"), exist_ok=True) |
| for res in self.resols: |
| os.makedirs(self.img_dir(res), exist_ok=True) |
| os.makedirs(self.lat_dir(res), exist_ok=True) |
| os.makedirs(self.orig_dir(), exist_ok=True) |
|
|
|
|
| |
| def load_global_done(paths): |
| cf = paths.captions_file() |
| if os.path.exists(cf) and os.path.getsize(cf) > 2: |
| with open(cf) as f: |
| return set(json.load(f).keys()) |
| return set() |
|
|
|
|
| def load_worker_state(paths, idx): |
| wf = paths.worker_caps_file(idx) |
| ff = paths.failed_file(idx) |
| caps = {} |
| if os.path.exists(wf) and os.path.getsize(wf) > 2: |
| with open(wf) as f: |
| caps = json.load(f) |
| failed = set() |
| if os.path.exists(ff) and os.path.getsize(ff) > 2: |
| with open(ff) as f: |
| failed = set(json.load(f)) |
| return caps, failed |
|
|
|
|
| def flush_worker(paths, idx, caps, failed): |
| with open(paths.worker_caps_file(idx), "w") as f: |
| json.dump(caps, f, ensure_ascii=False) |
| with open(paths.failed_file(idx), "w") as f: |
| json.dump(sorted(failed), f, indent=2) |
|
|
|
|
| def merge_to_global(paths, idx): |
| wf = paths.worker_caps_file(idx) |
| if not os.path.exists(wf): |
| return |
| with open(wf) as f: |
| worker = json.load(f) |
| cf = paths.captions_file() |
| lock = cf + ".lock" |
| with open(lock, "w") as lk: |
| fcntl.flock(lk, fcntl.LOCK_EX) |
| try: |
| g = {} |
| if os.path.exists(cf) and os.path.getsize(cf) > 2: |
| with open(cf) as f: |
| g = json.load(f) |
| g.update(worker) |
| tmp = cf + ".tmp" |
| with open(tmp, "w") as f: |
| json.dump(g, f, ensure_ascii=False) |
| os.replace(tmp, cf) |
| finally: |
| fcntl.flock(lk, fcntl.LOCK_UN) |
| print(f"[shard {idx:06d}] Merged {len(worker):,} captions β global file") |
|
|
|
|
| def save_subshard(paths, idx, sub_idx, data): |
| p = os.path.join(paths.shards_dir(), f"shard_{idx:06d}_{sub_idx:04d}.json") |
| with open(p, "w") as f: |
| json.dump(data, f, ensure_ascii=False) |
|
|
|
|
| def update_meta(paths, processed, errors): |
| mf = paths.meta_file() |
| lock = mf + ".lock" |
| os.makedirs(os.path.dirname(mf), exist_ok=True) |
| with open(lock, "w") as lk: |
| fcntl.flock(lk, fcntl.LOCK_EX) |
| try: |
| info = {} |
| if os.path.exists(mf) and os.path.getsize(mf) > 2: |
| with open(mf) as f: |
| info = json.load(f) |
| info["processed_count"] = info.get("processed_count", 0) + processed |
| info["failed_count"] = info.get("failed_count", 0) + errors |
| info["last_run"] = time.strftime("%Y-%m-%dT%H:%M:%S") |
| with open(mf, "w") as f: |
| json.dump(info, f, indent=2) |
| finally: |
| fcntl.flock(lk, fcntl.LOCK_UN) |
|
|
|
|
| |
| def build_vae_transforms(resolutions): |
| return { |
| res: T.Compose([ |
| T.Resize((res, res), interpolation=T.InterpolationMode.LANCZOS), |
| T.ToTensor(), |
| T.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]), |
| ]) |
| for res in resolutions |
| } |
|
|
|
|
| @torch.inference_mode() |
| def encode_latent(vae, tensor): |
| latent = vae.encode(tensor).latent_dist.sample() |
| return (latent * 0.18215).cpu() |
|
|
|
|
| def coerce_image(v) -> Optional[Image.Image]: |
| """Convert any image-like value to a PIL RGB image.""" |
| try: |
| if isinstance(v, Image.Image): |
| return v.convert("RGB") |
| if isinstance(v, bytes): |
| return Image.open(io.BytesIO(v)).convert("RGB") |
| if isinstance(v, dict): |
| raw = v.get("bytes") or v.get("data") or v.get("image") |
| if raw: |
| return coerce_image(raw) |
| if isinstance(v, str) and os.path.exists(v): |
| return Image.open(v).convert("RGB") |
| except Exception: |
| pass |
| return None |
|
|
|
|
| def extract_caption(sample, field): |
| if field and field in sample: |
| v = sample[field] |
| if isinstance(v, list): |
| return " ".join(str(x) for x in v) |
| return str(v) |
| |
| for f in CAPTION_FIELDS: |
| if f in sample and isinstance(sample[f], str): |
| return sample[f] |
| return "" |
|
|
|
|
| |
| def iter_parquet(path: str) -> Iterator[dict]: |
| import pyarrow.parquet as pq |
| from datasets import Dataset |
| ds = Dataset(pq.read_table(path)) |
| yield from ds |
|
|
|
|
| def iter_arrow(path: str) -> Iterator[dict]: |
| import pyarrow as pa |
| with pa.memory_map(path, "r") as src: |
| reader = pa.ipc.open_file(src) |
| for i in range(reader.num_record_batches): |
| batch = reader.get_batch(i) |
| for row_idx in range(batch.num_rows): |
| yield {col: batch.column(col)[row_idx].as_py() |
| for col in batch.schema.names} |
|
|
|
|
| def iter_webdataset(path: str) -> Iterator[dict]: |
| """ |
| Iterate a WebDataset tar shard. |
| Groups consecutive tar members by stem into one sample dict. |
| """ |
| current_key = None |
| current_samp = {} |
|
|
| def emit(s): |
| return s if s else None |
|
|
| with tarfile.open(path, "r:*") as tf: |
| for member in tf: |
| if member.isdir() or member.size == 0: |
| continue |
| name = os.path.basename(member.name) |
| stem, ext = os.path.splitext(name) |
| ext = ext.lstrip(".").lower() |
|
|
| if current_key is None: |
| current_key = stem |
|
|
| if stem != current_key: |
| if current_samp: |
| yield current_samp |
| current_key = stem |
| current_samp = {} |
|
|
| fobj = tf.extractfile(member) |
| if fobj is None: |
| continue |
| raw = fobj.read() |
|
|
| if ext in ("jpg", "jpeg", "png", "gif", "webp", "bmp"): |
| try: |
| current_samp["image"] = Image.open(io.BytesIO(raw)).convert("RGB") |
| current_samp["__img_bytes__"] = raw |
| except Exception: |
| pass |
| elif ext == "txt": |
| current_samp["caption"] = raw.decode("utf-8", errors="replace").strip() |
| elif ext == "json": |
| try: |
| current_samp.update(json.loads(raw)) |
| except Exception: |
| pass |
| elif ext == "cls": |
| try: |
| current_samp["label"] = raw.decode().strip() |
| except Exception: |
| pass |
| else: |
| current_samp[ext] = raw |
|
|
| if current_samp: |
| yield current_samp |
|
|
|
|
| def iter_zip(path: str) -> Iterator[dict]: |
| """ |
| Iterate a ZIP file. |
| Groups image files with their sibling caption files by stem. |
| """ |
| with zipfile.ZipFile(path, "r") as zf: |
| names = set(zf.namelist()) |
| img_ext = {"jpg", "jpeg", "png", "gif", "webp", "bmp"} |
|
|
| for name in sorted(names): |
| ext = Path(name).suffix.lower().lstrip(".") |
| if ext not in img_ext: |
| continue |
| stem = Path(name).stem |
| sample = {} |
|
|
| try: |
| raw = zf.read(name) |
| sample["image"] = Image.open(io.BytesIO(raw)).convert("RGB") |
| except Exception: |
| continue |
|
|
| |
| for cap_ext in ("txt", "caption"): |
| sib = str(Path(name).with_suffix(f".{cap_ext}")) |
| if sib in names: |
| try: |
| sample["caption"] = zf.read(sib).decode("utf-8", errors="replace").strip() |
| except Exception: |
| pass |
|
|
| |
| sib_json = str(Path(name).with_suffix(".json")) |
| if sib_json in names: |
| try: |
| sample.update(json.loads(zf.read(sib_json))) |
| except Exception: |
| pass |
|
|
| yield sample |
|
|
|
|
| def iter_jsonl(path: str) -> Iterator[dict]: |
| with open(path) as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| try: |
| yield json.loads(line) |
| except Exception: |
| continue |
|
|
|
|
| def iter_image_folder(path: str) -> Iterator[dict]: |
| img_ext = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"} |
| for root, _, files in os.walk(path): |
| for fname in sorted(files): |
| if Path(fname).suffix.lower() not in img_ext: |
| continue |
| img_path = os.path.join(root, fname) |
| sample = {} |
| try: |
| sample["image"] = Image.open(img_path).convert("RGB") |
| except Exception: |
| continue |
| txt_path = os.path.join(root, Path(fname).stem + ".txt") |
| if os.path.exists(txt_path): |
| sample["caption"] = open(txt_path).read().strip() |
| json_path = os.path.join(root, Path(fname).stem + ".json") |
| if os.path.exists(json_path): |
| try: |
| sample.update(json.loads(open(json_path).read())) |
| except Exception: |
| pass |
| yield sample |
|
|
|
|
| def iter_hf_streaming(dataset_name: str, split: str) -> Iterator[dict]: |
| from datasets import load_dataset |
| ds = load_dataset(dataset_name, split=split, streaming=True) |
| yield from ds |
|
|
|
|
| def get_iterator(args, info: DatasetInfo) -> Iterator[dict]: |
| """Return the right iterator based on detected format.""" |
| if args.shard_file: |
| fmt = info.fmt |
| p = args.shard_file |
| if fmt == "parquet": |
| return iter_parquet(p) |
| elif fmt in ("tar", "tar.gz"): |
| return iter_webdataset(p) |
| elif fmt == "zip": |
| return iter_zip(p) |
| elif fmt == "arrow": |
| return iter_arrow(p) |
| elif fmt == "jsonl": |
| return iter_jsonl(p) |
| elif fmt == "folder": |
| return iter_image_folder(p) |
| else: |
| print(f"[warn] Unknown format '{fmt}', trying HF datasets as fallback...") |
| from datasets import load_dataset |
| ds = load_dataset("parquet", data_files={"train": p}, split="train") |
| return iter(ds) |
| else: |
| return iter_hf_streaming(args.hf_dataset, args.hf_split) |
|
|
|
|
| |
| def main(): |
| args = parse_args() |
|
|
| |
| src = args.shard_file or args.hf_dataset |
| print(f"[shard {args.shard_idx:06d}] Detecting format: {src}") |
|
|
| if args.shard_file: |
| info = detect(args.shard_file) |
| else: |
| |
| info = DatasetInfo("hf_streaming", None, None, {}) |
|
|
| |
| if args.image_field: |
| info.image_field = args.image_field |
| if args.caption_field: |
| info.caption_field = args.caption_field |
|
|
| print(f"[shard {args.shard_idx:06d}] {info}") |
|
|
| if args.detect_only: |
| print(f"Sample keys: {list(info.sample.keys())}") |
| return |
|
|
| |
| device_str = f"cuda:{args.cuda_device}" if torch.cuda.is_available() else "cpu" |
| device = torch.device(device_str) |
| print(f"[shard {args.shard_idx:06d}] Device: {device_str}") |
|
|
| paths = Paths(args.base_dir, args.resolutions) |
| paths.ensure_global_dirs() |
|
|
| already_done_global = load_global_done(paths) |
| worker_caps, failed = load_worker_state(paths, args.shard_idx) |
| already_done = already_done_global | set(worker_caps.keys()) |
| print(f"[shard {args.shard_idx:06d}] Already done: {len(already_done):,} Failed: {len(failed):,}") |
|
|
| |
| vae = None |
| vae_xforms = {} |
| if not args.no_latents: |
| print(f"[shard {args.shard_idx:06d}] Loading VAE: {args.vae_model}") |
| vae = AutoencoderKL.from_pretrained(args.vae_model).to(device) |
| vae.eval() |
| vae_xforms = build_vae_transforms(args.resolutions) |
|
|
| |
| data_iter = get_iterator(args, info) |
| new_caps = {} |
| sub_data = {} |
| sub_idx = 0 |
| dirs_seen = set() |
| processed = 0 |
| skipped = 0 |
| errors = 0 |
| t0 = time.time() |
|
|
| pbar = tqdm( |
| total=args.max_samples, |
| unit="img", |
| dynamic_ncols=True, |
| desc=f"shard {args.shard_idx:03d}/{args.total_shards:03d} [{info.fmt}]", |
| ) |
|
|
| for local_idx, sample in enumerate(data_iter): |
| if args.max_samples and local_idx >= args.max_samples: |
| break |
|
|
| global_idx = args.shard_idx * 1_000_000 + local_idx |
| stem = f"{global_idx:012d}" |
|
|
| |
| if stem in already_done: |
| skipped += 1 |
| pbar.update(1) |
| continue |
|
|
| |
| try: |
| raw_img = sample.get(info.image_field) if info.image_field else None |
| |
| if raw_img is None: |
| for f in IMAGE_FIELDS: |
| if f in sample: |
| raw_img = sample[f] |
| break |
| if raw_img is None: |
| raise ValueError(f"No image field found. Keys: {list(sample.keys())}") |
|
|
| pil_img = coerce_image(raw_img) |
| if pil_img is None: |
| raise ValueError(f"Could not coerce image from field '{info.image_field}'") |
|
|
| caption = extract_caption(sample, info.caption_field) |
|
|
| except Exception as e: |
| failed.add(stem) |
| errors += 1 |
| pbar.update(1) |
| continue |
|
|
| |
| bucket = paths.bucket(stem) |
| if bucket not in dirs_seen: |
| paths.ensure_dirs(stem) |
| dirs_seen.add(bucket) |
|
|
| |
| try: |
| if not args.no_originals: |
| pil_img.save(paths.orig_path(stem), format="JPEG", quality=95) |
|
|
| for res in args.resolutions: |
| resized = pil_img.resize((res, res), Image.LANCZOS) |
| resized.save(paths.img_path(res, stem), format="JPEG", quality=90) |
|
|
| if vae is not None: |
| tensor = vae_xforms[res](pil_img).unsqueeze(0).to(device) |
| lat = encode_latent(vae, tensor) |
| torch.save(lat, paths.lat_path(res, stem)) |
|
|
| worker_caps[stem] = caption |
| new_caps[stem] = caption |
| sub_data[stem] = caption |
| already_done.add(stem) |
|
|
| if len(sub_data) >= args.shard_size: |
| save_subshard(paths, args.shard_idx, sub_idx, sub_data) |
| sub_idx += 1 |
| sub_data = {} |
|
|
| processed += 1 |
|
|
| except Exception: |
| failed.add(stem) |
| errors += 1 |
| traceback.print_exc() |
|
|
| pbar.update(1) |
| elapsed = time.time() - t0 + 1e-6 |
| pbar.set_postfix( |
| ok=processed, skip=skipped, err=errors, |
| fps=f"{processed/elapsed:.1f}", |
| ) |
|
|
| |
| if processed % args.flush_every == 0 and new_caps: |
| flush_worker(paths, args.shard_idx, worker_caps, failed) |
| new_caps = {} |
|
|
| pbar.close() |
|
|
| |
| flush_worker(paths, args.shard_idx, worker_caps, failed) |
| if sub_data: |
| save_subshard(paths, args.shard_idx, sub_idx, sub_data) |
|
|
| merge_to_global(paths, args.shard_idx) |
| update_meta(paths, processed, errors) |
|
|
| elapsed = time.time() - t0 |
| print( |
| f"\n[shard {args.shard_idx:06d}] Done in {elapsed/60:.1f} min\n" |
| f" Format : {info.fmt}\n" |
| f" Img field : {info.image_field}\n" |
| f" Cap field : {info.caption_field}\n" |
| f" Processed : {processed:,}\n" |
| f" Skipped : {skipped:,}\n" |
| f" Errors : {errors:,}\n" |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|