File size: 2,051 Bytes
435e715
 
 
 
 
bdbd54d
435e715
bdbd54d
435e715
 
 
 
 
bdbd54d
 
435e715
 
bdbd54d
435e715
 
 
 
bdbd54d
 
 
435e715
 
bdbd54d
435e715
 
 
 
bdbd54d
435e715
 
 
bdbd54d
435e715
 
 
 
bdbd54d
 
 
 
 
 
 
 
435e715
 
 
 
 
 
bdbd54d
435e715
 
bdbd54d
435e715
bdbd54d
435e715
 
 
 
 
 
 
 
 
 
 
bdbd54d
 
 
 
435e715
 
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
import gradio as gr
from transformers import AutoModelForImageClassification, ViTImageProcessor
from PIL import Image
import torch

# -------------------------------
# Load model once (global)
# -------------------------------
model_id = "jacoballessio/ai-image-detect-distilled"

processor = ViTImageProcessor.from_pretrained(model_id)
model = AutoModelForImageClassification.from_pretrained(
    model_id,
    dtype=torch.float32,
    low_cpu_mem_usage=True
)

model.eval()
device = "cpu"
model.to(device)


# -------------------------------
# Prediction function
# -------------------------------
def predict(image: Image.Image):
    if image is None:
        return "Please upload an image", None

    # Preprocess
    inputs = processor(image, return_tensors="pt").to(device)

    # Inference
    with torch.no_grad():
        outputs = model(**inputs)

    # Probabilities
    probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
    confidence = probs.max().item()
    predicted_label = model.config.id2label[probs.argmax().item()]

    # Convert to dict for Gradio Label
    labels = model.config.id2label
    scores = probs.squeeze().tolist()

    confidence_dict = {
        labels[i]: float(scores[i]) for i in range(len(scores))
    }

    # Result text
    if predicted_label.lower() == "fake":
        result = f"⚠️ AI-GENERATED\nConfidence: {confidence:.3f}"
    else:
        result = f"✅ REAL IMAGE\nConfidence: {confidence:.3f}"

    return result, confidence_dict


# -------------------------------
# UI
# -------------------------------
app = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil", label="Upload Image"),
    outputs=[
        gr.Textbox(label="Prediction"),
        gr.Label(label="Confidence Scores")
    ],
    title="🖼️ AI vs Real Image Detector",
    description="Upload an image to check if it's AI-generated or real."
)


# -------------------------------
# Run app
# -------------------------------
if __name__ == "__main__":
    app.launch(server_name="0.0.0.0", server_port=7860)