Image Classification
Transformers
ONNX
Safetensors
Transformers.js
convnextv2
ai-image-detection
deepfake-detection
image-forensics
agent-forensics
ai-image-detector
ai-detector
synthetic-image-detection
Instructions to use Tamarillo/ai-image-forensics-guard-small with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Tamarillo/ai-image-forensics-guard-small with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-classification", model="Tamarillo/ai-image-forensics-guard-small") pipe("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/parrots.png")# pip install -U transformers accelerate # Load model directly from transformers import AutoImageProcessor, AutoModelForImageClassification processor = AutoImageProcessor.from_pretrained("Tamarillo/ai-image-forensics-guard-small") model = AutoModelForImageClassification.from_pretrained("Tamarillo/ai-image-forensics-guard-small", device_map="auto") - Transformers.js
How to use Tamarillo/ai-image-forensics-guard-small with Transformers.js:
// npm i @huggingface/transformers import { pipeline } from '@huggingface/transformers'; // Allocate pipeline const pipe = await pipeline('image-classification', 'Tamarillo/ai-image-forensics-guard-small'); - Notebooks
- Google Colab
- Kaggle
Release Tamarillo/ai-image-forensics-guard-small (Apache-2.0, Stage-2 PASS audited)
4359b6c verified Download scripts/eval_image_suite.py from Tamarillo/ai-image-forensics-guard-small: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/Tamarillo/ai-image-forensics-guard-small/resolve/main/scripts/eval_image_suite.py
- Command line
-
hf download hf://Tamarillo/ai-image-forensics-guard-small/scripts/eval_image_suite.py
-
curl -L -o eval_image_suite.py https://huggingface.co/Tamarillo/ai-image-forensics-guard-small/resolve/main/scripts/eval_image_suite.py
12.5 kB
| """Family #12 Step 1B-3: Head-to-head 5-Suite Public OOD Benchmark evaluating Tamarillo tiers | |
| against ALL 6 top Hugging Face AI-image forensics incumbents on identical frozen images: | |
| - umm-maybe/AI-image-detector (65.2K dl/mo, 86M Swin-Base, NO ONNX) | |
| - buildborderless/CommunityForensics-DeepfakeDet-ViT (23.6K dl/mo, 21.8M ViT-Small 384px, timm) | |
| - Ateeqq/ai-vs-human-image-detector (12.1K dl/mo, 92.9M SigLIP, NO ONNX) | |
| - Organika/sdxl-detector (8.6K dl/mo, 86.8M Swin-Base, CC-BY-NC-3.0) | |
| - haywoodsloan/ai-image-detector-deploy (5.0K dl/mo, 195.2M SwinV2, NO ONNX) | |
| - abacusai/Smaug-AI-Image-Detector (5.7K dl/mo, 438.8M, NO ONNX) | |
| - Plus Tamarillo FP32 & full-suite INT8 ONNX verification! | |
| Reports per-suite EER, ROC-AUC, Balanced Acc @0.50, Fake Recall @0.50, Real-Photo FPR @0.50, | |
| TPR@5%FPR, 4-Suite Strict Zero-Touch OOD Mean, 5-Suite Public Mean, and per-generator OpenFake breakdown. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import gc | |
| import json | |
| import os | |
| import time | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import onnxruntime as ort | |
| import torch | |
| from huggingface_hub import hf_hub_download | |
| from PIL import Image | |
| from sklearn.metrics import roc_auc_score, roc_curve | |
| from transformers import AutoImageProcessor, AutoModelForImageClassification | |
| Image.MAX_IMAGE_PIXELS = None | |
| SUITES_4Z = ["ood_openfake_core", "ood_openfake_reddit", "ood_synthbuster", "ood_social_recompressed"] | |
| SUITES_ALL5 = SUITES_4Z + ["eval_commfor_comp"] | |
| def compute_metrics(y_art: np.ndarray, p_art: np.ndarray, rows: list[dict[str, Any]]) -> dict[str, Any]: | |
| fpr, tpr, _ = roc_curve(y_art, p_art) | |
| fnr = 1.0 - tpr | |
| idx = int(np.nanargmin(np.abs(fnr - fpr))) | |
| eer = float(0.5 * (fpr[idx] + fnr[idx])) | |
| auc = float(roc_auc_score(y_art, p_art)) | |
| t5 = float(tpr[np.where(fpr <= 0.05)[0][-1]]) if np.any(fpr <= 0.05) else 0.0 | |
| t1 = float(tpr[np.where(fpr <= 0.01)[0][-1]]) if np.any(fpr <= 0.01) else 0.0 | |
| pred_art = (p_art >= 0.50).astype(np.int32) | |
| fake_mask = y_art == 1 | |
| real_mask = y_art == 0 | |
| fake_rec = float(pred_art[fake_mask].mean()) if fake_mask.any() else 0.0 | |
| real_fpr = float(pred_art[real_mask].mean()) if real_mask.any() else 0.0 | |
| bal_acc = 0.5 * (fake_rec + (1.0 - real_fpr)) | |
| out: dict[str, Any] = { | |
| "n": int(len(y_art)), | |
| "eer": round(eer, 5), | |
| "roc_auc": round(auc, 5), | |
| "tpr_at_5fpr": round(t5, 5), | |
| "tpr_at_1fpr": round(t1, 5), | |
| "bal_acc_050": round(bal_acc, 5), | |
| "fake_rec_050": round(fake_rec, 5), | |
| "real_fpr_050": round(real_fpr, 5), | |
| } | |
| # Per-generator fake recall / mean P(artificial) breakdown when model metadata exists | |
| by_mod: dict[str, list[float]] = defaultdict(list) | |
| for r, p, ya in zip(rows, p_art, y_art): | |
| if ya == 1: | |
| by_mod[str(r.get("model", "unknown"))].append(float(p)) | |
| if len(by_mod) >= 2: | |
| real_scores = p_art[real_mask] | |
| gen_stats = {} | |
| for gm, scores in sorted(by_mod.items(), key=lambda x: -len(x[1]))[:15]: | |
| if len(scores) < 10: | |
| continue | |
| arr = np.asarray(scores, dtype=np.float32) | |
| # Compute per-generator AUC against all real photos in this suite | |
| y_comb = np.concatenate([np.zeros(len(real_scores)), np.ones(len(arr))]) | |
| s_comb = np.concatenate([real_scores, arr]) | |
| gen_stats[gm] = { | |
| "n": len(scores), | |
| "auc": round(float(roc_auc_score(y_comb, s_comb)), 4), | |
| "rec_050": round(float((arr >= 0.50).mean()), 4), | |
| "mean_p": round(float(arr.mean()), 4), | |
| } | |
| out["by_generator"] = gen_stats | |
| return out | |
| def _detect_artificial_index(id2label: dict[Any, str]) -> int: | |
| for k, v in id2label.items(): | |
| vl = str(v).strip().lower() | |
| if any(tok in vl for tok in ("artificial", "fake", "ai", "synthetic", "generated", "deepfake", "spoof")): | |
| return int(k) | |
| return 0 | |
| def score_hf_classifier(model_id_or_dir: str, paths: list[str], device: torch.device, bs: int = 32) -> tuple[np.ndarray, float]: | |
| proc = AutoImageProcessor.from_pretrained(model_id_or_dir) | |
| model = AutoModelForImageClassification.from_pretrained(model_id_or_dir).to(device).eval() | |
| params_m = sum(p.numel() for p in model.parameters()) / 1e6 | |
| art_idx = _detect_artificial_index(model.config.id2label) | |
| print(f" [hf] {model_id_or_dir}: {params_m:.2f}M | id2label={model.config.id2label} -> art_idx={art_idx}", flush=True) | |
| scores = [] | |
| with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16): | |
| for i in range(0, len(paths), bs): | |
| ims = [Image.open(p).convert("RGB") for p in paths[i : i + bs]] | |
| enc = proc(images=ims, return_tensors="pt").to(device) | |
| logits = model(**enc).logits.float() | |
| if logits.shape[-1] == 1: | |
| p = torch.sigmoid(logits[:, 0]).cpu().numpy() | |
| else: | |
| p = torch.softmax(logits, dim=-1)[:, art_idx].cpu().numpy() | |
| scores.append(p) | |
| del model | |
| gc.collect() | |
| torch.cuda.empty_cache() | |
| return np.concatenate(scores, axis=0), params_m | |
| def score_commfor_vit(paths: list[str], bs: int = 32) -> tuple[np.ndarray, float]: | |
| """Score buildborderless/CommunityForensics-DeepfakeDet-ViT via its official ONNX artifact & official CLIP processor.""" | |
| repo = "buildborderless/CommunityForensics-DeepfakeDet-ViT" | |
| proc = AutoImageProcessor.from_pretrained(repo) | |
| onnx_path = hf_hub_download(repo_id=repo, filename="onnx/model.onnx") | |
| opts = ort.SessionOptions() | |
| opts.intra_op_num_threads = 8 | |
| sess = ort.InferenceSession(onnx_path, sess_options=opts, providers=["CPUExecutionProvider"]) | |
| in_name = sess.get_inputs()[0].name | |
| print(f" [commfor-onnx] {repo}: input={in_name} {sess.get_inputs()[0].shape} proc={type(proc).__name__}", flush=True) | |
| scores = [] | |
| for i in range(0, len(paths), bs): | |
| ims = [Image.open(p).convert("RGB") for p in paths[i : i + bs]] | |
| x = proc(images=ims, return_tensors="np")["pixel_values"].astype(np.float32) | |
| out = sess.run(None, {in_name: x})[0] | |
| if out.ndim == 2 and out.shape[-1] == 1: | |
| p = 1.0 / (1.0 + np.exp(-out[:, 0])) | |
| elif out.ndim == 1: | |
| p = 1.0 / (1.0 + np.exp(-out)) | |
| else: | |
| ex = np.exp(out - out.max(axis=-1, keepdims=True)) | |
| # CommunityForensics convention: label 1 = Fake, 0 = Real | |
| p = (ex / ex.sum(axis=-1, keepdims=True))[:, 1] | |
| scores.append(p.astype(np.float32)) | |
| return np.concatenate(scores, axis=0), 21.81 | |
| def score_tamarillo_onnx(model_dir: Path, onnx_file: str, paths: list[str], bs: int = 32) -> np.ndarray: | |
| """Full-suite ONNX evaluation (proves INT8 preserves actual OOD ROC-AUC/EER!).""" | |
| proc = AutoImageProcessor.from_pretrained(str(model_dir)) | |
| opts = ort.SessionOptions() | |
| opts.intra_op_num_threads = 8 | |
| sess = ort.InferenceSession(str(model_dir / "onnx" / onnx_file), sess_options=opts, providers=["CPUExecutionProvider"]) | |
| in_name = sess.get_inputs()[0].name | |
| sz = 224 | |
| if hasattr(proc, "size") and isinstance(proc.size, dict): | |
| sz = int(proc.size.get("height", proc.size.get("shortest_edge", 224))) | |
| scores = [] | |
| for i in range(0, len(paths), bs): | |
| ims = [Image.open(p).convert("RGB") for p in paths[i : i + bs]] | |
| x = proc(images=ims, return_tensors="np")["pixel_values"].astype(np.float32) | |
| logits = sess.run(None, {in_name: x})[0] | |
| ex = np.exp(logits - logits.max(axis=-1, keepdims=True)) | |
| p_art = (ex / ex.sum(axis=-1, keepdims=True))[:, 0] | |
| scores.append(p_art.astype(np.float32)) | |
| return np.concatenate(scores, axis=0) | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--ood-dir", type=str, required=True) | |
| ap.add_argument("--models", type=str, nargs="+", required=True, help="key=path_or_hf_id pairs") | |
| ap.add_argument("--int8-check-dirs", type=str, nargs="*", default=[], help="key=model_dir pairs for full-suite INT8 OOD eval") | |
| ap.add_argument("--out-json", type=str, required=True) | |
| args = ap.parse_args() | |
| os.environ["HF_HOME"] = "/tmp/hf" | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| ood_dir = Path(args.ood_dir) | |
| suites: dict[str, tuple[list[str], np.ndarray, list[dict[str, Any]]]] = {} | |
| for sn in SUITES_ALL5: | |
| jp = ood_dir / f"{sn}.jsonl" | |
| if not jp.exists(): | |
| continue | |
| rows = [json.loads(l) for l in jp.read_text(encoding="utf-8").splitlines() if l.strip()] | |
| paths = [r["path"] for r in rows] | |
| y_art = np.array([1 if int(r["label"]) == 0 else 0 for r in rows], dtype=np.int32) | |
| suites[sn] = (paths, y_art, rows) | |
| print(f"[eval] Loaded {sn}: n={len(rows)} (art={int(y_art.sum())}, hum={int((1-y_art).sum())})", flush=True) | |
| results: dict[str, Any] = {"suites_4z": SUITES_4Z, "suites_all5": SUITES_ALL5, "models": {}} | |
| for spec in args.models: | |
| key, mpath = spec.split("=", 1) | |
| print(f"\n=== Evaluating {key} ({mpath}) ===", flush=True) | |
| t0 = time.time() | |
| try: | |
| suite_res = {} | |
| params_m = 0.0 | |
| for sn, (paths, y_art, rows) in suites.items(): | |
| if "CommunityForensics-DeepfakeDet-ViT" in mpath: | |
| p_art, params_m = score_commfor_vit(paths, bs=32) | |
| else: | |
| p_art, params_m = score_hf_classifier(mpath, paths, device, bs=32) | |
| # Sanity check polarity ONLY for CommunityForensics if needed? No — never flip dynamically; | |
| # log exact raw score! | |
| suite_res[sn] = compute_metrics(y_art, p_art, rows) | |
| print( | |
| f" {sn:24s} | EER={suite_res[sn]['eer']*100:5.2f}% | AUC={suite_res[sn]['roc_auc']:.4f} | " | |
| f"Rec@0.5={suite_res[sn]['fake_rec_050']*100:5.1f}% | RealFPR@0.5={suite_res[sn]['real_fpr_050']*100:4.1f}%", | |
| flush=True, | |
| ) | |
| z4_eer = float(np.mean([suite_res[s]["eer"] for s in SUITES_4Z if s in suite_res])) | |
| z4_auc = float(np.mean([suite_res[s]["roc_auc"] for s in SUITES_4Z if s in suite_res])) | |
| m5_eer = float(np.mean([suite_res[s]["eer"] for s in SUITES_ALL5 if s in suite_res])) | |
| m5_auc = float(np.mean([suite_res[s]["roc_auc"] for s in SUITES_ALL5 if s in suite_res])) | |
| results["models"][key] = { | |
| "repo_or_path": mpath, | |
| "params_m": round(params_m, 2), | |
| "z4_mean_eer": round(z4_eer, 5), | |
| "z4_mean_auc": round(z4_auc, 5), | |
| "all5_mean_eer": round(m5_eer, 5), | |
| "all5_mean_auc": round(m5_auc, 5), | |
| "suites": suite_res, | |
| "elapsed_s": round(time.time() - t0, 1), | |
| } | |
| print(f" ==> {key}: 4Z Mean EER={z4_eer*100:.2f}% AUC={z4_auc:.4f} | 5-Suite EER={m5_eer*100:.2f}% AUC={m5_auc:.4f}", flush=True) | |
| except Exception as e: | |
| print(f" [ERROR] {key} failed: {e}", flush=True) | |
| results["models"][key] = {"repo_or_path": mpath, "error": str(e)} | |
| # Full-suite INT8 OOD evaluation on ood_openfake_core & ood_social_recompressed | |
| int8_eval = {} | |
| for spec in args.int8_check_dirs: | |
| key, mdir_s = spec.split("=", 1) | |
| mdir = Path(mdir_s) | |
| q8_p = mdir / "onnx" / "model_quantized.onnx" | |
| if not q8_p.exists(): | |
| continue | |
| print(f"\n=== Full-Suite INT8 ONNX Eval: {key} ===", flush=True) | |
| sub = {} | |
| for sn in ("ood_openfake_core", "ood_social_recompressed"): | |
| if sn not in suites: | |
| continue | |
| paths, y_art, rows = suites[sn] | |
| p_art = score_tamarillo_onnx(mdir, "model_quantized.onnx", paths, bs=32) | |
| sub[sn] = compute_metrics(y_art, p_art, rows) | |
| print(f" INT8 {sn:24s} | EER={sub[sn]['eer']*100:5.2f}% | AUC={sub[sn]['roc_auc']:.4f}", flush=True) | |
| int8_eval[key] = sub | |
| results["int8_full_ood_eval"] = int8_eval | |
| Path(args.out_json).write_text(json.dumps(results, indent=2), encoding="utf-8") | |
| print(f"\n[DONE] Saved full benchmark -> {args.out_json}", flush=True) | |
| if __name__ == "__main__": | |
| main() | |