Download src/build_eval_sets.py from ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/resolve/main/src/build_eval_sets.py
- Command line
-
hf download hf://spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/src/build_eval_sets.py
-
curl -L -o build_eval_sets.py https://huggingface.co/spaces/ElenaZhan/TrueSight_AI_Detection_with_Stability_Checks/resolve/main/src/build_eval_sets.py
11.8 kB
| """Fixed on-disk evaluation sets. Deliverable for teammate C. | |
| Seven conditions: clean jpeg_q90 jpeg_q70 jpeg_q50 jpeg_q30 blur_s2 crop80 | |
| THE HARD CONSTRAINT | |
| All seven conditions contain the SAME source images at the SAME crop positions; only the | |
| transform differs. This is guaranteed structurally: every condition is generated from the | |
| identical list of already-fixed 256px crops in manifests/val.csv, so a crop cannot drift | |
| between conditions. If clean and jpeg_q30 drew different images, the gap between their AUCs | |
| would mix in image difficulty and could no longer be attributed to compression. | |
| Deterministic and written to disk: C needs byte-identical inputs across runs, and the | |
| competition requires reproducible open-source evaluation code. Every output file's sha256 is | |
| recorded in its manifest; `--verify` recomputes them. | |
| Stored as PNG so that the condition's own transform is the only degradation present -- saving | |
| a q30 image as JPEG would stack a second compression on top of the one being measured. | |
| Usage | |
| python src/build_eval_sets.py | |
| python src/build_eval_sets.py --verify | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import collections | |
| import csv | |
| import hashlib | |
| import sys | |
| import time | |
| from pathlib import Path | |
| from PIL import Image, ImageFilter | |
| from tqdm import tqdm | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import common as C # noqa: E402 | |
| EVAL_COLUMNS = ["crop_path", "img_id", "crop_idx", "label_orig", "label_bin", | |
| "source", "split", "condition", "sha256"] | |
| # -------------------------------------------------------------------------------------- | |
| # conditions: single, fixed, non-random transforms | |
| # -------------------------------------------------------------------------------------- | |
| def apply_condition(img: Image.Image, spec: dict) -> Image.Image: | |
| op = spec["op"] | |
| if op == "none": | |
| return img | |
| if op == "jpeg": | |
| import io | |
| buf = io.BytesIO() | |
| img.save(buf, "JPEG", quality=int(spec["quality"])) | |
| buf.seek(0) | |
| out = Image.open(buf) | |
| out.load() | |
| return out.convert("RGB") | |
| if op == "blur": | |
| return img.filter(ImageFilter.GaussianBlur(radius=float(spec["sigma"]))) | |
| if op == "crop": | |
| # Centre crop to `scale` then resample back, so every condition yields the same | |
| # pixel dimensions and the model input stays comparable across conditions. | |
| w, h = img.size | |
| s = float(spec["scale"]) | |
| cw, ch = int(round(w * s)), int(round(h * s)) | |
| x, y = (w - cw) // 2, (h - ch) // 2 | |
| return img.crop((x, y, x + cw, y + ch)).resize((w, h), Image.Resampling.BICUBIC) | |
| raise ValueError("unknown eval op: %r" % op) | |
| def stratum(r: dict) -> str: | |
| """The group an image is balanced within. | |
| v1 manifests have no `arch`, so this falls back to label_orig and reproduces the original | |
| behaviour exactly. In v2 `label_orig` is dataset-local -- label 1 means full_synthetic in | |
| SID_Set but simply "fake" in WildFake -- so balancing on it would silently blend two | |
| different things. `arch` is the cross-dataset key, and reals are split by their source so | |
| neither dataset dominates the negative class. | |
| """ | |
| arch = r.get("arch") | |
| if arch is None: | |
| return "L%s" % r["label_orig"] | |
| if arch: | |
| return arch | |
| return "real_%s" % r["source"].split(":")[0] | |
| def _select_rows_v1(cfg: dict, rows: list, n_images: int = None) -> list: | |
| """The v1 selection, preserved verbatim. | |
| v1's eval sets are already published; re-running this script on a v1 manifest must return | |
| a byte-identical set or the sha256 column stops meaning anything. Do not "improve" this. | |
| """ | |
| target = int(n_images or cfg["eval_sets"]["n_images"]) | |
| per_img = int(cfg["normalize"]["crops_per_image"]) | |
| labels = sorted({int(r["label_orig"]) for r in rows}) | |
| per_label_imgs = max(1, target // (len(labels) * per_img)) | |
| by_label = collections.defaultdict(lambda: collections.defaultdict(list)) | |
| for r in rows: | |
| by_label[int(r["label_orig"])][r["img_id"]].append(r) | |
| picked = [] | |
| for lab in labels: | |
| ids = sorted(by_label[lab], key=lambda i: C.md5_order_key("evalpick", lab, i)) | |
| for iid in ids[:per_label_imgs]: | |
| picked.extend(sorted(by_label[lab][iid], key=lambda r: int(r["crop_idx"]))) | |
| picked.sort(key=lambda r: C.md5_order_key("evalorder", r["img_id"], r["crop_idx"])) | |
| return picked | |
| def select_rows(cfg: dict, rows: list, n_images: int = None) -> list: | |
| """Deterministic, stratified selection of WHOLE images (never half an image). | |
| A manifest without an `arch` column is v1 and goes down the frozen v1 path. With `arch` | |
| present, the real:fake ratio is held at the manifest's own ratio and, within each side, | |
| strata get equal counts. | |
| """ | |
| if not rows or "arch" not in rows[0]: | |
| return _select_rows_v1(cfg, rows, n_images) | |
| target = int(n_images or cfg["eval_sets"]["n_images"]) | |
| per_img = int(cfg["normalize"]["crops_per_image"]) | |
| n_img_total = max(1, target // per_img) | |
| by_stratum = collections.defaultdict(lambda: collections.defaultdict(list)) | |
| side = {} | |
| for r in rows: | |
| s = stratum(r) | |
| by_stratum[s][r["img_id"]].append(r) | |
| side[s] = int(r["label_bin"]) | |
| real_s = sorted(s for s in by_stratum if side[s] == 0) | |
| fake_s = sorted(s for s in by_stratum if side[s] == 1) | |
| n_real_img = int(round(n_img_total * len( | |
| [r for r in rows if r["label_bin"] == "0"]) / max(len(rows), 1))) | |
| n_fake_img = n_img_total - n_real_img | |
| picked = [] | |
| for group, quota in ((real_s, n_real_img), (fake_s, n_fake_img)): | |
| if not group: | |
| continue | |
| per = max(1, quota // len(group)) | |
| for s in group: | |
| ids = sorted(by_stratum[s], key=lambda i: C.md5_order_key("evalpick", s, i)) | |
| for iid in ids[:per]: | |
| picked.extend(sorted(by_stratum[s][iid], key=lambda r: int(r["crop_idx"]))) | |
| picked.sort(key=lambda r: C.md5_order_key("evalorder", r["img_id"], r["crop_idx"])) | |
| return picked | |
| def sha256_file(p: Path) -> str: | |
| h = hashlib.sha256() | |
| with open(p, "rb") as fh: | |
| for chunk in iter(lambda: fh.read(1 << 20), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| # -------------------------------------------------------------------------------------- | |
| def build(cfg: dict, tag: str = "", source: str = None, n_images: int = None) -> int: | |
| """`tag` isolates the outputs (data/eval_sets_<tag>/, manifests/<tag>_eval_*.csv) so a | |
| rebuild for a later dataset version can never overwrite the sets teammates already have.""" | |
| root = Path(cfg["_root"]) | |
| src_manifest = root / (source or cfg["eval_sets"]["source"]) | |
| if not src_manifest.exists(): | |
| print("[eval] source manifest missing: %s (run build_sid.py --split val first)" | |
| % src_manifest) | |
| return 2 | |
| with open(src_manifest, newline="", encoding="utf-8") as fh: | |
| rows = list(csv.DictReader(fh)) | |
| picked = select_rows(cfg, rows, n_images) | |
| conditions = cfg["eval_sets"]["conditions"] | |
| fmt = cfg["eval_sets"].get("store_format", "PNG").upper() | |
| ext = ".png" if fmt == "PNG" else ".jpg" | |
| print("[eval] %d crops from %d images x %d conditions = %d files" | |
| % (len(picked), len({r['img_id'] for r in picked}), len(conditions), | |
| len(picked) * len(conditions))) | |
| eval_root = C.ensure_dir(root / (cfg["paths"]["eval_dir"] + (("_" + tag) if tag else ""))) | |
| man_dir = C.ensure_dir(root / cfg["paths"]["manifests_dir"]) | |
| pre = (tag + "_") if tag else "" | |
| index_rows = [] | |
| t0 = time.time() | |
| # Load each source crop ONCE and fan it out to all seven conditions: same bytes in, | |
| # so the conditions cannot diverge in which image or which crop they used. | |
| per_cond = {name: [] for name in conditions} | |
| for r in tqdm(picked, desc="[eval] crops", unit="crop"): | |
| src = root / r["crop_path"] | |
| base = Image.open(src) | |
| base.load() | |
| base = base.convert("RGB") | |
| stem = "%s__c%s__L%s" % (r["img_id"], r["crop_idx"], r["label_orig"]) | |
| for name, spec in conditions.items(): | |
| out_dir = C.ensure_dir(eval_root / name / str(r["label_orig"])) | |
| out_p = out_dir / (stem + ext) | |
| apply_condition(base, spec).save(out_p, fmt) | |
| rel = str(out_p.relative_to(root)).replace("\\", "/") | |
| row = {"crop_path": rel, "img_id": r["img_id"], "crop_idx": r["crop_idx"], | |
| "label_orig": r["label_orig"], "label_bin": r["label_bin"], | |
| "source": r["source"], "split": r["split"], "condition": name, | |
| "sha256": sha256_file(out_p)} | |
| per_cond[name].append(row) | |
| index_rows.append(row) | |
| for name, rws in per_cond.items(): | |
| p = man_dir / ("%seval_%s.csv" % (pre, name)) | |
| with open(p, "w", newline="", encoding="utf-8") as fh: | |
| w = csv.DictWriter(fh, fieldnames=EVAL_COLUMNS) | |
| w.writeheader() | |
| w.writerows(rws) | |
| idx = man_dir / ("%seval_index.csv" % pre) | |
| with open(idx, "w", newline="", encoding="utf-8") as fh: | |
| w = csv.DictWriter(fh, fieldnames=EVAL_COLUMNS) | |
| w.writeheader() | |
| w.writerows(index_rows) | |
| # Structural proof of the hard constraint, printed so it is visible in the run log. | |
| keysets = {n: {(r["img_id"], r["crop_idx"]) for r in rws} for n, rws in per_cond.items()} | |
| ref = keysets["clean"] | |
| identical = all(v == ref for v in keysets.values()) | |
| print("\n[eval] wrote %d files in %s" % (len(index_rows), C.fmt_secs(time.time() - t0))) | |
| print("[eval] all conditions share the same (img_id, crop_idx) set: %s" % identical) | |
| if not identical: | |
| print("[eval] FATAL: conditions diverged") | |
| return 3 | |
| strata = collections.Counter(stratum(r) for r in picked) | |
| bins = collections.Counter(r["label_bin"] for r in per_cond["clean"]) | |
| print("[eval] per condition: %d crops | label_bin %s" % (len(ref), dict(sorted(bins.items())))) | |
| for k, v in sorted(strata.items()): | |
| print(" %-22s %5d crops" % (k, v)) | |
| print("[eval] manifests: %s and %seval_<condition>.csv" % (idx, pre)) | |
| return 0 | |
| def verify(cfg: dict, tag: str = "") -> int: | |
| root = Path(cfg["_root"]) | |
| pre = (tag + "_") if tag else "" | |
| idx = root / cfg["paths"]["manifests_dir"] / ("%seval_index.csv" % pre) | |
| if not idx.exists(): | |
| print("[verify] %s missing; build first" % idx) | |
| return 2 | |
| with open(idx, newline="", encoding="utf-8") as fh: | |
| rows = list(csv.DictReader(fh)) | |
| bad = missing = 0 | |
| for r in tqdm(rows, desc="[verify]", unit="file"): | |
| p = root / r["crop_path"] | |
| if not p.exists(): | |
| missing += 1 | |
| continue | |
| if sha256_file(p) != r["sha256"]: | |
| bad += 1 | |
| print("[verify] %d files, %d missing, %d checksum mismatches" % (len(rows), missing, bad)) | |
| return 0 if (bad == 0 and missing == 0) else 1 | |
| def main() -> int: | |
| ap = argparse.ArgumentParser(description="build fixed evaluation sets") | |
| ap.add_argument("--config", default=None) | |
| ap.add_argument("--verify", action="store_true") | |
| ap.add_argument("--tag", default="", | |
| help="isolate outputs: data/eval_sets_<tag>/, manifests/<tag>_eval_*.csv") | |
| ap.add_argument("--source", default=None, | |
| help="val manifest to build from (default: config eval_sets.source)") | |
| ap.add_argument("--n", type=int, default=None, help="target crop count") | |
| args = ap.parse_args() | |
| cfg = C.load_config(args.config) | |
| return verify(cfg, args.tag) if args.verify else build(cfg, args.tag, args.source, args.n) | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |