#!/usr/bin/env python3 'Build zero-shot and jointly supervised cross-dataset training and evaluation manifests.' from __future__ import annotations import argparse import csv import hashlib import json import sys from collections import defaultdict from pathlib import Path from typing import Any PROJECT_ROOT = Path(__file__).resolve().parents[2] SPLIT_DIR = PROJECT_ROOT / "artifacts" / "metadata" / "fixed_split" DEFAULT_OUTPUT_DIR = PROJECT_ROOT / "artifacts" / "metadata" / "transfer" TRAINING_SPLIT = PROJECT_ROOT / "artifacts" / "metadata" / "training" / "splits" / "training_split_n900_realratio_0p1_seed42.json" N_GRID = [900, 90, 18] ALLOWED_EXTS = {".jpg", ".jpeg", ".png", ".webp"} csv.field_size_limit(min(sys.maxsize, 2_147_483_647)) def stable_rank(seed: int, group_key: str, sample_id: str) -> int: key = f"{seed}:{group_key}:{sample_id}".encode("utf-8") return int(hashlib.sha256(key).hexdigest(), 16) def read_csv(path: Path) -> list[dict[str, str]]: with path.open("r", newline="", encoding="utf-8") as f: return list(csv.DictReader(f)) def write_json(path: Path, data: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False) def ratio_tag(value: float) -> str: return str(value).replace(".", "p") def ranked_rows(rows: list[dict[str, str]], seed: int, group: str) -> list[dict[str, str]]: def key(row: dict[str, str]) -> tuple[int, int, str]: split_rank = row.get("split_rank") if split_rank not in (None, ""): return (0, int(split_rank), row["sample_id"]) return (1, stable_rank(seed, group, row["sample_id"]), row["sample_id"]) return sorted(rows, key=key) def group_ai(rows: list[dict[str, str]]) -> dict[str, list[dict[str, str]]]: grouped: dict[str, list[dict[str, str]]] = defaultdict(list) for row in rows: grouped[row["source_model_id"]].append(row) return grouped def manifest_row(path: str, label: int, source: str, source_type: str) -> dict[str, Any]: return {"path": path, "label": label, "source": source, "source_type": source_type} def to_manifest_rows(rows: list[dict[str, str]], label: int, source: str, source_type: str) -> list[dict[str, Any]]: return [manifest_row(row["image_path"], label, source, source_type) for row in rows] def image_files(path: Path) -> list[str]: if not path.is_dir(): return [] return [str(p) for p in sorted(path.iterdir()) if p.is_file() and p.suffix.lower() in ALLOWED_EXTS] def collect_genimage(root: Path) -> dict[str, dict[str, list[str]]]: data: dict[str, dict[str, list[str]]] = {} for gen_dir in sorted([p for p in root.iterdir() if p.is_dir()]): if gen_dir.name.startswith("_"): continue fake = image_files(gen_dir / "val" / "ai") real = image_files(gen_dir / "val" / "nature") if fake and real: data[gen_dir.name] = {"fake": fake, "real": real} return data def collect_forensynths(root: Path) -> dict[str, dict[str, list[str]]]: data: dict[str, dict[str, list[str]]] = {} for gen_dir in sorted([p for p in root.iterdir() if p.is_dir()]): fake: list[str] = [] real: list[str] = [] if (gen_dir / "0_real").is_dir() and (gen_dir / "1_fake").is_dir(): real.extend(image_files(gen_dir / "0_real")) fake.extend(image_files(gen_dir / "1_fake")) else: for class_dir in sorted([p for p in gen_dir.iterdir() if p.is_dir()]): real.extend(image_files(class_dir / "0_real")) fake.extend(image_files(class_dir / "1_fake")) if fake and real: data[gen_dir.name] = {"fake": fake, "real": real} return data def build_external_manifests( name: str, data: dict[str, dict[str, list[str]]], seed: int, output_dir: Path, real_ratio: float = 0.1, exclude_insufficient_k900: bool = False, ) -> dict[int, Path]: paths: dict[int, Path] = {} for k in [0]: sources = sorted(data) if exclude_insufficient_k900 and k == 900: sources = [source for source in sources if len(data[source]["fake"]) >= 1000 and len(data[source]["real"]) >= 900] train_rows: list[dict[str, Any]] = [] test_rows: list[dict[str, Any]] = [] source_summary: dict[str, dict[str, int]] = {} for source in sources: fake = sorted(data[source]["fake"], key=lambda p: stable_rank(seed, f"{name}:fake:{source}", p)) real = sorted(data[source]["real"], key=lambda p: stable_rank(seed, f"{name}:real:{source}", p)) fake_train_count = min(k, len(fake)) if k > 0 else 0 real_train_count = min(int(real_ratio * fake_train_count), len(real)) if k > 0 else 0 if k > 0: train_rows.extend(manifest_row(p, 1, source, name) for p in fake[:fake_train_count]) train_rows.extend(manifest_row(p, 0, f"real:{source}", "real") for p in real[:real_train_count]) test_rows.extend(manifest_row(p, 1, source, name) for p in fake[fake_train_count:]) test_rows.extend(manifest_row(p, 0, f"real:{source}", "real") for p in real[real_train_count:]) source_summary[source] = { "fake_total": len(fake), "real_total": len(real), "fake_train": fake_train_count, "real_train": real_train_count, "fake_test": max(0, len(fake) - fake_train_count), "real_test": max(0, len(real) - real_train_count), } path = output_dir / "manifests" / f"{name}_k{k}_realratio_{ratio_tag(real_ratio)}_seed{seed}.json" write_json( path, { "name": name, "k_per_source": k, "real_ratio": real_ratio, "sources": sources, "source_summary": source_summary, "train": train_rows, "test": test_rows, }, ) paths[k] = path return paths def load_wildgen_balanced_rows(training_split: Path, k: int, real_ratio: float) -> list[dict[str, Any]]: """Take K images per WildGen source (+ real_ratio*K*num_sources pooled real) from the Phase-2 binary training split. Paths are kept in the split's deterministic order, so the first K per source is a nested subset across K values.""" with training_split.open("r", encoding="utf-8") as f: split = json.load(f) train = split["train"] ai_ids = sorted([mid for mid in train if mid != "0"], key=int) rows: list[dict[str, Any]] = [] for mid in ai_ids: for path in train[mid][:k]: rows.append(manifest_row(path, 1, f"wildgen:{mid}", "wildgen")) real_needed = int(real_ratio * k * len(ai_ids)) for path in train["0"][:real_needed]: rows.append(manifest_row(path, 0, "real:wildgen", "real")) return rows def build_joint_external_manifests( name: str, data: dict[str, dict[str, list[str]]], training_split: Path, seed: int, output_dir: Path, real_ratio: float = 0.1, exclude_insufficient_k900: bool = False, target_real_ratio: float | None = None, ) -> dict[int, Path]: """Balanced joint few-shot manifests: K images per source from BOTH the target benchmark and the WildGen training pool are mixed into the train set; the test set stays target-only so the reported metric is comparable to the zero-shot/cross-benchmark numbers. real_ratio controls the WildGen real anchor (real = real_ratio*K per WildGen source pooled). target_real_ratio, if given, independently controls the target real anchor (real = target_real_ratio*K per target source); this lets the target real distribution be aligned with the WildGen real pool rather than left as a tiny fraction.""" trr = target_real_ratio if target_real_ratio is not None else real_ratio tag = f"_tr{ratio_tag(trr)}" if target_real_ratio is not None and trr != real_ratio else "" paths: dict[int, Path] = {} for k in N_GRID: sources = sorted(data) if exclude_insufficient_k900 and k == 900: sources = [s for s in sources if len(data[s]["fake"]) >= 1000 and len(data[s]["real"]) >= 900] target_train: list[dict[str, Any]] = [] test_rows: list[dict[str, Any]] = [] source_summary: dict[str, dict[str, int]] = {} for source in sources: fake = sorted(data[source]["fake"], key=lambda p: stable_rank(seed, f"{name}:fake:{source}", p)) real = sorted(data[source]["real"], key=lambda p: stable_rank(seed, f"{name}:real:{source}", p)) fake_train_count = min(k, len(fake)) real_train_count = min(int(trr * fake_train_count), len(real)) target_train.extend(manifest_row(p, 1, source, name) for p in fake[:fake_train_count]) target_train.extend(manifest_row(p, 0, f"real:{source}", "real") for p in real[:real_train_count]) test_rows.extend(manifest_row(p, 1, source, name) for p in fake[fake_train_count:]) test_rows.extend(manifest_row(p, 0, f"real:{source}", "real") for p in real[real_train_count:]) source_summary[source] = { "fake_total": len(fake), "real_total": len(real), "fake_train": fake_train_count, "real_train": real_train_count, "fake_test": max(0, len(fake) - fake_train_count), "real_test": max(0, len(real) - real_train_count), } wildgen_rows = load_wildgen_balanced_rows(training_split, k, real_ratio) train_rows = wildgen_rows + target_train path = output_dir / "manifests" / f"{name}_joint{tag}_k{k}_realratio_{ratio_tag(real_ratio)}_seed{seed}.json" write_json( path, { "name": f"{name}_joint", "k_per_source": k, "real_ratio": real_ratio, "target_real_ratio": trr, "init": "warm_start", "wildgen_train_rows": len(wildgen_rows), "target_train_rows": len(target_train), "sources": sources, "source_summary": source_summary, "train": train_rows, "test": test_rows, }, ) paths[k] = path return paths def main() -> None: parser = argparse.ArgumentParser(description="Build the configured zero-shot and joint cross-benchmark manifests.") parser.add_argument("--genimage-root", type=Path, required=True) parser.add_argument("--forensynths-root", type=Path, required=True) parser.add_argument("--training-split", type=Path, required=True) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--seed", type=int, default=42) args = parser.parse_args() summary = {"seed": args.seed, "target_real_ratio": 1.0, "datasets": {}} for name, root, collect in [("genimage", args.genimage_root, collect_genimage), ("forensynths", args.forensynths_root, collect_forensynths)]: data = collect(root) if not data: raise ValueError(f"No benchmark images found under {root}") zero = build_external_manifests(name, data, args.seed, args.output_dir, exclude_insufficient_k900=(name == "forensynths")) joint = build_joint_external_manifests(name, data, args.training_split, args.seed, args.output_dir, exclude_insufficient_k900=(name == "forensynths"), target_real_ratio=1.0) summary["datasets"][name] = {"zero_shot": str(zero[0]), "joint": {str(k): str(v) for k, v in joint.items()}} write_json(args.output_dir / "cross_benchmark_manifest_summary.json", summary) print(json.dumps(summary, indent=2)) if __name__ == "__main__": main()