RojaKatta commited on
Commit
9c49035
Β·
verified Β·
1 Parent(s): 5886e53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -137
app.py CHANGED
@@ -2,10 +2,10 @@ 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"),
@@ -17,19 +17,17 @@ if HAIR_DIR is None:
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():
@@ -51,7 +49,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,25 +75,13 @@ 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):
93
  h, w = hair_bgra.shape[:2]
94
  if filename in 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)
@@ -105,65 +91,51 @@ def warp_and_alpha_blend(base_bgr, hair_bgra, M, opacity=1.0):
105
  H, W = base_bgr.shape[:2]
106
  hair_rgb = hair_bgra[:, :, :3]
107
  hair_a = hair_bgra[:, :, 3] / 255.0
108
- hair_warp = cv2.warpAffine(hair_rgb, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_TRANSPARENT)
109
- a_warp = cv2.warpAffine(hair_a, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_TRANSPARENT)
 
 
 
110
  a = np.clip(a_warp * opacity, 0, 1)[..., None]
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:
123
- return np.array(image), "Pick a hairstyle first."
124
 
125
  img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
126
-
127
  kpts = detect_face_keypoints(img_bgr)
128
  if kpts is None:
129
- return image, "No face detected. Try a brighter, front-facing photo."
130
 
131
  hair = load_hair_png(hairstyle)
132
  hair_pts = hair_reference_points(hair, hairstyle, meta)
133
 
134
- # Destination points (with user nudges)
135
  dst = kpts.copy()
136
  dst[:, 0] += dx
137
  dst[:, 1] += dy
138
 
139
- # Scale + rotate around hair anchor centroid
140
  center = hair_pts.mean(axis=0)
141
- theta = np.deg2rad(rot_deg)
142
  s = max(0.5, scale_pct / 100.0)
143
- R = np.array([[np.cos(theta), -np.sin(theta)],
144
- [np.sin(theta), np.cos(theta)]], dtype=np.float32)
145
- hair_pts_adj = (hair_pts - center) @ R.T * s + center
146
 
147
  M, _ = cv2.estimateAffinePartial2D(hair_pts_adj, dst, method=cv2.LMEDS)
148
  if M is None:
149
- return image, "Could not compute alignment for this image/style."
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,13 +143,13 @@ 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)
178
  hair_bgra = cv2.resize(hair_bgra, (int(w*scale), int(h*scale)), interpolation=cv2.INTER_LINEAR)
179
  h, w = hair_bgra.shape[:2]
180
- bg_rgb = np.full((h, w, 3), 255, dtype=np.uint8) # white background
181
  a = (hair_bgra[:, :, 3:4] / 255.0)
182
  comp = (a * hair_bgra[:, :, :3] + (1 - a) * bg_rgb).astype(np.uint8)
183
  return cv2.cvtColor(comp, cv2.COLOR_BGR2RGB)
@@ -187,140 +159,102 @@ def build_gallery_items(files):
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"])
214
  out_img = gr.Image(label="Preview", height=360)
 
215
  with gr.Row():
216
- hair_sel = gr.Dropdown(
217
- choices=HAIR_FILES,
218
- value=(HAIR_FILES[0] if HAIR_FILES else None),
219
- label="Selected hairstyle",
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():
229
- refresh = gr.Button("πŸ”„ Refresh")
 
230
  count_md = gr.Markdown(f"Found {len(HAIR_FILES)} hairstyles.")
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
 
238
- with gr.Accordion("Fine-tune placement", open=True):
239
  with gr.Row():
240
- scale = gr.Slider(50, 200, 100, 1, label="Scale (β‰ˆ temple distance %)")
241
- rot = gr.Slider(-30, 30, 0, 1, label="Extra rotation (Β°)")
242
  with gr.Row():
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()
267
  items = build_gallery_items(files)
268
  msg = f"Found {len(files)} hairstyles."
269
- return items, gr.update(choices=files, value=(files[0] if files else None)), files, msg
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")
288
- with gr.Row():
289
- scale2 = gr.Slider(50, 200, 100, 1, label="Scale %")
290
- rot2 = gr.Slider(-25, 25, 0, 1, label="Rotate (Β°)")
291
- with gr.Row():
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
 
323
- # Export for Spaces autostart
324
  app = build_ui()
325
  demo = app
326
 
 
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"),
9
  os.path.join(BASE_DIR, "assets", "hairstyles"),
10
  os.path.join(BASE_DIR, "assets", "Hairstyles"),
11
  os.path.join(BASE_DIR, "hairstyles"),
 
17
 
18
  META_PATH = os.path.join(HAIR_DIR, "meta.json") # optional per-style anchors
19
 
20
+ # =============== Dependencies ===============
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
  LM = {"left_eye_outer": 33, "right_eye_outer": 263, "mid_forehead": 10}
28
 
29
+ # =============== Helpers ===============
30
  def natural_key(s: str):
 
31
  return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]
32
 
33
  def load_hairstyles():
 
49
  return {}
50
 
51
  def premultiply_alpha(bgra):
52
+ """Eliminate gray/white halos on edges."""
53
  bgr = bgra[:, :, :3].astype(np.float32) / 255.0
54
  a = (bgra[:, :, 3:4].astype(np.float32) / 255.0)
55
  bgr_pm = (bgr * a * 255.0).astype(np.uint8)
 
75
  def xy(i): return np.array([lm[i].x*w, lm[i].y*h], dtype=np.float32)
76
  return np.stack([xy(LM["left_eye_outer"]), xy(LM["right_eye_outer"]), xy(LM["mid_forehead"])])
77
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  def hair_reference_points(hair_bgra, filename, meta):
79
  h, w = hair_bgra.shape[:2]
80
  if filename in meta:
81
  pts = np.array(meta[filename], dtype=np.float32)
82
  if pts.shape == (3, 2):
83
  return pts
84
+ # Defaults (OK for many styles). For pixel-perfect fit, add 3 points to meta.json.
85
  pL = np.array([0.30*w, 0.60*h], dtype=np.float32)
86
  pR = np.array([0.70*w, 0.60*h], dtype=np.float32)
87
  pM = np.array([0.50*w, 0.40*h], dtype=np.float32)
 
91
  H, W = base_bgr.shape[:2]
92
  hair_rgb = hair_bgra[:, :, :3]
93
  hair_a = hair_bgra[:, :, 3] / 255.0
94
+ # borderMode CONSTANT avoids odd edge artifacts; value black (transparent)
95
+ hair_warp = cv2.warpAffine(hair_rgb, M, (W, H), flags=cv2.INTER_LINEAR,
96
+ borderMode=cv2.BORDER_CONSTANT, borderValue=(0,0,0))
97
+ a_warp = cv2.warpAffine(hair_a, M, (W, H), flags=cv2.INTER_LINEAR,
98
+ borderMode=cv2.BORDER_CONSTANT, borderValue=0)
99
  a = np.clip(a_warp * opacity, 0, 1)[..., None]
100
  out = (a * hair_warp + (1 - a) * base_bgr).astype(np.uint8)
101
  return out
102
 
103
+ def apply_tryon(image, hairstyle, scale_pct, dx, dy, opacity, meta):
104
+ """No head-mask (prevents neck lines & cropping)."""
 
 
 
 
105
  if image is None:
106
+ return None, "Upload a photo first."
107
  if not hairstyle:
108
+ return np.array(image), "Pick a hairstyle."
109
 
110
  img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
 
111
  kpts = detect_face_keypoints(img_bgr)
112
  if kpts is None:
113
+ return image, "No face detected. Use a brighter, front-facing photo."
114
 
115
  hair = load_hair_png(hairstyle)
116
  hair_pts = hair_reference_points(hair, hairstyle, meta)
117
 
118
+ # Target points = facial anchors + user nudges
119
  dst = kpts.copy()
120
  dst[:, 0] += dx
121
  dst[:, 1] += dy
122
 
123
+ # Scale hair anchors around their centroid (no rotation for simplicity)
124
  center = hair_pts.mean(axis=0)
 
125
  s = max(0.5, scale_pct / 100.0)
126
+ hair_pts_adj = (hair_pts - center) * s + center
 
 
127
 
128
  M, _ = cv2.estimateAffinePartial2D(hair_pts_adj, dst, method=cv2.LMEDS)
129
  if M is None:
130
+ return image, "Alignment failed for this image/style."
131
 
132
  out = warp_and_alpha_blend(img_bgr, hair, M, opacity=opacity)
 
 
 
 
 
 
 
 
133
  out_rgb = cv2.cvtColor(out, cv2.COLOR_BGR2RGB)
134
  return out_rgb, "OK"
135
 
136
  def save_png_to_tmp(img, filename="output_tryon.png"):
 
137
  if img is None:
138
+ raise gr.Error("No image to save. Click a hairstyle or 'Apply' first.")
139
  out_path = os.path.join(tempfile.gettempdir(), filename)
140
  if isinstance(img, np.ndarray):
141
  Image.fromarray(img).save(out_path)
 
143
  img.save(out_path)
144
  return out_path
145
 
146
+ # ---- white thumbnails with labels ----
147
  def thumb_on_white(hair_bgra, max_h=220):
148
  h, w = hair_bgra.shape[:2]
149
  scale = min(1.0, max_h / h)
150
  hair_bgra = cv2.resize(hair_bgra, (int(w*scale), int(h*scale)), interpolation=cv2.INTER_LINEAR)
151
  h, w = hair_bgra.shape[:2]
152
+ bg_rgb = np.full((h, w, 3), 255, dtype=np.uint8)
153
  a = (hair_bgra[:, :, 3:4] / 255.0)
154
  comp = (a * hair_bgra[:, :, :3] + (1 - a) * bg_rgb).astype(np.uint8)
155
  return cv2.cvtColor(comp, cv2.COLOR_BGR2RGB)
 
159
  for idx, fname in enumerate(files, start=1):
160
  try:
161
  img = load_hair_png(fname)
162
+ items.append((thumb_on_white(img), f"{idx}. {fname}")) # show number + filename
163
  except Exception:
164
  continue
165
  return items
166
 
167
+ # =============== UI ===============
168
  def build_ui():
169
  META = load_meta()
170
  HAIR_FILES = load_hairstyles()
171
 
172
+ with gr.Blocks(title="Salon Hairstyle Virtual Try-On (Simple)") as demo:
173
+ gr.Markdown("Upload a photo, then **click a hairstyle** below. Use a few sliders if needed, then **Save result**.")
 
 
 
174
 
175
+ selected_file = gr.State(None) # currently selected hairstyle filename
176
+ meta_state = gr.State(META)
177
+ files_state = gr.State(HAIR_FILES)
178
 
179
  with gr.Tabs():
 
180
  with gr.Tab("πŸ“· Photo (Upload)"):
181
  with gr.Row():
182
  in_img = gr.Image(label="Input photo (JPEG/PNG)", type="pil", height=360, sources=["upload"])
183
  out_img = gr.Image(label="Preview", height=360)
184
+
185
  with gr.Row():
186
+ apply_btn = gr.Button("✨ Apply (optional)")
187
+ save_btn = gr.Button("πŸ’Ύ Save result")
 
 
 
 
 
 
 
188
  save_file = gr.File(label="Saved file", visible=False)
 
189
 
190
  with gr.Row():
191
+ refresh = gr.Button("πŸ”„ Refresh styles")
192
+
193
  count_md = gr.Markdown(f"Found {len(HAIR_FILES)} hairstyles.")
194
  gallery = gr.Gallery(
195
+ label="Hairstyles (click to apply)",
196
  value=build_gallery_items(HAIR_FILES),
197
+ columns=6, rows=3, height=520,
198
  allow_preview=False, object_fit="contain", show_label=True
199
  )
200
 
201
+ with gr.Accordion("Fine-tune (simple)", open=True):
202
  with gr.Row():
203
+ scale = gr.Slider(50, 200, 100, 1, label="Scale (temple distance %)") # main size
204
+ opacity = gr.Slider(0.4, 1.0, 1.0, 0.05, label="Hair opacity")
205
  with gr.Row():
206
+ dx = gr.Slider(-200, 200, 0, 1, label="Left ↔ Right (px)")
207
+ dy = gr.Slider(-200, 200, 0, 1, label="Up ↕ Down (px)")
208
+
209
+ status = gr.Markdown("")
 
210
 
211
+ # ----- actions -----
212
+ def do_apply(im, hairfile, s, dxv, dyv, op, meta):
213
+ return apply_tryon(im, hairfile, s, dxv, dyv, op, meta)
214
 
215
+ # 1) click a tile -> set selected file AND auto-apply
216
+ def on_gallery_select(evt, files, im, s, dxv, dyv, op, meta):
217
+ idx = getattr(evt, "index", None)
218
+ if idx is None or not files:
219
+ return None, gr.update(), None
220
+ idx = max(0, min(idx, len(files)-1))
221
+ hairfile = files[idx]
222
+ out, msg = do_apply(im, hairfile, s, dxv, dyv, op, meta)
223
+ return hairfile, out, msg
224
+
225
+ gallery.select(
226
+ on_gallery_select,
227
+ inputs=[files_state, in_img, scale, dx, dy, opacity, meta_state],
228
+ outputs=[selected_file, out_img, status]
229
+ )
230
+
231
+ # 2) Apply button (useful after slider tweaks)
232
  apply_btn.click(
233
  fn=do_apply,
234
+ inputs=[in_img, selected_file, scale, dx, dy, opacity, meta_state],
235
  outputs=[out_img, status]
236
  )
237
 
238
+ # 3) Save
239
  def do_save(im):
240
  path = save_png_to_tmp(im, "output_tryon.png")
241
  return gr.File.update(value=path, visible=True)
242
 
243
  save_btn.click(fn=do_save, inputs=[out_img], outputs=[save_file])
244
 
245
+ # 4) Refresh styles
246
  def do_refresh():
247
  files = load_hairstyles()
248
  items = build_gallery_items(files)
249
  msg = f"Found {len(files)} hairstyles."
250
+ # Keep selection if name still exists
251
+ return items, files, msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
+ refresh.click(fn=do_refresh, inputs=[], outputs=[gallery, files_state, count_md])
254
 
255
  return demo
256
 
257
+ # export for Spaces
258
  app = build_ui()
259
  demo = app
260