Download code/prepare_data.py from pei2333/Grid_CrossDomain_Compress_Delivery_20261105: direct link, hf CLI and curl.
- Browser
- Download file 7.63 kB
-
https://huggingface.co/datasets/pei2333/Grid_CrossDomain_Compress_Delivery_20261105/resolve/main/code/prepare_data.py
- Command line
-
hf download hf://datasets/pei2333/Grid_CrossDomain_Compress_Delivery_20261105/code/prepare_data.py
-
curl -L -o prepare_data.py https://huggingface.co/datasets/pei2333/Grid_CrossDomain_Compress_Delivery_20261105/resolve/main/code/prepare_data.py
7.63 kB
| """Same-task / different-domain power-grid detection splits (YOLO format, images hardlinked). | |
| A_weather (clear -> fog), classes insulator/defect, from SFID (UPID images + synthetic fog): | |
| SFID id i comes from UPID source image i//10 (i%10==0 is the original, the rest are its augmentations; | |
| checked against UPID augmented_labels_train.json: all 686 originals sit at 10g). SFID's own split puts copies | |
| of one source in both train and test, so we re-split by source: 70/10/20. Train sources are halved so | |
| clear-train and fog-train never share a scene; val/test use the same sources in both domains (paired). | |
| B_region (China -> Brazil), class insulator: | |
| cn = SFID clear images (CPLID-derived), all train sources, same val/test sources as A, defect boxes dropped. | |
| br = InsPLAD-det (UAV, Brazil; Voxel51/InsPLAD FiftyOne export), glass + polymer insulator -> insulator. | |
| Official det val -> test; official det train split by tower/flight prefix 90/10 -> train/val. | |
| python prepare_data.py sfid --raw raw/sfid/SFID --out A_weather | |
| python prepare_data.py region --raw raw/sfid/SFID --insplad raw/insplad_hf --out B_region | |
| """ | |
| import argparse, json, os, random | |
| from pathlib import Path | |
| def put(root, split, stem, img, lines): | |
| dst = root / "images" / split / f"{stem}{img.suffix}" | |
| dst.parent.mkdir(parents=True, exist_ok=True) | |
| if not dst.exists(): os.link(img, dst) | |
| lab = root / "labels" / split / f"{stem}.txt" | |
| lab.parent.mkdir(parents=True, exist_ok=True) | |
| lab.write_text("".join(l + "\n" for l in lines)) | |
| def write_yaml(path, root, names, train, val, test): | |
| fmt = lambda v: "[" + ", ".join(v) + "]" if isinstance(v, list) else v | |
| path.write_text(f"path: {root}\ntrain: {fmt(train)}\nval: {fmt(val)}\ntest: {fmt(test)}\nnames: {dict(enumerate(names))}\n") | |
| def write_yamls(out, doms, names): | |
| for d in doms: | |
| write_yaml(out / f"{d}.yaml", out, names, *(f"{d}/images/{s}" for s in ("train", "val", "test"))) | |
| write_yaml(out / "multi.yaml", out, names, *([f"{d}/images/{s}" for d in doms] for s in ("train", "val", "test"))) | |
| def sfid_groups(raw, seed=0): | |
| """SFID images {stem: path} and UPID source group -> 'train_clear' | 'train_fog' | 'val' | 'test'.""" | |
| imgs = {p.stem: p for p in Path(raw).glob("images/*/*.jpg")} | |
| groups = sorted({int(s.removeprefix("fogged_")) // 10 for s in imgs}) | |
| random.Random(seed).shuffle(groups) | |
| n = len(groups); a, b = int(.7 * n), int(.8 * n) | |
| split = {g: "val" for g in groups[a:b]} | {g: "test" for g in groups[b:]} | |
| split |= {g: ("train_clear", "train_fog")[i % 2] for i, g in enumerate(groups[:a])} | |
| return imgs, split | |
| def sfid_labels(raw, img, stem): | |
| p = Path(raw) / "labels" / img.parent.name / f"{stem}.txt" | |
| return [l.strip() for l in p.read_text().splitlines() if l.strip()] if p.exists() else [] | |
| def sfid(raw, out, seed=0): | |
| out = Path(out).resolve(); imgs, split = sfid_groups(raw, seed); count = {} | |
| for stem, img in imgs.items(): | |
| dom, i = ("fog" if stem.startswith("fogged_") else "clear"), int(stem.removeprefix("fogged_")) | |
| s = split[i // 10] | |
| if s.startswith("train_"): | |
| if s != f"train_{dom}": continue | |
| s = "train" | |
| put(out / dom, s, f"{i:06d}", img, sfid_labels(raw, img, stem)) | |
| count[dom, s] = count.get((dom, s), 0) + 1 | |
| write_yamls(out, ("clear", "fog"), ["insulator", "defect"]) | |
| print("A_weather images", dict(sorted(count.items()))) | |
| INSPLAD_INSULATOR = {"glass insulator", "polymer insulator"} | |
| def region(raw, insplad, out, seed=0): | |
| out, ins = Path(out).resolve(), Path(insplad).resolve(); imgs, split = sfid_groups(raw, seed); count = {} | |
| for stem, img in imgs.items(): | |
| if stem.startswith("fogged_"): continue | |
| s = split[int(stem) // 10].split("_")[0] # both train halves | |
| put(out / "cn", s, stem, img, [l for l in sfid_labels(raw, img, stem) if l.split()[0] == "0"]) | |
| count["cn", s] = count.get(("cn", s), 0) + 1 | |
| det = [x for x in json.load(open(ins / "samples.json"))["samples"] if x["task"] == "detection"] | |
| pre = lambda x: Path(x["filepath"]).stem.split("_")[0] # tower / flight id | |
| assert len({Path(x["filepath"]).stem for x in det}) == len(det), "InsPLAD stems collide" | |
| tr = sorted({pre(x) for x in det if "train" in x["tags"]}); random.Random(seed).shuffle(tr) | |
| val_pre, missing = set(tr[: len(tr) // 10]), 0 | |
| for x in det: | |
| img = ins / x["filepath"] | |
| if not img.exists(): missing += 1; continue | |
| s = "test" if "val" in x["tags"] else "val" if pre(x) in val_pre else "train" | |
| boxes = [d["bounding_box"] for d in (x["ground_truth"] or {}).get("detections", []) if d["label"] in INSPLAD_INSULATOR] | |
| put(out / "br", s, img.stem, img, [f"0 {b[0] + b[2] / 2:.6f} {b[1] + b[3] / 2:.6f} {b[2]:.6f} {b[3]:.6f}" for b in boxes]) | |
| count["br", s] = count.get(("br", s), 0) + 1 | |
| write_yamls(out, ("cn", "br"), ["insulator"]) | |
| print("B_region images", dict(sorted(count.items())), "| InsPLAD missing", missing) | |
| def cnfog(raw, out, seed=0): | |
| """Third B site: the cn scenes under SFID's synthetic fog (same source groups and splits as cn), insulator only.""" | |
| out = Path(out).resolve(); imgs, split = sfid_groups(raw, seed); count = {} | |
| for stem, img in imgs.items(): | |
| if not stem.startswith("fogged_"): continue | |
| i = int(stem.removeprefix("fogged_")); s = split[i // 10].split("_")[0] # both train halves, as cn | |
| put(out / "cnfog", s, f"{i:06d}", img, [l for l in sfid_labels(raw, img, stem) if l.split()[0] == "0"]) | |
| count[s] = count.get(s, 0) + 1 | |
| write_yaml(out / "cnfog.yaml", out, ["insulator"], *(f"cnfog/images/{s}" for s in ("train", "val", "test"))) | |
| write_yaml(out / "multi3.yaml", out, ["insulator"], *([f"{d}/images/{s}" for d in ("cn", "cnfog", "br")] for s in ("train", "val", "test"))) | |
| print("B_region cnfog images", dict(sorted(count.items()))) | |
| def coco_ref(zip_path, out): | |
| """Generic images with empty labels: the local-support switch's negative density (gridkd.py lsl --neg).""" | |
| import zipfile | |
| root = Path(out).resolve() | |
| img, lab = root / "images" / "val", root / "labels" / "val" | |
| img.mkdir(parents=True, exist_ok=True); lab.mkdir(parents=True, exist_ok=True) | |
| with zipfile.ZipFile(zip_path) as z: | |
| for n in z.namelist(): | |
| if n.lower().endswith(".jpg"): | |
| (img / Path(n).name).write_bytes(z.read(n)) | |
| (lab / f"{Path(n).stem}.txt").write_text("") | |
| for tag, names in (("1c", ["insulator"]), ("2c", ["insulator", "defect"])): # class names must match the model | |
| write_yaml(root / f"ref_{tag}.yaml", root, names, "images/val", "images/val", "images/val") | |
| print(len(list(img.glob("*.jpg"))), "reference images ->", root) | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser(); sub = ap.add_subparsers(dest="cmd", required=True) | |
| for c in ("sfid", "region"): | |
| p = sub.add_parser(c); p.add_argument("--raw", required=True); p.add_argument("--out", required=True); p.add_argument("--seed", type=int, default=0) | |
| if c == "region": p.add_argument("--insplad", required=True) | |
| p = sub.add_parser("coco_ref"); p.add_argument("--zip", required=True); p.add_argument("--out", required=True) | |
| p = sub.add_parser("cnfog"); p.add_argument("--raw", required=True); p.add_argument("--out", required=True) | |
| a = ap.parse_args() | |
| if a.cmd == "coco_ref": coco_ref(a.zip, a.out) | |
| elif a.cmd == "cnfog": cnfog(a.raw, a.out) | |
| elif a.cmd == "sfid": sfid(a.raw, a.out, a.seed) | |
| else: region(a.raw, a.insplad, a.out, a.seed) | |