Run this model with HF Jobs

Run Tamarillo/ai-image-forensics-guard-tiny on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/Tamarillo/ai-image-forensics-guard-tiny. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/Tamarillo/ai-image-forensics-guard-tiny on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
File size: 12,565 Bytes
656e994
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Family #12 v2 Pre-Cache (runs on cheap CPU node in parallel with A100 synthesis!):
Streams strictly commercial real photography (`finedet/openimages` CC-BY-2.0/4.0, n=12,000),
diverse multi-generator synthetic images (`OwensLab/CommunityForensics` CC-BY-4.0, n=12,000),
and builds the EXACT 5 frozen Public OOD evaluation suites (`ood_openfake_core`, `ood_openfake_reddit`,
`ood_synthbuster`, `ood_social_recompressed`, `eval_commfor_comp`) with v1's exact seeds,
then archives them to `$OUTPUT_DIR/img_base_cache_v2.tar` so A100 training/eval jobs spend ZERO GPU time streaming!
"""

from __future__ import annotations

import argparse
import gc
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 build_image_data import _decode_pil, _save_rgb_jpg, _social_recompress


def iter_parquet_shards_lowmem(
    repo_id: str,
    prefix: str,
    columns: list[str],
    seed: int,
    max_per_shard: int | None = None,
) -> Iterator[dict[str, Any]]:
    """Low-RAM streaming parquet iterator (batch_size=32, <500MB peak RAM even on huge image shards!)."""
    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:
                for batch in pf.iter_batches(batch_size=32, row_groups=[rg], columns=use_cols):
                    rows_b = batch.to_pylist()
                    rng.shuffle(rows_b)
                    for r in rows_b:
                        yield r
                        yielded += 1
                        if max_per_shard is not None and yielded >= max_per_shard:
                            break
                    del rows_b, batch
                    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:
            gc.collect()
            try:
                Path(local_pq).unlink(missing_ok=True)
                blob_path.unlink(missing_ok=True)
            except Exception:
                pass


iter_parquet_shards = iter_parquet_shards_lowmem


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--work-dir", type=str, default="/tmp/img_cache_work")
    ap.add_argument("--out-tar", type=str, required=True)
    ap.add_argument("--n-openimages", type=int, default=12000)
    ap.add_argument("--n-commfor-sys", type=int, default=6500)
    ap.add_argument("--n-commfor-man", type=int, default=5500)
    args = ap.parse_args()

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

    train_rows: list[dict[str, Any]] = []
    val_rows: list[dict[str, Any]] = []

    print(f"[1/4] 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=450):
        im = _decode_pil(row.get("image"))
        if im is None:
            continue
        rel = f"openimages/oi_{len(oi_rows):06d}.jpg"
        if _save_rgb_jpg(im, root / rel, quality=95):
            oi_rows.append({"rel": rel, "label": 1, "source": "openimages", "weight": 1.0})
        if len(oi_rows) >= args.n_openimages:
            break
    n_oi_val = min(700, 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)

    print(f"[2/4] Streaming OwensLab/CommunityForensics (Sys={args.n_commfor_sys}, Man={args.n_commfor_man})...", flush=True)
    cf_rows: list[dict[str, Any]] = []
    for sname, pref, quota, mps, sd in [
        ("systematic", "data/systematic/", args.n_commfor_sys, 2000, 51),
        ("manual", "data/manual/", args.n_commfor_man, 1750, 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"))
            rel = f"commfor_train/cf_{sname}_{got:06d}.jpg"
            if _save_rgb_jpg(im, root / rel, quality=95):
                cf_rows.append({"rel": rel, "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) < 700:
            cf_val.extend(cf_by_model[mk])
        else:
            cf_tr.extend(cf_by_model[mk])
    val_rows.extend(cf_val[:700])
    train_rows.extend(cf_tr)
    print(f"  commfor -> distinct_models={len(cf_by_model)} | val_unseen_gens={len(cf_val[:700])}, train={len(cf_tr)}", flush=True)

    (root / "base_train.jsonl").write_text("\n".join(json.dumps(r) for r in train_rows) + "\n", encoding="utf-8")
    (root / "base_val.jsonl").write_text("\n".join(json.dumps(r) for r in val_rows) + "\n", encoding="utf-8")

    # 3. Frozen 5-Suite Public OOD Eval Cache (exact same seeds & quotas as v1!)
    ood_root = root / "ood"
    ood_root.mkdir(parents=True, exist_ok=True)
    ood_suites: dict[str, list[dict[str, Any]]] = {}

    print("[3/4] Building frozen ood_openfake_core, ood_openfake_reddit, ood_synthbuster, eval_commfor_comp...", flush=True)
    for sname, pref, n_per, sd in [
        ("ood_openfake_core", "core/test-", 1000, 201),
        ("ood_openfake_reddit", "reddit/test-", 800, 202),
    ]:
        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)
            rel = f"ood/{sname}/{'real' if lbl == 1 else 'fake'}_{idx:05d}.jpg"
            if not _save_rgb_jpg(im, root / rel, quality=95):
                continue
            rec = {"rel": rel, "label": lbl, "model": str(row.get("model", "unknown")), "media_type": str(row.get("type", "image"))}
            (real_l if lbl == 1 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)

    sb_real, sb_fake = [], []
    for row in iter_parquet_shards("marco-willi/synthbuster-plus", "data/test-", ["image", "label", "source", "ds_name"], seed=203):
        lbl = 1 if int(row["label"]) == 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)
        rel = f"ood/ood_synthbuster/{'real' if lbl == 1 else 'fake'}_{idx:05d}.jpg"
        if not _save_rgb_jpg(im, root / rel, quality=95):
            continue
        rec = {"rel": rel, "label": lbl, "model": str(row.get("source") or row.get("ds_name") or "unknown")}
        (sb_real if lbl == 1 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_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):
        lbl = 1 if int(row["label"]) == 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)
        rel = f"ood/eval_commfor_comp/{'real' if lbl == 1 else 'fake'}_{idx:05d}.jpg"
        if not _save_rgb_jpg(im, root / rel, quality=95):
            continue
        rec = {"rel": rel, "label": lbl, "model": str(row.get("model_name", "unknown"))}
        (ce_real if lbl == 1 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("[4/4] Building ood_social_recompressed & archiving to tar...", flush=True)
    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):
            rel = f"ood/ood_social_recompressed/{base_name}_{'real' if r['label'] == 1 else 'fake'}_{j:04d}.jpg"
            if _social_recompress(root / r["rel"], root / rel):
                sr_rows.append({"rel": rel, "label": r["label"], "model": r.get("model", "unknown"), "origin": base_name})
    random.Random(204).shuffle(sr_rows)
    ood_suites["ood_social_recompressed"] = sr_rows

    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")

    out_tar = Path(args.out_tar)
    out_tar.parent.mkdir(parents=True, exist_ok=True)
    with tarfile.open(out_tar, "w") as tf:
        tf.add(root, arcname=".")
    summary = {
        "base_train_n": len(train_rows),
        "base_val_n": len(val_rows),
        "ood_counts": {k: len(v) for k, v in ood_suites.items()},
        "tar_mb": round(out_tar.stat().st_size / 1e6, 2),
        "elapsed_min": round((time.time() - t0) / 60.0, 2),
    }
    (out_tar.parent / "base_cache_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print(f"[DONE] Base cache complete: {json.dumps(summary, indent=2)}", flush=True)


if __name__ == "__main__":
    main()