Download route/efficientnetb3_detector.py from Manar55/truscan: direct link, hf CLI and curl.
- Browser
- Download file 3.69 kB
-
https://huggingface.co/spaces/Manar55/truscan/resolve/main/route/efficientnetb3_detector.py
- Command line
-
hf download hf://spaces/Manar55/truscan/route/efficientnetb3_detector.py
-
curl -L -o efficientnetb3_detector.py https://huggingface.co/spaces/Manar55/truscan/resolve/main/route/efficientnetb3_detector.py
3.69 kB
| """ | |
| Fourth trained model — EfficientNet-B3 (torchvision architecture), | |
| fine-tuned specifically for deepfake/fake-image detection on a 399k-image | |
| dataset ("DeepFakeFusion V2"). Unlike the other checkpoints found during | |
| this project, this one ships with FULL embedded metadata (architecture | |
| name, exact input size, label mapping, and a validated decision | |
| threshold), so nothing here is guessed — it's read directly from the | |
| checkpoint. | |
| Reported test-set performance (from the checkpoint's own metadata): | |
| accuracy=93.7%, ROC-AUC=0.988, F1=0.938 | |
| This is currently the strongest single model in the pipeline. Weight file | |
| (best_efficientnet_b3_deepfake_detector_399k.pth, ~43MB) is NOT downloaded | |
| automatically — it has to be placed locally. See efficientnetb3_model/README.txt. | |
| Fails gracefully: if torch or the weight file aren't available, | |
| classify_image() returns None and the app keeps working without this | |
| category. | |
| """ | |
| import os | |
| import threading | |
| MODEL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "models") | |
| MODEL_PATH = os.path.join(MODEL_DIR, "best_efficientnet_b3_deepfake_detector_399k.pth") | |
| _model = None | |
| _transform = None | |
| _load_error = None | |
| _lock = threading.Lock() | |
| _meta = {} # populated from the checkpoint itself once loaded | |
| def _load(): | |
| global _model, _transform, _load_error, _meta | |
| if _model is not None or _load_error is not None: | |
| return | |
| with _lock: | |
| if _model is not None or _load_error is not None: | |
| return | |
| if not os.path.exists(MODEL_PATH): | |
| _load_error = f"Model file not found at {MODEL_PATH}" | |
| return | |
| try: | |
| import torch | |
| import torchvision | |
| from torchvision import transforms | |
| ckpt = torch.load(MODEL_PATH, map_location="cpu", weights_only=False) | |
| _meta = { | |
| "image_size": ckpt.get("image_size", 256), | |
| "label_map": ckpt.get("label_map", {"real": 0, "fake": 1}), | |
| "threshold": ckpt.get("threshold", 0.5), | |
| "test_metrics": ckpt.get("final_test_metrics", {}), | |
| } | |
| net = torchvision.models.efficientnet_b3(weights=None) | |
| # Checkpoint's classifier head outputs a single logit (binary, | |
| # via sigmoid) rather than torchvision's default 1000-class head. | |
| import torch.nn as nn | |
| net.classifier[1] = nn.Linear(net.classifier[1].in_features, 1) | |
| net.load_state_dict(ckpt["state_dict"]) | |
| net.eval() | |
| _model = net | |
| size = _meta["image_size"] | |
| _transform = transforms.Compose([ | |
| transforms.Resize((size, size)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), | |
| ]) | |
| except Exception as e: | |
| _load_error = str(e) | |
| def is_available(): | |
| _load() | |
| return _model is not None | |
| def get_load_error(): | |
| _load() | |
| return _load_error | |
| def get_reported_accuracy(): | |
| """The checkpoint's own held-out test-set accuracy, if available.""" | |
| _load() | |
| return _meta.get("test_metrics", {}).get("accuracy") | |
| def classify_image(pil_image): | |
| """ | |
| Returns a float 0-100 = probability the image is fake, or None if the | |
| model isn't available. | |
| """ | |
| _load() | |
| if _model is None: | |
| return None | |
| try: | |
| import torch | |
| tensor = _transform(pil_image.convert("RGB")).unsqueeze(0) | |
| with torch.no_grad(): | |
| logit = _model(tensor) | |
| prob_fake = torch.sigmoid(logit).item() | |
| return prob_fake * 100 | |
| except Exception: | |
| return None | |