Spaces:
Running
Running
Upload 3 files
Browse files123234563 unmodified lines10111213131415151617181920171822192021222324242526272829303132333435363738394041424344454647484950512526---title: FaceSense Live Phase 1emoji: 🧠title: FaceSense Liveemoji: 🚀colorFrom: bluecolorTo: greensdk: gradio3 unmodified lineslicense: mit---
# FaceSense Live — Phase 1# FaceSense Live
This phase validates the live web app loop:Phase 1 validates live webcam processing on Hugging Face Spaces.
1. Browser webcam input2. Server-side frame processing3. Live face bounding boxes4. A polished Gradio UI for Hugging Face Spaces## How to use
Prediction models are intentionally not included yet. After Phase 1 is working, Phase 2 will add expression classification and confidence smoothing.1. Open the Space.2. Allow camera permission.3. Click **Record** in the webcam panel.4. Keep your face centered and well lit.5. The annotated output should update with face bounding boxes.
## Local run
```bashpython -m venv .venvsource .venv/bin/activate # Windows: .venv\Scripts\activatepip install -r requirements.txtpython app.py```
## Hugging Face Space deployment
Create a new Hugging Face Space using the Gradio SDK, then upload these files:
- `app.py`- `requirements.txt`- `README.md`
After the Space builds, open it and click the webcam recording button. On phones, allow camera permission; your browser may offer front/rear camera selection depending on iOS Safari or Android Chrome.
## Test checklist
- The app opens without build errors.- The browser asks for webcam permission.- The webcam stream starts on desktop.- The webcam opens on a phone browser.- Front/rear camera selection is available from the browser camera picker when supported.- A green/cyan face bounding box appears around a frontal face.- The live status card updates with face count and processing time.On mobile, the browser controls camera permission and may allow switching between front and rear cameras.A later phase can add a custom WebRTC frontend if a dedicated in-app front/rear toggle is required.122345678910118913141516171819202122232425262728293031323334353637383940414243441011121314151617181920212223242526272829303132333435363738394041424344454647484647484950515251525354555657585354555657586061625960616263646566676869706465666771727374697071727574757676777879808182838485867980818788838990919288939495969293949596979899100101102103104105106107108109110111112113114115116117979899100101102122123124125126127128129130131132133134103104105106107108109110136137138139140141142143144145146111112113114115116117118119120121150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265122123124125126127128129130131132133134135136137138139140141142143144268145import timefrom typing import List, Tuplefrom typing import Optional, Tuple
import cv2import gradio as grimport numpy as np
# ------------------------------------------------------------# Phase 1: live webcam -> face bounding boxes -> beautiful UI# The emotion / age / demographic inference modules will be added later.# ------------------------------------------------------------FACE_CASCADE = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
CASCADE_PATH = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"FACE_CASCADE = cv2.CascadeClassifier(CASCADE_PATH)
APP_TITLE = "FaceSense Live"APP_SUBTITLE = "Real-time face boxes for desktop and mobile webcam testing"
def _draw_corner_box( image: np.ndarray, x: int, y: int, w: int, h: int, color: Tuple[int, int, int] = (52, 235, 186), thickness: int = 3, corner_ratio: float = 0.28,) -> None: """Draw a modern corner-style bounding box directly on an RGB image.""" corner_w = max(18, int(w * corner_ratio)) corner_h = max(18, int(h * corner_ratio))
# Top-left cv2.line(image, (x, y), (x + corner_w, y), color, thickness, cv2.LINE_AA) cv2.line(image, (x, y), (x, y + corner_h), color, thickness, cv2.LINE_AA)
# Top-right cv2.line(image, (x + w, y), (x + w - corner_w, y), color, thickness, cv2.LINE_AA) cv2.line(image, (x + w, y), (x + w, y + corner_h), color, thickness, cv2.LINE_AA)
# Bottom-left cv2.line(image, (x, y + h), (x + corner_w, y + h), color, thickness, cv2.LINE_AA) cv2.line(image, (x, y + h), (x, y + h - corner_h), color, thickness, cv2.LINE_AA)CUSTOM_CSS = """:root { --radius-xl: 22px; }.gradio-container { max-width: 1500px !important; margin: auto !important; background: radial-gradient(circle at 15% 15%, rgba(38, 166, 191, .22), transparent 30%), linear-gradient(135deg, #101827 0%, #273142 48%, #10232b 100%) !important; color: #eef6ff !important;}#component-0, .contain, .block, .panel { border-radius: var(--radius-xl) !important;}.prose h1, h1 { font-size: clamp(2.2rem, 5vw, 4.4rem) !important; text-align: center !important; letter-spacing: -0.04em !important;}.prose p, .prose li { color: #c9d6e8 !important; }label, .label-wrap span { font-weight: 800 !important; }button { border-radius: 999px !important; font-weight: 800 !important;}.image-container, .wrap, .block { overflow: hidden !important;}#status_box textarea, #status_box .prose { font-size: 1.05rem !important;}@media (max-width: 760px) { .gradio-container { padding: 8px !important; } h1 { font-size: 2.35rem !important; } .image-container img, .image-container video { max-height: 62vh !important; object-fit: contain !important; }}"""
# Bottom-right cv2.line(image, (x + w, y + h), (x + w - corner_w, y + h), color, thickness, cv2.LINE_AA) cv2.line(image, (x + w, y + h), (x + w, y + h - corner_h), color, thickness, cv2.LINE_AA)HEADER = """# FaceSense LiveReal-time face boxes for desktop and mobile webcam testing. Click **Record** on the camera panel to start live analysis. On phones, allow camera permission; your browser may offer front/rear camera selection."""
def _draw_label(image: np.ndarray, x: int, y: int, lines: List[str]) -> None: """Draw a translucent label card above a face box.""" font = cv2.FONT_HERSHEY_SIMPLEX font_scale = 0.55 thickness = 1 padding_x = 10 padding_y = 8 line_height = 21def draw_corner_box(img: np.ndarray, x: int, y: int, w: int, h: int) -> None: color = (0, 238, 255) shadow = (6, 18, 28) thickness = 4 line = max(18, int(min(w, h) * 0.22))
widths = [cv2.getTextSize(line, font, font_scale, thickness)[0][0] for line in lines] card_w = max(widths) + padding_x * 2 card_h = line_height * len(lines) + padding_y * 2 # shadow first for readability cv2.rectangle(img, (x, y), (x + w, y + h), shadow, 7) # corner style box cv2.line(img, (x, y), (x + line, y), color, thickness) cv2.line(img, (x, y), (x, y + line), color, thickness) cv2.line(img, (x + w, y), (x + w - line, y), color, thickness) cv2.line(img, (x + w, y), (x + w, y + line), color, thickness) cv2.line(img, (x, y + h), (x + line, y + h), color, thickness) cv2.line(img, (x, y + h), (x, y + h - line), color, thickness) cv2.line(img, (x + w, y + h), (x + w - line, y + h), color, thickness) cv2.line(img, (x + w, y + h), (x + w, y + h - line), color, thickness)
y1 = max(8, y - card_h - 10) x1 = max(8, min(x, image.shape[1] - card_w - 8)) x2 = min(image.shape[1] - 8, x1 + card_w) y2 = min(image.shape[0] - 8, y1 + card_h) label = "Face detected" cv2.rectangle(img, (x, max(0, y - 38)), (x + 185, y), (0, 145, 175), -1) cv2.putText(img, label, (x + 10, max(22, y - 12)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
overlay = image.copy() cv2.rectangle(overlay, (x1, y1), (x2, y2), (14, 18, 31), -1) cv2.addWeighted(overlay, 0.72, image, 0.28, 0, image) cv2.rectangle(image, (x1, y1), (x2, y2), (52, 235, 186), 1, cv2.LINE_AA)
for i, line in enumerate(lines): text_y = y1 + padding_y + 16 + i * line_height cv2.putText(image, line, (x1 + padding_x, text_y), font, font_scale, (242, 250, 255), thickness, cv2.LINE_AA)def process_frame(frame: Optional[np.ndarray]) -> Tuple[Optional[np.ndarray], str]: start = time.perf_counter() if frame is None: return None, "### Waiting for camera\nClick **Record** on the webcam panel to start live analysis."
output = frame.copy() if output.ndim == 2: output = cv2.cvtColor(output, cv2.COLOR_GRAY2RGB) if output.shape[-1] == 4: output = cv2.cvtColor(output, cv2.COLOR_RGBA2RGB)
def _detect_faces(frame_rgb: np.ndarray) -> List[Tuple[int, int, int, int]]: """Detect frontal faces with OpenCV's built-in Haar cascade.""" gray = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2GRAY) gray = cv2.cvtColor(output, cv2.COLOR_RGB2GRAY) gray = cv2.equalizeHist(gray)
faces = FACE_CASCADE.detectMultiScale( gray, scaleFactor=1.08, minNeighbors=5, minSize=(70, 70), minSize=(55, 55), flags=cv2.CASCADE_SCALE_IMAGE, )
# Largest faces first makes the UI feel stable when several faces exist. faces_list = [(int(x), int(y), int(w), int(h)) for x, y, w, h in faces] return sorted(faces_list, key=lambda b: b[2] * b[3], reverse=True)
def analyze_frame(frame: np.ndarray): """Process one webcam frame. Gradio calls this repeatedly while streaming.""" if frame is None: return None, "### Waiting for camera\nClick **Record from webcam** to start Phase 1."
start = time.perf_counter() output = frame.copy() faces = _detect_faces(output)
for idx, (x, y, w, h) in enumerate(faces, start=1): _draw_corner_box(output, x, y, w, h) _draw_label( output, x, y, [ f"Face {idx}", "Expression: Phase 2", "Age range: Phase 3", ], ) for (x, y, w, h) in faces: draw_corner_box(output, int(x), int(y), int(w), int(h))
elapsed_ms = (time.perf_counter() - start) * 1000 fps = 1000 / elapsed_ms if elapsed_ms > 0 else 0
if faces: status = f"""### Live status
<div class='metric-grid'> <div class='metric-card'><span class='metric-number'>{len(faces)}</span><span class='metric-label'>face(s) detected</span></div> <div class='metric-card'><span class='metric-number'>{elapsed_ms:.1f} ms</span><span class='metric-label'>processing time</span></div> <div class='metric-card'><span class='metric-number'>{fps:.1f}</span><span class='metric-label'>estimated FPS</span></div></div>
**Phase 1 result:** webcam streaming and bounding boxes are active. **Next:** add expression model, smoothing, and calibrated confidence labels.""" if len(faces) == 0: status = ( "### Live status\n" "No frontal face detected yet. Move your face toward the center, improve lighting, and keep the camera steady.\n\n" f"**Processing:** {elapsed_ms:.1f} ms \n" f"**Approx FPS:** {fps:.1f}" ) else: status = f"""### Live status
<div class='metric-grid'> <div class='metric-card'><span class='metric-number'>0</span><span class='metric-label'>faces detected</span></div> <div class='metric-card'><span class='metric-number'>{elapsed_ms:.1f} ms</span><span class='metric-label'>processing time</span></div></div>
Move closer to the camera, face the lens, and use decent lighting. Phase 1 uses a lightweight detector so we can confirm deployment first."""
status = ( "### Live status\n" f"**Faces detected:** {len(faces)} \n" "**Phase 1:** bounding boxes only \n" "**Next phase:** facial expression + apparent age range + optional presentation estimate \n\n" f"**Processing:** {elapsed_ms:.1f} ms \n" f"**Approx FPS:** {fps:.1f}" ) return output, status
CUSTOM_CSS = """.gradio-container { background: radial-gradient(circle at top left, rgba(72, 219, 251, 0.22), transparent 34%), radial-gradient(circle at bottom right, rgba(163, 255, 181, 0.16), transparent 34%), linear-gradient(135deg, #070b16 0%, #111827 45%, #0b1020 100%) !important; color: #f8fafc !important;}.hero { text-align: center; padding: 24px 20px 10px 20px;}.hero h1 { font-size: 3rem; line-height: 1.05; margin-bottom: 8px; letter-spacing: -0.04em;}.hero p { color: #cbd5e1; font-size: 1.05rem; margin: 0 auto; max-width: 760px;}.panel { border: 1px solid rgba(148, 163, 184, 0.24) !important; border-radius: 22px !important; background: rgba(15, 23, 42, 0.74) !important; box-shadow: 0 18px 70px rgba(0, 0, 0, 0.38) !important; backdrop-filter: blur(18px) !important; overflow: hidden !important;}.metric-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 12px; margin: 12px 0 16px;}.metric-card { padding: 14px; border-radius: 16px; background: rgba(15, 23, 42, 0.78); border: 1px solid rgba(72, 219, 251, 0.28);}.metric-number { display: block; font-size: 1.4rem; font-weight: 800; color: #7dd3fc;}.metric-label { display: block; color: #cbd5e1; font-size: 0.82rem; margin-top: 2px;}.footer-note { text-align: center; color: #94a3b8; font-size: 0.92rem; padding: 12px 0 4px;}"""
with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="cyan", neutral_hue="slate")) as demo: gr.HTML( f""" <div class='hero'> <h1>{APP_TITLE}</h1> <p>{APP_SUBTITLE}</p> </div> """ )
with gr.Row(equal_height=True): with gr.Column(scale=1, elem_classes=["panel"]): webcam = gr.Image( label="Camera input", sources=["webcam"], type="numpy", streaming=True, height=520, show_download_button=False, ) with gr.Column(scale=1, elem_classes=["panel"]): annotated = gr.Image( label="Annotated output", type="numpy", height=520, show_download_button=False, )
with gr.Row(): with gr.Column(elem_classes=["panel"]): status = gr.Markdown( "### Waiting for camera\nClick **Record from webcam** to start Phase 1.", elem_id="status-card", )
gr.HTML( """ <div class='footer-note'> Phase 1 validates live webcam processing and deployment. On mobile, allow camera permission; your browser may offer front/rear camera selection. </div> """ )
# Using change() with a streaming webcam is more stable on Spaces than stream() for this Phase 1 build. # The webcam component still captures repeated frames while recording, and every changed frame is analyzed. webcam.change( analyze_frame, inputs=webcam, outputs=[annotated, status], queue=False, show_progress="hidden", )demo = gr.Interface( fn=process_frame, inputs=gr.Image( label="Camera input", sources=["webcam"], type="numpy", streaming=True, mirror_webcam=True, height=520, ), outputs=[ gr.Image(label="Annotated output", type="numpy", height=520), gr.Markdown(label="Status"), ], title="FaceSense Live", description=HEADER, live=True, css=CUSTOM_CSS, allow_flagging="never", api_name="predict",)
if __name__ == "__main__": demo.launch() demo.queue(default_concurrency_limit=4).launch()README.md+12-37
app.py+111-234