"""Fetch the pictures OBELICS and PixMo publish only as links. Max side 512 px, JPEG q88, stored at /images//.jpg; an index parquet maps url -> file (or the failure reason). Resumable. Dead links are expected and simply recorded. python3 fetch_images.py obelics 400000 # first N documents with 1-4 pictures python3 fetch_images.py pixmo """ import sys, io, os, glob, hashlib, time, json, pathlib, concurrent.futures as cf import pyarrow as pa, pyarrow.parquet as pq BASE = pathlib.Path("/workspace/shadow/data/understanding/image") UA = {"User-Agent": "Mozilla/5.0 (research dataset fetch; img2dataset-style)"} def urls_obelics(ndocs): out, docs = [], 0 sel = [] for f in sorted(glob.glob(str(BASE / "obelics/**/*.parquet"), recursive=True)): t = pq.read_table(f, columns=["images"]).column("images").to_pylist() for i, imgs in enumerate(t): u = [x for x in (imgs or []) if x] if 1 <= len(u) <= 4: sel.append((os.path.relpath(f, BASE / "obelics"), i)); out += u; docs += 1 if docs >= ndocs: break if docs >= ndocs: break pq.write_table(pa.table({"file": [a for a, _ in sel], "row": [b for _, b in sel]}), BASE / "obelics/selected_docs.parquet") return out def urls_pixmo(d=BASE / "pixmo-cap"): out = [] for f in sorted(glob.glob(str(d / "**/*.parquet"), recursive=True)): out += pq.read_table(f, columns=["image_url"]).column("image_url").to_pylist() return out def fetch_chunk(args): urls, outdir = args import requests from PIL import Image Image.MAX_IMAGE_PIXELS = 60_000_000 # bigger ones cost seconds of CPU each; dropped s = requests.Session(); s.headers.update(UA); res = [] for u in urls: h = hashlib.sha1(u.encode()).hexdigest(); p = pathlib.Path(outdir) / h[:2] / (h + ".jpg") if p.exists(): res.append((u, str(p), "ok")); continue try: r = s.get(u, timeout=(5, 12), stream=True) if r.status_code != 200: res.append((u, "", f"http{r.status_code}")); continue b = r.raw.read(15_000_000, decode_content=True) im = Image.open(io.BytesIO(b)); im.draft("RGB", (1024, 1024)); im = im.convert("RGB"); im.thumbnail((512, 512)) # draft: JPEG decodes at 1/2..1/8 scale if min(im.size) < 32: res.append((u, "", "tiny")); continue p.parent.mkdir(parents=True, exist_ok=True); im.save(p, "JPEG", quality=88); res.append((u, str(p), "ok")) except Exception as e: res.append((u, "", type(e).__name__[:20])) return res def main(): src = sys.argv[1] ASK = BASE.parent.parent / "sft/vision/pixmo-ask" urls = (urls_obelics(int(sys.argv[2]) if len(sys.argv) > 2 else 400000) if src == "obelics" else urls_pixmo(ASK) if src == "pixmo-ask" else urls_pixmo()) urls = list(dict.fromkeys(urls)); outdir = (ASK if src == "pixmo-ask" else BASE / src) / "images" print(time.strftime("%H:%M:%S"), src, len(urls), "unique urls", flush=True) chunks = [(urls[i:i + 200], str(outdir)) for i in range(0, len(urls), 200)] got, t0, allres = 0, time.time(), [] # threads inside processes: 96 processes x the chunk loop; network-bound, so many at once with cf.ProcessPoolExecutor(48) as ex: # the pod's cgroup has 31 cores futs = [ex.submit(fetch_chunk, c) for c in chunks] for k, fu in enumerate(cf.as_completed(futs)): r = fu.result(); allres += r; got += sum(1 for x in r if x[2] == "ok") if k % 200 == 0: print(time.strftime("%H:%M:%S"), f"{len(allres):,}/{len(urls):,} tried, {got:,} ok ({100*got/max(1,len(allres)):.0f}%), {len(allres)/(time.time()-t0):.0f}/s", flush=True) pq.write_table(pa.table({"url": [a for a, _, _ in allres], "path": [b for _, b, _ in allres], "status": [c for _, _, c in allres]}), outdir.parent / "fetch_index.parquet") print(time.strftime("%H:%M:%S"), f"DONE {src}: {got:,} of {len(urls):,} pictures ({100*got/len(urls):.0f}%)", flush=True) if __name__ == "__main__": main()