Spaces:
Sleeping

mdmf-api / server.py
kchromatic3's picture
Update server.py
f2180dd verified
Raw History Blame Contribute Delete
7.31 kB
"""FastAPI backend for MDMF deepfake detection."""
import io, os, base64, tempfile
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, File, UploadFile, HTTPException, Form
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from PIL import Image
from mdmf_inference import MDMFInference
app = FastAPI(title="MDMF Detector API", version="1.3")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["POST", "GET", "OPTIONS"],
allow_headers=["*"],
)
ALLOWED_IMAGE_TYPES = {"image/jpeg", "image/png", "image/webp", "image/gif", "image/bmp"}
MAX_BYTES = 20 * 1024 * 1024
print("[server] Loading MDMF engines. First run downloads DINOv2 (~1 GB)...")
engine_imagenet = MDMFInference(variant="imagenet")
engine_sdv14 = MDMFInference(variant="sdv14")
print("[server] Both engines ready.")
VARIANT_SPREAD = {
"imagenet": 1.0,
"sdv14": 0.6,
}
def score_to_percent(score, threshold, variant="imagenet"):
"""Display transform β€” not a calibrated probability."""
import math
spread = VARIANT_SPREAD.get(variant, 1.0)
z = (score - threshold) / spread
z = max(min(z, 50.0), -50.0)
pct = 100.0 / (1.0 + math.exp(-z))
if score > threshold and pct < 70.0:
pct = 70.0 + (pct - 50.0) * 0.6
elif score < threshold and pct > 30.0:
pct = 30.0 - (50.0 - pct) * 0.6
return pct
def encode_png_to_data_url(path):
with open(path, "rb") as f:
b64 = base64.b64encode(f.read()).decode("ascii")
return f"data:image/png;base64,{b64}"
def apply_sensitivity_offset(default_threshold: float, sensitivity: float) -> float:
"""
Map a 0-1 sensitivity value to a threshold offset.
sensitivity = 0.0 β†’ strict (only flag obvious fakes) β†’ threshold + 2.0
sensitivity = 0.5 β†’ calibrated default β†’ threshold + 0.0
sensitivity = 1.0 β†’ lenient (catch borderline cases) β†’ threshold - 2.0
The Β±2.0 range is chosen to span roughly one "spread" unit on each side of
the calibrated operating point β€” enough to meaningfully change verdicts on
near-threshold images without making the slider trivially flip everything.
"""
sens = max(0.0, min(1.0, sensitivity))
offset = (0.5 - sens) * 4.0
return default_threshold + offset
@app.get("/")
def root():
return {
"service": "MDMF Detector API",
"variants": ["imagenet", "sdv14", "both"],
"endpoint": "POST /detect (multipart form, fields: file, sensitivity?, mode?)",
"version": "1.3",
}
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/detect")
async def detect(
file: UploadFile = File(...),
sensitivity: Optional[float] = Form(None), # NEW: 0.0 (strict) β†’ 1.0 (lenient)
mode: Optional[str] = Form("both"), # NEW: "imagenet", "sdv14", or "both"
):
if file.content_type not in ALLOWED_IMAGE_TYPES:
raise HTTPException(status_code=400, detail=f"Unsupported file type: {file.content_type}.")
data = await file.read()
if len(data) > MAX_BYTES:
raise HTTPException(status_code=400, detail=f"File too large ({len(data)/1e6:.1f} MB). Max 20 MB.")
try:
Image.open(io.BytesIO(data)).verify()
except Exception:
raise HTTPException(status_code=400, detail="Could not decode image.")
# NEW: validate mode
mode = (mode or "both").lower()
if mode not in {"imagenet", "sdv14", "both"}:
raise HTTPException(status_code=400, detail=f"Invalid mode '{mode}'. Use 'imagenet', 'sdv14', or 'both'.")
# NEW: compute effective thresholds from sensitivity
if sensitivity is not None:
thr_img = apply_sensitivity_offset(engine_imagenet.threshold, sensitivity)
thr_sd = apply_sensitivity_offset(engine_sdv14.threshold, sensitivity)
else:
thr_img = engine_imagenet.threshold
thr_sd = engine_sdv14.threshold
with tempfile.TemporaryDirectory() as tmp:
img_path = os.path.join(tmp, file.filename or "upload.png")
with open(img_path, "wb") as f:
f.write(data)
# NEW: only run the engines requested by mode
r_img = None
r_sd = None
if mode in ("imagenet", "both"):
r_img = engine_imagenet.predict(img_path, output_dir=os.path.join(tmp, "out_imagenet"))
# Re-apply label using the (possibly user-adjusted) threshold
r_img["label"] = "fake" if r_img["score"] > thr_img else "real"
r_img["threshold"] = thr_img
if mode in ("sdv14", "both"):
r_sd = engine_sdv14.predict(img_path, output_dir=os.path.join(tmp, "out_sdv14"))
r_sd["label"] = "fake" if r_sd["score"] > thr_sd else "real"
r_sd["threshold"] = thr_sd
# Encode overlays only for variants that ran
overlay_img = encode_png_to_data_url(r_img["outputs"]["mil_overlay_grid"]) if r_img else None
overlay_sd = encode_png_to_data_url(r_sd["outputs"]["mil_overlay_grid"]) if r_sd else None
# Build per-variant blocks
variants_block = {}
if r_img is not None:
pct_img = score_to_percent(r_img["score"], thr_img, "imagenet")
variants_block["imagenet"] = {
"label": r_img["label"],
"score": round(r_img["score"], 4),
"threshold": round(thr_img, 4),
"default_threshold": round(engine_imagenet.threshold, 4), # NEW: for UI display
"score_percent": round(pct_img, 2),
"distance_from_threshold": round(r_img["score"] - thr_img, 4), # NEW: for visualization
"overlay_image": overlay_img,
}
if r_sd is not None:
pct_sd = score_to_percent(r_sd["score"], thr_sd, "sdv14")
variants_block["sdv14"] = {
"label": r_sd["label"],
"score": round(r_sd["score"], 4),
"threshold": round(thr_sd, 4),
"default_threshold": round(engine_sdv14.threshold, 4),
"score_percent": round(pct_sd, 2),
"distance_from_threshold": round(r_sd["score"] - thr_sd, 4),
"overlay_image": overlay_sd,
}
# Consensus logic β€” adapted to handle single-variant mode
if mode == "both":
agreement = r_img["label"] == r_sd["label"]
if agreement:
consensus = r_img["label"]
consensus_percent = round(
(variants_block["imagenet"]["score_percent"]
+ variants_block["sdv14"]["score_percent"]) / 2.0, 2)
else:
consensus = "unsure"
consensus_percent = None
elif mode == "imagenet":
agreement = True
consensus = r_img["label"]
consensus_percent = variants_block["imagenet"]["score_percent"]
else: # sdv14
agreement = True
consensus = r_sd["label"]
consensus_percent = variants_block["sdv14"]["score_percent"]
return JSONResponse({
"filename": file.filename,
"media_type": "image",
"mode": mode,
"sensitivity": sensitivity,
"consensus_label": consensus,
"agreement": agreement,
"score_percent": consensus_percent,
"label": consensus,
"variants": variants_block,
})