RojaKatta commited on
Commit
5ca35cd
Β·
verified Β·
1 Parent(s): 145406d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -69
app.py CHANGED
@@ -1,43 +1,43 @@
1
- import os, json, tempfile, re
2
  import cv2, numpy as np, gradio as gr
3
  from PIL import Image
4
 
5
- # -------------------- Paths --------------------
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"),
12
  ]
13
- HAIR_DIR = next((p for p in CANDIDATES if os.path.isdir(p)), None)
 
 
 
 
14
  if HAIR_DIR is None:
15
  HAIR_DIR = os.path.join(BASE_DIR, "hair")
16
  os.makedirs(HAIR_DIR, exist_ok=True)
17
 
18
  META_PATH = os.path.join(HAIR_DIR, "meta.json") # optional per-style anchors
19
 
20
- # -------------------- Deps --------------------
21
  try:
22
  import mediapipe as mp
23
  except Exception as e:
24
  raise RuntimeError(f"Mediapipe import failed. Check requirements pins. Details: {e}")
25
 
26
  mp_face_mesh = mp.solutions.face_mesh
27
- mp_selfie_seg = mp.solutions.selfie_segmentation # optional (off by default)
28
  LM = {"left_eye_outer": 33, "right_eye_outer": 263, "mid_forehead": 10}
29
 
30
- # -------------------- Helpers --------------------
31
- def natural_key(s: str):
32
- # sorts photo1, photo2, ... photo10 in numeric order
33
- return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]
34
-
35
  def load_hairstyles():
36
  try:
37
  files = [f for f in os.listdir(HAIR_DIR) if f.lower().endswith(".png")]
38
  except FileNotFoundError:
39
  files = []
40
- files.sort(key=natural_key)
41
  return files
42
 
43
  def load_meta():
@@ -51,7 +51,7 @@ def load_meta():
51
  return {}
52
 
53
  def premultiply_alpha(bgra):
54
- """Reduce gray/white halos on edges for nicer blending."""
55
  bgr = bgra[:, :, :3].astype(np.float32) / 255.0
56
  a = (bgra[:, :, 3:4].astype(np.float32) / 255.0)
57
  bgr_pm = (bgr * a * 255.0).astype(np.uint8)
@@ -77,16 +77,12 @@ def detect_face_keypoints(img_bgr):
77
  def xy(i): return np.array([lm[i].x*w, lm[i].y*h], dtype=np.float32)
78
  return np.stack([xy(LM["left_eye_outer"]), xy(LM["right_eye_outer"]), xy(LM["mid_forehead"])])
79
 
80
- def person_mask(img_bgr, expand_px=20):
81
- """Optional head mask (OFF by default). We expand+blur to avoid 'neck lines'."""
82
  with mp_selfie_seg.SelfieSegmentation(model_selection=1) as seg:
83
  rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
84
  m = seg.process(rgb).segmentation_mask
85
- mask = (m > 0.5).astype(np.uint8)
86
- if expand_px > 0:
87
- k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2*expand_px+1, 2*expand_px+1))
88
- mask = cv2.dilate(mask, k, iterations=1)
89
- mask = cv2.GaussianBlur(mask.astype(np.float32), (41, 41), 0)
90
  return mask
91
 
92
  def hair_reference_points(hair_bgra, filename, meta):
@@ -95,7 +91,7 @@ def hair_reference_points(hair_bgra, filename, meta):
95
  pts = np.array(meta[filename], dtype=np.float32)
96
  if pts.shape == (3, 2):
97
  return pts
98
- # Defaults (ok for many styles). For perfect fit, add 3 points per file to meta.json.
99
  pL = np.array([0.30*w, 0.60*h], dtype=np.float32)
100
  pR = np.array([0.70*w, 0.60*h], dtype=np.float32)
101
  pM = np.array([0.50*w, 0.40*h], dtype=np.float32)
@@ -111,12 +107,7 @@ def warp_and_alpha_blend(base_bgr, hair_bgra, M, opacity=1.0):
111
  out = (a * hair_warp + (1 - a) * base_bgr).astype(np.uint8)
112
  return out
113
 
114
- def apply_tryon(image, hairstyle, scale_pct, rot_deg, dx, dy, opacity, meta,
115
- limit_head=False, expand_pct=3.0):
116
- """
117
- limit_head=False by default to avoid 'missing hair' and neck lines.
118
- If True, we use an expanded soft head mask.
119
- """
120
  if image is None:
121
  return None, "Upload a photo or enable webcam."
122
  if not hairstyle:
@@ -150,20 +141,18 @@ def apply_tryon(image, hairstyle, scale_pct, rot_deg, dx, dy, opacity, meta,
150
 
151
  out = warp_and_alpha_blend(img_bgr, hair, M, opacity=opacity)
152
 
153
- if limit_head:
154
- H, W = img_bgr.shape[:2]
155
- expand_px = max(8, int(min(H, W) * (expand_pct / 100.0))) # soft expansion
156
- head = person_mask(img_bgr, expand_px=expand_px) # soft & expanded
157
- head3 = head[..., None]
158
- out = (head3 * out + (1 - head3) * img_bgr).astype(np.uint8)
159
 
160
  out_rgb = cv2.cvtColor(out, cv2.COLOR_BGR2RGB)
161
  return out_rgb, "OK"
162
 
163
  def save_png_to_tmp(img, filename="output_tryon.png"):
164
- """Create a file in /tmp and return the path (used by the Save button)."""
165
  if img is None:
166
- raise gr.Error("No image to save. Click Apply first.")
167
  out_path = os.path.join(tempfile.gettempdir(), filename)
168
  if isinstance(img, np.ndarray):
169
  Image.fromarray(img).save(out_path)
@@ -171,7 +160,7 @@ def save_png_to_tmp(img, filename="output_tryon.png"):
171
  img.save(out_path)
172
  return out_path
173
 
174
- # ---------- WHITE background thumbnails (shows filename number) ----------
175
  def thumb_on_white(hair_bgra, max_h=220):
176
  h, w = hair_bgra.shape[:2]
177
  scale = min(1.0, max_h / h)
@@ -184,30 +173,30 @@ def thumb_on_white(hair_bgra, max_h=220):
184
 
185
  def build_gallery_items(files):
186
  items = []
187
- for idx, fname in enumerate(files, start=1):
188
  try:
189
  img = load_hair_png(fname)
190
- items.append((thumb_on_white(img), f"{idx}. {fname}")) # caption shows number & filename
191
  except Exception:
192
  continue
193
  return items
194
 
195
- # -------------------- UI --------------------
196
  def build_ui():
197
  META = load_meta()
198
  HAIR_FILES = load_hairstyles()
199
 
200
  with gr.Blocks(title="Salon Hairstyle Virtual Try-On", css="""
201
- .gradio-container {max-width: 1200px; margin:auto;}
202
  @media (max-width: 768px){ .gradio-container {padding: 8px;} }
203
  """) as demo:
204
- gr.Markdown("Upload a photo or use webcam. Put transparent **PNGs** in **`hair/`**, then click **Refresh**.")
205
 
206
- files_state = gr.State(HAIR_FILES) # filenames (natural order)
207
  meta_state = gr.State(META)
208
 
209
  with gr.Tabs():
210
- # -------- Photo Tab --------
211
  with gr.Tab("πŸ“· Photo (Upload)"):
212
  with gr.Row():
213
  in_img = gr.Image(label="Input photo (JPEG/PNG)", type="pil", height=360, sources=["upload"])
@@ -220,9 +209,9 @@ def build_ui():
220
  interactive=True
221
  )
222
  apply_btn = gr.Button("✨ Apply (Align & Overlay)")
223
- # SAVE (replaces Download)
224
- save_btn = gr.Button("πŸ’Ύ Save result")
225
- save_file = gr.File(label="Saved file", visible=False)
226
  status = gr.Markdown()
227
 
228
  with gr.Row():
@@ -231,7 +220,7 @@ def build_ui():
231
  gallery = gr.Gallery(
232
  label="Hairstyles (click to choose)",
233
  value=build_gallery_items(HAIR_FILES),
234
- columns=6, rows=3, height=520, # up to 18 tiles visible; all 11 will show
235
  allow_preview=False, object_fit="contain", show_label=True
236
  )
237
 
@@ -243,24 +232,23 @@ def build_ui():
243
  dx = gr.Slider(-200, 200, 0, 1, label="Left ↔ Right shift (px)")
244
  dy = gr.Slider(-200, 200, 0, 1, label="Up ↕ Down shift (px)")
245
  opacity = gr.Slider(0.2, 1.0, 1.0, 0.05, label="Hair opacity")
246
- limit_head = gr.Checkbox(label="Limit overlay to head (avoid spill)", value=False)
247
- expand = gr.Slider(0.0, 10.0, 3.0, 0.5, label="Head-mask expansion (%) β€” only if enabled")
248
 
249
  # --- Callbacks ---
250
- def do_apply(im, hfile, s, r, dxv, dyv, op, meta, lh, ex):
251
- return apply_tryon(im, hfile, s, r, dxv, dyv, op, meta, limit_head=lh, expand_pct=ex)
252
 
253
  apply_btn.click(
254
  fn=do_apply,
255
- inputs=[in_img, hair_sel, scale, rot, dx, dy, opacity, meta_state, limit_head, expand],
256
  outputs=[out_img, status]
257
  )
258
 
259
- def do_save(im):
 
260
  path = save_png_to_tmp(im, "output_tryon.png")
261
- return gr.File.update(value=path, visible=True)
262
 
263
- save_btn.click(fn=do_save, inputs=[out_img], outputs=[save_file])
264
 
265
  def do_refresh():
266
  files = load_hairstyles()
@@ -270,18 +258,18 @@ def build_ui():
270
 
271
  refresh.click(fn=do_refresh, inputs=[], outputs=[gallery, hair_sel, files_state, count_md])
272
 
273
- # Gallery click -> set dropdown to that filename
274
  def on_gallery_select(evt, files):
275
  idx = getattr(evt, "index", None)
276
  if idx is None or not files:
277
  return gr.update()
278
- # our captions start at 1., map index to filename directly
279
- idx = max(0, min(idx, len(files)-1))
280
  return gr.update(value=files[idx])
281
 
282
  gallery.select(on_gallery_select, inputs=[files_state], outputs=[hair_sel])
283
 
284
- # -------- Webcam Tab (unchanged except 'Save Snapshot') --------
285
  with gr.Tab("πŸ“Ή Webcam (Live Beta)"):
286
  cam = gr.Image(sources=["webcam"], streaming=True, type="pil", label="Enable camera")
287
  hair2 = gr.Dropdown(choices=HAIR_FILES, value=(HAIR_FILES[0] if HAIR_FILES else None), label="Selected hairstyle")
@@ -292,31 +280,29 @@ def build_ui():
292
  dx2 = gr.Slider(-150, 150, 0, 1, label="Left ↔ Right (px)")
293
  dy2 = gr.Slider(-150, 150, 0, 1, label="Up ↕ Down (px)")
294
  opacity2 = gr.Slider(0.2, 1.0, 0.95, 0.05, label="Hair opacity")
295
- limit_head2 = gr.Checkbox(label="Limit overlay to head", value=False)
296
- expand2 = gr.Slider(0.0, 10.0, 3.0, 0.5, label="Head-mask expansion (%)", visible=True)
297
  out2 = gr.Image(label="Live result", height=360)
298
  state_live = gr.State(None)
299
  snap = gr.Button("πŸ“Έ Snapshot")
300
- save_live_btn = gr.Button("πŸ’Ύ Save snapshot")
301
- save_live_file = gr.File(label="snapshot", visible=False)
302
 
303
- def live(im, h, s, r, dxv, dyv, op, meta, lh, ex):
304
- res, _ = apply_tryon(im, h, s, r, dxv, dyv, op, meta, limit_head=lh, expand_pct=ex)
305
  return res, res
306
 
307
  cam.stream(
308
  fn=live,
309
- inputs=[cam, hair2, scale2, rot2, dx2, dy2, opacity2, meta_state, limit_head2, expand2],
310
  outputs=[out2, state_live]
311
  )
312
 
313
  snap.click(lambda x: x, inputs=[state_live], outputs=[out2])
314
 
315
- def save_snap(im):
316
  path = save_png_to_tmp(im, "tryon_webcam.png")
317
- return gr.File.update(value=path, visible=True)
318
 
319
- save_live_btn.click(fn=save_snap, inputs=[state_live], outputs=[save_live_file])
320
 
321
  return demo
322
 
@@ -324,5 +310,6 @@ def build_ui():
324
  app = build_ui()
325
  demo = app
326
 
 
327
  if __name__ == "__main__":
328
  app.launch()
 
1
+ import os, json, tempfile
2
  import cv2, numpy as np, gradio as gr
3
  from PIL import Image
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"),
12
  ]
13
+ HAIR_DIR = None
14
+ for p in CANDIDATES:
15
+ if os.path.isdir(p):
16
+ HAIR_DIR = p
17
+ break
18
  if HAIR_DIR is None:
19
  HAIR_DIR = os.path.join(BASE_DIR, "hair")
20
  os.makedirs(HAIR_DIR, exist_ok=True)
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:
28
  raise RuntimeError(f"Mediapipe import failed. Check requirements pins. Details: {e}")
29
 
30
  mp_face_mesh = mp.solutions.face_mesh
31
+ mp_selfie_seg = mp.solutions.selfie_segmentation
32
  LM = {"left_eye_outer": 33, "right_eye_outer": 263, "mid_forehead": 10}
33
 
34
+ # ===================== Utilities =====================
 
 
 
 
35
  def load_hairstyles():
36
  try:
37
  files = [f for f in os.listdir(HAIR_DIR) if f.lower().endswith(".png")]
38
  except FileNotFoundError:
39
  files = []
40
+ files.sort()
41
  return files
42
 
43
  def load_meta():
 
51
  return {}
52
 
53
  def premultiply_alpha(bgra):
54
+ """Nicer blending (removes gray halos)."""
55
  bgr = bgra[:, :, :3].astype(np.float32) / 255.0
56
  a = (bgra[:, :, 3:4].astype(np.float32) / 255.0)
57
  bgr_pm = (bgr * a * 255.0).astype(np.uint8)
 
77
  def xy(i): return np.array([lm[i].x*w, lm[i].y*h], dtype=np.float32)
78
  return np.stack([xy(LM["left_eye_outer"]), xy(LM["right_eye_outer"]), xy(LM["mid_forehead"])])
79
 
80
+ def person_mask(img_bgr):
 
81
  with mp_selfie_seg.SelfieSegmentation(model_selection=1) as seg:
82
  rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
83
  m = seg.process(rgb).segmentation_mask
84
+ mask = (m > 0.5).astype(np.float32)
85
+ mask = cv2.GaussianBlur(mask, (35, 35), 0)
 
 
 
86
  return mask
87
 
88
  def hair_reference_points(hair_bgra, filename, meta):
 
91
  pts = np.array(meta[filename], dtype=np.float32)
92
  if pts.shape == (3, 2):
93
  return pts
94
+ # Defaults (OK for many styles). For perfect fit, add 3 points per file to meta.json.
95
  pL = np.array([0.30*w, 0.60*h], dtype=np.float32)
96
  pR = np.array([0.70*w, 0.60*h], dtype=np.float32)
97
  pM = np.array([0.50*w, 0.40*h], dtype=np.float32)
 
107
  out = (a * hair_warp + (1 - a) * base_bgr).astype(np.uint8)
108
  return out
109
 
110
+ def apply_tryon(image, hairstyle, scale_pct, rot_deg, dx, dy, opacity, meta):
 
 
 
 
 
111
  if image is None:
112
  return None, "Upload a photo or enable webcam."
113
  if not hairstyle:
 
141
 
142
  out = warp_and_alpha_blend(img_bgr, hair, M, opacity=opacity)
143
 
144
+ # Restrict to head region for cleaner look
145
+ head = person_mask(img_bgr)
146
+ head3 = head[..., None]
147
+ out = (head3 * out + (1 - head3) * img_bgr).astype(np.uint8)
 
 
148
 
149
  out_rgb = cv2.cvtColor(out, cv2.COLOR_BGR2RGB)
150
  return out_rgb, "OK"
151
 
152
  def save_png_to_tmp(img, filename="output_tryon.png"):
153
+ """Create a file in /tmp and return the path."""
154
  if img is None:
155
+ raise gr.Error("No image to download. Click Apply first.")
156
  out_path = os.path.join(tempfile.gettempdir(), filename)
157
  if isinstance(img, np.ndarray):
158
  Image.fromarray(img).save(out_path)
 
160
  img.save(out_path)
161
  return out_path
162
 
163
+ # ----- WHITE background thumbnails (no checkerboard) -----
164
  def thumb_on_white(hair_bgra, max_h=220):
165
  h, w = hair_bgra.shape[:2]
166
  scale = min(1.0, max_h / h)
 
173
 
174
  def build_gallery_items(files):
175
  items = []
176
+ for fname in files:
177
  try:
178
  img = load_hair_png(fname)
179
+ items.append((thumb_on_white(img), fname)) # (image, caption)
180
  except Exception:
181
  continue
182
  return items
183
 
184
+ # ===================== UI =====================
185
  def build_ui():
186
  META = load_meta()
187
  HAIR_FILES = load_hairstyles()
188
 
189
  with gr.Blocks(title="Salon Hairstyle Virtual Try-On", css="""
190
+ .gradio-container {max-width: 1200px; margin:auto;} /* wider so more tiles fit */
191
  @media (max-width: 768px){ .gradio-container {padding: 8px;} }
192
  """) as demo:
193
+ gr.Markdown("Upload a photo or use webcam. Put transparent **PNGs** in the **`hair/`** folder, then click **Refresh**.")
194
 
195
+ files_state = gr.State(HAIR_FILES) # keep filenames
196
  meta_state = gr.State(META)
197
 
198
  with gr.Tabs():
199
+ # ---------------- Photo Tab ----------------
200
  with gr.Tab("πŸ“· Photo (Upload)"):
201
  with gr.Row():
202
  in_img = gr.Image(label="Input photo (JPEG/PNG)", type="pil", height=360, sources=["upload"])
 
209
  interactive=True
210
  )
211
  apply_btn = gr.Button("✨ Apply (Align & Overlay)")
212
+ # One-click download + visible link fallback
213
+ download_btn = gr.DownloadButton("⬇️ Download")
214
+ download_file = gr.File(label="download (fallback)", visible=False)
215
  status = gr.Markdown()
216
 
217
  with gr.Row():
 
220
  gallery = gr.Gallery(
221
  label="Hairstyles (click to choose)",
222
  value=build_gallery_items(HAIR_FILES),
223
+ columns=6, rows=2, height=340, # up to 12 visible at once
224
  allow_preview=False, object_fit="contain", show_label=True
225
  )
226
 
 
232
  dx = gr.Slider(-200, 200, 0, 1, label="Left ↔ Right shift (px)")
233
  dy = gr.Slider(-200, 200, 0, 1, label="Up ↕ Down shift (px)")
234
  opacity = gr.Slider(0.2, 1.0, 1.0, 0.05, label="Hair opacity")
 
 
235
 
236
  # --- Callbacks ---
237
+ def do_apply(im, hfile, s, r, dxv, dyv, op, meta):
238
+ return apply_tryon(im, hfile, s, r, dxv, dyv, op, meta)
239
 
240
  apply_btn.click(
241
  fn=do_apply,
242
+ inputs=[in_img, hair_sel, scale, rot, dx, dy, opacity, meta_state],
243
  outputs=[out_img, status]
244
  )
245
 
246
+ # Return path for one-click download AND show fallback file link
247
+ def prepare_download_dual(im):
248
  path = save_png_to_tmp(im, "output_tryon.png")
249
+ return path, gr.File.update(value=path, visible=True)
250
 
251
+ download_btn.click(fn=prepare_download_dual, inputs=[out_img], outputs=[download_btn, download_file])
252
 
253
  def do_refresh():
254
  files = load_hairstyles()
 
258
 
259
  refresh.click(fn=do_refresh, inputs=[], outputs=[gallery, hair_sel, files_state, count_md])
260
 
261
+ # Clicking a tile sets the dropdown to that filename
262
  def on_gallery_select(evt, files):
263
  idx = getattr(evt, "index", None)
264
  if idx is None or not files:
265
  return gr.update()
266
+ if idx >= len(files):
267
+ idx = len(files) - 1
268
  return gr.update(value=files[idx])
269
 
270
  gallery.select(on_gallery_select, inputs=[files_state], outputs=[hair_sel])
271
 
272
+ # ---------------- Webcam Tab ----------------
273
  with gr.Tab("πŸ“Ή Webcam (Live Beta)"):
274
  cam = gr.Image(sources=["webcam"], streaming=True, type="pil", label="Enable camera")
275
  hair2 = gr.Dropdown(choices=HAIR_FILES, value=(HAIR_FILES[0] if HAIR_FILES else None), label="Selected hairstyle")
 
280
  dx2 = gr.Slider(-150, 150, 0, 1, label="Left ↔ Right (px)")
281
  dy2 = gr.Slider(-150, 150, 0, 1, label="Up ↕ Down (px)")
282
  opacity2 = gr.Slider(0.2, 1.0, 0.95, 0.05, label="Hair opacity")
 
 
283
  out2 = gr.Image(label="Live result", height=360)
284
  state_live = gr.State(None)
285
  snap = gr.Button("πŸ“Έ Snapshot")
286
+ save_live_btn = gr.DownloadButton("⬇️ Download Snapshot")
287
+ save_live_file = gr.File(label="snapshot (fallback)", visible=False)
288
 
289
+ def live(im, h, s, r, dxv, dyv, op, meta):
290
+ res, _ = apply_tryon(im, h, s, r, dxv, dyv, op, meta)
291
  return res, res
292
 
293
  cam.stream(
294
  fn=live,
295
+ inputs=[cam, hair2, scale2, rot2, dx2, dy2, opacity2, meta_state],
296
  outputs=[out2, state_live]
297
  )
298
 
299
  snap.click(lambda x: x, inputs=[state_live], outputs=[out2])
300
 
301
+ def prepare_webcam_download_dual(im):
302
  path = save_png_to_tmp(im, "tryon_webcam.png")
303
+ return path, gr.File.update(value=path, visible=True)
304
 
305
+ save_live_btn.click(fn=prepare_webcam_download_dual, inputs=[state_live], outputs=[save_live_btn, save_live_file])
306
 
307
  return demo
308
 
 
310
  app = build_ui()
311
  demo = app
312
 
313
+ # Local dev
314
  if __name__ == "__main__":
315
  app.launch()