/
serve
executable file
·308 lines (246 loc) · 10.1 KB
/
serve
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
#!/usr/bin/env python3
from share import *
import config
import cv2
import einops
import numpy as np
import torch
import random, logging, json, base64, boto3, uuid, zipfile, urllib
from botocore.exceptions import ClientError
from io import BytesIO
from PIL import Image, ImageOps
import gc
from flask import Flask
from flask import Response
from flask import request
from pytorch_lightning import seed_everything
from annotator.util import HWC3
from annotator.canny import CannyDetector
from cldm.model import create_model, load_state_dict
from cldm.ddim_hacked import DDIMSampler
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)
class Predictor:
def __init__(self, config_path, weight_path):
self.apply_canny = CannyDetector()
model = create_model(str(config_path)).cpu()
model.load_state_dict(load_state_dict(str(weight_path), location='cuda'))
self.model = model.cuda()
logging.info("Model loaded")
self.ddim_sampler = DDIMSampler(self.model)
logging.info("DDIM sampler loaded")
with open('prompts.txt', 'r') as f:
prompts = f.readlines()
self.prompts = [p.strip() for p in prompts]
#self.prompts = random.sample(self.prompts, 3)
logging.info(f"Running with {len(self.prompts)} prompts")
def gen(self,
img,
num_samples,
a_prompt='',
n_prompt='',
ddim_steps=20,
guess_mode=False,
strength=1.0,
low_threshold=100,
high_threshold=200,
scale=9.0,
seed=-1,
eta=0.0):
for i, prompt in enumerate(self.prompts):
logging.info(f"Processing prompt N {i}: {prompt}")
yield self.process(img=img,
prompt=prompt,
a_prompt=a_prompt,
n_prompt=n_prompt,
num_samples=num_samples,
ddim_steps=ddim_steps,
guess_mode=guess_mode,
strength=strength,
low_threshold=low_threshold,
high_threshold=high_threshold,
scale=scale,
seed=seed,
eta=eta)
def process(self,
img: np.ndarray,
prompt: str,
a_prompt='',
n_prompt='',
num_samples=1,
ddim_steps=20,
guess_mode=False,
strength=1.0,
low_threshold=100,
high_threshold=200,
scale=9.0,
seed=42,
eta=0.0):
logging.info(f"Processing with seed: {seed}")
config.save_memory = True
with torch.no_grad():
H, W, _ = img.shape
detected_map = self.apply_canny(img, low_threshold, high_threshold)
detected_map = HWC3(detected_map)
logging.info(f"Edges detected with Canny on img size {H}x{W}")
control = torch.from_numpy(detected_map.copy()).float().cuda() / 255.0
control = torch.stack([control for _ in range(num_samples)], dim=0)
control = einops.rearrange(control, 'b h w c -> b c h w').clone()
if seed == -1:
seed = random.randint(0, 65535)
seed_everything(seed)
if config.save_memory:
self.model.low_vram_shift(is_diffusing=False)
cond = {"c_concat": [control], "c_crossattn": [self.model.get_learned_conditioning([prompt + ', ' + a_prompt] * num_samples)]}
un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [self.model.get_learned_conditioning([n_prompt] * num_samples)]}
shape = (4, H // 8, W // 8)
if config.save_memory:
self.model.low_vram_shift(is_diffusing=True)
self.model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13) # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
samples, _ = self.ddim_sampler.sample(ddim_steps, num_samples,
shape, cond, verbose=False, eta=eta,
unconditional_guidance_scale=scale,
unconditional_conditioning=un_cond)
logging.info("ControlNet samples generated")
if config.save_memory:
self.model.low_vram_shift(is_diffusing=False)
x_samples = self.model.decode_first_stage(samples)
x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
results = [x_samples[i] for i in range(num_samples)]
del samples, x_samples, control, cond, un_cond, detected_map
torch.cuda.empty_cache()
return results
def resize_image(input_image, resolution):
H, W, C = input_image.shape
H = float(H)
W = float(W)
max_HW = max(H, W)
k = float(resolution) / max_HW
H *= k
W *= k
H = int(np.round(H / 64.0)) * 64
W = int(np.round(W / 64.0)) * 64
img = cv2.resize(input_image, (W, H), interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA)
return img
def parse_request(req: request):
content = req.get_json()
img_id = content['img_id']
parsed_url = urllib.parse.urlparse(img_id)
bucket = parsed_url.netloc
key = parsed_url.path[1:]
obj = S3.get_object(Bucket=bucket, Key=key)
img = Image.open(BytesIO(obj['Body'].read())).convert('RGB')
img = ImageOps.exif_transpose(img)
img = np.array(img)
logging.info(f"Image loaded from {img_id} with size {img.shape}")
img = resize_image(HWC3(img), 768)
email = content['email']
s3_location = content['s3_location']
logging.info(f"Processing image of size {img.shape} for {email} and save results to {s3_location}")
logging.info(f"Image resized to {img.shape}")
return img, email, s3_location
def upload_to_s3(img, s3_location):
sm_key = f"{s3_location}/{uuid.uuid4().hex}.jpeg"
img = cv2.imencode('.png', img)[1].tobytes()
S3.put_object(
Bucket=SM_BUCKET,
Key=sm_key,
Body=img
)
logging.info(f"Uploaded image to s3://{SM_BUCKET}/{sm_key}")
return f"s3://{SM_BUCKET}/{sm_key}"
def zip_images(s3_key_prefix):
zip_file_name = f"{uuid.uuid4().hex}.zip"
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, mode='w') as zip_file:
for s3_object in S3.list_objects(Bucket=SM_BUCKET, Prefix=s3_key_prefix)['Contents']:
if not s3_object['Key'].endswith('.jpeg'):
continue
file_content = S3.get_object(Bucket=SM_BUCKET, Key=s3_object['Key'])['Body'].read()
zip_file.writestr(f"logo/{s3_object['Key'].split('/')[-1]}", file_content)
zip_buffer.seek(0)
with open(zip_file_name, 'wb') as f:
f.write(zip_buffer.getvalue())
zip_key = f"{'/'.join(s3_object['Key'].split('/')[:-1])}/{zip_file_name}"
S3.upload_file(zip_file_name, SM_BUCKET, zip_key)
S3.upload_file(zip_file_name, SM_BUCKET, f"zipped/{zip_file_name}")
logging.info(f"Uploaded zip file to s3://{SM_BUCKET}/{zip_key}")
return f"https://s3-eu-west-1.amazonaws.com/{SM_BUCKET}/zipped/{zip_file_name}"
def send_email_to_user(recipient, zip_file_url):
BODY_HTML = f"""
<html>
<head></head>
<body>
<h4>Our AI artists finished crunching your logo!</h4>
<p>
We asked them to be as creative as possible, and the results are really cool!
<br>
You can download your custom logos <a href="{zip_file_url}">here</a>.
<br>
</p>
</body>
</html>
"""
# Try to send the email.
try:
#Provide the contents of the email.
response = SES.send_email(
Destination={
'ToAddresses': [
recipient,
],
},
Message={
'Body': {
'Html': {
'Charset': CHARSET,
'Data': BODY_HTML,
},
'Text': {
'Charset': CHARSET,
'Data': BODY_TEXT,
},
},
'Subject': {
'Charset': CHARSET,
'Data': SUBJECT,
},
},
Source=SENDER,
)
except ClientError as e:
logging.info(e.response['Error']['Message'])
else:
logging.info(f"Email sent! Message ID:{response['MessageId']}")
return
app = Flask(__name__)
PREDICTOR = Predictor('./models/cldm_v15.yaml', './models/control_sd15_canny.pth')
S3 = boto3.client('s3')
SM_BUCKET = "visualneurons.com-logos-outputs"
SENDER = "fra.pochetti@gmail.com"
CHARSET = "UTF-8"
SES = boto3.client('ses', region_name="eu-west-1")
SUBJECT = "VisualNeurons.com - your personalised logos are ready!"
BODY_TEXT = ("VisualNeurons.com - your personalised logos are ready! \r\n"
"Our AI artists finished crunching your image, and are quite pleased with the result. \r\n"
"You can find your custom logos via the provided link."
""
)
@app.route("/invocations", methods=["POST"])
def predict():
input_image, recipient, s3_location = parse_request(request)
logging.info("Image loaded. Processing...")
out_gen = PREDICTOR.gen(img=input_image, num_samples=1)
for res in out_gen:
for img in res:
upload_to_s3(img, s3_location)
zip_file_name = zip_images(s3_location)
logging.info(f"Zipped images to {zip_file_name}")
send_email_to_user(recipient, zip_file_name)
del out_gen, res, img, input_image
torch.cuda.empty_cache()
gc.collect()
return Response(response="Done", status=200)
@app.route("/ping")
def ping(): return Response(response="OK", status=200)
app.run(host="0.0.0.0", port=8080)