Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import cv2
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
from facenet_pytorch import MTCNN
|
| 6 |
+
from transformers import pipeline
|
| 7 |
+
|
| 8 |
+
# 1) Initialize device, face detector, and HF pipelines
|
| 9 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 10 |
+
mtcnn = MTCNN(keep_all=True, device=device)
|
| 11 |
+
|
| 12 |
+
age_pipe = pipeline(
|
| 13 |
+
"image-classification",
|
| 14 |
+
model="nateraw/vit-age-classifier",
|
| 15 |
+
device=0 if device.type=="cuda" else -1
|
| 16 |
+
)
|
| 17 |
+
gender_pipe = pipeline(
|
| 18 |
+
"image-classification",
|
| 19 |
+
model="prithivMLmods/Gender-Classifier-Mini",
|
| 20 |
+
device=0 if device.type=="cuda" else -1
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# 2) Frame annotation function
|
| 24 |
+
def annotate(frame: np.ndarray) -> np.ndarray:
|
| 25 |
+
"""
|
| 26 |
+
Input: H×W×3 RGB frame as NumPy array
|
| 27 |
+
Output: same frame with boxes + age/gender labels drawn
|
| 28 |
+
"""
|
| 29 |
+
img = frame.copy()
|
| 30 |
+
boxes, _ = mtcnn.detect(img)
|
| 31 |
+
if boxes is not None:
|
| 32 |
+
for box in boxes:
|
| 33 |
+
x1, y1, x2, y2 = map(int, box)
|
| 34 |
+
face = img[y1:y2, x1:x2]
|
| 35 |
+
# HF pipelines accept NumPy RGB directly
|
| 36 |
+
age_pred = age_pipe(face)[0]
|
| 37 |
+
gender_pred = gender_pipe(face)[0]
|
| 38 |
+
label = (
|
| 39 |
+
f"{gender_pred['label']} {gender_pred['score']:.2f}, "
|
| 40 |
+
f"{age_pred['label']} {age_pred['score']:.2f}"
|
| 41 |
+
)
|
| 42 |
+
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
| 43 |
+
cv2.putText(
|
| 44 |
+
img, label, (x1, y1 - 10),
|
| 45 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2
|
| 46 |
+
)
|
| 47 |
+
return img
|
| 48 |
+
|
| 49 |
+
# 3) Build Gradio interface
|
| 50 |
+
iface = gr.Interface(
|
| 51 |
+
fn=annotate,
|
| 52 |
+
inputs=gr.Image(source="webcam", tool="editor", streaming=True),
|
| 53 |
+
outputs=gr.Image(type="numpy"),
|
| 54 |
+
title="Real-Time Age & Gender Prediction",
|
| 55 |
+
description=(
|
| 56 |
+
"Allow webcam access in your browser; faces will be boxed with age & gender labels."
|
| 57 |
+
),
|
| 58 |
+
live=True
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# 4) Launch for HF Spaces (no share=True needed)
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|