lam107 commited on
Commit
d993d4f
·
verified ·
1 Parent(s): ee7417a

Upload app_cleaned.py

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