"""Caption CC3M images through the local strata OpenAI-compatible endpoint. Two-phase on purpose: phase 1 (this script) -> captions.jsonl, append-only and resumable phase 2 (recaption.py) -> turn jsonl + images into a token dataset Resumable because 5k images at ~1.3 s each is a ~2 h job; a crash should not throw away finished work. """ import argparse import base64 import io import json import os import re import tarfile import time import urllib.request from PIL import Image COLOURS = ["red", "blue", "green", "yellow", "white", "black", "silver", "grey", "gray", "orange", "brown", "gold"] PROMPT = ("Describe this image in one detailed sentence. Include the main " "subject's colour, what it is doing, and the setting. " "Output the sentence only, no preamble.") def b64_jpeg(im, side=512): im = im.convert("RGB") w, h = im.size s = side / max(w, h) if s < 1: im = im.resize((int(w * s), int(h * s)), Image.BICUBIC) buf = io.BytesIO() im.save(buf, format="JPEG", quality=88) return base64.b64encode(buf.getvalue()).decode() def caption_one(url, model, im, timeout=180, retries=3): payload = { "model": model, "messages": [{ "role": "user", "content": [ {"type": "text", "text": PROMPT}, {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + b64_jpeg(im)}}, ], }], "max_tokens": 90, "temperature": 0.2, "chat_template_kwargs": {"enable_thinking": False}, } last = None for a in range(retries): try: req = urllib.request.Request( url, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=timeout) as r: body = json.loads(r.read().decode()) txt = (body["choices"][0]["message"].get("content") or "").strip() txt = " ".join(txt.split()) if txt: return txt last = "empty content" except Exception as e: last = str(e)[:120] time.sleep(2 + 2 * a) raise RuntimeError(last) def main(): ap = argparse.ArgumentParser() ap.add_argument("--shards", nargs="+", required=True) ap.add_argument("--filter", default="car") ap.add_argument("--out", default="../data_mm_car_q/captions.jsonl") ap.add_argument("--url", default="http://127.0.0.1:8080/v1/chat/completions") ap.add_argument("--model", default="qwen3.8-flash-next-gyro-gyro-s") ap.add_argument("--limit", type=int, default=0) args = ap.parse_args() os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True) done = set() if os.path.exists(args.out): with open(args.out) as f: for line in f: try: done.add(json.loads(line)["key"]) except Exception: pass print(f"resume: {len(done)} already captioned", flush=True) filt = re.compile(r"\b" + re.escape(args.filter) + r"s?\b", re.I) n = 0 t0 = time.time() fout = open(args.out, "a") for shard in args.shards: try: tf = tarfile.open(shard) except Exception: continue try: for m in tf: if not m.isfile() or not m.name.endswith(".txt"): continue key = m.name[:-4] if key in done: continue cap = tf.extractfile(m).read().decode("utf-8", "ignore").strip() if not filt.search(cap): continue try: jm = tf.getmember(key + ".jpg") except KeyError: continue try: im = Image.open(io.BytesIO(tf.extractfile(jm).read())) if min(im.size) < 200: continue txt = caption_one(args.url, args.model, im) except Exception as e: print(f" skip {key}: {e}", flush=True) continue rec = {"key": key, "shard": os.path.basename(shard), "old": cap, "new": txt, "has_colour": any(re.search(r"\b" + w + r"\b", txt.lower()) for w in COLOURS)} fout.write(json.dumps(rec, ensure_ascii=False) + "\n") fout.flush() n += 1 if n % 100 == 0: el = time.time() - t0 print(f" {n} new ({len(done)+n} total) " f"{el/n:.2f} s/img eta {(5184-n)*el/n/60:.0f} min", flush=True) if args.limit and n >= args.limit: raise SystemExit(0) except SystemExit: raise except Exception as e: print(f" partial {os.path.basename(shard)}: {e}", flush=True) finally: tf.close() fout.close() print(f"done: {n} newly captioned, {len(done)+n} total", flush=True) if __name__ == "__main__": main()