kodnuke commited on
Commit
4767546
·
verified ·
1 Parent(s): 2f15aca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -48
app.py CHANGED
@@ -1,5 +1,7 @@
1
  import os
2
  import cv2
 
 
3
  import gradio as gr
4
  import numpy as np
5
  import random
@@ -8,73 +10,152 @@ import requests
8
  import json
9
  import time
10
 
11
- MAX_SEED = 999999
12
 
13
  def tryon(person_img, garment_img, seed, randomize_seed):
 
14
  if person_img is None or garment_img is None:
15
  return None, None, "Empty image"
16
-
17
  if randomize_seed:
18
  seed = random.randint(0, MAX_SEED)
 
 
 
 
19
 
20
- encoded_person_img = base64.b64encode(cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()).decode('utf-8')
21
- encoded_garment_img = base64.b64encode(cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()).decode('utf-8')
22
-
23
- url = "http://" + os.getenv('tryon_url', '') + "Submit"
24
- token = os.getenv('token', '')
25
- cookie = os.getenv('Cookie', '')
26
- referer = os.getenv('referer', '')
27
  headers = {'Content-Type': 'application/json', 'token': token, 'Cookie': cookie, 'referer': referer}
28
-
29
  data = {
30
  "clothImage": encoded_garment_img,
31
  "humanImage": encoded_person_img,
32
  "seed": seed
33
  }
34
-
35
- uuid = None
36
  try:
37
  response = requests.post(url, headers=headers, data=json.dumps(data), timeout=50)
 
38
  if response.status_code == 200:
39
  result = response.json()['result']
40
- if result['status'] == "success":
 
41
  uuid = result['result']
 
42
  except Exception as err:
43
  print(f"Error: {err}")
44
- return None, None, "Too many users, please try again later"
 
 
45
 
 
46
  time.sleep(9)
47
  Max_Retry = 10
48
  result_img = None
49
- for _ in range(Max_Retry):
50
  try:
51
- url = "http://" + os.getenv('tryon_url', '') + "Query?taskId=" + uuid
52
  response = requests.get(url, headers=headers, timeout=15)
 
53
  if response.status_code == 200:
54
  result = response.json()['result']
55
- if result['status'] == "success":
 
56
  result = base64.b64decode(result['result'])
57
  result_np = np.frombuffer(result, np.uint8)
58
  result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
59
  result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
60
- return result_img, seed, "Success"
61
- elif result['status'] == "error":
62
- return None, seed, "Too many users, please try again later"
 
63
  else:
64
- return None, seed, "URL error, please contact the admin"
 
65
  except requests.exceptions.ReadTimeout:
66
- time.sleep(1)
 
67
  except Exception as err:
68
  print(f"Error: {err}")
69
-
70
- return result_img, seed, "Failed to get result after multiple attempts"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  example_path = os.path.join(os.path.dirname(__file__), 'assets')
73
- garm_list_path = [os.path.join(example_path, "cloth", garm) for garm in os.listdir(os.path.join(example_path, "cloth"))]
74
- human_list_path = [os.path.join(example_path, "human", human) for human in os.listdir(os.path.join(example_path, "human"))]
75
 
76
- css = """
77
- #col-left, #col-mid, #col-right {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  margin: 0 auto;
79
  max-width: 430px;
80
  }
@@ -89,44 +170,96 @@ css = """
89
 
90
  def load_description(fp):
91
  with open(fp, 'r', encoding='utf-8') as f:
92
- return f.read()
 
 
 
 
93
 
94
  with gr.Blocks(css=css) as Tryon:
95
  gr.HTML(load_description("assets/title.md"))
96
  with gr.Row():
97
- with gr.Column(elem_id="col-left"):
98
- gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 1. Upload a person image ⬇️</div>")
99
- with gr.Column(elem_id="col-mid"):
100
- gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 2. Upload a garment image ⬇️</div>")
101
- with gr.Column(elem_id="col-right"):
102
- gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 3. Press “Run” to get try-on results</div>")
103
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  with gr.Row():
105
- with gr.Column(elem_id="col-left"):
106
  imgs = gr.Image(label="Person image", sources='upload', type="numpy")
107
- gr.Examples(inputs=imgs, examples_per_page=12, examples=human_list_path)
108
- with gr.Column(elem_id="col-mid"):
 
 
 
 
 
109
  garm_img = gr.Image(label="Garment image", sources='upload', type="numpy")
110
- gr.Examples(inputs=garm_img, examples_per_page=12, examples=garm_list_path)
111
- with gr.Column(elem_id="col-right"):
 
 
 
 
112
  image_out = gr.Image(label="Result", show_share_button=False)
113
  with gr.Row():
114
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
 
 
 
 
 
 
115
  randomize_seed = gr.Checkbox(label="Random seed", value=True)
116
  with gr.Row():
117
  seed_used = gr.Number(label="Seed used")
118
  result_info = gr.Text(label="Response")
119
- gr.Button(value="Run", elem_id="button").click(fn=tryon, inputs=[imgs, garm_img, seed, randomize_seed], outputs=[image_out, seed_used, result_info], api_name='tryon', concurrency_limit=40)
 
 
 
 
 
120
 
121
- with gr.Column(elem_id="col-showcase"):
122
- gr.HTML("<div style='text-align: center; font-size: 20px;'>Virtual try-on examples in pairs of person and garment images</div>")
123
- gr.Examples(
 
 
 
 
 
 
 
 
124
  examples=[
125
  ["assets/examples/model2.png", "assets/examples/garment2.png", "assets/examples/result2.png"],
126
  ["assets/examples/model3.png", "assets/examples/garment3.png", "assets/examples/result3.png"],
127
  ["assets/examples/model1.png", "assets/examples/garment1.png", "assets/examples/result1.png"],
128
  ],
129
- inputs=[imgs, garm_img, image_out]
 
130
  )
131
 
132
- Tryon.launch()
 
 
 
1
  import os
2
  import cv2
3
+ import spaces
4
+ from PIL import Image
5
  import gradio as gr
6
  import numpy as np
7
  import random
 
10
  import json
11
  import time
12
 
 
13
 
14
  def tryon(person_img, garment_img, seed, randomize_seed):
15
+ post_start_time = time.time()
16
  if person_img is None or garment_img is None:
17
  return None, None, "Empty image"
 
18
  if randomize_seed:
19
  seed = random.randint(0, MAX_SEED)
20
+ encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
21
+ encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
22
+ encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
23
+ encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
24
 
25
+ url = "http://" + os.environ['tryon_url'] + "Submit"
26
+ token = os.environ['token']
27
+ cookie = os.environ['Cookie']
28
+ referer = os.environ['referer']
 
 
 
29
  headers = {'Content-Type': 'application/json', 'token': token, 'Cookie': cookie, 'referer': referer}
 
30
  data = {
31
  "clothImage": encoded_garment_img,
32
  "humanImage": encoded_person_img,
33
  "seed": seed
34
  }
 
 
35
  try:
36
  response = requests.post(url, headers=headers, data=json.dumps(data), timeout=50)
37
+ print("post response code", response.status_code)
38
  if response.status_code == 200:
39
  result = response.json()['result']
40
+ status = result['status']
41
+ if status == "success":
42
  uuid = result['result']
43
+ print(uuid)
44
  except Exception as err:
45
  print(f"Error: {err}")
46
+ raise gr.Error("Too many users, please try again later")
47
+ post_end_time = time.time()
48
+ print(f"post time used: {post_end_time-post_start_time}")
49
 
50
+ get_start_time =time.time()
51
  time.sleep(9)
52
  Max_Retry = 10
53
  result_img = None
54
+ for i in range(Max_Retry):
55
  try:
56
+ url = "http://" + os.environ['tryon_url'] + "Query?taskId=" + uuid
57
  response = requests.get(url, headers=headers, timeout=15)
58
+ print("get response code", response.status_code)
59
  if response.status_code == 200:
60
  result = response.json()['result']
61
+ status = result['status']
62
+ if status == "success":
63
  result = base64.b64decode(result['result'])
64
  result_np = np.frombuffer(result, np.uint8)
65
  result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
66
  result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
67
+ info = "Success"
68
+ break
69
+ elif status == "error":
70
+ raise gr.Error("Too many users, please try again later")
71
  else:
72
+ print(response.text)
73
+ info = "URL error, pleace contact the admin"
74
  except requests.exceptions.ReadTimeout:
75
+ print("timeout")
76
+ info = "Too many users, please try again later"
77
  except Exception as err:
78
  print(f"Error: {err}")
79
+ time.sleep(1)
80
+ get_end_time = time.time()
81
+ print(f"get time used: {get_end_time-get_start_time}")
82
+
83
+ return result_img, seed, info
84
+
85
+ def start_tryon(person_img, garment_img, seed, randomize_seed):
86
+ start_time = time.time()
87
+ if person_img is None or garment_img is None:
88
+ return None, None, "Empty image"
89
+ if randomize_seed:
90
+ seed = random.randint(0, MAX_SEED)
91
+ encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
92
+ encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
93
+ encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
94
+ encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
95
+
96
+ url = "http://" + os.environ['tryon_url']
97
+ token = os.environ['token']
98
+ cookie = os.environ['Cookie']
99
+ referer = os.environ['referer']
100
+
101
+ headers = {'Content-Type': 'application/json', 'token': token, 'Cookie': cookie, 'referer': referer}
102
+ data = {
103
+ "clothImage": encoded_garment_img,
104
+ "humanImage": encoded_person_img,
105
+ "seed": seed
106
+ }
107
+
108
+ result_img = None
109
+ try:
110
+ session = requests.Session()
111
+ response = session.post(url, headers=headers, data=json.dumps(data), timeout=60)
112
+ print("response code", response.status_code)
113
+ if response.status_code == 200:
114
+ result = response.json()['result']
115
+ status = result['status']
116
+ if status == "success":
117
+ result = base64.b64decode(result['result'])
118
+ result_np = np.frombuffer(result, np.uint8)
119
+ result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
120
+ result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
121
+ info = "Success"
122
+ else:
123
+ info = "Try again latter"
124
+ else:
125
+ print(response.text)
126
+ info = "URL error, pleace contact the admin"
127
+ except requests.exceptions.ReadTimeout:
128
+ print("timeout")
129
+ info = "Too many users, please try again later"
130
+ raise gr.Error("Too many users, please try again later")
131
+ except Exception as err:
132
+ print(f"其他错误: {err}")
133
+ info = "Error, pleace contact the admin"
134
+ end_time = time.time()
135
+ print(f"time used: {end_time-start_time}")
136
+
137
+ return result_img, seed, info
138
+
139
+ MAX_SEED = 999999
140
 
141
  example_path = os.path.join(os.path.dirname(__file__), 'assets')
 
 
142
 
143
+ garm_list = os.listdir(os.path.join(example_path,"cloth"))
144
+ garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list]
145
+
146
+ human_list = os.listdir(os.path.join(example_path,"human"))
147
+ human_list_path = [os.path.join(example_path,"human",human) for human in human_list]
148
+
149
+ css="""
150
+ #col-left {
151
+ margin: 0 auto;
152
+ max-width: 430px;
153
+ }
154
+ #col-mid {
155
+ margin: 0 auto;
156
+ max-width: 430px;
157
+ }
158
+ #col-right {
159
  margin: 0 auto;
160
  max-width: 430px;
161
  }
 
170
 
171
  def load_description(fp):
172
  with open(fp, 'r', encoding='utf-8') as f:
173
+ content = f.read()
174
+ return content
175
+
176
+ def change_imgs(image1, image2):
177
+ return image1, image2
178
 
179
  with gr.Blocks(css=css) as Tryon:
180
  gr.HTML(load_description("assets/title.md"))
181
  with gr.Row():
182
+ with gr.Column(elem_id = "col-left"):
183
+ gr.HTML("""
184
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
185
+ <div>
186
+ Step 1. Upload a person image ⬇️
187
+ </div>
188
+ </div>
189
+ """)
190
+ with gr.Column(elem_id = "col-mid"):
191
+ gr.HTML("""
192
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
193
+ <div>
194
+ Step 2. Upload a garment image ⬇️
195
+ </div>
196
+ </div>
197
+ """)
198
+ with gr.Column(elem_id = "col-right"):
199
+ gr.HTML("""
200
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
201
+ <div>
202
+ Step 3. Press “Run” to get try-on results
203
+ </div>
204
+ </div>
205
+ """)
206
  with gr.Row():
207
+ with gr.Column(elem_id = "col-left"):
208
  imgs = gr.Image(label="Person image", sources='upload', type="numpy")
209
+ # category = gr.Dropdown(label="Garment category", choices=['upper_body', 'lower_body', 'dresses'], value="upper_body")
210
+ example = gr.Examples(
211
+ inputs=imgs,
212
+ examples_per_page=12,
213
+ examples=human_list_path
214
+ )
215
+ with gr.Column(elem_id = "col-mid"):
216
  garm_img = gr.Image(label="Garment image", sources='upload', type="numpy")
217
+ example = gr.Examples(
218
+ inputs=garm_img,
219
+ examples_per_page=12,
220
+ examples=garm_list_path
221
+ )
222
+ with gr.Column(elem_id = "col-right"):
223
  image_out = gr.Image(label="Result", show_share_button=False)
224
  with gr.Row():
225
+ seed = gr.Slider(
226
+ label="Seed",
227
+ minimum=0,
228
+ maximum=MAX_SEED,
229
+ step=1,
230
+ value=0,
231
+ )
232
  randomize_seed = gr.Checkbox(label="Random seed", value=True)
233
  with gr.Row():
234
  seed_used = gr.Number(label="Seed used")
235
  result_info = gr.Text(label="Response")
236
+ # try_button = gr.Button(value="Run", elem_id="button")
237
+ test_button = gr.Button(value="Run", elem_id="button")
238
+
239
+
240
+ # 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)
241
+ test_button.click(fn=tryon, inputs=[imgs, garm_img, seed, randomize_seed], outputs=[image_out, seed_used, result_info], api_name='tryon', concurrency_limit=40)
242
 
243
+ with gr.Column(elem_id = "col-showcase"):
244
+ gr.HTML("""
245
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
246
+ <div> </div>
247
+ <br>
248
+ <div>
249
+ Virtual try-on examples in pairs of person and garment images
250
+ </div>
251
+ </div>
252
+ """)
253
+ show_case = gr.Examples(
254
  examples=[
255
  ["assets/examples/model2.png", "assets/examples/garment2.png", "assets/examples/result2.png"],
256
  ["assets/examples/model3.png", "assets/examples/garment3.png", "assets/examples/result3.png"],
257
  ["assets/examples/model1.png", "assets/examples/garment1.png", "assets/examples/result1.png"],
258
  ],
259
+ inputs=[imgs, garm_img, image_out],
260
+ label=None
261
  )
262
 
263
+ # ip = requests.get('http://ifconfig.me/ip', timeout=1).text.strip()
264
+ # print("ip address", ip)
265
+ Tryon.launch()