Spaces:
Running on Zero
Running on Zero
Fix black screen: Use native Gradio webcam streamer with live CAD overlay
Browse files164 unmodified lines165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610164 unmodified lines}# ------------------------------------------------------------------------------# FULLSCREEN REAL-TIME CLIENT INTERFACE (HTML5 + WebXR + Canvas HUD)# ------------------------------------------------------------------------------APP_HTML = """<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"><title>AR + HRNet Waistband Measurement</title><style>* { box-sizing: border-box; margin: 0; padding: 0; user-select: none; -webkit-user-select: none; }body, html { width: 100%; height: 100%; overflow: hidden; background: #000; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; color: #fff; }#container { position: relative; width: 100vw; height: 100vh; overflow: hidden; }video#camera { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; z-index: 1; }canvas#overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2; pointer-events: none; }/* Top HUD Badge */#top-hud {position: absolute;top: env(safe-area-inset-top, 16px);left: 12px;right: 12px;z-index: 10;display: flex;justify-content: space-between;align-items: center;gap: 8px;pointer-events: none;}.badge {background: rgba(11, 15, 25, 0.78);backdrop-filter: blur(10px);-webkit-backdrop-filter: blur(10px);border: 1px solid rgba(255, 255, 255, 0.15);border-radius: 999px;padding: 6px 14px;font-size: 13px;font-weight: 600;letter-spacing: 0.3px;display: flex;align-items: center;gap: 6px;}.badge-pulse {width: 8px;height: 8px;border-radius: 50%;background: #38bdf8;box-shadow: 0 0 10px #38bdf8;animation: blink 1.2s infinite ease-in-out;}@keyframes blink {0%, 100% { opacity: 0.3; transform: scale(0.85); }50% { opacity: 1; transform: scale(1.15); }}/* Bottom Measurement Card */#bottom-card {position: absolute;bottom: env(safe-area-inset-bottom, 20px);left: 16px;right: 16px;z-index: 10;background: linear-gradient(135deg, rgba(15, 23, 42, 0.92) 0%, rgba(30, 41, 59, 0.92) 100%);backdrop-filter: blur(16px);-webkit-backdrop-filter: blur(16px);border: 1.5px solid rgba(56, 189, 248, 0.4);border-radius: 20px;padding: 16px 20px;box-shadow: 0 12px 40px rgba(0, 0, 0, 0.6);pointer-events: auto;text-align: center;}.metric-label {font-size: 11px;font-weight: 700;text-transform: uppercase;letter-spacing: 1.5px;color: #38bdf8;margin-bottom: 2px;}.metric-value {font-size: 34px;font-weight: 800;color: #f8fafc;letter-spacing: -0.5px;line-height: 1.1;}.metric-sub {font-size: 14px;color: #94a3b8;font-weight: 600;margin-top: 4px;}.coords-row {display: flex;justify-content: space-around;margin-top: 10px;padding-top: 10px;border-top: 1px solid rgba(255, 255, 255, 0.1);font-size: 12px;color: #cbd5e1;font-family: ui-monospace, SFMono-Regular, Menlo, monospace;}.pt-label-1 { color: #38bdf8; font-weight: 700; }.pt-label-2 { color: #4ade80; font-weight: 700; }/* Permission / Error overlay */#perm-dialog {display: none;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);z-index: 50;background: #0f172a;border: 1px solid #38bdf8;border-radius: 16px;padding: 24px;text-align: center;max-width: 85%;}#perm-btn {margin-top: 16px;background: #0284c7;color: white;border: none;padding: 12px 24px;border-radius: 999px;font-size: 15px;font-weight: 700;cursor: pointer;}</style></head><body><div id="container"><!-- Fullscreen Rear Camera --><video id="camera" autoplay playsinline muted></video><!-- Canvas Overlay for Point 1, Point 2, and Line --><canvas id="overlay"></canvas><!-- Top HUD Status --><div id="top-hud"><div class="badge" id="ar-status-badge"><span class="badge-pulse"></span><span id="ar-status-text">Scanning AR Depth...</span></div><div class="badge" id="fps-badge">HRNet Active</div></div><!-- Bottom Real-time Measurement HUD --><div id="bottom-card"><div class="metric-label">Waistband Pixel Distance</div><div class="metric-value" id="pixel-val">-- px</div><div class="metric-sub" id="z-val">Z-Depth: Estimating...</div><div class="coords-row"><span><span class="pt-label-1">Point 1</span>: <span id="p1-coords">(--, --)</span></span><span><span class="pt-label-2">Point 2</span>: <span id="p2-coords">(--, --)</span></span></div></div><!-- Dialog for manual tap if autoplay blocked --><div id="perm-dialog"><h3 style="margin-bottom:8px;">Camera Access Needed</h3><p style="font-size:14px; color:#94a3b8;">Please allow access to your back camera to measure trousers.</p><button id="perm-btn" onclick="startCamera()">Open Back Camera</button></div></div><script>const video = document.getElementById('camera');const canvas = document.getElementById('overlay');const ctx = canvas.getContext('2d');const arStatusText = document.getElementById('ar-status-text');const pixelVal = document.getElementById('pixel-val');const zVal = document.getElementById('z-val');const p1Coords = document.getElementById('p1-coords');const p2Coords = document.getElementById('p2-coords');let offscreenCanvas = document.createElement('canvas');let offscreenCtx = offscreenCanvas.getContext('2d');let isPredicting = false;let latestKeypoints = null;let currentZDistanceCm = null;let xrDepthAvailable = false;// 1. Initialize Back Camera Immediatelyasync function startCamera() {document.getElementById('perm-dialog').style.display = 'none';try {const stream = await navigator.mediaDevices.getUserMedia({video: {facingMode: { ideal: "environment" },width: { ideal: 1280 },height: { ideal: 720 }},audio: false});video.srcObject = stream;video.onloadedmetadata = () => {video.play().catch(e => console.log('Autoplay deferred:', e));resizeCanvas();startInferenceLoop();};} catch (err) {console.error('Camera error:', err);document.getElementById('perm-dialog').style.display = 'block';}}// 2. Real AR Z-Distance via WebXR (if supported on Android ARCore / Chrome)async function probeRealARDepth() {if (!navigator.xr) {reportNoAR();return;}try {const supported = await navigator.xr.isSessionSupported('immersive-ar');if (!supported) {reportNoAR();return;}arStatusText.textContent = 'ARCore Depth Ready';} catch (e) {reportNoAR();}}function reportNoAR() {xrDepthAvailable = false;arStatusText.textContent = 'WebXR Depth Unavailable';zVal.textContent = 'Z-Depth: Unavailable (Requires WebXR/ARCore)';}function resizeCanvas() {canvas.width = window.innerWidth;canvas.height = window.innerHeight;}window.addEventListener('resize', resizeCanvas);// 3. Inference Loop: Capture frame -> Send to /predict_landmarks -> Receive (x1, y1) & (x2, y2)async function startInferenceLoop() {probeRealARDepth();requestAnimationFrame(renderLoop);setInterval(async () => {if (isPredicting || video.readyState < 2) return;isPredicting = true;try {const vw = video.videoWidth;const vh = video.videoHeight;if (!vw || !vh) { isPredicting = false; return; }const targetW = 640;const targetH = Math.round(vh * (targetW / vw));offscreenCanvas.width = targetW;offscreenCanvas.height = targetH;offscreenCtx.drawImage(video, 0, 0, targetW, targetH);const dataUrl = offscreenCanvas.toDataURL('image/jpeg', 0.75);const resp = await fetch('/predict_landmarks', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ image: dataUrl, orig_w: vw, orig_h: vh })});if (resp.ok) {const data = await resp.json();latestKeypoints = data;updateHUD(data);}} catch (err) {console.warn('Inference frame skipped:', err);} finally {isPredicting = false;}}, 280);}// 4. Update Bottom HUD Numbersfunction updateHUD(data) {if (!data || !data.point1 || !data.point2) return;pixelVal.textContent = `${data.pixel_distance} px`;p1Coords.textContent = `(${data.point1.x}, ${data.point1.y})`;p2Coords.textContent = `(${data.point2.x}, ${data.point2.y})`;if (data.z_distance_cm !== undefined && data.z_distance_cm !== null) {zVal.textContent = `Z-Distance: ${data.z_distance_cm.toFixed(1)} cm`;} else {zVal.textContent = 'Z-Depth: Unavailable (Requires WebXR/ARCore)';}}// 5. High-Performance Canvas HUD Renderer (Plots Point 1, Point 2, connecting line)function renderLoop() {ctx.clearRect(0, 0, canvas.width, canvas.height);if (latestKeypoints && latestKeypoints.point1 && latestKeypoints.point2 && video.videoWidth) {const p1 = latestKeypoints.point1;const p2 = latestKeypoints.point2;const vw = latestKeypoints.frame_width || video.videoWidth;const vh = latestKeypoints.frame_height || video.videoHeight;const screenW = canvas.width;const screenH = canvas.height;const scale = Math.max(screenW / vw, screenH / vh);const offsetX = (screenW - vw * scale) / 2;const offsetY = (screenH - vh * scale) / 2;const sx1 = p1.x * scale + offsetX;const sy1 = p1.y * scale + offsetY;const sx2 = p2.x * scale + offsetX;const sy2 = p2.y * scale + offsetY;// Draw straight dimension line connecting Point 1 and Point 2ctx.beginPath();ctx.moveTo(sx1, sy1);ctx.lineTo(sx2, sy2);ctx.lineWidth = 3.5;ctx.strokeStyle = '#ffffff';ctx.shadowColor = 'rgba(0,0,0,0.8)';ctx.shadowBlur = 8;ctx.stroke();// Draw Point 1: Cyan Pinpoint DotdrawDot(sx1, sy1, '#38bdf8', 'Point 1');// Draw Point 2: Green Pinpoint DotdrawDot(sx2, sy2, '#4ade80', 'Point 2');}requestAnimationFrame(renderLoop);}function drawDot(x, y, color, label) {// Outer glowing pulse ringctx.beginPath();ctx.arc(x, y, 14, 0, Math.PI * 2);ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';ctx.fill();// Solid target centerctx.beginPath();ctx.arc(x, y, 9, 0, Math.PI * 2);ctx.fillStyle = color;ctx.fill();ctx.lineWidth = 2.5;ctx.strokeStyle = '#ffffff';ctx.stroke();// Text label pillctx.font = 'bold 12px -apple-system, sans-serif';const textWidth = ctx.measureText(label).width;ctx.fillStyle = 'rgba(11, 15, 25, 0.85)';ctx.roundRect(x - textWidth / 2 - 6, y - 32, textWidth + 12, 20, 6);ctx.fill();ctx.strokeStyle = color;ctx.lineWidth = 1;ctx.stroke();ctx.fillStyle = '#ffffff';ctx.fillText(label, x - textWidth / 2, y - 18);}window.addEventListener('DOMContentLoaded', () => {startCamera();});</script></body></html>"""# ------------------------------------------------------------------------------# GRADIO APPLICATION WITH CUSTOM API ROUTE# ------------------------------------------------------------------------------with gr.Blocks(title="AR + HRNet Waistband Measurement", theme=gr.themes.Soft(primary_hue="sky")) as demo:gr.HTML(APP_HTML)app = demo.app@app.post("/predict_landmarks")async def predict_landmarks(req: Request):"""Lightweight JSON endpoint called by client viewfinder loop.Decodes frame, runs ZeroGPU HRNet model, returns Point 1 & Point 2."""try:body = await req.json()data_uri = body.get("image", "")if "," in data_uri:data_uri = data_uri.split(",", 1)[1]img_bytes = base64.b64decode(data_uri)nparr = np.frombuffer(img_bytes, np.uint8)img_bgr = cv2.imdecode(nparr, cv2.IMREAD_COLOR)if img_bgr is None:return JSONResponse({"error": "Invalid image payload"}, status_code=400)# Run HRNet inferenceres = run_hrnet_inference(img_bgr)res["z_distance_cm"] = Noneorig_w = body.get("orig_w")orig_h = body.get("orig_h")if orig_w and orig_h:curr_w = res["frame_width"]curr_h = res["frame_height"]scale_x = float(orig_w) / float(curr_w)scale_y = float(orig_h) / float(curr_h)res["point1"]["x"] = int(round(res["point1"]["x"] * scale_x))res["point1"]["y"] = int(round(res["point1"]["y"] * scale_y))res["point2"]["x"] = int(round(res["point2"]["x"] * scale_x))res["point2"]["y"] = int(round(res["point2"]["y"] * scale_y))res["frame_width"] = orig_wres["frame_height"] = orig_hres["pixel_distance"] = round(math.hypot(res["point2"]["x"] - res["point1"]["x"],res["point2"]["y"] - res["point1"]["y"]), 1)return JSONResponse(res)except Exception as e:print(f"Error in predict_landmarks: {e}", flush=True)return JSONResponse({"error": str(e)}, status_code=500)if __name__ == "__main__":demo.queue().launch()164 unmodified lines165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343164 unmodified lines}# ==============================================================================# 2. STREAMING AR MEASUREMENT PIPELINE (ZEROGPU ACCELERATED)# ==============================================================================def draw_ar_measurement_overlay(img, p1, p2, pc, pixel_dist):"""Renders live CAD dimension overlay:- Point 1 (Cyan) and Point 2 (Green) auto-plotted by HRNet- Straight dimension line connecting Point 1 and Point 2- HUD showing Euclidean pixel distance and coordinates"""draw = img.copy()H, W = draw.shape[:2]scale = max(1.0, min(W, H) / 750.0)line_thick = max(2, int(round(3.0 * scale)))font_scale = max(0.65, 0.75 * scale)pt_radius = max(7, int(round(9.0 * scale)))text_thick = max(1, int(2.0 * scale))font = cv2.FONT_HERSHEY_SIMPLEX# 1. Straight dimension line connecting Point 1 and Point 2cv2.line(draw, p1, p2, (255, 255, 255), line_thick, cv2.LINE_AA)# Waistband curve line via centercv2.line(draw, p1, pc, (56, 189, 248), max(1, int(line_thick * 0.7)), cv2.LINE_AA)cv2.line(draw, pc, p2, (56, 189, 248), max(1, int(line_thick * 0.7)), cv2.LINE_AA)# 2. Pinpoint Circlesdef draw_pinpoint(pt, color):cv2.circle(draw, pt, pt_radius + int(4 * scale), (255, 255, 255), 2, cv2.LINE_AA)cv2.circle(draw, pt, pt_radius, color, -1, cv2.LINE_AA)draw_pinpoint(p1, (56, 189, 248)) # Point 1: Cyandraw_pinpoint(p2, (74, 222, 128)) # Point 2: Greendraw_pinpoint(pc, (251, 191, 36)) # Center: Amber# 3. Badges on pointsdef draw_badge(text, pt, color, offset_y=-24):t_size, _ = cv2.getTextSize(text, font, font_scale * 0.7, text_thick)tx = max(8, min(W - t_size[0] - 8, int(pt[0] - t_size[0] / 2)))ty = max(t_size[1] + 8, min(H - 8, int(pt[1] + offset_y * scale)))pad = int(5 * scale)cv2.rectangle(draw, (tx - pad, ty - t_size[1] - pad), (tx + t_size[0] + pad, ty + pad), (11, 15, 25), -1)cv2.rectangle(draw, (tx - pad, ty - t_size[1] - pad), (tx + t_size[0] + pad, ty + pad), color, 1)cv2.putText(draw, text, (tx, ty), font, font_scale * 0.7, (255, 255, 255), text_thick, cv2.LINE_AA)draw_badge(f"Point 1 ({p1[0]},{p1[1]})", p1, (56, 189, 248), offset_y=-24)draw_badge(f"Point 2 ({p2[0]},{p2[1]})", p2, (74, 222, 128), offset_y=-24)# 4. Central Callout Boxmid_x = int((p1[0] + p2[0]) / 2)mid_y = int((p1[1] + p2[1]) / 2) - int(36 * scale)if mid_y < 50:mid_y = int((p1[1] + p2[1]) / 2) + int(50 * scale)hud_main = f"{int(round(pixel_dist))} px"hud_sub = f"P1:({p1[0]},{p1[1]}) -> P2:({p2[0]},{p2[1]})"s1, _ = cv2.getTextSize(hud_main, font, font_scale * 0.85, text_thick)s2, _ = cv2.getTextSize(hud_sub, font, font_scale * 0.65, text_thick)box_w = max(s1[0], s2[0]) + int(24 * scale)box_h = s1[1] + s2[1] + int(24 * scale)bx1 = max(4, mid_x - box_w // 2)by1 = max(4, mid_y - box_h // 2)bx2 = min(W - 4, bx1 + box_w)by2 = min(H - 4, by1 + box_h)cv2.rectangle(draw, (bx1, by1), (bx2, by2), (11, 15, 25), -1)cv2.rectangle(draw, (bx1, by1), (bx2, by2), (56, 189, 248), 2)tx1 = bx1 + int(12 * scale)ty1 = by1 + s1[1] + int(8 * scale)cv2.putText(draw, hud_main, (tx1, ty1), font, font_scale * 0.85, (255, 255, 255), text_thick, cv2.LINE_AA)tx2 = bx1 + int(12 * scale)ty2 = ty1 + s2[1] + int(8 * scale)cv2.putText(draw, hud_sub, (tx2, ty2), font, font_scale * 0.65, (56, 189, 248), text_thick, cv2.LINE_AA)return draw@spaces.GPUdef process_live_stream(frame):"""Called on each camera frame from webcam or uploaded photo.Extracts Point 1 & Point 2 using HRNet and auto-plots the CAD overlay."""if frame is None:return None, "<div style='color:#94a3b8; text-align:center;'>Open camera or upload pant photo to start.</div>"img_rgb = np.array(frame)img_bgr = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)res = run_hrnet_inference(img_bgr)p1 = (res["point1"]["x"], res["point1"]["y"])p2 = (res["point2"]["x"], res["point2"]["y"])pc = (res["center"]["x"], res["center"]["y"])px_dist = res["pixel_distance"]annotated_bgr = draw_ar_measurement_overlay(img_bgr, p1, p2, pc, px_dist)annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)info_card = f"""<div style="background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); border: 1.5px solid #38bdf8; border-radius: 16px; padding: 18px; color: white; text-align: center;"><div style="font-size: 0.8rem; font-weight: 700; text-transform: uppercase; letter-spacing: 2px; color: #38bdf8;">Waistband Pixel Distance</div><div style="font-size: 2.8rem; font-weight: 800; color: #f8fafc; margin: 4px 0;">{px_dist:.1f} px</div><div style="font-size: 0.95rem; color: #94a3b8; margin-bottom: 8px;"><span style="color:#f59e0b; font-weight:600;">Z-Depth:</span> Unavailable (Requires WebXR/ARCore)</div><div style="display: flex; justify-content: space-around; margin-top: 10px; padding-top: 10px; border-top: 1px solid rgba(255,255,255,0.1); font-size: 0.85rem; font-family: monospace;"><span style="color:#38bdf8; font-weight:bold;">Point 1: ({p1[0]}, {p1[1]}) [conf: {res['point1']['confidence']}]</span><span style="color:#4ade80; font-weight:bold;">Point 2: ({p2[0]}, {p2[1]}) [conf: {res['point2']['confidence']}]</span></div></div>"""return annotated_rgb, info_card# ------------------------------------------------------------------------------# GRADIO APPLICATION# ------------------------------------------------------------------------------custom_css = """body, .gradio-container {background-color: #0b0f19 !important;color: #f8fafc !important;}.gradio-container {max-width: 1200px !important;}"""with gr.Blocks(title="AR + HRNet Waistband Measurement", css=custom_css, theme=gr.themes.Soft(primary_hue="sky")) as demo:gr.HTML("""<div style="text-align: center; padding: 16px 10px 10px 10px;"><h1 style="font-size: 2rem; font-weight: 800; background: linear-gradient(135deg, #38bdf8, #818cf8); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 4px;">AR + HRNet Waistband Measurement</h1><p style="color: #94a3b8; font-size: 0.95rem;">Auto-plots Point 1 (Left Waist) & Point 2 (Right Waist) directly on the video • Real-time pixel distance</p></div>""")with gr.Row():with gr.Column(scale=1):camera_in = gr.Image(sources=["webcam", "upload"],streaming=True,label="Camera Viewfinder (Click Webcam to start)",type="numpy")with gr.Column(scale=1):overlay_out = gr.Image(label="Live CAD Measurement (Point 1 ↔ Point 2 Auto-Plotted)",interactive=False)stats_out = gr.HTML("<div style='text-align:center; color:#94a3b8; padding:12px;'>Waiting for camera feed...</div>")# Connect streaming video loopcamera_in.stream(fn=process_live_stream,inputs=camera_in,outputs=[overlay_out, stats_out],stream_every=0.3)camera_in.change(fn=process_live_stream,inputs=camera_in,outputs=[overlay_out, stats_out])if __name__ == "__main__":demo.queue().launch()
app.py+164-431