Spaces:
Running
Running
Commit ·
1de5ee4
1
Parent(s): 6063991
feat: add replaceable image detector
Browse files- app/services/image_detector.py +116 -0
app/services/image_detector.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import time
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
from app.config import settings
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ImageDetector:
|
| 17 |
+
def __init__(self) -> None:
|
| 18 |
+
self.device = torch.device("cpu")
|
| 19 |
+
self.model: torch.nn.Module | None = None
|
| 20 |
+
self.preprocess: Any | None = None
|
| 21 |
+
self.model_name = "efficientnet_b0_binary"
|
| 22 |
+
self.model_status = "not_loaded"
|
| 23 |
+
self.warning: str | None = None
|
| 24 |
+
|
| 25 |
+
@property
|
| 26 |
+
def is_loaded(self) -> bool:
|
| 27 |
+
return self.model is not None
|
| 28 |
+
|
| 29 |
+
def load(self) -> None:
|
| 30 |
+
if self.model is not None:
|
| 31 |
+
return
|
| 32 |
+
try:
|
| 33 |
+
from torchvision import models, transforms
|
| 34 |
+
|
| 35 |
+
model = models.efficientnet_b0(weights=None)
|
| 36 |
+
in_features = model.classifier[1].in_features
|
| 37 |
+
model.classifier[1] = torch.nn.Linear(in_features, 2)
|
| 38 |
+
self.preprocess = transforms.Compose(
|
| 39 |
+
[
|
| 40 |
+
transforms.Resize((224, 224)),
|
| 41 |
+
transforms.ToTensor(),
|
| 42 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 43 |
+
]
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if settings.model_path.exists():
|
| 47 |
+
state = torch.load(settings.model_path, map_location=self.device)
|
| 48 |
+
if isinstance(state, dict) and "state_dict" in state:
|
| 49 |
+
state = state["state_dict"]
|
| 50 |
+
model.load_state_dict(state, strict=False)
|
| 51 |
+
self.model_status = "loaded"
|
| 52 |
+
self.warning = None
|
| 53 |
+
else:
|
| 54 |
+
self.model_status = "untrained_placeholder"
|
| 55 |
+
self.warning = (
|
| 56 |
+
"No fine-tuned weights found at models/image_detector.pth. "
|
| 57 |
+
"Model probabilities are from an unfine-tuned binary head and should not be treated as reliable."
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
model.eval()
|
| 61 |
+
self.model = model.to(self.device)
|
| 62 |
+
except Exception as exc:
|
| 63 |
+
logger.exception("Image detector failed to load")
|
| 64 |
+
self.model_status = "failed"
|
| 65 |
+
self.warning = str(exc)
|
| 66 |
+
|
| 67 |
+
def predict(self, image: Image.Image) -> dict[str, Any]:
|
| 68 |
+
start = time.perf_counter()
|
| 69 |
+
if self.model is None or self.preprocess is None:
|
| 70 |
+
return {
|
| 71 |
+
"model_name": self.model_name,
|
| 72 |
+
"model_status": self.model_status,
|
| 73 |
+
"predicted_label": "unknown",
|
| 74 |
+
"real_probability": None,
|
| 75 |
+
"ai_generated_probability": None,
|
| 76 |
+
"inference_time_ms": 0,
|
| 77 |
+
"warning": self.warning or "Model is not available.",
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
try:
|
| 81 |
+
tensor = self.preprocess(image).unsqueeze(0).to(self.device)
|
| 82 |
+
with torch.no_grad():
|
| 83 |
+
logits = self.model(tensor)
|
| 84 |
+
probs = torch.softmax(logits, dim=1).squeeze(0).cpu().tolist()
|
| 85 |
+
real_prob = float(probs[0])
|
| 86 |
+
ai_prob = float(probs[1])
|
| 87 |
+
return {
|
| 88 |
+
"model_name": self.model_name,
|
| 89 |
+
"model_status": self.model_status,
|
| 90 |
+
"predicted_label": "likely_ai_generated" if ai_prob >= real_prob else "likely_authentic",
|
| 91 |
+
"real_probability": round(real_prob, 4),
|
| 92 |
+
"ai_generated_probability": round(ai_prob, 4),
|
| 93 |
+
"inference_time_ms": round((time.perf_counter() - start) * 1000, 2),
|
| 94 |
+
"warning": self.warning,
|
| 95 |
+
}
|
| 96 |
+
except Exception as exc:
|
| 97 |
+
return {
|
| 98 |
+
"model_name": self.model_name,
|
| 99 |
+
"model_status": "failed",
|
| 100 |
+
"predicted_label": "unknown",
|
| 101 |
+
"real_probability": None,
|
| 102 |
+
"ai_generated_probability": None,
|
| 103 |
+
"inference_time_ms": round((time.perf_counter() - start) * 1000, 2),
|
| 104 |
+
"error": str(exc),
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
def target_layer(self) -> torch.nn.Module | None:
|
| 108 |
+
if self.model is None:
|
| 109 |
+
return None
|
| 110 |
+
try:
|
| 111 |
+
return self.model.features[-1]
|
| 112 |
+
except Exception:
|
| 113 |
+
return None
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
image_detector = ImageDetector()
|