File size: 11,284 Bytes
f69cd15 eaa8689 1ecb321 eaa8689 5cbc9b1 6af3026 f8801dc 18f423a 7187944 4caf25d 18f423a 7187944 4e460bd 18f423a 5d19a11 18f423a 7187944 18f423a 7187944 18f423a 7187944 73cb919 5b58307 7187944 18f423a 4e460bd 7187944 8947405 a079d6c 5b58307 7187944 4e460bd 5b58307 4e460bd 7187944 24f237b e4c119e d25f2a3 a079d6c 8d83455 7187944 4e460bd 7187944 4e460bd b470d34 8d83455 2231fef 5d19a11 18f423a 7187944 5d19a11 7187944 4e460bd 8d83455 5d19a11 b6434bc 8d83455 4284d10 7187944 4e460bd 5b58307 a079d6c 7187944 22a00a3 8d83455 a079d6c 8d83455 5d19a11 18f423a 1ecb321 eaa8689 f8801dc dbe8337 0805db6 eaa8689 7187944 8c2fca3 eaa8689 8c2fca3 eaa8689 8654223 7187944 49eabb6 7187944 6af3026 b453f9d 0c1a8d3 4ad0645 7187944 0c1a8d3 7187944 b453f9d 0c1a8d3 7187944 0c1a8d3 64d0526 0c1a8d3 7187944 f8801dc 6af3026 b453f9d 1ecb321 534e5bb f69cd15 1ecb321 f69cd15 4dd113c 01db67e 4dd113c f69cd15 1ecb321 4dd113c f69cd15 4db4e89 a9ba2aa 4db4e89 f69cd15 1ecb321 f69cd15 1ecb321 f69cd15 01db67e bd8fedc 070a1ae bd8fedc 13ac53c bd8fedc ad30fcb bd8fedc 070a1ae bd8fedc 13ac53c bd8fedc ad30fcb bd8fedc 070a1ae bd8fedc 7187944 bd8fedc ad30fcb 4311e2a f69cd15 1e19884 f69cd15 1ecb321 01db67e 4311e2a f69cd15 1e19884 cc17840 01db67e fa6131f b453f9d 7de6d0d 534e5bb 7de6d0d fa6131f 7de6d0d b470d34 7de6d0d 7187944 1ecb321 4db4e89 537454a 070a1ae 6c767ec 291f384 537454a 070a1ae 537454a d562784 4db4e89 68b15ec 878600a 394c62a 4db4e89 a9ba2aa 5900e16 4db4e89 d77e663 7187944 93de4ad 7187944 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
import os
import cv2
import gradio as gr
import numpy as np
import random
import base64
import requests
import json
import time
# Environment variables
TRYON_URL = os.getenv('TRYON_URL')
TOKEN = os.getenv('TOKEN')
COOKIE = os.getenv('COOKIE')
REFERER = os.getenv('REFERER')
# Environment variables kontrolü
if not all([TRYON_URL, TOKEN, COOKIE, REFERER]):
print("Warning: Some environment variables are missing!")
print(f"TRYON_URL: {'Set' if TRYON_URL else 'Missing'}")
print(f"TOKEN: {'Set' if TOKEN else 'Missing'}")
print(f"COOKIE: {'Set' if COOKIE else 'Missing'}")
print(f"REFERER: {'Set' if REFERER else 'Missing'}")
MAX_SEED = 999999
def tryon(person_img, garment_img, seed, randomize_seed):
if not all([TRYON_URL, TOKEN, COOKIE, REFERER]):
raise gr.Error("Server configuration is missing. Please contact administrator.")
post_start_time = time.time()
if person_img is None or garment_img is None:
gr.Warning("Empty image")
return None, None, "Empty image"
if randomize_seed:
seed = random.randint(0, MAX_SEED)
try:
# Resim kodlama
encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
# URL oluşturma
if not TRYON_URL.startswith(('http://', 'https://')):
base_url = f"https://{TRYON_URL}"
else:
base_url = TRYON_URL
url = f"{base_url.rstrip('/')}/Submit"
headers = {
'Content-Type': 'application/json',
'token': TOKEN,
'Cookie': COOKIE,
'referer': REFERER
}
data = {
"clothImage": encoded_garment_img,
"humanImage": encoded_person_img,
"seed": seed
}
response = requests.post(url, headers=headers, data=json.dumps(data), timeout=50)
print("post response code", response.status_code)
if response.status_code == 200:
result = response.json()['result']
status = result['status']
if status == "success":
uuid = result['result']
print(uuid)
except Exception as err:
print(f"Post Exception Error: {err}")
raise gr.Error("Too many users, please try again later")
post_end_time = time.time()
print(f"post time used: {post_end_time-post_start_time}")
get_start_time = time.time()
time.sleep(9)
Max_Retry = 12
result_img = None
info = ""
err_log = ""
for i in range(Max_Retry):
try:
query_url = f"{base_url.rstrip('/')}/Query?taskId={uuid}"
response = requests.get(query_url, headers=headers, timeout=20)
print("get response code", response.status_code)
if response.status_code == 200:
result = response.json()['result']
status = result['status']
if status == "success":
result = base64.b64decode(result['result'])
result_np = np.frombuffer(result, np.uint8)
result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
info = "Success"
break
elif status == "error":
err_log = f"Status is Error"
info = "Error"
break
else:
err_log = "URL error, please contact the admin"
info = "URL error, please contact the admin"
break
except requests.exceptions.ReadTimeout:
err_log = "Http Timeout"
info = "Http Timeout, please try again later"
except Exception as err:
err_log = f"Get Exception Error: {err}"
time.sleep(1)
get_end_time = time.time()
print(f"get time used: {get_end_time-get_start_time}")
print(f"all time used: {get_end_time-get_start_time+post_end_time-post_start_time}")
if info == "":
err_log = f"No image after {Max_Retry} retries"
info = "Too many users, please try again later"
if info != "Success":
print(f"Error Log: {err_log}")
gr.Warning("Too many users, please try again later")
return result_img, seed, info
def start_tryon(person_img, garment_img, seed, randomize_seed):
start_time = time.time()
if person_img is None or garment_img is None:
return None, None, "Empty image"
if randomize_seed:
seed = random.randint(0, MAX_SEED)
encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
if not TRYON_URL.startswith(('http://', 'https://')):
base_url = f"https://{TRYON_URL}"
else:
base_url = TRYON_URL
headers = {
'Content-Type': 'application/json',
'token': TOKEN,
'Cookie': COOKIE,
'referer': REFERER
}
data = {
"clothImage": encoded_garment_img,
"humanImage": encoded_person_img,
"seed": seed
}
result_img = None
try:
session = requests.Session()
response = session.post(base_url, headers=headers, data=json.dumps(data), timeout=60)
print("response code", response.status_code)
if response.status_code == 200:
result = response.json()['result']
status = result['status']
if status == "success":
result = base64.b64decode(result['result'])
result_np = np.frombuffer(result, np.uint8)
result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
info = "Success"
else:
info = "Try again later"
else:
print(response.text)
info = "URL error, please contact the admin"
except requests.exceptions.ReadTimeout:
print("timeout")
info = "Too many users, please try again later"
raise gr.Error("Too many users, please try again later")
except Exception as err:
print(f"Error: {err}")
info = "Error, please contact the admin"
end_time = time.time()
print(f"time used: {end_time-start_time}")
return result_img, seed, info
example_path = os.path.join(os.path.dirname(__file__), 'assets')
garm_list = os.listdir(os.path.join(example_path,"cloth"))
garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list]
human_list = os.listdir(os.path.join(example_path,"human"))
human_list_path = [os.path.join(example_path,"human",human) for human in human_list]
css="""
#col-left {
margin: 0 auto;
max-width: 430px;
}
#col-mid {
margin: 0 auto;
max-width: 430px;
}
#col-right {
margin: 0 auto;
max-width: 430px;
}
#col-showcase {
margin: 0 auto;
max-width: 1100px;
}
#button {
color: blue;
}
"""
def load_description(fp):
with open(fp, 'r', encoding='utf-8') as f:
content = f.read()
return content
with gr.Blocks(css=css) as Tryon:
gr.HTML(load_description("assets/title.md"))
with gr.Row():
with gr.Column(elem_id = "col-left"):
gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div>
Step 1. Upload a person image ⬇️
</div>
</div>
""")
with gr.Column(elem_id = "col-mid"):
gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div>
Step 2. Upload a garment image ⬇️
</div>
</div>
""")
with gr.Column(elem_id = "col-right"):
gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div>
Step 3. Press "Run" to get try-on results
</div>
</div>
""")
with gr.Row():
with gr.Column(elem_id = "col-left"):
imgs = gr.Image(label="Person image", sources='upload', type="numpy")
example = gr.Examples(
inputs=imgs,
examples_per_page=12,
examples=human_list_path
)
with gr.Column(elem_id = "col-mid"):
garm_img = gr.Image(label="Garment image", sources='upload', type="numpy")
example = gr.Examples(
inputs=garm_img,
examples_per_page=12,
examples=garm_list_path
)
with gr.Column(elem_id = "col-right"):
image_out = gr.Image(label="Result", show_share_button=False)
with gr.Row():
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=0,
)
randomize_seed = gr.Checkbox(label="Random seed", value=True)
with gr.Row():
seed_used = gr.Number(label="Seed used")
result_info = gr.Text(label="Response")
test_button = gr.Button(value="Run", elem_id="button")
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
)
with gr.Column(elem_id = "col-showcase"):
gr.HTML("""
<div style="display: flex; justify-content: center; align-items: center; text-align: center; font-size: 20px;">
<div> </div>
<br>
<div>
Virtual try-on examples in pairs of person and garment images
</div>
</div>
""")
show_case = gr.Examples(
examples=[
["assets/examples/model2.png", "assets/examples/garment2.png", "assets/examples/result2.png"],
["assets/examples/model3.png", "assets/examples/garment3.png", "assets/examples/result3.png"],
["assets/examples/model1.png", "assets/examples/garment1.png", "assets/examples/result1.png"],
],
inputs=[imgs, garm_img, image_out],
label=None
)
# Uygulamayı başlat
Tryon.queue(api_open=False).launch(
server_name="0.0.0.0",
show_api=False,
debug=True
) |