Download scripts/caption.py from RASHID778/king2-image-dataset: direct link, hf CLI and curl.
- Browser
- Download file 6.7 kB
-
https://huggingface.co/datasets/RASHID778/king2-image-dataset/resolve/main/scripts/caption.py
- Command line
-
hf download hf://datasets/RASHID778/king2-image-dataset/scripts/caption.py
-
curl -L -o caption.py https://huggingface.co/datasets/RASHID778/king2-image-dataset/resolve/main/scripts/caption.py
6.7 kB
| import argparse | |
| import json | |
| import os | |
| import shutil | |
| import sys | |
| RUN_DIR = os.environ.get("RUN_DIR", "/content") | |
| def get_token() -> str: | |
| tok = os.environ.get("HF_TOKEN", "").strip() | |
| if tok: | |
| return tok | |
| for p in ( | |
| os.path.join(RUN_DIR, "king_hf_token.txt"), | |
| "/content/king_hf_token.txt", | |
| "/content/hf_token.txt", | |
| ): | |
| if os.path.isfile(p): | |
| tok = open(p, encoding="utf-8-sig").read().strip() | |
| if tok: | |
| return tok | |
| try: | |
| from google.colab import userdata | |
| tok = str(userdata.get("HF_TOKEN") or "").strip() | |
| if tok: | |
| return tok | |
| except Exception: | |
| pass | |
| try: | |
| from kaggle_secrets import UserSecretsClient | |
| tok = str(UserSecretsClient().get_secret("HF_TOKEN") or "").strip() | |
| if tok: | |
| return tok | |
| except Exception: | |
| pass | |
| raise RuntimeError(f"HF_TOKEN not found (env, {RUN_DIR}/king_hf_token.txt, Colab or Kaggle secret 'HF_TOKEN')") | |
| def _push_metadata(rows_by_key: dict, output: str, repo_id: str) -> None: | |
| from huggingface_hub import HfApi | |
| tmp = os.path.join(RUN_DIR, "metadata_upload.jsonl") | |
| with open(tmp, "w", encoding="utf-8") as fh: | |
| for k, v in sorted(rows_by_key.items()): | |
| fh.write(json.dumps({"file_name": k, "text": v}, ensure_ascii=False) + "\n") | |
| HfApi().upload_file( | |
| path_or_fileobj=tmp, | |
| path_in_repo=output, | |
| repo_id=repo_id, | |
| repo_type="dataset", | |
| commit_message=f"captions progress ({len(rows_by_key)} rows)", | |
| ) | |
| print(f"[pushed] {len(rows_by_key)} rows -> {repo_id}/{output}", flush=True) | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--repo_id", default="RASHID778/king2-image-dataset") | |
| ap.add_argument("--data_dir", default="", help="local dir with indoor/outdoor subfolders + metadata.jsonl; skips snapshot_download") | |
| ap.add_argument("--model", default="microsoft/Florence-2-base") | |
| ap.add_argument("--task", default="DETAILED_CAPTION") | |
| ap.add_argument("--batch", type=int, default=8) | |
| ap.add_argument("--max_new_tokens", type=int, default=512) | |
| ap.add_argument("--start", type=int, default=0) | |
| ap.add_argument("--end", type=int, default=0) | |
| ap.add_argument("--output", default="metadata.jsonl") | |
| args = ap.parse_args() | |
| import torch | |
| from huggingface_hub import login, snapshot_download | |
| from PIL import Image | |
| from transformers import AutoModelForCausalLM, AutoProcessor | |
| login(token=get_token()) | |
| print("[download] dataset images", flush=True) | |
| data_dir = args.data_dir or snapshot_download( | |
| args.repo_id, | |
| repo_type="dataset", | |
| allow_patterns=["indoor/*", "outdoor/*", "metadata.jsonl"], | |
| ) | |
| if not os.path.isdir(data_dir): | |
| raise RuntimeError(f"data_dir missing: {data_dir}") | |
| # always pull the newest metadata.jsonl from the repo so we resume | |
| from huggingface_hub import hf_hub_download | |
| meta_dl = hf_hub_download( | |
| repo_id=args.repo_id, filename="metadata.jsonl", repo_type="dataset" | |
| ) | |
| shutil.copy(meta_dl, os.path.join(data_dir, "metadata.jsonl")) | |
| meta_path = os.path.join(data_dir, "metadata.jsonl") | |
| rows_by_key: dict[str, str] = {} | |
| if os.path.isfile(meta_path): | |
| for line in open(meta_path, encoding="utf-8"): | |
| row = json.loads(line) | |
| rows_by_key[row["file_name"]] = row.get("text", "") | |
| images = [] | |
| actual = {} | |
| for sub in ("indoor", "outdoor"): | |
| subdir = os.path.join(data_dir, sub) | |
| if not os.path.isdir(subdir): | |
| subdir = os.path.join(data_dir, sub.capitalize()) | |
| if not os.path.isdir(subdir): | |
| continue | |
| actual[sub] = subdir | |
| for name in sorted(os.listdir(subdir)): | |
| images.append(f"{sub}/{name}") | |
| total = len(images) | |
| end = args.end or total | |
| images = images[args.start:end] | |
| pending = [im for im in images if not rows_by_key.get(im, "").strip()] | |
| print( | |
| f"[plan] caption {len(pending)} of {len(images)} (start={args.start}, end={args.end or total})", | |
| flush=True, | |
| ) | |
| images = pending | |
| processor = AutoProcessor.from_pretrained(args.model, trust_remote_code=True) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| args.model, trust_remote_code=True, torch_dtype=torch.float16 | |
| ).to("cuda") | |
| print(f"[loaded] {args.model} on cuda, task={args.task}", flush=True) | |
| task_prompt = f"<{args.task}>" | |
| done = 0 | |
| last_upload = 0 | |
| for i in range(0, len(images), args.batch): | |
| chunk = images[i : i + args.batch] | |
| paths = [] | |
| for fn in chunk: | |
| sub, name = fn.split("/", 1) | |
| paths.append(os.path.join(actual.get(sub, os.path.join(data_dir, sub)), name)) | |
| pil = [Image.open(p).convert("RGB") for p in paths] | |
| inputs = processor(text=[task_prompt] * len(pil), images=pil, return_tensors="pt").to("cuda") | |
| with torch.no_grad(): | |
| with torch.autocast(device_type="cuda"): | |
| generated = model.generate( | |
| **inputs, | |
| max_new_tokens=args.max_new_tokens, | |
| num_beams=3, | |
| do_sample=False, | |
| ) | |
| texts = processor.batch_decode(generated, skip_special_tokens=True) | |
| for fn, t in zip(chunk, texts): | |
| cap = t.replace(task_prompt, "").strip() | |
| rows_by_key[fn] = cap | |
| done += 1 | |
| if done % (args.batch * 25) == 0 or i + args.batch >= len(images): | |
| print(f"[progress] {done}/{len(images)} captioned", flush=True) | |
| with open(os.path.join(RUN_DIR, "caption_progress.jsonl"), "w", encoding="utf-8") as fh: | |
| for k, v in rows_by_key.items(): | |
| fh.write(json.dumps({"file_name": k, "text": v}, ensure_ascii=False) + "\n") | |
| if done - last_upload >= 500: | |
| last_upload = done | |
| _push_metadata(rows_by_key, args.output, args.repo_id) | |
| print("[complete] writing metadata.jsonl", flush=True) | |
| out_path = os.path.join(RUN_DIR, "metadata.jsonl") | |
| lines = [{"file_name": k, "text": v} for k, v in sorted(rows_by_key.items())] | |
| with open(out_path, "w", encoding="utf-8") as fh: | |
| for row in lines: | |
| fh.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| sample = [r for r in lines if r["text"]][:3] | |
| for s in sample: | |
| print(f" {s['file_name']}: {s['text'][:120]}", flush=True) | |
| _push_metadata(rows_by_key, args.output, args.repo_id) | |
| print(f"[uploaded] {args.output} -> {args.repo_id}", flush=True) | |
| if __name__ == "__main__": | |
| main() |