programmingghost commited on
Commit
435e715
·
verified ·
1 Parent(s): b9c72b5
Files changed (1) hide show
  1. app.py +57 -0
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoModelForImageClassification, ViTImageProcessor
3
+ from PIL import Image
4
+ import torch
5
+
6
+ # Load model once (global)
7
+ model_id = "jacoballessio/ai-image-detect-distilled"
8
+
9
+ processor = ViTImageProcessor.from_pretrained(model_id)
10
+ model = AutoModelForImageClassification.from_pretrained(
11
+ model_id,
12
+ torch_dtype=torch.float32
13
+ )
14
+ model.eval()
15
+
16
+ device = "cpu"
17
+ model.to(device)
18
+
19
+
20
+ def predict(image: Image.Image):
21
+ if image is None:
22
+ return "Please upload an image", ""
23
+
24
+ # Preprocess
25
+ inputs = processor(image, return_tensors="pt").to(device)
26
+
27
+ with torch.no_grad():
28
+ outputs = model(**inputs)
29
+
30
+ # Softmax
31
+ probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
32
+ confidence = probs.max().item()
33
+ predicted_label = model.config.id2label[probs.argmax().item()]
34
+
35
+ # Result text
36
+ if predicted_label.lower() == "fake":
37
+ result = f"⚠️ AI-GENERATED\nConfidence: {confidence:.3f}"
38
+ else:
39
+ result = f"✅ REAL IMAGE\nConfidence: {confidence:.3f}"
40
+
41
+ return result, probs.squeeze().tolist()
42
+
43
+
44
+ # UI
45
+ app = gr.Interface(
46
+ fn=predict,
47
+ inputs=gr.Image(type="pil", label="Upload Image"),
48
+ outputs=[
49
+ gr.Textbox(label="Prediction"),
50
+ gr.Label(label="Confidence Scores")
51
+ ],
52
+ title="🖼️ AI vs Real Image Detector",
53
+ description="Upload an image to check if it's AI-generated or real."
54
+ )
55
+
56
+ if __name__ == "__main__":
57
+ app.launch(server_name="0.0.0.0", server_port=7860)