zaghamrasool commited on
Commit
3f88f2c
Β·
verified Β·
1 Parent(s): 7433d63
Files changed (1) hide show
  1. app.py +6 -175
app.py CHANGED
@@ -1,181 +1,12 @@
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
- # βœ… Fixed the environment variable issue here
12
- os.environ['tryon_url'] = "127.0.0.1:5000/"
13
- os.environ['token'] = "dummy_token"
14
- os.environ['Cookie'] = "dummy_cookie"
15
- os.environ['referer'] = "http://localhost"
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
- gr.Warning("Empty image")
21
- return None, None, "Empty image"
22
  if randomize_seed:
23
  seed = random.randint(0, MAX_SEED)
24
- encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
25
- encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
26
- encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
27
- encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
28
-
29
- url = "http://" + os.environ['tryon_url'] + "Submit"
30
- token = os.environ['token']
31
- cookie = os.environ['Cookie']
32
- referer = os.environ['referer']
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
- try:
40
- response = requests.post(url, headers=headers, data=json.dumps(data), timeout=50)
41
- if response.status_code == 200:
42
- result = response.json()['result']
43
- status = result['status']
44
- if status == "success":
45
- uuid = result['result']
46
- except Exception as err:
47
- print(f"Post Exception Error: {err}")
48
- raise gr.Error("Too many users, please try again later")
49
- post_end_time = time.time()
50
- print(f"post time used: {post_end_time-post_start_time}")
51
-
52
- get_start_time = time.time()
53
- time.sleep(9)
54
- Max_Retry = 12
55
- result_img = None
56
- info = ""
57
- err_log = ""
58
- for i in range(Max_Retry):
59
- try:
60
- url = "http://" + os.environ['tryon_url'] + "Query?taskId=" + uuid
61
- response = requests.get(url, headers=headers, timeout=20)
62
- if response.status_code == 200:
63
- result = response.json()['result']
64
- status = result['status']
65
- if status == "success":
66
- result = base64.b64decode(result['result'])
67
- result_np = np.frombuffer(result, np.uint8)
68
- result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
69
- result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
70
- info = "Success"
71
- break
72
- elif status == "error":
73
- err_log = f"Status is Error"
74
- info = "Error"
75
- break
76
- else:
77
- err_log = "URL error, pleace contact the admin"
78
- info = "URL error, pleace contact the admin"
79
- break
80
- except requests.exceptions.ReadTimeout:
81
- err_log = "Http Timeout"
82
- info = "Http Timeout, please try again later"
83
- except Exception as err:
84
- err_log = f"Get Exception Error: {err}"
85
- time.sleep(1)
86
- get_end_time = time.time()
87
- print(f"get time used: {get_end_time-get_start_time}")
88
- print(f"all time used: {get_end_time-get_start_time+post_end_time-post_start_time}")
89
- if info == "":
90
- err_log = f"No image after {Max_Retry} retries"
91
- info = "Too many users, please try again later"
92
- if info != "Success":
93
- print(f"Error Log: {err_log}")
94
- gr.Warning("Too many users, please try again later")
95
-
96
- return result_img, seed, info
97
-
98
- MAX_SEED = 999999
99
-
100
- example_path = os.path.join(os.path.dirname(__file__), 'assets')
101
-
102
- garm_list = os.listdir(os.path.join(example_path,"cloth"))
103
- garm_list_path = [os.path.join(example_path,"cloth",garm) for garm in garm_list]
104
-
105
- human_list = os.listdir(os.path.join(example_path,"human"))
106
- human_list_path = [os.path.join(example_path,"human",human) for human in human_list]
107
-
108
- css="""
109
- #col-left {
110
- margin: 0 auto;
111
- max-width: 430px;
112
- }
113
- #col-mid {
114
- margin: 0 auto;
115
- max-width: 430px;
116
- }
117
- #col-right {
118
- margin: 0 auto;
119
- max-width: 430px;
120
- }
121
- #col-showcase {
122
- margin: 0 auto;
123
- max-width: 1100px;
124
- }
125
- #button {
126
- color: blue;
127
- }
128
- """
129
-
130
- def load_description(fp):
131
- with open(fp, 'r', encoding='utf-8') as f:
132
- content = f.read()
133
- return content
134
-
135
- with gr.Blocks(css=css) as Tryon:
136
- gr.HTML(load_description("assets/title.md"))
137
- with gr.Row():
138
- with gr.Column(elem_id = "col-left"):
139
- gr.HTML("Step 1. Upload a person image ⬇️")
140
- with gr.Column(elem_id = "col-mid"):
141
- gr.HTML("Step 2. Upload a garment image ⬇️")
142
- with gr.Column(elem_id = "col-right"):
143
- gr.HTML("Step 3. Press β€œRun” to get try-on results")
144
-
145
- with gr.Row():
146
- with gr.Column(elem_id = "col-left"):
147
- imgs = gr.Image(label="Person image", sources='upload', type="numpy")
148
- gr.Examples(inputs=imgs, examples_per_page=12, examples=human_list_path)
149
- with gr.Column(elem_id = "col-mid"):
150
- garm_img = gr.Image(label="Garment image", sources='upload', type="numpy")
151
- gr.Examples(inputs=garm_img, examples_per_page=12, examples=garm_list_path)
152
- with gr.Column(elem_id = "col-right"):
153
- image_out = gr.Image(label="Result", show_share_button=False)
154
- with gr.Row():
155
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
156
- randomize_seed = gr.Checkbox(label="Random seed", value=True)
157
- with gr.Row():
158
- seed_used = gr.Number(label="Seed used")
159
- result_info = gr.Text(label="Response")
160
- test_button = gr.Button(value="Run", elem_id="button")
161
-
162
- test_button.click(
163
- fn=tryon,
164
- inputs=[imgs, garm_img, seed, randomize_seed],
165
- outputs=[image_out, seed_used, result_info],
166
- api_name=False,
167
- concurrency_limit=45
168
- )
169
 
170
- with gr.Column(elem_id = "col-showcase"):
171
- gr.HTML("Virtual try-on examples in pairs of person and garment images")
172
- gr.Examples(
173
- examples=[
174
- ["assets/examples/model2.png", "assets/examples/garment2.png", "assets/examples/result2.png"],
175
- ["assets/examples/model3.png", "assets/examples/garment3.png", "assets/examples/result3.png"],
176
- ["assets/examples/model1.png", "assets/examples/garment1.png", "assets/examples/result1.png"],
177
- ],
178
- inputs=[imgs, garm_img, image_out]
179
- )
180
 
181
- Tryon.queue(api_open=False).launch(show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def tryon(person_img, garment_img, seed, randomize_seed):
 
2
  if person_img is None or garment_img is None:
3
+ return None, seed, "❌ Please upload both images"
4
+
5
  if randomize_seed:
6
  seed = random.randint(0, MAX_SEED)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # Dummy white image with text for demo
9
+ dummy_result = np.ones((512, 384, 3), dtype=np.uint8) * 255
10
+ cv2.putText(dummy_result, "🎨 Demo Output", (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3)
 
 
 
 
 
 
 
11
 
12
+ return dummy_result, seed, "βœ… Demo output generated"