File size: 23,716 Bytes
f8e648b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
"""
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


# ── CLI ───────────────────────────────────────────────────────────────────────
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()


# ── Path helpers ──────────────────────────────────────────────────────────────
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)


# ── State helpers ─────────────────────────────────────────────────────────────
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)


# ── Image helpers ─────────────────────────────────────────────────────────────
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)
    # Fallback: try all known caption fields
    for f in CAPTION_FIELDS:
        if f in sample and isinstance(sample[f], str):
            return sample[f]
    return ""


# ── Format-specific iterators ─────────────────────────────────────────────────
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

            # Sibling caption
            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

            # Sibling JSON metadata
            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)


# ── Main ──────────────────────────────────────────────────────────────────────
def main():
    args = parse_args()

    # ── Detect format + fields ────────────────────────────────────────────────
    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:
        # HF streaming: create a minimal info stub
        info = DatasetInfo("hf_streaming", None, None, {})

    # Allow CLI overrides
    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

    # ── Setup ─────────────────────────────────────────────────────────────────
    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):,}")

    # ── Load VAE ──────────────────────────────────────────────────────────────
    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)

    # ── Iterator ──────────────────────────────────────────────────────────────
    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}"

        # ── Resume ────────────────────────────────────────────────────────────
        if stem in already_done:
            skipped += 1
            pbar.update(1)
            continue

        # ── Extract image ──────────────────────────────────────────────────────
        try:
            raw_img = sample.get(info.image_field) if info.image_field else None
            # Fallback: try all known image fields
            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

        # ── Ensure dirs ────────────────────────────────────────────────────────
        bucket = paths.bucket(stem)
        if bucket not in dirs_seen:
            paths.ensure_dirs(stem)
            dirs_seen.add(bucket)

        # ── Save ───────────────────────────────────────────────────────────────
        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}",
        )

        # ── Periodic flush ────────────────────────────────────────────────────
        if processed % args.flush_every == 0 and new_caps:
            flush_worker(paths, args.shard_idx, worker_caps, failed)
            new_caps = {}

    pbar.close()

    # ── Final flush ────────────────────────────────────────────────────────────
    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()