Dailytouch123's picture
import gradio as gr import numpy as np from PIL import Image import cv2 # ========= CONFIG ========= SITE_URL = "https://sites.google.com/view/daily-insights-/home" # your website BRAND_SUGGESTIONS = { "Oily": [ ("CeraVe Foaming Facial Cleanser", "Oil control, gentle"), ("The Ordinary Niacinamide 10% + Zinc 1%", "Sebum balance"), ("La Roche-Posay Anthelios Oil Control SPF", "Sunscreen"), ], "Dry": [ ("CeraVe Hydrating Cleanser", "Non-stripping"), ("Neutrogena Hydro Boost Water Gel", "Hyaluronic acid"), ("La Roche-Posay Cicaplast Baume B5", "Barrier repair"), ], "Normal": [ ("Simple Kind to Skin Cleanser", "Gentle daily wash"), ("CeraVe Daily Moisturizing Lotion", "Balanced moisture"), ("Biore UV Aqua Rich SPF", "Daily sunscreen"), ], "Acne-Prone": [ ("CeraVe SA Cleanser (Salicylic Acid)", "Exfoliating cleanser"), ("The Ordinary Azelaic Acid 10%", "Redness & texture"), ("Differin (Adapalene 0.1%)", "Night treatment*"), ], } # ========================== def _crop_face(img_bgr): """Return a face crop using OpenCV haarcascade. Fallback to center crop.""" gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY) face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + "haarcascade_frontalface_default.xml" ) faces = face_cascade.detectMultiScale(gray, 1.2, 5, minSize=(80, 80)) if len(faces): x, y, w, h = max(faces, key=lambda r: r[2] * r[3]) pad = int(0.12 * max(w, h)) x0, y0 = max(0, x - pad), max(0, y - pad) x1, y1 = min(img_bgr.shape[1], x + w + pad), min(img_bgr.shape[0], y + h + pad) return img_bgr[y0:y1, x0:x1] # fallback center crop h, w = img_bgr.shape[:2] side = int(min(h, w) * 0.7) cx, cy = w // 2, h // 2 x0, y0 = max(0, cx - side // 2), max(0, cy - side // 2) return img_bgr[y0 : y0 + side, x0 : x0 + side] def _analyze_heuristics(img_bgr): """ Lightweight, on-device heuristics (no heavy model): - Oily proxy: high highlight (HSV V) in T-zone vs cheeks - Dry proxy: low overall V + higher edge roughness - Acne proxy: count of small red-ish blobs within skin area - Normal if none dominate Returns dict of scores in [0,1]. """ face = _crop_face(img_bgr) face = cv2.resize(face, (320, 320), interpolation=cv2.INTER_AREA) hsv = cv2.cvtColor(face, cv2.COLOR_BGR2HSV) h_, s_, v_ = cv2.split(hsv) # Define simple T-zone and cheeks ROIs H, W = v_.shape tzone = v_[int(0.20 * H) : int(0.50 * H), int(0.35 * W) : int(0.65 * W)] cheek_l = v_[int(0.45 * H) : int(0.75 * H), int(0.10 * W) : int(0.30 * W)] cheek_r = v_[int(0.45 * H) : int(0.75 * H), int(0.70 * W) : int(0.90 * W)] cheeks = np.concatenate([cheek_l.flatten(), cheek_r.flatten()]) # Oily: T-zone brightness relative to cheeks oily_raw = float(np.clip(np.mean(tzone) - np.mean(cheeks), 0, 255) / 255.0) # Dry: low brightness + higher edge energy (texture looks flaky) v_norm = v_ / 255.0 low_light = float(np.clip(0.6 - np.mean(v_norm), 0, 0.6) / 0.6) # darker β†’ drier proxy lap = cv2.Laplacian(cv2.cvtColor(face, cv2.COLOR_BGR2GRAY), cv2.CV_64F) edge_var = float(np.var(lap) / 4000.0) # normalize dry_raw = float(np.clip(0.5 * low_light + 0.5 * np.clip(edge_var, 0, 1), 0, 1)) # Acne: red-ish small blobs b, g, r = cv2.split(face) red = cv2.subtract(r, cv2.max(b, g)) _, red_mask = cv2.threshold(red, 30, 255, cv2.THRESH_BINARY) red_mask = cv2.medianBlur(red_mask, 5) cnts, _ = cv2.findContours(red_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) acne_spots = [c for c in cnts if 6 < cv2.contourArea(c) < 200] acne_density = float(len(acne_spots)) / 120.0 # normalize roughly acne_raw = float(np.clip(acne_density, 0, 1)) # Normal score is inverse of others normal_raw = float(np.clip(1.2 - (oily_raw + dry_raw + acne_raw), 0, 1)) # Softmax-like normalization to probabilities scores = { "Oily": oily_raw, "Dry": dry_raw, "Acne-Prone": acne_raw, "Normal": normal_raw, } arr = np.array(list(scores.values()), dtype=np.float32) arr = np.clip(arr, 1e-6, None) probs = arr / arr.sum() return {k: float(v) for k, v in zip(scores.keys(), probs)} def _advice_for(skin_type): base = { "Oily": ( "Your skin looks a bit oily today β€” totally normal. " "Use a gentle foaming cleanser morning and night, avoid heavy creams, " "and pick non-comedogenic, oil-free products. Finish with a lightweight, matte sunscreen." ), "Dry": ( "Skin looks on the dry side. Go for a hydrating, non-foaming cleanser, " "apply a moisturizer with ceramides or hyaluronic acid while skin is slightly damp, " "and use a nourishing sunscreen. Avoid alcohol-heavy toners." ), "Normal": ( "Balanced skin! Keep a simple routine: gentle cleanse β†’ light moisturizer β†’ daily sunscreen. " "Introduce actives slowly (vitamin C in the morning, retinoid at night) if you want extra glow." ), "Acne-Prone": ( "I see signs of acne. Use a gentle cleanser and introduce salicylic acid (BHA) 2–3Γ—/week. " "Spot treat with benzoyl peroxide, and use a non-comedogenic moisturizer. " "If irritation persists, consult a dermatologist." ), } return base[skin_type] def _product_html(skin_type): items = BRAND_SUGGESTIONS[skin_type] li = "\n".join( f"<li><b>{name}</b> β€” <span style='color:#6b7280'>{note}</span></li>" for name, note in items ) return f""" <ul style="margin:8px 0 0 18px; line-height:1.5">{li}</ul> """ def analyze(image: Image.Image): if image is None: return "<div style='color:#ef4444'>Please upload a clear face photo.</div>" img = np.array(image.convert("RGB"))[:, :, ::-1] # to BGR scores = _analyze_heuristics(img) skin_type = max(scores, key=scores.get) confidence = int(round(scores[skin_type] * 100)) advice = _advice_for(skin_type) products = _product_html(skin_type) html = f""" <div style=" font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto; background:#0b1220; color:#e5e7eb; padding:18px; border-radius:16px; border:1px solid rgba(255,255,255,.08); box-shadow:0 10px 24px rgba(0,0,0,.25) "> <div style="display:flex;gap:10px;align-items:center;margin-bottom:6px"> <div style="font-size:18px;font-weight:700">AI Skin Analysis</div> <span style="padding:4px 10px;border-radius:999px;background:#111827;border:1px solid #1f2937;font-size:12px"> Honest assistant mode </span> </div> <div style="display:grid;gap:8px"> <div><b>Skin Type:</b> <span style="color:#a7f3d0">{skin_type}</span></div> <div><b>Confidence:</b> {confidence}/100</div> <div style="height:8px;background:#111827;border-radius:999px;overflow:hidden"> <div style="height:100%;width:{confidence}%;background:#10b981"></div> </div> </div> <div style="margin-top:10px;line-height:1.6"> <b>Advice:</b><br>{advice} </div> <div style="margin-top:12px"> <b>Suggested products (demo, trusted global brands):</b> {products} </div> <div style="margin-top:12px;padding:10px;background:#0f172a;border-radius:12px;border:1px solid #1f2937"> For original & safe products, visit: <a href="{SITE_URL}" target="_blank" style="color:#22d3ee;text-decoration:none"> Daily Insights β†’</a> </div> <div style="margin-top:8px;color:#9ca3af;font-size:12px"> Privacy note: your photo is analyzed to generate advice; do not rely on this for medical diagnosis. </div> </div> """ return html css = """ .gradio-container { max-width: 760px !important; } footer { display: none !important; } """ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo: gr.Markdown( "# ✨ AI Skin Care Advisor\n" "Upload a selfie for skin type analysis, honest advice, and product suggestions.\n" "This demo uses lightweight on-device heuristics (no heavy cloud model)." ) with gr.Row(): inp = gr.Image(type="pil", label="Upload a clear face photo") out = gr.HTML(label="Results") btn = gr.Button("Analyze", variant="primary") btn.click(analyze, inputs=inp, outputs=out) gr.Markdown( f"<div style='margin-top:8px;color:#94a3b8;font-size:12px'>" f"For original items, visit <a href='{SITE_URL}' target='_blank'>Daily Insights</a>.</div>" ) demo.launch()
b1cefd5 verified