Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,256 +1,315 @@
|
|
| 1 |
-
import os,
|
| 2 |
-
import numpy as np
|
| 3 |
from PIL import Image
|
| 4 |
-
import gradio as gr
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
try:
|
| 11 |
-
import cv2
|
| 12 |
import mediapipe as mp
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
#
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
#
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 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
|
| 80 |
-
|
| 81 |
lm = res.multi_face_landmarks[0].landmark
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 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 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
return out_path
|
| 186 |
|
| 187 |
-
#
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
if __name__ == "__main__":
|
| 256 |
-
|
|
|
|
| 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():
|
| 44 |
+
if os.path.exists(META_PATH):
|
| 45 |
+
try:
|
| 46 |
+
with open(META_PATH, "r") as f:
|
| 47 |
+
m = json.load(f)
|
| 48 |
+
return m if isinstance(m, dict) else {}
|
| 49 |
+
except Exception:
|
| 50 |
+
return {}
|
| 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)
|
| 58 |
+
return np.dstack([bgr_pm, bgra[:, :, 3]])
|
| 59 |
+
|
| 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):
|
| 68 |
+
h, w = img_bgr.shape[:2]
|
| 69 |
+
with mp_face_mesh.FaceMesh(
|
| 70 |
+
static_image_mode=True, max_num_faces=1, refine_landmarks=True,
|
| 71 |
+
min_detection_confidence=0.6
|
| 72 |
+
) as fm:
|
| 73 |
+
res = fm.process(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
if not res.multi_face_landmarks:
|
| 75 |
+
return None
|
|
|
|
| 76 |
lm = res.multi_face_landmarks[0].landmark
|
| 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 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)
|
| 98 |
+
return np.stack([pL, pR, pM], axis=0)
|
| 99 |
+
|
| 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 = hair_bgra[:, :, 3] / 255.0
|
| 104 |
+
hair_warp = cv2.warpAffine(hair_rgb, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_TRANSPARENT)
|
| 105 |
+
a_warp = cv2.warpAffine(hair_a, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_TRANSPARENT)
|
| 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, rot_deg, dx, dy, opacity, meta):
|
| 111 |
+
if image is None:
|
| 112 |
+
return None, "Upload a photo or enable webcam."
|
| 113 |
+
if not hairstyle:
|
| 114 |
+
return np.array(image), "Pick a hairstyle first."
|
| 115 |
+
|
| 116 |
+
img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
| 117 |
+
|
| 118 |
+
kpts = detect_face_keypoints(img_bgr)
|
| 119 |
+
if kpts is None:
|
| 120 |
+
return image, "No face detected. Try a brighter, front-facing photo."
|
| 121 |
+
|
| 122 |
+
hair = load_hair_png(hairstyle)
|
| 123 |
+
hair_pts = hair_reference_points(hair, hairstyle, meta)
|
| 124 |
+
|
| 125 |
+
# Destination points (with user nudges)
|
| 126 |
+
dst = kpts.copy()
|
| 127 |
+
dst[:, 0] += dx
|
| 128 |
+
dst[:, 1] += dy
|
| 129 |
+
|
| 130 |
+
# Scale + rotate around hair anchor centroid
|
| 131 |
+
center = hair_pts.mean(axis=0)
|
| 132 |
+
theta = np.deg2rad(rot_deg)
|
| 133 |
+
s = max(0.5, scale_pct / 100.0)
|
| 134 |
+
R = np.array([[np.cos(theta), -np.sin(theta)],
|
| 135 |
+
[np.sin(theta), np.cos(theta)]], dtype=np.float32)
|
| 136 |
+
hair_pts_adj = (hair_pts - center) @ R.T * s + center
|
| 137 |
+
|
| 138 |
+
M, _ = cv2.estimateAffinePartial2D(hair_pts_adj, dst, method=cv2.LMEDS)
|
| 139 |
+
if M is None:
|
| 140 |
+
return image, "Could not compute alignment for this image/style."
|
| 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)
|
| 159 |
+
else:
|
| 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)
|
| 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) # white background
|
| 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)) # (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"])
|
| 203 |
+
out_img = gr.Image(label="Preview", height=360)
|
| 204 |
+
with gr.Row():
|
| 205 |
+
hair_sel = gr.Dropdown(
|
| 206 |
+
choices=HAIR_FILES,
|
| 207 |
+
value=(HAIR_FILES[0] if HAIR_FILES else None),
|
| 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 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 |
+
|
| 227 |
+
with gr.Accordion("Fine-tune placement", open=True):
|
| 228 |
+
with gr.Row():
|
| 229 |
+
scale = gr.Slider(50, 200, 100, 1, label="Scale (β temple distance %)")
|
| 230 |
+
rot = gr.Slider(-30, 30, 0, 1, label="Extra rotation (Β°)")
|
| 231 |
+
with gr.Row():
|
| 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()
|
| 255 |
+
items = build_gallery_items(files)
|
| 256 |
+
msg = f"Found {len(files)} hairstyles."
|
| 257 |
+
return items, gr.update(choices=files, value=(files[0] if files else None)), files, msg
|
| 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 |
+
save_live_btn.click(fn=prepare_webcam_download_dual, inputs=[state_live], outputs=[save_live_btn, save_live_file])
|
| 306 |
+
|
| 307 |
+
return demo
|
| 308 |
+
|
| 309 |
+
# Export for Spaces autostart
|
| 310 |
+
app = build_ui()
|
| 311 |
+
demo = app
|
| 312 |
+
|
| 313 |
+
# Local dev
|
| 314 |
if __name__ == "__main__":
|
| 315 |
+
app.launch()
|