Update app.py
Browse files
app.py
CHANGED
@@ -1,43 +1,35 @@
|
|
1 |
-
|
2 |
-
import os
|
3 |
-
from flask import Flask, request, jsonify,send_file
|
4 |
-
from PIL import Image
|
5 |
-
from io import BytesIO
|
6 |
import torch
|
7 |
-
import base64
|
8 |
-
import io
|
9 |
-
import logging
|
10 |
-
import gradio as gr
|
11 |
-
import numpy as np
|
12 |
-
import spaces
|
13 |
-
import uuid
|
14 |
-
import random
|
15 |
-
from src.tryon_pipeline import StableDiffusionXLInpaintPipeline as TryonPipeline
|
16 |
-
from src.unet_hacked_garmnet import UNet2DConditionModel as UNet2DConditionModel_ref
|
17 |
-
from src.unet_hacked_tryon import UNet2DConditionModel
|
18 |
from transformers import (
|
19 |
-
|
20 |
-
|
21 |
CLIPTextModel,
|
22 |
CLIPTextModelWithProjection,
|
23 |
-
|
|
|
|
|
24 |
)
|
25 |
-
from
|
26 |
-
|
27 |
-
from
|
28 |
-
import apply_net
|
29 |
-
from preprocess.humanparsing.run_parsing import Parsing
|
30 |
-
from preprocess.openpose.run_openpose import OpenPose
|
31 |
-
from detectron2.data.detection_utils import convert_PIL_to_numpy, _apply_exif_orientation
|
32 |
-
from torchvision.transforms.functional import to_pil_image
|
33 |
|
34 |
app = Flask(__name__)
|
35 |
|
36 |
-
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
def load_models():
|
40 |
global unet, tokenizer_one, tokenizer_two, noise_scheduler, text_encoder_one, text_encoder_two, image_encoder, vae, UNet_Encoder
|
|
|
41 |
unet = UNet2DConditionModel.from_pretrained(base_path, subfolder="unet", torch_dtype=torch.float16, force_download=False)
|
42 |
tokenizer_one = AutoTokenizer.from_pretrained(base_path, subfolder="tokenizer", use_fast=False, force_download=False)
|
43 |
tokenizer_two = AutoTokenizer.from_pretrained(base_path, subfolder="tokenizer_2", use_fast=False, force_download=False)
|
@@ -48,328 +40,59 @@ def load_models():
|
|
48 |
vae = AutoencoderKL.from_pretrained(base_path, subfolder="vae", torch_dtype=torch.float16, force_download=False)
|
49 |
UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(base_path, subfolder="unet_encoder", torch_dtype=torch.float16, force_download=False)
|
50 |
|
|
|
51 |
load_models()
|
52 |
|
53 |
-
|
54 |
-
openpose_model = OpenPose(0)
|
55 |
-
|
56 |
-
UNet_Encoder.requires_grad_(False)
|
57 |
-
image_encoder.requires_grad_(False)
|
58 |
-
vae.requires_grad_(False)
|
59 |
-
unet.requires_grad_(False)
|
60 |
-
text_encoder_one.requires_grad_(False)
|
61 |
-
text_encoder_two.requires_grad_(False)
|
62 |
-
tensor_transfrom = transforms.Compose(
|
63 |
-
[
|
64 |
-
transforms.ToTensor(),
|
65 |
-
transforms.Normalize([0.5], [0.5]),
|
66 |
-
]
|
67 |
-
)
|
68 |
-
|
69 |
-
pipe = TryonPipeline.from_pretrained(
|
70 |
-
base_path,
|
71 |
-
unet=unet,
|
72 |
-
vae=vae,
|
73 |
-
feature_extractor= CLIPImageProcessor(),
|
74 |
-
text_encoder = text_encoder_one,
|
75 |
-
text_encoder_2 = text_encoder_two,
|
76 |
-
tokenizer = tokenizer_one,
|
77 |
-
tokenizer_2 = tokenizer_two,
|
78 |
-
scheduler = noise_scheduler,
|
79 |
-
image_encoder=image_encoder,
|
80 |
-
torch_dtype=torch.float16,
|
81 |
-
force_download=False
|
82 |
-
)
|
83 |
-
pipe.unet_encoder = UNet_Encoder
|
84 |
-
|
85 |
-
def pil_to_binary_mask(pil_image, threshold=0):
|
86 |
-
np_image = np.array(pil_image)
|
87 |
-
grayscale_image = Image.fromarray(np_image).convert("L")
|
88 |
-
binary_mask = np.array(grayscale_image) > threshold
|
89 |
-
mask = np.zeros(binary_mask.shape, dtype=np.uint8)
|
90 |
-
for i in range(binary_mask.shape[0]):
|
91 |
-
for j in range(binary_mask.shape[1]):
|
92 |
-
if binary_mask[i, j]:
|
93 |
-
mask[i, j] = 1
|
94 |
-
mask = (mask * 255).astype(np.uint8)
|
95 |
-
output_mask = Image.fromarray(mask)
|
96 |
-
return output_mask
|
97 |
-
|
98 |
-
def get_image_from_url(url):
|
99 |
-
try:
|
100 |
-
response = requests.get(url)
|
101 |
-
response.raise_for_status() # Vรฉrifie les erreurs HTTP
|
102 |
-
img = Image.open(BytesIO(response.content))
|
103 |
-
return img
|
104 |
-
except Exception as e:
|
105 |
-
logging.error(f"Error fetching image from URL: {e}")
|
106 |
-
raise
|
107 |
-
|
108 |
-
def decode_image_from_base64(base64_str):
|
109 |
-
try:
|
110 |
-
img_data = base64.b64decode(base64_str)
|
111 |
-
img = Image.open(BytesIO(img_data))
|
112 |
-
return img
|
113 |
-
except Exception as e:
|
114 |
-
logging.error(f"Error decoding image: {e}")
|
115 |
-
raise
|
116 |
-
|
117 |
-
def encode_image_to_base64(img):
|
118 |
-
try:
|
119 |
-
buffered = BytesIO()
|
120 |
-
img.save(buffered, format="PNG")
|
121 |
-
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
122 |
-
return img_str
|
123 |
-
except Exception as e:
|
124 |
-
logging.error(f"Error encoding image: {e}")
|
125 |
-
raise
|
126 |
-
|
127 |
-
def save_image(img):
|
128 |
-
unique_name = str(uuid.uuid4()) + ".webp"
|
129 |
-
img.save(unique_name, format="WEBP", lossless=True)
|
130 |
-
return unique_name
|
131 |
-
|
132 |
-
|
133 |
def clear_gpu_memory():
|
134 |
torch.cuda.empty_cache()
|
135 |
torch.cuda.synchronize()
|
136 |
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
top = (height - target_height) / 2
|
154 |
-
right = (width + target_width) / 2
|
155 |
-
bottom = (height + target_height) / 2
|
156 |
-
cropped_img = human_img_orig.crop((left, top, right, bottom))
|
157 |
-
crop_size = cropped_img.size
|
158 |
-
human_img = cropped_img.resize((512, 768))
|
159 |
-
else:
|
160 |
-
human_img = human_img_orig.resize((512, 768))
|
161 |
-
|
162 |
-
if is_checked:
|
163 |
-
keypoints = openpose_model(human_img.resize((384, 512)))
|
164 |
-
model_parse, _ = parsing_model(human_img.resize((384, 512)))
|
165 |
-
mask, mask_gray = get_mask_location('hd', categorie , model_parse, keypoints)
|
166 |
-
mask = mask.resize((768, 1024))
|
167 |
-
else:
|
168 |
-
mask = pil_to_binary_mask(dict['layers'][0].convert("RGB").resize((512, 768)))
|
169 |
-
mask_gray = (1 - transforms.ToTensor()(mask)) * tensor_transfrom(human_img)
|
170 |
-
mask_gray = to_pil_image((mask_gray + 1.0) / 2.0)
|
171 |
-
|
172 |
-
human_img_arg = _apply_exif_orientation(human_img.resize((384, 512)))
|
173 |
-
human_img_arg = convert_PIL_to_numpy(human_img_arg, format="BGR")
|
174 |
-
|
175 |
-
args = apply_net.create_argument_parser().parse_args(('show', './configs/densepose_rcnn_R_50_FPN_s1x.yaml', './ckpt/densepose/model_final_162be9.pkl', 'dp_segm', '-v', '--opts', 'MODEL.DEVICE', 'cuda'))
|
176 |
-
pose_img = args.func(args, human_img_arg)
|
177 |
-
pose_img = pose_img[:, :, ::-1]
|
178 |
-
pose_img = Image.fromarray(pose_img).resize((512, 768))
|
179 |
-
|
180 |
-
with torch.no_grad():
|
181 |
-
with torch.cuda.amp.autocast():
|
182 |
-
prompt = "model is wearing " + garment_des
|
183 |
-
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
184 |
-
with torch.inference_mode():
|
185 |
-
(
|
186 |
-
prompt_embeds,
|
187 |
-
negative_prompt_embeds,
|
188 |
-
pooled_prompt_embeds,
|
189 |
-
negative_pooled_prompt_embeds,
|
190 |
-
) = pipe.encode_prompt(
|
191 |
-
prompt,
|
192 |
-
num_images_per_prompt=1,
|
193 |
-
do_classifier_free_guidance=True,
|
194 |
-
negative_prompt=negative_prompt,
|
195 |
-
)
|
196 |
-
|
197 |
-
prompt = "a photo of " + garment_des
|
198 |
-
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
199 |
-
if not isinstance(prompt, list):
|
200 |
-
prompt = [prompt] * 1
|
201 |
-
if not isinstance(negative_prompt, list):
|
202 |
-
negative_prompt = [negative_prompt] * 1
|
203 |
-
with torch.inference_mode():
|
204 |
-
(
|
205 |
-
prompt_embeds_c,
|
206 |
-
_,
|
207 |
-
_,
|
208 |
-
_,
|
209 |
-
) = pipe.encode_prompt(
|
210 |
-
prompt,
|
211 |
-
num_images_per_prompt=1,
|
212 |
-
do_classifier_free_guidance=False,
|
213 |
-
negative_prompt=negative_prompt,
|
214 |
-
)
|
215 |
-
|
216 |
-
pose_img = tensor_transfrom(pose_img).unsqueeze(0).to(device, torch.float16)
|
217 |
-
garm_tensor = tensor_transfrom(garm_img).unsqueeze(0).to(device, torch.float16)
|
218 |
-
generator = torch.Generator(device).manual_seed(seed) if seed is not None else None
|
219 |
-
images = pipe(
|
220 |
-
prompt_embeds=prompt_embeds.to(device, torch.float16),
|
221 |
-
negative_prompt_embeds=negative_prompt_embeds.to(device, torch.float16),
|
222 |
-
pooled_prompt_embeds=pooled_prompt_embeds.to(device, torch.float16),
|
223 |
-
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds.to(device, torch.float16),
|
224 |
-
num_inference_steps=denoise_steps,
|
225 |
-
generator=generator,
|
226 |
-
strength=1.0,
|
227 |
-
pose_img=pose_img.to(device, torch.float16),
|
228 |
-
text_embeds_cloth=prompt_embeds_c.to(device, torch.float16),
|
229 |
-
cloth=garm_tensor.to(device, torch.float16),
|
230 |
-
mask_image=mask,
|
231 |
-
image=human_img,
|
232 |
-
height=1024,
|
233 |
-
width=768,
|
234 |
-
ip_adapter_image=garm_img.resize((512, 768)),
|
235 |
-
guidance_scale=2.0,
|
236 |
-
)[0]
|
237 |
-
clear_gpu_memory()
|
238 |
-
if is_checked_crop:
|
239 |
-
out_img = images[0].resize(crop_size)
|
240 |
-
human_img_orig.paste(out_img, (int(left), int(top)))
|
241 |
-
return human_img_orig, mask_gray
|
242 |
-
else:
|
243 |
-
return images[0], mask_gray
|
244 |
-
|
245 |
-
|
246 |
-
def process_image(image_data):
|
247 |
-
# Vรฉrifie si l'image est en base64 ou URL
|
248 |
-
if image_data.startswith('http://') or image_data.startswith('https://'):
|
249 |
-
return get_image_from_url(image_data) # Tรฉlรฉcharge l'image depuis l'URL
|
250 |
-
else:
|
251 |
-
return decode_image_from_base64(image_data) # Dรฉcode l'image base64
|
252 |
-
|
253 |
-
@app.route('/tryon', methods=['POST'])
|
254 |
-
def tryon():
|
255 |
-
data = request.json
|
256 |
-
human_image = process_image(data['human_image'])
|
257 |
-
garment_image = process_image(data['garment_image'])
|
258 |
-
description = data.get('description')
|
259 |
-
use_auto_mask = data.get('use_auto_mask', True)
|
260 |
-
use_auto_crop = data.get('use_auto_crop', False)
|
261 |
-
denoise_steps = int(data.get('denoise_steps', 30))
|
262 |
-
seed = int(data.get('seed', 42))
|
263 |
-
categorie = data.get('categorie' , 'upper_body')
|
264 |
-
human_dict = {
|
265 |
-
'background': human_image,
|
266 |
-
'layers': [human_image] if not use_auto_mask else None,
|
267 |
-
'composite': None
|
268 |
-
}
|
269 |
-
|
270 |
-
output_image, mask_image = start_tryon(human_dict, garment_image, description, use_auto_mask, use_auto_crop, denoise_steps, seed , categorie)
|
271 |
-
|
272 |
-
output_base64 = encode_image_to_base64(output_image)
|
273 |
-
mask_base64 = encode_image_to_base64(mask_image)
|
274 |
-
|
275 |
-
return jsonify({
|
276 |
-
'output_image': output_base64,
|
277 |
-
'mask_image': mask_base64
|
278 |
-
})
|
279 |
-
|
280 |
-
@app.route('/tryon-v2', methods=['POST'])
|
281 |
-
def tryon_v2():
|
282 |
-
|
283 |
-
data = request.json
|
284 |
-
human_image_data = data['human_image']
|
285 |
-
garment_image_data = data['garment_image']
|
286 |
-
|
287 |
-
# Process images (base64 ou URL)
|
288 |
-
human_image = process_image(human_image_data)
|
289 |
-
garment_image = process_image(garment_image_data)
|
290 |
-
|
291 |
-
description = data.get('description')
|
292 |
-
use_auto_mask = data.get('use_auto_mask', True)
|
293 |
-
use_auto_crop = data.get('use_auto_crop', False)
|
294 |
-
denoise_steps = int(data.get('denoise_steps', 30))
|
295 |
-
seed = int(data.get('seed', random.randint(0, 9999999)))
|
296 |
-
categorie = data.get('categorie', 'upper_body')
|
297 |
-
|
298 |
-
# Vรฉrifie si 'mask_image' est prรฉsent dans les donnรฉes
|
299 |
-
mask_image = None
|
300 |
-
if 'mask_image' in data:
|
301 |
-
mask_image_data = data['mask_image']
|
302 |
-
mask_image = process_image(mask_image_data)
|
303 |
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
'composite': None
|
308 |
-
}
|
309 |
-
output_image, mask_image = start_tryon(human_dict, garment_image, description, use_auto_mask, use_auto_crop, denoise_steps, seed , categorie)
|
310 |
-
return jsonify({
|
311 |
-
'image_id': save_image(output_image)
|
312 |
-
})
|
313 |
-
|
314 |
-
@spaces.GPU
|
315 |
-
def generate_mask(human_img, categorie='upper_body'):
|
316 |
-
device = "cuda"
|
317 |
-
openpose_model.preprocessor.body_estimation.model.to(device)
|
318 |
-
pipe.to(device)
|
319 |
|
|
|
|
|
|
|
|
|
320 |
try:
|
321 |
-
#
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
#
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
logging.error(f"Error generating mask: {e}")
|
335 |
-
raise e
|
336 |
|
337 |
-
|
338 |
-
|
339 |
-
def generate_mask_api():
|
340 |
-
try:
|
341 |
-
# Rรฉcupรฉrer les donnรฉes de l'image ร partir de la requรชte
|
342 |
-
data = request.json
|
343 |
-
base64_image = data.get('human_image')
|
344 |
-
categorie = data.get('categorie', 'upper_body')
|
345 |
-
|
346 |
-
# Dรฉcodage de l'image ร partir de base64
|
347 |
-
human_img = process_image(base64_image)
|
348 |
-
|
349 |
-
# Appeler la fonction pour gรฉnรฉrer le masque
|
350 |
-
mask_resized = generate_mask(human_img, categorie)
|
351 |
-
|
352 |
-
# Encodage du masque en base64 pour la rรฉponse
|
353 |
-
mask_base64 = encode_image_to_base64(mask_resized)
|
354 |
-
|
355 |
-
return jsonify({
|
356 |
-
'mask_image': mask_base64
|
357 |
-
}), 200
|
358 |
except Exception as e:
|
359 |
-
|
360 |
-
return jsonify({
|
361 |
-
|
362 |
-
# Route pour rรฉcupรฉrer l'image gรฉnรฉrรฉe
|
363 |
-
@app.route('/api/get_image/<image_id>', methods=['GET'])
|
364 |
-
def get_image(image_id):
|
365 |
-
# Construire le chemin complet de l'image
|
366 |
-
image_path = image_id # Assurez-vous que le nom de fichier correspond ร celui que vous avez utilisรฉ lors de la sauvegarde
|
367 |
-
|
368 |
-
# Renvoyer l'image
|
369 |
-
try:
|
370 |
-
return send_file(image_path, mimetype='image/webp')
|
371 |
-
except FileNotFoundError:
|
372 |
-
return jsonify({'error': 'Image not found'}), 404
|
373 |
|
374 |
-
if __name__ ==
|
375 |
-
app.run(
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
|
|
|
|
|
|
|
|
2 |
import torch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
from transformers import (
|
4 |
+
UNet2DConditionModel,
|
5 |
+
AutoTokenizer,
|
6 |
CLIPTextModel,
|
7 |
CLIPTextModelWithProjection,
|
8 |
+
CLIPVisionModelWithProjection,
|
9 |
+
AutoencoderKL,
|
10 |
+
DDPMScheduler
|
11 |
)
|
12 |
+
from PIL import Image
|
13 |
+
import base64
|
14 |
+
from io import BytesIO
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
app = Flask(__name__)
|
17 |
|
18 |
+
# Global variables for models to load them once at startup
|
19 |
+
unet = None
|
20 |
+
tokenizer_one = None
|
21 |
+
tokenizer_two = None
|
22 |
+
noise_scheduler = None
|
23 |
+
text_encoder_one = None
|
24 |
+
text_encoder_two = None
|
25 |
+
image_encoder = None
|
26 |
+
vae = None
|
27 |
+
UNet_Encoder = None
|
28 |
+
|
29 |
+
# Load models once at startup
|
30 |
def load_models():
|
31 |
global unet, tokenizer_one, tokenizer_two, noise_scheduler, text_encoder_one, text_encoder_two, image_encoder, vae, UNet_Encoder
|
32 |
+
base_path = "your_base_path_here"
|
33 |
unet = UNet2DConditionModel.from_pretrained(base_path, subfolder="unet", torch_dtype=torch.float16, force_download=False)
|
34 |
tokenizer_one = AutoTokenizer.from_pretrained(base_path, subfolder="tokenizer", use_fast=False, force_download=False)
|
35 |
tokenizer_two = AutoTokenizer.from_pretrained(base_path, subfolder="tokenizer_2", use_fast=False, force_download=False)
|
|
|
40 |
vae = AutoencoderKL.from_pretrained(base_path, subfolder="vae", torch_dtype=torch.float16, force_download=False)
|
41 |
UNet_Encoder = UNet2DConditionModel_ref.from_pretrained(base_path, subfolder="unet_encoder", torch_dtype=torch.float16, force_download=False)
|
42 |
|
43 |
+
# Call the function to load models at startup
|
44 |
load_models()
|
45 |
|
46 |
+
# Helper function to free up GPU memory after processing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
def clear_gpu_memory():
|
48 |
torch.cuda.empty_cache()
|
49 |
torch.cuda.synchronize()
|
50 |
|
51 |
+
# Helper function to convert base64 to image
|
52 |
+
def base64_to_image(base64_str):
|
53 |
+
image_data = base64.b64decode(base64_str)
|
54 |
+
image = Image.open(BytesIO(image_data)).convert("RGB")
|
55 |
+
return image
|
56 |
+
|
57 |
+
# Helper function to resize images for faster processing
|
58 |
+
def resize_image(image, size=(512, 768)):
|
59 |
+
return image.resize(size)
|
60 |
+
|
61 |
+
# Example try-on function
|
62 |
+
@app.route('/start_tryon', methods=['POST'])
|
63 |
+
def start_tryon():
|
64 |
+
data = request.get_json()
|
65 |
+
garm_img_base64 = data['garm_img']
|
66 |
+
human_img_base64 = data['human_img']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
+
# Decode and resize images
|
69 |
+
garm_img = resize_image(base64_to_image(garm_img_base64))
|
70 |
+
human_img = resize_image(base64_to_image(human_img_base64))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
+
# Convert images to tensors and move to GPU
|
73 |
+
garm_img_tensor = torch.tensor(garm_img, dtype=torch.float16).unsqueeze(0).to('cuda')
|
74 |
+
human_img_tensor = torch.tensor(human_img, dtype=torch.float16).unsqueeze(0).to('cuda')
|
75 |
+
|
76 |
try:
|
77 |
+
# Processing steps (dummy example, replace with your logic)
|
78 |
+
with torch.inference_mode():
|
79 |
+
# Run the inference for both images
|
80 |
+
result_tensor = unet(garm_img_tensor, human_img_tensor) # Replace with your actual logic
|
81 |
+
|
82 |
+
# Free GPU memory after inference
|
83 |
+
clear_gpu_memory()
|
84 |
+
|
85 |
+
# Convert result back to base64 for return
|
86 |
+
result_img = Image.fromarray(result_tensor.squeeze(0).cpu().numpy())
|
87 |
+
buffered = BytesIO()
|
88 |
+
result_img.save(buffered, format="JPEG")
|
89 |
+
result_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
|
|
|
|
90 |
|
91 |
+
return jsonify({"result": result_base64})
|
92 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
except Exception as e:
|
94 |
+
clear_gpu_memory()
|
95 |
+
return jsonify({"error": str(e)}), 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
+
if __name__ == '__main__':
|
98 |
+
app.run(host='0.0.0.0', port=7860)
|