File size: 3,868 Bytes
e3cb0cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""Extract images from ULVR_all parquet files into Monet training layout."""
import argparse
import json
import multiprocessing as mp
import os

import pyarrow.parquet as pq


def build_mapping(jsonl_path: str) -> dict:
    mapping = {}
    with open(jsonl_path) as f:
        for line in f:
            d = json.loads(line)
            sid = d["metadata"]["sample_id"]
            input_path = None
            inter_paths = []
            for msg in d["data"]:
                if msg["role"] == "user":
                    for c in msg["content"]:
                        if c["type"] == "image":
                            input_path = c["image"]
                elif msg["role"] == "assistant":
                    for c in msg["content"]:
                        if c["type"] == "image":
                            inter_paths.append(c["image"])
            mapping[sid] = (input_path, inter_paths)
    return mapping


def process_parquet(args):
    parq_path, mapping = args
    written = 0
    skipped = 0
    out_root = process_parquet.out_root
    f = pq.ParquetFile(parq_path)
    cols = [
        "id",
        "input_image",
        "intermediate_image_1",
        "intermediate_image_2",
        "intermediate_image_3",
    ]
    for batch in f.iter_batches(batch_size=256, columns=cols):
        df = batch.to_pandas()
        for _, row in df.iterrows():
            sid = row["id"]
            if sid not in mapping:
                skipped += 1
                continue
            input_path, inter_paths = mapping[sid]
            img = row["input_image"]
            if img is not None and img.get("bytes"):
                out = os.path.join(out_root, input_path)
                os.makedirs(os.path.dirname(out), exist_ok=True)
                if not os.path.exists(out) or os.path.getsize(out) != len(img["bytes"]):
                    with open(out, "wb") as fp:
                        fp.write(img["bytes"])
                written += 1
            for i, inter_path in enumerate(inter_paths, start=1):
                col = f"intermediate_image_{i}"
                img = row.get(col)
                if img is None or not hasattr(img, "get"):
                    continue
                b = img.get("bytes")
                if not b:
                    continue
                out = os.path.join(out_root, inter_path)
                os.makedirs(os.path.dirname(out), exist_ok=True)
                if not os.path.exists(out) or os.path.getsize(out) != len(b):
                    with open(out, "wb") as fp:
                        fp.write(b)
                written += 1
    return parq_path, written, skipped


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--jsonl", required=True)
    parser.add_argument("--parquet-dir", required=True)
    parser.add_argument("--out-root", required=True)
    parser.add_argument("--workers", type=int, default=8)
    args = parser.parse_args()

    mapping = build_mapping(args.jsonl)
    print(f"Need to extract images for {len(mapping)} samples", flush=True)

    files = sorted(
        os.path.join(args.parquet_dir, f)
        for f in os.listdir(args.parquet_dir)
        if f.endswith(".parquet")
    )
    if len(files) != 26:
        print(f"WARNING: expected 26 parquet shards, found {len(files)}", flush=True)
    print(f"{len(files)} parquet files", flush=True)

    process_parquet.out_root = args.out_root
    pool_args = [(p, mapping) for p in files]
    nproc = min(args.workers, len(files))
    with mp.Pool(nproc) as pool:
        for parq_path, written, skipped in pool.imap_unordered(process_parquet, pool_args):
            print(
                f"  done {os.path.basename(parq_path)}: written={written}, skipped={skipped}",
                flush=True,
            )
    print("All done.", flush=True)


if __name__ == "__main__":
    main()