File size: 17,611 Bytes
e318704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
"""Family #12 Step 1B-1: Build clean commercially permissive AI-Image Forensics training/val sets
and frozen 5-suite Public OOD Evaluation Cache directly via PyArrow Parquet + HF Hub (ZERO datasets YAML bugs!).

Training sources (100% commercially permissive: CC-BY-2.0 / CC-BY-4.0 / Public Domain / Apache-2.0):
  1. Matched 2025-2026 Pairs (Step 1A tar): Commercial COCO-2017 train2017 (license in {4,7,8})
     real photos paired 1:1 with aspect- & caption-matched SANA-Sprint, SANA-1.5, Lumina-2.0, SSD-1B fakes.
  2. Broad Multi-Generator Coverage: finedet/openimages (CC-BY-2.0/4.0) real photos paired with
     OwensLab/CommunityForensics (CC-BY-4.0, Systematic + Manual ONLY, nsfw_flag=False, shuffled across
     all 100+ shards for maximum generator diversity!).

Frozen 5-Suite Public Eval Cache (eval-only, ZERO rows in training):
  - ood_openfake_core       (ComplexDataLab/OpenFake core/test, n=2,000 balanced, STRICT ZERO-TOUCH)
  - ood_openfake_reddit     (ComplexDataLab/OpenFake reddit/test, n<=1,600 balanced, STRICT ZERO-TOUCH)
  - ood_synthbuster         (marco-willi/synthbuster-plus test, n=2,000 balanced, STRICT ZERO-TOUCH)
  - ood_social_recompressed (1,000 OpenFake Core + 1,000 Synthbuster -> Bilinear 512px + JPEG Q45 + WebP Q55)
  - eval_commfor_comp       (OwensLab/CommunityForensics-Eval CompEval, n=2,000 balanced across shuffled shards)

Label convention (exact 1-line drop-in for umm-maybe/AI-image-detector & Organika/sdxl-detector):
  0 = "artificial" (AI-generated / synthetic)
  1 = "human"      (authentic human photograph)
"""

from __future__ import annotations

import argparse
import io
import json
import os
import random
import tarfile
import time
from collections import Counter
from pathlib import Path
from typing import Any, Iterator

import pyarrow.parquet as pq
from huggingface_hub import HfApi, hf_hub_download
from PIL import Image

Image.MAX_IMAGE_PIXELS = None


def _save_rgb_jpg(img: Image.Image, path: Path, quality: int = 95, max_side: int = 1024) -> bool:
    try:
        rgb = img.convert("RGB")
        w, h = rgb.size
        if min(w, h) < 128:
            return False
        if max(w, h) > max_side:
            scale = max_side / max(w, h)
            rgb = rgb.resize((max(128, int(w * scale)), max(128, int(h * scale))), Image.Resampling.LANCZOS)
        path.parent.mkdir(parents=True, exist_ok=True)
        rgb.save(path, format="JPEG", quality=quality)
        return True
    except Exception:
        return False


def _social_recompress(src_path: Path, dst_path: Path) -> bool:
    try:
        im = Image.open(src_path).convert("RGB")
        w, h = im.size
        if max(w, h) > 512:
            sc = 512.0 / max(w, h)
            im = im.resize((max(64, int(w * sc)), max(64, int(h * sc))), Image.Resampling.BILINEAR)
        buf1 = io.BytesIO()
        im.save(buf1, format="JPEG", quality=45)
        buf1.seek(0)
        im2 = Image.open(buf1).convert("RGB")
        buf2 = io.BytesIO()
        im2.save(buf2, format="WEBP", quality=55)
        buf2.seek(0)
        im3 = Image.open(buf2).convert("RGB")
        dst_path.parent.mkdir(parents=True, exist_ok=True)
        im3.save(dst_path, format="JPEG", quality=92)
        return True
    except Exception:
        return False


def _decode_pil(val: Any) -> Image.Image | None:
    if isinstance(val, Image.Image):
        return val
    if isinstance(val, dict) and val.get("bytes"):
        return Image.open(io.BytesIO(val["bytes"]))
    if isinstance(val, (bytes, bytearray)):
        return Image.open(io.BytesIO(val))
    return None


def iter_parquet_shards(
    repo_id: str,
    prefix: str,
    columns: list[str],
    seed: int,
    max_per_shard: int | None = None,
) -> Iterator[dict[str, Any]]:
    """Stream rows directly from shuffled HF Parquet shards with row-group shuffling,
    3-attempt retry, and immediate real-blob cleanup so disk & RAM stay tiny!"""
    api = HfApi()
    shards = sorted(f for f in api.list_repo_files(repo_id, repo_type="dataset") if f.startswith(prefix) and f.endswith(".parquet"))
    rng = random.Random(seed)
    rng.shuffle(shards)
    for sh in shards:
        local_pq = None
        for attempt in range(3):
            try:
                local_pq = hf_hub_download(repo_id=repo_id, filename=sh, repo_type="dataset")
                break
            except Exception as e:
                print(f"  [retry {attempt+1}/3] {repo_id}/{sh}: {e}", flush=True)
                time.sleep(3 * (attempt + 1))
        if not local_pq:
            continue
        blob_path = Path(os.path.realpath(local_pq))
        try:
            pf = pq.ParquetFile(local_pq)
            avail = set(pf.schema_arrow.names)
            use_cols = [c for c in columns if c in avail]
            rgs = list(range(pf.num_row_groups))
            rng.shuffle(rgs)
            yielded = 0
            for rg in rgs:
                tbl = pf.read_row_group(rg, columns=use_cols)
                rows_rg = tbl.to_pylist()
                rng.shuffle(rows_rg)
                for r in rows_rg:
                    yield r
                    yielded += 1
                    if max_per_shard is not None and yielded >= max_per_shard:
                        break
                if max_per_shard is not None and yielded >= max_per_shard:
                    break
        except Exception as e:
            print(f"  [skip shard] {repo_id}/{sh}: {e}", flush=True)
        finally:
            try:
                Path(local_pq).unlink(missing_ok=True)
                blob_path.unlink(missing_ok=True)
            except Exception:
                pass


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--pairs-tar", type=str, default="")
    ap.add_argument("--ood-only", action="store_true", help="Build only the 5 frozen Public OOD evaluation suites (fast!)")
    ap.add_argument("--out-dir", type=str, default="/tmp/img_data")
    ap.add_argument("--n-openimages", type=int, default=10000)
    ap.add_argument("--n-commfor-sys", type=int, default=5500)
    ap.add_argument("--n-commfor-man", type=int, default=4500)
    args = ap.parse_args()

    os.environ["HF_HOME"] = "/tmp/hf"
    t0 = time.time()
    root = Path(args.out_dir)
    root.mkdir(parents=True, exist_ok=True)

    train_rows: list[dict[str, Any]] = []
    val_rows: list[dict[str, Any]] = []
    if not args.ood_only:
        # 1. Extract Step 1A matched 2025-2026 pairs
        pairs_dir = root / "matched_2026"
        pairs_dir.mkdir(parents=True, exist_ok=True)
        print(f"[1/6] Extracting {args.pairs_tar}...", flush=True)
        with tarfile.open(args.pairs_tar, "r") as tf:
            tf.extractall(pairs_dir)
        manifest_rows = [json.loads(l) for l in (pairs_dir / "manifest.jsonl").read_text(encoding="utf-8").splitlines() if l.strip()]
        random.Random(42).shuffle(manifest_rows)

        by_gen: dict[str, list[dict[str, Any]]] = {}
        for r in manifest_rows:
            by_gen.setdefault(r["generator"], []).append(r)

        for gname, grows in sorted(by_gen.items()):
            n_val = min(150, len(grows) // 6)
            for idx, r in enumerate(grows):
                rp = str(pairs_dir / r["real_rel"])
                fp = str(pairs_dir / r["fake_rel"])
                target = val_rows if idx < n_val else train_rows
                target.append({"path": rp, "label": 1, "source": f"coco_matched_{gname}", "weight": 2.5})
                target.append({"path": fp, "label": 0, "source": f"gen2026_{gname}", "weight": 2.5})
        print(f"  matched_2026 -> train={len(train_rows)}, val={len(val_rows)}", flush=True)

        # 2. Stream diverse authentic real photography from finedet/openimages (CC-BY-2.0/4.0)
        print(f"[2/6] Streaming {args.n_openimages} real photos from finedet/openimages (CC-BY)...", flush=True)
        oi_dir = root / "openimages"
        oi_rows: list[dict[str, Any]] = []
        for row in iter_parquet_shards("finedet/openimages", "data/train-", ["image"], seed=42, max_per_shard=400):
            im = _decode_pil(row.get("image"))
            if im is None:
                continue
            p = oi_dir / f"oi_{len(oi_rows):06d}.jpg"
            if _save_rgb_jpg(im, p, quality=95):
                oi_rows.append({"path": str(p), "label": 1, "source": "openimages", "weight": 1.0})
            if len(oi_rows) >= args.n_openimages:
                break
        n_oi_val = min(600, len(oi_rows) // 10)
        val_rows.extend(oi_rows[:n_oi_val])
        train_rows.extend(oi_rows[n_oi_val:])
        print(f"  openimages -> saved={len(oi_rows)} (val={n_oi_val}, train={len(oi_rows)-n_oi_val})", flush=True)

        # 3. Stream broad multi-generator synthetic diversity from OwensLab/CommunityForensics (CC-BY-4.0)
        print(f"[3/6] Streaming OwensLab/CommunityForensics (Systematic={args.n_commfor_sys}, Manual={args.n_commfor_man})...", flush=True)
        cf_dir = root / "commfor_train"
        cf_rows: list[dict[str, Any]] = []
        for sname, pref, quota, mps, sd in [
            ("systematic", "data/systematic/", args.n_commfor_sys, 1850, 51),
            ("manual", "data/manual/", args.n_commfor_man, 1550, 52),
        ]:
            got = 0
            for row in iter_parquet_shards("OwensLab/CommunityForensics", pref, ["image_data", "model_name", "nsfw_flag", "split"], seed=sd, max_per_shard=mps):
                nsfw = row.get("nsfw_flag")
                if nsfw is True or str(nsfw).lower() == "true":
                    continue
                if str(row.get("split", "train")).lower() == "test":
                    continue
                im = _decode_pil(row.get("image_data"))
                if im is None:
                    continue
                mname = str(row.get("model_name", "unknown"))
                p = cf_dir / f"cf_{sname}_{got:06d}.jpg"
                if _save_rgb_jpg(im, p, quality=95):
                    cf_rows.append({"path": str(p), "label": 0, "source": f"commfor_{sname}", "generator": mname, "weight": 1.0})
                    got += 1
                if got >= quota:
                    break
            print(f"  commfor {sname} -> saved={got}", flush=True)

        cf_by_model: dict[str, list[dict[str, Any]]] = {}
        for r in cf_rows:
            cf_by_model.setdefault(r.get("generator", "unk"), []).append(r)
        mkeys = list(cf_by_model.keys())
        random.Random(53).shuffle(mkeys)
        cf_val, cf_tr = [], []
        for mk in mkeys:
            if len(cf_val) < 600:
                cf_val.extend(cf_by_model[mk])
            else:
                cf_tr.extend(cf_by_model[mk])
        val_rows.extend(cf_val[:600])
        train_rows.extend(cf_tr)
        print(f"  commfor -> distinct_models={len(cf_by_model)} | val_unseen_gens={len(cf_val[:600])}, train={len(cf_tr)}", flush=True)

        random.Random(42).shuffle(train_rows)
        random.Random(43).shuffle(val_rows)
        (root / "train.jsonl").write_text("\n".join(json.dumps(r) for r in train_rows) + "\n", encoding="utf-8")
        (root / "val.jsonl").write_text("\n".join(json.dumps(r) for r in val_rows) + "\n", encoding="utf-8")

    # 4. Build Frozen 5-Suite Public Eval Cache (eval-only, ZERO rows in train!)
    ood_root = root / "ood"
    ood_root.mkdir(parents=True, exist_ok=True)
    ood_suites: dict[str, list[dict[str, Any]]] = {}

    print("[4/6] Building ood_openfake_core & ood_openfake_reddit (STRICT ZERO-TOUCH OOD)...", flush=True)
    for sname, pref, n_per, sd in [
        ("ood_openfake_core", "core/test-", 1000, 201),
        ("ood_openfake_reddit", "reddit/test-", 800, 202),
    ]:
        sdir = ood_root / sname
        real_l, fake_l = [], []
        for row in iter_parquet_shards("ComplexDataLab/OpenFake", pref, ["image", "label", "model", "type", "release_date"], seed=sd, max_per_shard=None):
            raw_lbl = str(row.get("label", "")).strip().lower()
            is_real = raw_lbl in ("real", "human", "0") if raw_lbl in ("real", "human") else (raw_lbl != "fake" and raw_lbl != "artificial")
            lbl = 1 if is_real else 0
            if lbl == 1 and len(real_l) >= n_per:
                continue
            if lbl == 0 and len(fake_l) >= n_per:
                continue
            im = _decode_pil(row.get("image"))
            if im is None:
                continue
            idx = len(real_l) if lbl == 1 else len(fake_l)
            p = sdir / f"{'real' if lbl == 1 else 'fake'}_{idx:05d}.jpg"
            if not _save_rgb_jpg(im, p, quality=95):
                continue
            rec = {
                "path": str(p),
                "label": lbl,
                "model": str(row.get("model", "unknown")),
                "media_type": str(row.get("type", "image")),
                "release_date": str(row.get("release_date", "")),
            }
            if lbl == 1:
                real_l.append(rec)
            else:
                fake_l.append(rec)
            if len(real_l) >= n_per and len(fake_l) >= n_per:
                break
        comb = real_l + fake_l
        random.Random(sd).shuffle(comb)
        ood_suites[sname] = comb
        print(f"  {sname}: real={len(real_l)}, fake={len(fake_l)}", flush=True)

    print("[5/6] Building ood_synthbuster & eval_commfor_comp...", flush=True)
    sb_dir = ood_root / "ood_synthbuster"
    sb_real, sb_fake = [], []
    for row in iter_parquet_shards("marco-willi/synthbuster-plus", "data/test-", ["image", "label", "source", "ds_name"], seed=203):
        raw_l = int(row["label"])  # 0=real, 1=fake
        lbl = 1 if raw_l == 0 else 0
        if lbl == 1 and len(sb_real) >= 1000:
            continue
        if lbl == 0 and len(sb_fake) >= 1000:
            continue
        im = _decode_pil(row.get("image"))
        if im is None:
            continue
        idx = len(sb_real) if lbl == 1 else len(sb_fake)
        p = sb_dir / f"{'real' if lbl == 1 else 'fake'}_{idx:05d}.jpg"
        if not _save_rgb_jpg(im, p, quality=95):
            continue
        rec = {"path": str(p), "label": lbl, "model": str(row.get("source") or row.get("ds_name") or "unknown")}
        if lbl == 1:
            sb_real.append(rec)
        else:
            sb_fake.append(rec)
        if len(sb_real) >= 1000 and len(sb_fake) >= 1000:
            break
    sb_all = sb_real + sb_fake
    random.Random(203).shuffle(sb_all)
    ood_suites["ood_synthbuster"] = sb_all
    print(f"  ood_synthbuster: real={len(sb_real)}, fake={len(sb_fake)}", flush=True)

    ce_dir = ood_root / "eval_commfor_comp"
    ce_real, ce_fake = [], []
    for row in iter_parquet_shards("OwensLab/CommunityForensics-Eval", "data/CompEval-", ["image_data", "label", "model_name", "real_source"], seed=205, max_per_shard=60):
        raw_l = int(row["label"])  # 0=real, 1=fake
        lbl = 1 if raw_l == 0 else 0
        if lbl == 1 and len(ce_real) >= 1000:
            continue
        if lbl == 0 and len(ce_fake) >= 1000:
            continue
        im = _decode_pil(row.get("image_data"))
        if im is None:
            continue
        idx = len(ce_real) if lbl == 1 else len(ce_fake)
        p = ce_dir / f"{'real' if lbl == 1 else 'fake'}_{idx:05d}.jpg"
        if not _save_rgb_jpg(im, p, quality=95):
            continue
        rec = {"path": str(p), "label": lbl, "model": str(row.get("model_name", "unknown")), "real_source": str(row.get("real_source", ""))}
        if lbl == 1:
            ce_real.append(rec)
        else:
            ce_fake.append(rec)
        if len(ce_real) >= 1000 and len(ce_fake) >= 1000:
            break
    ce_all = ce_real + ce_fake
    random.Random(205).shuffle(ce_all)
    ood_suites["eval_commfor_comp"] = ce_all
    print(f"  eval_commfor_comp: real={len(ce_real)}, fake={len(ce_fake)}", flush=True)

    print("[6/6] Building ood_social_recompressed (WhatsApp/X/Discord JPEG Q45 + WebP Q55 + 512px Bilinear)...", flush=True)
    sr_dir = ood_root / "ood_social_recompressed"
    sr_rows: list[dict[str, Any]] = []
    for base_name, pool in [("openfake", ood_suites["ood_openfake_core"]), ("synthbuster", ood_suites["ood_synthbuster"])]:
        reals = [r for r in pool if r["label"] == 1][:500]
        fakes = [r for r in pool if r["label"] == 0][:500]
        for j, r in enumerate(reals + fakes):
            dst = sr_dir / f"{base_name}_{'real' if r['label'] == 1 else 'fake'}_{j:04d}.jpg"
            if _social_recompress(Path(r["path"]), dst):
                sr_rows.append({"path": str(dst), "label": r["label"], "model": r.get("model", "unknown"), "origin": base_name})
    random.Random(204).shuffle(sr_rows)
    ood_suites["ood_social_recompressed"] = sr_rows
    print(f"  ood_social_recompressed: n={len(sr_rows)}", flush=True)

    for sname, srows in ood_suites.items():
        (ood_root / f"{sname}.jsonl").write_text("\n".join(json.dumps(r) for r in srows) + "\n", encoding="utf-8")

    summary = {
        "train_n": len(train_rows),
        "train_by_label": dict(Counter(r["label"] for r in train_rows)),
        "train_by_source": dict(Counter(r["source"] for r in train_rows)),
        "val_n": len(val_rows),
        "val_by_label": dict(Counter(r["label"] for r in val_rows)),
        "ood_counts": {k: {"n": len(v), "by_label": dict(Counter(r["label"] for r in v))} for k, v in ood_suites.items()},
        "elapsed_s": round(time.time() - t0, 1),
    }
    (root / "data_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print(f"[DONE] Built Family #12 dataset in {summary['elapsed_s']}s: {json.dumps(summary, indent=2)}", flush=True)


if __name__ == "__main__":
    main()