-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
49 lines (40 loc) · 1.38 KB
/
Copy pathapp.py
File metadata and controls
49 lines (40 loc) · 1.38 KB
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
import torch
import gradio as gr
from PIL import Image
import torchvision.transforms as T
from models.encoder import ResNetEncoder
from models.metaoptnet_svm import MetaOptNetSVM
from build_support_set import build_support_set
# Device setup to use CPU
device = torch.device("cpu")
# Load model
encoder = ResNetEncoder()
encoder.load_state_dict(torch.load("models/encoder_ep8.pth", map_location=device))
encoder = encoder.to(device)
encoder.eval()
classifier = MetaOptNetSVM()
# Build support set once at startup
support_x, support_y = build_support_set("data", num_per_class=5)
support_x, support_y = support_x.to(device), support_y.to(device)
# Preprocessing function
transform = T.Compose([
T.Resize((224, 224)),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
def predict(image: Image.Image) -> str:
query_x = transform(image.convert("RGB")).unsqueeze(0).to(device)
support_features = encoder(support_x)
query_features = encoder(query_x)
preds = classifier(support_features, support_y, query_features)
label = preds.argmax(dim=1).item()
return "Fake" if label == 1 else "Real"
# Launch Gradio app
gr.Interface(
fn=predict,
inputs=gr.Image(type="pil"),
outputs="text",
title="Deepfake Image Detector",
description="Upload an image to classify it as Real or Fake using meta-learning."
).launch()