RojaKatta commited on
Commit
0a26ca4
·
verified ·
1 Parent(s): 374009a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -256
app.py CHANGED
@@ -1,256 +0,0 @@
1
- app.py:import os, glob, math
2
- import numpy as np
3
- from PIL import Image
4
- import gradio as gr
5
-
6
- # Your hairstyles live here:
7
- HAIR_DIR = "hair"
8
-
9
- # Optional heavy deps (installed via requirements.txt)
10
- try:
11
- import cv2
12
- import mediapipe as mp
13
- MP_AVAILABLE = True
14
- except Exception:
15
- MP_AVAILABLE = False
16
-
17
- APP_TITLE = "Salon Hairstyle Virtual Try-On — Pro Demo"
18
-
19
- # --------------------------
20
- # Asset loading / utilities
21
- # --------------------------
22
- def list_hairstyle_files():
23
- files = sorted(glob.glob(os.path.join(HAIR_DIR, "*.png")))
24
- labels = [os.path.basename(f).replace(".png","").replace("_"," ").title() for f in files]
25
- thumbs = [f for f in files] # Gradio Gallery accepts path strings
26
- return labels, files, thumbs
27
-
28
- def ensure_rgba(im: Image.Image) -> Image.Image:
29
- return im if im.mode == "RGBA" else im.convert("RGBA")
30
-
31
- def overlay_rgba(base: Image.Image, overlay: Image.Image, x: int, y: int) -> Image.Image:
32
- base = ensure_rgba(base)
33
- overlay = ensure_rgba(overlay)
34
- bw, bh = base.size
35
- ow, oh = overlay.size
36
- if ow <= 0 or oh <= 0:
37
- return base
38
- x1, y1 = max(0, x), max(0, y)
39
- x2, y2 = min(bw, x + ow), min(bh, y + oh)
40
- if x1 >= x2 or y1 >= y2:
41
- return base
42
- crop = overlay.crop((x1 - x, y1 - y, x2 - x, y2 - y))
43
- region = base.crop((x1, y1, x2, y2))
44
- region = Image.alpha_composite(region, crop)
45
- base.paste(region, (x1, y1))
46
- return base
47
-
48
- # --------------------------
49
- # Face detection / anchoring
50
- # --------------------------
51
- def detect_face_keypoints(np_img):
52
- """
53
- Returns dict:
54
- bbox: (x1,y1,x2,y2)
55
- temples: (lx,ly, rx,ry)
56
- forehead_y: int
57
- """
58
- h, w = np_img.shape[:2]
59
-
60
- def fallback():
61
- cx, cy = w // 2, int(h * 0.42)
62
- bw, bh = int(w * 0.4), int(h * 0.45)
63
- x1, y1 = max(0, cx - bw // 2), max(0, cy - bh // 2)
64
- x2, y2 = min(w, x1 + bw), min(h, y1 + bh)
65
- return {
66
- "bbox": (x1, y1, x2, y2),
67
- "temples": (x1, (y1 + y2) // 2, x2, (y1 + y2) // 2),
68
- "forehead_y": max(0, int(y1 - 0.1 * (y2 - y1))),
69
- }
70
-
71
- if not MP_AVAILABLE:
72
- return fallback()
73
-
74
- mpfm = mp.solutions.face_mesh
75
- with mpfm.FaceMesh(static_image_mode=True, max_num_faces=1, refine_landmarks=False) as fm:
76
- rgb = cv2.cvtColor(np_img, cv2.COLOR_BGR2RGB) if np_img.shape[2] == 3 else np_img[..., :3]
77
- res = fm.process(rgb)
78
- if not res.multi_face_landmarks:
79
- return fallback()
80
-
81
- lm = res.multi_face_landmarks[0].landmark
82
- xs = np.array([p.x for p in lm]) * w
83
- ys = np.array([p.y for p in lm]) * h
84
- x1, y1, x2, y2 = int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())
85
-
86
- def safe_idx(i):
87
- i = int(i)
88
- i = max(0, min(len(lm) - 1, i))
89
- return int(xs[i]), int(ys[i])
90
-
91
- lx, ly = safe_idx(127) # approx left temple
92
- rx, ry = safe_idx(356) # approx right temple
93
- _, fy = safe_idx(10) # approx forehead
94
- y1 = max(0, int(y1 - 0.12 * (y2 - y1))) # include hairline
95
- return {
96
- "bbox": (x1, y1, x2, y2),
97
- "temples": (lx, ly, rx, ry),
98
- "forehead_y": fy,
99
- }
100
-
101
- def place_and_render(base_np, hair_path, scale, lr_shift_pct, ud_shift_pct, rotation_deg):
102
- if base_np is None:
103
- raise gr.Error("Please upload or capture a photo first.")
104
- base = Image.fromarray(base_np.astype("uint8")).convert("RGBA")
105
- key = detect_face_keypoints(np.array(base.convert("RGB")))
106
- x1, y1, x2, y2 = key["bbox"]
107
- lx, ly, rx, ry = key["temples"]
108
- forehead_y = key["forehead_y"]
109
-
110
- hair = Image.open(hair_path).convert("RGBA")
111
-
112
- # Scale from temple distance
113
- temple_dx = rx - lx
114
- temple_dy = ry - ly
115
- temple_dist = max(1, (temple_dx ** 2 + temple_dy ** 2) ** 0.5)
116
- target_w = max(1, int(temple_dist * 2.0 * scale))
117
- ratio = target_w / hair.width
118
- target_h = max(1, int(hair.height * ratio))
119
- hair_resized = hair.resize((target_w, target_h), Image.LANCZOS)
120
-
121
- # Auto-rotation + manual extra rotation
122
- auto_deg = math.degrees(math.atan2(temple_dy, temple_dx))
123
- rot_total = auto_deg + rotation_deg
124
- hair_resized = hair_resized.rotate(rot_total, expand=True)
125
-
126
- # Anchor at temple midpoint, above forehead
127
- midx = int((lx + rx) / 2)
128
- anchor_x = int(midx - hair_resized.width / 2)
129
- anchor_y = int(forehead_y - hair_resized.height * 0.45)
130
-
131
- # Apply shifts (percent of image size)
132
- img_w, img_h = base.size
133
- anchor_x += int(lr_shift_pct * img_w / 100.0) # +right, -left
134
- anchor_y += int(ud_shift_pct * img_h / 100.0) # +down, -up
135
-
136
- out = overlay_rgba(base, hair_resized, anchor_x, anchor_y).convert("RGB")
137
- return out
138
-
139
- # --------------------------
140
- # Gradio callbacks
141
- # --------------------------
142
- def refresh_assets():
143
- labels, files, thumbs = list_hairstyle_files()
144
- if not files:
145
- return (
146
- gr.update(value=None, choices=[]),
147
- gr.update(value=None),
148
- "No PNGs found in the 'hair/' folder.",
149
- )
150
- dd = gr.update(choices=labels, value=labels[0])
151
- gallery = gr.update(value=[[p, l] for p, l in zip(thumbs, labels)])
152
- return dd, gallery, f"Found {len(files)} hairstyles."
153
-
154
- def refresh_dropdown_only():
155
- labels, files, _ = list_hairstyle_files()
156
- if not files:
157
- return gr.update(value=None, choices=[])
158
- return gr.update(choices=labels, value=labels[0])
159
-
160
- def pick_from_gallery(gallery_select, current_dropdown):
161
- # When user clicks a gallery item, we set the dropdown to match
162
- labels, _, _ = list_hairstyle_files()
163
- if not labels:
164
- raise gr.Error("No hairstyles available.")
165
- if gallery_select is None:
166
- return current_dropdown
167
- idx = gallery_select[0]
168
- idx = max(0, min(len(labels) - 1, idx))
169
- return labels[idx]
170
-
171
- def apply_from_dropdown(image, hairstyle_label, scale, lr, ud, rot):
172
- labels, files, _ = list_hairstyle_files()
173
- if not labels:
174
- raise gr.Error("No hairstyle assets found.")
175
- if hairstyle_label not in labels:
176
- raise gr.Error("Choose a hairstyle first.")
177
- path = files[labels.index(hairstyle_label)]
178
- return place_and_render(image, path, scale, lr, ud, rot)
179
-
180
- def save_image(img_np):
181
- if img_np is None:
182
- raise gr.Error("Nothing to save. Generate a preview first.")
183
- out_path = "output_tryon.png"
184
- Image.fromarray(img_np).save(out_path)
185
- return out_path
186
-
187
- # --------------------------
188
- # UI
189
- # --------------------------
190
- with gr.Blocks(fill_height=True, theme=gr.themes.Soft()) as demo:
191
- gr.Markdown(f"# {APP_TITLE}")
192
- gr.Markdown("Upload a photo or use webcam. Put **transparent PNGs** in the hair/ folder, then click **Refresh**.")
193
-
194
- with gr.Tabs():
195
- # -------- Upload tab --------
196
- with gr.Tab("📷 Photo (Upload)"):
197
- with gr.Row():
198
- with gr.Column():
199
- img = gr.Image(label="Photo", sources=["upload"], type="numpy", height=420)
200
-
201
- hair_dd = gr.Dropdown(label="Hairstyle", choices=[], interactive=True)
202
- refresh = gr.Button("🔄 Refresh")
203
- status = gr.Markdown("Drop PNGs into hair/ and press Refresh.")
204
- gallery = gr.Gallery(
205
- label="Hairstyles (click to choose)",
206
- columns=4,
207
- height=220,
208
- allow_preview=False,
209
- interactive=True,
210
- )
211
-
212
- with gr.Accordion("Fine-tune placement", open=False):
213
- scale = gr.Slider(0.6, 2.2, value=1.3, step=0.01, label="Scale (× temple distance)")
214
- lr = gr.Slider(-30, 30, value=0, step=0.5, label="Left ↔ Right shift (%)")
215
- ud = gr.Slider(-30, 30, value=0, step=0.5, label="Up ↕ Down shift (%)")
216
- rot = gr.Slider(-30, 30, value=0, step=0.5, label="Extra rotation (°)")
217
-
218
- run_dd = gr.Button("✨ Apply")
219
-
220
- with gr.Column():
221
- out = gr.Image(label="Preview", height=480)
222
- save_btn = gr.Button("💾 Save result")
223
- file_out = gr.File(label="Download")
224
-
225
- # Wiring
226
- refresh.click(fn=refresh_assets, inputs=None, outputs=[hair_dd, gallery, status])
227
- demo.load(fn=refresh_assets, inputs=None, outputs=[hair_dd, gallery, status])
228
-
229
- # Clicking gallery picks the dropdown value; one Apply button only
230
- gallery.select(fn=pick_from_gallery, inputs=[gallery, hair_dd], outputs=hair_dd)
231
- run_dd.click(fn=apply_from_dropdown, inputs=[img, hair_dd, scale, lr, ud, rot], outputs=out)
232
- save_btn.click(fn=save_image, inputs=out, outputs=file_out)
233
-
234
- # -------- Webcam tab --------
235
- with gr.Tab("🎥 Webcam (Live Beta)"):
236
- gr.Markdown("Live mode processes frames continuously. Keep resolution small on CPU Spaces.")
237
- cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="Webcam")
238
- hair_dd2 = gr.Dropdown(label="Hairstyle", choices=[], interactive=True)
239
- scale2 = gr.Slider(0.6, 2.2, value=1.25, step=0.01, label="Scale")
240
- lr2 = gr.Slider(-30, 30, value=0, step=0.5, label="Left ↔ Right shift (%)")
241
- ud2 = gr.Slider(-30, 30, value=0, step=0.5, label="Up ↕ Down shift (%)")
242
- rot2 = gr.Slider(-30, 30, value=0, step=0.5, label="Rotation (°)")
243
- out_live = gr.Image(label="Live Preview", interactive=False, height=420)
244
-
245
- def live_process(frame, label, s, lrp, udp, r):
246
- labels, files, _ = list_hairstyle_files()
247
- if frame is None or not labels or label not in labels:
248
- return frame
249
- path = files[labels.index(label)]
250
- return place_and_render(frame, path, s, lrp, udp, r)
251
-
252
- cam.stream(fn=live_process, inputs=[cam, hair_dd2, scale2, lr2, ud2, rot2], outputs=out_live)
253
- demo.load(fn=refresh_dropdown_only, inputs=None, outputs=hair_dd2)
254
-
255
- if __name__ == "__main__":
256
- demo.launch()