angolinn commited on
Commit
e124496
·
verified ·
1 Parent(s): b9e37b2

Update app.py

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