-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
298 lines (222 loc) · 7.38 KB
/
Copy pathapp.py
File metadata and controls
298 lines (222 loc) · 7.38 KB
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
import os
import torch
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from flask_wtf import FlaskForm
from flask_bootstrap import Bootstrap
from werkzeug.utils import secure_filename
from wtforms import FileField, SubmitField, FloatField, HiddenField
from wtforms.validators import InputRequired
from PIL import Image
from torchvision import transforms
import io
import gc
torch.set_num_threads(1)
# Import your existing AdaIN code
from utils.models import VGGEncoder, Decoder
from utils.utils import adaptive_instance_normalization, calc_mean_std
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get(
'SECRET_KEY',
'supersecretkey'
)
app.config['UPLOAD_FOLDER'] = 'static/uploads'
app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg'}
Bootstrap(app)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
class UploadForm(FlaskForm):
content = FileField('Content Image')
style = FileField('Style Image')
content_path = HiddenField()
style_path = HiddenField()
alpha = FloatField('Alpha', default=1.0)
submit = SubmitField('Transfer Style')
device = torch.device("cpu")
encoder = VGGEncoder('vgg_normalised.pth').to(device)
decoder = Decoder().to(device)
decoder.load_state_dict(
torch.load(
'experiment/big_dataset/decoder_final.pth',
map_location=device
)
)
encoder.eval()
decoder.eval()
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
def style_transfer(content_image, style_image,
encoder, decoder,
alpha, device):
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor()
])
content_image = transform(
content_image
).unsqueeze(0).to(device)
style_image = transform(
style_image
).unsqueeze(0).to(device)
with torch.no_grad():
content_feats = encoder(
content_image,
is_test=True
)
style_feats = encoder(
style_image,
is_test=True
)
stylized_feats = adaptive_instance_normalization(
content_feats,
style_feats
)
stylized_feats = (
alpha*stylized_feats
+(1-alpha)*content_feats
)
stylized_image = decoder(
stylized_feats
)
del content_feats
del style_feats
del stylized_feats
del content_image
del style_image
gc.collect()
return stylized_image
from PIL import ImageEnhance
def save_image(image, path):
image = image.cpu().clone()
image = image.squeeze(0)
image = image.clamp(0,1)
image = transforms.ToPILImage()(image)
image = image.resize((768,768))
enhancer = ImageEnhance.Sharpness(image)
image = enhancer.enhance(1.8)
color = ImageEnhance.Color(image)
image = color.enhance(1.15)
contrast = ImageEnhance.Contrast(image)
image = contrast.enhance(1.1)
image.save(path, quality=100)
@app.route('/', methods=['GET', 'POST'])
def index():
form = UploadForm()
result_image = None
content_filename = None
style_filename = None
error = None
if request.method == 'POST':
if form.validate_on_submit():
if form.content.data and form.content.data.filename:
if allowed_file(form.content.data.filename):
content_filename = secure_filename(
form.content.data.filename
)
form.content.data.save(
os.path.join(
app.config['UPLOAD_FOLDER'],
content_filename
)
)
form.content_path.data = content_filename
else:
content_filename = form.content_path.data
if form.style.data and form.style.data.filename:
if allowed_file(form.style.data.filename):
style_filename = secure_filename(
form.style.data.filename
)
form.style.data.save(
os.path.join(
app.config['UPLOAD_FOLDER'],
style_filename
)
)
form.style_path.data = style_filename
else:
style_filename = form.style_path.data
if content_filename and style_filename:
try:
content_path = os.path.join(
app.config['UPLOAD_FOLDER'],
content_filename
)
style_path = os.path.join(
app.config['UPLOAD_FOLDER'],
style_filename
)
content_image = Image.open(
content_path
).convert('RGB')
style_image = Image.open(
style_path
).convert('RGB')
alpha = min(
float(form.alpha.data),
0.75
)
stylized_image = style_transfer(
content_image,
style_image,
encoder,
decoder,
alpha,
device
)
import gc
del content_image
del style_image
gc.collect()
result_filename = (
'stylized_' +
content_filename
)
result_path = os.path.join(
app.config['UPLOAD_FOLDER'],
result_filename
)
save_image(
stylized_image,
result_path
)
del stylized_image
gc.collect()
result_image = result_filename
except Exception as e:
import traceback
error = traceback.format_exc()
print(error)
else:
error = "Upload both images"
return render_template(
'index.html',
form=form,
result_image=result_image,
content_image=content_filename,
style_image=style_filename,
error=error
)
@app.route('/uploads/<filename>')
def send_image(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
@app.route('/content_data/<filename>')
def send_content_example(filename):
return send_from_directory(
'content_data',
filename
)
@app.route('/style_data/<filename>')
def send_style_example(filename):
return send_from_directory(
'style_data',
filename
)
@app.route('/experiment/<filename>')
def send_generated(filename):
return send_from_directory(
'experiment/big_dataset',
filename
)
if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 5000, app, use_reloader=True, use_debugger=True)