Solar-Prince commited on
Commit
7fd00f2
·
verified ·
1 Parent(s): a02f1ff

Upload 3 files

Browse files
Files changed (2) hide show
  1. README.md +12 -37
  2. app.py +111 -234
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
- title: FaceSense Live Phase 1
3
- emoji: 🧠
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: gradio
@@ -10,42 +10,17 @@ pinned: false
10
  license: mit
11
  ---
12
 
13
- # FaceSense Live — Phase 1
14
 
15
- This phase validates the live web app loop:
16
 
17
- 1. Browser webcam input
18
- 2. Server-side frame processing
19
- 3. Live face bounding boxes
20
- 4. A polished Gradio UI for Hugging Face Spaces
21
 
22
- Prediction models are intentionally not included yet. After Phase 1 is working, Phase 2 will add expression classification and confidence smoothing.
 
 
 
 
23
 
24
- ## Local run
25
-
26
- ```bash
27
- python -m venv .venv
28
- source .venv/bin/activate # Windows: .venv\Scripts\activate
29
- pip install -r requirements.txt
30
- python app.py
31
- ```
32
-
33
- ## Hugging Face Space deployment
34
-
35
- Create a new Hugging Face Space using the Gradio SDK, then upload these files:
36
-
37
- - `app.py`
38
- - `requirements.txt`
39
- - `README.md`
40
-
41
- 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.
42
-
43
- ## Test checklist
44
-
45
- - The app opens without build errors.
46
- - The browser asks for webcam permission.
47
- - The webcam stream starts on desktop.
48
- - The webcam opens on a phone browser.
49
- - Front/rear camera selection is available from the browser camera picker when supported.
50
- - A green/cyan face bounding box appears around a frontal face.
51
- - The live status card updates with face count and processing time.
 
1
  ---
2
+ title: FaceSense Live
3
+ emoji: 🚀
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: gradio
 
10
  license: mit
11
  ---
12
 
13
+ # FaceSense Live
14
 
15
+ Phase 1 validates live webcam processing on Hugging Face Spaces.
16
 
17
+ ## How to use
 
 
 
18
 
19
+ 1. Open the Space.
20
+ 2. Allow camera permission.
21
+ 3. Click **Record** in the webcam panel.
22
+ 4. Keep your face centered and well lit.
23
+ 5. The annotated output should update with face bounding boxes.
24
 
25
+ On mobile, the browser controls camera permission and may allow switching between front and rear cameras.
26
+ A later phase can add a custom WebRTC frontend if a dedicated in-app front/rear toggle is required.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,268 +1,145 @@
1
  import time
2
- from typing import List, Tuple
3
 
4
  import cv2
5
  import gradio as gr
6
  import numpy as np
7
 
8
- # ------------------------------------------------------------
9
- # Phase 1: live webcam -> face bounding boxes -> beautiful UI
10
- # The emotion / age / demographic inference modules will be added later.
11
- # ------------------------------------------------------------
12
 
13
- CASCADE_PATH = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
14
- FACE_CASCADE = cv2.CascadeClassifier(CASCADE_PATH)
15
-
16
- APP_TITLE = "FaceSense Live"
17
- APP_SUBTITLE = "Real-time face boxes for desktop and mobile webcam testing"
18
-
19
-
20
- def _draw_corner_box(
21
- image: np.ndarray,
22
- x: int,
23
- y: int,
24
- w: int,
25
- h: int,
26
- color: Tuple[int, int, int] = (52, 235, 186),
27
- thickness: int = 3,
28
- corner_ratio: float = 0.28,
29
- ) -> None:
30
- """Draw a modern corner-style bounding box directly on an RGB image."""
31
- corner_w = max(18, int(w * corner_ratio))
32
- corner_h = max(18, int(h * corner_ratio))
33
-
34
- # Top-left
35
- cv2.line(image, (x, y), (x + corner_w, y), color, thickness, cv2.LINE_AA)
36
- cv2.line(image, (x, y), (x, y + corner_h), color, thickness, cv2.LINE_AA)
37
-
38
- # Top-right
39
- cv2.line(image, (x + w, y), (x + w - corner_w, y), color, thickness, cv2.LINE_AA)
40
- cv2.line(image, (x + w, y), (x + w, y + corner_h), color, thickness, cv2.LINE_AA)
41
-
42
- # Bottom-left
43
- cv2.line(image, (x, y + h), (x + corner_w, y + h), color, thickness, cv2.LINE_AA)
44
- cv2.line(image, (x, y + h), (x, y + h - corner_h), color, thickness, cv2.LINE_AA)
 
 
 
45
 
46
- # Bottom-right
47
- cv2.line(image, (x + w, y + h), (x + w - corner_w, y + h), color, thickness, cv2.LINE_AA)
48
- cv2.line(image, (x + w, y + h), (x + w, y + h - corner_h), color, thickness, cv2.LINE_AA)
 
 
49
 
50
 
51
- def _draw_label(image: np.ndarray, x: int, y: int, lines: List[str]) -> None:
52
- """Draw a translucent label card above a face box."""
53
- font = cv2.FONT_HERSHEY_SIMPLEX
54
- font_scale = 0.55
55
- thickness = 1
56
- padding_x = 10
57
- padding_y = 8
58
- line_height = 21
59
 
60
- widths = [cv2.getTextSize(line, font, font_scale, thickness)[0][0] for line in lines]
61
- card_w = max(widths) + padding_x * 2
62
- card_h = line_height * len(lines) + padding_y * 2
 
 
 
 
 
 
 
 
63
 
64
- y1 = max(8, y - card_h - 10)
65
- x1 = max(8, min(x, image.shape[1] - card_w - 8))
66
- x2 = min(image.shape[1] - 8, x1 + card_w)
67
- y2 = min(image.shape[0] - 8, y1 + card_h)
68
 
69
- overlay = image.copy()
70
- cv2.rectangle(overlay, (x1, y1), (x2, y2), (14, 18, 31), -1)
71
- cv2.addWeighted(overlay, 0.72, image, 0.28, 0, image)
72
- cv2.rectangle(image, (x1, y1), (x2, y2), (52, 235, 186), 1, cv2.LINE_AA)
73
 
74
- for i, line in enumerate(lines):
75
- text_y = y1 + padding_y + 16 + i * line_height
76
- cv2.putText(image, line, (x1 + padding_x, text_y), font, font_scale, (242, 250, 255), thickness, cv2.LINE_AA)
 
77
 
 
 
 
 
 
78
 
79
- def _detect_faces(frame_rgb: np.ndarray) -> List[Tuple[int, int, int, int]]:
80
- """Detect frontal faces with OpenCV's built-in Haar cascade."""
81
- gray = cv2.cvtColor(frame_rgb, cv2.COLOR_RGB2GRAY)
82
  gray = cv2.equalizeHist(gray)
83
-
84
  faces = FACE_CASCADE.detectMultiScale(
85
  gray,
86
  scaleFactor=1.08,
87
  minNeighbors=5,
88
- minSize=(70, 70),
89
  flags=cv2.CASCADE_SCALE_IMAGE,
90
  )
91
 
92
- # Largest faces first makes the UI feel stable when several faces exist.
93
- faces_list = [(int(x), int(y), int(w), int(h)) for x, y, w, h in faces]
94
- return sorted(faces_list, key=lambda b: b[2] * b[3], reverse=True)
95
-
96
-
97
- def analyze_frame(frame: np.ndarray):
98
- """Process one webcam frame. Gradio calls this repeatedly while streaming."""
99
- if frame is None:
100
- return None, "### Waiting for camera\nClick **Record from webcam** to start Phase 1."
101
-
102
- start = time.perf_counter()
103
- output = frame.copy()
104
- faces = _detect_faces(output)
105
-
106
- for idx, (x, y, w, h) in enumerate(faces, start=1):
107
- _draw_corner_box(output, x, y, w, h)
108
- _draw_label(
109
- output,
110
- x,
111
- y,
112
- [
113
- f"Face {idx}",
114
- "Expression: Phase 2",
115
- "Age range: Phase 3",
116
- ],
117
- )
118
 
119
  elapsed_ms = (time.perf_counter() - start) * 1000
120
  fps = 1000 / elapsed_ms if elapsed_ms > 0 else 0
121
 
122
- if faces:
123
- status = f"""
124
- ### Live status
125
-
126
- <div class='metric-grid'>
127
- <div class='metric-card'><span class='metric-number'>{len(faces)}</span><span class='metric-label'>face(s) detected</span></div>
128
- <div class='metric-card'><span class='metric-number'>{elapsed_ms:.1f} ms</span><span class='metric-label'>processing time</span></div>
129
- <div class='metric-card'><span class='metric-number'>{fps:.1f}</span><span class='metric-label'>estimated FPS</span></div>
130
- </div>
131
-
132
- **Phase 1 result:** webcam streaming and bounding boxes are active.
133
- **Next:** add expression model, smoothing, and calibrated confidence labels.
134
- """
135
  else:
136
- status = f"""
137
- ### Live status
138
-
139
- <div class='metric-grid'>
140
- <div class='metric-card'><span class='metric-number'>0</span><span class='metric-label'>faces detected</span></div>
141
- <div class='metric-card'><span class='metric-number'>{elapsed_ms:.1f} ms</span><span class='metric-label'>processing time</span></div>
142
- </div>
143
-
144
- Move closer to the camera, face the lens, and use decent lighting. Phase 1 uses a lightweight detector so we can confirm deployment first.
145
- """
146
-
147
  return output, status
148
 
149
 
150
- CUSTOM_CSS = """
151
- .gradio-container {
152
- background:
153
- radial-gradient(circle at top left, rgba(72, 219, 251, 0.22), transparent 34%),
154
- radial-gradient(circle at bottom right, rgba(163, 255, 181, 0.16), transparent 34%),
155
- linear-gradient(135deg, #070b16 0%, #111827 45%, #0b1020 100%) !important;
156
- color: #f8fafc !important;
157
- }
158
- .hero {
159
- text-align: center;
160
- padding: 24px 20px 10px 20px;
161
- }
162
- .hero h1 {
163
- font-size: 3rem;
164
- line-height: 1.05;
165
- margin-bottom: 8px;
166
- letter-spacing: -0.04em;
167
- }
168
- .hero p {
169
- color: #cbd5e1;
170
- font-size: 1.05rem;
171
- margin: 0 auto;
172
- max-width: 760px;
173
- }
174
- .panel {
175
- border: 1px solid rgba(148, 163, 184, 0.24) !important;
176
- border-radius: 22px !important;
177
- background: rgba(15, 23, 42, 0.74) !important;
178
- box-shadow: 0 18px 70px rgba(0, 0, 0, 0.38) !important;
179
- backdrop-filter: blur(18px) !important;
180
- overflow: hidden !important;
181
- }
182
- .metric-grid {
183
- display: grid;
184
- grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
185
- gap: 12px;
186
- margin: 12px 0 16px;
187
- }
188
- .metric-card {
189
- padding: 14px;
190
- border-radius: 16px;
191
- background: rgba(15, 23, 42, 0.78);
192
- border: 1px solid rgba(72, 219, 251, 0.28);
193
- }
194
- .metric-number {
195
- display: block;
196
- font-size: 1.4rem;
197
- font-weight: 800;
198
- color: #7dd3fc;
199
- }
200
- .metric-label {
201
- display: block;
202
- color: #cbd5e1;
203
- font-size: 0.82rem;
204
- margin-top: 2px;
205
- }
206
- .footer-note {
207
- text-align: center;
208
- color: #94a3b8;
209
- font-size: 0.92rem;
210
- padding: 12px 0 4px;
211
- }
212
- """
213
-
214
- with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="cyan", neutral_hue="slate")) as demo:
215
- gr.HTML(
216
- f"""
217
- <div class='hero'>
218
- <h1>{APP_TITLE}</h1>
219
- <p>{APP_SUBTITLE}</p>
220
- </div>
221
- """
222
- )
223
-
224
- with gr.Row(equal_height=True):
225
- with gr.Column(scale=1, elem_classes=["panel"]):
226
- webcam = gr.Image(
227
- label="Camera input",
228
- sources=["webcam"],
229
- type="numpy",
230
- streaming=True,
231
- height=520,
232
- show_download_button=False,
233
- )
234
- with gr.Column(scale=1, elem_classes=["panel"]):
235
- annotated = gr.Image(
236
- label="Annotated output",
237
- type="numpy",
238
- height=520,
239
- show_download_button=False,
240
- )
241
-
242
- with gr.Row():
243
- with gr.Column(elem_classes=["panel"]):
244
- status = gr.Markdown(
245
- "### Waiting for camera\nClick **Record from webcam** to start Phase 1.",
246
- elem_id="status-card",
247
- )
248
-
249
- gr.HTML(
250
- """
251
- <div class='footer-note'>
252
- Phase 1 validates live webcam processing and deployment. On mobile, allow camera permission; your browser may offer front/rear camera selection.
253
- </div>
254
- """
255
- )
256
-
257
- # Using change() with a streaming webcam is more stable on Spaces than stream() for this Phase 1 build.
258
- # The webcam component still captures repeated frames while recording, and every changed frame is analyzed.
259
- webcam.change(
260
- analyze_frame,
261
- inputs=webcam,
262
- outputs=[annotated, status],
263
- queue=False,
264
- show_progress="hidden",
265
- )
266
 
267
  if __name__ == "__main__":
268
- demo.launch()
 
1
  import time
2
+ from typing import Optional, Tuple
3
 
4
  import cv2
5
  import gradio as gr
6
  import numpy as np
7
 
8
+ FACE_CASCADE = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
 
 
 
9
 
10
+ CUSTOM_CSS = """
11
+ :root { --radius-xl: 22px; }
12
+ .gradio-container {
13
+ max-width: 1500px !important;
14
+ margin: auto !important;
15
+ background: radial-gradient(circle at 15% 15%, rgba(38, 166, 191, .22), transparent 30%),
16
+ linear-gradient(135deg, #101827 0%, #273142 48%, #10232b 100%) !important;
17
+ color: #eef6ff !important;
18
+ }
19
+ #component-0, .contain, .block, .panel {
20
+ border-radius: var(--radius-xl) !important;
21
+ }
22
+ .prose h1, h1 {
23
+ font-size: clamp(2.2rem, 5vw, 4.4rem) !important;
24
+ text-align: center !important;
25
+ letter-spacing: -0.04em !important;
26
+ }
27
+ .prose p, .prose li { color: #c9d6e8 !important; }
28
+ label, .label-wrap span { font-weight: 800 !important; }
29
+ button {
30
+ border-radius: 999px !important;
31
+ font-weight: 800 !important;
32
+ }
33
+ .image-container, .wrap, .block {
34
+ overflow: hidden !important;
35
+ }
36
+ #status_box textarea, #status_box .prose {
37
+ font-size: 1.05rem !important;
38
+ }
39
+ @media (max-width: 760px) {
40
+ .gradio-container { padding: 8px !important; }
41
+ h1 { font-size: 2.35rem !important; }
42
+ .image-container img, .image-container video { max-height: 62vh !important; object-fit: contain !important; }
43
+ }
44
+ """
45
 
46
+ HEADER = """
47
+ # FaceSense Live
48
+ Real-time face boxes for desktop and mobile webcam testing.
49
+ Click **Record** on the camera panel to start live analysis. On phones, allow camera permission; your browser may offer front/rear camera selection.
50
+ """
51
 
52
 
53
+ def draw_corner_box(img: np.ndarray, x: int, y: int, w: int, h: int) -> None:
54
+ color = (0, 238, 255)
55
+ shadow = (6, 18, 28)
56
+ thickness = 4
57
+ line = max(18, int(min(w, h) * 0.22))
 
 
 
58
 
59
+ # shadow first for readability
60
+ cv2.rectangle(img, (x, y), (x + w, y + h), shadow, 7)
61
+ # corner style box
62
+ cv2.line(img, (x, y), (x + line, y), color, thickness)
63
+ cv2.line(img, (x, y), (x, y + line), color, thickness)
64
+ cv2.line(img, (x + w, y), (x + w - line, y), color, thickness)
65
+ cv2.line(img, (x + w, y), (x + w, y + line), color, thickness)
66
+ cv2.line(img, (x, y + h), (x + line, y + h), color, thickness)
67
+ cv2.line(img, (x, y + h), (x, y + h - line), color, thickness)
68
+ cv2.line(img, (x + w, y + h), (x + w - line, y + h), color, thickness)
69
+ cv2.line(img, (x + w, y + h), (x + w, y + h - line), color, thickness)
70
 
71
+ label = "Face detected"
72
+ cv2.rectangle(img, (x, max(0, y - 38)), (x + 185, y), (0, 145, 175), -1)
73
+ cv2.putText(img, label, (x + 10, max(22, y - 12)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
 
74
 
 
 
 
 
75
 
76
+ def process_frame(frame: Optional[np.ndarray]) -> Tuple[Optional[np.ndarray], str]:
77
+ start = time.perf_counter()
78
+ if frame is None:
79
+ return None, "### Waiting for camera\nClick **Record** on the webcam panel to start live analysis."
80
 
81
+ output = frame.copy()
82
+ if output.ndim == 2:
83
+ output = cv2.cvtColor(output, cv2.COLOR_GRAY2RGB)
84
+ if output.shape[-1] == 4:
85
+ output = cv2.cvtColor(output, cv2.COLOR_RGBA2RGB)
86
 
87
+ gray = cv2.cvtColor(output, cv2.COLOR_RGB2GRAY)
 
 
88
  gray = cv2.equalizeHist(gray)
 
89
  faces = FACE_CASCADE.detectMultiScale(
90
  gray,
91
  scaleFactor=1.08,
92
  minNeighbors=5,
93
+ minSize=(55, 55),
94
  flags=cv2.CASCADE_SCALE_IMAGE,
95
  )
96
 
97
+ for (x, y, w, h) in faces:
98
+ draw_corner_box(output, int(x), int(y), int(w), int(h))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
  elapsed_ms = (time.perf_counter() - start) * 1000
101
  fps = 1000 / elapsed_ms if elapsed_ms > 0 else 0
102
 
103
+ if len(faces) == 0:
104
+ status = (
105
+ "### Live status\n"
106
+ "No frontal face detected yet. Move your face toward the center, improve lighting, and keep the camera steady.\n\n"
107
+ f"**Processing:** {elapsed_ms:.1f} ms \n"
108
+ f"**Approx FPS:** {fps:.1f}"
109
+ )
 
 
 
 
 
 
110
  else:
111
+ status = (
112
+ "### Live status\n"
113
+ f"**Faces detected:** {len(faces)} \n"
114
+ "**Phase 1:** bounding boxes only \n"
115
+ "**Next phase:** facial expression + apparent age range + optional presentation estimate \n\n"
116
+ f"**Processing:** {elapsed_ms:.1f} ms \n"
117
+ f"**Approx FPS:** {fps:.1f}"
118
+ )
 
 
 
119
  return output, status
120
 
121
 
122
+ demo = gr.Interface(
123
+ fn=process_frame,
124
+ inputs=gr.Image(
125
+ label="Camera input",
126
+ sources=["webcam"],
127
+ type="numpy",
128
+ streaming=True,
129
+ mirror_webcam=True,
130
+ height=520,
131
+ ),
132
+ outputs=[
133
+ gr.Image(label="Annotated output", type="numpy", height=520),
134
+ gr.Markdown(label="Status"),
135
+ ],
136
+ title="FaceSense Live",
137
+ description=HEADER,
138
+ live=True,
139
+ css=CUSTOM_CSS,
140
+ allow_flagging="never",
141
+ api_name="predict",
142
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  if __name__ == "__main__":
145
+ demo.queue(default_concurrency_limit=4).launch()