Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -8,229 +8,131 @@ 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 |
-
|
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,
|
42 |
if response.status_code == 200:
|
43 |
-
result = response.json()
|
44 |
-
|
45 |
-
|
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 |
-
#
|
57 |
get_start_time = time.time()
|
58 |
-
time.sleep(
|
59 |
-
Max_Retry =
|
60 |
result_img = None
|
61 |
info = ""
|
62 |
err_log = ""
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
if
|
73 |
-
result =
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
break
|
83 |
-
|
84 |
-
err_log = "
|
85 |
-
info = "
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
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(
|
106 |
|
107 |
return result_img, seed, info
|
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 = {
|
133 |
-
"clothImage": encoded_garment_img,
|
134 |
-
"humanImage": encoded_person_img,
|
135 |
-
"seed": seed
|
136 |
-
}
|
137 |
-
|
138 |
-
result_img = None
|
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']
|
145 |
-
if status == "success":
|
146 |
-
result = base64.b64decode(result['result'])
|
147 |
-
result_np = np.frombuffer(result, np.uint8)
|
148 |
-
result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
|
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 |
-
|
164 |
-
return result_img, seed, info
|
165 |
-
|
166 |
-
MAX_SEED = 999999
|
167 |
-
|
168 |
-
example_path = os.path.join(os.path.dirname(__file__), 'assets')
|
169 |
-
|
170 |
-
garm_list = os.listdir(os.path.join(example_path,"cloth"))
|
171 |
-
garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list]
|
172 |
-
|
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;
|
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 |
with open(fp, 'r', encoding='utf-8') as f:
|
200 |
-
|
201 |
-
return content
|
202 |
|
203 |
-
|
204 |
-
|
|
|
|
|
|
|
|
|
|
|
205 |
|
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 |
-
|
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 |
-
|
231 |
with gr.Column(elem_id="col-mid"):
|
232 |
garm_img = gr.Image(label="Garment image", sources='upload', type="numpy")
|
233 |
-
|
234 |
with gr.Column(elem_id="col-right"):
|
235 |
image_out = gr.Image(label="Result", show_share_button=False)
|
236 |
with gr.Row():
|
@@ -244,20 +146,17 @@ with gr.Blocks(css=css) as Tryon:
|
|
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 |
-
|
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(
|
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 |
Tryon.queue(api_open=False).launch(show_api=False)
|
|
|
|
|
|
|
|
8 |
import json
|
9 |
import time
|
10 |
|
11 |
+
MAX_SEED = 999999
|
12 |
+
example_path = os.path.join(os.path.dirname(__file__), 'assets')
|
13 |
+
garm_list = os.listdir(os.path.join(example_path, "cloth"))
|
14 |
+
garm_list_path = [os.path.join(example_path, "cloth", garm) for garm in garm_list]
|
15 |
+
human_list = os.listdir(os.path.join(example_path, "human"))
|
16 |
+
human_list_path = [os.path.join(example_path, "human", human) for human in human_list]
|
17 |
+
|
18 |
def tryon(person_img, garment_img, seed, randomize_seed):
|
19 |
post_start_time = time.time()
|
|
|
20 |
if person_img is None or garment_img is None:
|
21 |
gr.Warning("Empty image")
|
22 |
return None, None, "Empty image"
|
|
|
23 |
if randomize_seed:
|
24 |
seed = random.randint(0, MAX_SEED)
|
25 |
|
26 |
encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
|
27 |
encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
|
|
|
28 |
encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
|
29 |
encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
|
30 |
|
31 |
+
url = "https://huggingface.co/spaces/zaghamrasool/Z-Virtual-Try-On"
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
data = {
|
33 |
"clothImage": encoded_garment_img,
|
34 |
"humanImage": encoded_person_img,
|
35 |
"seed": seed
|
36 |
}
|
37 |
+
|
38 |
+
uuid = None
|
39 |
try:
|
40 |
+
response = requests.post(url, data=json.dumps(data), timeout=50)
|
41 |
if response.status_code == 200:
|
42 |
+
result = response.json().get('result', {})
|
43 |
+
if result.get('status') == "success":
|
44 |
+
uuid = result.get('result')
|
|
|
|
|
|
|
45 |
except Exception as err:
|
46 |
print(f"Post Exception Error: {err}")
|
47 |
raise gr.Error("Too many users, please try again later")
|
48 |
+
|
49 |
post_end_time = time.time()
|
50 |
+
print(f"post time used: {post_end_time - post_start_time}")
|
51 |
|
52 |
+
# Retry loop
|
53 |
get_start_time = time.time()
|
54 |
+
time.sleep(5)
|
55 |
+
Max_Retry = 20
|
56 |
result_img = None
|
57 |
info = ""
|
58 |
err_log = ""
|
59 |
+
|
60 |
+
if not uuid:
|
61 |
+
err_log = "No task ID received from backend."
|
62 |
+
info = "Failed to get task ID from backend"
|
63 |
+
else:
|
64 |
+
for i in range(Max_Retry):
|
65 |
+
try:
|
66 |
+
url = f"https://huggingface.co/spaces/zaghamrasool/Z-Virtual-Try-On/SubmitQuery?taskId={uuid}"
|
67 |
+
response = requests.get(url, timeout=20)
|
68 |
+
if response.status_code == 200:
|
69 |
+
result = response.json()['result']
|
70 |
+
status = result['status']
|
71 |
+
if status == "success":
|
72 |
+
result = base64.b64decode(result['result'])
|
73 |
+
result_np = np.frombuffer(result, np.uint8)
|
74 |
+
result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
|
75 |
+
result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
|
76 |
+
info = "Success"
|
77 |
+
break
|
78 |
+
elif status == "error":
|
79 |
+
err_log = "Status is Error"
|
80 |
+
info = "Error"
|
81 |
+
break
|
82 |
+
else:
|
83 |
+
err_log = "URL error, please contact the admin"
|
84 |
+
info = "URL error, please contact the admin"
|
85 |
break
|
86 |
+
except requests.exceptions.ReadTimeout:
|
87 |
+
err_log = "Http Timeout"
|
88 |
+
info = "Http Timeout, please try again later"
|
89 |
+
except Exception as err:
|
90 |
+
err_log = f"Get Exception Error: {err}"
|
91 |
+
time.sleep(5)
|
92 |
+
|
|
|
|
|
|
|
|
|
|
|
93 |
get_end_time = time.time()
|
94 |
+
print(f"get time used: {get_end_time - get_start_time}")
|
95 |
+
print(f"all time used: {get_end_time - get_start_time + post_end_time - post_start_time}")
|
96 |
+
|
97 |
if info == "":
|
98 |
err_log = f"No image after {Max_Retry} retries"
|
99 |
info = "Too many users, please try again later"
|
|
|
100 |
if info != "Success":
|
101 |
print(f"Error Log: {err_log}")
|
102 |
+
gr.Warning(info)
|
103 |
|
104 |
return result_img, seed, info
|
105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
def load_description(fp):
|
107 |
with open(fp, 'r', encoding='utf-8') as f:
|
108 |
+
return f.read()
|
|
|
109 |
|
110 |
+
css = """
|
111 |
+
#col-left { margin: 0 auto; max-width: 430px; }
|
112 |
+
#col-mid { margin: 0 auto; max-width: 430px; }
|
113 |
+
#col-right { margin: 0 auto; max-width: 430px; }
|
114 |
+
#col-showcase { margin: 0 auto; max-width: 1100px; }
|
115 |
+
#button { color: blue; }
|
116 |
+
"""
|
117 |
|
118 |
with gr.Blocks(css=css) as Tryon:
|
119 |
gr.HTML(load_description("assets/title.md"))
|
120 |
+
|
121 |
with gr.Row():
|
122 |
with gr.Column(elem_id="col-left"):
|
123 |
+
gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 1. Upload a person image ⬇️</div>")
|
|
|
|
|
|
|
|
|
124 |
with gr.Column(elem_id="col-mid"):
|
125 |
+
gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 2. Upload a garment image ⬇️</div>")
|
|
|
|
|
|
|
|
|
126 |
with gr.Column(elem_id="col-right"):
|
127 |
+
gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 3. Press “Run” to get try-on results</div>")
|
128 |
+
|
|
|
|
|
|
|
129 |
with gr.Row():
|
130 |
with gr.Column(elem_id="col-left"):
|
131 |
imgs = gr.Image(label="Person image", sources='upload', type="numpy")
|
132 |
+
gr.Examples(inputs=imgs, examples_per_page=12, examples=human_list_path)
|
133 |
with gr.Column(elem_id="col-mid"):
|
134 |
garm_img = gr.Image(label="Garment image", sources='upload', type="numpy")
|
135 |
+
gr.Examples(inputs=garm_img, examples_per_page=12, examples=garm_list_path)
|
136 |
with gr.Column(elem_id="col-right"):
|
137 |
image_out = gr.Image(label="Result", show_share_button=False)
|
138 |
with gr.Row():
|
|
|
146 |
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)
|
147 |
|
148 |
with gr.Column(elem_id="col-showcase"):
|
149 |
+
gr.HTML("<div style='text-align: center; font-size: 20px;'>Virtual try-on examples in pairs of person and garment images</div>")
|
150 |
+
gr.Examples(
|
|
|
|
|
|
|
|
|
|
|
151 |
examples=[
|
152 |
["assets/examples/model2.png", "assets/examples/garment2.png", "assets/examples/result2.png"],
|
153 |
["assets/examples/model3.png", "assets/examples/garment3.png", "assets/examples/result3.png"],
|
154 |
+
["assets/examples/model1.png", "assets/examples/garment1.png", "assets/examples/result1.png"]
|
155 |
],
|
156 |
+
inputs=[imgs, garm_img, image_out]
|
|
|
157 |
)
|
158 |
|
159 |
Tryon.queue(api_open=False).launch(show_api=False)
|
160 |
+
Tryon.launch()
|
161 |
+
print("Gradio app is running...")
|
162 |
+
print("Please open the link in your browser to access the app.")
|