Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,9 +6,10 @@ import numpy as np
|
|
| 6 |
import cv2
|
| 7 |
from PIL import Image
|
| 8 |
import requests
|
| 9 |
-
from torchvision import transforms
|
| 10 |
import io
|
| 11 |
import os
|
|
|
|
|
|
|
| 12 |
|
| 13 |
# ββ Model Definition ββββββββββββββββββββββββββββββββββββββββ
|
| 14 |
class CIFAKECNN(nn.Module):
|
|
@@ -32,12 +33,15 @@ class CIFAKECNN(nn.Module):
|
|
| 32 |
x = torch.sigmoid(self.fc2(x))
|
| 33 |
return x
|
| 34 |
|
| 35 |
-
# ββ Load
|
| 36 |
device = torch.device('cpu')
|
| 37 |
model = CIFAKECNN().to(device)
|
| 38 |
model.load_state_dict(torch.load('cnn_model.pth', map_location=device))
|
| 39 |
model.eval()
|
| 40 |
|
|
|
|
|
|
|
|
|
|
| 41 |
# ββ Transform ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 42 |
transform = transforms.Compose([
|
| 43 |
transforms.Resize((32, 32)),
|
|
@@ -88,61 +92,74 @@ def get_gradcam_overlay(image_pil, image_tensor):
|
|
| 88 |
# ββ Detection Function βββββββββββββββββββββββββββββββββββββββ
|
| 89 |
def detect_image(image):
|
| 90 |
if image is None:
|
| 91 |
-
return "Please upload an image.", None
|
| 92 |
image_pil = Image.fromarray(image).convert('RGB')
|
| 93 |
image_tensor = transform(image_pil)
|
|
|
|
|
|
|
| 94 |
with torch.no_grad():
|
| 95 |
output = model(image_tensor.unsqueeze(0))
|
| 96 |
confidence = output.item()
|
| 97 |
label = "FAKE (AI-Generated)" if confidence > 0.5 else "REAL"
|
| 98 |
confidence_pct = confidence if confidence > 0.5 else 1 - confidence
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
gradcam_img = get_gradcam_overlay(image_pil, image_tensor)
|
| 101 |
-
return
|
| 102 |
|
| 103 |
# ββ Generate & Detect Function βββββββββββββββββββββββββββββββ
|
| 104 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 105 |
|
| 106 |
def generate_and_detect(prompt):
|
| 107 |
if not prompt:
|
| 108 |
-
return None, "Please enter a prompt.", None
|
| 109 |
response = requests.post(
|
| 110 |
"https://router.huggingface.co/hf-inference/models/black-forest-labs/FLUX.1-schnell",
|
| 111 |
headers={"Authorization": f"Bearer {HF_TOKEN}"},
|
| 112 |
json={"inputs": prompt}
|
| 113 |
)
|
| 114 |
if response.status_code != 200:
|
| 115 |
-
return None, f"Generation failed: {response.text}", None
|
| 116 |
image_pil = Image.open(io.BytesIO(response.content)).convert('RGB')
|
| 117 |
-
|
| 118 |
-
return image_pil,
|
| 119 |
|
| 120 |
# ββ Gradio Interface βββββββββββββββββββββββββββββββββββββββββ
|
| 121 |
with gr.Blocks(title="AI Image Detector") as demo:
|
| 122 |
gr.Markdown("# π Truth in the Noise: AI Image Detector")
|
| 123 |
-
gr.Markdown("Detect whether an image is real or AI-generated
|
| 124 |
|
| 125 |
with gr.Tabs():
|
| 126 |
with gr.Tab("π€ Upload & Detect"):
|
| 127 |
-
gr.Markdown("Upload any image to
|
| 128 |
with gr.Row():
|
| 129 |
upload_input = gr.Image(label="Upload Image")
|
| 130 |
with gr.Column():
|
| 131 |
-
|
| 132 |
-
|
|
|
|
| 133 |
upload_btn = gr.Button("Detect", variant="primary")
|
| 134 |
-
upload_btn.click(detect_image, inputs=upload_input,
|
|
|
|
| 135 |
|
| 136 |
with gr.Tab("π¨ Generate & Detect"):
|
| 137 |
-
gr.Markdown("
|
| 138 |
prompt_input = gr.Textbox(label="Prompt", placeholder="e.g. a cat sitting on a chair")
|
| 139 |
generate_btn = gr.Button("Generate & Detect", variant="primary")
|
| 140 |
with gr.Row():
|
| 141 |
generated_img = gr.Image(label="Generated Image")
|
| 142 |
with gr.Column():
|
| 143 |
-
|
| 144 |
-
|
|
|
|
| 145 |
generate_btn.click(generate_and_detect, inputs=prompt_input,
|
| 146 |
-
outputs=[generated_img,
|
| 147 |
|
| 148 |
demo.launch()
|
|
|
|
| 6 |
import cv2
|
| 7 |
from PIL import Image
|
| 8 |
import requests
|
|
|
|
| 9 |
import io
|
| 10 |
import os
|
| 11 |
+
from torchvision import transforms
|
| 12 |
+
from transformers import pipeline
|
| 13 |
|
| 14 |
# ββ Model Definition ββββββββββββββββββββββββββββββββββββββββ
|
| 15 |
class CIFAKECNN(nn.Module):
|
|
|
|
| 33 |
x = torch.sigmoid(self.fc2(x))
|
| 34 |
return x
|
| 35 |
|
| 36 |
+
# ββ Load our CNN βββββββββββββββββββββββββββββββββββββββββββββ
|
| 37 |
device = torch.device('cpu')
|
| 38 |
model = CIFAKECNN().to(device)
|
| 39 |
model.load_state_dict(torch.load('cnn_model.pth', map_location=device))
|
| 40 |
model.eval()
|
| 41 |
|
| 42 |
+
# ββ Load pretrained detector βββββββββββββββββββββββββββββββββ
|
| 43 |
+
pretrained_detector = pipeline("image-classification", model="Organika/sdxl-detector")
|
| 44 |
+
|
| 45 |
# ββ Transform ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 46 |
transform = transforms.Compose([
|
| 47 |
transforms.Resize((32, 32)),
|
|
|
|
| 92 |
# ββ Detection Function βββββββββββββββββββββββββββββββββββββββ
|
| 93 |
def detect_image(image):
|
| 94 |
if image is None:
|
| 95 |
+
return "Please upload an image.", "Please upload an image.", None
|
| 96 |
image_pil = Image.fromarray(image).convert('RGB')
|
| 97 |
image_tensor = transform(image_pil)
|
| 98 |
+
|
| 99 |
+
# Our CNN
|
| 100 |
with torch.no_grad():
|
| 101 |
output = model(image_tensor.unsqueeze(0))
|
| 102 |
confidence = output.item()
|
| 103 |
label = "FAKE (AI-Generated)" if confidence > 0.5 else "REAL"
|
| 104 |
confidence_pct = confidence if confidence > 0.5 else 1 - confidence
|
| 105 |
+
our_result = f"**{label}**\nConfidence: {confidence_pct:.1%}"
|
| 106 |
+
|
| 107 |
+
# Pretrained detector
|
| 108 |
+
pretrained_result = pretrained_detector(image_pil)
|
| 109 |
+
top = pretrained_result[0]
|
| 110 |
+
pretrained_label = top['label']
|
| 111 |
+
pretrained_conf = top['score']
|
| 112 |
+
pretrained_out = f"**{pretrained_label}**\nConfidence: {pretrained_conf:.1%}"
|
| 113 |
+
|
| 114 |
gradcam_img = get_gradcam_overlay(image_pil, image_tensor)
|
| 115 |
+
return our_result, pretrained_out, gradcam_img
|
| 116 |
|
| 117 |
# ββ Generate & Detect Function βββββββββββββββββββββββββββββββ
|
| 118 |
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 119 |
|
| 120 |
def generate_and_detect(prompt):
|
| 121 |
if not prompt:
|
| 122 |
+
return None, "Please enter a prompt.", "Please enter a prompt.", None
|
| 123 |
response = requests.post(
|
| 124 |
"https://router.huggingface.co/hf-inference/models/black-forest-labs/FLUX.1-schnell",
|
| 125 |
headers={"Authorization": f"Bearer {HF_TOKEN}"},
|
| 126 |
json={"inputs": prompt}
|
| 127 |
)
|
| 128 |
if response.status_code != 200:
|
| 129 |
+
return None, f"Generation failed: {response.text}", "", None
|
| 130 |
image_pil = Image.open(io.BytesIO(response.content)).convert('RGB')
|
| 131 |
+
our_result, pretrained_out, gradcam_img = detect_image(np.array(image_pil))
|
| 132 |
+
return image_pil, our_result, pretrained_out, gradcam_img
|
| 133 |
|
| 134 |
# ββ Gradio Interface βββββββββββββββββββββββββββββββββββββββββ
|
| 135 |
with gr.Blocks(title="AI Image Detector") as demo:
|
| 136 |
gr.Markdown("# π Truth in the Noise: AI Image Detector")
|
| 137 |
+
gr.Markdown("Detect whether an image is real or AI-generated. We compare our custom CNN (trained on CIFAKE) with a pretrained detector.")
|
| 138 |
|
| 139 |
with gr.Tabs():
|
| 140 |
with gr.Tab("π€ Upload & Detect"):
|
| 141 |
+
gr.Markdown("Upload any image to compare both models.")
|
| 142 |
with gr.Row():
|
| 143 |
upload_input = gr.Image(label="Upload Image")
|
| 144 |
with gr.Column():
|
| 145 |
+
upload_our = gr.Markdown(label="Our CNN (CIFAKE)")
|
| 146 |
+
upload_pretrained = gr.Markdown(label="Pretrained Detector")
|
| 147 |
+
upload_gradcam = gr.Image(label="GradCAM (Our CNN)")
|
| 148 |
upload_btn = gr.Button("Detect", variant="primary")
|
| 149 |
+
upload_btn.click(detect_image, inputs=upload_input,
|
| 150 |
+
outputs=[upload_our, upload_pretrained, upload_gradcam])
|
| 151 |
|
| 152 |
with gr.Tab("π¨ Generate & Detect"):
|
| 153 |
+
gr.Markdown("Generate an AI image and detect it with both models.")
|
| 154 |
prompt_input = gr.Textbox(label="Prompt", placeholder="e.g. a cat sitting on a chair")
|
| 155 |
generate_btn = gr.Button("Generate & Detect", variant="primary")
|
| 156 |
with gr.Row():
|
| 157 |
generated_img = gr.Image(label="Generated Image")
|
| 158 |
with gr.Column():
|
| 159 |
+
generate_our = gr.Markdown(label="Our CNN (CIFAKE)")
|
| 160 |
+
generate_pretrained = gr.Markdown(label="Pretrained Detector")
|
| 161 |
+
generate_gradcam = gr.Image(label="GradCAM (Our CNN)")
|
| 162 |
generate_btn.click(generate_and_detect, inputs=prompt_input,
|
| 163 |
+
outputs=[generated_img, generate_our, generate_pretrained, generate_gradcam])
|
| 164 |
|
| 165 |
demo.launch()
|