zaghamrasool commited on
Commit
9c91c6f
·
verified ·
1 Parent(s): af6493c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -120
app.py CHANGED
@@ -3,118 +3,42 @@ 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
  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
- # API details
19
- base_url = "https://huggingface.co/spaces/zaghamrasool/Z-Virtual-Try-On"
20
- upload_image_url = f"{base_url}/upload_image"
21
- create_save_task_url = f"{base_url}/create_save_task"
22
- execute_task_url = f"{base_url}/execute_task"
23
- query_task_url = f"{base_url}/query_task"
24
-
25
- def tryon(person_img, garment_img, seed, randomize_seed):
26
- post_start_time = time.time()
27
  if person_img is None or garment_img is None:
28
- gr.Warning("Empty image")
29
- return None, None, "Empty image"
 
30
  if randomize_seed:
31
  seed = random.randint(0, MAX_SEED)
32
-
33
- # Encode images
34
- encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
35
- encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
36
- encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
37
- encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
38
-
39
- # Prepare data
40
- data = {
41
- "clothImage": encoded_garment_img,
42
- "humanImage": encoded_person_img,
43
- "seed": seed
44
- }
45
-
46
- uuid = None
47
- try:
48
- # First API call to create task
49
- response = requests.post(create_save_task_url, data=json.dumps(data), timeout=50)
50
- if response.status_code == 200:
51
- result = response.json().get('result', {})
52
- if result.get('status') == "success":
53
- uuid = result.get('taskId') # Use taskId for querying
54
- else:
55
- raise Exception("Failed to create task, no task ID received.")
56
- else:
57
- raise Exception(f"Failed to create task. Status Code: {response.status_code}")
58
- except Exception as err:
59
- print(f"Post Exception Error: {err}")
60
- raise gr.Error("Too many users, please try again later")
61
 
62
- post_end_time = time.time()
63
- print(f"post time used: {post_end_time - post_start_time}")
 
 
64
 
65
- # Retry loop to query task status
66
- get_start_time = time.time()
67
- time.sleep(5)
68
- Max_Retry = 20
69
- result_img = None
70
- info = ""
71
- err_log = ""
72
 
73
- if not uuid:
74
- err_log = "No task ID received from backend."
75
- info = "Failed to get task ID from backend"
76
- else:
77
- for i in range(Max_Retry):
78
- try:
79
- url = f"{query_task_url}?taskId={uuid}"
80
- response = requests.get(url, timeout=20)
81
- if response.status_code == 200:
82
- result = response.json()['result']
83
- status = result['status']
84
- if status == "success":
85
- result = base64.b64decode(result['result'])
86
- result_np = np.frombuffer(result, np.uint8)
87
- result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
88
- result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
89
- info = "Success"
90
- break
91
- elif status == "error":
92
- err_log = "Status is Error"
93
- info = "Error"
94
- break
95
- else:
96
- err_log = "URL error, please contact the admin"
97
- info = "URL error, please contact the admin"
98
- break
99
- except requests.exceptions.ReadTimeout:
100
- err_log = "Http Timeout"
101
- info = "Http Timeout, please try again later"
102
- except Exception as err:
103
- err_log = f"Get Exception Error: {err}"
104
- time.sleep(5)
105
 
106
- get_end_time = time.time()
107
- print(f"get time used: {get_end_time - get_start_time}")
108
- print(f"all time used: {get_end_time - get_start_time + post_end_time - post_start_time}")
109
-
110
- if info == "":
111
- err_log = f"No image after {Max_Retry} retries"
112
- info = "Too many users, please try again later"
113
- if info != "Success":
114
- print(f"Error Log: {err_log}")
115
- gr.Warning(info)
116
-
117
- return result_img, seed, info
118
 
119
  def load_description(fp):
120
  with open(fp, 'r', encoding='utf-8') as f:
@@ -133,41 +57,42 @@ with gr.Blocks(css=css) as Tryon:
133
 
134
  with gr.Row():
135
  with gr.Column(elem_id="col-left"):
136
- gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 1. Upload a person image ⬇️</div>")
137
- with gr.Column(elem_id="col-mid"):
138
- gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 2. Upload a garment image ⬇️</div>")
139
- with gr.Column(elem_id="col-right"):
140
- gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 3. Press “Run” to get try-on results</div>")
141
-
142
- with gr.Row():
143
- with gr.Column(elem_id="col-left"):
144
- imgs = gr.Image(label="Person image", sources='upload', type="numpy")
145
  gr.Examples(inputs=imgs, examples_per_page=12, examples=human_list_path)
 
146
  with gr.Column(elem_id="col-mid"):
147
- garm_img = gr.Image(label="Garment image", sources='upload', type="numpy")
 
148
  gr.Examples(inputs=garm_img, examples_per_page=12, examples=garm_list_path)
 
149
  with gr.Column(elem_id="col-right"):
150
- image_out = gr.Image(label="Result", show_share_button=False)
 
151
  with gr.Row():
152
  seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
153
  randomize_seed = gr.Checkbox(label="Random seed", value=True)
154
  with gr.Row():
155
  seed_used = gr.Number(label="Seed used")
156
- result_info = gr.Text(label="Response")
157
- test_button = gr.Button(value="Run", elem_id="button")
158
 
159
- 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)
 
 
 
 
 
160
 
161
  with gr.Column(elem_id="col-showcase"):
162
- gr.HTML("<div style='text-align: center; font-size: 20px;'>Virtual try-on examples in pairs of person and garment images</div>")
163
  gr.Examples(
164
- examples=[["assets/examples/model2.png", "assets/examples/garment2.png", "assets/examples/result2.png"],
165
- ["assets/examples/model3.png", "assets/examples/garment3.png", "assets/examples/result3.png"],
166
- ["assets/examples/model1.png", "assets/examples/garment1.png", "assets/examples/result1.png"]],
167
- inputs=[imgs, garm_img, image_out]
 
 
168
  )
169
 
170
- Tryon.queue(api_open=False).launch(show_api=False)
171
- Tryon.launch()
172
- print("Gradio app is running...")
173
- print("Please open the link in your browser to access the app.")
 
3
  import gradio as gr
4
  import numpy as np
5
  import random
 
 
 
 
6
 
7
  MAX_SEED = 999999
8
  example_path = os.path.join(os.path.dirname(__file__), 'assets')
9
+
10
+ # Load example images
11
  garm_list = os.listdir(os.path.join(example_path, "cloth"))
12
  garm_list_path = [os.path.join(example_path, "cloth", garm) for garm in garm_list]
13
  human_list = os.listdir(os.path.join(example_path, "human"))
14
  human_list_path = [os.path.join(example_path, "human", human) for human in human_list]
15
 
16
+ def mock_tryon(person_img, garment_img, seed, randomize_seed, progress=gr.Progress()):
17
+ progress(0, desc="Starting mock try-on...")
18
+
 
 
 
 
 
 
19
  if person_img is None or garment_img is None:
20
+ gr.Warning("Please upload both images!")
21
+ return None, None, "Error: Empty image"
22
+
23
  if randomize_seed:
24
  seed = random.randint(0, MAX_SEED)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ progress(0.3, desc="Processing person image...")
27
+ # Convert to grayscale for demo (replace with actual try-on logic)
28
+ person_gray = cv2.cvtColor(person_img, cv2.COLOR_RGB2GRAY)
29
+ person_gray = cv2.cvtColor(person_gray, cv2.COLOR_GRAY2RGB)
30
 
31
+ progress(0.6, desc="Adding garment...")
32
+ # Resize garment to fit person (demo only)
33
+ garment_resized = cv2.resize(garment_img, (person_img.shape[1], person_img.shape[0]))
 
 
 
 
34
 
35
+ progress(0.8, desc="Blending images...")
36
+ # Simple alpha blending (replace with real try-on)
37
+ alpha = 0.7
38
+ result = cv2.addWeighted(person_gray, 1-alpha, garment_resized, alpha, 0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ progress(1.0, desc="Done!")
41
+ return result, seed, "Mock try-on complete"
 
 
 
 
 
 
 
 
 
 
42
 
43
  def load_description(fp):
44
  with open(fp, 'r', encoding='utf-8') as f:
 
57
 
58
  with gr.Row():
59
  with gr.Column(elem_id="col-left"):
60
+ gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 1. Upload person ⬇️</div>")
61
+ imgs = gr.Image(label="Person", sources='upload', type="numpy")
 
 
 
 
 
 
 
62
  gr.Examples(inputs=imgs, examples_per_page=12, examples=human_list_path)
63
+
64
  with gr.Column(elem_id="col-mid"):
65
+ gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 2. Upload garment ⬇️</div>")
66
+ garm_img = gr.Image(label="Garment", sources='upload', type="numpy")
67
  gr.Examples(inputs=garm_img, examples_per_page=12, examples=garm_list_path)
68
+
69
  with gr.Column(elem_id="col-right"):
70
+ gr.HTML("<div style='text-align: center; font-size: 20px;'>Step 3. Click Run</div>")
71
+ image_out = gr.Image(label="Result")
72
  with gr.Row():
73
  seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
74
  randomize_seed = gr.Checkbox(label="Random seed", value=True)
75
  with gr.Row():
76
  seed_used = gr.Number(label="Seed used")
77
+ result_info = gr.Text(label="Status")
78
+ test_button = gr.Button("Run", elem_id="button")
79
 
80
+ test_button.click(
81
+ fn=mock_tryon,
82
+ inputs=[imgs, garm_img, seed, randomize_seed],
83
+ outputs=[image_out, seed_used, result_info],
84
+ concurrency_limit=5
85
+ )
86
 
87
  with gr.Column(elem_id="col-showcase"):
88
+ gr.HTML("<div style='text-align: center; font-size: 20px;'>Examples</div>")
89
  gr.Examples(
90
+ examples=[
91
+ [human_list_path[0], garm_list_path[0]], # First human + first garment
92
+ [human_list_path[1], garm_list_path[1]], # Second pair
93
+ ],
94
+ inputs=[imgs, garm_img],
95
+ outputs=[image_out]
96
  )
97
 
98
+ Tryon.queue().launch()