Spaces:
Sleeping

File size: 7,313 Bytes
60fc1c3
b076de9
60fc1c3
b076de9
f2180dd
 
b076de9
 
 
 
 
f2180dd
b076de9
 
 
 
 
 
 
 
60fc1c3
 
b076de9
 
 
 
 
 
 
60fc1c3
88d01de
 
60fc1c3
 
 
 
f2180dd
b076de9
88d01de
60fc1c3
 
88d01de
 
6932cab
88d01de
6932cab
88d01de
b076de9
6932cab
60fc1c3
b076de9
 
 
 
 
f2180dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b076de9
 
 
 
f2180dd
 
 
b076de9
 
 
 
 
 
 
 
 
f2180dd
 
 
 
 
b076de9
60fc1c3
b076de9
 
 
60fc1c3
b076de9
 
60fc1c3
b076de9
 
 
f2180dd
 
 
 
 
 
 
 
 
 
 
 
 
b076de9
 
 
 
 
f2180dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b076de9
f2180dd
 
 
 
 
b076de9
60fc1c3
 
 
f2180dd
 
60fc1c3
 
f2180dd
60fc1c3
f2180dd
60fc1c3
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
"""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,
    })