RojaKatta commited on
Commit
b68a73e
·
verified ·
1 Parent(s): 3519881

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +4 -201
app.py CHANGED
@@ -4,9 +4,8 @@ from PIL import Image
4
 
5
  # ===================== Paths & Assets =====================
6
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
7
- # Look for your folder first (hair/). Fall back to other common names.
8
  CANDIDATES = [
9
- os.path.join(BASE_DIR, "hair"),
10
  os.path.join(BASE_DIR, "assets", "hairstyles"),
11
  os.path.join(BASE_DIR, "assets", "Hairstyles"),
12
  os.path.join(BASE_DIR, "hairstyles"),
@@ -22,7 +21,7 @@ if HAIR_DIR is None:
22
 
23
  META_PATH = os.path.join(HAIR_DIR, "meta.json") # optional per-style anchors
24
 
25
- # ===================== Dependences =====================
26
  try:
27
  import mediapipe as mp
28
  except Exception as e:
@@ -85,7 +84,7 @@ def hair_reference_points(hair_bgra, filename, meta):
85
  pts = np.array(meta[filename], dtype=np.float32)
86
  if pts.shape == (3, 2):
87
  return pts
88
- # Defaults (works OK for many styles). For pixel-perfect fit, add meta.json.
89
  pL = np.array([0.30*w, 0.60*h], dtype=np.float32)
90
  pR = np.array([0.70*w, 0.60*h], dtype=np.float32)
91
  pM = np.array([0.50*w, 0.40*h], dtype=np.float32)
@@ -109,200 +108,4 @@ def apply_tryon(image, hairstyle, scale_pct, rot_deg, dx, dy, opacity, meta):
109
 
110
  img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
111
 
112
- kpts = detect_face_keypoints(img_bgr)
113
- if kpts is None:
114
- return image, "No face detected. Try a brighter, front-facing photo."
115
-
116
- hair = load_hair_png(hairstyle)
117
- hair_pts = hair_reference_points(hair, hairstyle, meta)
118
-
119
- # Destination points (with user nudges)
120
- dst = kpts.copy()
121
- dst[:, 0] += dx
122
- dst[:, 1] += dy
123
-
124
- # Scale + rotate around hair anchor centroid
125
- center = hair_pts.mean(axis=0)
126
- theta = np.deg2rad(rot_deg)
127
- s = max(0.5, scale_pct / 100.0)
128
- R = np.array([[np.cos(theta), -np.sin(theta)],
129
- [np.sin(theta), np.cos(theta)]], dtype=np.float32)
130
- hair_pts_adj = (hair_pts - center) @ R.T * s + center
131
-
132
- M, _ = cv2.estimateAffinePartial2D(hair_pts_adj, dst, method=cv2.LMEDS)
133
- if M is None:
134
- return image, "Could not compute alignment for this image/style."
135
-
136
- out = warp_and_alpha_blend(img_bgr, hair, M, opacity=opacity)
137
-
138
- # Restrict to head region for cleaner look
139
- head = person_mask(img_bgr)
140
- head3 = head[..., None]
141
- out = (head3 * out + (1 - head3) * img_bgr).astype(np.uint8)
142
-
143
- out_rgb = cv2.cvtColor(out, cv2.COLOR_BGR2RGB)
144
- return out_rgb, "OK"
145
-
146
- def save_png_to_tmp(img, filename="output_tryon.png"):
147
- """DownloadButton needs a file path string."""
148
- if img is None:
149
- raise gr.Error("No image to download. Click Apply first.")
150
- out_path = os.path.join(tempfile.gettempdir(), filename)
151
- if isinstance(img, np.ndarray):
152
- Image.fromarray(img).save(out_path)
153
- else:
154
- img.save(out_path)
155
- return out_path
156
-
157
- # ----- thumbnails on checkerboard for the gallery -----
158
- def thumb_on_checker(hair_bgra, max_h=220):
159
- h, w = hair_bgra.shape[:2]
160
- scale = min(1.0, max_h / h)
161
- hair_bgra = cv2.resize(hair_bgra, (int(w*scale), int(h*scale)), interpolation=cv2.INTER_LINEAR)
162
- h, w = hair_bgra.shape[:2]
163
- tile = 12
164
- bg = np.kron(((np.indices((h//tile+1, w//tile+1)).sum(axis=0) % 2) * 64 + 192).astype(np.uint8),
165
- np.ones((tile, tile), np.uint8))[:h, :w]
166
- bg_rgb = np.dstack([bg, bg, bg])
167
- a = (hair_bgra[:, :, 3:4] / 255.0)
168
- comp = (a * hair_bgra[:, :, :3] + (1 - a) * bg_rgb).astype(np.uint8)
169
- return cv2.cvtColor(comp, cv2.COLOR_BGR2RGB)
170
-
171
- def build_gallery_items(files):
172
- items = []
173
- for fname in files:
174
- try:
175
- img = load_hair_png(fname)
176
- items.append((thumb_on_checker(img), fname)) # (image, caption)
177
- except Exception:
178
- continue
179
- return items
180
-
181
- # ===================== UI =====================
182
- def build_ui():
183
- META = load_meta()
184
- HAIR_FILES = load_hairstyles()
185
-
186
- with gr.Blocks(title="Salon Hairstyle Virtual Try-On — Pro Demo", css="""
187
- .gradio-container {max-width: 1100px; margin:auto;}
188
- @media (max-width: 768px){ .gradio-container {padding: 8px;} }
189
- """) as demo:
190
- gr.Markdown(
191
- "### Upload a photo or use webcam. Put transparent **PNGs** in the **`hair/`** folder, then click **Refresh**."
192
- )
193
-
194
- files_state = gr.State(HAIR_FILES) # keep current filenames order
195
- meta_state = gr.State(META) # pass meta to callbacks
196
-
197
- with gr.Tabs():
198
- # ---------------- Photo Tab ----------------
199
- with gr.Tab("📷 Photo (Upload)"):
200
- with gr.Row():
201
- in_img = gr.Image(label="Input photo (JPEG/PNG)", type="pil", height=360, sources=["upload"])
202
- out_img = gr.Image(label="Preview", height=360)
203
- with gr.Row():
204
- hair_sel = gr.Dropdown(
205
- choices=HAIR_FILES,
206
- value=(HAIR_FILES[0] if HAIR_FILES else None),
207
- label="Selected hairstyle",
208
- interactive=True
209
- )
210
- apply_btn = gr.Button("✨ Apply (Align & Overlay)")
211
- download_btn = gr.DownloadButton("⬇️ Download", file_name="output_tryon.png")
212
- status = gr.Markdown()
213
-
214
- with gr.Row():
215
- refresh = gr.Button("🔄 Refresh")
216
- gallery = gr.Gallery(
217
- label="Hairstyles (click to choose)",
218
- value=build_gallery_items(HAIR_FILES),
219
- columns=6, rows=2, height=320,
220
- allow_preview=False, object_fit="contain", show_label=True
221
- )
222
-
223
- with gr.Accordion("Fine-tune placement", open=True):
224
- with gr.Row():
225
- scale = gr.Slider(50, 200, 100, 1, label="Scale (≈ temple distance %)")
226
- rot = gr.Slider(-30, 30, 0, 1, label="Extra rotation (°)")
227
- with gr.Row():
228
- dx = gr.Slider(-200, 200, 0, 1, label="Left ↔ Right shift (px)")
229
- dy = gr.Slider(-200, 200, 0, 1, label="Up ↕ Down shift (px)")
230
- opacity = gr.Slider(0.2, 1.0, 1.0, 0.05, label="Hair opacity")
231
-
232
- # --- Callbacks ---
233
- def do_apply(im, hfile, s, r, dxv, dyv, op, meta):
234
- return apply_tryon(im, hfile, s, r, dxv, dyv, op, meta)
235
-
236
- apply_btn.click(
237
- fn=do_apply,
238
- inputs=[in_img, hair_sel, scale, rot, dx, dy, opacity, meta_state],
239
- outputs=[out_img, status]
240
- )
241
-
242
- download_btn.click(
243
- fn=lambda im: save_png_to_tmp(im, "output_tryon.png"),
244
- inputs=[out_img],
245
- outputs=[download_btn]
246
- )
247
-
248
- def do_refresh():
249
- files = load_hairstyles()
250
- items = build_gallery_items(files)
251
- return items, gr.update(choices=files, value=(files[0] if files else None)), files
252
-
253
- refresh.click(fn=do_refresh, inputs=[], outputs=[gallery, hair_sel, files_state])
254
-
255
- # Clicking a tile sets the dropdown to that filename
256
- def on_gallery_select(evt, files):
257
- idx = getattr(evt, "index", None)
258
- if idx is None or not files:
259
- return gr.update()
260
- if idx >= len(files):
261
- idx = len(files) - 1
262
- return gr.update(value=files[idx])
263
-
264
- gallery.select(on_gallery_select, inputs=[files_state], outputs=[hair_sel])
265
-
266
- # ---------------- Webcam Tab ----------------
267
- with gr.Tab("📹 Webcam (Live Beta)"):
268
- cam = gr.Image(sources=["webcam"], streaming=True, type="pil", label="Enable camera")
269
- hair2 = gr.Dropdown(choices=HAIR_FILES, value=(HAIR_FILES[0] if HAIR_FILES else None), label="Selected hairstyle")
270
- with gr.Row():
271
- scale2 = gr.Slider(50, 200, 100, 1, label="Scale %")
272
- rot2 = gr.Slider(-25, 25, 0, 1, label="Rotate (°)")
273
- with gr.Row():
274
- dx2 = gr.Slider(-150, 150, 0, 1, label="Left ↔ Right (px)")
275
- dy2 = gr.Slider(-150, 150, 0, 1, label="Up ↕ Down (px)")
276
- opacity2 = gr.Slider(0.2, 1.0, 0.95, 0.05, label="Hair opacity")
277
- out2 = gr.Image(label="Live result")
278
- state_live = gr.State(None)
279
- snap = gr.Button("📸 Snapshot")
280
- save_live = gr.DownloadButton("⬇️ Download Snapshot", file_name="tryon_webcam.png")
281
-
282
- def live(im, h, s, r, dxv, dyv, op, meta):
283
- res, _ = apply_tryon(im, h, s, r, dxv, dyv, op, meta)
284
- return res, res
285
-
286
- cam.stream(
287
- fn=live,
288
- inputs=[cam, hair2, scale2, rot2, dx2, dy2, opacity2, meta_state],
289
- outputs=[out2, state_live]
290
- )
291
-
292
- snap.click(lambda x: x, inputs=[state_live], outputs=[out2])
293
-
294
- save_live.click(
295
- fn=lambda im: save_png_to_tmp(im, "tryon_webcam.png"),
296
- inputs=[state_live],
297
- outputs=[save_live]
298
- )
299
-
300
- return demo
301
-
302
- # Export for Spaces autostart
303
- app = build_ui()
304
- demo = app # alias
305
-
306
- # Local dev
307
- if __name__ == "__main__":
308
- app.launch()
 
4
 
5
  # ===================== Paths & Assets =====================
6
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
 
7
  CANDIDATES = [
8
+ os.path.join(BASE_DIR, "hair"), # your folder
9
  os.path.join(BASE_DIR, "assets", "hairstyles"),
10
  os.path.join(BASE_DIR, "assets", "Hairstyles"),
11
  os.path.join(BASE_DIR, "hairstyles"),
 
21
 
22
  META_PATH = os.path.join(HAIR_DIR, "meta.json") # optional per-style anchors
23
 
24
+ # ===================== Dependencies =====================
25
  try:
26
  import mediapipe as mp
27
  except Exception as e:
 
84
  pts = np.array(meta[filename], dtype=np.float32)
85
  if pts.shape == (3, 2):
86
  return pts
87
+ # Defaults (ok for many styles). For perfect fit, put 3 points per file in meta.json.
88
  pL = np.array([0.30*w, 0.60*h], dtype=np.float32)
89
  pR = np.array([0.70*w, 0.60*h], dtype=np.float32)
90
  pM = np.array([0.50*w, 0.40*h], dtype=np.float32)
 
108
 
109
  img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
110
 
111
+ kpt