-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
348 lines (280 loc) · 10.2 KB
/
app.py
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# Main Flask application file
from flask import Flask, render_template, url_for, flash, redirect, request, g, send_from_directory
from forms import RegistrationForm, LoginForm, UploadForm, ButtonForm
from werkzeug.utils import secure_filename
import os
import shutil
from os import path
import time
import logging
import torch
import torchvision
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision import models
from PIL import Image
from torchvision.utils import save_image
from torch.autograd import Variable
import numpy as np
nz = 100
ngf = 64
ndf = 64
nl = 2
nc = 3
device = torch.device('cpu')
if torch.cuda.is_available():
device = torch.device('cuda')
app = Flask(__name__)
app.config['SECRET_KEY'] = '6e8af7ecab9c7e41e861fa359a89f385'
# support bundles should be .tar.gpg, process will fail and exit otherwise
ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png'}
# Initialize Models
PATH = './lung_generator.pth'
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[-1].lower() in ALLOWED_EXTENSIONS
def gan_generate():
# generate new image from upload here
# the uploaded image will be in static/uploads/original.jpg
make_stuff(transform_image())
# write new image to static/uploads/covidified.jpg
# check if file has correct extension
@app.route('/favicon.ico')
def favicon():
return send_from_directory(path.join(app.root_path, 'static'), 'virus.png', mimetype='image/vnd.microsoft.icon')
# render home landing page
@app.route("/")
def home():
return render_template("home.html")
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/info")
def info():
return render_template("info.html")
@app.route("/results")
def results():
return render_template("results.html")
# path for upload page to upload file
@app.route("/upload", methods=['GET', 'POST'])
def upload():
logging.info('Uploading file')
form = UploadForm()
if form.validate_on_submit():
logging.info('File validated')
if form.file.data:
filename = secure_filename(form.file.data.filename)
else:
flash('Please upload a file!', 'danger')
logging.error('Attempted submit without file')
return render_template('upload.html', form=form)
if not allowed_file(filename):
logging.info('Illegal file extension')
flash('File must have extension .jpg, .jpeg, or .png', 'danger')
else:
# save accepted file to uploads folder
try:
form.file.data.save('static/uploads/original.jpg')
logging.info('File saved locally')
except:
logging.info('Failed to save file')
logging.info('Image generation process beginning')
# here trigger the loady wheel
gan_generate()
return render_template('results.html')
return render_template('upload.html', form=form)
class Generator(torch.nn.Module):
def __init__(self):
super(Generator, self).__init__()
self.main = nn.Sequential(
# input is Z, going into a convolution
nn.ConvTranspose2d(
in_channels=nz + nl,
out_channels=ngf * 8,
kernel_size=4,
stride=1,
padding=0,
bias=False
),
nn.BatchNorm2d(
num_features=ngf * 8
),
nn.ReLU(
inplace=True
),
# state size. (ngf*8) x 4 x 4
nn.ConvTranspose2d(
in_channels=ngf * 8,
out_channels=ngf * 4,
kernel_size=4,
stride=2,
padding=1,
bias=False
),
nn.BatchNorm2d(
num_features=ngf * 4
),
nn.ReLU(
inplace=True
),
# state size. (ngf*4) x 8 x 8
nn.ConvTranspose2d(
in_channels=ngf * 4,
out_channels=ngf * 2,
kernel_size=4,
stride=2,
padding=1,
bias=False
),
nn.BatchNorm2d(
num_features=ngf * 2
),
nn.ReLU(
inplace=True
),
# state size. (ngf*2) x 16 x 16
nn.ConvTranspose2d(
in_channels=ngf * 2,
out_channels=ngf,
kernel_size=4,
stride=2,
padding=1,
bias=False
),
nn.BatchNorm2d(
num_features=ngf
),
nn.ReLU(
inplace=True
),
# state size. (ngf) x 32 x 32
nn.ConvTranspose2d(
in_channels=ngf,
out_channels=nc,
kernel_size=4,
stride=2,
padding=1,
bias=False
),
nn.Tanh()
# state size. (nc) x 64 x 64
)
def forward(self, inputs, condition):
# Concatenate Noise and Condition
cat_inputs = torch.cat(
(inputs, condition),
dim=1
)
# Reshape the latent vector into a feature map.
cat_inputs = cat_inputs.unsqueeze(2).unsqueeze(3)
return self.main(cat_inputs)
netG = Generator().to(device)
netG.load_state_dict(torch.load(PATH, map_location=device))
class SquashTransform:
def __call__(self, inputs):
return 2 * inputs - 1
def transform_image():
img = Image.open('./static/uploads/original.jpg')
data_transform = transforms.Compose([
transforms.Resize(64),
transforms.ToTensor(),
SquashTransform()
])
return data_transform(img).unsqueeze(0)
class VGGPerceptualLoss(torch.nn.Module):
def __init__(self, resize=True):
super(VGGPerceptualLoss, self).__init__()
blocks = []
blocks.append(torchvision.models.vgg16(
pretrained=True).features[:4].eval())
blocks.append(torchvision.models.vgg16(
pretrained=True).features[4:9].eval())
blocks.append(torchvision.models.vgg16(
pretrained=True).features[9:16].eval())
blocks.append(torchvision.models.vgg16(
pretrained=True).features[16:23].eval())
for bl in blocks:
for p in bl:
p.requires_grad = False
self.blocks = torch.nn.ModuleList(blocks)
self.transform = torch.nn.functional.interpolate
self.mean = torch.nn.Parameter(torch.tensor(
[0.485, 0.456, 0.406]).view(1, 3, 1, 1))
self.std = torch.nn.Parameter(torch.tensor(
[0.229, 0.224, 0.225]).view(1, 3, 1, 1))
self.resize = resize
def forward(self, input, target):
if input.shape[1] != 3:
input = input.repeat(1, 3, 1, 1)
target = target.repeat(1, 3, 1, 1)
input = (input-self.mean) / self.std
target = (target-self.mean) / self.std
if self.resize:
input = self.transform(input, mode='bilinear', size=(
224, 224), align_corners=False)
target = self.transform(target, mode='bilinear', size=(
224, 224), align_corners=False)
loss = 0.0
x = input
y = target
for block in self.blocks:
x = block(x)
y = block(y)
loss += torch.nn.functional.l1_loss(x, y)
return loss
def make_stuff(image):
init_noise = Variable(torch.randn(
1, nz
).to(device), requires_grad=True)
negative_label = torch.Tensor([[1, 0]]).to(device)
positive_label = torch.Tensor([[0, 1]]).to(device)
optim = torch.optim.Adam([init_noise], lr=0.1, betas=(0.5, 0.999))
original_image = image[0].to(device)
mask = torch.ones([1, 3, 64, 64]).to(device)
mask[0, :, 4:60, 20:60] = 2
for epoch in range(0, 20):
print('Epoch: ' + str(epoch))
original_image = image[0].to(device)
optim.zero_grad()
sample = netG(init_noise, negative_label).to(device)
sample = sample.reshape([1, 3, 64, 64])
original_image = original_image.reshape([1, 3, 64, 64])
loss_func = VGGPerceptualLoss().to(device)
loss = loss_func(sample, original_image) + 10 * \
torch.mean(mask*(original_image - sample)**2)
#loss = 100* torch.mean(mask*(original_image - sample)**2)
loss.backward()
optim.step()
if (epoch+1) % 10 == 0:
reconstructed_image = netG(
init_noise, negative_label
).detach().cpu().view(-1, 3, 64, 64)
reconstructed_image = reconstructed_image[0, ]
original_image = original_image.cpu().view(3, 64, 64)
original_image = np.transpose(original_image, (1, 2, 0))
original_image = (original_image + 1)/2
reconstructed_image = np.transpose(reconstructed_image, (1, 2, 0))
reconstructed_image = (reconstructed_image + 1)/2
original_image = image[0].to(device)
reconstructed_image_positive = netG(
init_noise, positive_label
).detach().cpu().view(-1, 3, 64, 64)
reconstructed_image_positive = reconstructed_image_positive[0, ]
reconstructed_image_negative = netG(
init_noise, negative_label
).detach().cpu().view(-1, 3, 64, 64)
reconstructed_image_negative = reconstructed_image_negative[0, ]
original_image = original_image.cpu().view(3, 64, 64)
original_image = np.transpose(original_image, (1, 2, 0))
original_image = (original_image + 1)/2
reconstructed_image_negative = np.transpose(
reconstructed_image_negative, (1, 2, 0))
reconstructed_image_negative = (reconstructed_image_negative + 1)/2
reconstructed_image_positive = (reconstructed_image_positive + 1)/2
save_image(reconstructed_image_positive, './static/uploads/covidified.jpg')
# only true if you run script directly, if imported will be false
if __name__ == '__main__':
logging.basicConfig(filename='app.log', format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S', filemode='w', level=logging.INFO)
logging.info('Started')
app.run(debug=True)
logging.info('Finished')