Monikashyapa commited on
Commit
a466d6e
·
verified ·
1 Parent(s): 3884ff3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -103
app.py CHANGED
@@ -1,121 +1,97 @@
1
- import os
2
- import cv2
3
  import gradio as gr
 
4
  import numpy as np
5
- import random
6
- import base64
7
- import time
8
- from gradio_client import Client
9
 
10
  # -----------------------------
11
- # Connect to Hunyuan3D Space
12
  # -----------------------------
13
- mesh_client = Client("tencent/Hunyuan3D-2.1") # has real API
14
- MESH_API_NAME = "/process"
15
-
16
- # -----------------------------
17
- # Kolors VTON code (internal)
18
- # -----------------------------
19
- MAX_SEED = 999999
20
-
21
- def tryon(person_img, garment_img, seed, randomize_seed):
22
  if person_img is None or garment_img is None:
23
- return None, seed, "Empty image"
24
- if randomize_seed:
25
- seed = random.randint(0, MAX_SEED)
26
-
27
- # Encode images
28
- encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
29
- encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
30
- encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
31
- encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')
32
-
33
- # Send request to internal tryon server (Kolors VTON)
34
- tryon_url = "http://" + os.environ['tryon_url'] + "Submit"
35
- token = os.environ['token']
36
- cookie = os.environ['Cookie']
37
- referer = os.environ['referer']
38
- headers = {'Content-Type': 'application/json', 'token': token, 'Cookie': cookie, 'referer': referer}
39
- data = {"clothImage": encoded_garment_img, "humanImage": encoded_person_img, "seed": seed}
40
-
41
- # Post request
42
- import requests
43
- try:
44
- response = requests.post(tryon_url, headers=headers, data=json.dumps(data), timeout=50)
45
- if response.status_code != 200:
46
- return None, seed, f"Tryon POST failed: {response.status_code}"
47
- result_json = response.json()['result']
48
- if result_json['status'] != "success":
49
- return None, seed, f"Tryon error: {result_json['status']}"
50
- task_uuid = result_json['result']
51
- except Exception as e:
52
- return None, seed, f"Tryon exception: {str(e)}"
53
-
54
- # Poll for result
55
- result_img = None
56
- for _ in range(12): # retry 12 times
57
- try:
58
- query_url = "http://" + os.environ['tryon_url'] + f"Query?taskId={task_uuid}"
59
- response = requests.get(query_url, headers=headers, timeout=20)
60
- if response.status_code == 200:
61
- r = response.json()['result']
62
- if r['status'] == "success":
63
- img_bytes = base64.b64decode(r['result'])
64
- result_np = np.frombuffer(img_bytes, np.uint8)
65
- result_img = cv2.imdecode(result_np, cv2.IMREAD_COLOR)
66
- result_img = cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB)
67
- break
68
- time.sleep(1)
69
- except:
70
- time.sleep(1)
71
-
72
- if result_img is None:
73
- return None, seed, "Tryon failed or timed out"
74
-
75
- return result_img, seed, "Success"
76
 
77
  # -----------------------------
78
- # Merge: Tryon + Hunyuan3D
79
  # -----------------------------
 
 
 
80
  def tryon_to_3d(person_img, garment_img, seed, randomize_seed):
81
- # Run 2D try-on
82
- tryon_img, seed_used, tryon_info = tryon(person_img, garment_img, seed, randomize_seed)
83
  if tryon_img is None:
84
- return None, None, seed_used, tryon_info
85
 
86
- # Run 3D mesh generation (Hunyuan3D)
87
  try:
88
- mesh_file = mesh_client.predict(tryon_img, api_name=MESH_API_NAME)
 
 
 
 
89
  except Exception as e:
90
- return tryon_img, None, seed_used, f"Hunyuan3D error: {str(e)}"
91
-
92
- return tryon_img, mesh_file, seed_used, "Success"
93
 
94
  # -----------------------------
95
- # Gradio Interface
96
  # -----------------------------
97
- with gr.Blocks() as demo:
98
- gr.Markdown("# Virtual Try-On → 3D Mesh Generator")
99
-
 
 
 
 
 
 
 
 
 
 
100
  with gr.Row():
101
- person_img = gr.Image(label="Person Image", type="numpy")
102
- garment_img = gr.Image(label="Garment Image", type="numpy")
103
-
104
- with gr.Row():
105
- seed = gr.Slider(0, MAX_SEED, step=1, value=0, label="Seed")
106
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
107
-
108
- with gr.Row():
109
- tryon_out = gr.Image(label="2D Try-On Result")
110
- mesh_out = gr.Model3D(label="3D Mesh Output")
111
-
112
- seed_used_out = gr.Number(label="Seed Used")
113
- status_out = gr.Textbox(label="Status")
114
-
115
- run_btn = gr.Button("Run")
116
- run_btn.click(fn=tryon_to_3d,
117
- inputs=[person_img, garment_img, seed, randomize_seed],
118
- outputs=[tryon_out, mesh_out, seed_used_out, status_out])
119
-
120
- if __name__ == "__main__":
121
- demo.launch()
 
 
 
1
  import gradio as gr
2
+ import cv2
3
  import numpy as np
 
 
 
 
4
 
5
  # -----------------------------
6
+ # Local "try-on" function
7
  # -----------------------------
8
+ def tryon_local(person_img, garment_img, seed, randomize_seed):
9
+ """
10
+ Simulates try-on by resizing the garment to fit the person and overlaying.
11
+ """
 
 
 
 
 
12
  if person_img is None or garment_img is None:
13
+ return None, None, "Empty image"
14
+
15
+ # Resize garment to width of person image
16
+ h_person, w_person = person_img.shape[:2]
17
+ h_garment, w_garment = garment_img.shape[:2]
18
+
19
+ scale = w_person / w_garment
20
+ new_w = int(w_garment * scale)
21
+ new_h = int(h_garment * scale)
22
+ garment_resized = cv2.resize(garment_img, (new_w, new_h))
23
+
24
+ # Simple overlay: top of garment onto top of person
25
+ overlay = person_img.copy()
26
+ y_offset = 0
27
+ x_offset = max(0, (w_person - new_w) // 2)
28
+
29
+ # Handle transparency if 4-channel
30
+ if garment_resized.shape[2] == 4:
31
+ alpha = garment_resized[:, :, 3] / 255.0
32
+ for c in range(3):
33
+ overlay[y_offset:y_offset+new_h, x_offset:x_offset+new_w, c] = \
34
+ alpha * garment_resized[:, :, c] + (1 - alpha) * overlay[y_offset:y_offset+new_h, x_offset:x_offset+new_w, c]
35
+ else:
36
+ overlay[y_offset:y_offset+new_h, x_offset:x_offset+new_w] = garment_resized
37
+
38
+ info = "Success (local simulation)"
39
+ return overlay, seed, info
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  # -----------------------------
42
+ # Hunyuan3D API call
43
  # -----------------------------
44
+ from gradio_client import Client
45
+ hunyuan_client = Client("tencent/Hunyuan3D-2.1")
46
+
47
  def tryon_to_3d(person_img, garment_img, seed, randomize_seed):
48
+ # Step 1: Run local try-on
49
+ tryon_img, seed_used, tryon_info = tryon_local(person_img, garment_img, seed, randomize_seed)
50
  if tryon_img is None:
51
+ return None, "Try-on failed"
52
 
53
+ # Step 2: Send 2D try-on result to Hunyuan3D
54
  try:
55
+ result_3d = hunyuan_client.predict(
56
+ tryon_img, # input image
57
+ api_name="/process"
58
+ )
59
+ return result_3d, tryon_info
60
  except Exception as e:
61
+ return None, f"Hunyuan3D API error: {e}"
 
 
62
 
63
  # -----------------------------
64
+ # Gradio UI
65
  # -----------------------------
66
+ css = """
67
+ #col-left, #col-mid, #col-right {
68
+ margin: 0 auto;
69
+ max-width: 430px;
70
+ }
71
+ #col-showcase {
72
+ margin: 0 auto;
73
+ max-width: 1100px;
74
+ }
75
+ #button { color: blue; }
76
+ """
77
+
78
+ with gr.Blocks(css=css) as app:
79
  with gr.Row():
80
+ with gr.Column(elem_id="col-left"):
81
+ person_input = gr.Image(label="Person Image", source="upload", type="numpy")
82
+ with gr.Column(elem_id="col-mid"):
83
+ garment_input = gr.Image(label="Garment Image", source="upload", type="numpy")
84
+ with gr.Column(elem_id="col-right"):
85
+ output_img = gr.Image(label="3D Result")
86
+ result_info = gr.Text(label="Info")
87
+ seed = gr.Slider(0, 999999, value=0, step=1, label="Seed")
88
+ randomize_seed = gr.Checkbox(label="Random seed", value=True)
89
+ run_btn = gr.Button("Run")
90
+
91
+ run_btn.click(
92
+ fn=tryon_to_3d,
93
+ inputs=[person_input, garment_input, seed, randomize_seed],
94
+ outputs=[output_img, result_info]
95
+ )
96
+
97
+ app.launch()