2.5_possible_fire_final / prepare_coco.py
unicornwhodev's picture
Unify corrected corpus additively: preserve 38,965 originals and add 64,374 images
d93939e verified
Raw History Blame Contribute Delete
2 kB
from pathlib import Path
import argparse, hashlib, json
from datasets import load_dataset, Image as DatasetImage
from huggingface_hub import HfApi, hf_hub_download
REPO="fireviewer/flame_smoke_detection_box_not_precise"
def prepare(output, task="fire_smoke", revision=None):
revision=revision or HfApi().dataset_info(REPO).sha
out=Path(output); out.mkdir(parents=True,exist_ok=True)
wanted={}; totals={}
for split in ["train","validation","test"]:
p=hf_hub_download(REPO,f"annotations/merged/{task}/{split}.json",repo_type="dataset",revision=revision)
d=json.loads(Path(p).read_text())
wanted[split]={im["sha256"]:im for im in d["images"]}
folder=out/split; (folder/"images").mkdir(parents=True,exist_ok=True)
for im in d["images"]: im["file_name"]="images/"+Path(im["file_name"]).name
(folder/"_annotations.coco.json").write_text(json.dumps(d,ensure_ascii=False),encoding="utf-8")
seen=set()
for row in load_dataset(REPO,"corpus",split=split,revision=revision,streaming=True).cast_column("image",DatasetImage(decode=False)):
h=row["sha256"]
if h not in wanted[split]: continue
image=row["image"]
if not isinstance(image,dict): raise RuntimeError("Image decoding must be disabled; cast the image column to datasets.Image(decode=False).")
blob=image["bytes"]; assert hashlib.sha256(blob).hexdigest()==h
dest=folder/wanted[split][h]["file_name"]
dest.write_bytes(blob); seen.add(h)
assert seen==set(wanted[split]),(split,len(seen),len(wanted[split]))
totals[split]=len(seen)
return totals, {"revision":revision,"task":task}
if __name__=="__main__":
p=argparse.ArgumentParser();p.add_argument("--output",required=True);p.add_argument("--task",choices=["fire_smoke","visible_flame","probable_fire"],default="fire_smoke");p.add_argument("--revision")
a=p.parse_args(); print(prepare(a.output,a.task,a.revision))