DevAtomicRelease commited on
Commit ·
3216a1f
0
Parent(s):
Initial deployment: Face Recognition Web App
Browse files- .dockerignore +14 -0
- .gitignore +45 -0
- Dockerfile +49 -0
- README.md +38 -0
- client/app.js +317 -0
- client/canvas.js +129 -0
- client/index.html +135 -0
- client/recognition.js +197 -0
- client/recorder.js +129 -0
- client/styles.css +343 -0
- client/uploader.js +160 -0
- package.json +19 -0
- requirements-hf.txt +10 -0
- requirements.txt +11 -0
- server/__init__.py +3 -0
- server/app.py +190 -0
- server/cleanup.py +46 -0
- server/embedding_generator.py +226 -0
- server/frame_extractor.py +108 -0
- server/models/.gitkeep +5 -0
- server/recognition_engine.py +79 -0
- server/session_manager.py +179 -0
- server/websocket_handler.py +126 -0
.dockerignore
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.pyc
|
| 4 |
+
.git/
|
| 5 |
+
.gitignore
|
| 6 |
+
tmp/
|
| 7 |
+
server/models/*.pth
|
| 8 |
+
node_modules/
|
| 9 |
+
*.md
|
| 10 |
+
!README.md
|
| 11 |
+
package.json
|
| 12 |
+
package-lock.json
|
| 13 |
+
.env
|
| 14 |
+
*.log
|
.gitignore
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ── Virtual Environment ──────────────────────────────────
|
| 2 |
+
.venv/
|
| 3 |
+
venv/
|
| 4 |
+
env/
|
| 5 |
+
.env/
|
| 6 |
+
|
| 7 |
+
# ── Python ───────────────────────────────────────────────
|
| 8 |
+
__pycache__/
|
| 9 |
+
*.py[cod]
|
| 10 |
+
*$py.class
|
| 11 |
+
*.so
|
| 12 |
+
*.egg-info/
|
| 13 |
+
dist/
|
| 14 |
+
build/
|
| 15 |
+
*.egg
|
| 16 |
+
|
| 17 |
+
# ── Model Weights (downloaded at runtime on HF) ─────────
|
| 18 |
+
server/models/*.pth
|
| 19 |
+
server/models/*.pt
|
| 20 |
+
|
| 21 |
+
# ── Session Temp Data ────────────────────────────────────
|
| 22 |
+
tmp/
|
| 23 |
+
|
| 24 |
+
# ── Node / Package Manager ───────────────────────────────
|
| 25 |
+
node_modules/
|
| 26 |
+
package-lock.json
|
| 27 |
+
|
| 28 |
+
# ── IDE / Editor ─────────────────────────────────────────
|
| 29 |
+
.vscode/
|
| 30 |
+
.idea/
|
| 31 |
+
*.swp
|
| 32 |
+
*.swo
|
| 33 |
+
*~
|
| 34 |
+
|
| 35 |
+
# ── OS Files ─────────────────────────────────────────────
|
| 36 |
+
.DS_Store
|
| 37 |
+
Thumbs.db
|
| 38 |
+
desktop.ini
|
| 39 |
+
|
| 40 |
+
# ── Logs ─────────────────────────────────────────────────
|
| 41 |
+
*.log
|
| 42 |
+
|
| 43 |
+
# ── Environment Variables ────────────────────────────────
|
| 44 |
+
.env
|
| 45 |
+
.env.local
|
Dockerfile
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ── Hugging Face Spaces Dockerfile ────────────────────────────────
|
| 2 |
+
# Free tier: 2 vCPU, 16GB RAM, CPU-only
|
| 3 |
+
# SDK: Docker | Port: 7860
|
| 4 |
+
|
| 5 |
+
FROM python:3.11-slim
|
| 6 |
+
|
| 7 |
+
# Install system dependencies for OpenCV
|
| 8 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 9 |
+
libgl1-mesa-glx \
|
| 10 |
+
libglib2.0-0 \
|
| 11 |
+
libsm6 \
|
| 12 |
+
libxext6 \
|
| 13 |
+
libxrender1 \
|
| 14 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 15 |
+
|
| 16 |
+
# Set working directory
|
| 17 |
+
WORKDIR /app
|
| 18 |
+
|
| 19 |
+
# Install CPU-only PyTorch first (smaller image, ~200MB vs ~2.5GB CUDA)
|
| 20 |
+
RUN pip install --no-cache-dir \
|
| 21 |
+
torch==2.2.2+cpu \
|
| 22 |
+
torchvision==0.17.2+cpu \
|
| 23 |
+
--index-url https://download.pytorch.org/whl/cpu
|
| 24 |
+
|
| 25 |
+
# Copy and install remaining requirements
|
| 26 |
+
COPY requirements-hf.txt .
|
| 27 |
+
RUN pip install --no-cache-dir -r requirements-hf.txt
|
| 28 |
+
|
| 29 |
+
# Copy application code
|
| 30 |
+
COPY server/ ./server/
|
| 31 |
+
COPY client/ ./client/
|
| 32 |
+
|
| 33 |
+
# Create tmp directory for sessions (writable at runtime)
|
| 34 |
+
RUN mkdir -p /tmp/sessions
|
| 35 |
+
|
| 36 |
+
# HF Spaces runs as user with uid 1000
|
| 37 |
+
RUN useradd -m -u 1000 appuser && \
|
| 38 |
+
chown -R appuser:appuser /app /tmp/sessions
|
| 39 |
+
USER appuser
|
| 40 |
+
|
| 41 |
+
# Expose HF Spaces default port
|
| 42 |
+
EXPOSE 7860
|
| 43 |
+
|
| 44 |
+
# Health check
|
| 45 |
+
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
|
| 46 |
+
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:7860/')" || exit 1
|
| 47 |
+
|
| 48 |
+
# Start the FastAPI server on port 7860
|
| 49 |
+
CMD ["uvicorn", "server.app:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Face Recognition with Embeddings
|
| 3 |
+
emoji: 🔐
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
pinned: false
|
| 9 |
+
license: mit
|
| 10 |
+
short_description: Real-time face recognition using MTCNN + InceptionResnetV1
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# Face Recognition Web App
|
| 14 |
+
|
| 15 |
+
Real-time browser-based face recognition using **MTCNN** for face detection and **InceptionResnetV1** (FaceNet) for embedding generation.
|
| 16 |
+
|
| 17 |
+
## Features
|
| 18 |
+
- 🎥 **Video Registration** — Record a short clip to register your face
|
| 19 |
+
- 📸 **Image Upload** — Upload 3-10 face images for registration
|
| 20 |
+
- ⚡ **Real-Time Recognition** — Live webcam face matching via WebSocket
|
| 21 |
+
- 🔒 **Session Isolation** — All data is ephemeral and auto-purged
|
| 22 |
+
- 🧠 **Cosine Similarity** — Identity matching with configurable threshold
|
| 23 |
+
|
| 24 |
+
## How It Works
|
| 25 |
+
1. **Register** — Enter your name and record a video or upload images
|
| 26 |
+
2. **Process** — MTCNN detects faces → InceptionResnetV1 generates 512-dim embeddings
|
| 27 |
+
3. **Recognize** — Live webcam stream matches faces against stored embeddings
|
| 28 |
+
|
| 29 |
+
## Tech Stack
|
| 30 |
+
- **Backend**: FastAPI + WebSocket
|
| 31 |
+
- **ML**: PyTorch, facenet-pytorch (MTCNN + InceptionResnetV1)
|
| 32 |
+
- **Frontend**: Vanilla JS, HTML5, CSS3
|
| 33 |
+
|
| 34 |
+
## Local Development
|
| 35 |
+
```bash
|
| 36 |
+
pip install -r requirements.txt
|
| 37 |
+
uvicorn server.app:app --host 0.0.0.0 --port 8000
|
| 38 |
+
```
|
client/app.js
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* app.js - Core UI logic and panel switching.
|
| 3 |
+
*
|
| 4 |
+
* Orchestrates the registration and recognition flow:
|
| 5 |
+
* session initialization, tab switching, recording/upload handling,
|
| 6 |
+
* panel transitions, and cleanup on page unload.
|
| 7 |
+
*/
|
| 8 |
+
|
| 9 |
+
(function () {
|
| 10 |
+
'use strict';
|
| 11 |
+
|
| 12 |
+
// ── State ──────────────────────────────────────────────────
|
| 13 |
+
let sessionId = null;
|
| 14 |
+
const recorder = new FaceRecorder();
|
| 15 |
+
const uploader = new FaceUploader();
|
| 16 |
+
let recognition = null;
|
| 17 |
+
let faceCanvas = null;
|
| 18 |
+
|
| 19 |
+
// ── DOM Elements ───────────────────────────────────────────
|
| 20 |
+
const $ = (id) => document.getElementById(id);
|
| 21 |
+
|
| 22 |
+
const els = {
|
| 23 |
+
statusDot: $('statusDot'),
|
| 24 |
+
sessionStatus: $('sessionStatus'),
|
| 25 |
+
step1: $('step1'),
|
| 26 |
+
step2: $('step2'),
|
| 27 |
+
stepLine1: $('stepLine1'),
|
| 28 |
+
registrationPanel: $('registrationPanel'),
|
| 29 |
+
recognitionPanel: $('recognitionPanel'),
|
| 30 |
+
nameInput: $('nameInput'),
|
| 31 |
+
tabRecord: $('tabRecord'),
|
| 32 |
+
tabUpload: $('tabUpload'),
|
| 33 |
+
recordContent: $('recordContent'),
|
| 34 |
+
uploadContent: $('uploadContent'),
|
| 35 |
+
recordVideo: $('recordVideo'),
|
| 36 |
+
recordOverlay: $('recordOverlay'),
|
| 37 |
+
recordingIndicator: $('recordingIndicator'),
|
| 38 |
+
recordTimer: $('recordTimer'),
|
| 39 |
+
btnRecord: $('btnRecord'),
|
| 40 |
+
uploadZone: $('uploadZone'),
|
| 41 |
+
fileInput: $('fileInput'),
|
| 42 |
+
previewGallery: $('previewGallery'),
|
| 43 |
+
btnUpload: $('btnUpload'),
|
| 44 |
+
processingState: $('processingState'),
|
| 45 |
+
processingText: $('processingText'),
|
| 46 |
+
resultState: $('resultState'),
|
| 47 |
+
resultIcon: $('resultIcon'),
|
| 48 |
+
resultText: $('resultText'),
|
| 49 |
+
resultDetail: $('resultDetail'),
|
| 50 |
+
btnStartRecognition: $('btnStartRecognition'),
|
| 51 |
+
recognitionVideo: $('recognitionVideo'),
|
| 52 |
+
recognitionCanvas: $('recognitionCanvas'),
|
| 53 |
+
fpsCounter: $('fpsCounter'),
|
| 54 |
+
detectionLog: $('detectionLog'),
|
| 55 |
+
registeredCount: $('registeredCount'),
|
| 56 |
+
btnStopRecognition: $('btnStopRecognition'),
|
| 57 |
+
};
|
| 58 |
+
|
| 59 |
+
// ── Session Init ───────────────────────────────────────────
|
| 60 |
+
async function initSession() {
|
| 61 |
+
try {
|
| 62 |
+
const res = await fetch('/api/session/start', { method: 'POST' });
|
| 63 |
+
const data = await res.json();
|
| 64 |
+
sessionId = data.session_id;
|
| 65 |
+
els.statusDot.classList.add('active');
|
| 66 |
+
els.sessionStatus.textContent = 'Session Active';
|
| 67 |
+
console.log('[App] Session started:', sessionId);
|
| 68 |
+
} catch (err) {
|
| 69 |
+
els.statusDot.classList.add('error');
|
| 70 |
+
els.sessionStatus.textContent = 'Connection Error';
|
| 71 |
+
console.error('[App] Failed to start session:', err);
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
// ── Tab Switching ──────────────────────────────────────────
|
| 76 |
+
function switchTab(tab) {
|
| 77 |
+
els.tabRecord.classList.toggle('active', tab === 'record');
|
| 78 |
+
els.tabUpload.classList.toggle('active', tab === 'upload');
|
| 79 |
+
els.recordContent.classList.toggle('active', tab === 'record');
|
| 80 |
+
els.uploadContent.classList.toggle('active', tab === 'upload');
|
| 81 |
+
|
| 82 |
+
if (tab === 'record') {
|
| 83 |
+
recorder.initCamera(els.recordVideo);
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
els.tabRecord.addEventListener('click', () => switchTab('record'));
|
| 88 |
+
els.tabUpload.addEventListener('click', () => switchTab('upload'));
|
| 89 |
+
|
| 90 |
+
// ── Recording ──────────────────────────────────────────────
|
| 91 |
+
els.btnRecord.addEventListener('click', async () => {
|
| 92 |
+
const name = els.nameInput.value.trim();
|
| 93 |
+
if (!name) {
|
| 94 |
+
els.nameInput.focus();
|
| 95 |
+
els.nameInput.style.borderColor = '#ef4444';
|
| 96 |
+
setTimeout(() => els.nameInput.style.borderColor = '', 2000);
|
| 97 |
+
return;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
if (!recorder.isRecording) {
|
| 101 |
+
// Start recording
|
| 102 |
+
await recorder.initCamera(els.recordVideo);
|
| 103 |
+
recorder.startRecording((time) => {
|
| 104 |
+
els.recordTimer.textContent = time;
|
| 105 |
+
});
|
| 106 |
+
els.btnRecord.innerHTML = '<div class="btn-record-inner" style="border-radius:3px;width:14px;height:14px;background:var(--danger)"></div>Stop Recording';
|
| 107 |
+
els.btnRecord.classList.add('recording');
|
| 108 |
+
els.recordOverlay.classList.add('active');
|
| 109 |
+
els.recordingIndicator.classList.add('active');
|
| 110 |
+
} else {
|
| 111 |
+
// Stop recording
|
| 112 |
+
const blob = await recorder.stopRecording();
|
| 113 |
+
els.btnRecord.innerHTML = '<div class="btn-record-inner"></div>Start Recording';
|
| 114 |
+
els.btnRecord.classList.remove('recording');
|
| 115 |
+
els.recordOverlay.classList.remove('active');
|
| 116 |
+
els.recordingIndicator.classList.remove('active');
|
| 117 |
+
els.recordTimer.textContent = '0:00';
|
| 118 |
+
|
| 119 |
+
if (blob && blob.size > 0) {
|
| 120 |
+
await registerViaVideo(blob, name);
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
});
|
| 124 |
+
|
| 125 |
+
// ── Upload ─────────────────────────────────────────────────
|
| 126 |
+
uploader.init(els.uploadZone, els.fileInput, els.previewGallery, (files) => {
|
| 127 |
+
els.btnUpload.disabled = !uploader.isReady();
|
| 128 |
+
});
|
| 129 |
+
|
| 130 |
+
els.btnUpload.addEventListener('click', async () => {
|
| 131 |
+
const name = els.nameInput.value.trim();
|
| 132 |
+
if (!name) {
|
| 133 |
+
els.nameInput.focus();
|
| 134 |
+
els.nameInput.style.borderColor = '#ef4444';
|
| 135 |
+
setTimeout(() => els.nameInput.style.borderColor = '', 2000);
|
| 136 |
+
return;
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
if (uploader.isReady()) {
|
| 140 |
+
await registerViaUpload(uploader.getFiles(), name);
|
| 141 |
+
}
|
| 142 |
+
});
|
| 143 |
+
|
| 144 |
+
// ── Registration API Calls ─────────────────────────────────
|
| 145 |
+
function showProcessing(text) {
|
| 146 |
+
els.processingState.classList.add('active');
|
| 147 |
+
els.processingText.textContent = text || 'Processing faces...';
|
| 148 |
+
els.recordContent.style.display = 'none';
|
| 149 |
+
els.uploadContent.style.display = 'none';
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
function showResult(success, text, detail) {
|
| 153 |
+
els.processingState.classList.remove('active');
|
| 154 |
+
els.resultState.classList.add('active');
|
| 155 |
+
els.resultIcon.className = `result-icon ${success ? 'success' : 'error'}`;
|
| 156 |
+
els.resultIcon.innerHTML = success
|
| 157 |
+
? '<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>'
|
| 158 |
+
: '<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
|
| 159 |
+
els.resultText.textContent = text;
|
| 160 |
+
els.resultDetail.textContent = detail || '';
|
| 161 |
+
els.btnStartRecognition.style.display = success ? '' : 'none';
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
async function registerViaVideo(blob, name) {
|
| 165 |
+
showProcessing('Extracting frames & generating embeddings...');
|
| 166 |
+
|
| 167 |
+
const formData = new FormData();
|
| 168 |
+
formData.append('session_id', sessionId);
|
| 169 |
+
formData.append('name', name);
|
| 170 |
+
formData.append('video', blob, 'recording.webm');
|
| 171 |
+
|
| 172 |
+
try {
|
| 173 |
+
const res = await fetch('/api/register/video', { method: 'POST', body: formData });
|
| 174 |
+
const data = await res.json();
|
| 175 |
+
|
| 176 |
+
if (data.status === 'ready') {
|
| 177 |
+
showResult(true, 'Registration Successful!',
|
| 178 |
+
`${data.faces_detected} faces detected, ${data.embeddings_count} embedding(s) stored.`);
|
| 179 |
+
els.registeredCount.textContent = data.embeddings_count;
|
| 180 |
+
} else {
|
| 181 |
+
showResult(false, 'Registration Failed', data.message || 'No faces detected.');
|
| 182 |
+
}
|
| 183 |
+
} catch (err) {
|
| 184 |
+
showResult(false, 'Registration Error', err.message);
|
| 185 |
+
}
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
async function registerViaUpload(files, name) {
|
| 189 |
+
showProcessing('Processing uploaded images...');
|
| 190 |
+
|
| 191 |
+
const formData = new FormData();
|
| 192 |
+
formData.append('session_id', sessionId);
|
| 193 |
+
formData.append('name', name);
|
| 194 |
+
files.forEach(f => formData.append('images', f));
|
| 195 |
+
|
| 196 |
+
try {
|
| 197 |
+
const res = await fetch('/api/register/upload', { method: 'POST', body: formData });
|
| 198 |
+
const data = await res.json();
|
| 199 |
+
|
| 200 |
+
if (data.status === 'ready') {
|
| 201 |
+
showResult(true, 'Registration Successful!',
|
| 202 |
+
`${data.faces_detected} faces detected, ${data.embeddings_count} embedding(s) stored.`);
|
| 203 |
+
els.registeredCount.textContent = data.embeddings_count;
|
| 204 |
+
} else {
|
| 205 |
+
showResult(false, 'Registration Failed', data.message || 'No faces detected.');
|
| 206 |
+
}
|
| 207 |
+
} catch (err) {
|
| 208 |
+
showResult(false, 'Registration Error', err.message);
|
| 209 |
+
}
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
// ── Panel Switching ────────────────────────────────────────
|
| 213 |
+
els.btnStartRecognition.addEventListener('click', () => {
|
| 214 |
+
recorder.stopCamera();
|
| 215 |
+
|
| 216 |
+
els.registrationPanel.classList.add('hidden');
|
| 217 |
+
els.recognitionPanel.classList.remove('hidden');
|
| 218 |
+
els.step1.classList.remove('active');
|
| 219 |
+
els.step1.classList.add('completed');
|
| 220 |
+
els.stepLine1.classList.add('active');
|
| 221 |
+
els.step2.classList.add('active');
|
| 222 |
+
|
| 223 |
+
startRecognition();
|
| 224 |
+
});
|
| 225 |
+
|
| 226 |
+
els.btnStopRecognition.addEventListener('click', () => {
|
| 227 |
+
stopRecognition();
|
| 228 |
+
els.recognitionPanel.classList.add('hidden');
|
| 229 |
+
els.registrationPanel.classList.remove('hidden');
|
| 230 |
+
els.step2.classList.remove('active');
|
| 231 |
+
els.stepLine1.classList.remove('active');
|
| 232 |
+
els.step1.classList.remove('completed');
|
| 233 |
+
els.step1.classList.add('active');
|
| 234 |
+
|
| 235 |
+
// Reset registration state for another round
|
| 236 |
+
els.resultState.classList.remove('active');
|
| 237 |
+
els.recordContent.style.display = '';
|
| 238 |
+
els.uploadContent.style.display = '';
|
| 239 |
+
switchTab('record');
|
| 240 |
+
});
|
| 241 |
+
|
| 242 |
+
// ── Recognition ────────────────────────────────────────────
|
| 243 |
+
function startRecognition() {
|
| 244 |
+
recognition = new FaceRecognition();
|
| 245 |
+
faceCanvas = new FaceCanvas(els.recognitionCanvas, els.recognitionVideo);
|
| 246 |
+
|
| 247 |
+
recognition.start(sessionId, els.recognitionVideo, {
|
| 248 |
+
onResults: (faces) => {
|
| 249 |
+
faceCanvas.drawResults(faces);
|
| 250 |
+
updateDetectionLog(faces);
|
| 251 |
+
},
|
| 252 |
+
onFpsUpdate: (fps) => {
|
| 253 |
+
els.fpsCounter.textContent = `${fps} FPS`;
|
| 254 |
+
},
|
| 255 |
+
onDisconnect: () => {
|
| 256 |
+
els.fpsCounter.textContent = 'Disconnected';
|
| 257 |
+
},
|
| 258 |
+
});
|
| 259 |
+
}
|
| 260 |
+
|
| 261 |
+
function stopRecognition() {
|
| 262 |
+
if (recognition) {
|
| 263 |
+
recognition.stop();
|
| 264 |
+
recognition = null;
|
| 265 |
+
}
|
| 266 |
+
if (faceCanvas) {
|
| 267 |
+
faceCanvas.clear();
|
| 268 |
+
faceCanvas = null;
|
| 269 |
+
}
|
| 270 |
+
els.detectionLog.innerHTML = '<p class="log-placeholder">Waiting for faces...</p>';
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
function updateDetectionLog(faces) {
|
| 274 |
+
if (!faces || faces.length === 0) return;
|
| 275 |
+
|
| 276 |
+
// Clear placeholder
|
| 277 |
+
const placeholder = els.detectionLog.querySelector('.log-placeholder');
|
| 278 |
+
if (placeholder) placeholder.remove();
|
| 279 |
+
|
| 280 |
+
for (const face of faces) {
|
| 281 |
+
const entry = document.createElement('div');
|
| 282 |
+
entry.className = 'log-entry';
|
| 283 |
+
|
| 284 |
+
const nameSpan = document.createElement('span');
|
| 285 |
+
nameSpan.className = 'name';
|
| 286 |
+
nameSpan.textContent = face.label;
|
| 287 |
+
|
| 288 |
+
const confSpan = document.createElement('span');
|
| 289 |
+
confSpan.className = face.label !== 'Unknown' ? 'confidence' : 'unknown';
|
| 290 |
+
confSpan.textContent = `${(face.confidence * 100).toFixed(1)}%`;
|
| 291 |
+
|
| 292 |
+
entry.appendChild(nameSpan);
|
| 293 |
+
entry.appendChild(confSpan);
|
| 294 |
+
|
| 295 |
+
els.detectionLog.insertBefore(entry, els.detectionLog.firstChild);
|
| 296 |
+
|
| 297 |
+
// Keep log manageable
|
| 298 |
+
while (els.detectionLog.children.length > 50) {
|
| 299 |
+
els.detectionLog.removeChild(els.detectionLog.lastChild);
|
| 300 |
+
}
|
| 301 |
+
}
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
// ── Cleanup on Unload ──────────────────────────────────────
|
| 305 |
+
window.addEventListener('beforeunload', () => {
|
| 306 |
+
if (sessionId) {
|
| 307 |
+
const formData = new FormData();
|
| 308 |
+
formData.append('session_id', sessionId);
|
| 309 |
+
navigator.sendBeacon('/api/session/end', formData);
|
| 310 |
+
}
|
| 311 |
+
});
|
| 312 |
+
|
| 313 |
+
// ── Init ───────────────────────────────────────────────────
|
| 314 |
+
initSession();
|
| 315 |
+
recorder.initCamera(els.recordVideo);
|
| 316 |
+
|
| 317 |
+
})();
|
client/canvas.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* canvas.js - Draws bounding boxes + labels on video frames.
|
| 3 |
+
*
|
| 4 |
+
* Renders face detection results (bounding boxes, name labels,
|
| 5 |
+
* confidence percentages) as an overlay on the recognition video feed.
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
class FaceCanvas {
|
| 9 |
+
constructor(canvasElement, videoElement) {
|
| 10 |
+
this.canvas = canvasElement;
|
| 11 |
+
this.video = videoElement;
|
| 12 |
+
this.ctx = canvasElement.getContext('2d');
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
/**
|
| 16 |
+
* Sync canvas dimensions with the video element.
|
| 17 |
+
*/
|
| 18 |
+
resize() {
|
| 19 |
+
this.canvas.width = this.video.videoWidth || this.video.clientWidth;
|
| 20 |
+
this.canvas.height = this.video.videoHeight || this.video.clientHeight;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
/**
|
| 24 |
+
* Clear the canvas.
|
| 25 |
+
*/
|
| 26 |
+
clear() {
|
| 27 |
+
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
/**
|
| 31 |
+
* Draw face detection results on the canvas.
|
| 32 |
+
* @param {Array} faces - Array of face result objects with box, label, confidence.
|
| 33 |
+
*/
|
| 34 |
+
drawResults(faces) {
|
| 35 |
+
this.resize();
|
| 36 |
+
this.clear();
|
| 37 |
+
|
| 38 |
+
if (!faces || faces.length === 0) return;
|
| 39 |
+
|
| 40 |
+
// Calculate scale factors (video may be displayed at different size)
|
| 41 |
+
const scaleX = this.canvas.width / (this.video.videoWidth || 1);
|
| 42 |
+
const scaleY = this.canvas.height / (this.video.videoHeight || 1);
|
| 43 |
+
|
| 44 |
+
for (const face of faces) {
|
| 45 |
+
const [x1, y1, x2, y2] = face.box;
|
| 46 |
+
const label = face.label;
|
| 47 |
+
const confidence = face.confidence;
|
| 48 |
+
const isRecognized = label !== 'Unknown';
|
| 49 |
+
|
| 50 |
+
// Mirror the x coordinates (video is mirrored with scaleX(-1))
|
| 51 |
+
const mirroredX1 = this.canvas.width - (x2 * scaleX);
|
| 52 |
+
const mirroredX2 = this.canvas.width - (x1 * scaleX);
|
| 53 |
+
const scaledY1 = y1 * scaleY;
|
| 54 |
+
const scaledY2 = y2 * scaleY;
|
| 55 |
+
|
| 56 |
+
const boxWidth = mirroredX2 - mirroredX1;
|
| 57 |
+
const boxHeight = scaledY2 - scaledY1;
|
| 58 |
+
|
| 59 |
+
// Colors
|
| 60 |
+
const boxColor = isRecognized ? '#22c55e' : '#ef4444';
|
| 61 |
+
const bgColor = isRecognized ? 'rgba(34,197,94,0.15)' : 'rgba(239,68,68,0.15)';
|
| 62 |
+
|
| 63 |
+
// Draw bounding box
|
| 64 |
+
this.ctx.strokeStyle = boxColor;
|
| 65 |
+
this.ctx.lineWidth = 2;
|
| 66 |
+
this.ctx.strokeRect(mirroredX1, scaledY1, boxWidth, boxHeight);
|
| 67 |
+
|
| 68 |
+
// Subtle fill
|
| 69 |
+
this.ctx.fillStyle = bgColor;
|
| 70 |
+
this.ctx.fillRect(mirroredX1, scaledY1, boxWidth, boxHeight);
|
| 71 |
+
|
| 72 |
+
// Corner accents
|
| 73 |
+
const cornerLen = Math.min(20, boxWidth * 0.25, boxHeight * 0.25);
|
| 74 |
+
this.ctx.strokeStyle = boxColor;
|
| 75 |
+
this.ctx.lineWidth = 3;
|
| 76 |
+
|
| 77 |
+
// Top-left
|
| 78 |
+
this.ctx.beginPath();
|
| 79 |
+
this.ctx.moveTo(mirroredX1, scaledY1 + cornerLen);
|
| 80 |
+
this.ctx.lineTo(mirroredX1, scaledY1);
|
| 81 |
+
this.ctx.lineTo(mirroredX1 + cornerLen, scaledY1);
|
| 82 |
+
this.ctx.stroke();
|
| 83 |
+
|
| 84 |
+
// Top-right
|
| 85 |
+
this.ctx.beginPath();
|
| 86 |
+
this.ctx.moveTo(mirroredX2 - cornerLen, scaledY1);
|
| 87 |
+
this.ctx.lineTo(mirroredX2, scaledY1);
|
| 88 |
+
this.ctx.lineTo(mirroredX2, scaledY1 + cornerLen);
|
| 89 |
+
this.ctx.stroke();
|
| 90 |
+
|
| 91 |
+
// Bottom-left
|
| 92 |
+
this.ctx.beginPath();
|
| 93 |
+
this.ctx.moveTo(mirroredX1, scaledY2 - cornerLen);
|
| 94 |
+
this.ctx.lineTo(mirroredX1, scaledY2);
|
| 95 |
+
this.ctx.lineTo(mirroredX1 + cornerLen, scaledY2);
|
| 96 |
+
this.ctx.stroke();
|
| 97 |
+
|
| 98 |
+
// Bottom-right
|
| 99 |
+
this.ctx.beginPath();
|
| 100 |
+
this.ctx.moveTo(mirroredX2 - cornerLen, scaledY2);
|
| 101 |
+
this.ctx.lineTo(mirroredX2, scaledY2);
|
| 102 |
+
this.ctx.lineTo(mirroredX2, scaledY2 - cornerLen);
|
| 103 |
+
this.ctx.stroke();
|
| 104 |
+
|
| 105 |
+
// Label background
|
| 106 |
+
const labelText = isRecognized
|
| 107 |
+
? `${label} ${(confidence * 100).toFixed(1)}%`
|
| 108 |
+
: `Unknown ${(confidence * 100).toFixed(1)}%`;
|
| 109 |
+
|
| 110 |
+
this.ctx.font = '600 13px Inter, sans-serif';
|
| 111 |
+
const textMetrics = this.ctx.measureText(labelText);
|
| 112 |
+
const labelPad = 8;
|
| 113 |
+
const labelHeight = 24;
|
| 114 |
+
const labelWidth = textMetrics.width + labelPad * 2;
|
| 115 |
+
|
| 116 |
+
this.ctx.fillStyle = 'rgba(0,0,0,0.75)';
|
| 117 |
+
this.ctx.beginPath();
|
| 118 |
+
this.ctx.roundRect(mirroredX1, scaledY1 - labelHeight - 4, labelWidth, labelHeight, 6);
|
| 119 |
+
this.ctx.fill();
|
| 120 |
+
|
| 121 |
+
// Label text
|
| 122 |
+
this.ctx.fillStyle = boxColor;
|
| 123 |
+
this.ctx.fillText(labelText, mirroredX1 + labelPad, scaledY1 - 10);
|
| 124 |
+
}
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
// Export globally
|
| 129 |
+
window.FaceCanvas = FaceCanvas;
|
client/index.html
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<meta name="description" content="Real-time face recognition web app using FaceNet embeddings.">
|
| 7 |
+
<title>FaceAuth | Real-Time Identity Matching</title>
|
| 8 |
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
| 9 |
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
| 10 |
+
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
|
| 11 |
+
<link rel="stylesheet" href="/static/styles.css">
|
| 12 |
+
</head>
|
| 13 |
+
<body>
|
| 14 |
+
<div class="bg-gradient"></div>
|
| 15 |
+
<div class="bg-grid"></div>
|
| 16 |
+
|
| 17 |
+
<div id="app" class="app-container">
|
| 18 |
+
<header class="app-header">
|
| 19 |
+
<div class="logo">
|
| 20 |
+
<div class="logo-icon">
|
| 21 |
+
<svg viewBox="0 0 32 32" fill="none"><rect x="2" y="2" width="12" height="12" rx="3" stroke="currentColor" stroke-width="2"/><rect x="18" y="2" width="12" height="12" rx="3" stroke="currentColor" stroke-width="2"/><rect x="2" y="18" width="12" height="12" rx="3" stroke="currentColor" stroke-width="2"/><circle cx="24" cy="24" r="5" stroke="currentColor" stroke-width="2"/><circle cx="24" cy="24" r="2" fill="currentColor"/></svg>
|
| 22 |
+
</div>
|
| 23 |
+
<h1>FaceAuth<span class="accent">.</span></h1>
|
| 24 |
+
</div>
|
| 25 |
+
<div class="session-info" id="sessionInfo">
|
| 26 |
+
<div class="status-dot" id="statusDot"></div>
|
| 27 |
+
<span id="sessionStatus">Initializing...</span>
|
| 28 |
+
</div>
|
| 29 |
+
</header>
|
| 30 |
+
|
| 31 |
+
<main class="main-content">
|
| 32 |
+
<div class="steps-bar">
|
| 33 |
+
<div class="step active" id="step1"><div class="step-number">1</div><span>Register</span></div>
|
| 34 |
+
<div class="step-line" id="stepLine1"></div>
|
| 35 |
+
<div class="step" id="step2"><div class="step-number">2</div><span>Recognize</span></div>
|
| 36 |
+
</div>
|
| 37 |
+
|
| 38 |
+
<!-- Registration Panel -->
|
| 39 |
+
<section class="panel registration-panel" id="registrationPanel">
|
| 40 |
+
<div class="panel-header">
|
| 41 |
+
<h2>Face Registration</h2>
|
| 42 |
+
<p class="panel-subtitle">Record a short video or upload face images to register your identity</p>
|
| 43 |
+
</div>
|
| 44 |
+
<div class="name-input-group">
|
| 45 |
+
<label for="nameInput">Your Name</label>
|
| 46 |
+
<input type="text" id="nameInput" placeholder="Enter your name..." autocomplete="off">
|
| 47 |
+
</div>
|
| 48 |
+
<div class="tab-switcher">
|
| 49 |
+
<button class="tab active" id="tabRecord" data-tab="record">
|
| 50 |
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="4" fill="currentColor"/></svg>
|
| 51 |
+
Record Video
|
| 52 |
+
</button>
|
| 53 |
+
<button class="tab" id="tabUpload" data-tab="upload">
|
| 54 |
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
|
| 55 |
+
Upload Images
|
| 56 |
+
</button>
|
| 57 |
+
</div>
|
| 58 |
+
|
| 59 |
+
<div class="tab-content active" id="recordContent">
|
| 60 |
+
<div class="video-container">
|
| 61 |
+
<video id="recordVideo" autoplay muted playsinline></video>
|
| 62 |
+
<div class="video-overlay" id="recordOverlay"><div class="scan-line"></div></div>
|
| 63 |
+
<div class="recording-indicator" id="recordingIndicator"><div class="rec-dot"></div><span>REC</span><span id="recordTimer">0:00</span></div>
|
| 64 |
+
</div>
|
| 65 |
+
<div class="record-controls">
|
| 66 |
+
<button class="btn btn-primary btn-record" id="btnRecord"><div class="btn-record-inner"></div>Start Recording</button>
|
| 67 |
+
<p class="hint">Record 5-10 seconds of your face looking at the camera</p>
|
| 68 |
+
</div>
|
| 69 |
+
</div>
|
| 70 |
+
|
| 71 |
+
<div class="tab-content" id="uploadContent">
|
| 72 |
+
<div class="upload-zone" id="uploadZone">
|
| 73 |
+
<div class="upload-icon"><svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg></div>
|
| 74 |
+
<p>Drag & drop face images here</p>
|
| 75 |
+
<span class="upload-hint">or click to browse (3-10 images, JPG/PNG)</span>
|
| 76 |
+
<input type="file" id="fileInput" multiple accept="image/*" hidden>
|
| 77 |
+
</div>
|
| 78 |
+
<div class="preview-gallery" id="previewGallery"></div>
|
| 79 |
+
<button class="btn btn-primary" id="btnUpload" disabled>Upload & Register</button>
|
| 80 |
+
</div>
|
| 81 |
+
|
| 82 |
+
<div class="processing-state" id="processingState">
|
| 83 |
+
<div class="spinner"></div>
|
| 84 |
+
<p id="processingText">Processing faces...</p>
|
| 85 |
+
</div>
|
| 86 |
+
|
| 87 |
+
<div class="result-state" id="resultState">
|
| 88 |
+
<div class="result-icon success" id="resultIcon"><svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg></div>
|
| 89 |
+
<p id="resultText">Registration successful!</p>
|
| 90 |
+
<p class="result-detail" id="resultDetail"></p>
|
| 91 |
+
<button class="btn btn-primary" id="btnStartRecognition">Start Recognition →</button>
|
| 92 |
+
</div>
|
| 93 |
+
</section>
|
| 94 |
+
|
| 95 |
+
<!-- Recognition Panel -->
|
| 96 |
+
<section class="panel recognition-panel hidden" id="recognitionPanel">
|
| 97 |
+
<div class="panel-header">
|
| 98 |
+
<h2>Real-Time Recognition</h2>
|
| 99 |
+
<p class="panel-subtitle">Live face detection and identity matching</p>
|
| 100 |
+
</div>
|
| 101 |
+
<div class="recognition-container">
|
| 102 |
+
<div class="video-container recognition-video">
|
| 103 |
+
<video id="recognitionVideo" autoplay muted playsinline></video>
|
| 104 |
+
<canvas id="recognitionCanvas"></canvas>
|
| 105 |
+
<div class="fps-counter" id="fpsCounter">0 FPS</div>
|
| 106 |
+
</div>
|
| 107 |
+
<div class="recognition-sidebar">
|
| 108 |
+
<div class="sidebar-card">
|
| 109 |
+
<h3>Detection Log</h3>
|
| 110 |
+
<div class="detection-log" id="detectionLog"><p class="log-placeholder">Waiting for faces...</p></div>
|
| 111 |
+
</div>
|
| 112 |
+
<div class="sidebar-card">
|
| 113 |
+
<h3>Session Info</h3>
|
| 114 |
+
<div class="session-details">
|
| 115 |
+
<div class="detail-row"><span>Registered Faces</span><span id="registeredCount">0</span></div>
|
| 116 |
+
<div class="detail-row"><span>Threshold</span><span>0.65</span></div>
|
| 117 |
+
<div class="detail-row"><span>Model</span><span>FaceNet v1</span></div>
|
| 118 |
+
</div>
|
| 119 |
+
</div>
|
| 120 |
+
<button class="btn btn-danger" id="btnStopRecognition">Stop Recognition</button>
|
| 121 |
+
</div>
|
| 122 |
+
</div>
|
| 123 |
+
</section>
|
| 124 |
+
</main>
|
| 125 |
+
|
| 126 |
+
<footer class="app-footer"><p>All session data is automatically purged when you leave.</p></footer>
|
| 127 |
+
</div>
|
| 128 |
+
|
| 129 |
+
<script src="/static/recorder.js"></script>
|
| 130 |
+
<script src="/static/uploader.js"></script>
|
| 131 |
+
<script src="/static/canvas.js"></script>
|
| 132 |
+
<script src="/static/recognition.js"></script>
|
| 133 |
+
<script src="/static/app.js"></script>
|
| 134 |
+
</body>
|
| 135 |
+
</html>
|
client/recognition.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* recognition.js - WebSocket client for real-time recognition feed.
|
| 3 |
+
*
|
| 4 |
+
* Connects to the server's WebSocket endpoint, captures frames from
|
| 5 |
+
* the webcam, sends them as base64 to the server, and receives
|
| 6 |
+
* face detection/recognition results back.
|
| 7 |
+
*/
|
| 8 |
+
|
| 9 |
+
class FaceRecognition {
|
| 10 |
+
constructor() {
|
| 11 |
+
this.ws = null;
|
| 12 |
+
this.stream = null;
|
| 13 |
+
this.captureCanvas = document.createElement('canvas');
|
| 14 |
+
this.captureCtx = this.captureCanvas.getContext('2d');
|
| 15 |
+
this.isRunning = false;
|
| 16 |
+
this.frameInterval = null;
|
| 17 |
+
this.fps = 5; // WS_FRAME_RATE
|
| 18 |
+
this.fpsCounter = { frames: 0, lastTime: Date.now(), current: 0 };
|
| 19 |
+
this.onResults = null;
|
| 20 |
+
this.onFpsUpdate = null;
|
| 21 |
+
this.onDisconnect = null;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
/**
|
| 25 |
+
* Start the recognition feed.
|
| 26 |
+
* @param {string} sessionId - The session ID for the WebSocket connection.
|
| 27 |
+
* @param {HTMLVideoElement} videoElement - The video element to capture frames from.
|
| 28 |
+
* @param {Object} callbacks - { onResults, onFpsUpdate, onDisconnect }
|
| 29 |
+
*/
|
| 30 |
+
async start(sessionId, videoElement, callbacks = {}) {
|
| 31 |
+
this.onResults = callbacks.onResults || null;
|
| 32 |
+
this.onFpsUpdate = callbacks.onFpsUpdate || null;
|
| 33 |
+
this.onDisconnect = callbacks.onDisconnect || null;
|
| 34 |
+
|
| 35 |
+
// Start webcam and wait for it to be fully ready
|
| 36 |
+
try {
|
| 37 |
+
this.stream = await navigator.mediaDevices.getUserMedia({
|
| 38 |
+
video: { width: { ideal: 640 }, height: { ideal: 480 }, facingMode: 'user' },
|
| 39 |
+
audio: false,
|
| 40 |
+
});
|
| 41 |
+
videoElement.srcObject = this.stream;
|
| 42 |
+
|
| 43 |
+
// Wait for video metadata and first frame to load
|
| 44 |
+
await new Promise((resolve, reject) => {
|
| 45 |
+
const timeout = setTimeout(() => reject(new Error('Video load timeout')), 10000);
|
| 46 |
+
|
| 47 |
+
if (videoElement.readyState >= 2) {
|
| 48 |
+
clearTimeout(timeout);
|
| 49 |
+
resolve();
|
| 50 |
+
return;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
videoElement.onloadeddata = () => {
|
| 54 |
+
clearTimeout(timeout);
|
| 55 |
+
resolve();
|
| 56 |
+
};
|
| 57 |
+
videoElement.onerror = () => {
|
| 58 |
+
clearTimeout(timeout);
|
| 59 |
+
reject(new Error('Video load error'));
|
| 60 |
+
};
|
| 61 |
+
});
|
| 62 |
+
|
| 63 |
+
await videoElement.play();
|
| 64 |
+
|
| 65 |
+
// Extra wait to ensure first frames are rendered
|
| 66 |
+
await new Promise(r => setTimeout(r, 500));
|
| 67 |
+
|
| 68 |
+
console.log(`[Recognition] Webcam ready: ${videoElement.videoWidth}x${videoElement.videoHeight}`);
|
| 69 |
+
} catch (err) {
|
| 70 |
+
console.error('[Recognition] Camera init failed:', err);
|
| 71 |
+
if (this.onDisconnect) this.onDisconnect();
|
| 72 |
+
return;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
// Connect WebSocket only after camera is fully ready
|
| 76 |
+
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
| 77 |
+
const wsUrl = `${protocol}//${location.host}/ws/recognize/${sessionId}`;
|
| 78 |
+
|
| 79 |
+
this.ws = new WebSocket(wsUrl);
|
| 80 |
+
|
| 81 |
+
this.ws.onopen = () => {
|
| 82 |
+
console.log('[Recognition] WebSocket connected.');
|
| 83 |
+
this.isRunning = true;
|
| 84 |
+
this._startFrameCapture(videoElement);
|
| 85 |
+
};
|
| 86 |
+
|
| 87 |
+
this.ws.onmessage = (event) => {
|
| 88 |
+
try {
|
| 89 |
+
const data = JSON.parse(event.data);
|
| 90 |
+
|
| 91 |
+
if (data.error) {
|
| 92 |
+
console.error('[Recognition] Server error:', data.error);
|
| 93 |
+
return;
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
// Update FPS counter
|
| 97 |
+
this.fpsCounter.frames++;
|
| 98 |
+
const now = Date.now();
|
| 99 |
+
if (now - this.fpsCounter.lastTime >= 1000) {
|
| 100 |
+
this.fpsCounter.current = this.fpsCounter.frames;
|
| 101 |
+
this.fpsCounter.frames = 0;
|
| 102 |
+
this.fpsCounter.lastTime = now;
|
| 103 |
+
if (this.onFpsUpdate) this.onFpsUpdate(this.fpsCounter.current);
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
if (this.onResults && data.faces) {
|
| 107 |
+
this.onResults(data.faces);
|
| 108 |
+
}
|
| 109 |
+
} catch (err) {
|
| 110 |
+
console.error('[Recognition] Failed to parse message:', err);
|
| 111 |
+
}
|
| 112 |
+
};
|
| 113 |
+
|
| 114 |
+
this.ws.onclose = () => {
|
| 115 |
+
console.log('[Recognition] WebSocket closed.');
|
| 116 |
+
this.isRunning = false;
|
| 117 |
+
this._stopFrameCapture();
|
| 118 |
+
if (this.onDisconnect) this.onDisconnect();
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
this.ws.onerror = (err) => {
|
| 122 |
+
console.error('[Recognition] WebSocket error:', err);
|
| 123 |
+
};
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
/**
|
| 127 |
+
* Start capturing and sending frames at the configured FPS.
|
| 128 |
+
* @param {HTMLVideoElement} videoElement
|
| 129 |
+
*/
|
| 130 |
+
_startFrameCapture(videoElement) {
|
| 131 |
+
const interval = 1000 / this.fps;
|
| 132 |
+
let pendingSend = false; // Prevent frame overlap
|
| 133 |
+
|
| 134 |
+
this.frameInterval = setInterval(() => {
|
| 135 |
+
if (!this.isRunning || this.ws.readyState !== WebSocket.OPEN || pendingSend) return;
|
| 136 |
+
|
| 137 |
+
// Verify video has valid dimensions
|
| 138 |
+
const vw = videoElement.videoWidth;
|
| 139 |
+
const vh = videoElement.videoHeight;
|
| 140 |
+
if (!vw || !vh) return;
|
| 141 |
+
|
| 142 |
+
// Size the capture canvas to the video
|
| 143 |
+
this.captureCanvas.width = vw;
|
| 144 |
+
this.captureCanvas.height = vh;
|
| 145 |
+
|
| 146 |
+
// Draw current frame
|
| 147 |
+
this.captureCtx.drawImage(videoElement, 0, 0, vw, vh);
|
| 148 |
+
|
| 149 |
+
// Convert to base64 JPEG and send
|
| 150 |
+
pendingSend = true;
|
| 151 |
+
this.captureCanvas.toBlob((blob) => {
|
| 152 |
+
pendingSend = false;
|
| 153 |
+
if (blob && this.ws && this.ws.readyState === WebSocket.OPEN) {
|
| 154 |
+
const reader = new FileReader();
|
| 155 |
+
reader.onloadend = () => {
|
| 156 |
+
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
| 157 |
+
const base64 = reader.result.split(',')[1];
|
| 158 |
+
this.ws.send(base64);
|
| 159 |
+
}
|
| 160 |
+
};
|
| 161 |
+
reader.readAsDataURL(blob);
|
| 162 |
+
}
|
| 163 |
+
}, 'image/jpeg', 0.7);
|
| 164 |
+
}, interval);
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
/**
|
| 168 |
+
* Stop frame capture.
|
| 169 |
+
*/
|
| 170 |
+
_stopFrameCapture() {
|
| 171 |
+
if (this.frameInterval) {
|
| 172 |
+
clearInterval(this.frameInterval);
|
| 173 |
+
this.frameInterval = null;
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
/**
|
| 178 |
+
* Stop the recognition feed entirely.
|
| 179 |
+
*/
|
| 180 |
+
stop() {
|
| 181 |
+
this.isRunning = false;
|
| 182 |
+
this._stopFrameCapture();
|
| 183 |
+
|
| 184 |
+
if (this.ws) {
|
| 185 |
+
this.ws.close();
|
| 186 |
+
this.ws = null;
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
if (this.stream) {
|
| 190 |
+
this.stream.getTracks().forEach(track => track.stop());
|
| 191 |
+
this.stream = null;
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
// Export globally
|
| 197 |
+
window.FaceRecognition = FaceRecognition;
|
client/recorder.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* recorder.js - MediaRecorder wrapper for video capture.
|
| 3 |
+
*
|
| 4 |
+
* Handles browser webcam access via getUserMedia, records 5-10 second
|
| 5 |
+
* video blobs using the MediaRecorder API, and provides start/stop controls.
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
class FaceRecorder {
|
| 9 |
+
constructor() {
|
| 10 |
+
this.stream = null;
|
| 11 |
+
this.mediaRecorder = null;
|
| 12 |
+
this.chunks = [];
|
| 13 |
+
this.isRecording = false;
|
| 14 |
+
this.timerInterval = null;
|
| 15 |
+
this.startTime = 0;
|
| 16 |
+
this.maxDuration = 10000; // 10 seconds max
|
| 17 |
+
this.minDuration = 5000; // 5 seconds min
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
/**
|
| 21 |
+
* Initialize webcam stream and attach to video element.
|
| 22 |
+
* @param {HTMLVideoElement} videoElement
|
| 23 |
+
*/
|
| 24 |
+
async initCamera(videoElement) {
|
| 25 |
+
try {
|
| 26 |
+
this.stream = await navigator.mediaDevices.getUserMedia({
|
| 27 |
+
video: { width: { ideal: 640 }, height: { ideal: 480 }, facingMode: 'user' },
|
| 28 |
+
audio: false,
|
| 29 |
+
});
|
| 30 |
+
videoElement.srcObject = this.stream;
|
| 31 |
+
await videoElement.play();
|
| 32 |
+
return true;
|
| 33 |
+
} catch (err) {
|
| 34 |
+
console.error('[Recorder] Camera access denied:', err);
|
| 35 |
+
return false;
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
/**
|
| 40 |
+
* Start recording video from the webcam stream.
|
| 41 |
+
* @param {Function} onTimerUpdate - Callback with formatted time string.
|
| 42 |
+
* @returns {Promise} Resolves when recording starts.
|
| 43 |
+
*/
|
| 44 |
+
startRecording(onTimerUpdate) {
|
| 45 |
+
if (!this.stream) throw new Error('Camera not initialized');
|
| 46 |
+
if (this.isRecording) return;
|
| 47 |
+
|
| 48 |
+
this.chunks = [];
|
| 49 |
+
const mimeType = MediaRecorder.isTypeSupported('video/webm;codecs=vp9')
|
| 50 |
+
? 'video/webm;codecs=vp9'
|
| 51 |
+
: 'video/webm';
|
| 52 |
+
|
| 53 |
+
this.mediaRecorder = new MediaRecorder(this.stream, { mimeType });
|
| 54 |
+
|
| 55 |
+
this.mediaRecorder.ondataavailable = (e) => {
|
| 56 |
+
if (e.data.size > 0) this.chunks.push(e.data);
|
| 57 |
+
};
|
| 58 |
+
|
| 59 |
+
this.mediaRecorder.start(100); // Collect data every 100ms
|
| 60 |
+
this.isRecording = true;
|
| 61 |
+
this.startTime = Date.now();
|
| 62 |
+
|
| 63 |
+
// Timer update
|
| 64 |
+
this.timerInterval = setInterval(() => {
|
| 65 |
+
const elapsed = Date.now() - this.startTime;
|
| 66 |
+
const secs = Math.floor(elapsed / 1000);
|
| 67 |
+
const mins = Math.floor(secs / 60);
|
| 68 |
+
const display = `${mins}:${String(secs % 60).padStart(2, '0')}`;
|
| 69 |
+
if (onTimerUpdate) onTimerUpdate(display);
|
| 70 |
+
|
| 71 |
+
// Auto-stop at max duration
|
| 72 |
+
if (elapsed >= this.maxDuration) {
|
| 73 |
+
this.stopRecording();
|
| 74 |
+
}
|
| 75 |
+
}, 100);
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
/**
|
| 79 |
+
* Stop recording and return the video blob.
|
| 80 |
+
* @returns {Promise<Blob>} The recorded video blob.
|
| 81 |
+
*/
|
| 82 |
+
stopRecording() {
|
| 83 |
+
return new Promise((resolve) => {
|
| 84 |
+
if (!this.isRecording || !this.mediaRecorder) {
|
| 85 |
+
resolve(null);
|
| 86 |
+
return;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
clearInterval(this.timerInterval);
|
| 90 |
+
|
| 91 |
+
this.mediaRecorder.onstop = () => {
|
| 92 |
+
const blob = new Blob(this.chunks, { type: 'video/webm' });
|
| 93 |
+
this.isRecording = false;
|
| 94 |
+
this.chunks = [];
|
| 95 |
+
resolve(blob);
|
| 96 |
+
};
|
| 97 |
+
|
| 98 |
+
this.mediaRecorder.stop();
|
| 99 |
+
});
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
/**
|
| 103 |
+
* Check if recording duration meets minimum requirement.
|
| 104 |
+
*/
|
| 105 |
+
hasMinDuration() {
|
| 106 |
+
if (!this.isRecording) return false;
|
| 107 |
+
return (Date.now() - this.startTime) >= this.minDuration;
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
/**
|
| 111 |
+
* Stop the camera stream entirely.
|
| 112 |
+
*/
|
| 113 |
+
stopCamera() {
|
| 114 |
+
if (this.stream) {
|
| 115 |
+
this.stream.getTracks().forEach(track => track.stop());
|
| 116 |
+
this.stream = null;
|
| 117 |
+
}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
/**
|
| 121 |
+
* Get the current stream for reuse.
|
| 122 |
+
*/
|
| 123 |
+
getStream() {
|
| 124 |
+
return this.stream;
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
// Export globally
|
| 129 |
+
window.FaceRecorder = FaceRecorder;
|
client/styles.css
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* ── CSS Variables & Design Tokens ───────────────────────────── */
|
| 2 |
+
:root {
|
| 3 |
+
--bg-primary: #0a0a0f;
|
| 4 |
+
--bg-secondary: #12121a;
|
| 5 |
+
--bg-card: rgba(18, 18, 26, 0.85);
|
| 6 |
+
--bg-card-hover: rgba(24, 24, 36, 0.9);
|
| 7 |
+
--border-color: rgba(255, 255, 255, 0.06);
|
| 8 |
+
--border-active: rgba(99, 102, 241, 0.4);
|
| 9 |
+
--text-primary: #f0f0f5;
|
| 10 |
+
--text-secondary: #8b8b9e;
|
| 11 |
+
--text-muted: #5a5a72;
|
| 12 |
+
--accent: #6366f1;
|
| 13 |
+
--accent-glow: rgba(99, 102, 241, 0.25);
|
| 14 |
+
--accent-light: #818cf8;
|
| 15 |
+
--success: #22c55e;
|
| 16 |
+
--success-glow: rgba(34, 197, 94, 0.2);
|
| 17 |
+
--danger: #ef4444;
|
| 18 |
+
--danger-glow: rgba(239, 68, 68, 0.2);
|
| 19 |
+
--warning: #f59e0b;
|
| 20 |
+
--font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
|
| 21 |
+
--radius-sm: 8px;
|
| 22 |
+
--radius-md: 12px;
|
| 23 |
+
--radius-lg: 16px;
|
| 24 |
+
--radius-xl: 20px;
|
| 25 |
+
--shadow-sm: 0 2px 8px rgba(0,0,0,0.2);
|
| 26 |
+
--shadow-md: 0 4px 24px rgba(0,0,0,0.3);
|
| 27 |
+
--shadow-lg: 0 8px 40px rgba(0,0,0,0.4);
|
| 28 |
+
--transition: 0.2s cubic-bezier(0.4, 0, 0.2, 1);
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
/* ── Reset & Base ───────────────────────────────────────────── */
|
| 32 |
+
*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
|
| 33 |
+
|
| 34 |
+
html { font-size: 16px; scroll-behavior: smooth; }
|
| 35 |
+
|
| 36 |
+
body {
|
| 37 |
+
font-family: var(--font-family);
|
| 38 |
+
background: var(--bg-primary);
|
| 39 |
+
color: var(--text-primary);
|
| 40 |
+
min-height: 100vh;
|
| 41 |
+
overflow-x: hidden;
|
| 42 |
+
-webkit-font-smoothing: antialiased;
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
/* ── Background Effects ─────────────────────────────────────── */
|
| 46 |
+
.bg-gradient {
|
| 47 |
+
position: fixed; inset: 0; z-index: 0; pointer-events: none;
|
| 48 |
+
background:
|
| 49 |
+
radial-gradient(ellipse 60% 50% at 20% 10%, rgba(99,102,241,0.08) 0%, transparent 60%),
|
| 50 |
+
radial-gradient(ellipse 40% 40% at 80% 80%, rgba(139,92,246,0.06) 0%, transparent 60%);
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
.bg-grid {
|
| 54 |
+
position: fixed; inset: 0; z-index: 0; pointer-events: none; opacity: 0.03;
|
| 55 |
+
background-image:
|
| 56 |
+
linear-gradient(rgba(255,255,255,0.1) 1px, transparent 1px),
|
| 57 |
+
linear-gradient(90deg, rgba(255,255,255,0.1) 1px, transparent 1px);
|
| 58 |
+
background-size: 60px 60px;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
/* ── App Container ──────────────────────────────────────────── */
|
| 62 |
+
.app-container {
|
| 63 |
+
position: relative; z-index: 1;
|
| 64 |
+
max-width: 960px; margin: 0 auto; padding: 24px 20px;
|
| 65 |
+
min-height: 100vh; display: flex; flex-direction: column;
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
/* ── Header ─────────────────────────────────────────────────── */
|
| 69 |
+
.app-header {
|
| 70 |
+
display: flex; justify-content: space-between; align-items: center;
|
| 71 |
+
padding: 16px 0; margin-bottom: 32px;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
.logo { display: flex; align-items: center; gap: 12px; }
|
| 75 |
+
.logo-icon { width: 36px; height: 36px; color: var(--accent); }
|
| 76 |
+
.logo h1 { font-size: 1.5rem; font-weight: 700; letter-spacing: -0.02em; }
|
| 77 |
+
.accent { color: var(--accent); }
|
| 78 |
+
|
| 79 |
+
.session-info {
|
| 80 |
+
display: flex; align-items: center; gap: 8px;
|
| 81 |
+
font-size: 0.8rem; color: var(--text-secondary);
|
| 82 |
+
background: var(--bg-card); padding: 8px 16px;
|
| 83 |
+
border-radius: var(--radius-lg); border: 1px solid var(--border-color);
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
.status-dot {
|
| 87 |
+
width: 8px; height: 8px; border-radius: 50%;
|
| 88 |
+
background: var(--warning); animation: pulse 2s infinite;
|
| 89 |
+
}
|
| 90 |
+
.status-dot.active { background: var(--success); }
|
| 91 |
+
.status-dot.error { background: var(--danger); }
|
| 92 |
+
|
| 93 |
+
@keyframes pulse {
|
| 94 |
+
0%, 100% { opacity: 1; } 50% { opacity: 0.4; }
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
/* ── Steps Bar ──────────────────────────────────────────────── */
|
| 98 |
+
.steps-bar {
|
| 99 |
+
display: flex; align-items: center; justify-content: center;
|
| 100 |
+
gap: 12px; margin-bottom: 32px;
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
.step {
|
| 104 |
+
display: flex; align-items: center; gap: 8px;
|
| 105 |
+
font-size: 0.85rem; color: var(--text-muted); transition: var(--transition);
|
| 106 |
+
}
|
| 107 |
+
.step.active { color: var(--accent); }
|
| 108 |
+
.step.completed { color: var(--success); }
|
| 109 |
+
|
| 110 |
+
.step-number {
|
| 111 |
+
width: 28px; height: 28px; border-radius: 50%;
|
| 112 |
+
display: flex; align-items: center; justify-content: center;
|
| 113 |
+
font-weight: 600; font-size: 0.75rem;
|
| 114 |
+
border: 2px solid var(--border-color);
|
| 115 |
+
transition: var(--transition);
|
| 116 |
+
}
|
| 117 |
+
.step.active .step-number { border-color: var(--accent); background: var(--accent-glow); color: var(--accent); }
|
| 118 |
+
.step.completed .step-number { border-color: var(--success); background: var(--success-glow); color: var(--success); }
|
| 119 |
+
|
| 120 |
+
.step-line { width: 60px; height: 2px; background: var(--border-color); transition: var(--transition); }
|
| 121 |
+
.step-line.active { background: var(--accent); }
|
| 122 |
+
|
| 123 |
+
/* ── Panels ─────────────────────────────────────────────────── */
|
| 124 |
+
.panel {
|
| 125 |
+
background: var(--bg-card); border: 1px solid var(--border-color);
|
| 126 |
+
border-radius: var(--radius-xl); padding: 32px;
|
| 127 |
+
backdrop-filter: blur(20px); box-shadow: var(--shadow-md);
|
| 128 |
+
animation: fadeIn 0.4s ease;
|
| 129 |
+
}
|
| 130 |
+
.panel.hidden { display: none; }
|
| 131 |
+
|
| 132 |
+
@keyframes fadeIn { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
|
| 133 |
+
|
| 134 |
+
.panel-header { margin-bottom: 24px; }
|
| 135 |
+
.panel-header h2 { font-size: 1.4rem; font-weight: 700; margin-bottom: 6px; }
|
| 136 |
+
.panel-subtitle { color: var(--text-secondary); font-size: 0.875rem; }
|
| 137 |
+
|
| 138 |
+
/* ── Name Input ─────────────────────────────────────────────── */
|
| 139 |
+
.name-input-group { margin-bottom: 20px; }
|
| 140 |
+
.name-input-group label {
|
| 141 |
+
display: block; font-size: 0.8rem; font-weight: 500;
|
| 142 |
+
color: var(--text-secondary); margin-bottom: 6px;
|
| 143 |
+
}
|
| 144 |
+
.name-input-group input {
|
| 145 |
+
width: 100%; padding: 12px 16px;
|
| 146 |
+
background: rgba(255,255,255,0.04); border: 1px solid var(--border-color);
|
| 147 |
+
border-radius: var(--radius-md); color: var(--text-primary);
|
| 148 |
+
font-family: var(--font-family); font-size: 0.95rem;
|
| 149 |
+
transition: var(--transition); outline: none;
|
| 150 |
+
}
|
| 151 |
+
.name-input-group input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-glow); }
|
| 152 |
+
.name-input-group input::placeholder { color: var(--text-muted); }
|
| 153 |
+
|
| 154 |
+
/* ── Tab Switcher ───────────────────────────────────────────── */
|
| 155 |
+
.tab-switcher {
|
| 156 |
+
display: flex; gap: 4px; padding: 4px;
|
| 157 |
+
background: rgba(255,255,255,0.03); border-radius: var(--radius-md);
|
| 158 |
+
margin-bottom: 24px;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
.tab {
|
| 162 |
+
flex: 1; display: flex; align-items: center; justify-content: center; gap: 8px;
|
| 163 |
+
padding: 10px 16px; border: none; border-radius: var(--radius-sm);
|
| 164 |
+
background: transparent; color: var(--text-secondary);
|
| 165 |
+
font-family: var(--font-family); font-size: 0.85rem; font-weight: 500;
|
| 166 |
+
cursor: pointer; transition: var(--transition);
|
| 167 |
+
}
|
| 168 |
+
.tab:hover { color: var(--text-primary); background: rgba(255,255,255,0.04); }
|
| 169 |
+
.tab.active { background: var(--accent); color: white; }
|
| 170 |
+
|
| 171 |
+
/* ── Tab Content ────────────────────────────────────────────── */
|
| 172 |
+
.tab-content { display: none; }
|
| 173 |
+
.tab-content.active { display: block; animation: fadeIn 0.3s ease; }
|
| 174 |
+
|
| 175 |
+
/* ── Video Container ────────────────────────────────────────── */
|
| 176 |
+
.video-container {
|
| 177 |
+
position: relative; border-radius: var(--radius-lg); overflow: hidden;
|
| 178 |
+
background: #000; aspect-ratio: 4/3; margin-bottom: 16px;
|
| 179 |
+
border: 1px solid var(--border-color);
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
.video-container video {
|
| 183 |
+
width: 100%; height: 100%; object-fit: cover; display: block;
|
| 184 |
+
transform: scaleX(-1);
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
.video-overlay {
|
| 188 |
+
position: absolute; inset: 0; pointer-events: none;
|
| 189 |
+
border: 2px solid transparent; border-radius: var(--radius-lg);
|
| 190 |
+
transition: var(--transition);
|
| 191 |
+
}
|
| 192 |
+
.video-overlay.active { border-color: var(--danger); }
|
| 193 |
+
|
| 194 |
+
.scan-line {
|
| 195 |
+
position: absolute; left: 10%; right: 10%; height: 2px;
|
| 196 |
+
background: linear-gradient(90deg, transparent, var(--accent), transparent);
|
| 197 |
+
opacity: 0; animation: none;
|
| 198 |
+
}
|
| 199 |
+
.video-overlay.active .scan-line { opacity: 1; animation: scanDown 2s linear infinite; }
|
| 200 |
+
|
| 201 |
+
@keyframes scanDown {
|
| 202 |
+
0% { top: 10%; } 100% { top: 90%; }
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
.recording-indicator {
|
| 206 |
+
position: absolute; top: 12px; left: 12px;
|
| 207 |
+
display: none; align-items: center; gap: 6px;
|
| 208 |
+
background: rgba(0,0,0,0.7); padding: 6px 12px;
|
| 209 |
+
border-radius: var(--radius-sm); font-size: 0.75rem; font-weight: 600; color: var(--danger);
|
| 210 |
+
}
|
| 211 |
+
.recording-indicator.active { display: flex; }
|
| 212 |
+
|
| 213 |
+
.rec-dot {
|
| 214 |
+
width: 8px; height: 8px; border-radius: 50%;
|
| 215 |
+
background: var(--danger); animation: pulse 1s infinite;
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
/* ── Record Controls ────────────────────────────────────────── */
|
| 219 |
+
.record-controls { text-align: center; }
|
| 220 |
+
|
| 221 |
+
.btn-record {
|
| 222 |
+
display: inline-flex; align-items: center; gap: 10px;
|
| 223 |
+
padding: 14px 28px;
|
| 224 |
+
}
|
| 225 |
+
.btn-record-inner {
|
| 226 |
+
width: 16px; height: 16px; border-radius: 50%;
|
| 227 |
+
background: var(--danger); transition: var(--transition);
|
| 228 |
+
}
|
| 229 |
+
.btn-record.recording .btn-record-inner { border-radius: 3px; width: 14px; height: 14px; }
|
| 230 |
+
|
| 231 |
+
.hint { color: var(--text-muted); font-size: 0.8rem; margin-top: 10px; }
|
| 232 |
+
|
| 233 |
+
/* ── Upload Zone ────────────────────────────────────────────── */
|
| 234 |
+
.upload-zone {
|
| 235 |
+
border: 2px dashed var(--border-color); border-radius: var(--radius-lg);
|
| 236 |
+
padding: 48px 24px; text-align: center; cursor: pointer;
|
| 237 |
+
transition: var(--transition); margin-bottom: 16px;
|
| 238 |
+
}
|
| 239 |
+
.upload-zone:hover, .upload-zone.dragover {
|
| 240 |
+
border-color: var(--accent); background: rgba(99,102,241,0.04);
|
| 241 |
+
}
|
| 242 |
+
.upload-icon { color: var(--text-muted); margin-bottom: 12px; }
|
| 243 |
+
.upload-zone p { font-size: 0.95rem; margin-bottom: 4px; }
|
| 244 |
+
.upload-hint { font-size: 0.8rem; color: var(--text-muted); }
|
| 245 |
+
|
| 246 |
+
.preview-gallery {
|
| 247 |
+
display: grid; grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
|
| 248 |
+
gap: 8px; margin-bottom: 16px;
|
| 249 |
+
}
|
| 250 |
+
.preview-gallery img {
|
| 251 |
+
width: 100%; aspect-ratio: 1; object-fit: cover;
|
| 252 |
+
border-radius: var(--radius-sm); border: 1px solid var(--border-color);
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
/* ── Buttons ────────────────────────────────────────────────── */
|
| 256 |
+
.btn {
|
| 257 |
+
padding: 12px 24px; border: none; border-radius: var(--radius-md);
|
| 258 |
+
font-family: var(--font-family); font-size: 0.9rem; font-weight: 600;
|
| 259 |
+
cursor: pointer; transition: var(--transition); display: inline-flex;
|
| 260 |
+
align-items: center; justify-content: center; gap: 8px;
|
| 261 |
+
}
|
| 262 |
+
.btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
| 263 |
+
|
| 264 |
+
.btn-primary {
|
| 265 |
+
background: var(--accent); color: white; width: 100%;
|
| 266 |
+
}
|
| 267 |
+
.btn-primary:hover:not(:disabled) { background: var(--accent-light); transform: translateY(-1px); box-shadow: 0 4px 16px var(--accent-glow); }
|
| 268 |
+
|
| 269 |
+
.btn-danger { background: rgba(239,68,68,0.12); color: var(--danger); width: 100%; border: 1px solid rgba(239,68,68,0.2); }
|
| 270 |
+
.btn-danger:hover { background: rgba(239,68,68,0.2); }
|
| 271 |
+
|
| 272 |
+
/* ── Processing & Result States ─────────────────────────────── */
|
| 273 |
+
.processing-state, .result-state {
|
| 274 |
+
display: none; flex-direction: column; align-items: center;
|
| 275 |
+
justify-content: center; padding: 40px 20px; text-align: center;
|
| 276 |
+
}
|
| 277 |
+
.processing-state.active, .result-state.active { display: flex; }
|
| 278 |
+
|
| 279 |
+
.spinner {
|
| 280 |
+
width: 40px; height: 40px; border: 3px solid var(--border-color);
|
| 281 |
+
border-top-color: var(--accent); border-radius: 50%;
|
| 282 |
+
animation: spin 0.8s linear infinite; margin-bottom: 16px;
|
| 283 |
+
}
|
| 284 |
+
@keyframes spin { to { transform: rotate(360deg); } }
|
| 285 |
+
|
| 286 |
+
.result-icon {
|
| 287 |
+
width: 56px; height: 56px; border-radius: 50%;
|
| 288 |
+
display: flex; align-items: center; justify-content: center;
|
| 289 |
+
margin-bottom: 16px;
|
| 290 |
+
}
|
| 291 |
+
.result-icon.success { background: var(--success-glow); color: var(--success); }
|
| 292 |
+
.result-icon.error { background: var(--danger-glow); color: var(--danger); }
|
| 293 |
+
.result-detail { color: var(--text-secondary); font-size: 0.85rem; margin: 8px 0 20px; }
|
| 294 |
+
|
| 295 |
+
/* ── Recognition ────────────────────────────────────────────── */
|
| 296 |
+
.recognition-container { display: grid; grid-template-columns: 1fr 280px; gap: 20px; }
|
| 297 |
+
|
| 298 |
+
.recognition-video { aspect-ratio: 4/3; position: relative; }
|
| 299 |
+
.recognition-video canvas {
|
| 300 |
+
position: absolute; inset: 0; width: 100%; height: 100%;
|
| 301 |
+
pointer-events: none;
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
.fps-counter {
|
| 305 |
+
position: absolute; top: 12px; right: 12px;
|
| 306 |
+
background: rgba(0,0,0,0.7); padding: 4px 10px;
|
| 307 |
+
border-radius: var(--radius-sm); font-size: 0.7rem;
|
| 308 |
+
font-weight: 600; color: var(--warning);
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
.recognition-sidebar { display: flex; flex-direction: column; gap: 16px; }
|
| 312 |
+
|
| 313 |
+
.sidebar-card {
|
| 314 |
+
background: rgba(255,255,255,0.03); border: 1px solid var(--border-color);
|
| 315 |
+
border-radius: var(--radius-md); padding: 16px;
|
| 316 |
+
}
|
| 317 |
+
.sidebar-card h3 { font-size: 0.8rem; font-weight: 600; color: var(--text-secondary); margin-bottom: 12px; text-transform: uppercase; letter-spacing: 0.05em; }
|
| 318 |
+
|
| 319 |
+
.detection-log { max-height: 200px; overflow-y: auto; font-size: 0.8rem; }
|
| 320 |
+
.log-placeholder { color: var(--text-muted); font-style: italic; }
|
| 321 |
+
.log-entry { padding: 6px 0; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; }
|
| 322 |
+
.log-entry .name { font-weight: 500; }
|
| 323 |
+
.log-entry .confidence { color: var(--success); font-weight: 600; }
|
| 324 |
+
.log-entry .unknown { color: var(--danger); }
|
| 325 |
+
|
| 326 |
+
.session-details { font-size: 0.85rem; }
|
| 327 |
+
.detail-row { display: flex; justify-content: space-between; padding: 6px 0; border-bottom: 1px solid var(--border-color); }
|
| 328 |
+
.detail-row:last-child { border-bottom: none; }
|
| 329 |
+
.detail-row span:first-child { color: var(--text-secondary); }
|
| 330 |
+
.detail-row span:last-child { font-weight: 500; }
|
| 331 |
+
|
| 332 |
+
/* ── Footer ─────────────────────────────────────────────────── */
|
| 333 |
+
.app-footer {
|
| 334 |
+
margin-top: auto; padding: 24px 0; text-align: center;
|
| 335 |
+
font-size: 0.75rem; color: var(--text-muted);
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
/* ── Responsive ─────────────────────────────────────────────── */
|
| 339 |
+
@media (max-width: 768px) {
|
| 340 |
+
.recognition-container { grid-template-columns: 1fr; }
|
| 341 |
+
.panel { padding: 20px; }
|
| 342 |
+
.app-header { flex-direction: column; gap: 12px; }
|
| 343 |
+
}
|
client/uploader.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* uploader.js - Image upload handler (drag-drop + file picker).
|
| 3 |
+
*
|
| 4 |
+
* Manages the drag-and-drop upload zone and file picker for face images.
|
| 5 |
+
* Validates file types and counts, generates preview thumbnails,
|
| 6 |
+
* and prepares files for upload to the server.
|
| 7 |
+
*/
|
| 8 |
+
|
| 9 |
+
class FaceUploader {
|
| 10 |
+
constructor() {
|
| 11 |
+
this.files = [];
|
| 12 |
+
this.maxFiles = 10;
|
| 13 |
+
this.minFiles = 3;
|
| 14 |
+
this.acceptedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
/**
|
| 18 |
+
* Initialize the upload zone with drag-drop and click handlers.
|
| 19 |
+
* @param {HTMLElement} dropZone - The drop zone element.
|
| 20 |
+
* @param {HTMLInputElement} fileInput - The hidden file input.
|
| 21 |
+
* @param {HTMLElement} gallery - The preview gallery container.
|
| 22 |
+
* @param {Function} onFilesChanged - Callback when files list changes.
|
| 23 |
+
*/
|
| 24 |
+
init(dropZone, fileInput, gallery, onFilesChanged) {
|
| 25 |
+
this.dropZone = dropZone;
|
| 26 |
+
this.fileInput = fileInput;
|
| 27 |
+
this.gallery = gallery;
|
| 28 |
+
this.onFilesChanged = onFilesChanged;
|
| 29 |
+
|
| 30 |
+
// Click to open file picker
|
| 31 |
+
dropZone.addEventListener('click', () => fileInput.click());
|
| 32 |
+
|
| 33 |
+
// File input change
|
| 34 |
+
fileInput.addEventListener('change', (e) => {
|
| 35 |
+
this.addFiles(Array.from(e.target.files));
|
| 36 |
+
fileInput.value = ''; // Reset so same files can be re-selected
|
| 37 |
+
});
|
| 38 |
+
|
| 39 |
+
// Drag events
|
| 40 |
+
dropZone.addEventListener('dragover', (e) => {
|
| 41 |
+
e.preventDefault();
|
| 42 |
+
dropZone.classList.add('dragover');
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
dropZone.addEventListener('dragleave', () => {
|
| 46 |
+
dropZone.classList.remove('dragover');
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
dropZone.addEventListener('drop', (e) => {
|
| 50 |
+
e.preventDefault();
|
| 51 |
+
dropZone.classList.remove('dragover');
|
| 52 |
+
const droppedFiles = Array.from(e.dataTransfer.files);
|
| 53 |
+
this.addFiles(droppedFiles);
|
| 54 |
+
});
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/**
|
| 58 |
+
* Add files to the upload queue, validating type and count.
|
| 59 |
+
* @param {File[]} newFiles
|
| 60 |
+
*/
|
| 61 |
+
addFiles(newFiles) {
|
| 62 |
+
for (const file of newFiles) {
|
| 63 |
+
if (this.files.length >= this.maxFiles) {
|
| 64 |
+
console.warn(`[Uploader] Maximum ${this.maxFiles} files allowed.`);
|
| 65 |
+
break;
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
if (!this.acceptedTypes.includes(file.type)) {
|
| 69 |
+
console.warn(`[Uploader] Rejected file type: ${file.type}`);
|
| 70 |
+
continue;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
this.files.push(file);
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
this.renderPreviews();
|
| 77 |
+
|
| 78 |
+
if (this.onFilesChanged) {
|
| 79 |
+
this.onFilesChanged(this.files);
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
/**
|
| 84 |
+
* Render thumbnail previews of all queued files.
|
| 85 |
+
*/
|
| 86 |
+
renderPreviews() {
|
| 87 |
+
this.gallery.innerHTML = '';
|
| 88 |
+
|
| 89 |
+
this.files.forEach((file, index) => {
|
| 90 |
+
const wrapper = document.createElement('div');
|
| 91 |
+
wrapper.style.position = 'relative';
|
| 92 |
+
|
| 93 |
+
const img = document.createElement('img');
|
| 94 |
+
img.src = URL.createObjectURL(file);
|
| 95 |
+
img.alt = `Face image ${index + 1}`;
|
| 96 |
+
|
| 97 |
+
// Remove button
|
| 98 |
+
const removeBtn = document.createElement('button');
|
| 99 |
+
removeBtn.textContent = '×';
|
| 100 |
+
removeBtn.style.cssText = `
|
| 101 |
+
position: absolute; top: 4px; right: 4px;
|
| 102 |
+
width: 20px; height: 20px; border-radius: 50%;
|
| 103 |
+
background: rgba(239,68,68,0.8); color: white;
|
| 104 |
+
border: none; cursor: pointer; font-size: 14px;
|
| 105 |
+
display: flex; align-items: center; justify-content: center;
|
| 106 |
+
line-height: 1;
|
| 107 |
+
`;
|
| 108 |
+
removeBtn.addEventListener('click', (e) => {
|
| 109 |
+
e.stopPropagation();
|
| 110 |
+
this.removeFile(index);
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
wrapper.appendChild(img);
|
| 114 |
+
wrapper.appendChild(removeBtn);
|
| 115 |
+
this.gallery.appendChild(wrapper);
|
| 116 |
+
});
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
/**
|
| 120 |
+
* Remove a file from the queue by index.
|
| 121 |
+
* @param {number} index
|
| 122 |
+
*/
|
| 123 |
+
removeFile(index) {
|
| 124 |
+
this.files.splice(index, 1);
|
| 125 |
+
this.renderPreviews();
|
| 126 |
+
|
| 127 |
+
if (this.onFilesChanged) {
|
| 128 |
+
this.onFilesChanged(this.files);
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
/**
|
| 133 |
+
* Check if enough files are queued for upload.
|
| 134 |
+
*/
|
| 135 |
+
isReady() {
|
| 136 |
+
return this.files.length >= this.minFiles;
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
/**
|
| 140 |
+
* Get the queued files for upload.
|
| 141 |
+
* @returns {File[]}
|
| 142 |
+
*/
|
| 143 |
+
getFiles() {
|
| 144 |
+
return this.files;
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
/**
|
| 148 |
+
* Clear all queued files.
|
| 149 |
+
*/
|
| 150 |
+
clear() {
|
| 151 |
+
this.files = [];
|
| 152 |
+
this.gallery.innerHTML = '';
|
| 153 |
+
if (this.onFilesChanged) {
|
| 154 |
+
this.onFilesChanged(this.files);
|
| 155 |
+
}
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
// Export globally
|
| 160 |
+
window.FaceUploader = FaceUploader;
|
package.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "face-recognition-web",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"description": "Browser-based real-time face recognition system using FaceNet embeddings",
|
| 5 |
+
"main": "client/index.html",
|
| 6 |
+
"scripts": {
|
| 7 |
+
"start": "cd server && uvicorn app:app --host 0.0.0.0 --port 8000"
|
| 8 |
+
},
|
| 9 |
+
"keywords": [
|
| 10 |
+
"face-recognition",
|
| 11 |
+
"facenet",
|
| 12 |
+
"mtcnn",
|
| 13 |
+
"embeddings",
|
| 14 |
+
"real-time",
|
| 15 |
+
"websocket"
|
| 16 |
+
],
|
| 17 |
+
"author": "",
|
| 18 |
+
"license": "MIT"
|
| 19 |
+
}
|
requirements-hf.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# HF Spaces requirements (torch installed separately in Dockerfile)
|
| 2 |
+
facenet-pytorch>=2.5.2
|
| 3 |
+
opencv-python-headless>=4.5.0
|
| 4 |
+
fastapi>=0.68.0
|
| 5 |
+
uvicorn[standard]>=0.15.0
|
| 6 |
+
python-multipart>=0.0.5
|
| 7 |
+
websockets>=10.0
|
| 8 |
+
numpy>=1.21.0
|
| 9 |
+
scikit-learn>=0.24.0
|
| 10 |
+
Pillow>=8.0
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python (server)
|
| 2 |
+
torch>=1.9.0
|
| 3 |
+
facenet-pytorch>=2.5.2
|
| 4 |
+
opencv-python>=4.5.0
|
| 5 |
+
fastapi>=0.68.0
|
| 6 |
+
uvicorn>=0.15.0
|
| 7 |
+
python-multipart>=0.0.5
|
| 8 |
+
websockets>=10.0
|
| 9 |
+
numpy>=1.21.0
|
| 10 |
+
scikit-learn>=0.24.0
|
| 11 |
+
Pillow>=8.0
|
server/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
server package initializer.
|
| 3 |
+
"""
|
server/app.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app.py - FastAPI entry point and route definitions.
|
| 3 |
+
|
| 4 |
+
Serves the client static files and exposes REST + WebSocket endpoints
|
| 5 |
+
for session management, face registration (video/upload), and
|
| 6 |
+
real-time recognition.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import uuid
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import List
|
| 13 |
+
|
| 14 |
+
from fastapi import FastAPI, File, Form, UploadFile, HTTPException, WebSocket
|
| 15 |
+
from fastapi.staticfiles import StaticFiles
|
| 16 |
+
from fastapi.responses import FileResponse, JSONResponse
|
| 17 |
+
|
| 18 |
+
from server.session_manager import (
|
| 19 |
+
create_session, get_session, get_session_path,
|
| 20 |
+
session_exists, end_session, start_cleanup_daemon, list_active_sessions,
|
| 21 |
+
)
|
| 22 |
+
from server.frame_extractor import extract_frames_from_video
|
| 23 |
+
from server.embedding_generator import process_images_for_embeddings, load_session_embeddings
|
| 24 |
+
from server.websocket_handler import handle_recognition_websocket
|
| 25 |
+
from server.cleanup import register_cleanup_handlers, cleanup_session
|
| 26 |
+
|
| 27 |
+
# ── App Setup ────────────────────────────────────────────────────────
|
| 28 |
+
app = FastAPI(title="Face Recognition Web App", version="1.0.0")
|
| 29 |
+
|
| 30 |
+
# Resolve paths
|
| 31 |
+
SERVER_DIR = Path(__file__).resolve().parent
|
| 32 |
+
PROJECT_DIR = SERVER_DIR.parent
|
| 33 |
+
CLIENT_DIR = PROJECT_DIR / "client"
|
| 34 |
+
|
| 35 |
+
# Serve static client files
|
| 36 |
+
app.mount("/static", StaticFiles(directory=str(CLIENT_DIR)), name="static")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# ── Lifecycle Events ─────────────────────────────────────────────────
|
| 40 |
+
@app.on_event("startup")
|
| 41 |
+
async def startup_event():
|
| 42 |
+
"""Initialize cleanup daemon and register shutdown handlers."""
|
| 43 |
+
register_cleanup_handlers()
|
| 44 |
+
start_cleanup_daemon()
|
| 45 |
+
print("[App] Face Recognition Web App started.")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# ── Client Serving ───────────────────────────────────────────────────
|
| 49 |
+
@app.get("/")
|
| 50 |
+
async def serve_index():
|
| 51 |
+
"""Serve the main HTML page."""
|
| 52 |
+
index_path = CLIENT_DIR / "index.html"
|
| 53 |
+
if not index_path.exists():
|
| 54 |
+
raise HTTPException(status_code=404, detail="Client index.html not found")
|
| 55 |
+
return FileResponse(str(index_path), media_type="text/html")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ── Session Endpoints ────────────────────────────────────────────────
|
| 59 |
+
@app.post("/api/session/start")
|
| 60 |
+
async def start_session():
|
| 61 |
+
"""
|
| 62 |
+
Create a new session.
|
| 63 |
+
Returns: { session_id: str }
|
| 64 |
+
"""
|
| 65 |
+
session = create_session()
|
| 66 |
+
return JSONResponse(content={"session_id": session["session_id"]})
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@app.post("/api/session/end")
|
| 70 |
+
async def end_session_endpoint(session_id: str = Form(...)):
|
| 71 |
+
"""
|
| 72 |
+
Manually end a session and trigger cleanup.
|
| 73 |
+
Uses sendBeacon-compatible form data.
|
| 74 |
+
"""
|
| 75 |
+
result = cleanup_session(session_id)
|
| 76 |
+
return JSONResponse(content={"cleaned": result})
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@app.delete("/api/session/{session_id}")
|
| 80 |
+
async def delete_session(session_id: str):
|
| 81 |
+
"""Fallback cleanup endpoint."""
|
| 82 |
+
result = cleanup_session(session_id)
|
| 83 |
+
if not result:
|
| 84 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 85 |
+
return JSONResponse(content={"cleaned": True})
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@app.get("/api/register/status/{session_id}")
|
| 89 |
+
async def get_registration_status(session_id: str):
|
| 90 |
+
"""
|
| 91 |
+
Check embedding generation status for a session.
|
| 92 |
+
Returns: { status: "processing" | "ready" | "failed" | "no_session" }
|
| 93 |
+
"""
|
| 94 |
+
session_path = get_session_path(session_id)
|
| 95 |
+
if not session_path:
|
| 96 |
+
return JSONResponse(content={"status": "no_session"})
|
| 97 |
+
|
| 98 |
+
embeddings, names = load_session_embeddings(session_path)
|
| 99 |
+
if embeddings is not None and len(embeddings) > 0:
|
| 100 |
+
return JSONResponse(content={
|
| 101 |
+
"status": "ready",
|
| 102 |
+
"embeddings_count": len(names),
|
| 103 |
+
"names": names,
|
| 104 |
+
})
|
| 105 |
+
else:
|
| 106 |
+
return JSONResponse(content={"status": "pending", "embeddings_count": 0})
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# ── Registration Endpoints ───────────────────────────────────────────
|
| 110 |
+
@app.post("/api/register/video")
|
| 111 |
+
async def register_via_video(
|
| 112 |
+
session_id: str = Form(...),
|
| 113 |
+
name: str = Form(...),
|
| 114 |
+
video: UploadFile = File(...)
|
| 115 |
+
):
|
| 116 |
+
"""
|
| 117 |
+
Accept a video blob, extract frames, detect faces, generate embeddings.
|
| 118 |
+
"""
|
| 119 |
+
session_path = get_session_path(session_id)
|
| 120 |
+
if not session_path:
|
| 121 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 122 |
+
|
| 123 |
+
# Read video bytes
|
| 124 |
+
video_bytes = await video.read()
|
| 125 |
+
if not video_bytes:
|
| 126 |
+
raise HTTPException(status_code=400, detail="Empty video file")
|
| 127 |
+
|
| 128 |
+
# Extract frames from video
|
| 129 |
+
frame_paths = extract_frames_from_video(video_bytes, session_path)
|
| 130 |
+
if not frame_paths:
|
| 131 |
+
raise HTTPException(status_code=400, detail="No frames could be extracted from video")
|
| 132 |
+
|
| 133 |
+
# Generate embeddings from extracted frames
|
| 134 |
+
result = process_images_for_embeddings(frame_paths, name, session_path)
|
| 135 |
+
|
| 136 |
+
return JSONResponse(content=result)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@app.post("/api/register/upload")
|
| 140 |
+
async def register_via_upload(
|
| 141 |
+
session_id: str = Form(...),
|
| 142 |
+
name: str = Form(...),
|
| 143 |
+
images: List[UploadFile] = File(...)
|
| 144 |
+
):
|
| 145 |
+
"""
|
| 146 |
+
Accept uploaded face images, detect faces, generate embeddings.
|
| 147 |
+
Maximum 10 images per upload.
|
| 148 |
+
"""
|
| 149 |
+
MAX_UPLOAD_IMAGES = 10
|
| 150 |
+
|
| 151 |
+
session_path = get_session_path(session_id)
|
| 152 |
+
if not session_path:
|
| 153 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 154 |
+
|
| 155 |
+
if len(images) > MAX_UPLOAD_IMAGES:
|
| 156 |
+
raise HTTPException(
|
| 157 |
+
status_code=400,
|
| 158 |
+
detail=f"Maximum {MAX_UPLOAD_IMAGES} images allowed per upload"
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# Save uploaded images to session uploads directory
|
| 162 |
+
uploads_dir = os.path.join(session_path, "uploads")
|
| 163 |
+
os.makedirs(uploads_dir, exist_ok=True)
|
| 164 |
+
|
| 165 |
+
saved_paths = []
|
| 166 |
+
for img_file in images:
|
| 167 |
+
file_ext = os.path.splitext(img_file.filename or "image.jpg")[1] or ".jpg"
|
| 168 |
+
file_name = f"{uuid.uuid4().hex}{file_ext}"
|
| 169 |
+
file_path = os.path.join(uploads_dir, file_name)
|
| 170 |
+
|
| 171 |
+
content = await img_file.read()
|
| 172 |
+
if content:
|
| 173 |
+
with open(file_path, "wb") as f:
|
| 174 |
+
f.write(content)
|
| 175 |
+
saved_paths.append(file_path)
|
| 176 |
+
|
| 177 |
+
if not saved_paths:
|
| 178 |
+
raise HTTPException(status_code=400, detail="No valid images uploaded")
|
| 179 |
+
|
| 180 |
+
# Generate embeddings from uploaded images
|
| 181 |
+
result = process_images_for_embeddings(saved_paths, name, session_path)
|
| 182 |
+
|
| 183 |
+
return JSONResponse(content=result)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# ── WebSocket Recognition Endpoint ──────────────────────────────────
|
| 187 |
+
@app.websocket("/ws/recognize/{session_id}")
|
| 188 |
+
async def websocket_recognize(websocket: WebSocket, session_id: str):
|
| 189 |
+
"""WebSocket endpoint for real-time frame streaming and recognition."""
|
| 190 |
+
await handle_recognition_websocket(websocket, session_id)
|
server/cleanup.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
cleanup.py - Deletion of session directories on disconnect.
|
| 3 |
+
|
| 4 |
+
Provides atexit handlers and utility functions for ensuring
|
| 5 |
+
all session data is purged when appropriate.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import atexit
|
| 9 |
+
from server import session_manager
|
| 10 |
+
from server.embedding_generator import unload_models
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _shutdown_handler():
|
| 14 |
+
"""Handler called on normal Python interpreter exit."""
|
| 15 |
+
print("[Cleanup] Server shutting down — purging all session data...")
|
| 16 |
+
session_manager.stop_cleanup_daemon()
|
| 17 |
+
session_manager.cleanup_all_sessions()
|
| 18 |
+
unload_models()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def register_cleanup_handlers():
|
| 22 |
+
"""
|
| 23 |
+
Register atexit handler for cleanup on shutdown.
|
| 24 |
+
Uvicorn handles SIGINT/SIGTERM natively — we only need atexit.
|
| 25 |
+
"""
|
| 26 |
+
atexit.register(_shutdown_handler)
|
| 27 |
+
print("[Cleanup] Cleanup handlers registered.")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def cleanup_session(session_id: str) -> bool:
|
| 31 |
+
"""
|
| 32 |
+
Clean up a specific session. Called on WebSocket disconnect,
|
| 33 |
+
browser close, or manual session end.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
session_id: The session ID to clean up.
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
True if the session was found and cleaned up, False otherwise.
|
| 40 |
+
"""
|
| 41 |
+
result = session_manager.end_session(session_id)
|
| 42 |
+
if result:
|
| 43 |
+
print(f"[Cleanup] Session {session_id} cleaned up successfully.")
|
| 44 |
+
else:
|
| 45 |
+
print(f"[Cleanup] Session {session_id} not found (may already be cleaned up).")
|
| 46 |
+
return result
|
server/embedding_generator.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
embedding_generator.py - MTCNN face detection + InceptionResnetV1 embedding generation.
|
| 3 |
+
|
| 4 |
+
Detects faces in images using MTCNN, crops and aligns them,
|
| 5 |
+
then generates 512-dimensional embeddings using InceptionResnetV1
|
| 6 |
+
pretrained on VGGFace2.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import pickle
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
from PIL import Image
|
| 14 |
+
from facenet_pytorch import MTCNN, InceptionResnetV1
|
| 15 |
+
|
| 16 |
+
# Configuration
|
| 17 |
+
MIN_FACE_SIZE = 40 # Minimum face bounding box dimension in pixels
|
| 18 |
+
MODEL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
|
| 19 |
+
MODEL_PATH = os.path.join(MODEL_DIR, "inception_resnet_v1_vggface2.pth")
|
| 20 |
+
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 21 |
+
|
| 22 |
+
# Global model instances (loaded once, shared across requests)
|
| 23 |
+
_mtcnn = None
|
| 24 |
+
_resnet = None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _load_models():
|
| 28 |
+
"""Load MTCNN and InceptionResnetV1 models (lazy initialization)."""
|
| 29 |
+
global _mtcnn, _resnet
|
| 30 |
+
|
| 31 |
+
if _mtcnn is None:
|
| 32 |
+
_mtcnn = MTCNN(
|
| 33 |
+
image_size=160,
|
| 34 |
+
margin=20,
|
| 35 |
+
keep_all=True,
|
| 36 |
+
post_process=True,
|
| 37 |
+
min_face_size=MIN_FACE_SIZE,
|
| 38 |
+
device=DEVICE,
|
| 39 |
+
)
|
| 40 |
+
print(f"[EmbeddingGenerator] MTCNN loaded on {DEVICE}")
|
| 41 |
+
|
| 42 |
+
if _resnet is None:
|
| 43 |
+
_resnet = InceptionResnetV1(pretrained=None)
|
| 44 |
+
|
| 45 |
+
if os.path.exists(MODEL_PATH):
|
| 46 |
+
state = torch.load(MODEL_PATH, map_location=DEVICE)
|
| 47 |
+
# Remove logits layer keys if present (transfer learning artifact)
|
| 48 |
+
for k in list(state.keys()):
|
| 49 |
+
if k.startswith("logits."):
|
| 50 |
+
del state[k]
|
| 51 |
+
_resnet.load_state_dict(state, strict=False)
|
| 52 |
+
print(f"[EmbeddingGenerator] InceptionResnetV1 loaded from {MODEL_PATH}")
|
| 53 |
+
else:
|
| 54 |
+
# Fall back to downloading pretrained weights
|
| 55 |
+
_resnet = InceptionResnetV1(pretrained="vggface2")
|
| 56 |
+
print("[EmbeddingGenerator] InceptionResnetV1 loaded with pretrained VGGFace2 weights")
|
| 57 |
+
|
| 58 |
+
_resnet.eval().to(DEVICE)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def l2_normalize(x: np.ndarray) -> np.ndarray:
|
| 62 |
+
"""L2-normalize embedding vectors."""
|
| 63 |
+
norms = np.linalg.norm(x, axis=1, keepdims=True)
|
| 64 |
+
norms[norms == 0] = 1.0
|
| 65 |
+
return x / norms
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def detect_faces(image_path: str) -> tuple:
|
| 69 |
+
"""
|
| 70 |
+
Detect faces in an image using MTCNN.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
image_path: Path to the image file.
|
| 74 |
+
|
| 75 |
+
Returns:
|
| 76 |
+
Tuple of (face_tensors, boxes) where face_tensors is a batch tensor
|
| 77 |
+
of aligned 160x160 face crops, and boxes are the bounding box coordinates.
|
| 78 |
+
"""
|
| 79 |
+
_load_models()
|
| 80 |
+
|
| 81 |
+
img = Image.open(image_path).convert("RGB")
|
| 82 |
+
boxes, _ = _mtcnn.detect(img)
|
| 83 |
+
|
| 84 |
+
if boxes is None:
|
| 85 |
+
return None, None
|
| 86 |
+
|
| 87 |
+
faces = _mtcnn.extract(img, boxes, save_path=None)
|
| 88 |
+
|
| 89 |
+
if isinstance(faces, torch.Tensor):
|
| 90 |
+
if faces.ndim == 3:
|
| 91 |
+
faces = faces.unsqueeze(0)
|
| 92 |
+
if faces.shape[0] > 0:
|
| 93 |
+
return faces, boxes
|
| 94 |
+
|
| 95 |
+
return None, None
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def generate_embeddings(face_tensors: torch.Tensor) -> np.ndarray:
|
| 99 |
+
"""
|
| 100 |
+
Generate 512-dimensional embeddings from face tensors.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
face_tensors: Batch tensor of aligned 160x160 face crops.
|
| 104 |
+
|
| 105 |
+
Returns:
|
| 106 |
+
NumPy array of L2-normalized 512-dim embeddings, shape (N, 512).
|
| 107 |
+
"""
|
| 108 |
+
_load_models()
|
| 109 |
+
|
| 110 |
+
with torch.no_grad():
|
| 111 |
+
embeddings = _resnet(face_tensors.to(DEVICE)).cpu().numpy()
|
| 112 |
+
|
| 113 |
+
return l2_normalize(embeddings)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def process_images_for_embeddings(image_paths: list[str], name: str, session_path: str) -> dict:
|
| 117 |
+
"""
|
| 118 |
+
Process a list of images: detect faces, generate embeddings, average them,
|
| 119 |
+
and store in a session-specific .pkl file.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
image_paths: List of image file paths to process.
|
| 123 |
+
name: Name/label to associate with this face.
|
| 124 |
+
session_path: Path to the session directory.
|
| 125 |
+
|
| 126 |
+
Returns:
|
| 127 |
+
Dict with status, faces_detected count, and embeddings_count.
|
| 128 |
+
"""
|
| 129 |
+
_load_models()
|
| 130 |
+
|
| 131 |
+
all_embeddings = []
|
| 132 |
+
total_faces = 0
|
| 133 |
+
|
| 134 |
+
for img_path in image_paths:
|
| 135 |
+
try:
|
| 136 |
+
faces, boxes = detect_faces(img_path)
|
| 137 |
+
if faces is not None:
|
| 138 |
+
embs = generate_embeddings(faces)
|
| 139 |
+
all_embeddings.append(embs)
|
| 140 |
+
total_faces += len(embs)
|
| 141 |
+
except Exception as e:
|
| 142 |
+
print(f"[EmbeddingGenerator] Error processing {img_path}: {e}")
|
| 143 |
+
continue
|
| 144 |
+
|
| 145 |
+
if not all_embeddings:
|
| 146 |
+
return {
|
| 147 |
+
"status": "failed",
|
| 148 |
+
"message": "No faces detected in any of the provided images.",
|
| 149 |
+
"faces_detected": 0,
|
| 150 |
+
"embeddings_count": 0,
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
# Concatenate all embeddings and compute average
|
| 154 |
+
all_embs = np.vstack(all_embeddings)
|
| 155 |
+
avg_embedding = l2_normalize(np.mean(all_embs, axis=0, keepdims=True))
|
| 156 |
+
|
| 157 |
+
# Save embeddings to session pkl file
|
| 158 |
+
embeddings_path = os.path.join(session_path, "embeddings.pkl")
|
| 159 |
+
|
| 160 |
+
# Load existing embeddings if any
|
| 161 |
+
existing_data = {"embeddings": [], "names": []}
|
| 162 |
+
if os.path.exists(embeddings_path):
|
| 163 |
+
with open(embeddings_path, "rb") as f:
|
| 164 |
+
existing_data = pickle.load(f)
|
| 165 |
+
|
| 166 |
+
# Append new embedding
|
| 167 |
+
if len(existing_data["embeddings"]) == 0:
|
| 168 |
+
existing_data["embeddings"] = avg_embedding
|
| 169 |
+
else:
|
| 170 |
+
existing_data["embeddings"] = np.vstack([existing_data["embeddings"], avg_embedding])
|
| 171 |
+
existing_data["names"].append(name)
|
| 172 |
+
|
| 173 |
+
with open(embeddings_path, "wb") as f:
|
| 174 |
+
pickle.dump(existing_data, f)
|
| 175 |
+
|
| 176 |
+
print(f"[EmbeddingGenerator] Stored embedding for '{name}': "
|
| 177 |
+
f"{total_faces} faces detected, 1 averaged embedding saved.")
|
| 178 |
+
|
| 179 |
+
return {
|
| 180 |
+
"status": "ready",
|
| 181 |
+
"faces_detected": total_faces,
|
| 182 |
+
"embeddings_count": len(existing_data["names"]),
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def load_session_embeddings(session_path: str) -> tuple:
|
| 187 |
+
"""
|
| 188 |
+
Load stored embeddings for a session.
|
| 189 |
+
|
| 190 |
+
Returns:
|
| 191 |
+
Tuple of (embeddings_array, names_list) or (None, None) if not found.
|
| 192 |
+
"""
|
| 193 |
+
embeddings_path = os.path.join(session_path, "embeddings.pkl")
|
| 194 |
+
|
| 195 |
+
if not os.path.exists(embeddings_path):
|
| 196 |
+
return None, None
|
| 197 |
+
|
| 198 |
+
with open(embeddings_path, "rb") as f:
|
| 199 |
+
data = pickle.load(f)
|
| 200 |
+
|
| 201 |
+
embeddings = data.get("embeddings", np.empty((0, 512)))
|
| 202 |
+
names = data.get("names", [])
|
| 203 |
+
|
| 204 |
+
if isinstance(embeddings, list):
|
| 205 |
+
embeddings = np.array(embeddings)
|
| 206 |
+
|
| 207 |
+
return embeddings, names
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def unload_models():
|
| 211 |
+
"""Explicitly release model memory. Called on server shutdown."""
|
| 212 |
+
global _mtcnn, _resnet
|
| 213 |
+
|
| 214 |
+
_mtcnn = None
|
| 215 |
+
_resnet = None
|
| 216 |
+
|
| 217 |
+
# Force garbage collection
|
| 218 |
+
import gc
|
| 219 |
+
gc.collect()
|
| 220 |
+
|
| 221 |
+
# Clear CUDA cache if available
|
| 222 |
+
if torch.cuda.is_available():
|
| 223 |
+
torch.cuda.empty_cache()
|
| 224 |
+
|
| 225 |
+
print("[EmbeddingGenerator] Models unloaded, memory freed.")
|
| 226 |
+
|
server/frame_extractor.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
frame_extractor.py - Extracts frames from uploaded video blobs.
|
| 3 |
+
|
| 4 |
+
Receives a video file, extracts N frames at even intervals using OpenCV,
|
| 5 |
+
and saves them as images in the session's frames/ directory.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import cv2
|
| 10 |
+
import tempfile
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
# Configuration
|
| 14 |
+
MIN_FRAMES = 10
|
| 15 |
+
MAX_FRAMES = 30
|
| 16 |
+
FRAME_INTERVAL = 0.3 # seconds between extracted frames
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def extract_frames_from_video(video_bytes: bytes, session_path: str) -> list[str]:
|
| 20 |
+
"""
|
| 21 |
+
Extract frames from a video blob at even intervals.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
video_bytes: Raw bytes of the uploaded video file.
|
| 25 |
+
session_path: Path to the session directory.
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
List of file paths to the extracted frame images.
|
| 29 |
+
"""
|
| 30 |
+
frames_dir = os.path.join(session_path, "frames")
|
| 31 |
+
os.makedirs(frames_dir, exist_ok=True)
|
| 32 |
+
|
| 33 |
+
# Write video bytes to a temporary file for OpenCV to read
|
| 34 |
+
temp_video_path = os.path.join(session_path, "temp_video.webm")
|
| 35 |
+
try:
|
| 36 |
+
with open(temp_video_path, "wb") as f:
|
| 37 |
+
f.write(video_bytes)
|
| 38 |
+
|
| 39 |
+
cap = cv2.VideoCapture(temp_video_path)
|
| 40 |
+
if not cap.isOpened():
|
| 41 |
+
print("[FrameExtractor] Failed to open video file.")
|
| 42 |
+
return []
|
| 43 |
+
|
| 44 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 45 |
+
if fps <= 0:
|
| 46 |
+
fps = 30.0 # Default fallback for browser-recorded WebM
|
| 47 |
+
|
| 48 |
+
# Calculate frame skip interval based on desired extraction rate
|
| 49 |
+
# Extract approximately 1 frame every FRAME_INTERVAL seconds
|
| 50 |
+
skip_interval = max(1, int(fps * FRAME_INTERVAL))
|
| 51 |
+
|
| 52 |
+
# Read frames sequentially (browser WebM doesn't support seeking)
|
| 53 |
+
all_frames = []
|
| 54 |
+
frame_count = 0
|
| 55 |
+
while True:
|
| 56 |
+
ret, frame = cap.read()
|
| 57 |
+
if not ret:
|
| 58 |
+
break
|
| 59 |
+
|
| 60 |
+
# Only save every Nth frame
|
| 61 |
+
if frame_count % skip_interval == 0:
|
| 62 |
+
frame_path = os.path.join(frames_dir, f"frame_{len(all_frames):04d}.jpg")
|
| 63 |
+
cv2.imwrite(frame_path, frame)
|
| 64 |
+
all_frames.append(frame_path)
|
| 65 |
+
|
| 66 |
+
# Stop once we hit the maximum
|
| 67 |
+
if len(all_frames) >= MAX_FRAMES:
|
| 68 |
+
break
|
| 69 |
+
|
| 70 |
+
frame_count += 1
|
| 71 |
+
|
| 72 |
+
cap.release()
|
| 73 |
+
|
| 74 |
+
print(f"[FrameExtractor] Extracted {len(all_frames)} frames from video "
|
| 75 |
+
f"(total read: {frame_count}, fps: {fps:.1f}, skip: every {skip_interval})")
|
| 76 |
+
|
| 77 |
+
return all_frames
|
| 78 |
+
|
| 79 |
+
finally:
|
| 80 |
+
# Clean up temp video file
|
| 81 |
+
if os.path.exists(temp_video_path):
|
| 82 |
+
os.remove(temp_video_path)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def extract_frames_from_images(image_paths: list[str]) -> list[str]:
|
| 86 |
+
"""
|
| 87 |
+
Validate and return image paths (for the upload path).
|
| 88 |
+
Images are already saved; this just confirms they're valid.
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
image_paths: List of paths to uploaded images.
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
List of valid image file paths.
|
| 95 |
+
"""
|
| 96 |
+
valid_paths = []
|
| 97 |
+
for path in image_paths:
|
| 98 |
+
if os.path.exists(path):
|
| 99 |
+
# Quick validation: try to read the image
|
| 100 |
+
img = cv2.imread(path)
|
| 101 |
+
if img is not None:
|
| 102 |
+
valid_paths.append(path)
|
| 103 |
+
else:
|
| 104 |
+
print(f"[FrameExtractor] Invalid image file skipped: {path}")
|
| 105 |
+
else:
|
| 106 |
+
print(f"[FrameExtractor] File not found: {path}")
|
| 107 |
+
|
| 108 |
+
return valid_paths
|
server/models/.gitkeep
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Place the pretrained model weights file here:
|
| 2 |
+
# inception_resnet_v1_vggface2.pth
|
| 3 |
+
#
|
| 4 |
+
# Download from the Real-Time-Face-Recognition-using-Embeddings repo
|
| 5 |
+
# or generate using the Colab notebook.
|
server/recognition_engine.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
recognition_engine.py - Cosine similarity matching against stored embeddings.
|
| 3 |
+
|
| 4 |
+
Takes a query embedding from a detected face and compares it
|
| 5 |
+
against all stored reference embeddings using cosine similarity.
|
| 6 |
+
Returns the best match label and confidence score.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 11 |
+
|
| 12 |
+
# Configuration
|
| 13 |
+
THRESHOLD = 0.65 # Cosine similarity cutoff for positive match
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def find_best_match(query_embedding: np.ndarray, db_embeddings: np.ndarray,
|
| 17 |
+
db_names: list, threshold: float = THRESHOLD) -> tuple:
|
| 18 |
+
"""
|
| 19 |
+
Find the best matching identity for a query embedding.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
query_embedding: 512-dim embedding vector of the query face.
|
| 23 |
+
db_embeddings: Array of stored reference embeddings, shape (N, 512).
|
| 24 |
+
db_names: List of names corresponding to each stored embedding.
|
| 25 |
+
threshold: Minimum cosine similarity for a positive match.
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
Tuple of (name, confidence_score). Returns ("Unknown", score) if below threshold.
|
| 29 |
+
"""
|
| 30 |
+
if db_embeddings is None or len(db_embeddings) == 0 or len(db_names) == 0:
|
| 31 |
+
return "Unknown", 0.0
|
| 32 |
+
|
| 33 |
+
# Ensure query is 2D for cosine_similarity
|
| 34 |
+
if query_embedding.ndim == 1:
|
| 35 |
+
query_embedding = query_embedding.reshape(1, -1)
|
| 36 |
+
|
| 37 |
+
sims = cosine_similarity(query_embedding, db_embeddings)[0]
|
| 38 |
+
best_idx = int(np.argmax(sims))
|
| 39 |
+
best_score = float(sims[best_idx])
|
| 40 |
+
|
| 41 |
+
if best_score >= threshold:
|
| 42 |
+
return str(db_names[best_idx]), best_score
|
| 43 |
+
else:
|
| 44 |
+
return "Unknown", best_score
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def recognize_faces(face_embeddings: np.ndarray, db_embeddings: np.ndarray,
|
| 48 |
+
db_names: list, boxes: np.ndarray,
|
| 49 |
+
threshold: float = THRESHOLD) -> list[dict]:
|
| 50 |
+
"""
|
| 51 |
+
Recognize multiple faces in a single frame.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
face_embeddings: Array of query embeddings, shape (M, 512).
|
| 55 |
+
db_embeddings: Array of stored reference embeddings, shape (N, 512).
|
| 56 |
+
db_names: List of names for each stored embedding.
|
| 57 |
+
boxes: Bounding box coordinates for each detected face, shape (M, 4).
|
| 58 |
+
threshold: Cosine similarity threshold for positive match.
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
List of dicts, each containing:
|
| 62 |
+
- "box": [x1, y1, x2, y2] bounding box coordinates
|
| 63 |
+
- "label": Recognized name or "Unknown"
|
| 64 |
+
- "confidence": Similarity score as float
|
| 65 |
+
"""
|
| 66 |
+
results = []
|
| 67 |
+
|
| 68 |
+
for i, emb in enumerate(face_embeddings):
|
| 69 |
+
name, score = find_best_match(emb, db_embeddings, db_names, threshold)
|
| 70 |
+
|
| 71 |
+
box = boxes[i].tolist() if hasattr(boxes[i], 'tolist') else list(boxes[i])
|
| 72 |
+
|
| 73 |
+
results.append({
|
| 74 |
+
"box": [int(coord) for coord in box],
|
| 75 |
+
"label": name,
|
| 76 |
+
"confidence": round(score, 4),
|
| 77 |
+
})
|
| 78 |
+
|
| 79 |
+
return results
|
server/session_manager.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
session_manager.py - Session creation, tracking, and cleanup logic.
|
| 3 |
+
|
| 4 |
+
Manages unique session IDs, creates per-session temp directories,
|
| 5 |
+
tracks active sessions, and triggers cleanup on disconnect/close.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
import uuid
|
| 10 |
+
import time
|
| 11 |
+
import shutil
|
| 12 |
+
import threading
|
| 13 |
+
import platform
|
| 14 |
+
|
| 15 |
+
# Base directory for all session temp storage
|
| 16 |
+
# On Linux/Docker (HF Spaces): use /tmp/sessions (always writable)
|
| 17 |
+
# On Windows (local dev): use project-relative tmp/sessions
|
| 18 |
+
if platform.system() == "Windows":
|
| 19 |
+
BASE_SESSION_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "tmp", "sessions")
|
| 20 |
+
else:
|
| 21 |
+
BASE_SESSION_DIR = "/tmp/sessions"
|
| 22 |
+
|
| 23 |
+
# Configuration
|
| 24 |
+
SESSION_TTL = 900 # 15 minutes of inactivity before auto-cleanup
|
| 25 |
+
|
| 26 |
+
# Active sessions tracker: { session_id: { "created_at": float, "last_active": float, "path": str } }
|
| 27 |
+
_active_sessions = {}
|
| 28 |
+
_lock = threading.Lock()
|
| 29 |
+
_cleanup_thread = None
|
| 30 |
+
_running = False
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _ensure_base_dir():
|
| 34 |
+
"""Ensure the base session directory exists."""
|
| 35 |
+
os.makedirs(BASE_SESSION_DIR, exist_ok=True)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def create_session() -> dict:
|
| 39 |
+
"""
|
| 40 |
+
Create a new session with a unique ID and its directory structure.
|
| 41 |
+
Returns dict with session_id and path information.
|
| 42 |
+
"""
|
| 43 |
+
_ensure_base_dir()
|
| 44 |
+
|
| 45 |
+
session_id = str(uuid.uuid4())
|
| 46 |
+
session_path = os.path.join(BASE_SESSION_DIR, session_id)
|
| 47 |
+
|
| 48 |
+
# Create session subdirectories
|
| 49 |
+
os.makedirs(os.path.join(session_path, "frames"), exist_ok=True)
|
| 50 |
+
os.makedirs(os.path.join(session_path, "uploads"), exist_ok=True)
|
| 51 |
+
|
| 52 |
+
now = time.time()
|
| 53 |
+
session_info = {
|
| 54 |
+
"session_id": session_id,
|
| 55 |
+
"created_at": now,
|
| 56 |
+
"last_active": now,
|
| 57 |
+
"path": session_path,
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
with _lock:
|
| 61 |
+
_active_sessions[session_id] = session_info
|
| 62 |
+
|
| 63 |
+
return {"session_id": session_id, "path": session_path}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_session(session_id: str) -> dict | None:
|
| 67 |
+
"""Retrieve session info and update last_active timestamp."""
|
| 68 |
+
with _lock:
|
| 69 |
+
session = _active_sessions.get(session_id)
|
| 70 |
+
if session:
|
| 71 |
+
session["last_active"] = time.time()
|
| 72 |
+
return session.copy()
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def get_session_path(session_id: str) -> str | None:
|
| 77 |
+
"""Get the filesystem path for a session."""
|
| 78 |
+
session = get_session(session_id)
|
| 79 |
+
if session:
|
| 80 |
+
return session["path"]
|
| 81 |
+
return None
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def session_exists(session_id: str) -> bool:
|
| 85 |
+
"""Check if a session ID is active."""
|
| 86 |
+
with _lock:
|
| 87 |
+
return session_id in _active_sessions
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def end_session(session_id: str) -> bool:
|
| 91 |
+
"""
|
| 92 |
+
End a session and delete all associated data.
|
| 93 |
+
Returns True if the session was found and cleaned up.
|
| 94 |
+
"""
|
| 95 |
+
with _lock:
|
| 96 |
+
session = _active_sessions.pop(session_id, None)
|
| 97 |
+
|
| 98 |
+
if session:
|
| 99 |
+
_delete_session_dir(session["path"])
|
| 100 |
+
return True
|
| 101 |
+
return False
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _delete_session_dir(session_path: str):
|
| 105 |
+
"""Safely delete a session directory and all its contents."""
|
| 106 |
+
try:
|
| 107 |
+
if os.path.exists(session_path):
|
| 108 |
+
shutil.rmtree(session_path)
|
| 109 |
+
print(f"[SessionManager] Cleaned up session directory: {session_path}")
|
| 110 |
+
except Exception as e:
|
| 111 |
+
print(f"[SessionManager] Error cleaning up {session_path}: {e}")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _cleanup_expired_sessions():
|
| 115 |
+
"""Remove sessions that have exceeded the TTL."""
|
| 116 |
+
now = time.time()
|
| 117 |
+
expired = []
|
| 118 |
+
|
| 119 |
+
with _lock:
|
| 120 |
+
for sid, info in _active_sessions.items():
|
| 121 |
+
if now - info["last_active"] > SESSION_TTL:
|
| 122 |
+
expired.append((sid, info["path"]))
|
| 123 |
+
|
| 124 |
+
for sid, _ in expired:
|
| 125 |
+
del _active_sessions[sid]
|
| 126 |
+
|
| 127 |
+
for sid, path in expired:
|
| 128 |
+
_delete_session_dir(path)
|
| 129 |
+
print(f"[SessionManager] Expired session cleaned up: {sid}")
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _cleanup_loop():
|
| 133 |
+
"""Background thread that periodically checks for expired sessions."""
|
| 134 |
+
global _running
|
| 135 |
+
while _running:
|
| 136 |
+
time.sleep(60) # Check every 60 seconds
|
| 137 |
+
_cleanup_expired_sessions()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def start_cleanup_daemon():
|
| 141 |
+
"""Start the background cleanup daemon thread."""
|
| 142 |
+
global _cleanup_thread, _running
|
| 143 |
+
if _cleanup_thread is None or not _cleanup_thread.is_alive():
|
| 144 |
+
_running = True
|
| 145 |
+
_cleanup_thread = threading.Thread(target=_cleanup_loop, daemon=True)
|
| 146 |
+
_cleanup_thread.start()
|
| 147 |
+
print("[SessionManager] Cleanup daemon started.")
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def stop_cleanup_daemon():
|
| 151 |
+
"""Stop the background cleanup daemon."""
|
| 152 |
+
global _running
|
| 153 |
+
_running = False
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def cleanup_all_sessions():
|
| 157 |
+
"""
|
| 158 |
+
Purge ALL active sessions. Called on server shutdown.
|
| 159 |
+
"""
|
| 160 |
+
with _lock:
|
| 161 |
+
sessions = list(_active_sessions.items())
|
| 162 |
+
_active_sessions.clear()
|
| 163 |
+
|
| 164 |
+
for sid, info in sessions:
|
| 165 |
+
_delete_session_dir(info["path"])
|
| 166 |
+
|
| 167 |
+
# Also clean up the entire sessions directory as a safety net
|
| 168 |
+
try:
|
| 169 |
+
if os.path.exists(BASE_SESSION_DIR):
|
| 170 |
+
shutil.rmtree(BASE_SESSION_DIR)
|
| 171 |
+
print("[SessionManager] All session data purged on shutdown.")
|
| 172 |
+
except Exception as e:
|
| 173 |
+
print(f"[SessionManager] Error during full purge: {e}")
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def list_active_sessions() -> list:
|
| 177 |
+
"""Return a list of active session IDs."""
|
| 178 |
+
with _lock:
|
| 179 |
+
return list(_active_sessions.keys())
|
server/websocket_handler.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
websocket_handler.py - WebSocket connection for real-time frame streaming.
|
| 3 |
+
|
| 4 |
+
Handles the WebSocket endpoint for streaming webcam frames from the browser
|
| 5 |
+
to the server, running face detection + recognition on each frame,
|
| 6 |
+
and sending annotated results back to the client.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import asyncio
|
| 10 |
+
import base64
|
| 11 |
+
import io
|
| 12 |
+
import numpy as np
|
| 13 |
+
import torch
|
| 14 |
+
from PIL import Image
|
| 15 |
+
from fastapi import WebSocket, WebSocketDisconnect
|
| 16 |
+
|
| 17 |
+
from server import session_manager
|
| 18 |
+
from server import embedding_generator
|
| 19 |
+
from server import recognition_engine
|
| 20 |
+
|
| 21 |
+
# Configuration
|
| 22 |
+
WS_FRAME_RATE = 5 # Target FPS for recognition processing
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _process_frame(frame_data: bytes, db_embeddings, db_names) -> dict:
|
| 26 |
+
"""
|
| 27 |
+
Process a single frame synchronously (runs in thread pool).
|
| 28 |
+
Detects faces, generates embeddings, and matches against stored data.
|
| 29 |
+
"""
|
| 30 |
+
try:
|
| 31 |
+
image = Image.open(io.BytesIO(frame_data)).convert("RGB")
|
| 32 |
+
|
| 33 |
+
# Ensure models are loaded
|
| 34 |
+
embedding_generator._load_models()
|
| 35 |
+
|
| 36 |
+
boxes, _ = embedding_generator._mtcnn.detect(image)
|
| 37 |
+
|
| 38 |
+
if boxes is not None:
|
| 39 |
+
faces = embedding_generator._mtcnn.extract(image, boxes, save_path=None)
|
| 40 |
+
|
| 41 |
+
if isinstance(faces, torch.Tensor):
|
| 42 |
+
if faces.ndim == 3:
|
| 43 |
+
faces = faces.unsqueeze(0)
|
| 44 |
+
|
| 45 |
+
if faces.shape[0] > 0:
|
| 46 |
+
query_embeddings = embedding_generator.generate_embeddings(faces)
|
| 47 |
+
|
| 48 |
+
results = recognition_engine.recognize_faces(
|
| 49 |
+
query_embeddings, db_embeddings, db_names, boxes
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
return {"faces": results}
|
| 53 |
+
|
| 54 |
+
return {"faces": []}
|
| 55 |
+
|
| 56 |
+
except Exception as e:
|
| 57 |
+
return {"faces": [], "error": str(e)}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
async def handle_recognition_websocket(websocket: WebSocket, session_id: str):
|
| 61 |
+
"""
|
| 62 |
+
Handle a WebSocket connection for real-time face recognition.
|
| 63 |
+
|
| 64 |
+
Protocol:
|
| 65 |
+
- Client sends frames as base64-encoded JPEG/PNG images.
|
| 66 |
+
- Server responds with JSON containing detected faces, labels, and confidence.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
websocket: The FastAPI WebSocket connection.
|
| 70 |
+
session_id: The session ID to use for loading stored embeddings.
|
| 71 |
+
"""
|
| 72 |
+
await websocket.accept()
|
| 73 |
+
|
| 74 |
+
# Validate session exists
|
| 75 |
+
session_path = session_manager.get_session_path(session_id)
|
| 76 |
+
if not session_path:
|
| 77 |
+
await websocket.send_json({"error": "Invalid session ID"})
|
| 78 |
+
await websocket.close()
|
| 79 |
+
return
|
| 80 |
+
|
| 81 |
+
# Load stored embeddings for this session (run in thread to avoid blocking)
|
| 82 |
+
loop = asyncio.get_event_loop()
|
| 83 |
+
db_embeddings, db_names = await loop.run_in_executor(
|
| 84 |
+
None, embedding_generator.load_session_embeddings, session_path
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
if db_embeddings is None or len(db_embeddings) == 0:
|
| 88 |
+
await websocket.send_json({"error": "No embeddings found. Please register a face first."})
|
| 89 |
+
await websocket.close()
|
| 90 |
+
return
|
| 91 |
+
|
| 92 |
+
# Pre-load models in background thread so first frame isn't slow
|
| 93 |
+
await loop.run_in_executor(None, embedding_generator._load_models)
|
| 94 |
+
|
| 95 |
+
print(f"[WebSocket] Recognition session started for {session_id} "
|
| 96 |
+
f"with {len(db_names)} registered face(s).")
|
| 97 |
+
|
| 98 |
+
# Send ready signal to client
|
| 99 |
+
await websocket.send_json({"status": "ready", "registered": len(db_names)})
|
| 100 |
+
|
| 101 |
+
try:
|
| 102 |
+
while True:
|
| 103 |
+
# Receive frame data from client
|
| 104 |
+
data = await websocket.receive_text()
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
frame_data = base64.b64decode(data)
|
| 108 |
+
|
| 109 |
+
# Run face detection + recognition in thread pool
|
| 110 |
+
# to avoid blocking the async event loop
|
| 111 |
+
result = await loop.run_in_executor(
|
| 112 |
+
None, _process_frame, frame_data, db_embeddings, db_names
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
await websocket.send_json(result)
|
| 116 |
+
|
| 117 |
+
except Exception as e:
|
| 118 |
+
print(f"[WebSocket] Frame processing error: {e}")
|
| 119 |
+
await websocket.send_json({"faces": [], "error": str(e)})
|
| 120 |
+
|
| 121 |
+
except WebSocketDisconnect:
|
| 122 |
+
print(f"[WebSocket] Client disconnected: {session_id}")
|
| 123 |
+
except Exception as e:
|
| 124 |
+
print(f"[WebSocket] Connection error: {e}")
|
| 125 |
+
finally:
|
| 126 |
+
print(f"[WebSocket] Session {session_id} WebSocket closed.")
|