bijoy01 commited on
Commit
b4c9518
·
verified ·
1 Parent(s): 626859c

Update app.py

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