Spaces:
Sleeping
Sleeping
Update server.py
Browse files7 unmodified lines89101112131411 unmodified lines262728293031323334353637383940415 unmodified lines47484950515253545556575859606162636465666768697071727374757642 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521537 unmodified linesfrom PIL import Imagefrom mdmf_inference import MDMFInferenceapp = FastAPI(title="MDMF Detector API", version="1.1")app.add_middleware(CORSMiddleware,allow_origins=["*"],11 unmodified linesprint("[server] Both engines ready.")# Per-variant "score spread" β roughly the distance past the threshold at# which the display should saturate near the extremes. Chosen from the paper's# reported score distributions (imagenet has a wider spread than sdv14).## At |score - threshold| == spread, display β 73%# At |score - threshold| == 2*spread, display β 88%# At |score - threshold| == 3*spread, display β 95%# Per-variant "score spread" β smaller = more extreme display.# With spread=1.0, even a score 2 units past the threshold maps to ~88%.# With spread=0.5, 1 unit past β ~88%, 2 units past β ~98%.VARIANT_SPREAD = {"imagenet": 1.0,"sdv14": 0.6,5 unmodified linesMap raw MDMF score to 0β100% AI-likelihood display with an aggressive slope.Any score meaningfully past the threshold saturates quickly. Near-thresholdscores are pulled slightly away from 50% too (via the min-margin nudge)so the display rarely sits exactly in the "uncertain" middle.Note: this is a *display transform*, not a calibrated probability."""import mathspread = VARIANT_SPREAD.get(variant, 1.0)# Base logisticz = (score - threshold) / spread# Nudge: if score is on one side of threshold, push the output at least# 20 percentage points away from 50%. Makes borderline cases still look# decisive while keeping the sign correct.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 # compress into 70β82% rangeelif score < threshold and pct > 30.0:pct = 30.0 - (50.0 - pct) * 0.6 # compress into 18β30% rangereturn pctdef encode_png_to_data_url(path):with open(path, "rb") as f:b64 = base64.b64encode(f.read()).decode("ascii")42 unmodified linespct_img = score_to_percent(r_img["score"], r_img["threshold"], variant="imagenet")pct_sd = score_to_percent(r_sd["score"], r_sd["threshold"], variant="sdv14")# Confidence-weighted consensus: each variant's "vote" is weighted by how# far its percentage is from the 50% uncertain midpoint. A variant# screaming 95% dominates a variant shrugging at 52%.## We raise the distance to a power > 1 so the weighting is nonlinear β# high-confidence predictions dominate far more than their linear share.conf_img = abs(pct_img - 50.0) ** 2conf_sd = abs(pct_sd - 50.0) ** 2total_conf = conf_img + conf_sdif total_conf < 1e-6:# Both variants perfectly on the fence β fall back to simple averageavg_pct = (pct_img + pct_sd) / 2.0else:avg_pct = (pct_img * conf_img + pct_sd * conf_sd) / total_confagreement = r_img["label"] == r_sd["label"]if agreement:consensus = r_img["label"]else:# When variants disagree, side with whichever is more extremeconsensus = r_img["label"] if conf_img > conf_sd else r_sd["label"]return JSONResponse({"filename": file.filename,"media_type": "image","consensus_label": consensus,"agreement": agreement,"score_percent": round(avg_pct, 2),"label": consensus,"variants": {"imagenet": {7 unmodified lines89101112131411 unmodified lines262728293031325 unmodified lines383940414243444546474849505152535455565758596061626342 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281297 unmodified linesfrom PIL import Imagefrom mdmf_inference import MDMFInferenceapp = FastAPI(title="MDMF Detector API", version="1.2")app.add_middleware(CORSMiddleware,allow_origins=["*"],11 unmodified linesprint("[server] Both engines ready.")# Per-variant "score spread" β smaller = more extreme display.VARIANT_SPREAD = {"imagenet": 1.0,"sdv14": 0.6,5 unmodified linesMap raw MDMF score to 0β100% AI-likelihood display with an aggressive slope.Any score meaningfully past the threshold saturates quickly. Near-thresholdscores are pulled slightly away from 50% via the min-margin nudge so thedisplay rarely sits exactly in the "uncertain" middle.Note: this is a *display transform*, not a calibrated probability."""import mathspread = VARIANT_SPREAD.get(variant, 1.0)z = (score - threshold) / spreadz = 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.6elif score < threshold and pct > 30.0:pct = 30.0 - (50.0 - pct) * 0.6return pctdef encode_png_to_data_url(path):with open(path, "rb") as f:b64 = base64.b64encode(f.read()).decode("ascii")42 unmodified linespct_img = score_to_percent(r_img["score"], r_img["threshold"], variant="imagenet")pct_sd = score_to_percent(r_sd["score"], r_sd["threshold"], variant="sdv14")agreement = r_img["label"] == r_sd["label"]# Consensus rules:# - if variants agree: consensus = that label, score = avg of both pcts# - if variants disagree: consensus = "unsure", score_percent = Noneif agreement:consensus = r_img["label"]consensus_percent = round((pct_img + pct_sd) / 2.0, 2)else:consensus = "unsure"consensus_percent = Nonereturn JSONResponse({"filename": file.filename,"media_type": "image","consensus_label": consensus,"agreement": agreement,"score_percent": consensus_percent, # null when variants disagree"label": consensus,"variants": {"imagenet": {
server.py+14-38