Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,43 +1,42 @@
|
|
| 1 |
-
import os, json, tempfile
|
| 2 |
import cv2, numpy as np, gradio as gr
|
| 3 |
from PIL import Image
|
| 4 |
|
| 5 |
-
#
|
| 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"),
|
| 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 |
-
#
|
| 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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,7 +50,7 @@ def load_meta():
|
|
| 51 |
return {}
|
| 52 |
|
| 53 |
def premultiply_alpha(bgra):
|
| 54 |
-
"""
|
| 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)
|
|
@@ -60,8 +59,8 @@ def premultiply_alpha(bgra):
|
|
| 60 |
def load_hair_png(name):
|
| 61 |
path = os.path.join(HAIR_DIR, name)
|
| 62 |
hair = cv2.imread(path, cv2.IMREAD_UNCHANGED) # BGRA
|
| 63 |
-
if hair is None or hair.shape[2] != 4:
|
| 64 |
-
raise ValueError(f"Invalid hair asset: {name} (must be RGBA PNG)")
|
| 65 |
return premultiply_alpha(hair)
|
| 66 |
|
| 67 |
def detect_face_keypoints(img_bgr):
|
|
@@ -77,21 +76,14 @@ 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):
|
| 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):
|
|
|
|
| 89 |
h, w = hair_bgra.shape[:2]
|
| 90 |
if filename in 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
|
| 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)
|
|
@@ -100,59 +92,56 @@ def hair_reference_points(hair_bgra, filename, meta):
|
|
| 100 |
def warp_and_alpha_blend(base_bgr, hair_bgra, M, opacity=1.0):
|
| 101 |
H, W = base_bgr.shape[:2]
|
| 102 |
hair_rgb = hair_bgra[:, :, :3]
|
| 103 |
-
hair_a
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
| 106 |
a = np.clip(a_warp * opacity, 0, 1)[..., None]
|
| 107 |
out = (a * hair_warp + (1 - a) * base_bgr).astype(np.uint8)
|
| 108 |
return out
|
| 109 |
|
| 110 |
-
def apply_tryon(image, hairstyle, scale_pct,
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 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
|
| 156 |
out_path = os.path.join(tempfile.gettempdir(), filename)
|
| 157 |
if isinstance(img, np.ndarray):
|
| 158 |
Image.fromarray(img).save(out_path)
|
|
@@ -160,156 +149,145 @@ def save_png_to_tmp(img, filename="output_tryon.png"):
|
|
| 160 |
img.save(out_path)
|
| 161 |
return out_path
|
| 162 |
|
| 163 |
-
#
|
| 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)
|
| 167 |
hair_bgra = cv2.resize(hair_bgra, (int(w*scale), int(h*scale)), interpolation=cv2.INTER_LINEAR)
|
| 168 |
h, w = hair_bgra.shape[:2]
|
| 169 |
-
bg_rgb = np.full((h, w, 3), 255, dtype=np.uint8)
|
| 170 |
a = (hair_bgra[:, :, 3:4] / 255.0)
|
| 171 |
comp = (a * hair_bgra[:, :, :3] + (1 - a) * bg_rgb).astype(np.uint8)
|
| 172 |
return cv2.cvtColor(comp, cv2.COLOR_BGR2RGB)
|
| 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))
|
| 180 |
except Exception:
|
| 181 |
continue
|
| 182 |
return items
|
| 183 |
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
def build_ui():
|
| 186 |
META = load_meta()
|
| 187 |
HAIR_FILES = load_hairstyles()
|
| 188 |
|
| 189 |
-
with gr.Blocks(title="Salon Hairstyle Virtual Try-On
|
| 190 |
-
|
| 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 |
-
|
| 196 |
-
meta_state
|
|
|
|
| 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"])
|
| 203 |
out_img = gr.Image(label="Preview", height=360)
|
|
|
|
| 204 |
with gr.Row():
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
label="Selected hairstyle",
|
| 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():
|
| 218 |
-
refresh = gr.Button("π Refresh")
|
|
|
|
| 219 |
count_md = gr.Markdown(f"Found {len(HAIR_FILES)} hairstyles.")
|
| 220 |
gallery = gr.Gallery(
|
| 221 |
-
label="Hairstyles (click to
|
| 222 |
value=build_gallery_items(HAIR_FILES),
|
| 223 |
-
columns=6, rows=
|
| 224 |
allow_preview=False, object_fit="contain", show_label=True
|
| 225 |
)
|
| 226 |
|
| 227 |
-
with gr.Accordion("Fine-tune
|
| 228 |
with gr.Row():
|
| 229 |
-
scale = gr.Slider(50, 200, 100, 1, label="Scale (
|
| 230 |
-
|
| 231 |
with gr.Row():
|
| 232 |
-
dx = gr.Slider(-200, 200, 0, 1, label="Left β Right
|
| 233 |
-
dy = gr.Slider(-200, 200, 0, 1, label="Up β Down
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
def do_apply(im,
|
| 238 |
-
return apply_tryon(im,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
|
|
|
| 240 |
apply_btn.click(
|
| 241 |
fn=do_apply,
|
| 242 |
-
inputs=[in_img,
|
| 243 |
outputs=[out_img, status]
|
| 244 |
)
|
| 245 |
|
| 246 |
-
#
|
| 247 |
-
def
|
| 248 |
path = save_png_to_tmp(im, "output_tryon.png")
|
| 249 |
-
return
|
| 250 |
|
| 251 |
-
|
| 252 |
|
|
|
|
| 253 |
def do_refresh():
|
| 254 |
files = load_hairstyles()
|
| 255 |
items = build_gallery_items(files)
|
| 256 |
msg = f"Found {len(files)} hairstyles."
|
| 257 |
-
return items,
|
| 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")
|
| 276 |
-
with gr.Row():
|
| 277 |
-
scale2 = gr.Slider(50, 200, 100, 1, label="Scale %")
|
| 278 |
-
rot2 = gr.Slider(-25, 25, 0, 1, label="Rotate (Β°)")
|
| 279 |
-
with gr.Row():
|
| 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 |
-
|
| 306 |
|
| 307 |
return demo
|
| 308 |
|
| 309 |
-
#
|
| 310 |
app = build_ui()
|
| 311 |
demo = app
|
| 312 |
|
| 313 |
-
# Local dev
|
| 314 |
if __name__ == "__main__":
|
| 315 |
app.launch()
|
|
|
|
| 1 |
+
import os, json, tempfile, re, traceback
|
| 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"),
|
| 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 |
LM = {"left_eye_outer": 33, "right_eye_outer": 263, "mid_forehead": 10}
|
| 28 |
|
| 29 |
+
# -------- Helpers --------
|
| 30 |
+
def natural_key(s: str):
|
| 31 |
+
"""Sort 'photo1.png'...'photo11.png' in numeric order."""
|
| 32 |
+
return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", s)]
|
| 33 |
+
|
| 34 |
def load_hairstyles():
|
| 35 |
try:
|
| 36 |
files = [f for f in os.listdir(HAIR_DIR) if f.lower().endswith(".png")]
|
| 37 |
except FileNotFoundError:
|
| 38 |
files = []
|
| 39 |
+
files.sort(key=natural_key)
|
| 40 |
return files
|
| 41 |
|
| 42 |
def load_meta():
|
|
|
|
| 50 |
return {}
|
| 51 |
|
| 52 |
def premultiply_alpha(bgra):
|
| 53 |
+
"""Removes gray/white halos on edges."""
|
| 54 |
bgr = bgra[:, :, :3].astype(np.float32) / 255.0
|
| 55 |
a = (bgra[:, :, 3:4].astype(np.float32) / 255.0)
|
| 56 |
bgr_pm = (bgr * a * 255.0).astype(np.uint8)
|
|
|
|
| 59 |
def load_hair_png(name):
|
| 60 |
path = os.path.join(HAIR_DIR, name)
|
| 61 |
hair = cv2.imread(path, cv2.IMREAD_UNCHANGED) # BGRA
|
| 62 |
+
if hair is None or hair.ndim != 3 or hair.shape[2] != 4:
|
| 63 |
+
raise ValueError(f"Invalid hair asset: {name} (must be RGBA PNG in {HAIR_DIR})")
|
| 64 |
return premultiply_alpha(hair)
|
| 65 |
|
| 66 |
def detect_face_keypoints(img_bgr):
|
|
|
|
| 76 |
def xy(i): return np.array([lm[i].x*w, lm[i].y*h], dtype=np.float32)
|
| 77 |
return np.stack([xy(LM["left_eye_outer"]), xy(LM["right_eye_outer"]), xy(LM["mid_forehead"])])
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
def hair_reference_points(hair_bgra, filename, meta):
|
| 80 |
+
"""Return 3 anchor points (L-eye, R-eye, mid-forehead) in hair PNG space."""
|
| 81 |
h, w = hair_bgra.shape[:2]
|
| 82 |
if filename in meta:
|
| 83 |
pts = np.array(meta[filename], dtype=np.float32)
|
| 84 |
if pts.shape == (3, 2):
|
| 85 |
return pts
|
| 86 |
+
# Defaults (OK for many styles). For perfection, put 3 points per file in hair/meta.json.
|
| 87 |
pL = np.array([0.30*w, 0.60*h], dtype=np.float32)
|
| 88 |
pR = np.array([0.70*w, 0.60*h], dtype=np.float32)
|
| 89 |
pM = np.array([0.50*w, 0.40*h], dtype=np.float32)
|
|
|
|
| 92 |
def warp_and_alpha_blend(base_bgr, hair_bgra, M, opacity=1.0):
|
| 93 |
H, W = base_bgr.shape[:2]
|
| 94 |
hair_rgb = hair_bgra[:, :, :3]
|
| 95 |
+
hair_a = hair_bgra[:, :, 3] / 255.0
|
| 96 |
+
# CONSTANT borders avoid clipping/edge artifacts
|
| 97 |
+
hair_warp = cv2.warpAffine(hair_rgb, M, (W, H), flags=cv2.INTER_LINEAR,
|
| 98 |
+
borderMode=cv2.BORDER_CONSTANT, borderValue=(0,0,0))
|
| 99 |
+
a_warp = cv2.warpAffine(hair_a, M, (W, H), flags=cv2.INTER_LINEAR,
|
| 100 |
+
borderMode=cv2.BORDER_CONSTANT, borderValue=0)
|
| 101 |
a = np.clip(a_warp * opacity, 0, 1)[..., None]
|
| 102 |
out = (a * hair_warp + (1 - a) * base_bgr).astype(np.uint8)
|
| 103 |
return out
|
| 104 |
|
| 105 |
+
def apply_tryon(image, hairstyle, scale_pct, dx, dy, opacity, meta):
|
| 106 |
+
"""Simple engine: NO head-mask (prevents neck lines + lost hair)."""
|
| 107 |
+
try:
|
| 108 |
+
if image is None:
|
| 109 |
+
return None, "Upload a photo first."
|
| 110 |
+
if not hairstyle:
|
| 111 |
+
return np.array(image), "Pick a hairstyle."
|
| 112 |
+
|
| 113 |
+
img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 114 |
+
kpts = detect_face_keypoints(img_bgr)
|
| 115 |
+
if kpts is None:
|
| 116 |
+
return image, "No face detected. Use a brighter, front-facing photo."
|
| 117 |
+
|
| 118 |
+
hair = load_hair_png(hairstyle)
|
| 119 |
+
hair_pts = hair_reference_points(hair, hairstyle, meta)
|
| 120 |
+
|
| 121 |
+
# destination landmarks + nudges
|
| 122 |
+
dst = kpts.copy()
|
| 123 |
+
dst[:, 0] += dx
|
| 124 |
+
dst[:, 1] += dy
|
| 125 |
+
|
| 126 |
+
# scale (no rotation β simpler UI)
|
| 127 |
+
center = hair_pts.mean(axis=0)
|
| 128 |
+
s = max(0.5, scale_pct / 100.0)
|
| 129 |
+
hair_pts_adj = (hair_pts - center) * s + center
|
| 130 |
+
|
| 131 |
+
M, _ = cv2.estimateAffinePartial2D(hair_pts_adj, dst, method=cv2.LMEDS)
|
| 132 |
+
if M is None:
|
| 133 |
+
return image, "Alignment failed for this image/style."
|
| 134 |
+
|
| 135 |
+
out = warp_and_alpha_blend(img_bgr, hair, M, opacity=opacity)
|
| 136 |
+
return cv2.cvtColor(out, cv2.COLOR_BGR2RGB), "OK"
|
| 137 |
+
except Exception as e:
|
| 138 |
+
print("apply_tryon error:", e)
|
| 139 |
+
traceback.print_exc()
|
| 140 |
+
return np.array(image) if image is not None else None, "Error applying style."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
def save_png_to_tmp(img, filename="output_tryon.png"):
|
|
|
|
| 143 |
if img is None:
|
| 144 |
+
raise gr.Error("No image to save. Click a hairstyle or 'Apply' first.")
|
| 145 |
out_path = os.path.join(tempfile.gettempdir(), filename)
|
| 146 |
if isinstance(img, np.ndarray):
|
| 147 |
Image.fromarray(img).save(out_path)
|
|
|
|
| 149 |
img.save(out_path)
|
| 150 |
return out_path
|
| 151 |
|
| 152 |
+
# White thumbnails with captions (number + filename)
|
| 153 |
def thumb_on_white(hair_bgra, max_h=220):
|
| 154 |
h, w = hair_bgra.shape[:2]
|
| 155 |
scale = min(1.0, max_h / h)
|
| 156 |
hair_bgra = cv2.resize(hair_bgra, (int(w*scale), int(h*scale)), interpolation=cv2.INTER_LINEAR)
|
| 157 |
h, w = hair_bgra.shape[:2]
|
| 158 |
+
bg_rgb = np.full((h, w, 3), 255, dtype=np.uint8)
|
| 159 |
a = (hair_bgra[:, :, 3:4] / 255.0)
|
| 160 |
comp = (a * hair_bgra[:, :, :3] + (1 - a) * bg_rgb).astype(np.uint8)
|
| 161 |
return cv2.cvtColor(comp, cv2.COLOR_BGR2RGB)
|
| 162 |
|
| 163 |
def build_gallery_items(files):
|
| 164 |
items = []
|
| 165 |
+
for idx, fname in enumerate(files, start=1):
|
| 166 |
try:
|
| 167 |
img = load_hair_png(fname)
|
| 168 |
+
items.append((thumb_on_white(img), f"{idx}. {fname}"))
|
| 169 |
except Exception:
|
| 170 |
continue
|
| 171 |
return items
|
| 172 |
|
| 173 |
+
def event_to_filename(evt, files):
|
| 174 |
+
"""Robust across Gradio versions."""
|
| 175 |
+
idx = getattr(evt, "index", None)
|
| 176 |
+
if isinstance(idx, int) and 0 <= idx < len(files):
|
| 177 |
+
return files[idx]
|
| 178 |
+
val = getattr(evt, "value", None)
|
| 179 |
+
cap = None
|
| 180 |
+
if isinstance(val, str):
|
| 181 |
+
cap = val
|
| 182 |
+
elif isinstance(val, (tuple, list)) and len(val) >= 2 and isinstance(val[1], str):
|
| 183 |
+
cap = val[1]
|
| 184 |
+
elif isinstance(val, dict) and "caption" in val and isinstance(val["caption"], str):
|
| 185 |
+
cap = val["caption"]
|
| 186 |
+
if cap:
|
| 187 |
+
m = re.search(r"\b(\d+)\.\s*(.+)$", cap.strip())
|
| 188 |
+
if m:
|
| 189 |
+
i = int(m.group(1)) - 1
|
| 190 |
+
if 0 <= i < len(files):
|
| 191 |
+
return files[i]
|
| 192 |
+
for f in files:
|
| 193 |
+
if f.lower() == cap.lower():
|
| 194 |
+
return f
|
| 195 |
+
return files[0] if files else None
|
| 196 |
+
|
| 197 |
+
# -------- UI --------
|
| 198 |
def build_ui():
|
| 199 |
META = load_meta()
|
| 200 |
HAIR_FILES = load_hairstyles()
|
| 201 |
|
| 202 |
+
with gr.Blocks(title="Salon Hairstyle Virtual Try-On β Simple & Stable") as demo:
|
| 203 |
+
gr.Markdown("Upload a photo, then **click a hairstyle**. Adjust size/position if needed. Use **Save result** to export.")
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
+
selected_file = gr.State(None)
|
| 206 |
+
meta_state = gr.State(META)
|
| 207 |
+
files_state = gr.State(HAIR_FILES)
|
| 208 |
|
| 209 |
with gr.Tabs():
|
|
|
|
| 210 |
with gr.Tab("π· Photo (Upload)"):
|
| 211 |
with gr.Row():
|
| 212 |
in_img = gr.Image(label="Input photo (JPEG/PNG)", type="pil", height=360, sources=["upload"])
|
| 213 |
out_img = gr.Image(label="Preview", height=360)
|
| 214 |
+
|
| 215 |
with gr.Row():
|
| 216 |
+
apply_btn = gr.Button("β¨ Apply (optional)")
|
| 217 |
+
save_btn = gr.Button("πΎ Save result")
|
| 218 |
+
save_file = gr.File(label="Saved file", visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
with gr.Row():
|
| 221 |
+
refresh = gr.Button("π Refresh styles")
|
| 222 |
+
|
| 223 |
count_md = gr.Markdown(f"Found {len(HAIR_FILES)} hairstyles.")
|
| 224 |
gallery = gr.Gallery(
|
| 225 |
+
label="Hairstyles (click to apply)",
|
| 226 |
value=build_gallery_items(HAIR_FILES),
|
| 227 |
+
columns=6, rows=3, height=520,
|
| 228 |
allow_preview=False, object_fit="contain", show_label=True
|
| 229 |
)
|
| 230 |
|
| 231 |
+
with gr.Accordion("Fine-tune (simple)", open=True):
|
| 232 |
with gr.Row():
|
| 233 |
+
scale = gr.Slider(50, 200, 100, 1, label="Scale (temple distance %)")
|
| 234 |
+
opacity = gr.Slider(0.4, 1.0, 1.0, 0.05, label="Hair opacity")
|
| 235 |
with gr.Row():
|
| 236 |
+
dx = gr.Slider(-200, 200, 0, 1, label="Left β Right (px)")
|
| 237 |
+
dy = gr.Slider(-200, 200, 0, 1, label="Up β Down (px)")
|
| 238 |
+
|
| 239 |
+
status = gr.Markdown("")
|
| 240 |
+
|
| 241 |
+
def do_apply(im, hairfile, s, dxv, dyv, op, meta):
|
| 242 |
+
return apply_tryon(im, hairfile, s, dxv, dyv, op, meta)
|
| 243 |
+
|
| 244 |
+
# Click a tile β apply (robust to Gradio variants)
|
| 245 |
+
def on_gallery_select(evt, files, im, s, dxv, dyv, op, meta):
|
| 246 |
+
try:
|
| 247 |
+
hairfile = event_to_filename(evt, files)
|
| 248 |
+
if hairfile is None:
|
| 249 |
+
return None, im, "No styles found."
|
| 250 |
+
out, msg = do_apply(im, hairfile, s, dxv, dyv, op, meta)
|
| 251 |
+
return hairfile, out, msg
|
| 252 |
+
except Exception as e:
|
| 253 |
+
print("gallery.select error:", e)
|
| 254 |
+
traceback.print_exc()
|
| 255 |
+
return None, im, "Error applying style."
|
| 256 |
+
|
| 257 |
+
gallery.select(
|
| 258 |
+
on_gallery_select,
|
| 259 |
+
inputs=[files_state, in_img, scale, dx, dy, opacity, meta_state],
|
| 260 |
+
outputs=[selected_file, out_img, status]
|
| 261 |
+
)
|
| 262 |
|
| 263 |
+
# Apply after slider tweaks
|
| 264 |
apply_btn.click(
|
| 265 |
fn=do_apply,
|
| 266 |
+
inputs=[in_img, selected_file, scale, dx, dy, opacity, meta_state],
|
| 267 |
outputs=[out_img, status]
|
| 268 |
)
|
| 269 |
|
| 270 |
+
# Save to a real file (shows a link you can click to download)
|
| 271 |
+
def do_save(im):
|
| 272 |
path = save_png_to_tmp(im, "output_tryon.png")
|
| 273 |
+
return gr.File.update(value=path, visible=True)
|
| 274 |
|
| 275 |
+
save_btn.click(fn=do_save, inputs=[out_img], outputs=[save_file])
|
| 276 |
|
| 277 |
+
# Refresh styles list
|
| 278 |
def do_refresh():
|
| 279 |
files = load_hairstyles()
|
| 280 |
items = build_gallery_items(files)
|
| 281 |
msg = f"Found {len(files)} hairstyles."
|
| 282 |
+
return items, files, msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
+
refresh.click(fn=do_refresh, inputs=[], outputs=[gallery, files_state, count_md])
|
| 285 |
|
| 286 |
return demo
|
| 287 |
|
| 288 |
+
# Spaces autostart
|
| 289 |
app = build_ui()
|
| 290 |
demo = app
|
| 291 |
|
|
|
|
| 292 |
if __name__ == "__main__":
|
| 293 |
app.launch()
|