File size: 2,360 Bytes
b373569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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)