"""Собрать обучающие данные из настоящего COCO train. Источник: jxie/coco_captions — parquet-шарды с полями image / filename / cocoid / caption. Одна строка = одна подпись, на картинку их 5, поэтому группируем по cocoid: пиксели пишем один раз, подписи копим списком. Выход — тот же формат, что у vl_data: images.npy (N×3×128×128 uint8), captions.bin (uint16), captions_off.npy, captions_img.npy, meta.json. Запуск: python train/local/build_coco_train.py --images 30000 """ from __future__ import annotations import argparse import json import os import sys import time import numpy as np from PIL import Image WS = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) PKG = os.path.join(WS, "train", "ppai") sys.path.insert(0, PKG) IMAGE_SIZE = 128 SHARD_URL = ("https://huggingface.co/datasets/jxie/coco_captions/resolve/main/" "data/train-{i:05d}-of-00182-{h}.parquet") # имена шардов с хешами (берём подряд, порядок не важен) SHARDS = [ "5c0b9bd6a017ebf2", "da54490dde6f6b5a", "8e857bc953d617a4", ] def list_shards(token: str | None) -> list[str]: from huggingface_hub import HfApi api = HfApi(token=token) files = api.list_repo_files("jxie/coco_captions", repo_type="dataset", token=token) return sorted(f for f in files if "/train-" in f) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--images", type=int, default=30000) ap.add_argument("--out", default=os.path.join(WS, "pposr_local75", "data")) ap.add_argument("--base", default=os.path.join(WS, "pposr_local", "export"), help="откуда взять токенизатор") ap.add_argument("--files", type=int, default=0, help="сколько шардов качать (0 = авто)") args = ap.parse_args() from datasets import load_dataset from transformers import AutoTokenizer tok = AutoTokenizer.from_pretrained(args.base, trust_remote_code=True) eos = tok.eos_token_id print(f"[coco] токенизатор {len(tok)}, eos={eos}", flush=True) files = list_shards(None) need = args.files or max(6, int(args.images / 650 * 1.25)) files = files[:need] print(f"[coco] шардов: {len(files)} (цель {args.images} картинок)", flush=True) os.makedirs(args.out, exist_ok=True) images = np.zeros((args.images, 3, IMAGE_SIZE, IMAGE_SIZE), dtype=np.uint8) idx_of: dict[int, int] = {} caps_of: list[list[str]] = [] n = 0 seen_rows = 0 t0 = time.time() for fi in files: url = f"https://huggingface.co/datasets/jxie/coco_captions/resolve/main/{fi}" try: ds = load_dataset("parquet", data_files=[url], split="train", streaming=True) except Exception as exc: # noqa: BLE001 print(f"[coco] шард {os.path.basename(fi)}: пропуск ({type(exc).__name__})", flush=True) continue for ex in ds: if n >= args.images: break cid = int(ex.get("cocoid") or 0) cap = (ex.get("caption") or "").strip() if not cid or not cap: continue seen_rows += 1 if cid not in idx_of: if n >= args.images: break img = ex.get("image") if img is None: continue if not isinstance(img, Image.Image): img = Image.fromarray(np.asarray(img)) small = np.asarray( img.convert("RGB").resize((IMAGE_SIZE, IMAGE_SIZE), Image.BICUBIC), dtype=np.uint8, ).transpose(2, 0, 1) images[n] = small idx_of[cid] = n caps_of.append([]) n += 1 if n % 2000 == 0: el = (time.time() - t0) / 60 print(f"[coco] {n} картинок, {sum(len(c) for c in caps_of)} подписей, " f"{el:.0f} мин", flush=True) caps_of[idx_of[cid]].append(cap) if n >= args.images: break print(f"[coco] собрано {n} картинок, строк просмотрено {seen_rows}", flush=True) # плоские массивы подписей flat: list[int] = [] offsets: list[int] = [] img_idx: list[int] = [] pos = 0 for i, caps in enumerate(caps_of[:n]): if not caps: continue for c in caps[:5]: ids = tok(c, add_special_tokens=False).input_ids[:255] if not ids: continue offsets.append(pos) img_idx.append(i) flat.extend(ids + [eos]) pos += len(ids) + 1 images = images[:n] np.save(os.path.join(args.out, "images.npy"), images) np.asarray(flat, dtype=np.uint16).tofile(os.path.join(args.out, "captions.bin")) np.save(os.path.join(args.out, "captions_off.npy"), np.asarray(offsets, dtype=np.int64)) np.save(os.path.join(args.out, "captions_img.npy"), np.asarray(img_idx, dtype=np.int32)) lens = np.diff(np.asarray(offsets + [pos])) meta = {"n_images": int(n), "n_captions": len(offsets), "mean_caption_len": float(lens.mean()) if len(lens) else 0.0, "vocab_size": len(tok), "image_size": IMAGE_SIZE, "eos": eos, "source": "jxie/coco_captions train"} json.dump(meta, open(os.path.join(args.out, "meta.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=2) print(f"[coco] готово: {meta['n_images']} картинок, {meta['n_captions']} подписей, " f"средняя длина {meta['mean_caption_len']:.1f}", flush=True) if __name__ == "__main__": main()