"""TruthLens: is this image a real photo or AI-generated? Gradio app (Hugging Face Spaces entry point). Run locally with: .venv/bin/python app.py # http://127.0.0.1:7860 Environment variables: PORT / GRADIO_SERVER_PORT port to listen on (default 7860) TRUTHLENS_FORCE_STUB=1 always use the simulated detector (UI development) TRUTHLENS_CONFIG model config in models/ (default config.json; config_fast.json = ViT-B/16, faster) TRUTHLENS_DEVICE torch device for the detector (default cpu locally, cuda on ZeroGPU) SPACES_ZERO_GPU set by Hugging Face ZeroGPU hardware: models go to CUDA at startup and predictions run inside @spaces.GPU (15 s per image, up to 60 s per batch) TRUTHLENS_EXAMPLES_DIR alternative examples folder (default: examples/) TRUTHLENS_METRICS alternative metrics.json (default: reports/metrics.json) """ from __future__ import annotations import csv import json import logging import os import sys import tempfile import threading import time from pathlib import Path ROOT = Path(__file__).resolve().parent sys.path.insert(0, str(ROOT / "src")) import gradio as gr # noqa: E402 import numpy as np # noqa: E402 from truthlens import ui # noqa: E402 from truthlens.stub import StubDetector # noqa: E402 try: # Hugging Face ZeroGPU: `spaces` is preinstalled there; locally it is usually absent import spaces # noqa: E402 GPU = spaces.GPU except ImportError: # no-op stand-in so the same code runs on CPU/MPS def GPU(fn=None, **_kwargs): return fn if callable(fn) else (lambda f: f) # ZeroGPU sets SPACES_ZERO_GPU (read by the `spaces` package itself to enable the GPU decorator). ZERO_GPU = os.environ.get("SPACES_ZERO_GPU", "").lower() in ("1", "t", "true") logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") log = logging.getLogger("truthlens.app") MODELS_DIR = ROOT / "models" CONFIG_NAME = os.environ.get("TRUTHLENS_CONFIG") or "config.json" # e.g. config_fast.json (ViT-B/16, ~2x faster) CONFIG_PATH = MODELS_DIR / CONFIG_NAME # Local default is CPU (matches the evaluated latency); ZeroGPU places the models on CUDA at startup. DEVICE = os.environ.get("TRUTHLENS_DEVICE") or ("cuda" if ZERO_GPU else "cpu") METRICS_PATH = Path(os.environ.get("TRUTHLENS_METRICS") or ROOT / "reports" / "metrics.json") FIGURES_DIR = ROOT / "reports" / "figures" EXAMPLES_DIR = Path(os.environ.get("TRUTHLENS_EXAMPLES_DIR") or ROOT / "examples") ASSETS_DIR = ROOT / "assets" MAX_ANALYZE_SIDE = 4096 # longest side passed to the detector (guards memory on huge uploads) MAX_DISPLAY_SIDE = 1024 # longest side of images sent back to the browser MAX_BATCH = 50 # --------------------------------------------------------------------------- detector def _read_config() -> dict: try: return json.loads(CONFIG_PATH.read_text(encoding="utf-8")) except Exception: return {} def _band(cfg: dict) -> tuple[float, float]: """Uncertainty band for the gauge, read from models/config.json (decision or thresholds).""" for sec in (cfg.get("decision"), cfg.get("thresholds"), cfg): if not isinstance(sec, dict): continue try: lo, hi = float(sec["uncertain_low"]), float(sec["uncertain_high"]) except (KeyError, TypeError, ValueError): continue if 0.0 <= lo <= hi <= 1.0: return lo, hi return ui.DEFAULT_BAND def load_detector(): cfg = _read_config() if os.environ.get("TRUTHLENS_FORCE_STUB") == "1": return StubDetector(), True, "Simulated results (forced by TRUTHLENS_FORCE_STUB).", cfg if CONFIG_PATH.is_file(): try: import torch from truthlens.inference import Detector if DEVICE.startswith("cuda"): # fp32 everywhere for parity with the evaluated pipeline (no TF32 shortcuts on Ampere+ GPUs) torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False if ZERO_GPU: # Outside @spaces.GPU there is no real GPU (CUDA is emulated), so skip the dummy warm-up pass. Detector._warmup = lambda self: None t0 = time.perf_counter() det = Detector(models_dir=str(MODELS_DIR), device=DEVICE, config=CONFIG_NAME) log.info("Loaded Detector (%s, %s) in %.1fs", CONFIG_NAME, det.device, time.perf_counter() - t0) return det, False, "", cfg except Exception: log.exception("Failed to load the real Detector; falling back to the stub") return StubDetector(), True, "The model failed to load, so results are simulated.", cfg log.warning("models/%s not found; using StubDetector (demo mode)", CONFIG_NAME) return StubDetector(), True, "Model weights not found, so results are simulated.", cfg DETECTOR, IS_STUB, DEMO_NOTICE, CONFIG = load_detector() BAND = _band(CONFIG) _LOCK = threading.Lock() def _mode_label() -> str: if IS_STUB: return "demo mode (simulated)" ver = str(getattr(DETECTOR, "version", None) or CONFIG.get("version") or "") label = "TruthLens " + (ver if ver.startswith("v") else f"v{ver}") if ver else "TruthLens" if CONFIG_NAME != "config.json": label += " fast" if "fast" in CONFIG_NAME else f" ({CONFIG_NAME})" dev = str(getattr(DETECTOR, "device", "") or "") return f"{label} on {dev.upper() if dev in ('cpu', 'mps', 'cuda') else dev}" if dev else label MODE = _mode_label() METRICS = ui.read_metrics(METRICS_PATH) or {} GEN_STATS = ui.generator_stats(METRICS) def _unseen_facts(m: dict) -> tuple[int, float | None, list[str]]: """(number of never-seen generators, their miss rate, hardest families) from metrics.json, for UI copy.""" gens = [r for r in m.get("per_generator") or [] if isinstance(r, dict) and r.get("split") == "test_unseen" and str(r.get("label")).lower() in ("ai", "1")] det = ((m.get("splits") or {}).get("test_unseen") or {}).get("detection_rate") hard = sorted((r for r in gens if int(r.get("n", 0)) >= 30), key=lambda r: float(r.get("accuracy", 1)))[:3] return len(gens), (1 - float(det)) if det is not None else None, [ui.pretty_source(r["source"]) for r in hard] N_UNSEEN, UNSEEN_MISS, HARDEST = _unseen_facts(METRICS) EXAMPLES = ui.discover_examples(EXAMPLES_DIR) EXAMPLES_BY_SHA = {e["sha1"]: e for e in EXAMPLES} MAIN_EXAMPLES = [e for e in EXAMPLES if not e["hard"]] HARD_EXAMPLES = [e for e in EXAMPLES if e["hard"]] log.info("Found %d example images (%d hard cases)", len(EXAMPLES), len(HARD_EXAMPLES)) # --------------------------------------------------------------------------- handlers @GPU(duration=15) def _predict_gpu(im): return DETECTOR.predict(im) def _batch_duration(images): return min(60, 10 + len(images)) def _predict_list(images): """Predict each image on its own, so one failure marks that row instead of losing the whole batch.""" out = [] for im in images: try: out.append(DETECTOR.predict(im)) except Exception: log.exception("Batch item failed") out.append(None) return out @GPU(duration=_batch_duration) def _predict_many_gpu(images): return _predict_list(images) def _predict(im): """One prediction. On ZeroGPU this borrows a GPU for up to 15 s; locally it runs under a lock.""" if ZERO_GPU and not IS_STUB: return _predict_gpu(im) with _LOCK: return DETECTOR.predict(im) def _predict_many(images): """Batch predictions in ONE GPU allocation on ZeroGPU (cheaper on the daily quota than one call per image).""" if ZERO_GPU and not IS_STUB: return _predict_many_gpu(images) with _LOCK: return _predict_list(images) def analyze(path: str | None, opacity: float): hidden = gr.update(visible=False) if not path: return ui.empty_card(), None, None, None, hidden try: im = ui.load_image(path, MAX_ANALYZE_SIDE) except Exception as e: log.warning("Unreadable upload: %s", e) return ui.error_card("This file could not be read as an image. Try a JPEG, PNG or WebP."), None, None, None, hidden try: res = _predict(im) except Exception as e: log.exception("Prediction failed") return ui.error_card(f"The detector raised an error ({type(e).__name__})."), None, None, None, hidden try: ex = EXAMPLES_BY_SHA.get(ui.file_sha1(path)) except OSError: ex = None disp = ui.downscale(im, MAX_DISPLAY_SIDE) disp_arr = np.asarray(disp, dtype=np.uint8) heat = res.get("heatmap") heat_disp = ui.resize_map(heat, disp.size) if heat is not None else None box = ui.analysed_box(disp.size) spec_img = ui.spectrum_image(res.get("spectrum")) card = ui.result_card(res, BAND, example=ex, gen_stats=GEN_STATS, image_size=im.size, mode=MODE, heatmap_available=heat is not None) state = {"img": disp_arr, "heat": heat_disp, "box": box} return card, ui.overlay(disp_arr, heat_disp, opacity, box), spec_img, state, gr.update(visible=True) def update_overlay(state, opacity: float): if not state: return gr.update() return ui.overlay(state["img"], state.get("heat"), opacity, state.get("box")) def _picker(items: list[dict]): def pick(evt: gr.SelectData): i = evt.index if isinstance(evt.index, int) else evt.index[0] return items[i]["path"] return pick def run_batch(files, progress=gr.Progress()): if not files: return None, '
', gr.update(visible=False) paths = [f if isinstance(f, str) else getattr(f, "name", str(f)) for f in files][:MAX_BATCH] rows, model_names = [], [] counts = {"AI-generated": 0, "Real": 0, "Uncertain": 0, "Error": 0} loaded = [] # (name, image or None) for p in progress.tqdm(paths, desc="Reading images"): name = Path(p).name try: loaded.append((name, ui.load_image(p, MAX_ANALYZE_SIDE))) except Exception as e: log.warning("Batch item unreadable (%s): %s", name, e) loaded.append((name, None)) progress(0.5, desc=f"Analyzing {sum(im is not None for _, im in loaded)} images") good = [im for _, im in loaded if im is not None] try: results = iter(_predict_many(good)) if good else iter(()) except Exception: log.exception("Batch prediction failed") return None, ui.error_card("The detector raised an error on this batch.").replace("tl-card", "tl-card tl-sm"), \ gr.update(visible=False) for name, im in loaded: if im is None: counts["Error"] += 1 rows.append({"File": name, "Verdict": "Error", "Note": "unreadable file"}) continue res = next(results) if res is None: counts["Error"] += 1 rows.append({"File": name, "Verdict": "Error", "Note": "detector error"}) continue v = str(res.get("verdict", "Uncertain")) counts[v] = counts.get(v, 0) + 1 row = {"File": name, "Verdict": v, "P(AI)": round(float(res["prob_ai"]), 4), "Confidence": "" if v == "Uncertain" else round(float(res.get("confidence", 0.0)), 4)} for m, mp in (res.get("models") or {}).items(): if m not in model_names: model_names.append(m) row[m] = round(float(mp), 4) row["Size"] = f"{im.size[0]}x{im.size[1]}" row["Note"] = "too small to judge" if v == "Uncertain" and min(im.size) < ui.MIN_SIDE else "" row["Latency (ms)"] = round(float(res.get("latency_ms", 0.0)), 1) rows.append(row) headers = ["File", "Verdict", "P(AI)", "Confidence", *model_names, "Size", "Note", "Latency (ms)"] table = [[r.get(h, "") for h in headers] for r in rows] out_dir = Path(tempfile.mkdtemp(prefix="truthlens_")) csv_path = out_dir / "truthlens_results.csv" with open(csv_path, "w", newline="", encoding="utf-8") as f: w = csv.writer(f) w.writerow(headers) # a file name starting with = + - @ would run as a formula in Excel/Sheets, so quote it w.writerows([["'" + c if isinstance(c, str) and c[:1] in ("=", "+", "-", "@") else c for c in r] for r in table]) note = f" (first {MAX_BATCH} of {len(files)})" if len(files) > MAX_BATCH else "" summary = ( f'Is this image a real photo or AI-generated? A calibrated answer, with the evidence.