ai557 commited on
Commit
f8e648b
Β·
verified Β·
1 Parent(s): 964434c

Upload 4 files

Browse files
format_detector.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ format_detector.py
3
+ ==================
4
+ Auto-detects:
5
+ - File format (parquet, tar/webdataset, zip, arrow, jsonl, image folder)
6
+ - Image field (image, img, jpeg, png, pixel_values, …)
7
+ - Caption field (caption, text, prompt, label, description, …)
8
+
9
+ Used by ingest_universal.py β€” import and call detect().
10
+ """
11
+
12
+ import os
13
+ import io
14
+ import json
15
+ import tarfile
16
+ import zipfile
17
+ import struct
18
+ from pathlib import Path
19
+ from typing import Optional
20
+
21
+ from PIL import Image
22
+
23
+
24
+ # ── Known field names ─────────────────────────────────────────────────────────
25
+ IMAGE_FIELDS = ["image", "img", "jpeg", "png", "gif", "webp",
26
+ "pixel_values", "image_bytes", "image_data",
27
+ "bytes", "data", "photo", "thumbnail"]
28
+
29
+ CAPTION_FIELDS = ["caption", "text", "prompt", "label", "description",
30
+ "title", "alt", "alt_text", "sentence", "query",
31
+ "blip_caption", "llava_caption", "cogvlm_caption",
32
+ "tag", "tags", "keyword", "keywords"]
33
+
34
+
35
+ # ── Format signatures ─────────────────────────────────────────────────────────
36
+ MAGIC = {
37
+ b"\x50\x4b\x03\x04": "zip",
38
+ b"\x1f\x8b": "tar.gz",
39
+ b"PAR1": "parquet",
40
+ b"\x41\x52\x52\x4f": "arrow", # ARROW1
41
+ }
42
+
43
+
44
+ def sniff_bytes(path: str) -> Optional[str]:
45
+ with open(path, "rb") as f:
46
+ header = f.read(8)
47
+ for magic, fmt in MAGIC.items():
48
+ if header[:len(magic)] == magic:
49
+ return fmt
50
+ # Bare tar (no gzip)
51
+ if tarfile.is_tarfile(path):
52
+ return "tar"
53
+ return None
54
+
55
+
56
+ # ── Per-format sample readers ─────────────────────────────────────────────────
57
+ def _sample_parquet(path: str) -> dict:
58
+ import pyarrow.parquet as pq
59
+ tbl = pq.read_table(path, memory_map=True).slice(0, 1)
60
+ row = {col: tbl.column(col)[0].as_py() for col in tbl.schema.names}
61
+ return row
62
+
63
+
64
+ def _sample_arrow(path: str) -> dict:
65
+ import pyarrow as pa
66
+ with pa.memory_map(path, "r") as src:
67
+ reader = pa.ipc.open_file(src)
68
+ batch = reader.get_batch(0)
69
+ row = {col: batch.column(col)[0].as_py() for col in batch.schema.names}
70
+ return row
71
+
72
+
73
+ def _sample_tar(path: str) -> dict:
74
+ """
75
+ WebDataset tars group files by key:
76
+ 000000.jpg 000000.txt 000000.json …
77
+ We read enough members to reconstruct one sample dict.
78
+ """
79
+ sample = {}
80
+ current_key = None
81
+ with tarfile.open(path, "r:*") as tf:
82
+ for member in tf:
83
+ if member.isdir():
84
+ continue
85
+ stem, ext = os.path.splitext(os.path.basename(member.name))
86
+ ext = ext.lstrip(".").lower()
87
+ if current_key is None:
88
+ current_key = stem
89
+ if stem != current_key:
90
+ break # moved to next sample
91
+ fobj = tf.extractfile(member)
92
+ if fobj is None:
93
+ continue
94
+ raw = fobj.read()
95
+ if ext in ("jpg", "jpeg", "png", "gif", "webp", "bmp"):
96
+ sample["__image_bytes__"] = raw
97
+ sample["image"] = Image.open(io.BytesIO(raw))
98
+ elif ext in ("txt",):
99
+ sample["caption"] = raw.decode("utf-8", errors="replace").strip()
100
+ elif ext in ("json",):
101
+ try:
102
+ d = json.loads(raw)
103
+ sample.update(d)
104
+ except Exception:
105
+ pass
106
+ else:
107
+ sample[ext] = raw
108
+ return sample
109
+
110
+
111
+ def _sample_zip(path: str) -> dict:
112
+ sample = {}
113
+ with zipfile.ZipFile(path) as zf:
114
+ names = zf.namelist()
115
+ # Find first image file
116
+ for name in names:
117
+ ext = Path(name).suffix.lower().lstrip(".")
118
+ if ext in ("jpg", "jpeg", "png", "gif", "webp"):
119
+ raw = zf.read(name)
120
+ sample["image"] = Image.open(io.BytesIO(raw))
121
+ # Look for sibling caption file
122
+ stem = Path(name).stem
123
+ for cap_ext in ("txt", "caption"):
124
+ cap_name = f"{stem}.{cap_ext}"
125
+ if cap_name in names:
126
+ sample["caption"] = zf.read(cap_name).decode("utf-8", errors="replace").strip()
127
+ # Also check for a metadata JSON
128
+ for json_name in (f"{stem}.json", "metadata.json", "captions.json"):
129
+ if json_name in names:
130
+ try:
131
+ d = json.loads(zf.read(json_name))
132
+ sample.update(d)
133
+ except Exception:
134
+ pass
135
+ break
136
+ return sample
137
+
138
+
139
+ def _sample_jsonl(path: str) -> dict:
140
+ with open(path) as f:
141
+ line = f.readline()
142
+ return json.loads(line)
143
+
144
+
145
+ def _sample_image_folder(path: str) -> dict:
146
+ """path is a directory; find first image + sibling txt."""
147
+ for root, _, files in os.walk(path):
148
+ for fname in sorted(files):
149
+ ext = Path(fname).suffix.lower().lstrip(".")
150
+ if ext in ("jpg", "jpeg", "png", "gif", "webp"):
151
+ img_path = os.path.join(root, fname)
152
+ sample = {"image": Image.open(img_path)}
153
+ txt = os.path.join(root, Path(fname).stem + ".txt")
154
+ if os.path.exists(txt):
155
+ sample["caption"] = open(txt).read().strip()
156
+ return sample
157
+ return {}
158
+
159
+
160
+ # ── Field detection ───────────────────────────────────────────────────────────
161
+ def _is_image_value(v) -> bool:
162
+ if isinstance(v, Image.Image):
163
+ return True
164
+ if isinstance(v, bytes):
165
+ try:
166
+ Image.open(io.BytesIO(v))
167
+ return True
168
+ except Exception:
169
+ return False
170
+ if isinstance(v, dict) and "bytes" in v:
171
+ return _is_image_value(v["bytes"])
172
+ return False
173
+
174
+
175
+ def detect_fields(sample: dict) -> tuple[Optional[str], Optional[str]]:
176
+ """Return (image_field, caption_field) from a sample dict."""
177
+ image_field = None
178
+ caption_field = None
179
+
180
+ # Priority: known names first, then any field whose value looks like an image
181
+ for name in IMAGE_FIELDS:
182
+ if name in sample and _is_image_value(sample[name]):
183
+ image_field = name
184
+ break
185
+ if image_field is None:
186
+ for k, v in sample.items():
187
+ if _is_image_value(v):
188
+ image_field = k
189
+ break
190
+
191
+ for name in CAPTION_FIELDS:
192
+ if name in sample and isinstance(sample[name], str):
193
+ caption_field = name
194
+ break
195
+ if caption_field is None:
196
+ for k, v in sample.items():
197
+ if k != image_field and isinstance(v, str) and len(v) > 1:
198
+ caption_field = k
199
+ break
200
+
201
+ return image_field, caption_field
202
+
203
+
204
+ # ── Main entry ────────────────────────────────────────────────────────────────
205
+ class DatasetInfo:
206
+ def __init__(self, fmt, image_field, caption_field, sample):
207
+ self.fmt = fmt # "parquet" | "tar" | "zip" | "arrow" | "jsonl" | "folder" | "hf_streaming"
208
+ self.image_field = image_field
209
+ self.caption_field = caption_field
210
+ self.sample = sample
211
+
212
+ def __repr__(self):
213
+ return (f"DatasetInfo(fmt={self.fmt!r}, "
214
+ f"image_field={self.image_field!r}, "
215
+ f"caption_field={self.caption_field!r})")
216
+
217
+
218
+ def detect(path: str) -> DatasetInfo:
219
+ """
220
+ Detect format + fields for a single file or directory.
221
+ Returns a DatasetInfo object.
222
+ """
223
+ if os.path.isdir(path):
224
+ fmt = "folder"
225
+ sample = _sample_image_folder(path)
226
+ else:
227
+ ext = Path(path).suffix.lower()
228
+ sniffed = sniff_bytes(path)
229
+ fmt = sniffed or ext.lstrip(".")
230
+
231
+ if fmt == "parquet":
232
+ sample = _sample_parquet(path)
233
+ elif fmt in ("tar", "tar.gz"):
234
+ sample = _sample_tar(path)
235
+ elif fmt == "zip":
236
+ sample = _sample_zip(path)
237
+ elif fmt == "arrow":
238
+ sample = _sample_arrow(path)
239
+ elif ext in (".jsonl", ".json"):
240
+ fmt = "jsonl"
241
+ sample = _sample_jsonl(path)
242
+ else:
243
+ # Unknown β€” try HF datasets as last resort
244
+ fmt = "hf_streaming"
245
+ sample = {}
246
+
247
+ img_f, cap_f = detect_fields(sample)
248
+ return DatasetInfo(fmt, img_f, cap_f, sample)
249
+
250
+
251
+ if __name__ == "__main__":
252
+ import sys
253
+ if len(sys.argv) < 2:
254
+ print("Usage: python format_detector.py <file_or_dir>")
255
+ sys.exit(1)
256
+ info = detect(sys.argv[1])
257
+ print(info)
258
+ print(f" Fields in sample: {list(info.sample.keys())}")
ingest_universal.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ingest_universal.py
3
+ ===================
4
+ Universal shard worker β€” handles ANY HuggingFace image dataset format:
5
+
6
+ βœ“ Parquet (.parquet)
7
+ βœ“ WebDataset tar (.tar, .tar.gz, .tgz)
8
+ βœ“ ZIP archives (.zip)
9
+ βœ“ Arrow IPC (.arrow)
10
+ βœ“ JSON Lines (.jsonl, .json)
11
+ βœ“ Image folder (directory of jpg/png + txt sibling files)
12
+ βœ“ HF Streaming (fallback for anything else via datasets library)
13
+
14
+ Auto-detects image field and caption field from the first sample.
15
+ Can be overridden via --image-field and --caption-field flags.
16
+
17
+ Usage
18
+ -----
19
+ # Auto-detect everything
20
+ python ingest_universal.py --shard-file train-00001.parquet --shard-idx 1
21
+
22
+ # WebDataset tar
23
+ python ingest_universal.py --shard-file 00001.tar --shard-idx 1
24
+
25
+ # ZIP archive
26
+ python ingest_universal.py --shard-file images.zip --shard-idx 0
27
+
28
+ # HF streaming fallback
29
+ python ingest_universal.py --hf-dataset laion/laion400m --shard-idx 0
30
+
31
+ # Override detected fields
32
+ python ingest_universal.py --shard-file f.parquet --image-field pixel_values --caption-field blip_caption
33
+ """
34
+
35
+ import os
36
+ import io
37
+ import json
38
+ import time
39
+ import fcntl
40
+ import tarfile
41
+ import zipfile
42
+ import argparse
43
+ import traceback
44
+ from pathlib import Path
45
+ from typing import Iterator, Optional
46
+
47
+ import torch
48
+ import torchvision.transforms as T
49
+ from PIL import Image
50
+ from tqdm import tqdm
51
+ from diffusers import AutoencoderKL
52
+
53
+ from format_detector import detect, DatasetInfo, IMAGE_FIELDS, CAPTION_FIELDS
54
+
55
+
56
+ # ── CLI ───────────────────────────────────────────────────────────────────────
57
+ def parse_args():
58
+ p = argparse.ArgumentParser(description="Universal HF image dataset ingest worker")
59
+
60
+ src = p.add_mutually_exclusive_group(required=True)
61
+ src.add_argument("--shard-file", help="Path to local shard file or directory")
62
+ src.add_argument("--hf-dataset", help="HuggingFace dataset name (streaming fallback)")
63
+
64
+ p.add_argument("--hf-split", default="train")
65
+ p.add_argument("--shard-idx", type=int, default=0)
66
+ p.add_argument("--total-shards", type=int, default=1)
67
+ p.add_argument("--base-dir", default="/workspace/hem/dataset_output")
68
+ p.add_argument("--vae-model", default="stabilityai/sd-vae-ft-ema")
69
+ p.add_argument("--resolutions", type=int, nargs="+", default=[256, 512])
70
+ p.add_argument("--shard-size", type=int, default=1000)
71
+ p.add_argument("--no-latents", action="store_true")
72
+ p.add_argument("--no-originals", action="store_true")
73
+ p.add_argument("--max-samples", type=int, default=None)
74
+ p.add_argument("--flush-every", type=int, default=200)
75
+ p.add_argument("--cuda-device", type=int, default=0)
76
+ p.add_argument("--image-field", default=None, help="Override auto-detected image field")
77
+ p.add_argument("--caption-field", default=None, help="Override auto-detected caption field")
78
+ p.add_argument("--detect-only", action="store_true", help="Print detected format/fields and exit")
79
+ return p.parse_args()
80
+
81
+
82
+ # ── Path helpers ──────────────────────────────────────────────────────────────
83
+ class Paths:
84
+ def __init__(self, base_dir, resolutions):
85
+ self.base = base_dir
86
+ self.resols = resolutions
87
+
88
+ def img_dir(self, res): return os.path.join(self.base, "images", f"{res}x{res}")
89
+ def orig_dir(self): return os.path.join(self.base, "images", "original")
90
+ def lat_dir(self, res): return os.path.join(self.base, "latents", f"sd-vae-{res}")
91
+ def captions_file(self): return os.path.join(self.base, "captions", "captions.json")
92
+ def shards_dir(self): return os.path.join(self.base, "captions", "shards")
93
+ def meta_file(self): return os.path.join(self.base, "metadata", "dataset_info.json")
94
+ def logs_dir(self): return os.path.join(self.base, "metadata", "processing_logs")
95
+
96
+ def failed_file(self, idx):
97
+ return os.path.join(self.logs_dir(), f"failed_shard_{idx:06d}.json")
98
+
99
+ def worker_caps_file(self, idx):
100
+ return os.path.join(self.logs_dir(), f"captions_shard_{idx:06d}.json")
101
+
102
+ @staticmethod
103
+ def bucket(stem): return stem[:3]
104
+
105
+ def img_path(self, res, stem):
106
+ return os.path.join(self.img_dir(res), self.bucket(stem), f"{stem}.jpg")
107
+
108
+ def orig_path(self, stem):
109
+ return os.path.join(self.orig_dir(), self.bucket(stem), f"{stem}.jpg")
110
+
111
+ def lat_path(self, res, stem):
112
+ return os.path.join(self.lat_dir(res), self.bucket(stem), f"{stem}.pt")
113
+
114
+ def ensure_dirs(self, stem):
115
+ b = self.bucket(stem)
116
+ for res in self.resols:
117
+ os.makedirs(os.path.join(self.img_dir(res), b), exist_ok=True)
118
+ os.makedirs(os.path.join(self.lat_dir(res), b), exist_ok=True)
119
+ os.makedirs(os.path.join(self.orig_dir(), b), exist_ok=True)
120
+
121
+ def ensure_global_dirs(self):
122
+ os.makedirs(os.path.join(self.base, "captions", "shards"), exist_ok=True)
123
+ os.makedirs(os.path.join(self.base, "metadata", "processing_logs"), exist_ok=True)
124
+ for res in self.resols:
125
+ os.makedirs(self.img_dir(res), exist_ok=True)
126
+ os.makedirs(self.lat_dir(res), exist_ok=True)
127
+ os.makedirs(self.orig_dir(), exist_ok=True)
128
+
129
+
130
+ # ── State helpers ─────────────────────────────────────────────────────────────
131
+ def load_global_done(paths):
132
+ cf = paths.captions_file()
133
+ if os.path.exists(cf) and os.path.getsize(cf) > 2:
134
+ with open(cf) as f:
135
+ return set(json.load(f).keys())
136
+ return set()
137
+
138
+
139
+ def load_worker_state(paths, idx):
140
+ wf = paths.worker_caps_file(idx)
141
+ ff = paths.failed_file(idx)
142
+ caps = {}
143
+ if os.path.exists(wf) and os.path.getsize(wf) > 2:
144
+ with open(wf) as f:
145
+ caps = json.load(f)
146
+ failed = set()
147
+ if os.path.exists(ff) and os.path.getsize(ff) > 2:
148
+ with open(ff) as f:
149
+ failed = set(json.load(f))
150
+ return caps, failed
151
+
152
+
153
+ def flush_worker(paths, idx, caps, failed):
154
+ with open(paths.worker_caps_file(idx), "w") as f:
155
+ json.dump(caps, f, ensure_ascii=False)
156
+ with open(paths.failed_file(idx), "w") as f:
157
+ json.dump(sorted(failed), f, indent=2)
158
+
159
+
160
+ def merge_to_global(paths, idx):
161
+ wf = paths.worker_caps_file(idx)
162
+ if not os.path.exists(wf):
163
+ return
164
+ with open(wf) as f:
165
+ worker = json.load(f)
166
+ cf = paths.captions_file()
167
+ lock = cf + ".lock"
168
+ with open(lock, "w") as lk:
169
+ fcntl.flock(lk, fcntl.LOCK_EX)
170
+ try:
171
+ g = {}
172
+ if os.path.exists(cf) and os.path.getsize(cf) > 2:
173
+ with open(cf) as f:
174
+ g = json.load(f)
175
+ g.update(worker)
176
+ tmp = cf + ".tmp"
177
+ with open(tmp, "w") as f:
178
+ json.dump(g, f, ensure_ascii=False)
179
+ os.replace(tmp, cf)
180
+ finally:
181
+ fcntl.flock(lk, fcntl.LOCK_UN)
182
+ print(f"[shard {idx:06d}] Merged {len(worker):,} captions β†’ global file")
183
+
184
+
185
+ def save_subshard(paths, idx, sub_idx, data):
186
+ p = os.path.join(paths.shards_dir(), f"shard_{idx:06d}_{sub_idx:04d}.json")
187
+ with open(p, "w") as f:
188
+ json.dump(data, f, ensure_ascii=False)
189
+
190
+
191
+ def update_meta(paths, processed, errors):
192
+ mf = paths.meta_file()
193
+ lock = mf + ".lock"
194
+ os.makedirs(os.path.dirname(mf), exist_ok=True)
195
+ with open(lock, "w") as lk:
196
+ fcntl.flock(lk, fcntl.LOCK_EX)
197
+ try:
198
+ info = {}
199
+ if os.path.exists(mf) and os.path.getsize(mf) > 2:
200
+ with open(mf) as f:
201
+ info = json.load(f)
202
+ info["processed_count"] = info.get("processed_count", 0) + processed
203
+ info["failed_count"] = info.get("failed_count", 0) + errors
204
+ info["last_run"] = time.strftime("%Y-%m-%dT%H:%M:%S")
205
+ with open(mf, "w") as f:
206
+ json.dump(info, f, indent=2)
207
+ finally:
208
+ fcntl.flock(lk, fcntl.LOCK_UN)
209
+
210
+
211
+ # ── Image helpers ─────────────────────────────────────────────────────────────
212
+ def build_vae_transforms(resolutions):
213
+ return {
214
+ res: T.Compose([
215
+ T.Resize((res, res), interpolation=T.InterpolationMode.LANCZOS),
216
+ T.ToTensor(),
217
+ T.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
218
+ ])
219
+ for res in resolutions
220
+ }
221
+
222
+
223
+ @torch.inference_mode()
224
+ def encode_latent(vae, tensor):
225
+ latent = vae.encode(tensor).latent_dist.sample()
226
+ return (latent * 0.18215).cpu()
227
+
228
+
229
+ def coerce_image(v) -> Optional[Image.Image]:
230
+ """Convert any image-like value to a PIL RGB image."""
231
+ try:
232
+ if isinstance(v, Image.Image):
233
+ return v.convert("RGB")
234
+ if isinstance(v, bytes):
235
+ return Image.open(io.BytesIO(v)).convert("RGB")
236
+ if isinstance(v, dict):
237
+ raw = v.get("bytes") or v.get("data") or v.get("image")
238
+ if raw:
239
+ return coerce_image(raw)
240
+ if isinstance(v, str) and os.path.exists(v):
241
+ return Image.open(v).convert("RGB")
242
+ except Exception:
243
+ pass
244
+ return None
245
+
246
+
247
+ def extract_caption(sample, field):
248
+ if field and field in sample:
249
+ v = sample[field]
250
+ if isinstance(v, list):
251
+ return " ".join(str(x) for x in v)
252
+ return str(v)
253
+ # Fallback: try all known caption fields
254
+ for f in CAPTION_FIELDS:
255
+ if f in sample and isinstance(sample[f], str):
256
+ return sample[f]
257
+ return ""
258
+
259
+
260
+ # ── Format-specific iterators ──��──────────────────────────────────────────────
261
+ def iter_parquet(path: str) -> Iterator[dict]:
262
+ import pyarrow.parquet as pq
263
+ from datasets import Dataset
264
+ ds = Dataset(pq.read_table(path))
265
+ yield from ds
266
+
267
+
268
+ def iter_arrow(path: str) -> Iterator[dict]:
269
+ import pyarrow as pa
270
+ with pa.memory_map(path, "r") as src:
271
+ reader = pa.ipc.open_file(src)
272
+ for i in range(reader.num_record_batches):
273
+ batch = reader.get_batch(i)
274
+ for row_idx in range(batch.num_rows):
275
+ yield {col: batch.column(col)[row_idx].as_py()
276
+ for col in batch.schema.names}
277
+
278
+
279
+ def iter_webdataset(path: str) -> Iterator[dict]:
280
+ """
281
+ Iterate a WebDataset tar shard.
282
+ Groups consecutive tar members by stem into one sample dict.
283
+ """
284
+ current_key = None
285
+ current_samp = {}
286
+
287
+ def emit(s):
288
+ return s if s else None
289
+
290
+ with tarfile.open(path, "r:*") as tf:
291
+ for member in tf:
292
+ if member.isdir() or member.size == 0:
293
+ continue
294
+ name = os.path.basename(member.name)
295
+ stem, ext = os.path.splitext(name)
296
+ ext = ext.lstrip(".").lower()
297
+
298
+ if current_key is None:
299
+ current_key = stem
300
+
301
+ if stem != current_key:
302
+ if current_samp:
303
+ yield current_samp
304
+ current_key = stem
305
+ current_samp = {}
306
+
307
+ fobj = tf.extractfile(member)
308
+ if fobj is None:
309
+ continue
310
+ raw = fobj.read()
311
+
312
+ if ext in ("jpg", "jpeg", "png", "gif", "webp", "bmp"):
313
+ try:
314
+ current_samp["image"] = Image.open(io.BytesIO(raw)).convert("RGB")
315
+ current_samp["__img_bytes__"] = raw
316
+ except Exception:
317
+ pass
318
+ elif ext == "txt":
319
+ current_samp["caption"] = raw.decode("utf-8", errors="replace").strip()
320
+ elif ext == "json":
321
+ try:
322
+ current_samp.update(json.loads(raw))
323
+ except Exception:
324
+ pass
325
+ elif ext == "cls":
326
+ try:
327
+ current_samp["label"] = raw.decode().strip()
328
+ except Exception:
329
+ pass
330
+ else:
331
+ current_samp[ext] = raw
332
+
333
+ if current_samp:
334
+ yield current_samp
335
+
336
+
337
+ def iter_zip(path: str) -> Iterator[dict]:
338
+ """
339
+ Iterate a ZIP file.
340
+ Groups image files with their sibling caption files by stem.
341
+ """
342
+ with zipfile.ZipFile(path, "r") as zf:
343
+ names = set(zf.namelist())
344
+ img_ext = {"jpg", "jpeg", "png", "gif", "webp", "bmp"}
345
+
346
+ for name in sorted(names):
347
+ ext = Path(name).suffix.lower().lstrip(".")
348
+ if ext not in img_ext:
349
+ continue
350
+ stem = Path(name).stem
351
+ sample = {}
352
+
353
+ try:
354
+ raw = zf.read(name)
355
+ sample["image"] = Image.open(io.BytesIO(raw)).convert("RGB")
356
+ except Exception:
357
+ continue
358
+
359
+ # Sibling caption
360
+ for cap_ext in ("txt", "caption"):
361
+ sib = str(Path(name).with_suffix(f".{cap_ext}"))
362
+ if sib in names:
363
+ try:
364
+ sample["caption"] = zf.read(sib).decode("utf-8", errors="replace").strip()
365
+ except Exception:
366
+ pass
367
+
368
+ # Sibling JSON metadata
369
+ sib_json = str(Path(name).with_suffix(".json"))
370
+ if sib_json in names:
371
+ try:
372
+ sample.update(json.loads(zf.read(sib_json)))
373
+ except Exception:
374
+ pass
375
+
376
+ yield sample
377
+
378
+
379
+ def iter_jsonl(path: str) -> Iterator[dict]:
380
+ with open(path) as f:
381
+ for line in f:
382
+ line = line.strip()
383
+ if not line:
384
+ continue
385
+ try:
386
+ yield json.loads(line)
387
+ except Exception:
388
+ continue
389
+
390
+
391
+ def iter_image_folder(path: str) -> Iterator[dict]:
392
+ img_ext = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
393
+ for root, _, files in os.walk(path):
394
+ for fname in sorted(files):
395
+ if Path(fname).suffix.lower() not in img_ext:
396
+ continue
397
+ img_path = os.path.join(root, fname)
398
+ sample = {}
399
+ try:
400
+ sample["image"] = Image.open(img_path).convert("RGB")
401
+ except Exception:
402
+ continue
403
+ txt_path = os.path.join(root, Path(fname).stem + ".txt")
404
+ if os.path.exists(txt_path):
405
+ sample["caption"] = open(txt_path).read().strip()
406
+ json_path = os.path.join(root, Path(fname).stem + ".json")
407
+ if os.path.exists(json_path):
408
+ try:
409
+ sample.update(json.loads(open(json_path).read()))
410
+ except Exception:
411
+ pass
412
+ yield sample
413
+
414
+
415
+ def iter_hf_streaming(dataset_name: str, split: str) -> Iterator[dict]:
416
+ from datasets import load_dataset
417
+ ds = load_dataset(dataset_name, split=split, streaming=True)
418
+ yield from ds
419
+
420
+
421
+ def get_iterator(args, info: DatasetInfo) -> Iterator[dict]:
422
+ """Return the right iterator based on detected format."""
423
+ if args.shard_file:
424
+ fmt = info.fmt
425
+ p = args.shard_file
426
+ if fmt == "parquet":
427
+ return iter_parquet(p)
428
+ elif fmt in ("tar", "tar.gz"):
429
+ return iter_webdataset(p)
430
+ elif fmt == "zip":
431
+ return iter_zip(p)
432
+ elif fmt == "arrow":
433
+ return iter_arrow(p)
434
+ elif fmt == "jsonl":
435
+ return iter_jsonl(p)
436
+ elif fmt == "folder":
437
+ return iter_image_folder(p)
438
+ else:
439
+ print(f"[warn] Unknown format '{fmt}', trying HF datasets as fallback...")
440
+ from datasets import load_dataset
441
+ ds = load_dataset("parquet", data_files={"train": p}, split="train")
442
+ return iter(ds)
443
+ else:
444
+ return iter_hf_streaming(args.hf_dataset, args.hf_split)
445
+
446
+
447
+ # ── Main ──────────────────────────────────────────────────────────────────────
448
+ def main():
449
+ args = parse_args()
450
+
451
+ # ── Detect format + fields ────────────────────────────────────────────────
452
+ src = args.shard_file or args.hf_dataset
453
+ print(f"[shard {args.shard_idx:06d}] Detecting format: {src}")
454
+
455
+ if args.shard_file:
456
+ info = detect(args.shard_file)
457
+ else:
458
+ # HF streaming: create a minimal info stub
459
+ info = DatasetInfo("hf_streaming", None, None, {})
460
+
461
+ # Allow CLI overrides
462
+ if args.image_field:
463
+ info.image_field = args.image_field
464
+ if args.caption_field:
465
+ info.caption_field = args.caption_field
466
+
467
+ print(f"[shard {args.shard_idx:06d}] {info}")
468
+
469
+ if args.detect_only:
470
+ print(f"Sample keys: {list(info.sample.keys())}")
471
+ return
472
+
473
+ # ── Setup ─────────────────────────────────────────────────────────────────
474
+ device_str = f"cuda:{args.cuda_device}" if torch.cuda.is_available() else "cpu"
475
+ device = torch.device(device_str)
476
+ print(f"[shard {args.shard_idx:06d}] Device: {device_str}")
477
+
478
+ paths = Paths(args.base_dir, args.resolutions)
479
+ paths.ensure_global_dirs()
480
+
481
+ already_done_global = load_global_done(paths)
482
+ worker_caps, failed = load_worker_state(paths, args.shard_idx)
483
+ already_done = already_done_global | set(worker_caps.keys())
484
+ print(f"[shard {args.shard_idx:06d}] Already done: {len(already_done):,} Failed: {len(failed):,}")
485
+
486
+ # ── Load VAE ──────────────────────────────────────────────────────────────
487
+ vae = None
488
+ vae_xforms = {}
489
+ if not args.no_latents:
490
+ print(f"[shard {args.shard_idx:06d}] Loading VAE: {args.vae_model}")
491
+ vae = AutoencoderKL.from_pretrained(args.vae_model).to(device)
492
+ vae.eval()
493
+ vae_xforms = build_vae_transforms(args.resolutions)
494
+
495
+ # ── Iterator ──────────────────────────────────────────────────────────────
496
+ data_iter = get_iterator(args, info)
497
+ new_caps = {}
498
+ sub_data = {}
499
+ sub_idx = 0
500
+ dirs_seen = set()
501
+ processed = 0
502
+ skipped = 0
503
+ errors = 0
504
+ t0 = time.time()
505
+
506
+ pbar = tqdm(
507
+ total=args.max_samples,
508
+ unit="img",
509
+ dynamic_ncols=True,
510
+ desc=f"shard {args.shard_idx:03d}/{args.total_shards:03d} [{info.fmt}]",
511
+ )
512
+
513
+ for local_idx, sample in enumerate(data_iter):
514
+ if args.max_samples and local_idx >= args.max_samples:
515
+ break
516
+
517
+ global_idx = args.shard_idx * 1_000_000 + local_idx
518
+ stem = f"{global_idx:012d}"
519
+
520
+ # ── Resume ────────────────────────────────────────────────────────────
521
+ if stem in already_done:
522
+ skipped += 1
523
+ pbar.update(1)
524
+ continue
525
+
526
+ # ── Extract image ──────────────────────────────────────────────────────
527
+ try:
528
+ raw_img = sample.get(info.image_field) if info.image_field else None
529
+ # Fallback: try all known image fields
530
+ if raw_img is None:
531
+ for f in IMAGE_FIELDS:
532
+ if f in sample:
533
+ raw_img = sample[f]
534
+ break
535
+ if raw_img is None:
536
+ raise ValueError(f"No image field found. Keys: {list(sample.keys())}")
537
+
538
+ pil_img = coerce_image(raw_img)
539
+ if pil_img is None:
540
+ raise ValueError(f"Could not coerce image from field '{info.image_field}'")
541
+
542
+ caption = extract_caption(sample, info.caption_field)
543
+
544
+ except Exception as e:
545
+ failed.add(stem)
546
+ errors += 1
547
+ pbar.update(1)
548
+ continue
549
+
550
+ # ── Ensure dirs ────────────────────────────────────────────────────────
551
+ bucket = paths.bucket(stem)
552
+ if bucket not in dirs_seen:
553
+ paths.ensure_dirs(stem)
554
+ dirs_seen.add(bucket)
555
+
556
+ # ── Save ───────────────────────────────────────────────────────────────
557
+ try:
558
+ if not args.no_originals:
559
+ pil_img.save(paths.orig_path(stem), format="JPEG", quality=95)
560
+
561
+ for res in args.resolutions:
562
+ resized = pil_img.resize((res, res), Image.LANCZOS)
563
+ resized.save(paths.img_path(res, stem), format="JPEG", quality=90)
564
+
565
+ if vae is not None:
566
+ tensor = vae_xforms[res](pil_img).unsqueeze(0).to(device)
567
+ lat = encode_latent(vae, tensor)
568
+ torch.save(lat, paths.lat_path(res, stem))
569
+
570
+ worker_caps[stem] = caption
571
+ new_caps[stem] = caption
572
+ sub_data[stem] = caption
573
+ already_done.add(stem)
574
+
575
+ if len(sub_data) >= args.shard_size:
576
+ save_subshard(paths, args.shard_idx, sub_idx, sub_data)
577
+ sub_idx += 1
578
+ sub_data = {}
579
+
580
+ processed += 1
581
+
582
+ except Exception:
583
+ failed.add(stem)
584
+ errors += 1
585
+ traceback.print_exc()
586
+
587
+ pbar.update(1)
588
+ elapsed = time.time() - t0 + 1e-6
589
+ pbar.set_postfix(
590
+ ok=processed, skip=skipped, err=errors,
591
+ fps=f"{processed/elapsed:.1f}",
592
+ )
593
+
594
+ # ── Periodic flush ────────────────────────────────────────────────────
595
+ if processed % args.flush_every == 0 and new_caps:
596
+ flush_worker(paths, args.shard_idx, worker_caps, failed)
597
+ new_caps = {}
598
+
599
+ pbar.close()
600
+
601
+ # ── Final flush ────────────────────────────────────────────────────────────
602
+ flush_worker(paths, args.shard_idx, worker_caps, failed)
603
+ if sub_data:
604
+ save_subshard(paths, args.shard_idx, sub_idx, sub_data)
605
+
606
+ merge_to_global(paths, args.shard_idx)
607
+ update_meta(paths, processed, errors)
608
+
609
+ elapsed = time.time() - t0
610
+ print(
611
+ f"\n[shard {args.shard_idx:06d}] Done in {elapsed/60:.1f} min\n"
612
+ f" Format : {info.fmt}\n"
613
+ f" Img field : {info.image_field}\n"
614
+ f" Cap field : {info.caption_field}\n"
615
+ f" Processed : {processed:,}\n"
616
+ f" Skipped : {skipped:,}\n"
617
+ f" Errors : {errors:,}\n"
618
+ )
619
+
620
+
621
+ if __name__ == "__main__":
622
+ main()
run_pipeline_universal.sh ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # =============================================================================
3
+ # run_pipeline_universal.sh
4
+ # Universal pipeline: download ANY HuggingFace image dataset + process in parallel
5
+ #
6
+ # Supported formats (auto-detected):
7
+ # .parquet .tar .tar.gz .tgz .zip .arrow .jsonl image folders
8
+ #
9
+ # Usage
10
+ # -----
11
+ # HF_DATASET=laion/laion400m bash run_pipeline_universal.sh
12
+ # HF_DATASET=poloclub/diffusiondb JOBS=8 CUDA_DEVICES="0,1" bash run_pipeline_universal.sh
13
+ # HF_DATASET=timbrooks/instructpix2pix-clip-filtered bash run_pipeline_universal.sh
14
+ #
15
+ # Environment variables
16
+ # ----------------------
17
+ # HF_DATASET REQUIRED β€” HuggingFace dataset name (org/repo)
18
+ # HF_SPLIT Dataset split to use [default: train]
19
+ # BASE_DIR Output base directory [default: /workspace/hem/dataset_output]
20
+ # JOBS Parallel worker count [default: 4]
21
+ # CUDA_DEVICES GPU indices, comma-separated [default: 0]
22
+ # RESOLUTIONS Space-separated px sizes [default: "256 512"]
23
+ # NO_LATENTS Set to 1 to skip VAE encoding [default: 0]
24
+ # NO_ORIGINALS Set to 1 to skip original imgs [default: 0]
25
+ # MAX_SHARDS Limit shard count (testing) [default: all]
26
+ # MAX_SAMPLES Limit rows per shard (testing) [default: all]
27
+ # IMAGE_FIELD Override auto-detected field [default: auto]
28
+ # CAPTION_FIELD Override auto-detected field [default: auto]
29
+ # DOWNLOAD_ONLY Set to 1 β€” download then stop [default: 0]
30
+ # PROCESS_ONLY Set to 1 β€” skip download [default: 0]
31
+ # DRY_RUN Set to 1 β€” print, don't run [default: 0]
32
+ # ARIA2_CONNS aria2 parallel connections [default: 16]
33
+ # ARIA2_SPLITS aria2 splits per file [default: 5]
34
+ # PYTHON Python interpreter path [default: python3]
35
+ # =============================================================================
36
+
37
+ set -euo pipefail
38
+
39
+ # ── Defaults ──────────────────────────────────────────────────────────────────
40
+ : "${HF_DATASET:?ERROR: HF_DATASET is required. Example: HF_DATASET=laion/laion400m}"
41
+ : "${HF_SPLIT:=train}"
42
+ : "${BASE_DIR:=/workspace/hem/dataset_output}"
43
+ : "${JOBS:=4}"
44
+ : "${CUDA_DEVICES:=0}"
45
+ : "${RESOLUTIONS:=256 512}"
46
+ : "${NO_LATENTS:=0}"
47
+ : "${NO_ORIGINALS:=0}"
48
+ : "${MAX_SHARDS:=}"
49
+ : "${MAX_SAMPLES:=}"
50
+ : "${IMAGE_FIELD:=}"
51
+ : "${CAPTION_FIELD:=}"
52
+ : "${DOWNLOAD_ONLY:=0}"
53
+ : "${PROCESS_ONLY:=0}"
54
+ : "${DRY_RUN:=0}"
55
+ : "${ARIA2_CONNS:=16}"
56
+ : "${ARIA2_SPLITS:=5}"
57
+ : "${PYTHON:=python3}"
58
+
59
+ RAW_DIR="${BASE_DIR}/raw_shards"
60
+ LOG_DIR="${BASE_DIR}/metadata/processing_logs"
61
+ PARALLEL_LOG="${LOG_DIR}/parallel_jobs.log"
62
+ ARIA2_LOG="${LOG_DIR}/aria2.log"
63
+ URL_FILE="${LOG_DIR}/hf_shard_urls.txt"
64
+ SHARD_LIST="${LOG_DIR}/shard_list.tsv"
65
+ WORKER_LOG_DIR="${LOG_DIR}/worker_logs"
66
+
67
+ # ── Colors ────────────────────────────────────────────────────────────────────
68
+ GRN='\033[0;32m'; YLW='\033[1;33m'; RED='\033[0;31m'; CYN='\033[0;36m'; NC='\033[0m'
69
+ log() { echo -e "${GRN}[pipeline]${NC} $*"; }
70
+ warn() { echo -e "${YLW}[pipeline]${NC} $*"; }
71
+ info() { echo -e "${CYN}[pipeline]${NC} $*"; }
72
+ die() { echo -e "${RED}[pipeline] FATAL${NC} $*" >&2; exit 1; }
73
+ run() { [[ "$DRY_RUN" == "1" ]] && echo "[DRY-RUN] $*" || eval "$*"; }
74
+
75
+ # ── Dependency check ──────────────────────────────────────────────────────────
76
+ check_deps() {
77
+ log "Checking dependencies..."
78
+ local miss=()
79
+ command -v aria2c &>/dev/null || miss+=("aria2c β†’ sudo apt install aria2")
80
+ command -v parallel &>/dev/null || miss+=("parallel β†’ sudo apt install parallel")
81
+ command -v "$PYTHON" &>/dev/null || miss+=("$PYTHON")
82
+ "$PYTHON" -c "import datasets, diffusers, torch, torchvision, pyarrow, PIL" 2>/dev/null \
83
+ || miss+=("Python packages β†’ bash setup_universal.sh")
84
+ [[ ${#miss[@]} -gt 0 ]] && die "Missing:\n$(printf ' β€’ %s\n' "${miss[@]}")"
85
+ log "OK"
86
+ }
87
+
88
+ # ── HuggingFace token ─────────────────────────────────────────────────────────
89
+ get_hf_token() {
90
+ local tok_file="$HOME/.cache/huggingface/token"
91
+ if [[ -f "$tok_file" ]]; then
92
+ cat "$tok_file"
93
+ else
94
+ echo ""
95
+ fi
96
+ }
97
+
98
+ # ── Phase 0: Probe dataset (detect format, list files) ───────────────────────
99
+ phase_probe() {
100
+ log "=== Phase 0: Probe dataset $HF_DATASET ==="
101
+ mkdir -p "$RAW_DIR" "$LOG_DIR" "$WORKER_LOG_DIR"
102
+
103
+ "$PYTHON" - <<PYEOF
104
+ import sys, os, json
105
+ from huggingface_hub import HfFileSystem, hf_hub_download
106
+ from huggingface_hub.utils import EntryNotFoundError
107
+
108
+ fs = HfFileSystem()
109
+ repo = "datasets/${HF_DATASET}"
110
+ base = "https://huggingface.co/datasets/${HF_DATASET}/resolve/main"
111
+ token = open(os.path.expanduser("~/.cache/huggingface/token")).read().strip() \
112
+ if os.path.exists(os.path.expanduser("~/.cache/huggingface/token")) else None
113
+
114
+ # List all files in the repo
115
+ try:
116
+ all_files = fs.ls(repo, detail=False, recursive=True)
117
+ except Exception as e:
118
+ print(f"ERROR listing repo: {e}", file=sys.stderr)
119
+ sys.exit(1)
120
+
121
+ # Supported shard extensions (in preference order)
122
+ SHARD_EXTS = {".parquet", ".tar", ".tar.gz", ".tgz", ".zip", ".arrow", ".jsonl", ".json"}
123
+
124
+ shard_files = [f for f in sorted(all_files)
125
+ if any(f.endswith(ext) for ext in SHARD_EXTS)
126
+ and not f.endswith("metadata.json")
127
+ and not f.endswith(".gitattributes")]
128
+
129
+ if not shard_files:
130
+ # Maybe it's an image folder dataset β€” list image files
131
+ img_exts = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
132
+ shard_files = [f for f in sorted(all_files)
133
+ if any(f.endswith(e) for e in img_exts)]
134
+ is_folder = True
135
+ else:
136
+ is_folder = False
137
+
138
+ print(f"Found {len(shard_files)} shard files (folder_mode={is_folder})", file=sys.stderr)
139
+
140
+ # Write aria2 input file
141
+ with open("${URL_FILE}", "w") as out:
142
+ for p in shard_files:
143
+ rel = p.split("${HF_DATASET}/")[-1]
144
+ out.write(f"{base}/{rel}\n")
145
+ out.write(f" dir=${RAW_DIR}\n")
146
+ fname = rel.replace("/", "__") # flatten subdirs into filename
147
+ out.write(f" out={fname}\n")
148
+
149
+ # Write metadata about what we found
150
+ meta = {
151
+ "hf_dataset": "${HF_DATASET}",
152
+ "hf_split": "${HF_SPLIT}",
153
+ "shard_count": len(shard_files),
154
+ "is_folder_dataset": is_folder,
155
+ "sample_files": shard_files[:5],
156
+ }
157
+ with open("${LOG_DIR}/probe_result.json", "w") as f:
158
+ json.dump(meta, f, indent=2)
159
+
160
+ print(json.dumps(meta, indent=2))
161
+ PYEOF
162
+
163
+ log "Probe complete. URL file: $URL_FILE"
164
+ }
165
+
166
+ # ── Phase 1: Download with aria2 ─────────────────────────────────────────────
167
+ phase_download() {
168
+ log "=== Phase 1: Download shards ==="
169
+
170
+ [[ -s "$URL_FILE" ]] || die "URL file missing or empty. Run probe first."
171
+
172
+ SHARD_COUNT=$(grep -c "^https" "$URL_FILE" || true)
173
+ log "Downloading $SHARD_COUNT files with aria2 ($ARIA2_CONNS connections, $ARIA2_SPLITS splits/file)..."
174
+
175
+ HF_TOKEN="$(get_hf_token)"
176
+ AUTH=""
177
+ [[ -n "$HF_TOKEN" ]] && AUTH="--header=Authorization: Bearer ${HF_TOKEN}"
178
+
179
+ run aria2c \
180
+ --input-file="$URL_FILE" \
181
+ ${AUTH:+"$AUTH"} \
182
+ --max-concurrent-downloads="$ARIA2_CONNS" \
183
+ --split="$ARIA2_SPLITS" \
184
+ --min-split-size=10M \
185
+ --continue=true \
186
+ --retry-wait=5 \
187
+ --max-tries=10 \
188
+ --file-allocation=none \
189
+ --console-log-level=warn \
190
+ --log="$ARIA2_LOG" \
191
+ --log-level=notice \
192
+ --summary-interval=30
193
+
194
+ log "Download complete β†’ $RAW_DIR"
195
+ ls -lh "$RAW_DIR" | tail -5
196
+ }
197
+
198
+ # ── Phase 2: Detect shard format and build worker args ────────────────────────
199
+ phase_build_shard_list() {
200
+ log "=== Phase 2a: Build shard list ==="
201
+
202
+ mapfile -t RAW_FILES < <(find "$RAW_DIR" -type f | sort)
203
+ TOTAL="${#RAW_FILES[@]}"
204
+
205
+ if [[ "$TOTAL" -eq 0 ]]; then
206
+ die "No files in $RAW_DIR β€” run download phase first."
207
+ fi
208
+
209
+ # Probe first file to detect format
210
+ FIRST="${RAW_FILES[0]}"
211
+ info "Probing format of: $FIRST"
212
+ "$PYTHON" - "$FIRST" <<'PYEOF'
213
+ import sys
214
+ from format_detector import detect
215
+ info = detect(sys.argv[1])
216
+ print(f" Format: {info.fmt}")
217
+ print(f" Image field: {info.image_field}")
218
+ print(f" Caption field: {info.caption_field}")
219
+ PYEOF
220
+
221
+ # Apply MAX_SHARDS cap
222
+ if [[ -n "$MAX_SHARDS" && "$MAX_SHARDS" -lt "$TOTAL" ]]; then
223
+ warn "Capping to $MAX_SHARDS of $TOTAL shards"
224
+ RAW_FILES=("${RAW_FILES[@]:0:$MAX_SHARDS}")
225
+ TOTAL="$MAX_SHARDS"
226
+ fi
227
+
228
+ # Write shard list: idx TAB filepath
229
+ > "$SHARD_LIST"
230
+ for i in "${!RAW_FILES[@]}"; do
231
+ echo -e "${i}\t${RAW_FILES[$i]}" >> "$SHARD_LIST"
232
+ done
233
+
234
+ log "Shard list written: $SHARD_LIST ($TOTAL entries)"
235
+ }
236
+
237
+ # ── Phase 3: Process with GNU Parallel ───────────────────────────────────────
238
+ phase_process() {
239
+ log "=== Phase 2b: Process $TOTAL shards with $JOBS workers ==="
240
+
241
+ # Build GPU array
242
+ IFS=',' read -ra GPU_ARR <<< "$CUDA_DEVICES"
243
+ GPU_COUNT="${#GPU_ARR[@]}"
244
+
245
+ # Build optional flags
246
+ EXTRA_FLAGS=""
247
+ [[ "$NO_LATENTS" == "1" ]] && EXTRA_FLAGS+=" --no-latents"
248
+ [[ "$NO_ORIGINALS" == "1" ]] && EXTRA_FLAGS+=" --no-originals"
249
+ [[ -n "$IMAGE_FIELD" ]] && EXTRA_FLAGS+=" --image-field $IMAGE_FIELD"
250
+ [[ -n "$CAPTION_FIELD" ]] && EXTRA_FLAGS+=" --caption-field $CAPTION_FIELD"
251
+ [[ -n "$MAX_SAMPLES" ]] && EXTRA_FLAGS+=" --max-samples $MAX_SAMPLES"
252
+
253
+ RES_FLAGS="--resolutions $RESOLUTIONS"
254
+
255
+ # Per-job command
256
+ # GNU Parallel substitutions: {1}=shard_idx {2}=shard_file {%}=slot
257
+ read -r -d '' WORKER_CMD <<CMD || true
258
+ shard_idx={1}
259
+ shard_file={2}
260
+ slot={%}
261
+ gpu_idx=\${GPU_ARR[\$(( (slot-1) % GPU_COUNT ))]}
262
+
263
+ log_file="${WORKER_LOG_DIR}/shard_\$(printf '%06d' \$shard_idx).log"
264
+
265
+ echo "[slot \$slot | gpu \$gpu_idx] shard \$shard_idx β†’ \$shard_file" >&2
266
+
267
+ CUDA_VISIBLE_DEVICES=\$gpu_idx \\
268
+ $PYTHON ingest_universal.py \\
269
+ --shard-file "\$shard_file" \\
270
+ --shard-idx \$shard_idx \\
271
+ --total-shards $TOTAL \\
272
+ --base-dir "$BASE_DIR" \\
273
+ --cuda-device 0 \\
274
+ $RES_FLAGS \\
275
+ $EXTRA_FLAGS \\
276
+ > "\$log_file" 2>&1
277
+
278
+ ec=\$?
279
+ [[ \$ec -ne 0 ]] && echo "[FAILED shard \$shard_idx] exit=\$ec log: \$log_file" >&2
280
+ exit \$ec
281
+ CMD
282
+
283
+ # Export GPU array for subshell
284
+ export GPU_ARR GPU_COUNT
285
+
286
+ if [[ "$DRY_RUN" == "1" ]]; then
287
+ warn "[DRY-RUN] Would run GNU Parallel over $TOTAL shards"
288
+ warn "[DRY-RUN] Worker command:"
289
+ echo "$WORKER_CMD"
290
+ return
291
+ fi
292
+
293
+ parallel \
294
+ --jobs "$JOBS" \
295
+ --colsep '\t' \
296
+ --progress \
297
+ --eta \
298
+ --bar \
299
+ --joblog "$PARALLEL_LOG" \
300
+ --resume-failed \
301
+ --halt soon,fail=20 \
302
+ bash -c "$WORKER_CMD" \
303
+ :::: "$SHARD_LIST"
304
+
305
+ log "All workers finished."
306
+ }
307
+
308
+ # ── Phase 4: Report ───────────────────────────────────────────────────────────
309
+ phase_report() {
310
+ log "=== Pipeline Report ==="
311
+
312
+ echo ""
313
+ info "Dataset : $HF_DATASET"
314
+ info "Output dir : $BASE_DIR"
315
+ echo ""
316
+
317
+ # Count captions
318
+ CAPS=$("$PYTHON" -c "
319
+ import json, os
320
+ f = '${BASE_DIR}/captions/captions.json'
321
+ print(len(json.load(open(f))) if os.path.exists(f) and os.path.getsize(f) > 2 else 0)
322
+ " 2>/dev/null || echo "?")
323
+
324
+ # Count failed across all shards
325
+ FAILED=$( ls "${LOG_DIR}"/failed_shard_*.json 2>/dev/null \
326
+ | xargs -I{} "$PYTHON" -c "import json; d=json.load(open('{}'));print(len(d))" 2>/dev/null \
327
+ | paste -sd+ | bc 2>/dev/null || echo "?" )
328
+
329
+ # Disk usage
330
+ DISK=$(du -sh "$BASE_DIR" 2>/dev/null | cut -f1 || echo "?")
331
+
332
+ info "Captions processed : $CAPS"
333
+ info "Total failed IDs : $FAILED"
334
+ info "Disk used : $DISK"
335
+ info "Worker logs : $WORKER_LOG_DIR/"
336
+ info "Parallel job log : $PARALLEL_LOG"
337
+ echo ""
338
+
339
+ # Show any failed shards from GNU Parallel log
340
+ if [[ -f "$PARALLEL_LOG" ]]; then
341
+ FAILED_JOBS=$(awk -F'\t' 'NR>1 && $7!=0 {print $0}' "$PARALLEL_LOG" | wc -l)
342
+ if [[ "$FAILED_JOBS" -gt 0 ]]; then
343
+ warn "$FAILED_JOBS shards had errors. To retry:"
344
+ warn " PROCESS_ONLY=1 bash run_pipeline_universal.sh"
345
+ else
346
+ log "All shards completed successfully."
347
+ fi
348
+ fi
349
+ }
350
+
351
+ # ── Main ──────────────────────────────────────────────────────────────────────
352
+ main() {
353
+ echo ""
354
+ log "╔══════════════════════════════════════════════════════╗"
355
+ log "β•‘ Universal HF Image Dataset Pipeline β•‘"
356
+ log "β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•"
357
+ echo ""
358
+ log "Dataset : $HF_DATASET ($HF_SPLIT)"
359
+ log "Output : $BASE_DIR"
360
+ log "Workers : $JOBS | GPUs: $CUDA_DEVICES"
361
+ log "Res : $RESOLUTIONS | Latents: $([ "$NO_LATENTS" = "1" ] && echo NO || echo YES)"
362
+ [[ -n "$MAX_SHARDS" ]] && warn "MAX_SHARDS=$MAX_SHARDS (testing mode)"
363
+ [[ -n "$MAX_SAMPLES" ]] && warn "MAX_SAMPLES=$MAX_SAMPLES (testing mode)"
364
+ [[ "$DRY_RUN" == "1" ]] && warn "DRY_RUN=1 β€” no files will be written"
365
+ echo ""
366
+
367
+ check_deps
368
+
369
+ if [[ "$PROCESS_ONLY" != "1" ]]; then
370
+ phase_probe
371
+ phase_download
372
+ else
373
+ log "Skipping download (PROCESS_ONLY=1)"
374
+ fi
375
+
376
+ if [[ "$DOWNLOAD_ONLY" != "1" ]]; then
377
+ phase_build_shard_list
378
+ phase_process
379
+ else
380
+ log "Skipping processing (DOWNLOAD_ONLY=1)"
381
+ fi
382
+
383
+ phase_report
384
+ log "Pipeline done."
385
+ }
386
+
387
+ main "$@"
setup_universal.sh ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # =============================================================================
3
+ # setup_universal.sh β€” Install all dependencies for the universal pipeline
4
+ # =============================================================================
5
+ set -euo pipefail
6
+
7
+ GRN='\033[0;32m'; NC='\033[0m'
8
+ log() { echo -e "${GRN}[setup]${NC} $*"; }
9
+
10
+ # ── System packages ───────────────────────────────────────────────────────────
11
+ log "Installing system packages..."
12
+ sudo apt-get update -qq
13
+ sudo apt-get install -y --no-install-recommends \
14
+ aria2 \
15
+ parallel \
16
+ pigz \
17
+ pv \
18
+ jq \
19
+ bc \
20
+ curl wget ca-certificates \
21
+ libgl1 libglib2.0-0 # needed by Pillow on headless servers
22
+
23
+ # Silence GNU Parallel citation nag
24
+ mkdir -p ~/.parallel && touch ~/.parallel/will-cite
25
+
26
+ # ── Python packages ───────────────────────────────────────────────────────────
27
+ log "Installing Python packages..."
28
+ pip install --upgrade pip --quiet
29
+
30
+ pip install --quiet \
31
+ datasets \
32
+ diffusers \
33
+ transformers \
34
+ accelerate \
35
+ torch torchvision \
36
+ pyarrow \
37
+ Pillow \
38
+ tqdm \
39
+ huggingface_hub \
40
+ safetensors \
41
+ webdataset \
42
+ pyarrow \
43
+ orjson \
44
+ requests
45
+
46
+ # ── HuggingFace login ─────────────────────────────────────────────────────────
47
+ HF_TOKEN_FILE="$HOME/.cache/huggingface/token"
48
+ if [[ ! -f "$HF_TOKEN_FILE" ]]; then
49
+ log "No HuggingFace token found. Run: huggingface-cli login"
50
+ else
51
+ log "HuggingFace token found βœ“"
52
+ fi
53
+
54
+ # ── Directory scaffold ────────────────────────────────────────────────────────
55
+ BASE_DIR="${BASE_DIR:-/workspace/hem/dataset_output}"
56
+ log "Creating base directory structure: $BASE_DIR"
57
+
58
+ mkdir -p \
59
+ "${BASE_DIR}/images/original" \
60
+ "${BASE_DIR}/captions/shards" \
61
+ "${BASE_DIR}/metadata/processing_logs/worker_logs" \
62
+ "${BASE_DIR}/raw_shards" \
63
+ "${BASE_DIR}/logs"
64
+
65
+ for res in 256 512 1024; do
66
+ mkdir -p "${BASE_DIR}/images/${res}x${res}"
67
+ mkdir -p "${BASE_DIR}/latents/sd-vae-${res}"
68
+ done
69
+
70
+ # Seed empty files
71
+ CAPS="${BASE_DIR}/captions/captions.json"
72
+ [[ -f "$CAPS" ]] || echo '{}' > "$CAPS"
73
+
74
+ META="${BASE_DIR}/metadata/dataset_info.json"
75
+ if [[ ! -f "$META" ]]; then
76
+ cat > "$META" <<JSON
77
+ {
78
+ "hf_dataset": null,
79
+ "hf_split": "train",
80
+ "resolutions": [256, 512],
81
+ "vae_model": "stabilityai/sd-vae-ft-ema",
82
+ "processed_count": 0,
83
+ "failed_count": 0,
84
+ "last_run": null
85
+ }
86
+ JSON
87
+ fi
88
+
89
+ # ── Verify format_detector is importable ──────────────────────────────────────
90
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
91
+ if [[ -f "$SCRIPT_DIR/format_detector.py" ]]; then
92
+ log "Verifying format_detector.py..."
93
+ python3 -c "from format_detector import detect; print(' format_detector OK')" \
94
+ || echo " [warn] Could not import format_detector β€” ensure it is in the same folder"
95
+ fi
96
+
97
+ log ""
98
+ log "Setup complete βœ“"
99
+ log ""
100
+ log "Quick start:"
101
+ log " huggingface-cli login"
102
+ log " HF_DATASET=LLAAMM/text2image1m bash run_pipeline_universal.sh"
103
+ log ""
104
+ log "Other examples:"
105
+ log " HF_DATASET=laion/laion400m JOBS=8 CUDA_DEVICES=0,1,2,3 bash run_pipeline_universal.sh"
106
+ log " HF_DATASET=poloclub/diffusiondb RESOLUTIONS='256' NO_LATENTS=1 bash run_pipeline_universal.sh"
107
+ log " HF_DATASET=timbrooks/instructpix2pix-clip-filtered bash run_pipeline_universal.sh"
108
+ log ""
109
+ log "Test run (3 shards, 100 samples each, no VAE):"
110
+ log " HF_DATASET=your/dataset MAX_SHARDS=3 MAX_SAMPLES=100 NO_LATENTS=1 bash run_pipeline_universal.sh"