Solar-Prince commited on
Commit
d0378ad
·
verified ·
1 Parent(s): b64c755

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -263
app.py DELETED
@@ -1,263 +0,0 @@
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 box prototype for the Hugging Face Spaces deployment loop"
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
- )
233
- with gr.Column(scale=1, elem_classes=["panel"]):
234
- annotated = gr.Image(
235
- label="Annotated output",
236
- type="numpy",
237
- height=520,
238
- )
239
-
240
- with gr.Row():
241
- with gr.Column(elem_classes=["panel"]):
242
- status = gr.Markdown(
243
- "### Waiting for camera\nClick **Record from webcam** to start Phase 1.",
244
- elem_id="status-card",
245
- )
246
-
247
- gr.HTML(
248
- "<div class='footer-note'>Phase 1 validates live webcam processing and deployment. Prediction models come next after this passes your test.</div>"
249
- )
250
-
251
- webcam.stream(
252
- analyze_frame,
253
- inputs=webcam,
254
- outputs=[annotated, status],
255
- time_limit=30,
256
- stream_every=0.12,
257
- concurrency_limit=10,
258
- api_name="analyze_frame",
259
- )
260
-
261
- if __name__ == "__main__":
262
- demo.queue(default_concurrency_limit=10)
263
- demo.launch()