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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# coding: utf-8
|
| 3 |
+
|
| 4 |
+
# In[1]:
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
from google.colab import drive
|
| 8 |
+
drive.mount('/content/drive')
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# In[2]:
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
get_ipython().system('git clone https://github.com/NVlabs/stylegan2-ada-pytorch.git')
|
| 15 |
+
get_ipython().system('cd stylegan2-ada-pytorch')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# In[3]:
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
import sys
|
| 22 |
+
sys.path.append('/content/stylegan2-ada-pytorch')
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import pickle
|
| 26 |
+
import dnnlib
|
| 27 |
+
|
| 28 |
+
# Set device
|
| 29 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 30 |
+
|
| 31 |
+
# Load the model
|
| 32 |
+
pkl_path = "/content/drive/MyDrive/GP_Files_Dona/Experiementation/stylegan2-ffhq-512x512.pkl"
|
| 33 |
+
|
| 34 |
+
with open(pkl_path, "rb") as f:
|
| 35 |
+
data = pickle.load(f)
|
| 36 |
+
|
| 37 |
+
G = data['G_ema'].to(device) # Generator
|
| 38 |
+
D = data['D'].to(device) # Discriminator
|
| 39 |
+
|
| 40 |
+
# Set discriminator to evaluation mode
|
| 41 |
+
D.eval()
|
| 42 |
+
|
| 43 |
+
print("StyleGAN2 Discriminator loaded successfully on", device)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# In[4]:
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
import torch
|
| 50 |
+
import torch.nn as nn
|
| 51 |
+
import numpy as np
|
| 52 |
+
import torchvision.transforms as transforms
|
| 53 |
+
from timm import create_model
|
| 54 |
+
import cv2
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# In[5]:
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class_names = ["real", "fake"]
|
| 61 |
+
model = create_model('swin_large_patch4_window12_384', pretrained=False, num_classes=len(class_names))
|
| 62 |
+
model.load_state_dict(torch.load("/content/drive/MyDrive/GP_Files_Yara/swin_large_patch4_window12_384_RGB/best_model_final (1).pth", map_location=device))
|
| 63 |
+
model = model.to(device)
|
| 64 |
+
model.eval()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# In[6]:
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def compute_gradients(model, pil_image):
|
| 71 |
+
transform = transforms.Compose([
|
| 72 |
+
transforms.Resize((512, 512)),
|
| 73 |
+
transforms.ToTensor(),
|
| 74 |
+
transforms.Normalize([0.5], [0.5])
|
| 75 |
+
])
|
| 76 |
+
image = transform(pil_image.convert("RGB")).unsqueeze(0).to(device).requires_grad_(True)
|
| 77 |
+
|
| 78 |
+
c = torch.zeros([image.shape[0], model.c_dim], device=device) if model.c_dim > 0 else None
|
| 79 |
+
output = model(image, c)
|
| 80 |
+
|
| 81 |
+
loss = -output.mean()
|
| 82 |
+
loss.backward()
|
| 83 |
+
|
| 84 |
+
gradients = image.grad.detach().cpu().numpy()
|
| 85 |
+
gradients = np.abs(gradients).mean(axis=1)[0]
|
| 86 |
+
gradients = (gradients - gradients.min()) / (gradients.max() - gradients.min() + 1e-8)
|
| 87 |
+
gradients = (gradients * 255).astype(np.uint8)
|
| 88 |
+
|
| 89 |
+
# JET colormap
|
| 90 |
+
grad_color = cv2.applyColorMap(gradients, cv2.COLORMAP_JET)
|
| 91 |
+
grad_rgb = cv2.cvtColor(grad_color, cv2.COLOR_BGR2RGB)
|
| 92 |
+
|
| 93 |
+
return Image.fromarray(grad_rgb)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# In[7]:
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def swin_classifier(pil_image):
|
| 100 |
+
transform = transforms.Compose([
|
| 101 |
+
transforms.Resize((384, 384)),
|
| 102 |
+
transforms.ToTensor(),
|
| 103 |
+
transforms.Normalize([0.485, 0.456, 0.406],
|
| 104 |
+
[0.229, 0.224, 0.225])
|
| 105 |
+
])
|
| 106 |
+
image = transform(pil_image).unsqueeze(0).to(device)
|
| 107 |
+
|
| 108 |
+
with torch.no_grad():
|
| 109 |
+
output = model(image)
|
| 110 |
+
probabilities = torch.softmax(output, dim=1).squeeze().cpu().numpy()
|
| 111 |
+
return { "Real": float(probabilities[0]), "Fake": float(probabilities[1]) }
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# In[8]:
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def process_image(pil_img):
|
| 118 |
+
grad_pil = compute_gradients(D, pil_img).resize((384, 384))
|
| 119 |
+
prediction = swin_classifier(grad_pil)
|
| 120 |
+
return grad_pil, prediction
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# In[9]:
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
get_ipython().system('pip install gradio')
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
# In[10]:
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
import gradio as gr
|
| 133 |
+
from PIL import Image
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# In[ ]:
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="purple", secondary_hue="pink")) as demo:
|
| 140 |
+
gr.Markdown("**💜 Mukhbir**", elem_id= "logo")
|
| 141 |
+
gr.Markdown("# AI Generated Images Detection", elem_id="title")
|
| 142 |
+
gr.Markdown("Upload an image to detect whether it is real or fake.", elem_id="desc")
|
| 143 |
+
|
| 144 |
+
with gr.Row():
|
| 145 |
+
with gr.Column():
|
| 146 |
+
image_input = gr.Image(type="pil", label="Upload Image", elem_id="upload-img")
|
| 147 |
+
with gr.Row():
|
| 148 |
+
clear_button = gr.Button("Clear")
|
| 149 |
+
submit_button = gr.Button("Submit", variant="primary")
|
| 150 |
+
|
| 151 |
+
with gr.Column():
|
| 152 |
+
output_image = gr.Image(label="Gradient Image", type="pil", elem_id="grad-img")
|
| 153 |
+
output_label = gr.Label(label="Prediction")
|
| 154 |
+
|
| 155 |
+
submit_button.click(fn=process_image, inputs=image_input, outputs=[output_image, output_label])
|
| 156 |
+
clear_button.click(fn=lambda: (None, None, None), inputs=None, outputs=[image_input, output_image, output_label])
|
| 157 |
+
|
| 158 |
+
# Custom CSS
|
| 159 |
+
demo.css = """
|
| 160 |
+
#logo, #logo * {
|
| 161 |
+
font-size: 20px !important;
|
| 162 |
+
top: 10px;
|
| 163 |
+
left: 20px;
|
| 164 |
+
font-size: 90px;
|
| 165 |
+
font-weight: bold;
|
| 166 |
+
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
#title {
|
| 170 |
+
text-align: center;
|
| 171 |
+
margin-top: 10px;
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
#desc {
|
| 175 |
+
font-size: 100px;
|
| 176 |
+
text-align: left;
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
#submit-btn button {
|
| 180 |
+
background-color: #800080 !important;
|
| 181 |
+
color: white !important;
|
| 182 |
+
font-size: 18px !important;
|
| 183 |
+
padding: 10px 25px !important;
|
| 184 |
+
border-radius: 8px !important;
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
#submit-btn button:hover {
|
| 188 |
+
background-color: #6A006A !important;
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
#clear-btn button {
|
| 192 |
+
font-size: 18px !important;
|
| 193 |
+
padding: 10px 25px !important;
|
| 194 |
+
border-radius: 8px !important;
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
#upload-img img {
|
| 198 |
+
max-width: 256px;
|
| 199 |
+
max-height: 256px;
|
| 200 |
+
object-fit: contain;
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
#grad-img img {
|
| 205 |
+
max-width: 200px;
|
| 206 |
+
max-height: 200px;
|
| 207 |
+
border-radius: 10px;
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
demo.launch(share=True, debug=True)
|
| 213 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cv2
|
| 2 |
+
gradio
|
| 3 |
+
numpy
|
| 4 |
+
torch
|