Erfantgh1998 commited on
Commit
31052aa
·
verified ·
1 Parent(s): 5e28591

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +234 -40
app.py CHANGED
@@ -7,16 +7,12 @@ import base64
7
  import requests
8
  import json
9
  import time
10
- from dotenv import load_dotenv
11
 
12
- # بارگذاری متغیرهای محیطی از فایل .env
13
- load_dotenv()
14
-
15
- MAX_SEED = 999999
16
 
17
  def tryon(person_img, garment_img, seed, randomize_seed):
18
  post_start_time = time.time()
19
  if person_img is None or garment_img is None:
 
20
  return None, None, "Empty image"
21
  if randomize_seed:
22
  seed = random.randint(0, MAX_SEED)
@@ -25,10 +21,10 @@ def tryon(person_img, garment_img, seed, randomize_seed):
25
  encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
26
  encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
27
 
28
- url = os.getenv('tryon_url') + "Submit"
29
- token = os.getenv('token')
30
- cookie = os.getenv('Cookie')
31
- referer = os.getenv('referer')
32
  headers = {'Content-Type': 'application/json', 'token': token, 'Cookie': cookie, 'referer': referer}
33
  data = {
34
  "clothImage": encoded_garment_img,
@@ -37,16 +33,20 @@ def tryon(person_img, garment_img, seed, randomize_seed):
37
  }
38
  try:
39
  response = requests.post(url, headers=headers, data=json.dumps(data), timeout=50)
 
40
  if response.status_code == 200:
41
  result = response.json()['result']
42
  status = result['status']
43
  if status == "success":
44
  uuid = result['result']
 
45
  except Exception as err:
46
- return None, None, f"Post Exception Error: {err}"
 
47
  post_end_time = time.time()
 
48
 
49
- get_start_time = time.time()
50
  time.sleep(9)
51
  Max_Retry = 12
52
  result_img = None
@@ -54,8 +54,9 @@ def tryon(person_img, garment_img, seed, randomize_seed):
54
  err_log = ""
55
  for i in range(Max_Retry):
56
  try:
57
- url = os.getenv('tryon_url') + "Query?taskId=" + uuid
58
  response = requests.get(url, headers=headers, timeout=20)
 
59
  if response.status_code == 200:
60
  result = response.json()['result']
61
  status = result['status']
@@ -71,8 +72,9 @@ def tryon(person_img, garment_img, seed, randomize_seed):
71
  info = "Error"
72
  break
73
  else:
74
- err_log = "URL error, please contact the admin"
75
- info = "URL error, please contact the admin"
 
76
  break
77
  except requests.exceptions.ReadTimeout:
78
  err_log = "Http Timeout"
@@ -81,49 +83,241 @@ def tryon(person_img, garment_img, seed, randomize_seed):
81
  err_log = f"Get Exception Error: {err}"
82
  time.sleep(1)
83
  get_end_time = time.time()
 
 
84
  if info == "":
85
  err_log = f"No image after {Max_Retry} retries"
86
  info = "Too many users, please try again later"
87
  if info != "Success":
88
- return None, None, f"Error Log: {err_log}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  return result_img, seed, info
91
 
92
- def run_tryon(person_img, garment_img, seed=0, randomize_seed=True):
93
- result_img, seed_used, info = tryon(person_img, garment_img, seed, randomize_seed)
94
- if result_img is not None:
95
- return result_img, f"Seed used: {seed_used}", f"Response: {info}"
96
- else:
97
- return None, f"Seed used: {seed_used}", f"Response: {info}"
98
 
99
  example_path = os.path.join(os.path.dirname(__file__), 'assets')
 
 
100
  cloth_dir = os.path.join(example_path, "cloth")
101
  human_dir = os.path.join(example_path, "human")
102
 
 
 
 
103
  if not os.path.exists(cloth_dir):
104
  os.makedirs(cloth_dir)
 
105
  if not os.path.exists(human_dir):
106
  os.makedirs(human_dir)
 
107
 
 
108
  garm_list = os.listdir(cloth_dir) if os.path.exists(cloth_dir) else []
 
 
109
  human_list = os.listdir(human_dir) if os.path.exists(human_dir) else []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
- demo = gr.Interface(
112
- fn=run_tryon,
113
- inputs=[
114
- gr.inputs.Image(type="numpy", label="Upload a person image"),
115
- gr.inputs.Image(type="numpy", label="Upload a garment image"),
116
- gr.inputs.Slider(0, MAX_SEED, step=1, default=0, label="Seed"),
117
- gr.inputs.Checkbox(default=True, label="Random seed")
118
- ],
119
- outputs=[
120
- gr.outputs.Image(type="numpy", label="Result Image"),
121
- gr.outputs.Textbox(label="Seed used"),
122
- gr.outputs.Textbox(label="Response")
123
- ],
124
- title="Virtual Try-On Application",
125
- description="Upload a person image and a garment image to try on the garment virtually."
126
- )
127
-
128
- if __name__ == "__main__":
129
- demo.launch()
 
7
  import requests
8
  import json
9
  import time
 
10
 
 
 
 
 
11
 
12
  def tryon(person_img, garment_img, seed, randomize_seed):
13
  post_start_time = time.time()
14
  if person_img is None or garment_img is None:
15
+ gr.Warning("Empty image")
16
  return None, None, "Empty image"
17
  if randomize_seed:
18
  seed = random.randint(0, MAX_SEED)
 
21
  encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
22
  encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
23
 
24
+ url = "http://" + os.environ['tryon_url'] + "Submit"
25
+ token = os.environ['token']
26
+ cookie = os.environ['Cookie']
27
+ referer = os.environ['referer']
28
  headers = {'Content-Type': 'application/json', 'token': token, 'Cookie': cookie, 'referer': referer}
29
  data = {
30
  "clothImage": encoded_garment_img,
 
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
 
54
  err_log = ""
55
  for i in range(Max_Retry):
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
  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"
 
83
  err_log = f"Get Exception Error: {err}"
84
  time.sleep(1)
85
  get_end_time = time.time()
86
+ print(f"get time used: {get_end_time-get_start_time}")
87
+ print(f"all time used: {get_end_time-get_start_time+post_end_time-post_start_time}")
88
  if info == "":
89
  err_log = f"No image after {Max_Retry} retries"
90
  info = "Too many users, please try again later"
91
  if info != "Success":
92
+ print(f"Error Log: {err_log}")
93
+ gr.Warning("Too many users, please try again later")
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:
100
+ return None, None, "Empty image"
101
+ if randomize_seed:
102
+ seed = random.randint(0, MAX_SEED)
103
+ encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
104
+ encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
105
+ encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
106
+ encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
107
+
108
+ url = "http://" + os.environ['tryon_url']
109
+ token = os.environ['token']
110
+ cookie = os.environ['Cookie']
111
+ referer = os.environ['referer']
112
+
113
+ headers = {'Content-Type': 'application/json', 'token': token, 'Cookie': cookie, 'referer': referer}
114
+ data = {
115
+ "clothImage": encoded_garment_img,
116
+ "humanImage": encoded_person_img,
117
+ "seed": seed
118
+ }
119
+
120
+ result_img = None
121
+ try:
122
+ session = requests.Session()
123
+ response = session.post(url, headers=headers, data=json.dumps(data), timeout=60)
124
+ print("response code", response.status_code)
125
+ if response.status_code == 200:
126
+ result = response.json()['result']
127
+ status = result['status']
128
+ if status == "success":
129
+ result = base64.b64decode(result['result'])
130
+ result_np = np.frombuffer(result, np.uint8)
131
+ result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
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
+ # بررسی و ایجاد دایرکتوری‌های مورد نیاز
156
  cloth_dir = os.path.join(example_path, "cloth")
157
  human_dir = os.path.join(example_path, "human")
158
 
159
+ # ایجاد دایرکتوری‌ها اگر وجود ندارند
160
+ if not os.path.exists(example_path):
161
+ os.makedirs(example_path)
162
  if not os.path.exists(cloth_dir):
163
  os.makedirs(cloth_dir)
164
+ print(f"Created directory: {cloth_dir}")
165
  if not os.path.exists(human_dir):
166
  os.makedirs(human_dir)
167
+ print(f"Created directory: {human_dir}")
168
 
169
+ # بررسی محتوای دایرکتوری‌ها - اگر خالی هستند، با لیست‌های خالی مقداردهی می‌شوند
170
  garm_list = os.listdir(cloth_dir) if os.path.exists(cloth_dir) else []
171
+ garm_list_path = [os.path.join(cloth_dir, garm) for garm in garm_list]
172
+
173
  human_list = os.listdir(human_dir) if os.path.exists(human_dir) else []
174
+ human_list_path = [os.path.join(human_dir, human) for human in human_list]
175
+
176
+ css="""
177
+ #col-left {
178
+ margin: 0 auto;
179
+ max-width: 430px;
180
+ }
181
+ #col-mid {
182
+ margin: 0 auto;
183
+ max-width: 430px;
184
+ }
185
+ #col-right {
186
+ margin: 0 auto;
187
+ max-width: 430px;
188
+ }
189
+ #col-showcase {
190
+ margin: 0 auto;
191
+ max-width: 1100px;
192
+ }
193
+ #button {
194
+ color: blue;
195
+ }
196
+ """
197
+
198
+ def load_description(fp):
199
+ # بررسی وجود فایل توضیحات
200
+ if not os.path.exists(fp):
201
+ print(f"Warning: Description file {fp} not found")
202
+ return "Welcome to Virtual Try-On"
203
+
204
+ with open(fp, 'r', encoding='utf-8') as f:
205
+ content = f.read()
206
+ return content
207
+
208
+ def change_imgs(image1, image2):
209
+ return image1, image2
210
+
211
+ # بررسی وجود دایرکتوری examples
212
+ examples_dir = os.path.join(example_path, "examples")
213
+ if not os.path.exists(examples_dir):
214
+ os.makedirs(examples_dir)
215
+ print(f"Created directory: {examples_dir}")
216
+
217
+ with gr.Blocks(css=css) as Tryon:
218
+ # بررسی وجود فایل عنوان
219
+ title_path = os.path.join(example_path, "title.md")
220
+ if not os.path.exists(title_path):
221
+ with open(title_path, 'w', encoding='utf-8') as f:
222
+ f.write("# Virtual Try-On Application\n\nUpload a person image and a garment image to see the virtual try-on result.")
223
+ print(f"Created title file: {title_path}")
224
+
225
+ gr.HTML(load_description("assets/title.md"))
226
+ with gr.Row():
227
+ with gr.Column(elem_id = "col-left"):
228
+ gr.HTML("""
229
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
230
+ <div>
231
+ Step 1. Upload a person image ⬇️
232
+ </div>
233
+ </div>
234
+ """)
235
+ with gr.Column(elem_id = "col-mid"):
236
+ gr.HTML("""
237
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
238
+ <div>
239
+ Step 2. Upload a garment image ⬇️
240
+ </div>
241
+ </div>
242
+ """)
243
+ with gr.Column(elem_id = "col-right"):
244
+ gr.HTML("""
245
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
246
+ <div>
247
+ Step 3. Press "Run" to get try-on results
248
+ </div>
249
+ </div>
250
+ """)
251
+ with gr.Row():
252
+ with gr.Column(elem_id = "col-left"):
253
+ imgs = gr.Image(label="Person image", sources='upload', type="numpy")
254
+ # category = gr.Dropdown(label="Garment category", choices=['upper_body', 'lower_body', 'dresses'], value="upper_body")
255
+ example = gr.Examples(
256
+ inputs=imgs,
257
+ examples_per_page=12,
258
+ examples=human_list_path
259
+ )
260
+ with gr.Column(elem_id = "col-mid"):
261
+ garm_img = gr.Image(label="Garment image", sources='upload', type="numpy")
262
+ example = gr.Examples(
263
+ inputs=garm_img,
264
+ examples_per_page=12,
265
+ examples=garm_list_path
266
+ )
267
+ with gr.Column(elem_id = "col-right"):
268
+ image_out = gr.Image(label="Result", show_share_button=False)
269
+ with gr.Row():
270
+ seed = gr.Slider(
271
+ label="Seed",
272
+ minimum=0,
273
+ maximum=MAX_SEED,
274
+ step=1,
275
+ value=0,
276
+ )
277
+ randomize_seed = gr.Checkbox(label="Random seed", value=True)
278
+ with gr.Row():
279
+ seed_used = gr.Number(label="Seed used")
280
+ result_info = gr.Text(label="Response")
281
+ # try_button = gr.Button(value="Run", elem_id="button")
282
+ test_button = gr.Button(value="Run", elem_id="button")
283
+
284
+
285
+ # 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)
286
+ 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)
287
+
288
+ # بررسی وجود فایل‌های نمونه
289
+ example_files = [
290
+ ["assets/examples/model2.png", "assets/examples/garment2.png", "assets/examples/result2.png"],
291
+ ["assets/examples/model3.png", "assets/examples/garment3.png", "assets/examples/result3.png"],
292
+ ["assets/examples/model1.png", "assets/examples/garment1.png", "assets/examples/result1.png"],
293
+ ]
294
+
295
+ existing_examples = []
296
+ for example_set in example_files:
297
+ if all(os.path.exists(path) for path in example_set):
298
+ existing_examples.append(example_set)
299
+
300
+ with gr.Column(elem_id = "col-showcase"):
301
+ gr.HTML("""
302
+ <div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
303
+ <div> </div>
304
+ <br>
305
+ <div>
306
+ Virtual try-on examples in pairs of person and garment images
307
+ </div>
308
+ </div>
309
+ """)
310
+ if existing_examples:
311
+ show_case = gr.Examples(
312
+ examples=existing_examples,
313
+ inputs=[imgs, garm_img, image_out],
314
+ label=None
315
+ )
316
+ else:
317
+ gr.HTML("""
318
+ <div style="text-align: center;">
319
+ <p>No example images found. Please add example images to the 'assets/examples' directory.</p>
320
+ </div>
321
+ """)
322
 
323
+ Tryon.queue(api_open=False).launch(show_api=False)