thejagstudio commited on
Commit
7cbb4c7
·
verified ·
1 Parent(s): b55c177

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +386 -2
main.py CHANGED
@@ -1,2 +1,386 @@
1
- import os
2
- exec(os.environ.get('CODE'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask,jsonify,request,send_file, render_template
2
+ from flask_cors import CORS, cross_origin
3
+ import requests
4
+ import json
5
+ from io import BytesIO
6
+ import base64
7
+
8
+ from transformers import SegformerImageProcessor, TFSegformerForSemanticSegmentation
9
+ from PIL import Image,ImageFilter,ImageEnhance
10
+ import matplotlib.pyplot as plt
11
+ import tensorflow as tf
12
+ import numpy as np
13
+
14
+ processor = SegformerImageProcessor.from_pretrained("mattmdjaga/segformer_b2_clothes")
15
+ model = TFSegformerForSemanticSegmentation.from_pretrained("mattmdjaga/segformer_b2_clothes")
16
+
17
+
18
+ app = Flask(__name__)
19
+ cors = CORS(app)
20
+ app.config['CORS_HEADERS'] = 'Content-Type'
21
+
22
+ def ade_palette():
23
+ return [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[255,255,255],[255,255,255],[255,255,255],[255,255,255],[255,255,255],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[255,255,255]]
24
+
25
+ colormap = np.asarray(ade_palette())
26
+
27
+
28
+ @app.route('/api/v1/sdxl/generate', methods=['post'])
29
+ def generator():
30
+ try:
31
+ data = request.get_json()
32
+ cameraAngle = data["cameraAngle"]
33
+ age = data["age"]
34
+ base = data["base"]
35
+ expression = data["expression"]
36
+ bodyType = data["bodyType"]
37
+ style = data["style"]
38
+ action = data["action"]
39
+ boobs = data["boobs"]
40
+ ass = data["ass"]
41
+ clothing = data["clothing"]
42
+ hairStyle = data["hairStyle"]
43
+ quality = data["quality"]
44
+ clothingColor = data["clothingColor"]
45
+ clothingType = data["clothingType"]
46
+ clothingMaterial = data["clothingMaterial"]
47
+ clothingPattern = data["clothingPattern"]
48
+ lighting = data["lighting"]
49
+ setting = data["setting"]
50
+ background = data["background"]
51
+ seed = int(data["seed"])
52
+
53
+ url = "https://api.prodia.com/v1/sdxl/generate"
54
+
55
+ prompt ="A "+cameraAngle+" portrait of a "+age+" "+base+" with a "+expression+" and "+bodyType+" body, "+action+", "+boobs+" boobs, "+ass+" ass, "+clothing+", "+hairStyle+" hair, "+quality+" quality, "+clothingColor+" "+clothingType+", "+clothingMaterial+" with "+clothingPattern+", "+lighting+" in "+setting+" with "+background+" in background"
56
+ model = "dreamshaperXL10_alpha2.safetensors [c8afe2ef]"
57
+ if style == "photographic":
58
+ model = "juggernautXL_v45.safetensors [e75f5471]"
59
+ # model = "sd_xl_base_1.0.safetensors [be9edd61]"
60
+
61
+ payload = {
62
+ "model": model,
63
+ "prompt": prompt,
64
+ "seed": seed,
65
+ "cfg_scale": 15,
66
+ }
67
+ if style != "":
68
+ payload["style_preset"] = style
69
+ payload = json.dumps(payload)
70
+ headers = {
71
+ 'X-Prodia-Key': 'f2c81250-a5d8-461e-9caa-9fdb5abb5b60',
72
+ 'accept': 'application/json',
73
+ 'content-type': 'application/json'
74
+ }
75
+
76
+ response = requests.request("POST", url, headers=headers, data=payload)
77
+ try:
78
+ job = response.json()
79
+ return jsonify(job)
80
+ except Exception as e:
81
+ return jsonify(error=response.text,source="generator")
82
+ except Exception as e:
83
+ return jsonify(error=str(e),source="server")
84
+
85
+ @app.route('/api/v1/image/<jobId>', methods=['get'])
86
+ def image(jobId):
87
+ try:
88
+ url = "https://api.prodia.com/v1/job/"+ jobId.split(".")[0]
89
+
90
+ headers = {
91
+ 'X-Prodia-Key': 'f2c81250-a5d8-461e-9caa-9fdb5abb5b60',
92
+ 'accept': 'application/json'
93
+ }
94
+
95
+ responseImg = requests.request("GET", url, headers=headers)
96
+ if responseImg.json()["status"] == "succeeded":
97
+
98
+ url = "https://images.prodia.xyz/"+jobId
99
+ headers = {
100
+ 'accept': 'image/png'
101
+ }
102
+ response = requests.request("GET", url, headers=headers)
103
+ responseMain = app.response_class(
104
+ response=response.content,
105
+ status=200,
106
+ mimetype='image/png'
107
+ )
108
+ return responseMain
109
+ elif responseImg.json()["status"] == "failed":
110
+ url = "https://www.elegantthemes.com/blog/wp-content/uploads/2020/08/000-http-error-codes.png"
111
+ headers = {
112
+ 'accept': 'image/png'
113
+ }
114
+ response = requests.request("GET", url, headers=headers)
115
+ responseMain = app.response_class(
116
+ response=response.content,
117
+ status=200,
118
+ mimetype='image/png'
119
+ )
120
+ return responseMain
121
+ else:
122
+ return jsonify(responseImg.json())
123
+ except Exception as e:
124
+ return jsonify(error=str(e),source="server")
125
+
126
+ @app.route('/api/v1/nudify', methods=['post'])
127
+ def nudify():
128
+ global model,processor
129
+ try:
130
+ data = request.get_json()
131
+ if "/" not in data["image"]:
132
+ url = "https://images.prodia.xyz/"+ data["image"]
133
+ else:
134
+ url = data["image"]
135
+ cameraAngle = data["cameraAngle"]
136
+ age = data["age"]
137
+ base = data["base"]
138
+ expression = data["expression"]
139
+ bodyType = data["bodyType"]
140
+ style = data["style"]
141
+ action = data["action"]
142
+ boobs = data["boobs"]
143
+ ass = data["ass"]
144
+ clothing = data["clothing"]
145
+ hairStyle = data["hairStyle"]
146
+ quality = data["quality"]
147
+ clothingColor = data["clothingColor"]
148
+ clothingType = data["clothingType"]
149
+ clothingMaterial = data["clothingMaterial"]
150
+ clothingPattern = data["clothingPattern"]
151
+ lighting = data["lighting"]
152
+ setting = data["setting"]
153
+ background = data["background"]
154
+ seed = int(data["seed"])
155
+
156
+ prompt ="A "+cameraAngle+" angle full naked portrait of a "+age+" aged "+base+" with a "+bodyType+" body naked, "+action+", "+boobs+" boobs, "+ass+" ass, nude, naked, nsfw"
157
+ modelGen = "v1-5-inpainting.safetensors [21c7ab71]"
158
+ # modelGen = "sd_xl_base_1.0_inpainting_0.1.safetensors [5679a81a]"
159
+
160
+ input_img = Image.open(requests.get(url,stream=True).raw)
161
+ # input_img.save("input.png")
162
+ inputs = processor(images=input_img,return_tensors="tf")
163
+ outputs = model(**inputs)
164
+ logits = outputs.logits
165
+
166
+ # upsampled_logits = nn.functional.interpolate(
167
+ # logits,
168
+ # size=input_img.size[::-1],
169
+ # mode="bilinear",
170
+ # align_corners=False,
171
+ # )
172
+
173
+ # seg = upsampled_logits.argmax(dim=1)[0]
174
+ logits = tf.transpose(logits, [0, 2, 3, 1])
175
+ logits = tf.image.resize(
176
+ logits, input_img.size[::-1]
177
+ ) # We reverse the shape of `image` because `image.size` returns width and height.
178
+ seg = tf.math.argmax(logits, axis=-1)[0]
179
+
180
+ color_seg = np.zeros(
181
+ (seg.shape[0], seg.shape[1], 3), dtype=np.uint8
182
+ ) # height, width, 3
183
+ for label, color in enumerate(colormap):
184
+ color_seg[seg.numpy() == label, :] = color
185
+
186
+ # Show image + mask
187
+ pred_img = color_seg * 1
188
+ pred_img = pred_img.astype(np.uint8)
189
+
190
+ imgOut = Image.fromarray(pred_img)
191
+ # blur the mask
192
+ imgOut = imgOut.filter(ImageFilter.GaussianBlur(16))
193
+ imgOut = imgOut.convert("L")
194
+ # Apply thresholding to sharpen the image
195
+ threshold = 20
196
+ imgOut = imgOut.point(lambda p: p > threshold and 255)
197
+
198
+ # Enhance the sharpness of the image
199
+ enhancer = ImageEnhance.Sharpness(imgOut)
200
+ imgOut = enhancer.enhance(2.0)
201
+ imgOut = imgOut.filter(ImageFilter.GaussianBlur(8))
202
+ imgOut = imgOut.convert("RGB")
203
+
204
+ # imgOut.save("mask.png")
205
+ buffered = BytesIO()
206
+ imgOut.save(buffered, format="png")
207
+ base64_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
208
+
209
+ url2 = "https://api.prodia.com/v1/sd/inpainting"
210
+
211
+ payload = json.dumps({
212
+ "inpainting_full_res": False,
213
+ "imageUrl": url,
214
+ "maskData": base64_str,
215
+ "model": modelGen,
216
+ "prompt": prompt,
217
+ "negative_prompt": "bad anatomy, bad hands, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, worst face, three crus, extra crus, fused crus, worst feet, three feet, fused feet, fused thigh, three thigh, fused thigh, extra thigh, worst thigh, missing fingers, extra fingers, ugly fingers, long fingers, horn, extra eyes, huge eyes, 2girl, amputation, disconnected limbs",
218
+ "denoising_strength": 0.9,
219
+ "cfg_scale": 7,
220
+ "mask_blur": 4,
221
+ "inpainting_fill": 2,
222
+ "inpainting_mask_invert": 0,
223
+ "seed": seed,
224
+ "style_preset" : style,
225
+ "upscale": True
226
+ })
227
+ headers = {
228
+ 'X-Prodia-Key': 'f2c81250-a5d8-461e-9caa-9fdb5abb5b60',
229
+ 'accept': 'application/json',
230
+ 'content-type': 'application/json'
231
+ }
232
+
233
+ response = requests.request("POST", url2, headers=headers, data=payload)
234
+
235
+ try:
236
+ job = response.json()
237
+ return jsonify(job)
238
+ except Exception as e:
239
+ return jsonify(error=response.text,source="generator")
240
+ except Exception as e:
241
+ return jsonify(error=str(e),source="server")
242
+
243
+ @app.route('/api/v1/clotheChanger', methods=['post'])
244
+ def clotheChanger():
245
+ global model,processor
246
+ try:
247
+ data = request.get_json()
248
+ if "/" not in data["image"]:
249
+ url = "https://images.prodia.xyz/"+ data["image"]
250
+ else:
251
+ url = data["image"]
252
+ cameraAngle = data["cameraAngle"]
253
+ age = data["age"]
254
+ base = data["base"]
255
+ expression = data["expression"]
256
+ bodyType = data["bodyType"]
257
+ style = data["style"]
258
+ action = data["action"]
259
+ boobs = data["boobs"]
260
+ ass = data["ass"]
261
+ clothing = data["clothing"]
262
+ hairStyle = data["hairStyle"]
263
+ quality = data["quality"]
264
+ clothingColor = data["clothingColor"]
265
+ clothingType = data["clothingType"]
266
+ clothingMaterial = data["clothingMaterial"]
267
+ clothingPattern = data["clothingPattern"]
268
+ lighting = data["lighting"]
269
+ setting = data["setting"]
270
+ background = data["background"]
271
+ seed = int(data["seed"])
272
+
273
+ prompt ="A "+cameraAngle+" portrait of a "+age+" "+base+" with a "+expression+" and "+bodyType+" body, "+action+", "+boobs+" boobs, "+ass+" ass, "+clothing+", "+hairStyle+" hair, "+quality+" quality, "+clothingColor+" "+clothingType+", "+clothingMaterial+" with "+clothingPattern+", "+lighting+" in "+setting+" with "+background+" in background"
274
+ modelGen = "sd_xl_base_1.0_inpainting_0.1.safetensors [5679a81a]"
275
+
276
+ input_img = Image.open(requests.get(url,stream=True).raw)
277
+ inputs = processor(images=input_img,return_tensors="tf")
278
+ outputs = model(**inputs)
279
+ logits = outputs.logits
280
+
281
+ logits = tf.transpose(logits, [0, 2, 3, 1])
282
+ logits = tf.image.resize(
283
+ logits, input_img.size[::-1]
284
+ ) # We reverse the shape of `image` because `image.size` returns width and height.
285
+ seg = tf.math.argmax(logits, axis=-1)[0]
286
+
287
+ color_seg = np.zeros(
288
+ (seg.shape[0], seg.shape[1], 3), dtype=np.uint8
289
+ ) # height, width, 3
290
+ for label, color in enumerate(colormap):
291
+ color_seg[seg.numpy() == label, :] = color
292
+
293
+ # Show image + mask
294
+ pred_img = color_seg * 1
295
+ pred_img = pred_img.astype(np.uint8)
296
+
297
+ imgOut = Image.fromarray(pred_img)
298
+ # blur the mask
299
+ imgOut = imgOut.filter(ImageFilter.GaussianBlur(16))
300
+ imgOut = imgOut.convert("L")
301
+ # Apply thresholding to sharpen the image
302
+ threshold = 20
303
+ imgOut = imgOut.point(lambda p: p > threshold and 255)
304
+
305
+ # Enhance the sharpness of the image
306
+ enhancer = ImageEnhance.Sharpness(imgOut)
307
+ imgOut = enhancer.enhance(2.0)
308
+ imgOut = imgOut.filter(ImageFilter.GaussianBlur(8))
309
+ imgOut = imgOut.convert("RGB")
310
+
311
+ imgOut.save("mask.png")
312
+ buffered = BytesIO()
313
+ imgOut.save(buffered, format="png")
314
+ base64_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
315
+
316
+ url2 = "https://api.prodia.com/v1/sdxl/inpainting"
317
+
318
+ payload = json.dumps({
319
+ "inpainting_full_res": False,
320
+ "imageUrl": url,
321
+ "maskData": base64_str,
322
+ "model": modelGen,
323
+ "prompt": prompt,
324
+ "negative_prompt": "bad anatomy, bad hands, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, worst face, three crus, extra crus, fused crus, worst feet, three feet, fused feet, fused thigh, three thigh, fused thigh, extra thigh, worst thigh, missing fingers, extra fingers, ugly fingers, long fingers, horn, extra eyes, huge eyes, 2girl, amputation, disconnected limbs",
325
+ "denoising_strength": 0.9,
326
+ "cfg_scale": 7,
327
+ "mask_blur": 4,
328
+ "inpainting_fill": 2,
329
+ "inpainting_mask_invert": 0,
330
+ "seed": seed,
331
+ "style_preset" : style
332
+ })
333
+ headers = {
334
+ 'X-Prodia-Key': 'f2c81250-a5d8-461e-9caa-9fdb5abb5b60',
335
+ 'accept': 'application/json',
336
+ 'content-type': 'application/json'
337
+ }
338
+
339
+ response = requests.request("POST", url2, headers=headers, data=payload)
340
+
341
+ try:
342
+ job = response.json()
343
+ return jsonify(job)
344
+ except Exception as e:
345
+ return jsonify(error=response.text,source="generator")
346
+ except Exception as e:
347
+ return jsonify(error=str(e),source="server")
348
+
349
+ @app.route('/api/v1/upscale', methods=['post'])
350
+ def upscale():
351
+ try:
352
+ data = request.get_json()
353
+ if "/" not in data["image"]:
354
+ imgUrl = "https://images.prodia.xyz/"+ data["image"]
355
+ else:
356
+ imgUrl = data["image"]
357
+ url = "https://api.prodia.com/v1/upscale"
358
+ headers = {
359
+ 'X-Prodia-Key': 'f2c81250-a5d8-461e-9caa-9fdb5abb5b60',
360
+ 'accept': 'application/json',
361
+ 'content-type': 'application/json',
362
+ }
363
+ payload = json.dumps({
364
+ "resize": 4,
365
+ "model": "ESRGAN_4x",
366
+ "imageUrl": imgUrl
367
+ })
368
+ response = requests.request("POST", url, headers=headers, data=payload)
369
+ try:
370
+ job = response.json()
371
+ return jsonify(job)
372
+ except Exception as e:
373
+ return jsonify(error=response.text,source="generator")
374
+ except Exception as e:
375
+ return jsonify(error=str(e),source="server")
376
+
377
+ @app.route('/', methods=['get'])
378
+ def home():
379
+ return render_template("index.html")
380
+ @app.route('/generator', methods=['get'])
381
+ def generatorPage():
382
+ return render_template("index.html")
383
+
384
+
385
+ app.run(debug=True, host="0.0.0.0",port=7860)
386
+ # app.run(debug=True, host="127.0.0.1",port=8000)