subhan971 commited on
Commit
d1c501f
Β·
verified Β·
1 Parent(s): c7354ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +309 -70
app.py CHANGED
@@ -7,6 +7,7 @@ import base64
7
  import requests
8
  import json
9
  import time
 
10
 
11
 
12
  def tryon(person_img, garment_img, seed, randomize_seed):
@@ -33,20 +34,18 @@ def tryon(person_img, garment_img, seed, randomize_seed):
33
  }
34
  try:
35
  response = requests.post(url, headers=headers, data=json.dumps(data), timeout=50)
36
- # print("post response code", response.status_code)
37
  if response.status_code == 200:
38
  result = response.json()['result']
39
  status = result['status']
40
  if status == "success":
41
  uuid = result['result']
42
- # print(uuid)
43
  except Exception as err:
44
  print(f"Post Exception Error: {err}")
45
  raise gr.Error("Too many users, please try again later")
46
  post_end_time = time.time()
47
  print(f"post time used: {post_end_time-post_start_time}")
48
 
49
- get_start_time =time.time()
50
  time.sleep(9)
51
  Max_Retry = 12
52
  result_img = None
@@ -56,7 +55,6 @@ def tryon(person_img, garment_img, seed, randomize_seed):
56
  try:
57
  url = "http://" + os.environ['tryon_url'] + "Query?taskId=" + uuid
58
  response = requests.get(url, headers=headers, timeout=20)
59
- # print("get response code", response.status_code)
60
  if response.status_code == 200:
61
  result = response.json()['result']
62
  status = result['status']
@@ -72,9 +70,8 @@ def tryon(person_img, garment_img, seed, randomize_seed):
72
  info = "Error"
73
  break
74
  else:
75
- # print(response.text)
76
- err_log = "URL error, pleace contact the admin"
77
- info = "URL error, pleace contact the admin"
78
  break
79
  except requests.exceptions.ReadTimeout:
80
  err_log = "Http Timeout"
@@ -94,6 +91,7 @@ def tryon(person_img, garment_img, seed, randomize_seed):
94
 
95
  return result_img, seed, info
96
 
 
97
  def start_tryon(person_img, garment_img, seed, randomize_seed):
98
  start_time = time.time()
99
  if person_img is None or garment_img is None:
@@ -132,44 +130,96 @@ def start_tryon(person_img, garment_img, seed, randomize_seed):
132
  result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
133
  info = "Success"
134
  else:
135
- info = "Try again latter"
136
  else:
137
  print(response.text)
138
- info = "URL error, pleace contact the admin"
139
  except requests.exceptions.ReadTimeout:
140
  print("timeout")
141
  info = "Too many users, please try again later"
142
  raise gr.Error("Too many users, please try again later")
143
  except Exception as err:
144
- print(f"ε…Άδ»–ι”™θ――: {err}")
145
- info = "Error, pleace contact the admin"
146
  end_time = time.time()
147
  print(f"time used: {end_time-start_time}")
148
 
149
  return result_img, seed, info
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  MAX_SEED = 999999
152
 
153
  example_path = os.path.join(os.path.dirname(__file__), 'assets')
154
 
155
- garm_list = os.listdir(os.path.join(example_path,"cloth"))
156
- garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list]
 
 
 
 
 
 
 
 
157
 
158
- human_list = os.listdir(os.path.join(example_path,"human"))
159
- human_list_path = [os.path.join(example_path,"human",human) for human in human_list]
160
-
161
- css="""
162
  #col-left {
163
  margin: 0 auto;
164
- max-width: 430px;
165
  }
166
  #col-mid {
167
  margin: 0 auto;
168
- max-width: 430px;
169
  }
170
  #col-right {
171
  margin: 0 auto;
172
- max-width: 430px;
173
  }
174
  #col-showcase {
175
  margin: 0 auto;
@@ -178,61 +228,149 @@ css="""
178
  #button {
179
  color: blue;
180
  }
 
 
 
 
 
 
 
 
 
 
 
181
  """
182
 
183
  def load_description(fp):
184
- with open(fp, 'r', encoding='utf-8') as f:
185
- content = f.read()
186
- return content
 
 
 
 
 
 
 
 
 
 
187
 
188
  def change_imgs(image1, image2):
189
  return image1, image2
190
 
191
  with gr.Blocks(css=css) as Tryon:
192
  gr.HTML(load_description("assets/title.md"))
 
193
  with gr.Row():
194
- with gr.Column(elem_id = "col-left"):
195
  gr.HTML("""
196
  <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
197
  <div>
198
- Step 1. Upload a person image ⬇️
199
  </div>
200
  </div>
201
  """)
202
- with gr.Column(elem_id = "col-mid"):
203
  gr.HTML("""
204
  <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
205
  <div>
206
- Step 2. Upload a garment image ⬇️
207
  </div>
208
  </div>
209
  """)
210
- with gr.Column(elem_id = "col-right"):
211
  gr.HTML("""
212
  <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
213
  <div>
214
- Step 3. Press β€œRun” to get try-on results
215
  </div>
216
  </div>
217
  """)
 
218
  with gr.Row():
219
- with gr.Column(elem_id = "col-left"):
220
- imgs = gr.Image(label="Person image", sources='upload', type="numpy")
221
- # category = gr.Dropdown(label="Garment category", choices=['upper_body', 'lower_body', 'dresses'], value="upper_body")
222
- example = gr.Examples(
223
- inputs=imgs,
224
- examples_per_page=12,
225
- examples=human_list_path
226
- )
227
- with gr.Column(elem_id = "col-mid"):
228
- garm_img = gr.Image(label="Garment image", sources='upload', type="numpy")
229
- example = gr.Examples(
230
- inputs=garm_img,
231
- examples_per_page=12,
232
- examples=garm_list_path
233
- )
234
- with gr.Column(elem_id = "col-right"):
235
- image_out = gr.Image(label="Result", show_share_button=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  with gr.Row():
237
  seed = gr.Slider(
238
  label="Seed",
@@ -242,34 +380,135 @@ with gr.Blocks(css=css) as Tryon:
242
  value=0,
243
  )
244
  randomize_seed = gr.Checkbox(label="Random seed", value=True)
 
245
  with gr.Row():
246
  seed_used = gr.Number(label="Seed used")
247
- result_info = gr.Text(label="Response")
248
- # try_button = gr.Button(value="Run", elem_id="button")
249
- test_button = gr.Button(value="Run", elem_id="button")
250
-
251
-
252
- # try_button.click(fn=start_tryon, inputs=[imgs, garm_img, seed, randomize_seed], outputs=[image_out, seed_used, result_info], api_name='tryon',concurrency_limit=10)
253
- test_button.click(fn=tryon, inputs=[imgs, garm_img, seed, randomize_seed], outputs=[image_out, seed_used, result_info], api_name=False, concurrency_limit=45)
254
-
255
- with gr.Column(elem_id = "col-showcase"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  gr.HTML("""
257
- <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
258
- <div> </div>
259
- <br>
260
  <div>
261
- Virtual try-on examples in pairs of person and garment images
 
 
262
  </div>
263
  </div>
264
  """)
265
- show_case = gr.Examples(
266
- examples=[
267
- ["assets/examples/model2.png", "assets/examples/garment2.png", "assets/examples/result2.png"],
268
- ["assets/examples/model3.png", "assets/examples/garment3.png", "assets/examples/result3.png"],
269
- ["assets/examples/model1.png", "assets/examples/garment1.png", "assets/examples/result1.png"],
270
- ],
271
- inputs=[imgs, garm_img, image_out],
272
- label=None
273
- )
274
-
275
- Tryon.queue(api_open=False).launch(show_api=False)
 
 
 
 
 
 
 
 
 
 
 
7
  import requests
8
  import json
9
  import time
10
+ from PIL import Image
11
 
12
 
13
  def tryon(person_img, garment_img, seed, randomize_seed):
 
34
  }
35
  try:
36
  response = requests.post(url, headers=headers, data=json.dumps(data), timeout=50)
 
37
  if response.status_code == 200:
38
  result = response.json()['result']
39
  status = result['status']
40
  if status == "success":
41
  uuid = result['result']
 
42
  except Exception as err:
43
  print(f"Post Exception Error: {err}")
44
  raise gr.Error("Too many users, please try again later")
45
  post_end_time = time.time()
46
  print(f"post time used: {post_end_time-post_start_time}")
47
 
48
+ get_start_time = time.time()
49
  time.sleep(9)
50
  Max_Retry = 12
51
  result_img = None
 
55
  try:
56
  url = "http://" + os.environ['tryon_url'] + "Query?taskId=" + uuid
57
  response = requests.get(url, headers=headers, timeout=20)
 
58
  if response.status_code == 200:
59
  result = response.json()['result']
60
  status = result['status']
 
70
  info = "Error"
71
  break
72
  else:
73
+ err_log = "URL error, please contact the admin"
74
+ info = "URL error, please contact the admin"
 
75
  break
76
  except requests.exceptions.ReadTimeout:
77
  err_log = "Http Timeout"
 
91
 
92
  return result_img, seed, info
93
 
94
+
95
  def start_tryon(person_img, garment_img, seed, randomize_seed):
96
  start_time = time.time()
97
  if person_img is None or garment_img is None:
 
130
  result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
131
  info = "Success"
132
  else:
133
+ info = "Try again later"
134
  else:
135
  print(response.text)
136
+ info = "URL error, please contact the admin"
137
  except requests.exceptions.ReadTimeout:
138
  print("timeout")
139
  info = "Too many users, please try again later"
140
  raise gr.Error("Too many users, please try again later")
141
  except Exception as err:
142
+ print(f"Other error: {err}")
143
+ info = "Error, please contact the admin"
144
  end_time = time.time()
145
  print(f"time used: {end_time-start_time}")
146
 
147
  return result_img, seed, info
148
 
149
+
150
+ def capture_person_photo(webcam_image):
151
+ """Process captured person photo from webcam"""
152
+ if webcam_image is None:
153
+ gr.Warning("No image captured from camera")
154
+ return None
155
+ return webcam_image
156
+
157
+
158
+ def capture_garment_photo(webcam_image):
159
+ """Process captured garment photo from webcam"""
160
+ if webcam_image is None:
161
+ gr.Warning("No image captured from camera")
162
+ return None
163
+ return webcam_image
164
+
165
+
166
+ def clear_person_image():
167
+ """Clear the person image"""
168
+ return None
169
+
170
+
171
+ def clear_garment_image():
172
+ """Clear the garment image"""
173
+ return None
174
+
175
+
176
+ def switch_to_upload_person():
177
+ """Switch to upload mode for person image"""
178
+ return gr.update(visible=True), gr.update(visible=False)
179
+
180
+
181
+ def switch_to_camera_person():
182
+ """Switch to camera mode for person image"""
183
+ return gr.update(visible=False), gr.update(visible=True)
184
+
185
+
186
+ def switch_to_upload_garment():
187
+ """Switch to upload mode for garment image"""
188
+ return gr.update(visible=True), gr.update(visible=False)
189
+
190
+
191
+ def switch_to_camera_garment():
192
+ """Switch to camera mode for garment image"""
193
+ return gr.update(visible=False), gr.update(visible=True)
194
+
195
+
196
  MAX_SEED = 999999
197
 
198
  example_path = os.path.join(os.path.dirname(__file__), 'assets')
199
 
200
+ # Check if assets directory exists, if not create dummy lists
201
+ if os.path.exists(example_path):
202
+ garm_list = os.listdir(os.path.join(example_path, "cloth")) if os.path.exists(os.path.join(example_path, "cloth")) else []
203
+ garm_list_path = [os.path.join(example_path, "cloth", garm) for garm in garm_list]
204
+
205
+ human_list = os.listdir(os.path.join(example_path, "human")) if os.path.exists(os.path.join(example_path, "human")) else []
206
+ human_list_path = [os.path.join(example_path, "human", human) for human in human_list]
207
+ else:
208
+ garm_list_path = []
209
+ human_list_path = []
210
 
211
+ css = """
 
 
 
212
  #col-left {
213
  margin: 0 auto;
214
+ max-width: 450px;
215
  }
216
  #col-mid {
217
  margin: 0 auto;
218
+ max-width: 450px;
219
  }
220
  #col-right {
221
  margin: 0 auto;
222
+ max-width: 450px;
223
  }
224
  #col-showcase {
225
  margin: 0 auto;
 
228
  #button {
229
  color: blue;
230
  }
231
+ .camera-section {
232
+ border: 2px dashed #ccc;
233
+ border-radius: 10px;
234
+ padding: 10px;
235
+ margin: 5px 0;
236
+ }
237
+ .mode-buttons {
238
+ display: flex;
239
+ gap: 10px;
240
+ margin-bottom: 10px;
241
+ }
242
  """
243
 
244
  def load_description(fp):
245
+ """Load description from file if it exists, otherwise return default"""
246
+ try:
247
+ with open(fp, 'r', encoding='utf-8') as f:
248
+ content = f.read()
249
+ return content
250
+ except FileNotFoundError:
251
+ return """
252
+ # 🎯 Virtual Try-On Application
253
+
254
+ **Experience the future of fashion with AI-powered virtual try-on technology!**
255
+
256
+ Upload or capture photos of yourself and garments to see how they look together.
257
+ """
258
 
259
  def change_imgs(image1, image2):
260
  return image1, image2
261
 
262
  with gr.Blocks(css=css) as Tryon:
263
  gr.HTML(load_description("assets/title.md"))
264
+
265
  with gr.Row():
266
+ with gr.Column(elem_id="col-left"):
267
  gr.HTML("""
268
  <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
269
  <div>
270
+ πŸ“Έ Step 1. Get Person Image ⬇️
271
  </div>
272
  </div>
273
  """)
274
+ with gr.Column(elem_id="col-mid"):
275
  gr.HTML("""
276
  <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
277
  <div>
278
+ πŸ‘” Step 2. Get Garment Image ⬇️
279
  </div>
280
  </div>
281
  """)
282
+ with gr.Column(elem_id="col-right"):
283
  gr.HTML("""
284
  <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
285
  <div>
286
+ ✨ Step 3. Generate Try-On Result
287
  </div>
288
  </div>
289
  """)
290
+
291
  with gr.Row():
292
+ # Person Image Column
293
+ with gr.Column(elem_id="col-left"):
294
+ # Mode selection buttons for person
295
+ with gr.Row(elem_classes="mode-buttons"):
296
+ upload_person_btn = gr.Button("πŸ“ Upload Photo", variant="secondary", size="sm")
297
+ camera_person_btn = gr.Button("πŸ“· Take Photo", variant="secondary", size="sm")
298
+ clear_person_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary", size="sm")
299
+
300
+ # Upload interface for person (visible by default)
301
+ with gr.Group(visible=True) as person_upload_group:
302
+ person_img_upload = gr.Image(
303
+ label="Person Image (Upload)",
304
+ sources=['upload'],
305
+ type="numpy",
306
+ height=400
307
+ )
308
+
309
+ # Camera interface for person (hidden by default)
310
+ with gr.Group(visible=False, elem_classes="camera-section") as person_camera_group:
311
+ person_img_camera = gr.Image(
312
+ label="Person Image (Camera)",
313
+ sources=['webcam'],
314
+ type="numpy",
315
+ height=400
316
+ )
317
+ capture_person_btn = gr.Button("πŸ“Έ Capture Person Photo", variant="primary")
318
+
319
+ # Combined person image state
320
+ person_img_final = gr.State()
321
+
322
+ # Examples for person images
323
+ if human_list_path:
324
+ example_person = gr.Examples(
325
+ inputs=person_img_upload,
326
+ examples_per_page=8,
327
+ examples=human_list_path,
328
+ label="Example Person Images"
329
+ )
330
+
331
+ # Garment Image Column
332
+ with gr.Column(elem_id="col-mid"):
333
+ # Mode selection buttons for garment
334
+ with gr.Row(elem_classes="mode-buttons"):
335
+ upload_garment_btn = gr.Button("πŸ“ Upload Photo", variant="secondary", size="sm")
336
+ camera_garment_btn = gr.Button("πŸ“· Take Photo", variant="secondary", size="sm")
337
+ clear_garment_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary", size="sm")
338
+
339
+ # Upload interface for garment (visible by default)
340
+ with gr.Group(visible=True) as garment_upload_group:
341
+ garment_img_upload = gr.Image(
342
+ label="Garment Image (Upload)",
343
+ sources=['upload'],
344
+ type="numpy",
345
+ height=400
346
+ )
347
+
348
+ # Camera interface for garment (hidden by default)
349
+ with gr.Group(visible=False, elem_classes="camera-section") as garment_camera_group:
350
+ garment_img_camera = gr.Image(
351
+ label="Garment Image (Camera)",
352
+ sources=['webcam'],
353
+ type="numpy",
354
+ height=400
355
+ )
356
+ capture_garment_btn = gr.Button("πŸ“Έ Capture Garment Photo", variant="primary")
357
+
358
+ # Combined garment image state
359
+ garment_img_final = gr.State()
360
+
361
+ # Examples for garment images
362
+ if garm_list_path:
363
+ example_garment = gr.Examples(
364
+ inputs=garment_img_upload,
365
+ examples_per_page=8,
366
+ examples=garm_list_path,
367
+ label="Example Garment Images"
368
+ )
369
+
370
+ # Results Column
371
+ with gr.Column(elem_id="col-right"):
372
+ image_out = gr.Image(label="🎯 Try-On Result", show_share_button=False, height=400)
373
+
374
  with gr.Row():
375
  seed = gr.Slider(
376
  label="Seed",
 
380
  value=0,
381
  )
382
  randomize_seed = gr.Checkbox(label="Random seed", value=True)
383
+
384
  with gr.Row():
385
  seed_used = gr.Number(label="Seed used")
386
+ result_info = gr.Text(label="Status")
387
+
388
+ # Main try-on button
389
+ tryon_button = gr.Button("πŸš€ Generate Try-On", variant="primary", size="lg")
390
+
391
+ # Event handlers for person image mode switching
392
+ upload_person_btn.click(
393
+ switch_to_upload_person,
394
+ outputs=[person_upload_group, person_camera_group]
395
+ )
396
+
397
+ camera_person_btn.click(
398
+ switch_to_camera_person,
399
+ outputs=[person_upload_group, person_camera_group]
400
+ )
401
+
402
+ clear_person_btn.click(
403
+ clear_person_image,
404
+ outputs=[person_img_upload]
405
+ )
406
+
407
+ # Event handlers for garment image mode switching
408
+ upload_garment_btn.click(
409
+ switch_to_upload_garment,
410
+ outputs=[garment_upload_group, garment_camera_group]
411
+ )
412
+
413
+ camera_garment_btn.click(
414
+ switch_to_camera_garment,
415
+ outputs=[garment_upload_group, garment_camera_group]
416
+ )
417
+
418
+ clear_garment_btn.click(
419
+ clear_garment_image,
420
+ outputs=[garment_img_upload]
421
+ )
422
+
423
+ # Capture button handlers
424
+ capture_person_btn.click(
425
+ capture_person_photo,
426
+ inputs=[person_img_camera],
427
+ outputs=[person_img_final]
428
+ )
429
+
430
+ capture_garment_btn.click(
431
+ capture_garment_photo,
432
+ inputs=[garment_img_camera],
433
+ outputs=[garment_img_final]
434
+ )
435
+
436
+ # Function to get the current person image
437
+ def get_current_person_image(upload_img, camera_img, final_img):
438
+ if final_img is not None:
439
+ return final_img
440
+ elif upload_img is not None:
441
+ return upload_img
442
+ elif camera_img is not None:
443
+ return camera_img
444
+ return None
445
+
446
+ # Function to get the current garment image
447
+ def get_current_garment_image(upload_img, camera_img, final_img):
448
+ if final_img is not None:
449
+ return final_img
450
+ elif upload_img is not None:
451
+ return upload_img
452
+ elif camera_img is not None:
453
+ return camera_img
454
+ return None
455
+
456
+ # Modified try-on function to handle multiple image sources
457
+ def run_tryon(person_upload, person_camera, person_final,
458
+ garment_upload, garment_camera, garment_final,
459
+ seed, randomize_seed):
460
+
461
+ # Get the current person image
462
+ person_img = get_current_person_image(person_upload, person_camera, person_final)
463
+
464
+ # Get the current garment image
465
+ garment_img = get_current_garment_image(garment_upload, garment_camera, garment_final)
466
+
467
+ # Run the try-on process
468
+ return tryon(person_img, garment_img, seed, randomize_seed)
469
+
470
+ # Main try-on button click handler
471
+ tryon_button.click(
472
+ fn=run_tryon,
473
+ inputs=[
474
+ person_img_upload, person_img_camera, person_img_final,
475
+ garment_img_upload, garment_img_camera, garment_img_final,
476
+ seed, randomize_seed
477
+ ],
478
+ outputs=[image_out, seed_used, result_info],
479
+ api_name=False,
480
+ concurrency_limit=45
481
+ )
482
+
483
+ # Showcase section
484
+ with gr.Column(elem_id="col-showcase"):
485
  gr.HTML("""
486
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px; margin-top: 30px;">
 
 
487
  <div>
488
+ 🌟 Virtual Try-On Examples
489
+ <br><br>
490
+ <em>See how different garments look on various models</em>
491
  </div>
492
  </div>
493
  """)
494
+
495
+ # Only show examples if they exist
496
+ if os.path.exists("assets/examples"):
497
+ show_case = gr.Examples(
498
+ examples=[
499
+ ["assets/examples/model2.png", "assets/examples/garment2.png", "assets/examples/result2.png"],
500
+ ["assets/examples/model3.png", "assets/examples/garment3.png", "assets/examples/result3.png"],
501
+ ["assets/examples/model1.png", "assets/examples/garment1.png", "assets/examples/result1.png"],
502
+ ],
503
+ inputs=[person_img_upload, garment_img_upload, image_out],
504
+ label="Example Try-On Results"
505
+ )
506
+
507
+ # Launch the app
508
+ if __name__ == "__main__":
509
+ Tryon.queue(api_open=False).launch(
510
+ show_api=False,
511
+ share=False,
512
+ server_name="0.0.0.0",
513
+ server_port=7860
514
+ )