| """ |
| Prepare dataset for Flux fine-tuning. |
| Combines images + captions into WebDataset format (tar shards). |
| """ |
| import json |
| import io |
| import argparse |
| from pathlib import Path |
|
|
| import webdataset as wds |
| from PIL import Image |
| from tqdm import tqdm |
|
|
| IMAGE_DIR = Path("/home/adminuser/chungcat/data/raw/unsplash") |
| CAPTION_DIR = Path("/home/adminuser/chungcat/data/captions") |
| OUTPUT_DIR = Path("/home/adminuser/chungcat/data/processed/flux_train") |
|
|
|
|
| def create_webdataset(image_dir, caption_dir, output_dir, shard_size=1000): |
| output_dir.mkdir(parents=True, exist_ok=True) |
| pattern = str(output_dir / "shard-%06d.tar") |
|
|
| captions = list(caption_dir.glob("*.json")) |
| print(f"Found {len(captions)} captions") |
|
|
| with wds.ShardWriter(pattern, maxcount=shard_size) as sink: |
| written = 0 |
| for cap_path in tqdm(captions): |
| meta = json.loads(cap_path.read_text()) |
| stem = cap_path.stem |
|
|
| img_path = image_dir / f"{stem}.jpg" |
| if not img_path.exists(): |
| img_path = image_dir / f"{stem}.png" |
| if not img_path.exists(): |
| continue |
|
|
| try: |
| img = Image.open(img_path).convert("RGB") |
| img = img.resize((1024, 1024), Image.LANCZOS) |
|
|
| img_bytes = io.BytesIO() |
| img.save(img_bytes, format="JPEG", quality=95) |
| img_bytes = img_bytes.getvalue() |
|
|
| sample = { |
| "__key__": stem, |
| "jpg": img_bytes, |
| "txt": meta["caption"], |
| "json": json.dumps(meta).encode(), |
| } |
| sink.write(sample) |
| written += 1 |
| except Exception as e: |
| print(f"Error {stem}: {e}") |
|
|
| print(f"Done! Written {written} samples to {output_dir}") |
|
|
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser(description="Prepare WebDataset for Flux training") |
| parser.add_argument("--image-dir", type=Path, default=IMAGE_DIR) |
| parser.add_argument("--caption-dir", type=Path, default=CAPTION_DIR) |
| parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR) |
| parser.add_argument("--shard-size", type=int, default=1000) |
| args = parser.parse_args() |
|
|
| create_webdataset(args.image_dir, args.caption_dir, args.output_dir, args.shard_size) |
|
|