Spaces:
Sleeping
Sleeping
add:app
Browse files- Dockerfile +24 -0
- compo-singleone-v1-dev-acc.py +368 -0
- compo-singleone-v2-dev-acc.py +553 -0
- requirements.txt +69 -0
- server.py +59 -0
Dockerfile
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM guillaumeai/ast:ap2404_v1-195ik
|
2 |
+
|
3 |
+
RUN apt update && apt install -y sudo imagemagick
|
4 |
+
# RUN apt upgrade -y
|
5 |
+
|
6 |
+
RUN pip install -U pip
|
7 |
+
# #RUN pip install -U pyyaml
|
8 |
+
# RUN pip install -U runway-python
|
9 |
+
# #runway --force-reinstall
|
10 |
+
# #RUN pip install -U tensorflow
|
11 |
+
|
12 |
+
|
13 |
+
COPY requirements.txt .
|
14 |
+
RUN pip install -r requirements.txt
|
15 |
+
|
16 |
+
COPY server.py .
|
17 |
+
COPY compo-singleone-v1-dev-acc.py .
|
18 |
+
COPY compo-singleone-v2-dev-acc.py .
|
19 |
+
|
20 |
+
EXPOSE 7860
|
21 |
+
|
22 |
+
#compo-singleone-v1-dev-acc.py
|
23 |
+
|
24 |
+
CMD ["python", "compo-singleone-v2-dev-acc.py"]
|
compo-singleone-v1-dev-acc.py
ADDED
@@ -0,0 +1,368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#####################################################
|
2 |
+
# AST Composite Server Double Two
|
3 |
+
# By Guillaume Descoteaux-Isabelle, 20021
|
4 |
+
#
|
5 |
+
# This server compose two Adaptive Style Transfer model (output of the first pass serve as input to the second using the same model)
|
6 |
+
########################################################
|
7 |
+
#v1-dev
|
8 |
+
#Receive the 2 res from arguments in the request...
|
9 |
+
|
10 |
+
|
11 |
+
import os
|
12 |
+
import numpy as np
|
13 |
+
import tensorflow as tf
|
14 |
+
import cv2
|
15 |
+
from module import encoder, decoder
|
16 |
+
from glob import glob
|
17 |
+
import runway
|
18 |
+
from runway.data_types import number, text
|
19 |
+
|
20 |
+
|
21 |
+
#from utils import *
|
22 |
+
import scipy
|
23 |
+
from datetime import datetime
|
24 |
+
import time
|
25 |
+
|
26 |
+
|
27 |
+
#/var/lib/ast/model/model_cezanne:/data/styleCheckpoint/model_cezanne
|
28 |
+
|
29 |
+
# Determining the size of the passes
|
30 |
+
pass1_image_size = 1328
|
31 |
+
if not os.getenv('PASS1IMAGESIZE'):
|
32 |
+
print("PASS1IMAGESIZE env var non existent;using default:" + str(pass1_image_size))
|
33 |
+
else:
|
34 |
+
pass1_image_size = os.getenv('PASS1IMAGESIZE', 1328)
|
35 |
+
print("PASS1IMAGESIZE value:" + str(pass1_image_size))
|
36 |
+
|
37 |
+
|
38 |
+
# Determining the size of the passes
|
39 |
+
autoabc = 1
|
40 |
+
if not os.getenv('AUTOABC'):
|
41 |
+
print("AUTOABC env var non existent;using default:")
|
42 |
+
print(autoabc)
|
43 |
+
abcdefault = 1
|
44 |
+
print("NOTE----> when running docker, set AUTOABC variable")
|
45 |
+
print(" docker run ... -e AUTOABC=1 #enabled, 0 to disabled (default)")
|
46 |
+
else:
|
47 |
+
autoabc = os.getenv('AUTOABC',1)
|
48 |
+
print("AUTOABC value:")
|
49 |
+
print(autoabc)
|
50 |
+
abcdefault = autoabc
|
51 |
+
|
52 |
+
|
53 |
+
#pass2_image_size = 1024
|
54 |
+
#if not os.getenv('PASS2IMAGESIZE'):
|
55 |
+
# print("PASS2IMAGESIZE env var non existent;using default:" + pass2_image_size)
|
56 |
+
#else:
|
57 |
+
# pass2_image_size = os.getenv('PASS2IMAGESIZE')
|
58 |
+
# print("PASS2IMAGESIZE value:" + pass2_image_size)
|
59 |
+
|
60 |
+
# pass3_image_size = 2048
|
61 |
+
# if not os.getenv('PASS3IMAGESIZE'):
|
62 |
+
# print("PASS3IMAGESIZE env var non existent;using default:" + pass3_image_size)
|
63 |
+
# else:
|
64 |
+
# pass3_image_size = os.getenv('PASS3IMAGESIZE')
|
65 |
+
# print("PASS3IMAGESIZE value:" + pass3_image_size)
|
66 |
+
|
67 |
+
##########################################
|
68 |
+
## MODELS
|
69 |
+
#model name for sending it in the response
|
70 |
+
model1name = "UNNAMED"
|
71 |
+
if not os.getenv('MODEL1NAME'):
|
72 |
+
print("MODEL1NAME env var non existent;using default:" + model1name)
|
73 |
+
else:
|
74 |
+
model1name = os.getenv('MODEL1NAME', "UNNAMED")
|
75 |
+
print("MODEL1NAME value:" + model1name)
|
76 |
+
|
77 |
+
# #m2
|
78 |
+
# model2name = "UNNAMED"
|
79 |
+
# if not os.getenv('MODEL2NAME'): print("MODEL2NAME env var non existent;using default:" + model2name)
|
80 |
+
# else:
|
81 |
+
# model2name = os.getenv('MODEL2NAME')
|
82 |
+
# print("MODEL2NAME value:" + model2name)
|
83 |
+
|
84 |
+
# #m3
|
85 |
+
# model3name = "UNNAMED"
|
86 |
+
# if not os.getenv('MODEL3NAME'): print("MODEL3NAME env var non existent;using default:" + model3name)
|
87 |
+
# else:
|
88 |
+
# model3name = os.getenv('MODEL3NAME')
|
89 |
+
# print("MODEL3NAME value:" + model3name)
|
90 |
+
|
91 |
+
#######################################################
|
92 |
+
|
93 |
+
|
94 |
+
#########################################################
|
95 |
+
# SETUP
|
96 |
+
|
97 |
+
@runway.setup(options={'styleCheckpoint': runway.file(is_directory=True)})
|
98 |
+
def setup(opts):
|
99 |
+
sess = tf.Session()
|
100 |
+
# sess2 = tf.Session()
|
101 |
+
# sess3 = tf.Session()
|
102 |
+
init_op = tf.global_variables_initializer()
|
103 |
+
# init_op2 = tf.global_variables_initializer()
|
104 |
+
# init_op3 = tf.global_variables_initializer()
|
105 |
+
sess.run(init_op)
|
106 |
+
# sess2.run(init_op2)
|
107 |
+
# sess3.run(init_op3)
|
108 |
+
with tf.name_scope('placeholder'):
|
109 |
+
input_photo = tf.placeholder(dtype=tf.float32,
|
110 |
+
shape=[1, None, None, 3],
|
111 |
+
name='photo')
|
112 |
+
input_photo_features = encoder(image=input_photo,
|
113 |
+
options={'gf_dim': 32},
|
114 |
+
reuse=False)
|
115 |
+
output_photo = decoder(features=input_photo_features,
|
116 |
+
options={'gf_dim': 32},
|
117 |
+
reuse=False)
|
118 |
+
saver = tf.train.Saver()
|
119 |
+
# saver2 = tf.train.Saver()
|
120 |
+
# saver3 = tf.train.Saver()
|
121 |
+
path = opts['styleCheckpoint']
|
122 |
+
#Getting the model name
|
123 |
+
model_name = [p for p in os.listdir(path) if os.path.isdir(os.path.join(path, p))][0]
|
124 |
+
if not os.getenv('MODELNAME'):
|
125 |
+
dtprint("CONFIG::MODELNAME env var non existent;using default:" + model_name)
|
126 |
+
else:
|
127 |
+
model_name = os.getenv('MODELNAME')
|
128 |
+
|
129 |
+
|
130 |
+
|
131 |
+
# #Getting the model2 name
|
132 |
+
# model2_name = [p for p in os.listdir(path) if os.path.isdir(os.path.join(path, p))][1]
|
133 |
+
# if not os.getenv('MODEL2NAME'):
|
134 |
+
# dtprint("CONFIG::MODEL2NAME env var non existent;using default:" + model2_name)
|
135 |
+
# else:
|
136 |
+
# model2_name = os.getenv('MODEL2NAME')
|
137 |
+
|
138 |
+
|
139 |
+
##Getting the model3 name
|
140 |
+
# model3_name = [p for p in os.listdir(path) if os.path.isdir(os.path.join(path, p))][2]
|
141 |
+
# if not os.getenv('MODEL3NAME'):
|
142 |
+
# dtprint("CONFIG::MODEL3NAME env var non existent;using default:" + model3_name)
|
143 |
+
# else:
|
144 |
+
# model3_name = os.getenv('MODEL3NAME')
|
145 |
+
|
146 |
+
|
147 |
+
|
148 |
+
checkpoint_dir = os.path.join(path, model_name, 'checkpoint_long')
|
149 |
+
#checkpoint2_dir = os.path.join(path, model2_name, 'checkpoint_long')
|
150 |
+
# checkpoint3_dir = os.path.join(path, model3_name, 'checkpoint_long')
|
151 |
+
print("-----------------------------------------")
|
152 |
+
print("modelname is : " + model_name)
|
153 |
+
#print("model2name is : " + model2_name)
|
154 |
+
# print("model3name is : " + model3_name)
|
155 |
+
print("checkpoint_dir is : " + checkpoint_dir)
|
156 |
+
|
157 |
+
print("Auto Brightness-Contrast Correction can be set as the x2 of this SingleOne Server")
|
158 |
+
|
159 |
+
|
160 |
+
#print("checkpoint2_dir is : " + checkpoint2_dir)
|
161 |
+
# print("checkpoint3_dir is : " + checkpoint3_dir)
|
162 |
+
print("-----------------------------------------")
|
163 |
+
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
|
164 |
+
#ckpt2 = tf.train.get_checkpoint_state(checkpoint2_dir)
|
165 |
+
# ckpt3 = tf.train.get_checkpoint_state(checkpoint3_dir)
|
166 |
+
ckpt_name = os.path.basename(ckpt.model_checkpoint_path)
|
167 |
+
#ckpt2_name = os.path.basename(ckpt2.model_checkpoint_path)
|
168 |
+
# ckpt3_name = os.path.basename(ckpt3.model_checkpoint_path)
|
169 |
+
saver.restore(sess, os.path.join(checkpoint_dir, ckpt_name))
|
170 |
+
#saver2.restore(sess2, os.path.join(checkpoint2_dir, ckpt2_name))
|
171 |
+
# saver3.restore(sess3, os.path.join(checkpoint3_dir, ckpt3_name))
|
172 |
+
m1 = dict(sess=sess, input_photo=input_photo, output_photo=output_photo)
|
173 |
+
#m2 = dict(sess=sess2, input_photo=input_photo, output_photo=output_photo)
|
174 |
+
# m3 = dict(sess=sess3, input_photo=input_photo, output_photo=output_photo)
|
175 |
+
models = type('', (), {})()
|
176 |
+
models.m1 = m1
|
177 |
+
#models.m2 = m2
|
178 |
+
# models.m3 = m3
|
179 |
+
return models
|
180 |
+
|
181 |
+
|
182 |
+
#@STCGoal add number or text to specify resolution of the three pass
|
183 |
+
inputs={'contentImage': runway.image,'x1':number(default=1024,min=24,max=17000),'x2':number(default=0,min=-99,max=99)}
|
184 |
+
outputs={'stylizedImage': runway.image,'totaltime':number,'x1': number,'c1':number,'model1name':text}
|
185 |
+
|
186 |
+
@runway.command('stylize', inputs=inputs, outputs=outputs)
|
187 |
+
def stylize(models, inp):
|
188 |
+
start = time.time()
|
189 |
+
dtprint("Composing.1..")
|
190 |
+
model = models.m1
|
191 |
+
#model2 = models.m2
|
192 |
+
# model3 = models.m3
|
193 |
+
|
194 |
+
#Getting our names back (even though I think we dont need)
|
195 |
+
#@STCIssue BUGGED
|
196 |
+
# m1name=models.m1.name
|
197 |
+
# m2name=models.m2.name
|
198 |
+
# m3name=models.m3.name
|
199 |
+
|
200 |
+
#get size from inputs rather than env
|
201 |
+
x1 = inp['x1']
|
202 |
+
c1 = inp['x2']
|
203 |
+
# x3 = inp['x3']
|
204 |
+
if c1 > 99:
|
205 |
+
ci = abcdefault
|
206 |
+
|
207 |
+
|
208 |
+
#
|
209 |
+
img = inp['contentImage']
|
210 |
+
img = np.array(img)
|
211 |
+
img = img / 127.5 - 1.
|
212 |
+
|
213 |
+
#@a Pass 1 RESIZE to 1368px the smaller side
|
214 |
+
image_size=pass1_image_size
|
215 |
+
image_size=x1
|
216 |
+
img_shape = img.shape[:2]
|
217 |
+
alpha = float(image_size) / float(min(img_shape))
|
218 |
+
dtprint ("DEBUG::content.imgshape:" + str(tuple(img_shape)) + ", alpha:" + str(alpha))
|
219 |
+
|
220 |
+
try:
|
221 |
+
img = scipy.misc.imresize(img, size=alpha)
|
222 |
+
except:
|
223 |
+
pass
|
224 |
+
|
225 |
+
|
226 |
+
img = np.expand_dims(img, axis=0)
|
227 |
+
#@a INFERENCE PASS 1
|
228 |
+
dtprint("INFO:Pass1 inference starting")
|
229 |
+
img = model['sess'].run(model['output_photo'], feed_dict={model['input_photo']: img})
|
230 |
+
dtprint("INFO:Pass1 inference done")
|
231 |
+
#
|
232 |
+
img = (img + 1.) * 127.5
|
233 |
+
img = img.astype('uint8')
|
234 |
+
img = img[0]
|
235 |
+
#dtprint("INFO:Upresing Pass1 for Pass 2 (STARTING) ")
|
236 |
+
|
237 |
+
#@a Pass 2 RESIZE to 1024px the smaller side
|
238 |
+
#image_size=pass2_image_size
|
239 |
+
#image_size=x2
|
240 |
+
#img_shape = img.shape[:2]
|
241 |
+
|
242 |
+
|
243 |
+
#alpha = float(image_size) / float(min(img_shape))
|
244 |
+
#dtprint ("DEBUG::pass1.imgshape:" + str(tuple(img_shape)) + ", alpha:" + str(alpha))
|
245 |
+
|
246 |
+
#img = scipy.misc.imresize(img, size=alpha)
|
247 |
+
#dtprint("INFO:Upresing Pass1 (DONE) ")
|
248 |
+
|
249 |
+
#Iteration 2
|
250 |
+
#img = np.array(img)
|
251 |
+
#img = img / 127.5 - 1.
|
252 |
+
#img = np.expand_dims(img, axis=0)
|
253 |
+
#@a INFERENCE PASS 2 using the same model
|
254 |
+
#dtprint("INFO:Pass2 inference (STARTING)")
|
255 |
+
#img = model['sess'].run(model['output_photo'], feed_dict={model['input_photo']: img})
|
256 |
+
#dtprint("INFO:Pass2 inference (DONE)")
|
257 |
+
#img = (img + 1.) * 127.5
|
258 |
+
#img = img.astype('uint8')
|
259 |
+
#img = img[0]
|
260 |
+
|
261 |
+
|
262 |
+
|
263 |
+
# #pass3
|
264 |
+
|
265 |
+
# #@a Pass 3 RESIZE to 2048px the smaller side
|
266 |
+
# image_size=pass3_image_size
|
267 |
+
# image_size=x3
|
268 |
+
# img_shape = img.shape[:2]
|
269 |
+
|
270 |
+
|
271 |
+
# alpha = float(image_size) / float(min(img_shape))
|
272 |
+
# dtprint ("DEBUG::pass2.imgshape:" + str(tuple(img_shape)) + ", alpha:" + str(alpha))
|
273 |
+
|
274 |
+
# img = scipy.misc.imresize(img, size=alpha)
|
275 |
+
# dtprint("INFO:Upresing Pass2 (DONE) ")
|
276 |
+
|
277 |
+
# #Iteration 3
|
278 |
+
# img = np.array(img)
|
279 |
+
# img = img / 127.5 - 1.
|
280 |
+
# img = np.expand_dims(img, axis=0)
|
281 |
+
# #@a INFERENCE PASS 3
|
282 |
+
# dtprint("INFO:Pass3 inference (STARTING)")
|
283 |
+
# img = model3['sess'].run(model3['output_photo'], feed_dict={model3['input_photo']: img})
|
284 |
+
# dtprint("INFO:Pass3 inference (DONE)")
|
285 |
+
# img = (img + 1.) * 127.5
|
286 |
+
# img = img.astype('uint8')
|
287 |
+
# img = img[0]
|
288 |
+
# #pass3
|
289 |
+
|
290 |
+
#dtprint("INFO:Composing done")
|
291 |
+
print('autoabc value:')
|
292 |
+
print(c1)
|
293 |
+
if c1 != 0 :
|
294 |
+
print('Auto Brightening images...')
|
295 |
+
img = img, alpha2, beta = automatic_brightness_and_contrast(img,c1)
|
296 |
+
|
297 |
+
stop = time.time()
|
298 |
+
totaltime = stop - start
|
299 |
+
print("The time of the run:", totaltime)
|
300 |
+
res2 = dict(stylizedImage=img,totaltime=totaltime,x1=x1,model1name=model1name,c1=c1)
|
301 |
+
return res2
|
302 |
+
|
303 |
+
|
304 |
+
|
305 |
+
def dtprint(msg):
|
306 |
+
dttag=getdttag()
|
307 |
+
print(dttag + "::" + msg )
|
308 |
+
|
309 |
+
def getdttag():
|
310 |
+
# datetime object containing current date and time
|
311 |
+
now = datetime.now()
|
312 |
+
|
313 |
+
# dd/mm/YY H:M:S
|
314 |
+
# dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
|
315 |
+
return now.strftime("%H:%M:%S")
|
316 |
+
|
317 |
+
|
318 |
+
|
319 |
+
# Automatic brightness and contrast optimization with optional histogram clipping
|
320 |
+
def automatic_brightness_and_contrast(image, clip_hist_percent=25):
|
321 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
322 |
+
|
323 |
+
# Calculate grayscale histogram
|
324 |
+
hist = cv2.calcHist([gray],[0],None,[256],[0,256])
|
325 |
+
hist_size = len(hist)
|
326 |
+
|
327 |
+
# Calculate cumulative distribution from the histogram
|
328 |
+
accumulator = []
|
329 |
+
accumulator.append(float(hist[0]))
|
330 |
+
for index in range(1, hist_size):
|
331 |
+
accumulator.append(accumulator[index -1] + float(hist[index]))
|
332 |
+
|
333 |
+
# Locate points to clip
|
334 |
+
maximum = accumulator[-1]
|
335 |
+
clip_hist_percent *= (maximum/100.0)
|
336 |
+
clip_hist_percent /= 2.0
|
337 |
+
|
338 |
+
# Locate left cut
|
339 |
+
minimum_gray = 0
|
340 |
+
while accumulator[minimum_gray] < clip_hist_percent:
|
341 |
+
minimum_gray += 1
|
342 |
+
|
343 |
+
# Locate right cut
|
344 |
+
maximum_gray = hist_size -1
|
345 |
+
while accumulator[maximum_gray] >= (maximum - clip_hist_percent):
|
346 |
+
maximum_gray -= 1
|
347 |
+
|
348 |
+
# Calculate alpha and beta values
|
349 |
+
alpha = 255 / (maximum_gray - minimum_gray)
|
350 |
+
beta = -minimum_gray * alpha
|
351 |
+
|
352 |
+
'''
|
353 |
+
# Calculate new histogram with desired range and show histogram
|
354 |
+
new_hist = cv2.calcHist([gray],[0],None,[256],[minimum_gray,maximum_gray])
|
355 |
+
plt.plot(hist)
|
356 |
+
plt.plot(new_hist)
|
357 |
+
plt.xlim([0,256])
|
358 |
+
plt.show()
|
359 |
+
'''
|
360 |
+
|
361 |
+
auto_result = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
|
362 |
+
return (auto_result, alpha, beta)
|
363 |
+
|
364 |
+
|
365 |
+
if __name__ == '__main__':
|
366 |
+
#print('External Service port is:' +os.environ.get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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#####################################################
|
2 |
+
# AST Composite Server Double Two
|
3 |
+
# By Guillaume Descoteaux-Isabelle, 20021
|
4 |
+
#
|
5 |
+
# This server compose two Adaptive Style Transfer model (output of the first pass serve as input to the second using the same model)
|
6 |
+
########################################################
|
7 |
+
#v1-dev
|
8 |
+
#Receive the 2 res from arguments in the request...
|
9 |
+
|
10 |
+
|
11 |
+
import os
|
12 |
+
import numpy as np
|
13 |
+
import tensorflow as tf
|
14 |
+
import cv2
|
15 |
+
from module import encoder, decoder
|
16 |
+
from glob import glob
|
17 |
+
import runway
|
18 |
+
from runway.data_types import number, text
|
19 |
+
|
20 |
+
|
21 |
+
#from utils import *
|
22 |
+
import scipy
|
23 |
+
from datetime import datetime
|
24 |
+
import time
|
25 |
+
|
26 |
+
|
27 |
+
import re
|
28 |
+
|
29 |
+
|
30 |
+
SRV_TYPE="s1"
|
31 |
+
|
32 |
+
#set env var RW_ if not already set
|
33 |
+
if not os.getenv('RW_PORT'):
|
34 |
+
os.environ["RW_PORT"] = "7860"
|
35 |
+
|
36 |
+
if not os.getenv('RW_DEBUG'):
|
37 |
+
os.environ["RW_DEBUG"] = "0"
|
38 |
+
if not os.getenv('RW_HOST'):
|
39 |
+
os.environ["RW_HOST"] = "0.0.0.0"
|
40 |
+
#RW_MODEL_OPTIONS
|
41 |
+
if not os.getenv('RW_MODEL_OPTIONS'):
|
42 |
+
os.environ["RW_MODEL_OPTIONS"]='{"styleCheckpoint":"/data/styleCheckpoint"}'
|
43 |
+
|
44 |
+
# Determining the size of the passes
|
45 |
+
pass1_image_size = 1328
|
46 |
+
if not os.getenv('PASS1IMAGESIZE'):
|
47 |
+
print("PASS1IMAGESIZE env var non existent;using default:" + str(pass1_image_size))
|
48 |
+
else:
|
49 |
+
pass1_image_size = os.getenv('PASS1IMAGESIZE', 1328)
|
50 |
+
print("PASS1IMAGESIZE value:" + str(pass1_image_size))
|
51 |
+
|
52 |
+
|
53 |
+
# Determining the size of the passes
|
54 |
+
autoabc = 1
|
55 |
+
if not os.getenv('AUTOABC'):
|
56 |
+
print("AUTOABC env var non existent;using default:")
|
57 |
+
print(autoabc)
|
58 |
+
abcdefault = 1
|
59 |
+
print("NOTE----> when running docker, set AUTOABC variable")
|
60 |
+
print(" docker run ... -e AUTOABC=1 #enabled, 0 to disabled (default)")
|
61 |
+
else:
|
62 |
+
autoabc = os.getenv('AUTOABC',1)
|
63 |
+
print("AUTOABC value:")
|
64 |
+
print(autoabc)
|
65 |
+
abcdefault = autoabc
|
66 |
+
|
67 |
+
|
68 |
+
#pass2_image_size = 1024
|
69 |
+
#if not os.getenv('PASS2IMAGESIZE'):
|
70 |
+
# print("PASS2IMAGESIZE env var non existent;using default:" + pass2_image_size)
|
71 |
+
#else:
|
72 |
+
# pass2_image_size = os.getenv('PASS2IMAGESIZE')
|
73 |
+
# print("PASS2IMAGESIZE value:" + pass2_image_size)
|
74 |
+
|
75 |
+
# pass3_image_size = 2048
|
76 |
+
# if not os.getenv('PASS3IMAGESIZE'):
|
77 |
+
# print("PASS3IMAGESIZE env var non existent;using default:" + pass3_image_size)
|
78 |
+
# else:
|
79 |
+
# pass3_image_size = os.getenv('PASS3IMAGESIZE')
|
80 |
+
# print("PASS3IMAGESIZE value:" + pass3_image_size)
|
81 |
+
|
82 |
+
##########################################
|
83 |
+
## MODELS
|
84 |
+
#model name for sending it in the response
|
85 |
+
model1name = "UNNAMED"
|
86 |
+
if not os.getenv('MODEL1NAME'):
|
87 |
+
print("MODEL1NAME env var non existent;using default:" + model1name)
|
88 |
+
else:
|
89 |
+
model1name = os.getenv('MODEL1NAME', "UNNAMED")
|
90 |
+
print("MODEL1NAME value:" + model1name)
|
91 |
+
|
92 |
+
# #m2
|
93 |
+
# model2name = "UNNAMED"
|
94 |
+
# if not os.getenv('MODEL2NAME'): print("MODEL2NAME env var non existent;using default:" + model2name)
|
95 |
+
# else:
|
96 |
+
# model2name = os.getenv('MODEL2NAME')
|
97 |
+
# print("MODEL2NAME value:" + model2name)
|
98 |
+
|
99 |
+
# #m3
|
100 |
+
# model3name = "UNNAMED"
|
101 |
+
# if not os.getenv('MODEL3NAME'): print("MODEL3NAME env var non existent;using default:" + model3name)
|
102 |
+
# else:
|
103 |
+
# model3name = os.getenv('MODEL3NAME')
|
104 |
+
# print("MODEL3NAME value:" + model3name)
|
105 |
+
|
106 |
+
#######################################################
|
107 |
+
|
108 |
+
def get_model_simplified_name_from_dirname(dirname):
|
109 |
+
result_simple_name = dirname.replace("model_","").replace("_864x","").replace("_864","").replace("_new","").replace("-864","")
|
110 |
+
print(" result_simple_name:" + result_simple_name)
|
111 |
+
return result_simple_name
|
112 |
+
|
113 |
+
def get_padded_checkpoint_no_from_filename(checkpoint_filename):
|
114 |
+
match = re.search(r'ckpt-(\d+)', checkpoint_filename)
|
115 |
+
if match:
|
116 |
+
number = int(match.group(1))
|
117 |
+
checkpoint_number = round(number/1000,0)
|
118 |
+
print(checkpoint_number)
|
119 |
+
|
120 |
+
padded_checkpoint_number = str(str(checkpoint_number).zfill(3))
|
121 |
+
return padded_checkpoint_number.replace('.0','')
|
122 |
+
|
123 |
+
found_model='none'
|
124 |
+
found_model_checkpoint='0'
|
125 |
+
|
126 |
+
#########################################################
|
127 |
+
# SETUP
|
128 |
+
|
129 |
+
|
130 |
+
runway_files = runway.file(is_directory=True)
|
131 |
+
@runway.setup(options={'styleCheckpoint': runway_files})
|
132 |
+
def setup(opts):
|
133 |
+
global found_model,found_model_checkpoint
|
134 |
+
sess = tf.Session()
|
135 |
+
# sess2 = tf.Session()
|
136 |
+
# sess3 = tf.Session()
|
137 |
+
init_op = tf.global_variables_initializer()
|
138 |
+
# init_op2 = tf.global_variables_initializer()
|
139 |
+
# init_op3 = tf.global_variables_initializer()
|
140 |
+
sess.run(init_op)
|
141 |
+
# sess2.run(init_op2)
|
142 |
+
# sess3.run(init_op3)
|
143 |
+
with tf.name_scope('placeholder'):
|
144 |
+
input_photo = tf.placeholder(dtype=tf.float32,
|
145 |
+
shape=[1, None, None, 3],
|
146 |
+
name='photo')
|
147 |
+
input_photo_features = encoder(image=input_photo,
|
148 |
+
options={'gf_dim': 32},
|
149 |
+
reuse=False)
|
150 |
+
output_photo = decoder(features=input_photo_features,
|
151 |
+
options={'gf_dim': 32},
|
152 |
+
reuse=False)
|
153 |
+
saver = tf.train.Saver()
|
154 |
+
# saver2 = tf.train.Saver()
|
155 |
+
# saver3 = tf.train.Saver()
|
156 |
+
print("-------------====PATH---------------------->>>>--")
|
157 |
+
path_default = '/data/styleCheckpoint'
|
158 |
+
print("opts:")
|
159 |
+
print(opts)
|
160 |
+
print("----------------------------------------")
|
161 |
+
if opts is None:
|
162 |
+
print("ERROR:opts is None")
|
163 |
+
path = path_default
|
164 |
+
try:
|
165 |
+
path = opts['styleCheckpoint']
|
166 |
+
except:
|
167 |
+
opts= {'styleCheckpoint': u'/data/styleCheckpoint'}
|
168 |
+
path = opts['styleCheckpoint']
|
169 |
+
if not os.path.exists(path):
|
170 |
+
print("ERROR:Path does not exist:" + path)
|
171 |
+
path = path_default
|
172 |
+
print(path)
|
173 |
+
print("----------------PATH=======---------------<<<<--")
|
174 |
+
#Getting the model name
|
175 |
+
model_name = [p for p in os.listdir(path) if os.path.isdir(os.path.join(path, p))][0]
|
176 |
+
if not os.getenv('MODELNAME'):
|
177 |
+
dtprint("CONFIG::MODELNAME env var non existent;using default:" + model_name)
|
178 |
+
else:
|
179 |
+
model_name = os.getenv('MODELNAME')
|
180 |
+
|
181 |
+
|
182 |
+
|
183 |
+
# #Getting the model2 name
|
184 |
+
# model2_name = [p for p in os.listdir(path) if os.path.isdir(os.path.join(path, p))][1]
|
185 |
+
# if not os.getenv('MODEL2NAME'):
|
186 |
+
# dtprint("CONFIG::MODEL2NAME env var non existent;using default:" + model2_name)
|
187 |
+
# else:
|
188 |
+
# model2_name = os.getenv('MODEL2NAME')
|
189 |
+
|
190 |
+
|
191 |
+
##Getting the model3 name
|
192 |
+
# model3_name = [p for p in os.listdir(path) if os.path.isdir(os.path.join(path, p))][2]
|
193 |
+
# if not os.getenv('MODEL3NAME'):
|
194 |
+
# dtprint("CONFIG::MODEL3NAME env var non existent;using default:" + model3_name)
|
195 |
+
# else:
|
196 |
+
# model3_name = os.getenv('MODEL3NAME')
|
197 |
+
|
198 |
+
|
199 |
+
|
200 |
+
checkpoint_dir = os.path.join(path, model_name, 'checkpoint_long')
|
201 |
+
#checkpoint2_dir = os.path.join(path, model2_name, 'checkpoint_long')
|
202 |
+
# checkpoint3_dir = os.path.join(path, model3_name, 'checkpoint_long')
|
203 |
+
print("-----------------------------------------")
|
204 |
+
print("modelname is : " + model_name)
|
205 |
+
|
206 |
+
found_model=get_model_simplified_name_from_dirname(model_name)
|
207 |
+
|
208 |
+
#print("model2name is : " + model2_name)
|
209 |
+
# print("model3name is : " + model3_name)
|
210 |
+
print("checkpoint_dir is : " + checkpoint_dir)
|
211 |
+
|
212 |
+
|
213 |
+
|
214 |
+
|
215 |
+
#print("checkpoint2_dir is : " + checkpoint2_dir)
|
216 |
+
# print("checkpoint3_dir is : " + checkpoint3_dir)
|
217 |
+
print("-----------------------------------------")
|
218 |
+
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
|
219 |
+
#ckpt2 = tf.train.get_checkpoint_state(checkpoint2_dir)
|
220 |
+
# ckpt3 = tf.train.get_checkpoint_state(checkpoint3_dir)
|
221 |
+
ckpt_name = os.path.basename(ckpt.model_checkpoint_path)
|
222 |
+
|
223 |
+
found_model_checkpoint= get_padded_checkpoint_no_from_filename(ckpt_name)
|
224 |
+
|
225 |
+
#ckpt2_name = os.path.basename(ckpt2.model_checkpoint_path)
|
226 |
+
# ckpt3_name = os.path.basename(ckpt3.model_checkpoint_path)
|
227 |
+
saver.restore(sess, os.path.join(checkpoint_dir, ckpt_name))
|
228 |
+
#saver2.restore(sess2, os.path.join(checkpoint2_dir, ckpt2_name))
|
229 |
+
# saver3.restore(sess3, os.path.join(checkpoint3_dir, ckpt3_name))
|
230 |
+
m1 = dict(sess=sess, input_photo=input_photo, output_photo=output_photo)
|
231 |
+
#m2 = dict(sess=sess2, input_photo=input_photo, output_photo=output_photo)
|
232 |
+
# m3 = dict(sess=sess3, input_photo=input_photo, output_photo=output_photo)
|
233 |
+
models = type('', (), {})()
|
234 |
+
models.m1 = m1
|
235 |
+
#models.m2 = m2
|
236 |
+
# models.m3 = m3
|
237 |
+
return models
|
238 |
+
|
239 |
+
|
240 |
+
|
241 |
+
def make_target_output_filename( mname,checkpoint, fn='',res1=0,abc=0, ext='.jpg',svrtype="s1", modelid='', suffix='', xtra_model_id='',verbose=False):
|
242 |
+
fn_base=fn.replace(ext,"")
|
243 |
+
fn_base=fn_base.replace(".jpg","")
|
244 |
+
fn_base=fn_base.replace(".jpeg","")
|
245 |
+
fn_base=fn_base.replace(".JPG","")
|
246 |
+
fn_base=fn_base.replace(".JPEG","")
|
247 |
+
fn_base=fn_base.replace(".png","")
|
248 |
+
fn_base=fn_base.replace(".PNG","")
|
249 |
+
|
250 |
+
#pad res1 and res2 to 4 digits
|
251 |
+
res1_pad=str(res1).zfill(4)
|
252 |
+
|
253 |
+
abc_pad=str(abc).zfill(2)
|
254 |
+
if res1_pad=="0000":
|
255 |
+
res1_pad=""
|
256 |
+
|
257 |
+
|
258 |
+
#pad checkpoint to 3 digits
|
259 |
+
checkpoint=checkpoint.zfill(3)
|
260 |
+
|
261 |
+
if fn_base=="none":
|
262 |
+
fn_base=""
|
263 |
+
|
264 |
+
if '/' in fn_base:
|
265 |
+
fn_base=fn_base.split('/')[-1]
|
266 |
+
# Print out all input info:
|
267 |
+
if verbose :
|
268 |
+
|
269 |
+
print("-----------------------------")
|
270 |
+
print("fn_base: ",fn_base)
|
271 |
+
print("mname: ",mname)
|
272 |
+
print("suffix: ",suffix)
|
273 |
+
print("res1: ",res1_pad)
|
274 |
+
print("abc: ",abc_pad)
|
275 |
+
print("ext: ",ext)
|
276 |
+
print("svrtype: ",svrtype)
|
277 |
+
print("modelid: ",modelid)
|
278 |
+
print("xtra_model_id: ",xtra_model_id)
|
279 |
+
print("checkpoint: ",checkpoint)
|
280 |
+
print("fn: ",fn)
|
281 |
+
|
282 |
+
mtag = "{}__{}__{}x{}__{}__{}k".format(mname,suffix,res1_pad,abc_pad, svrtype, checkpoint).replace("_0x" + str(abc_pad), "")
|
283 |
+
if verbose:
|
284 |
+
print(mtag)
|
285 |
+
target_output = "{}__{}__{}{}{}".format(fn_base, modelid, mtag, xtra_model_id, ext).replace("_"+str(abc_pad)+"x"+str(abc_pad)+"_","").replace("_0x0_", "").replace("_0_", "").replace("_-", "_").replace("____", "__").replace("___", "__").replace("___", "__").replace("..",".").replace("model_","").replace("_x"+str(abc_pad)+"_","").replace("gia-ds-","")
|
286 |
+
target_output = replace_values_from_csv(target_output)
|
287 |
+
|
288 |
+
return target_output
|
289 |
+
|
290 |
+
def replace_values_from_csv(target_output):
|
291 |
+
# Implement the logic to replace values from CSV
|
292 |
+
#load replacer.csv and replace the values (src,dst)
|
293 |
+
src_dest_file = 'replacer.csv'
|
294 |
+
if os.path.exists(src_dest_file):
|
295 |
+
with open(src_dest_file, 'r') as file:
|
296 |
+
lines = file.readlines()
|
297 |
+
for line in lines:
|
298 |
+
src, dst = line.split(',')
|
299 |
+
target_output = target_output.replace(src, dst)
|
300 |
+
return target_output.replace("\n", "").replace("\r", "").replace(" ", "_")
|
301 |
+
|
302 |
+
|
303 |
+
def _make_meta_as_json(x1=0,c1=0,inp=None,result_dict=None):
|
304 |
+
global found_model,found_model_checkpoint
|
305 |
+
fn='none'
|
306 |
+
if inp['fn'] != 'none':
|
307 |
+
fn=inp['fn']
|
308 |
+
ext='.jpg'
|
309 |
+
if inp['ext'] != '.jpg':
|
310 |
+
ext=inp['ext']
|
311 |
+
|
312 |
+
filename=make_target_output_filename(found_model,found_model_checkpoint,fn,x1,c1,ext,SRV_TYPE)
|
313 |
+
|
314 |
+
if result_dict is None:
|
315 |
+
json_return = {
|
316 |
+
"model": str(found_model),
|
317 |
+
"checkpoint": str(found_model_checkpoint),
|
318 |
+
"filename": str(filename)
|
319 |
+
}
|
320 |
+
return json_return
|
321 |
+
else: #support adding to the existing dict the data directly
|
322 |
+
result_dict['model']=str(found_model)
|
323 |
+
result_dict['checkpoint']=str(found_model_checkpoint)
|
324 |
+
result_dict['filename']=str(filename)
|
325 |
+
return result_dict
|
326 |
+
|
327 |
+
|
328 |
+
|
329 |
+
meta_inputs={'meta':text}
|
330 |
+
meta_outputs={'model':text,'filename':text,'checkpoint':text}
|
331 |
+
|
332 |
+
@runway.command('meta2', inputs=meta_inputs, outputs=meta_outputs)
|
333 |
+
def get_geta(models, inp):
|
334 |
+
global found_model,found_model_checkpoint
|
335 |
+
|
336 |
+
json_return = _make_meta_as_json()
|
337 |
+
# "files": "nothing yet"
|
338 |
+
print(json_return)
|
339 |
+
return json_return
|
340 |
+
|
341 |
+
|
342 |
+
|
343 |
+
@runway.command('meta', inputs=meta_inputs, outputs=meta_outputs)
|
344 |
+
def get_geta(models, inp):
|
345 |
+
global found_model,found_model_checkpoint
|
346 |
+
|
347 |
+
json_return = _make_meta_as_json(inp)
|
348 |
+
# "files": "nothing yet"
|
349 |
+
print(json_return)
|
350 |
+
return json_return
|
351 |
+
|
352 |
+
|
353 |
+
|
354 |
+
|
355 |
+
#@STCGoal add number or text to specify resolution of the three pass
|
356 |
+
inputs={'contentImage': runway.image,'x1':number(default=1024,min=24,max=18000),'c1':number(default=0,min=-99,max=99),'fn':text(default='none'),'ext':text(default='.jpg')}
|
357 |
+
outputs={'stylizedImage': runway.image,'totaltime':number,'x1': number,'c1':number,'model1name':text,'checkpoint':text,'filename':text,'model':text}
|
358 |
+
|
359 |
+
@runway.command('stylize', inputs=inputs, outputs=outputs)
|
360 |
+
def stylize(models, inp):
|
361 |
+
global found_model,found_model_checkpoint,model1name
|
362 |
+
start = time.time()
|
363 |
+
|
364 |
+
model = models.m1
|
365 |
+
#model2 = models.m2
|
366 |
+
# model3 = models.m3
|
367 |
+
|
368 |
+
#Getting our names back (even though I think we dont need)
|
369 |
+
#@STCIssue BUGGED
|
370 |
+
# m1name=models.m1.name
|
371 |
+
# m2name=models.m2.name
|
372 |
+
# m3name=models.m3.name
|
373 |
+
|
374 |
+
#get size from inputs rather than env
|
375 |
+
x1 = int(inp['x1'])
|
376 |
+
|
377 |
+
c1 = int(inp['c1'])
|
378 |
+
|
379 |
+
#
|
380 |
+
img = inp['contentImage']
|
381 |
+
img = np.array(img)
|
382 |
+
img = img / 127.5 - 1.
|
383 |
+
|
384 |
+
#@a Pass 1 RESIZE to 1368px the smaller side
|
385 |
+
image_size=pass1_image_size
|
386 |
+
image_size=x1
|
387 |
+
img_shape = img.shape[:2]
|
388 |
+
alpha = float(image_size) / float(min(img_shape))
|
389 |
+
#dtprint ("DEBUG::content.imgshape:" + str(tuple(img_shape)) + ", alpha:" + str(alpha))
|
390 |
+
|
391 |
+
try:
|
392 |
+
img = scipy.misc.imresize(img, size=alpha)
|
393 |
+
except:
|
394 |
+
pass
|
395 |
+
|
396 |
+
|
397 |
+
img = np.expand_dims(img, axis=0)
|
398 |
+
#@a INFERENCE PASS 1
|
399 |
+
dtprint("INFO:Pass1 inference starting")
|
400 |
+
img = model['sess'].run(model['output_photo'], feed_dict={model['input_photo']: img})
|
401 |
+
|
402 |
+
#
|
403 |
+
img = (img + 1.) * 127.5
|
404 |
+
img = img.astype('uint8')
|
405 |
+
img = img[0]
|
406 |
+
#dtprint("INFO:Upresing Pass1 for Pass 2 (STARTING) ")
|
407 |
+
|
408 |
+
#@a Pass 2 RESIZE to 1024px the smaller side
|
409 |
+
#image_size=pass2_image_size
|
410 |
+
#image_size=x2
|
411 |
+
#img_shape = img.shape[:2]
|
412 |
+
|
413 |
+
|
414 |
+
#alpha = float(image_size) / float(min(img_shape))
|
415 |
+
#dtprint ("DEBUG::pass1.imgshape:" + str(tuple(img_shape)) + ", alpha:" + str(alpha))
|
416 |
+
|
417 |
+
#img = scipy.misc.imresize(img, size=alpha)
|
418 |
+
#dtprint("INFO:Upresing Pass1 (DONE) ")
|
419 |
+
|
420 |
+
#Iteration 2
|
421 |
+
#img = np.array(img)
|
422 |
+
#img = img / 127.5 - 1.
|
423 |
+
#img = np.expand_dims(img, axis=0)
|
424 |
+
#@a INFERENCE PASS 2 using the same model
|
425 |
+
#dtprint("INFO:Pass2 inference (STARTING)")
|
426 |
+
#img = model['sess'].run(model['output_photo'], feed_dict={model['input_photo']: img})
|
427 |
+
#dtprint("INFO:Pass2 inference (DONE)")
|
428 |
+
#img = (img + 1.) * 127.5
|
429 |
+
#img = img.astype('uint8')
|
430 |
+
#img = img[0]
|
431 |
+
|
432 |
+
|
433 |
+
|
434 |
+
# #pass3
|
435 |
+
|
436 |
+
# #@a Pass 3 RESIZE to 2048px the smaller side
|
437 |
+
# image_size=pass3_image_size
|
438 |
+
# image_size=x3
|
439 |
+
# img_shape = img.shape[:2]
|
440 |
+
|
441 |
+
|
442 |
+
# alpha = float(image_size) / float(min(img_shape))
|
443 |
+
# dtprint ("DEBUG::pass2.imgshape:" + str(tuple(img_shape)) + ", alpha:" + str(alpha))
|
444 |
+
|
445 |
+
# img = scipy.misc.imresize(img, size=alpha)
|
446 |
+
# dtprint("INFO:Upresing Pass2 (DONE) ")
|
447 |
+
|
448 |
+
# #Iteration 3
|
449 |
+
# img = np.array(img)
|
450 |
+
# img = img / 127.5 - 1.
|
451 |
+
# img = np.expand_dims(img, axis=0)
|
452 |
+
# #@a INFERENCE PASS 3
|
453 |
+
# dtprint("INFO:Pass3 inference (STARTING)")
|
454 |
+
# img = model3['sess'].run(model3['output_photo'], feed_dict={model3['input_photo']: img})
|
455 |
+
# dtprint("INFO:Pass3 inference (DONE)")
|
456 |
+
# img = (img + 1.) * 127.5
|
457 |
+
# img = img.astype('uint8')
|
458 |
+
# img = img[0]
|
459 |
+
# #pass3
|
460 |
+
|
461 |
+
#dtprint("INFO:Composing done")
|
462 |
+
|
463 |
+
if c1 != 0 :
|
464 |
+
print('Auto Brightening images...' + str(c1))
|
465 |
+
img = img, alpha2, beta = automatic_brightness_and_contrast(img,c1)
|
466 |
+
|
467 |
+
stop = time.time()
|
468 |
+
totaltime = stop - start
|
469 |
+
print("The time of the run:", totaltime)
|
470 |
+
|
471 |
+
#if model1name UNNAMED, use found_model
|
472 |
+
if model1name == "UNNAMED":
|
473 |
+
model1name=found_model
|
474 |
+
|
475 |
+
include_meta_directly_in_result=True
|
476 |
+
|
477 |
+
|
478 |
+
if include_meta_directly_in_result:
|
479 |
+
result_dict = dict(stylizedImage=img,totaltime=totaltime,x1=x1,model1name=model1name,c1=c1)
|
480 |
+
result_dict = _make_meta_as_json(x1,c1,inp,result_dict)
|
481 |
+
else:
|
482 |
+
meta_data = _make_meta_as_json(x1,c1,inp)
|
483 |
+
result_dict = dict(stylizedImage=img,totaltime=totaltime,x1=x1,model1name=model1name,c1=c1,meta=meta_data)
|
484 |
+
|
485 |
+
return result_dict
|
486 |
+
|
487 |
+
|
488 |
+
|
489 |
+
def dtprint(msg):
|
490 |
+
dttag=getdttag()
|
491 |
+
print(dttag + "::" + msg )
|
492 |
+
|
493 |
+
def getdttag():
|
494 |
+
# datetime object containing current date and time
|
495 |
+
now = datetime.now()
|
496 |
+
|
497 |
+
# dd/mm/YY H:M:S
|
498 |
+
# dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
|
499 |
+
return now.strftime("%H:%M:%S")
|
500 |
+
|
501 |
+
|
502 |
+
|
503 |
+
# Automatic brightness and contrast optimization with optional histogram clipping
|
504 |
+
def automatic_brightness_and_contrast(image, clip_hist_percent=25):
|
505 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
506 |
+
|
507 |
+
# Calculate grayscale histogram
|
508 |
+
hist = cv2.calcHist([gray],[0],None,[256],[0,256])
|
509 |
+
hist_size = len(hist)
|
510 |
+
|
511 |
+
# Calculate cumulative distribution from the histogram
|
512 |
+
accumulator = []
|
513 |
+
accumulator.append(float(hist[0]))
|
514 |
+
for index in range(1, hist_size):
|
515 |
+
accumulator.append(accumulator[index -1] + float(hist[index]))
|
516 |
+
|
517 |
+
# Locate points to clip
|
518 |
+
maximum = accumulator[-1]
|
519 |
+
clip_hist_percent *= (maximum/100.0)
|
520 |
+
clip_hist_percent /= 2.0
|
521 |
+
|
522 |
+
# Locate left cut
|
523 |
+
minimum_gray = 0
|
524 |
+
while accumulator[minimum_gray] < clip_hist_percent:
|
525 |
+
minimum_gray += 1
|
526 |
+
|
527 |
+
# Locate right cut
|
528 |
+
maximum_gray = hist_size -1
|
529 |
+
while accumulator[maximum_gray] >= (maximum - clip_hist_percent):
|
530 |
+
maximum_gray -= 1
|
531 |
+
|
532 |
+
# Calculate alpha and beta values
|
533 |
+
alpha = 255 / (maximum_gray - minimum_gray)
|
534 |
+
beta = -minimum_gray * alpha
|
535 |
+
|
536 |
+
'''
|
537 |
+
# Calculate new histogram with desired range and show histogram
|
538 |
+
new_hist = cv2.calcHist([gray],[0],None,[256],[minimum_gray,maximum_gray])
|
539 |
+
plt.plot(hist)
|
540 |
+
plt.plot(new_hist)
|
541 |
+
plt.xlim([0,256])
|
542 |
+
plt.show()
|
543 |
+
'''
|
544 |
+
|
545 |
+
auto_result = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
|
546 |
+
return (auto_result, alpha, beta)
|
547 |
+
|
548 |
+
|
549 |
+
if __name__ == '__main__':
|
550 |
+
#print('External Service port is:' +os.environ.get('SPORT'))
|
551 |
+
os.environ["RW_PORT"] = "7860"
|
552 |
+
print("Launched...")
|
553 |
+
runway.run()
|
requirements.txt
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
absl-py
|
2 |
+
asn1crypto
|
3 |
+
astor
|
4 |
+
backports.weakref
|
5 |
+
Brotli
|
6 |
+
certifi
|
7 |
+
cffi
|
8 |
+
chardet
|
9 |
+
click
|
10 |
+
colorcet
|
11 |
+
conda
|
12 |
+
conda-package-handling
|
13 |
+
cryptography
|
14 |
+
enum34
|
15 |
+
Flask
|
16 |
+
Flask-Compress
|
17 |
+
Flask-Cors
|
18 |
+
Flask-Sockets
|
19 |
+
funcsigs
|
20 |
+
functools32
|
21 |
+
futures
|
22 |
+
gast
|
23 |
+
gevent
|
24 |
+
gevent-websocket
|
25 |
+
google-pasta
|
26 |
+
greenlet
|
27 |
+
grpcio
|
28 |
+
h5py
|
29 |
+
idna
|
30 |
+
ipaddress
|
31 |
+
itsdangerous
|
32 |
+
Jinja2
|
33 |
+
Keras-Applications
|
34 |
+
Keras-Preprocessing
|
35 |
+
Markdown
|
36 |
+
MarkupSafe
|
37 |
+
mock
|
38 |
+
numpy
|
39 |
+
opencv-python
|
40 |
+
opt-einsum
|
41 |
+
packaging
|
42 |
+
param
|
43 |
+
Pillow
|
44 |
+
protobuf
|
45 |
+
pycosat
|
46 |
+
pycparser
|
47 |
+
pycrypto
|
48 |
+
pyct
|
49 |
+
pyOpenSSL
|
50 |
+
pyparsing
|
51 |
+
PySocks
|
52 |
+
PyYAML
|
53 |
+
requests
|
54 |
+
runway-model-runner
|
55 |
+
runway-python
|
56 |
+
scipy
|
57 |
+
six
|
58 |
+
tensorboard
|
59 |
+
tensorflow
|
60 |
+
tensorflow-estimator
|
61 |
+
termcolor
|
62 |
+
tqdm
|
63 |
+
Unidecode
|
64 |
+
urllib3
|
65 |
+
Werkzeug
|
66 |
+
wget
|
67 |
+
wrapt
|
68 |
+
zope.event
|
69 |
+
zope.interface
|
server.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
import tensorflow as tf
|
4 |
+
from module import encoder, decoder
|
5 |
+
from glob import glob
|
6 |
+
import runway
|
7 |
+
|
8 |
+
|
9 |
+
@runway.setup(options={"styleCheckpoint": runway.file(is_directory=True)})
|
10 |
+
def setup(opts):
|
11 |
+
sess = tf.Session()
|
12 |
+
init_op = tf.global_variables_initializer()
|
13 |
+
sess.run(init_op)
|
14 |
+
with tf.name_scope("placeholder"):
|
15 |
+
input_photo = tf.placeholder(
|
16 |
+
dtype=tf.float32, shape=[1, None, None, 3], name="photo"
|
17 |
+
)
|
18 |
+
input_photo_features = encoder(
|
19 |
+
image=input_photo, options={"gf_dim": 32}, reuse=False
|
20 |
+
)
|
21 |
+
output_photo = decoder(
|
22 |
+
features=input_photo_features, options={"gf_dim": 32}, reuse=False
|
23 |
+
)
|
24 |
+
saver = tf.train.Saver()
|
25 |
+
path = opts["styleCheckpoint"]
|
26 |
+
model_name = [p for p in os.listdir(path) if os.path.isdir(os.path.join(path, p))][
|
27 |
+
0
|
28 |
+
]
|
29 |
+
checkpoint_dir = os.path.join(path, model_name, "checkpoint_long")
|
30 |
+
ckpt = tf.train.get_checkpoint_state(checkpoint_dir)
|
31 |
+
ckpt_name = os.path.basename(ckpt.model_checkpoint_path)
|
32 |
+
saver.restore(sess, os.path.join(checkpoint_dir, ckpt_name))
|
33 |
+
return dict(sess=sess, input_photo=input_photo, output_photo=output_photo)
|
34 |
+
|
35 |
+
|
36 |
+
@runway.command(
|
37 |
+
"stylize",
|
38 |
+
inputs={"contentImage": runway.image},
|
39 |
+
outputs={"stylizedImage": runway.image},
|
40 |
+
)
|
41 |
+
def stylize(model, inp):
|
42 |
+
img = inp["contentImage"]
|
43 |
+
img = np.array(img)
|
44 |
+
img = img / 127.5 - 1.0
|
45 |
+
img = np.expand_dims(img, axis=0)
|
46 |
+
img = model["sess"].run(
|
47 |
+
model["output_photo"], feed_dict={model["input_photo"]: img}
|
48 |
+
)
|
49 |
+
img = (img + 1.0) * 127.5
|
50 |
+
img = img.astype("uint8")
|
51 |
+
img = img[0]
|
52 |
+
return dict(stylizedImage=img)
|
53 |
+
|
54 |
+
|
55 |
+
if __name__ == "__main__":
|
56 |
+
#print("External Service port is:" + os.environ.get("SPORT",7860))
|
57 |
+
#set env var: RW_PORT=7860
|
58 |
+
os.environ["RW_PORT"] = "7860"
|
59 |
+
runway.run()
|