zaghamrasool commited on
Commit
2f400e5
·
verified ·
1 Parent(s): 5a38175

Update app.py

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