Hkoradiya123 commited on
Commit
4854e2b
·
1 Parent(s): 74b3593

feat: Initialize frontend with Zustand for state management, Tailwind CSS for styling, and TypeScript for type safety

Browse files

- Added Zustand store for authentication, face embeddings, admin management, and user API keys.
- Implemented global styles using Tailwind CSS.
- Defined TypeScript types for user, tenant, face embeddings, and API responses.
- Configured Vite for development and build processes.
- Created a PowerShell script for environment setup with prompts for necessary configurations.

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +0 -35
  2. .gitignore +53 -0
  3. Dockerfile +0 -39
  4. README.md +469 -15
  5. backend/.env.example +42 -0
  6. backend/.gitattributes +35 -0
  7. backend/.gitignore +139 -0
  8. backend/API_EXAMPLES.md +315 -0
  9. backend/Dockerfile +46 -0
  10. backend/QUICK_START.md +243 -0
  11. backend/alembic.ini +36 -0
  12. app.py → backend/app.py +227 -227
  13. backend/app/__init__.py +1 -0
  14. backend/app/api/__init__.py +1 -0
  15. backend/app/api/admin_routes.py +237 -0
  16. backend/app/api/api_key_routes.py +73 -0
  17. backend/app/api/auth_routes.py +139 -0
  18. backend/app/api/external_routes.py +122 -0
  19. backend/app/api/face_routes.py +352 -0
  20. backend/app/api/webhook_routes.py +52 -0
  21. backend/app/core/__init__.py +1 -0
  22. backend/app/core/config.py +105 -0
  23. backend/app/core/database.py +59 -0
  24. backend/app/core/middleware.py +54 -0
  25. backend/app/core/rate_limit.py +26 -0
  26. backend/app/core/security.py +124 -0
  27. backend/app/main.py +133 -0
  28. backend/app/models/__init__.py +257 -0
  29. backend/app/schemas/__init__.py +234 -0
  30. backend/app/services/__init__.py +1 -0
  31. backend/app/services/api_key_service.py +110 -0
  32. backend/app/services/auth_service.py +181 -0
  33. backend/app/services/billing_service.py +63 -0
  34. backend/app/services/qdrant_service.py +119 -0
  35. backend/app/services/recognition_service.py +376 -0
  36. backend/app/services/webhook_service.py +86 -0
  37. backend/app/utils/__init__.py +1 -0
  38. backend/app/utils/common.py +208 -0
  39. backend/app/workers/__init__.py +1 -0
  40. backend/app/workers/celery_app.py +18 -0
  41. backend/app/workers/tasks.py +66 -0
  42. backend/conftest.py +66 -0
  43. backend/docker-compose.yml +123 -0
  44. backend/init_app.py +81 -0
  45. backend/insightface-0.7.3.tar.gz +3 -0
  46. backend/insightface-0.7.3/PKG-INFO +265 -0
  47. backend/insightface-0.7.3/README.md +153 -0
  48. backend/insightface-0.7.3/insightface/__init__.py +21 -0
  49. backend/insightface-0.7.3/insightface/app/__init__.py +2 -0
  50. backend/insightface-0.7.3/insightface/app/common.py +49 -0
.gitattributes CHANGED
@@ -1,36 +1 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  backend/insightface-0.7.3/insightface/data/images/* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  backend/insightface-0.7.3/insightface/data/images/* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Node / frontend
2
+ node_modules/
3
+ dist/
4
+ frontend/node_modules/
5
+ frontend/dist/
6
+
7
+ # Python / backend
8
+ __pycache__/
9
+ *.py[cod]
10
+ *.so
11
+ .venv/
12
+ venv/
13
+ env/
14
+ ENV/
15
+ backend/.venv/
16
+ backend/venv/
17
+ backend/env/
18
+ backend/ENV/
19
+ .pytest_cache/
20
+ .mypy_cache/
21
+ .coverage
22
+ htmlcov/
23
+
24
+ # Environment files
25
+ .env
26
+ .env.local
27
+ .env.*.local
28
+ backend/.env
29
+ backend/.env.local
30
+ backend/.env.*.local
31
+ frontend/.env
32
+ frontend/.env.local
33
+ frontend/.env.*.local
34
+
35
+ # Logs
36
+ *.log
37
+
38
+ # OS / editor
39
+ .DS_Store
40
+ Thumbs.db
41
+ .vscode/
42
+ .idea/
43
+ *.swp
44
+ *.swo
45
+ *~
46
+
47
+ # Project-specific runtime artifacts
48
+ /uploads/
49
+ /downloads/
50
+ /models/
51
+ *.db
52
+ *.sqlite
53
+ *.sqlite-journal
Dockerfile DELETED
@@ -1,39 +0,0 @@
1
- FROM python:3.10
2
-
3
- WORKDIR /app
4
-
5
- # Install system dependencies for opencv and insightface
6
- RUN apt-get update && apt-get install -y \
7
- libsm6 \
8
- libxext6 \
9
- libxrender-dev \
10
- libgomp1 \
11
- libgl1 \
12
- libglib2.0-0 \
13
- curl \
14
- && rm -rf /var/lib/apt/lists/*
15
-
16
- # Upgrade pip
17
- RUN pip install --upgrade pip setuptools wheel
18
-
19
- # Copy requirements and install Python packages
20
- COPY requirements.txt .
21
- RUN pip install --no-cache-dir -r requirements.txt
22
-
23
- # Copy application code
24
- COPY app.py .
25
- COPY static/ ./static/
26
-
27
- # Set environment variables
28
- ENV FACE_RECOGNITION_MODEL="buffalo_l"
29
- ENV PORT=7860
30
-
31
- # Expose port
32
- EXPOSE 7860
33
-
34
- # Health check using curl
35
- HEALTHCHECK --interval=30s --timeout=10s --start-period=180s --retries=3 \
36
- CMD curl -f http://localhost:7860/health || exit 1
37
-
38
- # Run application
39
- CMD ["python", "app.py"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,23 +1,477 @@
1
- ---
2
- title: Face Inference Service
3
- emoji: 👤
4
- colorFrom: blue
5
- colorTo: purple
6
- sdk: docker
7
- app_file: app.py
8
- pinned: false
9
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- # Face Inference Service
12
 
13
- A lightweight FastAPI service for face detection and recognition using InsightFace.
 
 
 
 
14
 
15
- ## Deployment on Hugging Face Spaces
 
 
 
 
 
16
 
17
- ### Option 1: Docker (Recommended)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- 1. Create a **new Space** on Hugging Face:
20
- - Go to https://huggingface.co/new-space
21
  - Name: `face-inference-service`
22
  - Space SDK: **Docker**
23
  - License: MIT
 
1
+ # Face Inference SaaS Platform
2
+
3
+ A production-grade **multi-tenant face recognition API platform** built with FastAPI, InsightFace, and MySQL.
4
+
5
+ ## UI Preview
6
+
7
+ The current frontend runs at `http://localhost:3000`.
8
+
9
+ ### Screens
10
+
11
+ - Dashboard: `http://localhost:3000/dashboard`
12
+ - Billing and payment settings: `http://localhost:3000/billing`
13
+ - Product docs: `http://localhost:3000/docs`
14
+
15
+ ### Notes
16
+
17
+ - The dashboard uses a compact profile menu for docs, billing, API keys, admin access, and logout.
18
+ - Billing is usage-based today: API calls and successful recognitions are metered per tenant and user.
19
+ - The billing page stores payment preferences locally for now and is ready to be connected to a real payment provider later.
20
+
21
+ ## 🎯 Features
22
+
23
+ ### Core Capabilities
24
+ - **Multi-tenant Architecture**: Complete data isolation between customers
25
+ - **Face Registration**: Register faces from exactly 3 single-person, different-angle images
26
+ - **Face Recognition**: Real-time face recognition from single frames or video streams
27
+ - **Secure APIs**: JWT authentication with role-based access control
28
+ - **Scalable**: Designed for horizontal scaling with Docker & Kubernetes
29
+
30
+ ### Security
31
+ - Multi-tenant data isolation at database level
32
+ - JWT access & refresh tokens
33
+ - Role-based access control (ADMIN/USER)
34
+ - Encrypted embeddings
35
+ - Rate limiting & request validation
36
+ - CORS protection
37
+
38
+ ### Advanced Features
39
+ - Face quality validation
40
+ - Duplicate face detection
41
+ - Recognition confidence scores
42
+ - Bounding box detection
43
+ - Analytics & monitoring
44
+ - Admin dashboard capabilities
45
+
46
+ ## 🏗️ Architecture
47
+
48
+ ```
49
+ ├── app/
50
+ │ ├── main.py # FastAPI application entry
51
+ │ ├── core/ # Core configuration & security
52
+ │ │ ├── config.py # Settings & environment
53
+ │ │ ├── database.py # SQLAlchemy & session management
54
+ │ │ ├── security.py # JWT & authentication utilities
55
+ │ │ └── middleware.py # Multi-tenant middleware
56
+ │ ├── models/ # SQLAlchemy ORM models
57
+ │ │ └── __init__.py # Tenant, User, FaceEmbedding, etc.
58
+ │ ├── schemas/ # Pydantic request/response schemas
59
+ │ ├── services/ # Business logic
60
+ │ │ ├── auth_service.py
61
+ │ │ └── recognition_service.py
62
+ │ ├── api/ # API routes
63
+ │ │ ├── auth_routes.py
64
+ │ │ ├── face_routes.py
65
+ │ │ └── admin_routes.py
66
+ │ └── utils/ # Utilities
67
+ │ └── common.py # Image processing, face detection
68
+ ├── docker-compose.yml # Local development stack
69
+ ├── Dockerfile # Multi-stage production build
70
+ ├── requirements.txt # Python dependencies
71
+ └── .env.example # Environment template
72
+ ```
73
+
74
+ ## 🚀 Quick Start
75
+
76
+ ### Prerequisites
77
+ - Docker & Docker Compose (recommended)
78
+ - Python 3.11+ (for local development)
79
+ - MySQL 8+
80
+ - Redis 7+
81
+
82
+ ### Option 1: Docker Compose (Recommended)
83
+
84
+ ```bash
85
+ # Clone the repository
86
+ git clone <repository-url>
87
+ cd fmproService
88
+
89
+ # Copy environment template
90
+ cp .env.example .env
91
+
92
+ # Start all services
93
+ docker-compose up -d
94
+
95
+ # Check service health
96
+ curl http://localhost/health
97
+
98
+ # View API docs
99
+ open http://localhost/docs
100
+ ```
101
+
102
+ This starts:
103
+ - MySQL database
104
+ - Redis cache
105
+ - MinIO S3 storage
106
+ - FastAPI backend
107
+ - Nginx reverse proxy
108
+
109
+ ### Option 2: Local Development
110
+
111
+ ```bash
112
+ # Create virtual environment
113
+ python -m venv venv
114
+ source venv/bin/activate # Windows: venv\Scripts\activate
115
+
116
+ # Install dependencies
117
+ pip install -r requirements.txt
118
+
119
+ # Configure environment
120
+ cp .env.example .env
121
+ # Edit .env with your local database URL
122
+
123
+ # Run migrations
124
+ alembic upgrade head
125
+
126
+ # Start development server
127
+ uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
128
+
129
+ # API docs available at: http://localhost:8000/docs
130
+ ```
131
 
132
+ ## 📡 API Endpoints
133
 
134
+ ### Authentication
135
+ - `POST /api/auth/register` - Register new user & tenant
136
+ - `POST /api/auth/login` - Login (JWT)
137
+ - `POST /api/auth/refresh` - Refresh access token
138
+ - `GET /api/auth/me` - Get current user
139
 
140
+ ### Face Operations
141
+ - `POST /api/face/register` - Register face from exactly 3 images & generate detailed embedding
142
+ - `POST /api/face/recognize` - Recognize faces in image
143
+ - `GET /api/face/embeddings` - List registered embeddings
144
+ - `GET /api/face/logs` - Get recognition logs
145
+ - `DELETE /api/face/embeddings/{embedding_id}` - Delete embedding
146
 
147
+ ### Admin
148
+ - `GET /api/admin/analytics` - Platform analytics
149
+ - `GET /api/admin/users` - List all users
150
+ - `DELETE /api/admin/users/{user_id}` - Delete user
151
+ - `POST /api/admin/api-keys` - Create third-party API key
152
+
153
+ ### Third-Party API
154
+ - `POST /api/v1/faces/register` - Register face with `X-API-Key`
155
+ - `POST /api/v1/faces/recognize` - Recognize faces with `X-API-Key`
156
+
157
+ ## Billing and Payments
158
+
159
+ Billing is currently usage-metered and exposed in the admin APIs and the frontend billing page.
160
+
161
+ - `GET /api/admin/usage?period=YYYY-MM` - Get monthly usage for the tenant
162
+ - `successful_recognitions` - Counted when a recognition matches a known face
163
+ - `api_calls` - Counted on each face register and recognize request
164
+
165
+ The frontend billing page is available at:
166
+
167
+ - `http://localhost:3000/billing`
168
+
169
+ It includes:
170
+
171
+ - billing profile fields
172
+ - payment method label
173
+ - invoice address
174
+ - auto-renew toggle
175
+ - monthly usage summary for admins
176
+
177
+ ## UI Screenshots
178
+
179
+ Use these live routes as the source of the current screenshots when capturing the UI for documentation:
180
+
181
+ ```text
182
+ http://localhost:3000/dashboard
183
+ http://localhost:3000/billing
184
+ http://localhost:3000/docs
185
+ ```
186
+
187
+ Recommended capture list:
188
+
189
+ - Dashboard header and profile menu
190
+ - Billing settings page
191
+ - Docs page billing section
192
+
193
+ ## 🔐 Authentication Flow
194
+
195
+ 1. **Register**: Create tenant & user account
196
+ ```bash
197
+ curl -X POST http://localhost:8000/api/auth/register \
198
+ -H "Content-Type: application/json" \
199
+ -d '{
200
+ "email": "user@company.com",
201
+ "password": "SecurePassword123",
202
+ "full_name": "John Doe"
203
+ }'
204
+ ```
205
+
206
+ 2. **Login**: Get access token
207
+ ```bash
208
+ curl -X POST http://localhost:8000/api/auth/login \
209
+ -H "Content-Type: application/json" \
210
+ -d '{
211
+ "email": "user@company.com",
212
+ "password": "SecurePassword123"
213
+ }'
214
+ ```
215
+
216
+ 3. **Use Token**: Access protected endpoints
217
+ ```bash
218
+ curl -X GET http://localhost:8000/api/auth/me \
219
+ -H "Authorization: Bearer {access_token}"
220
+ ```
221
+
222
+ ## 👤 Face Registration Example
223
+
224
+ Strict rules:
225
+ - exactly 3 images
226
+ - one person per frame
227
+ - no duplicate images
228
+ - 3 different detected face angles
229
+ - one detailed normalized embedding stored
230
+
231
+ ```bash
232
+ curl -X POST http://localhost:8000/api/face/register \
233
+ -H "Authorization: Bearer {access_token}" \
234
+ -F "person_id=EMP001" \
235
+ -F "name=John Doe" \
236
+ -F "images=@/path/to/front.jpg" \
237
+ -F "images=@/path/to/left.jpg" \
238
+ -F "images=@/path/to/right.jpg" \
239
+ -F "metadata={\"department\": \"Engineering\"}"
240
+ ```
241
+
242
+ ## 🎯 Face Recognition Example
243
+
244
+ ```bash
245
+ curl -X POST http://localhost:8000/api/face/recognize \
246
+ -H "Authorization: Bearer {access_token}" \
247
+ -F "image=@/path/to/test_frame.jpg" \
248
+ -F "threshold=0.5" \
249
+ -F "return_bboxes=true"
250
+ ```
251
+
252
+ Response:
253
+ ```json
254
+ {
255
+ "faces_detected": 2,
256
+ "recognized": [
257
+ {
258
+ "person_id": "EMP001",
259
+ "name": "John Doe",
260
+ "confidence": 0.96,
261
+ "bbox": [100, 200, 300, 400],
262
+ "embedding_id": "550e8400-e29b-41d4-a716-446655440000"
263
+ }
264
+ ],
265
+ "unrecognized_count": 1,
266
+ "processing_time_ms": 145.23
267
+ }
268
+ ```
269
+
270
+ ## Third-Party API Integration
271
+
272
+ Third-party clients use `X-API-Key`, not JWT. Create key from admin account first.
273
+
274
+ ### 1. Login As Admin
275
+
276
+ ```bash
277
+ curl -X POST http://localhost:8000/api/auth/login \
278
+ -H "Content-Type: application/json" \
279
+ -d '{
280
+ "email": "admin@fmproject.dev",
281
+ "password": "Admin@123456"
282
+ }'
283
+ ```
284
+
285
+ Copy `access_token`.
286
+
287
+ ### 2. Create API Key
288
+
289
+ ```bash
290
+ curl -X POST http://localhost:8000/api/admin/api-keys \
291
+ -H "Authorization: Bearer {access_token}" \
292
+ -H "Content-Type: application/json" \
293
+ -d '{
294
+ "key_name": "partner-app"
295
+ }'
296
+ ```
297
+
298
+ Response includes `api_key`. Save it now. It is returned once.
299
+
300
+ ```json
301
+ {
302
+ "id": "550e8400-e29b-41d4-a716-446655440000",
303
+ "key_name": "partner-app",
304
+ "is_active": true,
305
+ "created_at": "2026-05-07T10:00:00",
306
+ "last_used_at": null,
307
+ "api_key": "fmp_generated_secret_key"
308
+ }
309
+ ```
310
+
311
+ ### 3. Register Face From Third-Party App
312
+
313
+ ```bash
314
+ curl -X POST http://localhost:8000/api/v1/faces/register \
315
+ -H "X-API-Key: {api_key}" \
316
+ -F "person_id=EMP001" \
317
+ -F "name=John Doe" \
318
+ -F "images=@/path/to/front.jpg" \
319
+ -F "images=@/path/to/left.jpg" \
320
+ -F "images=@/path/to/right.jpg" \
321
+ -F "metadata={\"source\":\"partner-app\"}"
322
+ ```
323
+
324
+ ### 4. Recognize Face From Third-Party App
325
+
326
+ ```bash
327
+ curl -X POST http://localhost:8000/api/v1/faces/recognize \
328
+ -H "X-API-Key: {api_key}" \
329
+ -F "image=@/path/to/test_frame.jpg" \
330
+ -F "threshold=0.5" \
331
+ -F "return_bboxes=true"
332
+ ```
333
+
334
+ Third-party API uses tenant attached to API key. Recognition logs use source `third_party_api`.
335
+
336
+ ## 🛡️ Multi-Tenant Isolation
337
+
338
+ The system ensures strict data isolation:
339
+
340
+ 1. **JWT Validation**: Every request validated with tenant_id
341
+ 2. **Query Filtering**: All database queries filtered by tenant_id
342
+ 3. **Middleware**: Custom middleware enforces tenant context
343
+ 4. **Database Level**: Foreign keys prevent cross-tenant access
344
+
345
+ ```python
346
+ # Example: Only tenant's embeddings are loaded
347
+ embeddings = db.query(FaceEmbedding).filter(
348
+ FaceEmbedding.tenant_id == current_tenant_id
349
+ ).all()
350
+ ```
351
+
352
+ ## 📊 Database Schema
353
+
354
+ ### Tables
355
+ - **tenants**: Customer organizations
356
+ - **users**: Tenant members (admin, user roles)
357
+ - **face_embeddings**: Stored face vectors & metadata
358
+ - **recognition_logs**: Audit trail of recognitions
359
+ - **api_keys**: For programmatic access
360
+
361
+ All tables include:
362
+ - `tenant_id` for multi-tenant isolation
363
+ - Appropriate indexes for performance
364
+ - Timestamps for audit
365
+
366
+ ## 🔧 Configuration
367
+
368
+ Environment variables (see `.env.example`):
369
+
370
+ ```bash
371
+ # Database
372
+ DATABASE_URL=mysql+pymysql://user:pass@localhost:3306/fmproject_db
373
+
374
+ # JWT
375
+ SECRET_KEY=your-secret-key-min-32-chars
376
+ ACCESS_TOKEN_EXPIRE_MINUTES=30
377
+
378
+ # Face Recognition
379
+ INSIGHTFACE_MODEL=buffalo_l # buffalo_l, buffalo_s, etc.
380
+ INSIGHTFACE_GPU=False
381
+ FACE_RECOGNITION_THRESHOLD=0.5
382
+
383
+ # S3 Storage
384
+ S3_ENDPOINT=http://localhost:9000
385
+ S3_BUCKET=face-embeddings
386
+
387
+ # Security
388
+ CORS_ORIGINS=["http://localhost:3000"]
389
+ RATE_LIMIT_PER_MINUTE=100
390
+ ```
391
+
392
+ ## 📦 Deployment
393
+
394
+ ### Docker Compose (Development)
395
+ ```bash
396
+ docker-compose up -d
397
+ ```
398
+
399
+ ### Docker Production
400
+ ```bash
401
+ docker build -t fmproject-backend:latest .
402
+ docker run -d \
403
+ -e DATABASE_URL=mysql+pymysql://... \
404
+ -e SECRET_KEY=your-key \
405
+ -p 8000:8000 \
406
+ fmproject-backend:latest
407
+ ```
408
+
409
+ ### Kubernetes
410
+ See `k8s/` directory for Kubernetes manifests (helm charts, deployments, services).
411
+
412
+ ## 📈 Performance
413
+
414
+ - **Recognition Latency**: < 500ms per frame
415
+ - **Throughput**: 100+ concurrent users
416
+ - **Embedding Storage**: Optimized with binary format
417
+ - **Caching**: Redis for frequently accessed embeddings
418
+
419
+ ## 🧪 Testing
420
+
421
+ ```bash
422
+ # Run tests
423
+ pytest tests/ -v
424
+
425
+ # Run with coverage
426
+ pytest tests/ --cov=app
427
+ ```
428
+
429
+ ## 📝 Database Migrations
430
+
431
+ ```bash
432
+ # Create migration
433
+ alembic revision --autogenerate -m "Add new table"
434
+
435
+ # Apply migrations
436
+ alembic upgrade head
437
+
438
+ # Rollback
439
+ alembic downgrade -1
440
+ ```
441
+
442
+ ## 🤝 Contributing
443
+
444
+ 1. Fork repository
445
+ 2. Create feature branch (`git checkout -b feature/amazing-feature`)
446
+ 3. Commit changes (`git commit -m 'Add amazing feature'`)
447
+ 4. Push to branch (`git push origin feature/amazing-feature`)
448
+ 5. Open Pull Request
449
+
450
+ ## 📄 License
451
+
452
+ MIT License - see LICENSE file for details
453
+
454
+ ## 🆘 Support
455
+
456
+ - Documentation: `/docs` (interactive API docs)
457
+ - Issues: GitHub Issues
458
+ - Email: support@fmproject.com
459
+
460
+ ## 🗺️ Roadmap
461
+
462
+ - [ ] WebSocket support for real-time recognition
463
+ - [ ] Face clustering & grouping
464
+ - [ ] Liveness detection
465
+ - [ ] Webhooks for events
466
+ - [ ] Advanced analytics dashboard
467
+ - [ ] Face search API
468
+ - [ ] Batch processing
469
+ - [ ] GPU acceleration
470
+ - [ ] Multi-modal search
471
+
472
+ ---
473
 
474
+ **Built with ❤️ using FastAPI, InsightFace, and MySQL**
 
475
  - Name: `face-inference-service`
476
  - Space SDK: **Docker**
477
  - License: MIT
backend/.env.example ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment Configuration Template
2
+
3
+ # ========== APP ==========
4
+ DEBUG=False
5
+ APP_NAME="Face Inference SaaS Platform"
6
+ APP_VERSION="1.0.0"
7
+ ADMIN_DEFAULT_EMAIL=admin@fmproject.dev
8
+ ADMIN_DEFAULT_PASSWORD=Admin@123456
9
+
10
+ # ========== DATABASE ==========
11
+ DATABASE_URL=mysql+pymysql://fmproject:fmproject_password@localhost:3306/fmproject_db
12
+
13
+ # ========== JWT & SECURITY ==========
14
+ SECRET_KEY=your-super-secret-key-change-this-in-production-min-32-chars
15
+ ALGORITHM=HS256
16
+ ACCESS_TOKEN_EXPIRE_MINUTES=30
17
+ REFRESH_TOKEN_EXPIRE_DAYS=7
18
+
19
+ # ========== REDIS ==========
20
+ REDIS_URL=redis://localhost:6379
21
+
22
+ # ========== S3 / OBJECT STORAGE ==========
23
+ S3_ENDPOINT=http://localhost:9000
24
+ S3_ACCESS_KEY=minioadmin
25
+ S3_SECRET_KEY=minioadmin
26
+ S3_BUCKET=face-embeddings
27
+ S3_REGION=us-east-1
28
+
29
+ # ========== INSIGHTFACE ==========
30
+ INSIGHTFACE_MODEL=buffalo_l
31
+ INSIGHTFACE_GPU=False
32
+ FACE_RECOGNITION_THRESHOLD=0.5
33
+
34
+ # ========== CORS ==========
35
+ CORS_ORIGINS=["http://localhost:3000","http://localhost:5173"]
36
+
37
+ # ========== FILE UPLOAD ==========
38
+ MAX_UPLOAD_SIZE=10485760
39
+
40
+ # ========== RATE LIMITING ==========
41
+ RATE_LIMIT_ENABLED=True
42
+ RATE_LIMIT_PER_MINUTE=100
backend/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
backend/.gitignore ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ *.manifest
32
+ *.spec
33
+
34
+ # Unit test / coverage reports
35
+ htmlcov/
36
+ .tox/
37
+ .nox/
38
+ .coverage
39
+ .coverage.*
40
+ .cache
41
+ nosetests.xml
42
+ coverage.xml
43
+ *.cover
44
+ *.py,cover
45
+ .hypothesis/
46
+ .pytest_cache/
47
+
48
+ # Translations
49
+ *.mo
50
+ *.pot
51
+
52
+ # Django stuff:
53
+ *.log
54
+ local_settings.py
55
+ db.sqlite3
56
+ db.sqlite3-journal
57
+
58
+ # Flask stuff:
59
+ instance/
60
+ .webassets-cache
61
+
62
+ # Scrapy stuff:
63
+ .scrapy
64
+
65
+ # Sphinx documentation
66
+ docs/_build/
67
+
68
+ # PyBuilder
69
+ target/
70
+
71
+ # Jupyter Notebook
72
+ .ipynb_checkpoints
73
+
74
+ # IPython
75
+ profile_default/
76
+ ipython_config.py
77
+
78
+ # pyenv
79
+ .python-version
80
+
81
+ # pipenv
82
+ Pipfile.lock
83
+
84
+ # PEP 582
85
+ __pypackages__/
86
+
87
+ # Celery stuff
88
+ celerybeat-schedule
89
+ celerybeat.pid
90
+
91
+ # SageMath parsed files
92
+ *.sage.py
93
+
94
+ # Environments
95
+ .env
96
+ .venv
97
+ env/
98
+ venv/
99
+ ENV/
100
+ env.bak/
101
+ venv.bak/
102
+
103
+ # Spyder project settings
104
+ .spyderproject
105
+ .spyproject
106
+
107
+ # Rope project settings
108
+ .ropeproject
109
+
110
+ # mkdocs documentation
111
+ /site
112
+
113
+ # mypy
114
+ .mypy_cache/
115
+ .dmypy.json
116
+ dmypy.json
117
+
118
+ # Pyre type checker
119
+ .pyre/
120
+
121
+ # IDE
122
+ .vscode/
123
+ .idea/
124
+ *.swp
125
+ *.swo
126
+ *~
127
+
128
+ # OS
129
+ .DS_Store
130
+ Thumbs.db
131
+
132
+ # Project specific
133
+ *.db
134
+ *.sqlite
135
+ /uploads/
136
+ /downloads/
137
+ /models/
138
+ .env.local
139
+ .env.*.local
backend/API_EXAMPLES.md ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Comprehensive API Testing Examples"""
2
+
3
+ # Authentication Examples
4
+ ## Register New User
5
+ POST http://localhost:8000/api/auth/register
6
+ Content-Type: application/json
7
+
8
+ {
9
+ "email": "harsh@company.com",
10
+ "password": "SecurePassword123",
11
+ "full_name": "Harsh Kumar"
12
+ }
13
+
14
+ ### Expected Response (201)
15
+ {
16
+ "user": {
17
+ "id": "550e8400-e29b-41d4-a716-446655440000",
18
+ "email": "harsh@company.com",
19
+ "full_name": "Harsh Kumar",
20
+ "role": "user",
21
+ "tenant_id": "660e8400-e29b-41d4-a716-446655440000",
22
+ "is_active": true,
23
+ "created_at": "2024-01-15T10:30:00Z"
24
+ },
25
+ "tokens": {
26
+ "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
27
+ "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
28
+ "token_type": "bearer",
29
+ "expires_in": 1800
30
+ },
31
+ "tenant": {
32
+ "id": "660e8400-e29b-41d4-a716-446655440000",
33
+ "name": "org-company.com",
34
+ "plan": "free",
35
+ "api_quota": 10000,
36
+ "created_at": "2024-01-15T10:30:00Z"
37
+ }
38
+ }
39
+
40
+ ## Login
41
+ POST http://localhost:8000/api/auth/login
42
+ Content-Type: application/json
43
+
44
+ {
45
+ "email": "harsh@company.com",
46
+ "password": "SecurePassword123"
47
+ }
48
+
49
+ ### Expected Response (200)
50
+ {
51
+ "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
52
+ "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
53
+ "token_type": "bearer",
54
+ "expires_in": 1800
55
+ }
56
+
57
+ ## Refresh Token
58
+ POST http://localhost:8000/api/auth/refresh
59
+ Content-Type: application/json
60
+
61
+ {
62
+ "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
63
+ }
64
+
65
+ ### Expected Response (200)
66
+ {
67
+ "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
68
+ "token_type": "bearer",
69
+ "expires_in": 1800
70
+ }
71
+
72
+ ## Get Current User
73
+ GET http://localhost:8000/api/auth/me
74
+ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
75
+
76
+ ### Expected Response (200)
77
+ {
78
+ "id": "550e8400-e29b-41d4-a716-446655440000",
79
+ "email": "harsh@company.com",
80
+ "full_name": "Harsh Kumar",
81
+ "role": "user",
82
+ "tenant_id": "660e8400-e29b-41d4-a716-446655440000",
83
+ "is_active": true,
84
+ "created_at": "2024-01-15T10:30:00Z"
85
+ }
86
+
87
+ ---
88
+
89
+ # Face Operations Examples
90
+
91
+ ## Register Face (Form Data with File)
92
+ POST http://localhost:8000/api/face/register
93
+ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
94
+ Content-Type: multipart/form-data
95
+
96
+ person_id: EMP001
97
+ name: Harsh Kumar
98
+ image: @/path/to/harsh_photo.jpg
99
+ metadata: {"department": "Engineering", "designation": "Senior Developer"}
100
+
101
+ ### Expected Response (201)
102
+ {
103
+ "id": "770e8400-e29b-41d4-a716-446655440000",
104
+ "person_id": "EMP001",
105
+ "name": "Harsh Kumar",
106
+ "image_url": "s3://face-embeddings/...",
107
+ "face_quality_score": 0.92,
108
+ "created_at": "2024-01-15T10:35:00Z"
109
+ }
110
+
111
+ ## Register Multiple Faces for Same Person
112
+ POST http://localhost:8000/api/face/register
113
+ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
114
+ Content-Type: multipart/form-data
115
+
116
+ person_id: EMP001
117
+ name: Harsh Kumar
118
+ image: @/path/to/harsh_photo_2.jpg
119
+ metadata: {}
120
+
121
+ ---
122
+
123
+ ## Recognize Faces (Upload Frame)
124
+ POST http://localhost:8000/api/face/recognize
125
+ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
126
+ Content-Type: multipart/form-data
127
+
128
+ image: @/path/to/test_frame.jpg
129
+ threshold: 0.5
130
+ return_bboxes: true
131
+
132
+ ### Expected Response (200)
133
+ {
134
+ "faces_detected": 2,
135
+ "recognized": [
136
+ {
137
+ "person_id": "EMP001",
138
+ "name": "Harsh Kumar",
139
+ "confidence": 0.96,
140
+ "bbox": [100, 150, 250, 350],
141
+ "embedding_id": "770e8400-e29b-41d4-a716-446655440000"
142
+ },
143
+ {
144
+ "person_id": "EMP002",
145
+ "name": "John Doe",
146
+ "confidence": 0.88,
147
+ "bbox": [400, 200, 550, 450],
148
+ "embedding_id": "880e8400-e29b-41d4-a716-446655440000"
149
+ }
150
+ ],
151
+ "unrecognized_count": 0,
152
+ "processing_time_ms": 245.67
153
+ }
154
+
155
+ ## List Registered Embeddings
156
+ GET http://localhost:8000/api/face/embeddings?skip=0&limit=100
157
+ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
158
+
159
+ ### Optional filters:
160
+ GET http://localhost:8000/api/face/embeddings?person_id=EMP001&skip=0&limit=100
161
+
162
+ ### Expected Response (200)
163
+ [
164
+ {
165
+ "id": "770e8400-e29b-41d4-a716-446655440000",
166
+ "person_id": "EMP001",
167
+ "name": "Harsh Kumar",
168
+ "image_url": "s3://face-embeddings/...",
169
+ "face_quality_score": 0.92,
170
+ "embedding_dim": 512,
171
+ "face_angle": "frontal",
172
+ "created_at": "2024-01-15T10:35:00Z",
173
+ "updated_at": "2024-01-15T10:35:00Z"
174
+ }
175
+ ]
176
+
177
+ ## Get Recognition Logs
178
+ GET http://localhost:8000/api/face/logs?skip=0&limit=100
179
+ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
180
+
181
+ ### Expected Response (200)
182
+ [
183
+ {
184
+ "id": "990e8400-e29b-41d4-a716-446655440000",
185
+ "recognized_person_id": "EMP001",
186
+ "confidence": 0.96,
187
+ "source": "api",
188
+ "timestamp": "2024-01-15T10:40:00Z"
189
+ }
190
+ ]
191
+
192
+ ## Delete Embedding
193
+ DELETE http://localhost:8000/api/face/embeddings/770e8400-e29b-41d4-a716-446655440000
194
+ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
195
+
196
+ ### Expected Response (200)
197
+ {
198
+ "message": "Embedding deleted successfully"
199
+ }
200
+
201
+ ---
202
+
203
+ # Admin Endpoints
204
+
205
+ ## Get Analytics
206
+ GET http://localhost:8000/api/admin/analytics
207
+ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
208
+
209
+ ### Expected Response (200)
210
+ {
211
+ "total_tenants": 1,
212
+ "total_users": 5,
213
+ "total_face_embeddings": 42,
214
+ "total_recognition_logs": 156,
215
+ "total_api_calls": 1024,
216
+ "recognitions_today": 25,
217
+ "faces_registered_today": 3
218
+ }
219
+
220
+ ## List All Users
221
+ GET http://localhost:8000/api/admin/users?skip=0&limit=100
222
+ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
223
+
224
+ ### Expected Response (200)
225
+ [
226
+ {
227
+ "id": "550e8400-e29b-41d4-a716-446655440000",
228
+ "email": "harsh@company.com",
229
+ "full_name": "Harsh Kumar",
230
+ "role": "user",
231
+ "tenant_id": "660e8400-e29b-41d4-a716-446655440000",
232
+ "is_active": true,
233
+ "created_at": "2024-01-15T10:30:00Z",
234
+ "face_embeddings_count": 3
235
+ }
236
+ ]
237
+
238
+ ## Delete User (Admin Only)
239
+ DELETE http://localhost:8000/api/admin/users/550e8400-e29b-41d4-a716-446655440000
240
+ Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
241
+
242
+ ### Expected Response (200)
243
+ {
244
+ "message": "User deleted successfully"
245
+ }
246
+
247
+ ---
248
+
249
+ # Health & Status
250
+
251
+ ## Health Check
252
+ GET http://localhost:8000/health
253
+
254
+ ### Expected Response (200)
255
+ {
256
+ "status": "healthy",
257
+ "app": "Face Inference SaaS Platform",
258
+ "version": "1.0.0"
259
+ }
260
+
261
+ ## Root Info
262
+ GET http://localhost:8000/
263
+
264
+ ### Expected Response (200)
265
+ {
266
+ "app": "Face Inference SaaS Platform",
267
+ "version": "1.0.0",
268
+ "docs": "/docs",
269
+ "openapi_schema": "/openapi.json"
270
+ }
271
+
272
+ ---
273
+
274
+ # Error Responses
275
+
276
+ ## Invalid Credentials (401)
277
+ {
278
+ "detail": "Invalid email or password"
279
+ }
280
+
281
+ ## Unauthorized (401)
282
+ {
283
+ "detail": "Not authenticated"
284
+ }
285
+
286
+ ## Forbidden (403)
287
+ {
288
+ "detail": "Admin access required"
289
+ }
290
+
291
+ ## Not Found (404)
292
+ {
293
+ "detail": "Embedding not found"
294
+ }
295
+
296
+ ## Validation Error (422)
297
+ {
298
+ "detail": [
299
+ {
300
+ "loc": ["body", "email"],
301
+ "msg": "invalid email format",
302
+ "type": "value_error.email"
303
+ }
304
+ ]
305
+ }
306
+
307
+ ## No Faces Detected (400)
308
+ {
309
+ "detail": "No faces detected in image"
310
+ }
311
+
312
+ ## Server Error (500)
313
+ {
314
+ "detail": "Face recognition failed"
315
+ }
backend/Dockerfile ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ syntax=docker/dockerfile:1
2
+
3
+ FROM node:20-alpine AS frontend-builder
4
+ WORKDIR /app/frontend
5
+ COPY frontend/package*.json ./
6
+ RUN npm install
7
+ COPY frontend/ ./
8
+ RUN npm run build
9
+
10
+ FROM python:3.11-slim AS runtime
11
+
12
+ # Set environment variables
13
+ ENV PYTHONUNBUFFERED=1 \
14
+ PYTHONDONTWRITEBYTECODE=1 \
15
+ PIP_NO_CACHE_DIR=1
16
+
17
+ WORKDIR /app
18
+
19
+ # Install system dependencies for face recognition and computer vision
20
+ RUN apt-get update && apt-get install -y --no-install-recommends \
21
+ libsm6 \
22
+ libxext6 \
23
+ libxrender-dev \
24
+ libgomp1 \
25
+ libgl1 \
26
+ libglib2.0-0 \
27
+ libxext6 \
28
+ curl \
29
+ gcc \
30
+ && rm -rf /var/lib/apt/lists/*
31
+
32
+ COPY backend/requirements.txt /app/backend/requirements.txt
33
+ RUN pip install --upgrade pip setuptools wheel && \
34
+ pip install -r /app/backend/requirements.txt
35
+
36
+ COPY backend/ /app/backend/
37
+ COPY --from=frontend-builder /app/frontend/dist /app/backend/static
38
+
39
+ EXPOSE 7860
40
+
41
+ # Health check
42
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
43
+ CMD curl -f http://localhost:8000/health || exit 1
44
+
45
+ WORKDIR /app/backend
46
+ CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-7860} --workers 2"]
backend/QUICK_START.md ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 Quick Start Guide
2
+
3
+ ## 5-Minute Setup
4
+
5
+ ### 1. Start All Services
6
+ ```bash
7
+ docker-compose up -d
8
+ ```
9
+
10
+ ### 2. Verify Services Are Running
11
+ ```bash
12
+ # Check health
13
+ curl http://localhost/health
14
+
15
+ # View logs
16
+ docker-compose logs -f backend
17
+ ```
18
+
19
+ ### 3. Access Documentation
20
+ - **Swagger UI**: http://localhost/docs
21
+ - **ReDoc**: http://localhost/redoc
22
+ - **API Root**: http://localhost/
23
+
24
+ ### 4. Test the API
25
+
26
+ **Register a new user:**
27
+ ```bash
28
+ curl -X POST http://localhost/api/auth/register \
29
+ -H "Content-Type: application/json" \
30
+ -d '{
31
+ "email": "user@example.com",
32
+ "password": "Password@123",
33
+ "full_name": "Test User"
34
+ }'
35
+ ```
36
+
37
+ Save the `access_token` from the response.
38
+
39
+ **Login:**
40
+ ```bash
41
+ curl -X POST http://localhost/api/auth/login \
42
+ -H "Content-Type: application/json" \
43
+ -d '{
44
+ "email": "user@example.com",
45
+ "password": "Password@123"
46
+ }'
47
+ ```
48
+
49
+ **Get current user:**
50
+ ```bash
51
+ curl -X GET http://localhost/api/auth/me \
52
+ -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
53
+ ```
54
+
55
+ **Register a face:**
56
+ ```bash
57
+ curl -X POST http://localhost/api/face/register \
58
+ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
59
+ -F "person_id=USER001" \
60
+ -F "name=John Doe" \
61
+ -F "image=@path/to/photo.jpg"
62
+ ```
63
+
64
+ **Recognize faces:**
65
+ ```bash
66
+ curl -X POST http://localhost/api/face/recognize \
67
+ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
68
+ -F "image=@path/to/test_frame.jpg" \
69
+ -F "threshold=0.5"
70
+ ```
71
+
72
+ ---
73
+
74
+ ## Common Commands
75
+
76
+ ### View API Documentation
77
+ ```bash
78
+ # Interactive Swagger UI
79
+ open http://localhost/docs
80
+
81
+ # Alternative ReDoc
82
+ open http://localhost/redoc
83
+ ```
84
+
85
+ ### Check Service Health
86
+ ```bash
87
+ # Backend
88
+ curl http://localhost:8000/health
89
+
90
+ # Through Nginx
91
+ curl http://localhost/health
92
+ ```
93
+
94
+ ### View Logs
95
+ ```bash
96
+ # All services
97
+ docker-compose logs -f
98
+
99
+ # Specific service
100
+ docker-compose logs -f backend
101
+ docker-compose logs -f mysql
102
+ docker-compose logs -f redis
103
+ ```
104
+
105
+ ### Database Access
106
+ ```bash
107
+ # Connect to MySQL
108
+ docker-compose exec mysql mysql -u fmproject -pfmproject_password fmproject_db
109
+
110
+ # Common queries:
111
+ # SHOW TABLES; # List tables
112
+ # SELECT * FROM users; # View users
113
+ # SELECT * FROM tenants; # View tenants
114
+ # exit # Exit
115
+ ```
116
+
117
+ ### Redis CLI
118
+ ```bash
119
+ docker-compose exec redis redis-cli
120
+ ```
121
+
122
+ ### MinIO S3 Console
123
+ - URL: http://localhost:9001
124
+ - Username: minioadmin
125
+ - Password: minioadmin
126
+
127
+ ---
128
+
129
+ ## Troubleshooting
130
+
131
+ ### Services Won't Start
132
+ ```bash
133
+ # Clean up and restart
134
+ docker-compose down -v
135
+ docker-compose up -d
136
+ ```
137
+
138
+ ### Port Already in Use
139
+ ```bash
140
+ # Change ports in docker-compose.yml or:
141
+ lsof -i :8000 # Find process using port
142
+ kill -9 <PID>
143
+ ```
144
+
145
+ ### Database Connection Error
146
+ ```bash
147
+ # Wait for database to be ready
148
+ docker-compose logs mysql
149
+
150
+ # Manually create database (if needed)
151
+ docker-compose exec mysql mysql -uroot -pfmproject_root_password -e "CREATE DATABASE IF NOT EXISTS fmproject_db;"
152
+ ```
153
+
154
+ ### File Upload Issues
155
+ ```bash
156
+ # Check upload directory permissions
157
+ chmod 777 uploads/
158
+
159
+ # Or increase size limit in app/core/config.py
160
+ MAX_UPLOAD_SIZE = 10 * 1024 * 1024 # 10MB
161
+ ```
162
+
163
+ ---
164
+
165
+ ## Development Tips
166
+
167
+ ### Enable Debug Mode
168
+ Edit `.env`:
169
+ ```bash
170
+ DEBUG=True
171
+ ```
172
+
173
+ Restart:
174
+ ```bash
175
+ docker-compose restart backend
176
+ ```
177
+
178
+ ### Run Tests
179
+ ```bash
180
+ docker-compose exec backend pytest tests/ -v
181
+ ```
182
+
183
+ ### Database Migrations
184
+ ```bash
185
+ # Create migration
186
+ docker-compose exec backend alembic revision --autogenerate -m "Add new field"
187
+
188
+ # Apply migration
189
+ docker-compose exec backend alembic upgrade head
190
+ ```
191
+
192
+ ### Hot Reload
193
+ Backend automatically reloads on file changes (development mode).
194
+
195
+ ### Access Database Directly
196
+ ```bash
197
+ docker-compose exec mysql mysql -u fmproject -pfmproject_password fmproject_db
198
+ ```
199
+
200
+ ---
201
+
202
+ ## Default Credentials (Development)
203
+
204
+ When initialized via `init_app.py`:
205
+ - **Email**: admin@fmproject.local
206
+ - **Password**: Admin@123456
207
+
208
+ Change these in production!
209
+
210
+ ---
211
+
212
+ ## Next Steps
213
+
214
+ 1. ✅ Services running
215
+ 2. 📚 Review [API_EXAMPLES.md](API_EXAMPLES.md) for more examples
216
+ 3. 🔐 Change default credentials
217
+ 4. 🗄️ Set up production database
218
+ 5. 🔑 Generate strong SECRET_KEY
219
+ 6. 🌐 Configure CORS_ORIGINS for frontend
220
+ 7. 📦 Build and deploy frontend (React project)
221
+
222
+ ---
223
+
224
+ ## Useful Links
225
+
226
+ - FastAPI Docs: https://fastapi.tiangolo.com/
227
+ - SQLAlchemy: https://docs.sqlalchemy.org/
228
+ - InsightFace: https://github.com/deepinsight/insightface
229
+ - Docker Compose: https://docs.docker.com/compose/
230
+ - MySQL: https://dev.mysql.com/doc/
231
+
232
+ ---
233
+
234
+ ## Need Help?
235
+
236
+ 1. Check logs: `docker-compose logs -f`
237
+ 2. Review [API_EXAMPLES.md](API_EXAMPLES.md)
238
+ 3. Check [README.md](README.md) architecture section
239
+ 4. Review API docs at: http://localhost/docs
240
+
241
+ ---
242
+
243
+ **Happy Face Recognition! 🎯👤**
backend/alembic.ini ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [alembic]
2
+ script_location = migrations
3
+ sqlalchemy.url = driver://user:pass@localhost/dbname
4
+ sqlalchemy.echo = true
5
+
6
+ [loggers]
7
+ keys = root,sqlalchemy,alembic
8
+
9
+ [handlers]
10
+ keys = console
11
+
12
+ [formatters]
13
+ keys = generic
14
+
15
+ [logger_root]
16
+ level = WARN
17
+ handlers = console
18
+
19
+ [logger_sqlalchemy]
20
+ level = WARN
21
+ handlers = console
22
+ qualname = sqlalchemy.engine
23
+
24
+ [logger_alembic]
25
+ level = INFO
26
+ handlers = console
27
+ qualname = alembic
28
+
29
+ [handler_console]
30
+ class = StreamHandler
31
+ args = (sys.stderr,)
32
+ level = NOTSET
33
+ formatter = generic
34
+
35
+ [formatter_generic]
36
+ format = %(levelname)-5.5s [%(name)s] %(message)s
app.py → backend/app.py RENAMED
@@ -1,227 +1,227 @@
1
- """
2
- Face Inference Microservice for Hugging Face Spaces
3
- Extracts face embeddings and matches against known encodings
4
- """
5
-
6
- from fastapi import FastAPI, HTTPException, UploadFile, File, Form
7
- from fastapi.responses import JSONResponse, HTMLResponse, FileResponse
8
- from fastapi.staticfiles import StaticFiles
9
- import asyncio
10
- import numpy as np
11
- import io
12
- import base64
13
- from PIL import Image
14
- import cv2
15
- import logging
16
- from insightface.app import FaceAnalysis
17
- import os
18
-
19
- logging.basicConfig(level=logging.INFO)
20
- logger = logging.getLogger(__name__)
21
-
22
- # Global face recognition model (lazy-loaded on first use)
23
- face_app = None
24
- face_app_lock = asyncio.Lock()
25
-
26
- async def get_face_app():
27
- global face_app
28
- if face_app is not None:
29
- return face_app
30
-
31
- async with face_app_lock:
32
- if face_app is not None:
33
- return face_app
34
-
35
- try:
36
- logger.info("Loading face recognition model...")
37
- model_name = os.environ.get("FACE_RECOGNITION_MODEL", "buffalo_l")
38
- app_instance = FaceAnalysis(name=model_name, providers=["CPUExecutionProvider"])
39
- app_instance.prepare(ctx_id=-1)
40
- face_app = app_instance
41
- logger.info("✓ Model loaded successfully")
42
- except Exception as e:
43
- logger.error(f"Failed to load model: {e}")
44
- raise
45
-
46
- return face_app
47
-
48
- app = FastAPI(title="Face Inference Service", version="1.0")
49
-
50
- # Mount static files
51
- static_dir = os.path.join(os.path.dirname(__file__), "static")
52
- if os.path.exists(static_dir):
53
- app.mount("/static", StaticFiles(directory=static_dir), name="static")
54
- logger.info(f"✓ Static files mounted from {static_dir}")
55
-
56
- @app.get("/", response_class=HTMLResponse)
57
- async def root():
58
- """Serve the web UI"""
59
- html_path = os.path.join(os.path.dirname(__file__), "static", "index.html")
60
- if os.path.exists(html_path):
61
- with open(html_path, "r", encoding="utf-8") as f:
62
- return f.read()
63
- return "<h1>Face Inference Service</h1><p>API is running. Visit /docs for API documentation.</p>"
64
-
65
- @app.get("/health")
66
- async def health_check():
67
- """Health check endpoint"""
68
- return {
69
- "status": "healthy",
70
- "service": "face-inference",
71
- "model_loaded": face_app is not None,
72
- }
73
-
74
- @app.post("/recognize")
75
- async def recognize_face(
76
- frame_data: str = Form(...),
77
- known_encodings: str = Form(...),
78
- tolerance: float = Form(default=0.85)
79
- ):
80
- """
81
- Recognize faces in a frame against known encodings
82
-
83
- Args:
84
- frame_data: Base64 encoded image
85
- known_encodings: JSON string of numpy array (serialized)
86
- tolerance: Distance threshold for matching
87
-
88
- Returns:
89
- List of matched student IDs and distances
90
- """
91
- try:
92
- face_app_instance = await get_face_app()
93
-
94
- # Decode frame
95
- img_bytes = base64.b64decode(frame_data.split(',')[1] if ',' in frame_data else frame_data)
96
- img = Image.open(io.BytesIO(img_bytes)).convert('RGB')
97
- frame = np.array(img)
98
-
99
- # Detect faces
100
- faces = face_app_instance.get(frame)
101
-
102
- if not faces:
103
- return {"success": True, "recognized": [], "count": 0}
104
-
105
- # Parse known encodings
106
- import json
107
- known_data = json.loads(known_encodings)
108
- known_encodings_arr = np.array(known_data['encodings'])
109
- known_metadata = known_data.get('metadata', [])
110
-
111
- recognized = []
112
-
113
- # Match each detected face
114
- for face in faces:
115
- embedding = face.normed_embedding
116
- distances = np.linalg.norm(known_encodings_arr - embedding, axis=1)
117
- min_idx = np.argmin(distances)
118
- min_distance = float(distances[min_idx])
119
-
120
- if min_distance < tolerance:
121
- student_info = known_metadata[min_idx]
122
- recognized.append({
123
- "roll_no": student_info.get('roll_no', ''),
124
- "name": student_info.get('name', ''),
125
- "distance": min_distance
126
- })
127
- logger.info(f"✓ Recognized: {student_info.get('name')} - Distance: {min_distance:.3f}")
128
-
129
- return {
130
- "success": True,
131
- "recognized": recognized,
132
- "count": len(recognized),
133
- "faces_detected": len(faces)
134
- }
135
-
136
- except json.JSONDecodeError as e:
137
- logger.error(f"JSON parse error: {e}")
138
- raise HTTPException(status_code=400, detail="Invalid encoding data format")
139
- except Exception as e:
140
- logger.error(f"Recognition error: {e}")
141
- raise HTTPException(status_code=500, detail=str(e))
142
-
143
- @app.post("/recognize_batch")
144
- async def recognize_batch(
145
- frames: list = Form(...),
146
- known_encodings: str = Form(...),
147
- tolerance: float = Form(default=0.85)
148
- ):
149
- """
150
- Batch recognition for multiple frames
151
- """
152
- try:
153
- face_app_instance = await get_face_app()
154
-
155
- import json
156
- known_data = json.loads(known_encodings)
157
- known_encodings_arr = np.array(known_data['encodings'])
158
- known_metadata = known_data.get('metadata', [])
159
-
160
- all_recognized = set()
161
-
162
- for frame_data in frames:
163
- try:
164
- img_bytes = base64.b64decode(frame_data.split(',')[1] if ',' in frame_data else frame_data)
165
- img = Image.open(io.BytesIO(img_bytes)).convert('RGB')
166
- frame = np.array(img)
167
-
168
- faces = face_app_instance.get(frame)
169
-
170
- for face in faces:
171
- embedding = face.normed_embedding
172
- distances = np.linalg.norm(known_encodings_arr - embedding, axis=1)
173
- min_idx = np.argmin(distances)
174
- min_distance = float(distances[min_idx])
175
-
176
- if min_distance < tolerance:
177
- student_info = known_metadata[min_idx]
178
- all_recognized.add(student_info.get('roll_no', ''))
179
- except Exception as e:
180
- logger.warning(f"Error processing frame in batch: {e}")
181
- continue
182
-
183
- return {
184
- "success": True,
185
- "recognized": list(all_recognized),
186
- "count": len(all_recognized)
187
- }
188
-
189
- except Exception as e:
190
- logger.error(f"Batch recognition error: {e}")
191
- raise HTTPException(status_code=500, detail=str(e))
192
-
193
- @app.post("/get_embedding")
194
- async def get_embedding(
195
- image_data: str = Form(...)
196
- ):
197
- """
198
- Extract embedding from a single image
199
- """
200
- try:
201
- face_app_instance = await get_face_app()
202
-
203
- img_bytes = base64.b64decode(image_data.split(',')[1] if ',' in image_data else image_data)
204
- img = Image.open(io.BytesIO(img_bytes)).convert('RGB')
205
- frame = np.array(img)
206
-
207
- faces = face_app_instance.get(frame)
208
-
209
- if not faces:
210
- raise HTTPException(status_code=400, detail="No face detected in image")
211
-
212
- embedding = faces[0].normed_embedding.tolist()
213
-
214
- return {
215
- "success": True,
216
- "embedding": embedding,
217
- "faces_detected": len(faces)
218
- }
219
-
220
- except Exception as e:
221
- logger.error(f"Embedding error: {e}")
222
- raise HTTPException(status_code=500, detail=str(e))
223
-
224
- if __name__ == "__main__":
225
- import uvicorn
226
- port = int(os.environ.get("PORT", 7860))
227
- uvicorn.run(app, host="0.0.0.0", port=port)
 
1
+ """
2
+ Face Inference Microservice for Hugging Face Spaces
3
+ Extracts face embeddings and matches against known encodings
4
+ """
5
+
6
+ from fastapi import FastAPI, HTTPException, UploadFile, File, Form
7
+ from fastapi.responses import JSONResponse, HTMLResponse, FileResponse
8
+ from fastapi.staticfiles import StaticFiles
9
+ import asyncio
10
+ import numpy as np
11
+ import io
12
+ import base64
13
+ from PIL import Image
14
+ import cv2
15
+ import logging
16
+ from insightface.app import FaceAnalysis
17
+ import os
18
+
19
+ logging.basicConfig(level=logging.INFO)
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # Global face recognition model (lazy-loaded on first use)
23
+ face_app = None
24
+ face_app_lock = asyncio.Lock()
25
+
26
+ async def get_face_app():
27
+ global face_app
28
+ if face_app is not None:
29
+ return face_app
30
+
31
+ async with face_app_lock:
32
+ if face_app is not None:
33
+ return face_app
34
+
35
+ try:
36
+ logger.info("Loading face recognition model...")
37
+ model_name = os.environ.get("FACE_RECOGNITION_MODEL", "buffalo_l")
38
+ app_instance = FaceAnalysis(name=model_name, providers=["CPUExecutionProvider"])
39
+ app_instance.prepare(ctx_id=-1)
40
+ face_app = app_instance
41
+ logger.info("✓ Model loaded successfully")
42
+ except Exception as e:
43
+ logger.error(f"Failed to load model: {e}")
44
+ raise
45
+
46
+ return face_app
47
+
48
+ app = FastAPI(title="Face Inference Service", version="1.0")
49
+
50
+ # Mount static files
51
+ static_dir = os.path.join(os.path.dirname(__file__), "static")
52
+ if os.path.exists(static_dir):
53
+ app.mount("/static", StaticFiles(directory=static_dir), name="static")
54
+ logger.info(f"✓ Static files mounted from {static_dir}")
55
+
56
+ @app.get("/", response_class=HTMLResponse)
57
+ async def root():
58
+ """Serve the web UI"""
59
+ html_path = os.path.join(os.path.dirname(__file__), "static", "index.html")
60
+ if os.path.exists(html_path):
61
+ with open(html_path, "r", encoding="utf-8") as f:
62
+ return f.read()
63
+ return "<h1>Face Inference Service</h1><p>API is running. Visit /docs for API documentation.</p>"
64
+
65
+ @app.get("/health")
66
+ async def health_check():
67
+ """Health check endpoint"""
68
+ return {
69
+ "status": "healthy",
70
+ "service": "face-inference",
71
+ "model_loaded": face_app is not None,
72
+ }
73
+
74
+ @app.post("/recognize")
75
+ async def recognize_face(
76
+ frame_data: str = Form(...),
77
+ known_encodings: str = Form(...),
78
+ tolerance: float = Form(default=0.85)
79
+ ):
80
+ """
81
+ Recognize faces in a frame against known encodings
82
+
83
+ Args:
84
+ frame_data: Base64 encoded image
85
+ known_encodings: JSON string of numpy array (serialized)
86
+ tolerance: Distance threshold for matching
87
+
88
+ Returns:
89
+ List of matched student IDs and distances
90
+ """
91
+ try:
92
+ face_app_instance = await get_face_app()
93
+
94
+ # Decode frame
95
+ img_bytes = base64.b64decode(frame_data.split(',')[1] if ',' in frame_data else frame_data)
96
+ img = Image.open(io.BytesIO(img_bytes)).convert('RGB')
97
+ frame = np.array(img)
98
+
99
+ # Detect faces
100
+ faces = face_app_instance.get(frame)
101
+
102
+ if not faces:
103
+ return {"success": True, "recognized": [], "count": 0}
104
+
105
+ # Parse known encodings
106
+ import json
107
+ known_data = json.loads(known_encodings)
108
+ known_encodings_arr = np.array(known_data['encodings'])
109
+ known_metadata = known_data.get('metadata', [])
110
+
111
+ recognized = []
112
+
113
+ # Match each detected face
114
+ for face in faces:
115
+ embedding = face.normed_embedding
116
+ distances = np.linalg.norm(known_encodings_arr - embedding, axis=1)
117
+ min_idx = np.argmin(distances)
118
+ min_distance = float(distances[min_idx])
119
+
120
+ if min_distance < tolerance:
121
+ student_info = known_metadata[min_idx]
122
+ recognized.append({
123
+ "roll_no": student_info.get('roll_no', ''),
124
+ "name": student_info.get('name', ''),
125
+ "distance": min_distance
126
+ })
127
+ logger.info(f"✓ Recognized: {student_info.get('name')} - Distance: {min_distance:.3f}")
128
+
129
+ return {
130
+ "success": True,
131
+ "recognized": recognized,
132
+ "count": len(recognized),
133
+ "faces_detected": len(faces)
134
+ }
135
+
136
+ except json.JSONDecodeError as e:
137
+ logger.error(f"JSON parse error: {e}")
138
+ raise HTTPException(status_code=400, detail="Invalid encoding data format")
139
+ except Exception as e:
140
+ logger.error(f"Recognition error: {e}")
141
+ raise HTTPException(status_code=500, detail=str(e))
142
+
143
+ @app.post("/recognize_batch")
144
+ async def recognize_batch(
145
+ frames: list = Form(...),
146
+ known_encodings: str = Form(...),
147
+ tolerance: float = Form(default=0.85)
148
+ ):
149
+ """
150
+ Batch recognition for multiple frames
151
+ """
152
+ try:
153
+ face_app_instance = await get_face_app()
154
+
155
+ import json
156
+ known_data = json.loads(known_encodings)
157
+ known_encodings_arr = np.array(known_data['encodings'])
158
+ known_metadata = known_data.get('metadata', [])
159
+
160
+ all_recognized = set()
161
+
162
+ for frame_data in frames:
163
+ try:
164
+ img_bytes = base64.b64decode(frame_data.split(',')[1] if ',' in frame_data else frame_data)
165
+ img = Image.open(io.BytesIO(img_bytes)).convert('RGB')
166
+ frame = np.array(img)
167
+
168
+ faces = face_app_instance.get(frame)
169
+
170
+ for face in faces:
171
+ embedding = face.normed_embedding
172
+ distances = np.linalg.norm(known_encodings_arr - embedding, axis=1)
173
+ min_idx = np.argmin(distances)
174
+ min_distance = float(distances[min_idx])
175
+
176
+ if min_distance < tolerance:
177
+ student_info = known_metadata[min_idx]
178
+ all_recognized.add(student_info.get('roll_no', ''))
179
+ except Exception as e:
180
+ logger.warning(f"Error processing frame in batch: {e}")
181
+ continue
182
+
183
+ return {
184
+ "success": True,
185
+ "recognized": list(all_recognized),
186
+ "count": len(all_recognized)
187
+ }
188
+
189
+ except Exception as e:
190
+ logger.error(f"Batch recognition error: {e}")
191
+ raise HTTPException(status_code=500, detail=str(e))
192
+
193
+ @app.post("/get_embedding")
194
+ async def get_embedding(
195
+ image_data: str = Form(...)
196
+ ):
197
+ """
198
+ Extract embedding from a single image
199
+ """
200
+ try:
201
+ face_app_instance = await get_face_app()
202
+
203
+ img_bytes = base64.b64decode(image_data.split(',')[1] if ',' in image_data else image_data)
204
+ img = Image.open(io.BytesIO(img_bytes)).convert('RGB')
205
+ frame = np.array(img)
206
+
207
+ faces = face_app_instance.get(frame)
208
+
209
+ if not faces:
210
+ raise HTTPException(status_code=400, detail="No face detected in image")
211
+
212
+ embedding = faces[0].normed_embedding.tolist()
213
+
214
+ return {
215
+ "success": True,
216
+ "embedding": embedding,
217
+ "faces_detected": len(faces)
218
+ }
219
+
220
+ except Exception as e:
221
+ logger.error(f"Embedding error: {e}")
222
+ raise HTTPException(status_code=500, detail=str(e))
223
+
224
+ if __name__ == "__main__":
225
+ import uvicorn
226
+ port = int(os.environ.get("PORT", 7860))
227
+ uvicorn.run(app, host="0.0.0.0", port=port)
backend/app/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Face Inference SaaS Platform - Multi-tenant Face Recognition API"""
backend/app/api/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """API routes init"""
backend/app/api/admin_routes.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Admin routes"""
2
+ from fastapi import APIRouter, HTTPException, status, Depends, Query
3
+ from sqlalchemy.orm import Session
4
+ import logging
5
+
6
+ from app.schemas import TenantDetailResponse, UserDetailResponse, AdminAnalyticsResponse, APIKeyCreateRequest, APIKeyCreateResponse, APIKeyResponse, UsageMeterResponse
7
+ from app.core.database import get_db
8
+ from app.core.security import get_current_user_id, get_current_tenant_id
9
+ from app.services.auth_service import AuthService, TenantService
10
+ from app.services.recognition_service import RecognitionService
11
+ from app.models import UserRole, User
12
+ from app.services.api_key_service import APIKeyService
13
+ from app.services.billing_service import BillingService
14
+ from uuid import UUID
15
+ from typing import Optional
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ router = APIRouter(prefix="/api/admin", tags=["admin"])
20
+
21
+
22
+ async def verify_admin(
23
+ user_id: str = Depends(get_current_user_id),
24
+ tenant_id: str = Depends(get_current_tenant_id),
25
+ db: Session = Depends(get_db)
26
+ ):
27
+ """Verify user is admin"""
28
+ user = AuthService.get_user_by_id(db, UUID(user_id), UUID(tenant_id))
29
+
30
+ if user.role != UserRole.ADMIN:
31
+ raise HTTPException(
32
+ status_code=status.HTTP_403_FORBIDDEN,
33
+ detail="Admin access required"
34
+ )
35
+
36
+ return user
37
+
38
+
39
+ @router.get("/analytics", response_model=AdminAnalyticsResponse)
40
+ async def get_analytics(
41
+ user_id: str = Depends(get_current_user_id),
42
+ tenant_id: str = Depends(get_current_tenant_id),
43
+ db: Session = Depends(get_db),
44
+ admin: User = Depends(verify_admin)
45
+ ):
46
+ """Get platform analytics"""
47
+ try:
48
+ tenant_id_uuid = UUID(tenant_id)
49
+ analytics = RecognitionService.get_analytics(db, tenant_id_uuid)
50
+
51
+ # Get today's stats
52
+ from datetime import datetime, timedelta, timezone
53
+ today = datetime.now(timezone.utc).date()
54
+
55
+ from sqlalchemy import and_, func
56
+ from app.models import RecognitionLog, FaceEmbedding
57
+
58
+ recognitions_today = db.query(func.count(RecognitionLog.id)).filter(
59
+ and_(
60
+ RecognitionLog.tenant_id == tenant_id_uuid,
61
+ func.date(RecognitionLog.timestamp) == today
62
+ )
63
+ ).scalar() or 0
64
+
65
+ faces_today = db.query(func.count(FaceEmbedding.id)).filter(
66
+ and_(
67
+ FaceEmbedding.tenant_id == tenant_id_uuid,
68
+ func.date(FaceEmbedding.created_at) == today
69
+ )
70
+ ).scalar() or 0
71
+
72
+ return AdminAnalyticsResponse(
73
+ total_tenants=1, # For single tenant admin
74
+ total_users=analytics["total_users"],
75
+ total_face_embeddings=analytics["total_face_embeddings"],
76
+ total_recognition_logs=analytics["total_recognition_logs"],
77
+ total_api_calls=0, # Placeholder
78
+ recognitions_today=recognitions_today,
79
+ faces_registered_today=faces_today
80
+ )
81
+
82
+ except Exception as e:
83
+ logger.error(f"Analytics error: {str(e)}")
84
+ raise HTTPException(
85
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
86
+ detail="Failed to get analytics"
87
+ )
88
+
89
+
90
+ @router.get("/users", response_model=list[UserDetailResponse])
91
+ async def list_users(
92
+ skip: int = Query(0, ge=0),
93
+ limit: int = Query(100, ge=1, le=1000),
94
+ user_id: str = Depends(get_current_user_id),
95
+ tenant_id: str = Depends(get_current_tenant_id),
96
+ db: Session = Depends(get_db),
97
+ admin: User = Depends(verify_admin)
98
+ ):
99
+ """List all users in tenant"""
100
+ try:
101
+ tenant_id_uuid = UUID(tenant_id)
102
+
103
+ users = db.query(User).filter(
104
+ User.tenant_id == tenant_id_uuid
105
+ ).offset(skip).limit(limit).all()
106
+
107
+ return users
108
+
109
+ except Exception as e:
110
+ logger.error(f"List users error: {str(e)}")
111
+ raise HTTPException(
112
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
113
+ detail="Failed to list users"
114
+ )
115
+
116
+
117
+ @router.delete("/users/{user_id_to_delete}")
118
+ async def delete_user(
119
+ user_id_to_delete: str,
120
+ user_id: str = Depends(get_current_user_id),
121
+ tenant_id: str = Depends(get_current_tenant_id),
122
+ db: Session = Depends(get_db),
123
+ admin: User = Depends(verify_admin)
124
+ ):
125
+ """Delete a user (admin only)"""
126
+ try:
127
+ tenant_id_uuid = UUID(tenant_id)
128
+ user_to_delete_uuid = UUID(user_id_to_delete)
129
+
130
+ # Prevent self-deletion
131
+ if str(user_to_delete_uuid) == user_id:
132
+ raise ValueError("Cannot delete your own account")
133
+
134
+ user = AuthService.get_user_by_id(db, user_to_delete_uuid, tenant_id_uuid)
135
+
136
+ db.delete(user)
137
+ db.commit()
138
+
139
+ logger.info(f"User deleted: {user_to_delete_uuid}")
140
+ return {"message": "User deleted successfully"}
141
+
142
+ except ValueError as e:
143
+ raise HTTPException(
144
+ status_code=status.HTTP_400_BAD_REQUEST,
145
+ detail=str(e)
146
+ )
147
+ except Exception as e:
148
+ logger.error(f"Delete user error: {str(e)}")
149
+ raise HTTPException(
150
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
151
+ detail="Failed to delete user"
152
+ )
153
+
154
+
155
+ @router.post("/api-keys", response_model=APIKeyCreateResponse)
156
+ async def create_api_key(
157
+ request: APIKeyCreateRequest,
158
+ tenant_id: str = Depends(get_current_tenant_id),
159
+ db: Session = Depends(get_db),
160
+ admin: User = Depends(verify_admin),
161
+ ):
162
+ """Create an API key for third-party integrations. Key is returned once."""
163
+ try:
164
+ api_key, plain_key = APIKeyService.create_api_key(
165
+ db=db,
166
+ tenant_id=UUID(tenant_id),
167
+ key_name=request.key_name,
168
+ )
169
+ return APIKeyCreateResponse(
170
+ id=api_key.id,
171
+ key_name=api_key.key_name,
172
+ is_active=api_key.is_active,
173
+ created_at=api_key.created_at,
174
+ last_used_at=api_key.last_used_at,
175
+ api_key=plain_key,
176
+ )
177
+ except Exception as e:
178
+ logger.error(f"Create API key error: {str(e)}")
179
+ raise HTTPException(
180
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
181
+ detail="Failed to create API key",
182
+ )
183
+
184
+
185
+ @router.get("/api-keys", response_model=list[APIKeyResponse])
186
+ async def list_api_keys(
187
+ tenant_id: str = Depends(get_current_tenant_id),
188
+ db: Session = Depends(get_db),
189
+ admin: User = Depends(verify_admin),
190
+ ):
191
+ try:
192
+ keys = APIKeyService.list_api_keys(db, UUID(tenant_id))
193
+ return keys
194
+ except Exception as e:
195
+ logger.error(f"List API keys error: {str(e)}")
196
+ raise HTTPException(
197
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
198
+ detail="Failed to list API keys",
199
+ )
200
+
201
+
202
+ @router.delete("/api-keys/{api_key_id}", response_model=APIKeyResponse)
203
+ async def revoke_api_key(
204
+ api_key_id: str,
205
+ tenant_id: str = Depends(get_current_tenant_id),
206
+ db: Session = Depends(get_db),
207
+ admin: User = Depends(verify_admin),
208
+ ):
209
+ try:
210
+ revoked = APIKeyService.deactivate_api_key(db, UUID(tenant_id), UUID(api_key_id))
211
+ return revoked
212
+ except ValueError as e:
213
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
214
+ except Exception as e:
215
+ logger.error(f"Revoke API key error: {str(e)}")
216
+ raise HTTPException(
217
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
218
+ detail="Failed to revoke API key",
219
+ )
220
+
221
+
222
+ @router.get("/usage", response_model=UsageMeterResponse)
223
+ async def get_usage(
224
+ period: Optional[str] = None,
225
+ tenant_id: str = Depends(get_current_tenant_id),
226
+ db: Session = Depends(get_db),
227
+ admin: User = Depends(verify_admin),
228
+ ):
229
+ try:
230
+ usage = BillingService.get_usage(db, UUID(tenant_id), period)
231
+ return usage
232
+ except Exception as e:
233
+ logger.error(f"Usage lookup error: {str(e)}")
234
+ raise HTTPException(
235
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
236
+ detail="Failed to get usage",
237
+ )
backend/app/api/api_key_routes.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """User API key management routes"""
2
+ from uuid import UUID
3
+ from fastapi import APIRouter, Depends, HTTPException, status, Request
4
+ from sqlalchemy.orm import Session
5
+
6
+ from app.core.database import get_db
7
+ from app.core.security import get_current_tenant_id, get_current_user_id
8
+ from app.core.rate_limit import limiter, RATE_LIMIT_VALUE
9
+ from app.schemas import APIKeyCreateRequest, APIKeyCreateResponse, APIKeyResponse
10
+ from app.services.api_key_service import APIKeyService
11
+
12
+ router = APIRouter(prefix="/api/keys", tags=["api-keys"])
13
+
14
+
15
+ @router.post("", response_model=APIKeyCreateResponse)
16
+ @limiter.limit(RATE_LIMIT_VALUE)
17
+ async def create_api_key(
18
+ request: Request,
19
+ payload: APIKeyCreateRequest,
20
+ user_id: str = Depends(get_current_user_id),
21
+ tenant_id: str = Depends(get_current_tenant_id),
22
+ db: Session = Depends(get_db),
23
+ ):
24
+ try:
25
+ api_key, plain_key = APIKeyService.create_api_key(
26
+ db=db,
27
+ tenant_id=UUID(tenant_id),
28
+ key_name=payload.key_name,
29
+ user_id=UUID(user_id),
30
+ )
31
+ return APIKeyCreateResponse(
32
+ id=api_key.id,
33
+ key_name=api_key.key_name,
34
+ is_active=api_key.is_active,
35
+ created_at=api_key.created_at,
36
+ last_used_at=api_key.last_used_at,
37
+ api_key=plain_key,
38
+ )
39
+ except Exception as exc:
40
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc))
41
+
42
+
43
+ @router.get("", response_model=list[APIKeyResponse])
44
+ @limiter.limit(RATE_LIMIT_VALUE)
45
+ async def list_api_keys(
46
+ request: Request,
47
+ user_id: str = Depends(get_current_user_id),
48
+ tenant_id: str = Depends(get_current_tenant_id),
49
+ db: Session = Depends(get_db),
50
+ ):
51
+ try:
52
+ keys = APIKeyService.list_user_api_keys(db, UUID(tenant_id), UUID(user_id))
53
+ return keys
54
+ except Exception as exc:
55
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc))
56
+
57
+
58
+ @router.delete("/{api_key_id}", response_model=APIKeyResponse)
59
+ @limiter.limit(RATE_LIMIT_VALUE)
60
+ async def revoke_api_key(
61
+ request: Request,
62
+ api_key_id: str,
63
+ user_id: str = Depends(get_current_user_id),
64
+ tenant_id: str = Depends(get_current_tenant_id),
65
+ db: Session = Depends(get_db),
66
+ ):
67
+ try:
68
+ revoked = APIKeyService.deactivate_user_api_key(db, UUID(tenant_id), UUID(user_id), UUID(api_key_id))
69
+ return revoked
70
+ except ValueError as exc:
71
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
72
+ except Exception as exc:
73
+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc))
backend/app/api/auth_routes.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Authentication routes"""
2
+ from fastapi import APIRouter, HTTPException, status, Depends
3
+ from sqlalchemy.orm import Session
4
+ import logging
5
+
6
+ from app.schemas import (
7
+ UserRegisterRequest, UserLoginRequest, TokenResponse,
8
+ TokenRefreshRequest, UserResponse, TenantRegisterRequest, TenantResponse
9
+ )
10
+ from app.core.database import get_db
11
+ from app.core.security import get_current_user_token, get_current_user_id, get_current_tenant_id
12
+ from app.services.auth_service import AuthService, TenantService
13
+ from app.models import User
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ router = APIRouter(prefix="/api/auth", tags=["auth"])
18
+
19
+
20
+ @router.post("/register", response_model=dict)
21
+ async def register(
22
+ request: UserRegisterRequest,
23
+ db: Session = Depends(get_db)
24
+ ):
25
+ """Register a new user and tenant"""
26
+ try:
27
+ # Create or get tenant
28
+ if request.tenant_id:
29
+ tenant = TenantService.get_tenant_by_id(db, request.tenant_id)
30
+ else:
31
+ # Create new tenant from email domain
32
+ domain = request.email.split("@")[1]
33
+ tenant = TenantService.create_tenant(db, f"org-{domain}")
34
+
35
+ # Register user
36
+ user = AuthService.register_user(
37
+ db=db,
38
+ email=request.email,
39
+ password=request.password,
40
+ full_name=request.full_name or request.email.split("@")[0],
41
+ tenant_id=tenant.id
42
+ )
43
+
44
+ # Create tokens
45
+ tokens = AuthService.create_tokens(user)
46
+
47
+ return {
48
+ "user": UserResponse.from_orm(user),
49
+ "tokens": tokens,
50
+ "tenant": TenantResponse.from_orm(tenant)
51
+ }
52
+
53
+ except ValueError as e:
54
+ raise HTTPException(
55
+ status_code=status.HTTP_400_BAD_REQUEST,
56
+ detail=str(e)
57
+ )
58
+ except Exception as e:
59
+ logger.error(f"Registration error: {str(e)}")
60
+ raise HTTPException(
61
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
62
+ detail="Registration failed"
63
+ )
64
+
65
+
66
+ @router.post("/login", response_model=TokenResponse)
67
+ async def login(
68
+ request: UserLoginRequest,
69
+ db: Session = Depends(get_db)
70
+ ):
71
+ """Login and get access token"""
72
+ try:
73
+ # For login, we need tenant_id - for now assume single tenant per email
74
+ # In production, might need to prompt for tenant selection
75
+
76
+ # Try to find user by email (across all tenants - will improve later)
77
+ user = db.query(User).filter(User.email == request.email).first()
78
+
79
+ if not user:
80
+ raise HTTPException(
81
+ status_code=status.HTTP_401_UNAUTHORIZED,
82
+ detail="Invalid email or password"
83
+ )
84
+
85
+ # Authenticate
86
+ authenticated_user = AuthService.authenticate_user(
87
+ db=db,
88
+ email=request.email,
89
+ password=request.password,
90
+ tenant_id=user.tenant_id
91
+ )
92
+
93
+ # Create tokens
94
+ tokens = AuthService.create_tokens(authenticated_user)
95
+
96
+ return tokens
97
+
98
+ except ValueError as e:
99
+ raise HTTPException(
100
+ status_code=status.HTTP_401_UNAUTHORIZED,
101
+ detail=str(e)
102
+ )
103
+ except Exception as e:
104
+ logger.error(f"Login error: {str(e)}")
105
+ raise HTTPException(
106
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
107
+ detail="Login failed"
108
+ )
109
+
110
+
111
+ @router.post("/refresh", response_model=TokenResponse)
112
+ async def refresh_token(request: TokenRefreshRequest):
113
+ """Refresh access token"""
114
+ try:
115
+ tokens = AuthService.refresh_access_token(request.refresh_token)
116
+ return tokens
117
+ except ValueError as e:
118
+ raise HTTPException(
119
+ status_code=status.HTTP_401_UNAUTHORIZED,
120
+ detail=str(e)
121
+ )
122
+
123
+
124
+ @router.get("/me", response_model=UserResponse)
125
+ async def get_current_user(
126
+ user_id: str = Depends(get_current_user_id),
127
+ tenant_id: str = Depends(get_current_tenant_id),
128
+ db: Session = Depends(get_db)
129
+ ):
130
+ """Get current user info"""
131
+ try:
132
+ from uuid import UUID
133
+ user = AuthService.get_user_by_id(db, UUID(user_id), UUID(tenant_id))
134
+ return user
135
+ except ValueError as e:
136
+ raise HTTPException(
137
+ status_code=status.HTTP_404_NOT_FOUND,
138
+ detail=str(e)
139
+ )
backend/app/api/external_routes.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Third-party API routes authenticated by X-API-Key."""
2
+ from typing import List, Optional
3
+ import logging
4
+ import time
5
+ from uuid import UUID
6
+
7
+ from fastapi import APIRouter, Depends, File, Form, Header, HTTPException, UploadFile, status, Request
8
+ from sqlalchemy.orm import Session
9
+
10
+ from app.api.face_routes import create_three_angle_embedding
11
+ from app.core.config import settings
12
+ from app.core.rate_limit import limiter, RATE_LIMIT_VALUE
13
+ from app.core.database import get_db
14
+ from app.schemas import FaceEmbeddingResponse, FaceRecognitionResponse, RecognizedFace
15
+ from app.services.api_key_service import APIKeyService
16
+ from app.models import User
17
+ from app.services.recognition_service import RecognitionService
18
+ from app.services.billing_service import BillingService
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ router = APIRouter(prefix="/api/v1", tags=["third-party"])
23
+
24
+
25
+ async def get_api_key_context(
26
+ x_api_key: str = Header(..., alias="X-API-Key"),
27
+ db: Session = Depends(get_db),
28
+ ):
29
+ api_key = APIKeyService.get_active_api_key(db, x_api_key)
30
+ if not api_key:
31
+ raise HTTPException(
32
+ status_code=status.HTTP_401_UNAUTHORIZED,
33
+ detail="Invalid or inactive API key",
34
+ )
35
+
36
+ actor_user = APIKeyService.get_tenant_actor_user(db, api_key.tenant_id)
37
+ if api_key.user_id:
38
+ user = db.query(User).filter(User.id == api_key.user_id).first()
39
+ if user:
40
+ actor_user = user
41
+ return api_key, actor_user
42
+
43
+
44
+ @router.post("/faces/register", response_model=FaceEmbeddingResponse)
45
+ @limiter.limit(RATE_LIMIT_VALUE)
46
+ async def third_party_register_face(
47
+ request: Request,
48
+ person_id: str = Form(...),
49
+ images: List[UploadFile] = File(...),
50
+ metadata: Optional[str] = Form(None),
51
+ context=Depends(get_api_key_context),
52
+ db: Session = Depends(get_db),
53
+ ):
54
+ """Register one person using exactly 3 single-person different-angle images."""
55
+ try:
56
+ api_key, actor_user = context
57
+
58
+ if EmbeddingService.person_id_exists(db, api_key.tenant_id, person_id):
59
+ raise ValueError("This person ID is already occupied")
60
+
61
+ BillingService.record_api_call(db, api_key.tenant_id, actor_user.id)
62
+ return await create_three_angle_embedding(
63
+ db=db,
64
+ tenant_id=api_key.tenant_id,
65
+ user_id_uuid=actor_user.id,
66
+ person_id=person_id,
67
+ name=person_id,
68
+ images=images,
69
+ metadata=metadata,
70
+ )
71
+ except ValueError as e:
72
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
73
+ except Exception as e:
74
+ logger.error(f"Third-party face registration error: {str(e)}")
75
+ raise HTTPException(
76
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
77
+ detail="Face registration failed",
78
+ )
79
+
80
+
81
+ @router.post("/faces/recognize", response_model=FaceRecognitionResponse)
82
+ @limiter.limit(RATE_LIMIT_VALUE)
83
+ async def third_party_recognize_face(
84
+ request: Request,
85
+ image: UploadFile = File(...),
86
+ threshold: Optional[float] = Form(settings.FACE_RECOGNITION_THRESHOLD),
87
+ return_bboxes: Optional[bool] = Form(True),
88
+ context=Depends(get_api_key_context),
89
+ db: Session = Depends(get_db),
90
+ ):
91
+ """Recognize faces from one image using X-API-Key tenant context."""
92
+ start_time = time.time()
93
+
94
+ try:
95
+ api_key, actor_user = context
96
+ tenant_id_uuid: UUID = api_key.tenant_id
97
+
98
+ image_bytes = await image.read()
99
+ result = RecognitionService.recognize_from_bytes(
100
+ db=db,
101
+ image_bytes=image_bytes,
102
+ tenant_id=tenant_id_uuid,
103
+ user_id=actor_user.id,
104
+ threshold=threshold,
105
+ return_bboxes=return_bboxes,
106
+ source="third_party_api",
107
+ )
108
+
109
+ return FaceRecognitionResponse(
110
+ faces_detected=result["faces_detected"],
111
+ recognized=[RecognizedFace(**face) for face in result["recognized"]],
112
+ unrecognized_count=result["unrecognized_count"],
113
+ processing_time_ms=(time.time() - start_time) * 1000,
114
+ )
115
+ except ValueError as e:
116
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
117
+ except Exception as e:
118
+ logger.error(f"Third-party face recognition error: {str(e)}")
119
+ raise HTTPException(
120
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
121
+ detail="Face recognition failed",
122
+ )
backend/app/api/face_routes.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Face recognition and embedding routes"""
2
+ from fastapi import APIRouter, HTTPException, status, Depends, UploadFile, File, Form, Query, Request
3
+ from sqlalchemy.orm import Session
4
+ import logging
5
+ import numpy as np
6
+ from typing import Optional, List
7
+ import time
8
+ import json
9
+
10
+ from app.schemas import (
11
+ FaceEmbeddingResponse, FaceEmbeddingDetailResponse,
12
+ FaceRecognitionResponse, RecognizedFace, RecognitionLogResponse,
13
+ AsyncTaskResponse
14
+ )
15
+ from app.core.database import get_db
16
+ from app.core.security import get_current_user_id, get_current_tenant_id
17
+ from app.core.config import settings
18
+ from app.core.rate_limit import limiter, RATE_LIMIT_VALUE
19
+ from app.services.recognition_service import EmbeddingService, RecognitionService
20
+ from app.services.billing_service import BillingService
21
+ from app.utils.common import ImageUtils, FaceUtils
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ router = APIRouter(prefix="/api/face", tags=["face"])
26
+
27
+
28
+ async def create_three_angle_embedding(
29
+ *,
30
+ db: Session,
31
+ tenant_id,
32
+ user_id_uuid,
33
+ person_id: str = Form(...),
34
+ name: str = Form(...),
35
+ images: List[UploadFile] = File(...),
36
+ metadata: Optional[str] = Form(None),
37
+ ) -> FaceEmbeddingResponse:
38
+ if len(images) != 3:
39
+ raise ValueError("Exactly 3 face images are required")
40
+
41
+ embeddings = []
42
+ image_hashes = []
43
+ angles = []
44
+ quality_scores = []
45
+
46
+ FaceUtils.init_detector()
47
+
48
+ for index, image in enumerate(images, start=1):
49
+ image_bytes = await image.read()
50
+
51
+ if not ImageUtils.validate_image(image_bytes, settings.MAX_UPLOAD_SIZE // (1024 * 1024)):
52
+ raise ValueError(f"Image {index} is invalid or too large")
53
+
54
+ image_hashes.append(ImageUtils.compute_image_hash(image_bytes))
55
+
56
+ pil_image = ImageUtils.load_image_from_bytes(image_bytes)
57
+ pil_image = ImageUtils.resize_image(pil_image)
58
+ image_array = np.array(pil_image)
59
+ faces = FaceUtils.detect_faces(image_array)
60
+
61
+ if len(faces) == 0:
62
+ raise ValueError(f"Image {index}: no face detected")
63
+
64
+ if len(faces) > 1:
65
+ raise ValueError(f"Image {index}: multiple people detected. Only one person allowed per frame")
66
+
67
+ face = faces[0]
68
+ face_angle = FaceUtils.get_face_angle(face)
69
+ if face_angle == "unknown":
70
+ raise ValueError(f"Image {index}: face angle could not be verified")
71
+
72
+ angles.append(face_angle)
73
+ quality_scores.append(FaceUtils.get_face_quality(face))
74
+ embeddings.append(FaceUtils.get_face_embedding(image_array, face).astype(np.float32))
75
+
76
+ if len(set(image_hashes)) != 3:
77
+ raise ValueError("Duplicate images are not allowed")
78
+
79
+ if len(set(angles)) != 3:
80
+ raise ValueError(f"Images must show 3 different face angles. Detected: {', '.join(angles)}")
81
+
82
+ detailed_embedding = np.mean(np.stack(embeddings), axis=0)
83
+ norm = np.linalg.norm(detailed_embedding)
84
+ if norm > 0:
85
+ detailed_embedding = detailed_embedding / norm
86
+
87
+ metadata_payload = {
88
+ "registration_mode": "three_angle_detailed",
89
+ "angles": angles,
90
+ "quality_scores": quality_scores,
91
+ "image_hashes": image_hashes,
92
+ "user_metadata": metadata,
93
+ }
94
+
95
+ db_embedding = EmbeddingService.create_embedding(
96
+ db=db,
97
+ tenant_id=tenant_id,
98
+ user_id=user_id_uuid,
99
+ person_id=person_id,
100
+ name=name,
101
+ embedding_vector=detailed_embedding,
102
+ image_url=None,
103
+ image_hash=ImageUtils.compute_image_hash("|".join(image_hashes).encode("utf-8")),
104
+ face_quality_score=float(np.mean(quality_scores)),
105
+ face_angle=",".join(angles),
106
+ metadata=json.dumps(metadata_payload),
107
+ )
108
+
109
+ return FaceEmbeddingResponse.from_orm(db_embedding)
110
+
111
+
112
+ @router.post("/register", response_model=FaceEmbeddingResponse)
113
+ @limiter.limit(RATE_LIMIT_VALUE)
114
+ async def register_face(
115
+ request: Request,
116
+ person_id: str = Form(...),
117
+ images: List[UploadFile] = File(...),
118
+ metadata: Optional[str] = Form(None),
119
+ user_id: str = Depends(get_current_user_id),
120
+ tenant_id: str = Depends(get_current_tenant_id),
121
+ db: Session = Depends(get_db)
122
+ ):
123
+ """Register a face from exactly 3 single-person images with different angles."""
124
+ try:
125
+ from uuid import UUID
126
+ user_id_uuid = UUID(user_id)
127
+ tenant_id_uuid = UUID(tenant_id)
128
+
129
+ if EmbeddingService.person_id_exists(db, tenant_id_uuid, person_id):
130
+ raise ValueError("This person ID is already occupied")
131
+
132
+ BillingService.record_api_call(db, tenant_id_uuid, user_id_uuid)
133
+ return await create_three_angle_embedding(
134
+ db=db,
135
+ tenant_id=tenant_id_uuid,
136
+ user_id_uuid=user_id_uuid,
137
+ person_id=person_id,
138
+ name=person_id,
139
+ images=images,
140
+ metadata=metadata,
141
+ )
142
+
143
+ except ValueError as e:
144
+ raise HTTPException(
145
+ status_code=status.HTTP_400_BAD_REQUEST,
146
+ detail=str(e)
147
+ )
148
+ except Exception as e:
149
+ logger.error(f"Face registration error: {str(e)}")
150
+ raise HTTPException(
151
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
152
+ detail="Face registration failed"
153
+ )
154
+
155
+
156
+ @router.post("/recognize", response_model=FaceRecognitionResponse)
157
+ @limiter.limit(RATE_LIMIT_VALUE)
158
+ async def recognize_face(
159
+ request: Request,
160
+ image: UploadFile = File(...),
161
+ threshold: Optional[float] = Form(settings.FACE_RECOGNITION_THRESHOLD),
162
+ return_bboxes: Optional[bool] = Form(True),
163
+ user_id: str = Depends(get_current_user_id),
164
+ tenant_id: str = Depends(get_current_tenant_id),
165
+ db: Session = Depends(get_db)
166
+ ):
167
+ """Recognize faces in an image"""
168
+ start_time = time.time()
169
+
170
+ try:
171
+ from uuid import UUID
172
+ user_id_uuid = UUID(user_id)
173
+ tenant_id_uuid = UUID(tenant_id)
174
+
175
+ # Read image
176
+ image_bytes = await image.read()
177
+
178
+ result = RecognitionService.recognize_from_bytes(
179
+ db=db,
180
+ image_bytes=image_bytes,
181
+ tenant_id=tenant_id_uuid,
182
+ user_id=user_id_uuid,
183
+ threshold=threshold,
184
+ return_bboxes=return_bboxes,
185
+ source="api",
186
+ )
187
+
188
+ processing_time_ms = (time.time() - start_time) * 1000
189
+
190
+ return FaceRecognitionResponse(
191
+ faces_detected=result["faces_detected"],
192
+ recognized=[RecognizedFace(**face) for face in result["recognized"]],
193
+ unrecognized_count=result["unrecognized_count"],
194
+ processing_time_ms=processing_time_ms,
195
+ )
196
+
197
+ except ValueError as e:
198
+ raise HTTPException(
199
+ status_code=status.HTTP_400_BAD_REQUEST,
200
+ detail=str(e)
201
+ )
202
+ except Exception as e:
203
+ logger.error(f"Face recognition error: {str(e)}")
204
+ raise HTTPException(
205
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
206
+ detail="Face recognition failed"
207
+ )
208
+
209
+
210
+ @router.get("/embeddings", response_model=list[FaceEmbeddingDetailResponse])
211
+ @limiter.limit(RATE_LIMIT_VALUE)
212
+ async def list_embeddings(
213
+ request: Request,
214
+ person_id: Optional[str] = Query(None),
215
+ skip: int = Query(0, ge=0),
216
+ limit: int = Query(100, ge=1, le=1000),
217
+ user_id: str = Depends(get_current_user_id),
218
+ tenant_id: str = Depends(get_current_tenant_id),
219
+ db: Session = Depends(get_db)
220
+ ):
221
+ """List face embeddings for current tenant"""
222
+ try:
223
+ from uuid import UUID
224
+ tenant_id_uuid = UUID(tenant_id)
225
+
226
+ embeddings = EmbeddingService.get_tenant_embeddings(
227
+ db=db,
228
+ tenant_id=tenant_id_uuid,
229
+ person_id=person_id,
230
+ skip=skip,
231
+ limit=limit
232
+ )
233
+
234
+ return embeddings
235
+
236
+ except Exception as e:
237
+ logger.error(f"List embeddings error: {str(e)}")
238
+ raise HTTPException(
239
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
240
+ detail="Failed to list embeddings"
241
+ )
242
+
243
+
244
+ @router.get("/logs", response_model=list[RecognitionLogResponse])
245
+ @limiter.limit(RATE_LIMIT_VALUE)
246
+ async def list_recognition_logs(
247
+ request: Request,
248
+ skip: int = Query(0, ge=0),
249
+ limit: int = Query(100, ge=1, le=1000),
250
+ user_id: str = Depends(get_current_user_id),
251
+ tenant_id: str = Depends(get_current_tenant_id),
252
+ db: Session = Depends(get_db)
253
+ ):
254
+ """Get recognition logs"""
255
+ try:
256
+ from uuid import UUID
257
+ user_id_uuid = UUID(user_id)
258
+ tenant_id_uuid = UUID(tenant_id)
259
+
260
+ logs = RecognitionService.get_recognition_logs(
261
+ db=db,
262
+ tenant_id=tenant_id_uuid,
263
+ user_id=user_id_uuid,
264
+ skip=skip,
265
+ limit=limit
266
+ )
267
+
268
+ return logs
269
+
270
+ except Exception as e:
271
+ logger.error(f"Get logs error: {str(e)}")
272
+ raise HTTPException(
273
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
274
+ detail="Failed to get logs"
275
+ )
276
+
277
+
278
+ @router.delete("/embeddings/{embedding_id}")
279
+ @limiter.limit(RATE_LIMIT_VALUE)
280
+ async def delete_embedding(
281
+ request: Request,
282
+ embedding_id: str,
283
+ user_id: str = Depends(get_current_user_id),
284
+ tenant_id: str = Depends(get_current_tenant_id),
285
+ db: Session = Depends(get_db)
286
+ ):
287
+ """Delete a face embedding"""
288
+ try:
289
+ from uuid import UUID
290
+ embedding_uuid = UUID(embedding_id)
291
+ tenant_id_uuid = UUID(tenant_id)
292
+
293
+ EmbeddingService.delete_embedding(
294
+ db=db,
295
+ embedding_id=embedding_uuid,
296
+ tenant_id=tenant_id_uuid
297
+ )
298
+
299
+ return {"message": "Embedding deleted successfully"}
300
+
301
+ except ValueError as e:
302
+ raise HTTPException(
303
+ status_code=status.HTTP_404_NOT_FOUND,
304
+ detail=str(e)
305
+ )
306
+ except Exception as e:
307
+ logger.error(f"Delete embedding error: {str(e)}")
308
+ raise HTTPException(
309
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
310
+ detail="Failed to delete embedding"
311
+ )
312
+
313
+
314
+ @router.post("/recognize/async", response_model=AsyncTaskResponse)
315
+ @limiter.limit(RATE_LIMIT_VALUE)
316
+ async def recognize_face_async(
317
+ request: Request,
318
+ image: UploadFile = File(...),
319
+ threshold: Optional[float] = Form(settings.FACE_RECOGNITION_THRESHOLD),
320
+ return_bboxes: Optional[bool] = Form(True),
321
+ user_id: str = Depends(get_current_user_id),
322
+ tenant_id: str = Depends(get_current_tenant_id),
323
+ ):
324
+ if not settings.RECOGNITION_ASYNC_ENABLED:
325
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Async recognition is disabled")
326
+
327
+ from app.workers.tasks import recognize_face_task
328
+ from uuid import UUID
329
+ import base64
330
+
331
+ image_bytes = await image.read()
332
+ task = recognize_face_task.delay(
333
+ base64.b64encode(image_bytes).decode("utf-8"),
334
+ str(UUID(tenant_id)),
335
+ str(UUID(user_id)),
336
+ float(threshold),
337
+ bool(return_bboxes),
338
+ )
339
+ return AsyncTaskResponse(task_id=task.id)
340
+
341
+
342
+ @router.get("/recognize/async/{task_id}")
343
+ @limiter.limit(RATE_LIMIT_VALUE)
344
+ async def get_async_result(
345
+ request: Request,
346
+ task_id: str,
347
+ ):
348
+ from app.workers.celery_app import celery_app
349
+ result = celery_app.AsyncResult(task_id)
350
+ if result.ready():
351
+ return {"status": result.status, "result": result.result}
352
+ return {"status": result.status}
backend/app/api/webhook_routes.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Webhook management routes"""
2
+ from uuid import UUID
3
+ from fastapi import APIRouter, Depends, HTTPException, Query, status, Request
4
+ from sqlalchemy.orm import Session
5
+
6
+ from app.core.database import get_db
7
+ from app.core.security import get_current_tenant_id
8
+ from app.core.rate_limit import limiter, RATE_LIMIT_VALUE
9
+ from app.schemas import WebhookCreateRequest, WebhookResponse
10
+ from app.services.webhook_service import WebhookService
11
+
12
+ router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])
13
+
14
+
15
+ @router.post("", response_model=WebhookResponse)
16
+ @limiter.limit(RATE_LIMIT_VALUE)
17
+ async def create_webhook(
18
+ request: Request,
19
+ payload: WebhookCreateRequest,
20
+ tenant_id: str = Depends(get_current_tenant_id),
21
+ db: Session = Depends(get_db),
22
+ ):
23
+ try:
24
+ endpoint = WebhookService.create_endpoint(db, UUID(tenant_id), payload.url, payload.secret)
25
+ return endpoint
26
+ except Exception as exc:
27
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
28
+
29
+
30
+ @router.get("", response_model=list[WebhookResponse])
31
+ @limiter.limit(RATE_LIMIT_VALUE)
32
+ async def list_webhooks(
33
+ request: Request,
34
+ tenant_id: str = Depends(get_current_tenant_id),
35
+ db: Session = Depends(get_db),
36
+ ):
37
+ return WebhookService.list_endpoints(db, UUID(tenant_id))
38
+
39
+
40
+ @router.delete("/{endpoint_id}")
41
+ @limiter.limit(RATE_LIMIT_VALUE)
42
+ async def delete_webhook(
43
+ request: Request,
44
+ endpoint_id: str,
45
+ tenant_id: str = Depends(get_current_tenant_id),
46
+ db: Session = Depends(get_db),
47
+ ):
48
+ try:
49
+ WebhookService.delete_endpoint(db, UUID(tenant_id), UUID(endpoint_id))
50
+ return {"message": "Webhook deleted"}
51
+ except ValueError as exc:
52
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
backend/app/core/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Core module - Configuration, security, and database setup"""
backend/app/core/config.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Application configuration"""
2
+ import os
3
+ from typing import Optional
4
+ from pydantic import field_validator
5
+ from pydantic_settings import BaseSettings
6
+
7
+
8
+ class Settings(BaseSettings):
9
+ """Application settings from environment variables"""
10
+
11
+ # App
12
+ APP_NAME: str = "Face Inference SaaS Platform"
13
+ APP_VERSION: str = "1.0.0"
14
+ DEBUG: bool = os.getenv("DEBUG", "False").lower() == "true"
15
+ ADMIN_DEFAULT_EMAIL: str = os.getenv("ADMIN_DEFAULT_EMAIL", "admin@fmproject.dev")
16
+ ADMIN_DEFAULT_PASSWORD: str = os.getenv("ADMIN_DEFAULT_PASSWORD", "Admin@123456")
17
+
18
+ # Database
19
+ DATABASE_URL: str = os.getenv(
20
+ "DATABASE_URL",
21
+ "mysql+pymysql://fmproject:fmproject_password@localhost:3306/fmproject_db"
22
+ )
23
+
24
+ # JWT
25
+ SECRET_KEY: str = os.getenv(
26
+ "SECRET_KEY",
27
+ "your-secret-key-change-in-production"
28
+ )
29
+ ALGORITHM: str = "HS256"
30
+ ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
31
+ REFRESH_TOKEN_EXPIRE_DAYS: int = 7
32
+
33
+ # Redis
34
+ REDIS_URL: str = os.getenv("REDIS_URL", "redis://localhost:6379")
35
+
36
+ # S3 / Object Storage
37
+ S3_ENDPOINT: str = os.getenv("S3_ENDPOINT", "http://localhost:9000")
38
+ S3_ACCESS_KEY: str = os.getenv("S3_ACCESS_KEY", "minioadmin")
39
+ S3_SECRET_KEY: str = os.getenv("S3_SECRET_KEY", "minioadmin")
40
+ S3_BUCKET: str = os.getenv("S3_BUCKET", "face-embeddings")
41
+ S3_REGION: str = os.getenv("S3_REGION", "us-east-1")
42
+
43
+ # InsightFace
44
+ INSIGHTFACE_MODEL: str = os.getenv("INSIGHTFACE_MODEL", "buffalo_l")
45
+ INSIGHTFACE_GPU: bool = os.getenv("INSIGHTFACE_GPU", "False").lower() == "true"
46
+ INSIGHTFACE_GPU_AUTO: bool = os.getenv("INSIGHTFACE_GPU_AUTO", "True").lower() == "true"
47
+ FACE_RECOGNITION_THRESHOLD: float = 0.5
48
+ FACE_EMBEDDING_DIM: int = int(os.getenv("FACE_EMBEDDING_DIM", "512"))
49
+
50
+ # Face angle thresholds (yaw degrees)
51
+ FACE_ANGLE_FRONTAL_MAX_YAW: float = float(os.getenv("FACE_ANGLE_FRONTAL_MAX_YAW", "20"))
52
+ FACE_ANGLE_HALF_PROFILE_MAX_YAW: float = float(os.getenv("FACE_ANGLE_HALF_PROFILE_MAX_YAW", "55"))
53
+ # When False, registration skips the 3-angle requirement
54
+ FACE_ANGLE_REQUIRE_VALIDATION: bool = os.getenv("FACE_ANGLE_REQUIRE_VALIDATION", "True").lower() == "true"
55
+
56
+ # Qdrant
57
+ QDRANT_URL: str = os.getenv("QDRANT_URL", "")
58
+ QDRANT_API_KEY: str = os.getenv("QDRANT_API_KEY", "")
59
+ QDRANT_COLLECTION: str = os.getenv("QDRANT_COLLECTION", "face_embeddings")
60
+ QDRANT_ENABLE: bool = os.getenv("QDRANT_ENABLE", "True").lower() == "true"
61
+
62
+ # Async recognition queue (Celery)
63
+ CELERY_BROKER_URL: str = os.getenv("CELERY_BROKER_URL", REDIS_URL)
64
+ CELERY_RESULT_BACKEND: str = os.getenv("CELERY_RESULT_BACKEND", REDIS_URL)
65
+ RECOGNITION_ASYNC_ENABLED: bool = os.getenv("RECOGNITION_ASYNC_ENABLED", "True").lower() == "true"
66
+
67
+ # Security
68
+ CORS_ORIGINS: list = [
69
+ "http://localhost:3000",
70
+ "http://127.0.0.1:3000",
71
+ "http://localhost:5173",
72
+ "http://127.0.0.1:5173",
73
+ ]
74
+ MAX_UPLOAD_SIZE: int = 10 * 1024 * 1024 # 10MB
75
+
76
+ # Rate Limiting
77
+ RATE_LIMIT_ENABLED: bool = os.getenv("RATE_LIMIT_ENABLED", "True").lower() == "true"
78
+ RATE_LIMIT_PER_MINUTE: int = int(os.getenv("RATE_LIMIT_PER_MINUTE", "100"))
79
+
80
+ # Webhooks
81
+ WEBHOOK_MAX_RETRIES: int = int(os.getenv("WEBHOOK_MAX_RETRIES", "5"))
82
+ WEBHOOK_TIMEOUT_SECONDS: int = int(os.getenv("WEBHOOK_TIMEOUT_SECONDS", "5"))
83
+
84
+ # Billing (Stripe placeholders)
85
+ STRIPE_ENABLED: bool = os.getenv("STRIPE_ENABLED", "False").lower() == "true"
86
+ STRIPE_SECRET_KEY: str = os.getenv("STRIPE_SECRET_KEY", "")
87
+ STRIPE_WEBHOOK_SECRET: str = os.getenv("STRIPE_WEBHOOK_SECRET", "")
88
+
89
+ @field_validator("DEBUG", mode="before")
90
+ @classmethod
91
+ def parse_debug(cls, value):
92
+ if isinstance(value, str):
93
+ normalized = value.strip().lower()
94
+ if normalized in {"release", "prod", "production", "false", "0", "no", "off"}:
95
+ return False
96
+ if normalized in {"debug", "dev", "development", "true", "1", "yes", "on"}:
97
+ return True
98
+ return value
99
+
100
+ class Config:
101
+ env_file = ".env"
102
+ case_sensitive = True
103
+
104
+
105
+ settings = Settings()
backend/app/core/database.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Database configuration and session management"""
2
+ from sqlalchemy import create_engine, event
3
+ from sqlalchemy.orm import sessionmaker, Session, declarative_base
4
+ from contextlib import contextmanager
5
+ from typing import Generator
6
+ import logging
7
+
8
+ from app.core.config import settings
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ # Create engine
13
+ engine = create_engine(
14
+ settings.DATABASE_URL,
15
+ echo=settings.DEBUG,
16
+ pool_pre_ping=True,
17
+ pool_size=20,
18
+ max_overflow=40,
19
+ )
20
+
21
+ # Session factory
22
+ SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
23
+
24
+ # Base class for ORM models
25
+ Base = declarative_base()
26
+
27
+
28
+ def get_db() -> Generator[Session, None, None]:
29
+ """Dependency injection for database sessions"""
30
+ db = SessionLocal()
31
+ try:
32
+ yield db
33
+ finally:
34
+ db.close()
35
+
36
+
37
+ @contextmanager
38
+ def get_db_context() -> Generator[Session, None, None]:
39
+ """Context manager for database sessions"""
40
+ db = SessionLocal()
41
+ try:
42
+ yield db
43
+ finally:
44
+ db.close()
45
+
46
+
47
+ def init_db() -> None:
48
+ """Initialize database tables"""
49
+ Base.metadata.create_all(bind=engine)
50
+ logger.info("Database initialized")
51
+
52
+
53
+ # Enable foreign key constraints for SQLite (for development)
54
+ @event.listens_for(engine, "connect")
55
+ def set_sqlite_pragma(dbapi_conn, connection_record):
56
+ if "sqlite" in settings.DATABASE_URL:
57
+ cursor = dbapi_conn.cursor()
58
+ cursor.execute("PRAGMA foreign_keys=ON")
59
+ cursor.close()
backend/app/core/middleware.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Multi-tenant middleware"""
2
+ from fastapi import Request, HTTPException, status
3
+ from starlette.middleware.base import BaseHTTPMiddleware
4
+ import logging
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ class MultiTenantMiddleware(BaseHTTPMiddleware):
10
+ """
11
+ Middleware to enforce multi-tenant isolation.
12
+ Ensures tenant_id in JWT matches the request context.
13
+ """
14
+
15
+ async def dispatch(self, request: Request, call_next):
16
+ # Skip middleware for public endpoints
17
+ public_paths = ["/health", "/", "/docs", "/openapi.json", "/api/auth/register", "/api/auth/login"]
18
+
19
+ if request.url.path in public_paths:
20
+ return await call_next(request)
21
+
22
+ # For protected endpoints, validate tenant isolation
23
+ # This is a basic implementation - can be enhanced
24
+
25
+ response = await call_next(request)
26
+ return response
27
+
28
+
29
+ class TenantContextMiddleware(BaseHTTPMiddleware):
30
+ """
31
+ Middleware to store tenant context in request state.
32
+ Makes tenant_id accessible throughout the request lifecycle.
33
+ """
34
+
35
+ async def dispatch(self, request: Request, call_next):
36
+ # Extract tenant_id from token if available
37
+ from app.core.security import decode_token
38
+
39
+ auth_header = request.headers.get("Authorization")
40
+ tenant_id = None
41
+
42
+ if auth_header:
43
+ try:
44
+ token = auth_header.replace("Bearer ", "")
45
+ payload = decode_token(token)
46
+ tenant_id = payload.get("tenant_id")
47
+ except Exception:
48
+ pass
49
+
50
+ # Store in request state
51
+ request.state.tenant_id = tenant_id
52
+
53
+ response = await call_next(request)
54
+ return response
backend/app/core/rate_limit.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rate limiting configuration"""
2
+ from fastapi import Request
3
+ from slowapi import Limiter
4
+ from slowapi.util import get_remote_address
5
+
6
+ from app.core.config import settings
7
+
8
+
9
+ def _rate_limit_key(request: Request) -> str:
10
+ api_key = request.headers.get("X-API-Key")
11
+ if api_key:
12
+ return f"api_key:{api_key}"
13
+
14
+ auth_header = request.headers.get("Authorization")
15
+ if auth_header:
16
+ return f"auth:{auth_header}"
17
+
18
+ return get_remote_address(request)
19
+
20
+
21
+ limiter = Limiter(key_func=_rate_limit_key)
22
+
23
+ if settings.RATE_LIMIT_ENABLED:
24
+ RATE_LIMIT_VALUE = f"{settings.RATE_LIMIT_PER_MINUTE}/minute"
25
+ else:
26
+ RATE_LIMIT_VALUE = "1000000/minute"
backend/app/core/security.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Security utilities - JWT, hashing, tenant isolation"""
2
+ from datetime import datetime, timedelta, timezone
3
+ from typing import Optional, Dict, Any
4
+ import jwt
5
+ from passlib.context import CryptContext
6
+ from fastapi import HTTPException, status, Depends
7
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
8
+ import logging
9
+
10
+ from app.core.config import settings
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # Password hashing
15
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
16
+
17
+ # Bearer token
18
+ security = HTTPBearer()
19
+
20
+
21
+ def hash_password(password: str) -> str:
22
+ """Hash password using bcrypt"""
23
+ return pwd_context.hash(password)
24
+
25
+
26
+ def verify_password(plain_password: str, hashed_password: str) -> bool:
27
+ """Verify password against hash"""
28
+ return pwd_context.verify(plain_password, hashed_password)
29
+
30
+
31
+ def create_access_token(
32
+ data: Dict[str, Any],
33
+ expires_delta: Optional[timedelta] = None
34
+ ) -> str:
35
+ """Create JWT access token"""
36
+ to_encode = data.copy()
37
+
38
+ if expires_delta:
39
+ expire = datetime.now(timezone.utc) + expires_delta
40
+ else:
41
+ expire = datetime.now(timezone.utc) + timedelta(
42
+ minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
43
+ )
44
+
45
+ to_encode.update({"exp": expire})
46
+ encoded_jwt = jwt.encode(
47
+ to_encode,
48
+ settings.SECRET_KEY,
49
+ algorithm=settings.ALGORITHM
50
+ )
51
+ return encoded_jwt
52
+
53
+
54
+ def create_refresh_token(user_id: str, tenant_id: str) -> str:
55
+ """Create JWT refresh token (longer expiry)"""
56
+ expire = datetime.now(timezone.utc) + timedelta(
57
+ days=settings.REFRESH_TOKEN_EXPIRE_DAYS
58
+ )
59
+ data = {
60
+ "sub": user_id,
61
+ "tenant_id": tenant_id,
62
+ "exp": expire,
63
+ "type": "refresh"
64
+ }
65
+ return jwt.encode(
66
+ data,
67
+ settings.SECRET_KEY,
68
+ algorithm=settings.ALGORITHM
69
+ )
70
+
71
+
72
+ def decode_token(token: str) -> Dict[str, Any]:
73
+ """Decode and validate JWT token"""
74
+ try:
75
+ payload = jwt.decode(
76
+ token,
77
+ settings.SECRET_KEY,
78
+ algorithms=[settings.ALGORITHM]
79
+ )
80
+ return payload
81
+ except jwt.ExpiredSignatureError:
82
+ raise HTTPException(
83
+ status_code=status.HTTP_401_UNAUTHORIZED,
84
+ detail="Token has expired"
85
+ )
86
+ except jwt.InvalidTokenError:
87
+ raise HTTPException(
88
+ status_code=status.HTTP_401_UNAUTHORIZED,
89
+ detail="Invalid token"
90
+ )
91
+
92
+
93
+ async def get_current_user_token(
94
+ credentials: HTTPAuthorizationCredentials = Depends(security)
95
+ ) -> Dict[str, Any]:
96
+ """Extract and validate token from Authorization header"""
97
+ token = credentials.credentials
98
+ return decode_token(token)
99
+
100
+
101
+ async def get_current_tenant_id(
102
+ token: Dict[str, Any] = Depends(get_current_user_token)
103
+ ) -> str:
104
+ """Extract tenant_id from token - used for multi-tenant isolation"""
105
+ tenant_id = token.get("tenant_id")
106
+ if not tenant_id:
107
+ raise HTTPException(
108
+ status_code=status.HTTP_401_UNAUTHORIZED,
109
+ detail="Tenant ID not found in token"
110
+ )
111
+ return tenant_id
112
+
113
+
114
+ async def get_current_user_id(
115
+ token: Dict[str, Any] = Depends(get_current_user_token)
116
+ ) -> str:
117
+ """Extract user_id from token"""
118
+ user_id = token.get("sub")
119
+ if not user_id:
120
+ raise HTTPException(
121
+ status_code=status.HTTP_401_UNAUTHORIZED,
122
+ detail="User ID not found in token"
123
+ )
124
+ return user_id
backend/app/main.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI Application Entry Point"""
2
+ import os
3
+ from fastapi import FastAPI, Request
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ from contextlib import asynccontextmanager
6
+ import logging
7
+ from fastapi.responses import JSONResponse, HTMLResponse, FileResponse
8
+ from fastapi.staticfiles import StaticFiles
9
+ from slowapi.middleware import SlowAPIMiddleware
10
+ from slowapi.errors import RateLimitExceeded
11
+ from slowapi import _rate_limit_exceeded_handler
12
+
13
+ from app.core.config import settings
14
+ from app.core.rate_limit import limiter
15
+ from app.core.database import init_db
16
+ from app.api.auth_routes import router as auth_router
17
+ from app.api.face_routes import router as face_router
18
+ from app.api.admin_routes import router as admin_router
19
+ from app.api.external_routes import router as external_router
20
+ from app.api.webhook_routes import router as webhook_router
21
+ from app.api.api_key_routes import router as api_key_router
22
+
23
+ # Configure logging
24
+ logging.basicConfig(
25
+ level=logging.INFO,
26
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
27
+ )
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ @asynccontextmanager
32
+ async def lifespan(app: FastAPI):
33
+ """Lifespan context manager for startup/shutdown"""
34
+ # Startup
35
+ logger.info(f"Starting {settings.APP_NAME} v{settings.APP_VERSION}")
36
+ init_db()
37
+ try:
38
+ from app.services.qdrant_service import QdrantService
39
+ QdrantService.ensure_collection(settings.FACE_EMBEDDING_DIM)
40
+ except Exception as exc:
41
+ logger.warning("Qdrant initialization skipped: %s", exc)
42
+ logger.info("Database initialized")
43
+
44
+ yield
45
+
46
+ # Shutdown
47
+ logger.info("Shutting down application")
48
+
49
+
50
+ # Create FastAPI app
51
+ app = FastAPI(
52
+ title=settings.APP_NAME,
53
+ version=settings.APP_VERSION,
54
+ description="Multi-tenant Face Recognition SaaS Platform",
55
+ lifespan=lifespan
56
+ )
57
+
58
+ # Serve built frontend if present
59
+ static_dir = os.path.join(os.path.dirname(__file__), "static")
60
+ if os.path.exists(static_dir):
61
+ app.mount("/static", StaticFiles(directory=static_dir), name="static")
62
+
63
+ app.state.limiter = limiter
64
+ app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
65
+ app.add_middleware(SlowAPIMiddleware)
66
+
67
+ # CORS middleware
68
+ app.add_middleware(
69
+ CORSMiddleware,
70
+ allow_origins=settings.CORS_ORIGINS,
71
+ allow_credentials=True,
72
+ allow_methods=["*"],
73
+ allow_headers=["*"],
74
+ )
75
+
76
+
77
+ # Global exception handler
78
+ @app.exception_handler(Exception)
79
+ async def global_exception_handler(request: Request, exc: Exception):
80
+ """Global exception handler"""
81
+ logger.error(f"Unhandled exception: {str(exc)}", exc_info=True)
82
+ return JSONResponse(
83
+ status_code=500,
84
+ content={"detail": "Internal server error"}
85
+ )
86
+
87
+
88
+ # Health check endpoint
89
+ @app.get("/health")
90
+ async def health_check():
91
+ """Health check endpoint"""
92
+ return {
93
+ "status": "healthy",
94
+ "app": settings.APP_NAME,
95
+ "version": settings.APP_VERSION
96
+ }
97
+
98
+
99
+ # Root endpoint
100
+ @app.get("/", response_class=HTMLResponse)
101
+ async def root():
102
+ """Serve frontend if available, otherwise return API info"""
103
+ index_path = os.path.join(static_dir, "index.html")
104
+ if os.path.exists(index_path):
105
+ return FileResponse(index_path)
106
+ return HTMLResponse(
107
+ content=(
108
+ f"<h1>{settings.APP_NAME}</h1>"
109
+ f"<p>Version: {settings.APP_VERSION}</p>"
110
+ "<p>Docs: <a href='/docs'>/docs</a></p>"
111
+ )
112
+ )
113
+
114
+
115
+ # Register routers
116
+ app.include_router(auth_router)
117
+ app.include_router(face_router)
118
+ app.include_router(admin_router)
119
+ app.include_router(external_router)
120
+ app.include_router(webhook_router)
121
+ app.include_router(api_key_router)
122
+
123
+
124
+ if __name__ == "__main__":
125
+ import uvicorn
126
+
127
+ uvicorn.run(
128
+ "app.main:app",
129
+ host="0.0.0.0",
130
+ port=8000,
131
+ reload=settings.DEBUG,
132
+ log_level="info"
133
+ )
backend/app/models/__init__.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ORM Models for Face Inference Platform"""
2
+ from sqlalchemy import CHAR, Column, String, Integer, Float, DateTime, Boolean, ForeignKey, LargeBinary, Index, Enum as SQLEnum, Text
3
+ from sqlalchemy.orm import relationship
4
+ from sqlalchemy.dialects.postgresql import UUID as PostgresUUID
5
+ from sqlalchemy.types import TypeDecorator
6
+ from datetime import datetime, timezone
7
+ import uuid
8
+ import enum
9
+
10
+ from app.core.database import Base
11
+
12
+
13
+ class GUID(TypeDecorator):
14
+ """Platform-independent UUID type.
15
+
16
+ Uses native UUID on PostgreSQL and CHAR(36) elsewhere, including MySQL.
17
+ """
18
+
19
+ impl = CHAR
20
+ cache_ok = True
21
+
22
+ def load_dialect_impl(self, dialect):
23
+ if dialect.name == "postgresql":
24
+ return dialect.type_descriptor(PostgresUUID(as_uuid=True))
25
+ return dialect.type_descriptor(CHAR(36))
26
+
27
+ def process_bind_param(self, value, dialect):
28
+ if value is None:
29
+ return value
30
+ if dialect.name == "postgresql":
31
+ return value if isinstance(value, uuid.UUID) else uuid.UUID(str(value))
32
+ return str(value if isinstance(value, uuid.UUID) else uuid.UUID(str(value)))
33
+
34
+ def process_result_value(self, value, dialect):
35
+ if value is None or isinstance(value, uuid.UUID):
36
+ return value
37
+ return uuid.UUID(str(value))
38
+
39
+
40
+ class UserRole(str, enum.Enum):
41
+ """User role enumeration"""
42
+ ADMIN = "admin"
43
+ USER = "user"
44
+
45
+
46
+ class Tenant(Base):
47
+ """Tenant model - represents a customer"""
48
+ __tablename__ = "tenants"
49
+
50
+ id = Column(GUID(), primary_key=True, default=uuid.uuid4)
51
+ name = Column(String(255), nullable=False, unique=True)
52
+ plan = Column(String(50), default="free") # free, pro, enterprise
53
+ api_quota = Column(Integer, default=10000) # API calls per month
54
+ storage_quota = Column(Integer, default=1024) # MB
55
+ is_active = Column(Boolean, default=True)
56
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
57
+ updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
58
+
59
+ # Relationships
60
+ users = relationship("User", back_populates="tenant", cascade="all, delete-orphan")
61
+ face_embeddings = relationship("FaceEmbedding", back_populates="tenant", cascade="all, delete-orphan")
62
+ recognition_logs = relationship("RecognitionLog", back_populates="tenant", cascade="all, delete-orphan")
63
+ api_keys = relationship("APIKey", back_populates="tenant", cascade="all, delete-orphan")
64
+
65
+ __table_args__ = (
66
+ Index("ix_tenant_name", "name"),
67
+ Index("ix_tenant_is_active", "is_active"),
68
+ )
69
+
70
+
71
+ class User(Base):
72
+ """User model - represents a user within a tenant"""
73
+ __tablename__ = "users"
74
+
75
+ id = Column(GUID(), primary_key=True, default=uuid.uuid4)
76
+ tenant_id = Column(GUID(), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
77
+ email = Column(String(255), nullable=False)
78
+ password_hash = Column(String(255), nullable=False)
79
+ full_name = Column(String(255), nullable=True)
80
+ role = Column(SQLEnum(UserRole), default=UserRole.USER)
81
+ is_active = Column(Boolean, default=True)
82
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
83
+ updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
84
+
85
+ # Relationships
86
+ tenant = relationship("Tenant", back_populates="users")
87
+ face_embeddings = relationship("FaceEmbedding", back_populates="user", cascade="all, delete-orphan")
88
+ recognition_logs = relationship("RecognitionLog", back_populates="user")
89
+
90
+ __table_args__ = (
91
+ Index("ix_user_tenant_id_email", "tenant_id", "email"),
92
+ Index("ix_user_is_active", "is_active"),
93
+ )
94
+
95
+
96
+ class FaceEmbedding(Base):
97
+ """Face embedding model - stores face vectors and metadata"""
98
+ __tablename__ = "face_embeddings"
99
+
100
+ id = Column(GUID(), primary_key=True, default=uuid.uuid4)
101
+ tenant_id = Column(GUID(), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
102
+ user_id = Column(GUID(), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
103
+ person_id = Column(String(255), nullable=False) # e.g., "EMP001", "PERSON_001"
104
+ name = Column(String(255), nullable=False) # Person's name
105
+
106
+ # Embedding vector (store as binary for efficiency)
107
+ embedding_vector = Column(LargeBinary, nullable=False) # numpy array serialized
108
+ embedding_dim = Column(Integer, nullable=False) # e.g., 512
109
+
110
+ # Image metadata
111
+ image_url = Column(String(500), nullable=True) # S3 URL
112
+ image_hash = Column(String(64), nullable=True) # SHA256 for duplicate detection
113
+
114
+ # Quality metrics
115
+ face_quality_score = Column(Float, nullable=True) # 0-1
116
+ face_angle = Column(String(50), nullable=True) # frontal, profile, etc.
117
+
118
+ # Metadata
119
+ metadata_json = Column("metadata", Text, nullable=True) # JSON string with additional info
120
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
121
+ updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
122
+
123
+ # Relationships
124
+ tenant = relationship("Tenant", back_populates="face_embeddings")
125
+ user = relationship("User", back_populates="face_embeddings")
126
+
127
+ __table_args__ = (
128
+ Index("ix_face_tenant_id", "tenant_id"),
129
+ Index("ix_face_user_id", "user_id"),
130
+ Index("ix_face_person_id", "person_id"),
131
+ Index("ix_face_tenant_person", "tenant_id", "person_id"),
132
+ )
133
+
134
+
135
+ class RecognitionLog(Base):
136
+ """Recognition log model - tracks recognition results"""
137
+ __tablename__ = "recognition_logs"
138
+
139
+ id = Column(GUID(), primary_key=True, default=uuid.uuid4)
140
+ tenant_id = Column(GUID(), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
141
+ user_id = Column(GUID(), ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
142
+
143
+ recognized_person_id = Column(String(255), nullable=False) # Which person was recognized
144
+ recognized_embedding_id = Column(GUID(), nullable=True) # Which embedding matched
145
+ confidence = Column(Float, nullable=False) # 0-1 confidence score
146
+
147
+ # Request metadata
148
+ source = Column(String(50), nullable=False) # "api", "webcam", "upload"
149
+ image_url = Column(String(500), nullable=True) # Reference to input image
150
+
151
+ # Timestamp
152
+ timestamp = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
153
+
154
+ # Relationships
155
+ tenant = relationship("Tenant", back_populates="recognition_logs")
156
+ user = relationship("User", back_populates="recognition_logs")
157
+
158
+ __table_args__ = (
159
+ Index("ix_recog_tenant_id", "tenant_id"),
160
+ Index("ix_recog_user_id", "user_id"),
161
+ Index("ix_recog_timestamp", "timestamp"),
162
+ Index("ix_recog_tenant_timestamp", "tenant_id", "timestamp"),
163
+ )
164
+
165
+
166
+ class APIKey(Base):
167
+ """API Key model - for programmatic access"""
168
+ __tablename__ = "api_keys"
169
+
170
+ id = Column(GUID(), primary_key=True, default=uuid.uuid4)
171
+ tenant_id = Column(GUID(), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
172
+ user_id = Column(GUID(), ForeignKey("users.id", ondelete="CASCADE"), nullable=True)
173
+
174
+ # API key hash (don't store plain keys)
175
+ api_key_hash = Column(String(255), nullable=False, unique=True)
176
+ key_name = Column(String(255), nullable=False) # e.g., "Production API Key"
177
+
178
+ is_active = Column(Boolean, default=True)
179
+ last_used_at = Column(DateTime, nullable=True)
180
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
181
+ updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
182
+
183
+ # Relationships
184
+ tenant = relationship("Tenant", back_populates="api_keys")
185
+ user = relationship("User")
186
+
187
+ __table_args__ = (
188
+ Index("ix_apikey_tenant_id", "tenant_id"),
189
+ Index("ix_apikey_is_active", "is_active"),
190
+ )
191
+
192
+
193
+ class WebhookEndpoint(Base):
194
+ """Webhook endpoint for tenant events"""
195
+ __tablename__ = "webhook_endpoints"
196
+
197
+ id = Column(GUID(), primary_key=True, default=uuid.uuid4)
198
+ tenant_id = Column(GUID(), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
199
+ url = Column(String(500), nullable=False)
200
+ secret = Column(String(255), nullable=True)
201
+ is_active = Column(Boolean, default=True)
202
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
203
+ updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
204
+
205
+ tenant = relationship("Tenant")
206
+
207
+ __table_args__ = (
208
+ Index("ix_webhook_tenant_id", "tenant_id"),
209
+ Index("ix_webhook_is_active", "is_active"),
210
+ )
211
+
212
+
213
+ class WebhookEvent(Base):
214
+ """Webhook delivery events with retry tracking"""
215
+ __tablename__ = "webhook_events"
216
+
217
+ id = Column(GUID(), primary_key=True, default=uuid.uuid4)
218
+ tenant_id = Column(GUID(), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
219
+ endpoint_id = Column(GUID(), ForeignKey("webhook_endpoints.id", ondelete="CASCADE"), nullable=False)
220
+ event_type = Column(String(100), nullable=False)
221
+ payload = Column(Text, nullable=False)
222
+ attempt_count = Column(Integer, default=0)
223
+ last_status_code = Column(Integer, nullable=True)
224
+ delivered_at = Column(DateTime, nullable=True)
225
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
226
+ updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
227
+
228
+ endpoint = relationship("WebhookEndpoint")
229
+ tenant = relationship("Tenant")
230
+
231
+ __table_args__ = (
232
+ Index("ix_webhook_event_tenant_id", "tenant_id"),
233
+ Index("ix_webhook_event_endpoint_id", "endpoint_id"),
234
+ Index("ix_webhook_event_type", "event_type"),
235
+ )
236
+
237
+
238
+ class UsageMeter(Base):
239
+ """Monthly usage meters for billing"""
240
+ __tablename__ = "usage_meters"
241
+
242
+ id = Column(GUID(), primary_key=True, default=uuid.uuid4)
243
+ tenant_id = Column(GUID(), ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
244
+ user_id = Column(GUID(), ForeignKey("users.id", ondelete="CASCADE"), nullable=True)
245
+ period = Column(String(7), nullable=False) # YYYY-MM
246
+ successful_recognitions = Column(Integer, default=0)
247
+ api_calls = Column(Integer, default=0)
248
+ created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
249
+ updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
250
+
251
+ tenant = relationship("Tenant")
252
+ user = relationship("User")
253
+
254
+ __table_args__ = (
255
+ Index("ix_usage_tenant_user_period", "tenant_id", "user_id", "period", unique=True),
256
+ Index("ix_usage_tenant_id", "tenant_id"),
257
+ )
backend/app/schemas/__init__.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pydantic schemas - request/response validation"""
2
+ from pydantic import BaseModel, EmailStr, Field, ConfigDict
3
+ from typing import Optional, List
4
+ from datetime import datetime
5
+ from uuid import UUID
6
+
7
+
8
+ # ========== Auth Schemas ==========
9
+
10
+ class TenantRegisterRequest(BaseModel):
11
+ """Tenant registration request"""
12
+ name: str = Field(..., min_length=3, max_length=255)
13
+ plan: Optional[str] = Field("free", pattern="^(free|pro|enterprise)$")
14
+
15
+
16
+ class TenantResponse(BaseModel):
17
+ """Tenant response"""
18
+ id: UUID
19
+ name: str
20
+ plan: str
21
+ api_quota: int
22
+ created_at: datetime
23
+
24
+ model_config = ConfigDict(from_attributes=True)
25
+
26
+
27
+ class UserRegisterRequest(BaseModel):
28
+ """User registration request"""
29
+ email: EmailStr
30
+ password: str = Field(..., min_length=8, max_length=100)
31
+ full_name: Optional[str] = Field(None, max_length=255)
32
+ tenant_id: Optional[UUID] = None # If None, create new tenant
33
+
34
+
35
+ class UserLoginRequest(BaseModel):
36
+ """User login request"""
37
+ email: EmailStr
38
+ password: str
39
+
40
+
41
+ class TokenResponse(BaseModel):
42
+ """Token response"""
43
+ access_token: str
44
+ refresh_token: str
45
+ token_type: str = "bearer"
46
+ expires_in: int
47
+
48
+
49
+ class TokenRefreshRequest(BaseModel):
50
+ """Token refresh request"""
51
+ refresh_token: str
52
+
53
+
54
+ class UserResponse(BaseModel):
55
+ """User response"""
56
+ id: UUID
57
+ email: str
58
+ full_name: Optional[str]
59
+ role: str
60
+ tenant_id: UUID
61
+ is_active: bool
62
+ created_at: datetime
63
+
64
+ model_config = ConfigDict(from_attributes=True)
65
+
66
+
67
+ # ========== Face Embedding Schemas ==========
68
+
69
+ class FaceEmbeddingCreateRequest(BaseModel):
70
+ """Face embedding creation request"""
71
+ person_id: str = Field(..., min_length=1, max_length=255)
72
+ name: str = Field(..., min_length=1, max_length=255)
73
+ # image: file (handled separately in route)
74
+ metadata: Optional[str] = None
75
+
76
+
77
+ class FaceEmbeddingResponse(BaseModel):
78
+ """Face embedding response"""
79
+ id: UUID
80
+ person_id: str
81
+ name: str
82
+ image_url: Optional[str]
83
+ face_quality_score: Optional[float]
84
+ created_at: datetime
85
+
86
+ model_config = ConfigDict(from_attributes=True)
87
+
88
+
89
+ class FaceEmbeddingDetailResponse(FaceEmbeddingResponse):
90
+ """Detailed face embedding response"""
91
+ embedding_dim: int
92
+ face_angle: Optional[str]
93
+ updated_at: datetime
94
+
95
+
96
+ # ========== Face Recognition Schemas ==========
97
+
98
+ class RecognizedFace(BaseModel):
99
+ """A recognized face in recognition results"""
100
+ person_id: str
101
+ name: str
102
+ confidence: float
103
+ bbox: Optional[List[float]] = None # [x1, y1, x2, y2]
104
+ embedding_id: Optional[UUID] = None
105
+
106
+
107
+ class FaceRecognitionRequest(BaseModel):
108
+ """Face recognition request"""
109
+ # image: file or base64 (handled in route)
110
+ threshold: Optional[float] = Field(0.5, ge=0.0, le=1.0)
111
+ return_bboxes: Optional[bool] = True
112
+
113
+
114
+ class FaceRecognitionResponse(BaseModel):
115
+ """Face recognition response"""
116
+ faces_detected: int
117
+ recognized: List[RecognizedFace]
118
+ unrecognized_count: int
119
+ processing_time_ms: float
120
+
121
+
122
+ class AsyncTaskResponse(BaseModel):
123
+ task_id: str
124
+
125
+
126
+ class RecognitionLogResponse(BaseModel):
127
+ """Recognition log response"""
128
+ id: UUID
129
+ recognized_person_id: str
130
+ confidence: float
131
+ source: str
132
+ timestamp: datetime
133
+
134
+ model_config = ConfigDict(from_attributes=True)
135
+
136
+
137
+ # ========== Admin Schemas ==========
138
+
139
+ class UserDetailResponse(UserResponse):
140
+ """Detailed user response for admin"""
141
+ face_embeddings_count: Optional[int] = 0
142
+
143
+
144
+ class TenantDetailResponse(TenantResponse):
145
+ """Detailed tenant response for admin"""
146
+ user_count: Optional[int] = 0
147
+ face_embeddings_count: Optional[int] = 0
148
+ total_api_calls: Optional[int] = 0
149
+
150
+
151
+ class AdminAnalyticsResponse(BaseModel):
152
+ """Admin analytics response"""
153
+ total_tenants: int
154
+ total_users: int
155
+ total_face_embeddings: int
156
+ total_recognition_logs: int
157
+ total_api_calls: int
158
+ recognitions_today: int
159
+ faces_registered_today: int
160
+
161
+
162
+ # ========== API Key Schemas ==========
163
+
164
+ class APIKeyCreateRequest(BaseModel):
165
+ """API key creation request"""
166
+ key_name: str = Field(..., min_length=1, max_length=255)
167
+
168
+
169
+ class APIKeyResponse(BaseModel):
170
+ """API key response"""
171
+ id: UUID
172
+ key_name: str
173
+ is_active: bool
174
+ created_at: datetime
175
+ last_used_at: Optional[datetime]
176
+
177
+ model_config = ConfigDict(from_attributes=True)
178
+
179
+
180
+ class APIKeyCreateResponse(APIKeyResponse):
181
+ """API key creation response with actual key"""
182
+ api_key: str # Only returned once on creation
183
+
184
+
185
+ # ========== Webhook Schemas ==========
186
+
187
+ class WebhookCreateRequest(BaseModel):
188
+ url: str = Field(..., min_length=10, max_length=500)
189
+ secret: Optional[str] = Field(None, max_length=255)
190
+
191
+
192
+ class WebhookResponse(BaseModel):
193
+ id: UUID
194
+ url: str
195
+ is_active: bool
196
+ created_at: datetime
197
+
198
+ model_config = ConfigDict(from_attributes=True)
199
+
200
+
201
+ class WebhookEventResponse(BaseModel):
202
+ id: UUID
203
+ event_type: str
204
+ attempt_count: int
205
+ last_status_code: Optional[int]
206
+ delivered_at: Optional[datetime]
207
+ created_at: datetime
208
+
209
+ model_config = ConfigDict(from_attributes=True)
210
+
211
+
212
+ # ========== Usage/Billing Schemas ==========
213
+
214
+ class UsageMeterResponse(BaseModel):
215
+ period: str
216
+ successful_recognitions: int
217
+ api_calls: int
218
+
219
+ model_config = ConfigDict(from_attributes=True)
220
+
221
+
222
+ # ========== Error Schemas ==========
223
+
224
+ class ErrorResponse(BaseModel):
225
+ """Error response"""
226
+ error: str
227
+ message: str
228
+ status_code: int
229
+ timestamp: datetime
230
+
231
+
232
+ class ValidationErrorResponse(BaseModel):
233
+ """Validation error response"""
234
+ detail: List[dict]
backend/app/services/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Services init"""
backend/app/services/api_key_service.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """API key service for third-party integrations."""
2
+ from datetime import datetime, timezone
3
+ import hashlib
4
+ import secrets
5
+ from typing import Optional
6
+ from uuid import UUID
7
+
8
+ from sqlalchemy.orm import Session
9
+
10
+ from app.models import APIKey, User
11
+
12
+
13
+ class APIKeyService:
14
+ @staticmethod
15
+ def hash_key(api_key: str) -> str:
16
+ return hashlib.sha256(api_key.encode("utf-8")).hexdigest()
17
+
18
+ @staticmethod
19
+ def create_api_key(db: Session, tenant_id: UUID, key_name: str, user_id: Optional[UUID] = None) -> tuple[APIKey, str]:
20
+ plain_key = f"fmp_{secrets.token_urlsafe(32)}"
21
+ api_key = APIKey(
22
+ tenant_id=tenant_id,
23
+ user_id=user_id,
24
+ key_name=key_name,
25
+ api_key_hash=APIKeyService.hash_key(plain_key),
26
+ )
27
+ db.add(api_key)
28
+ db.commit()
29
+ db.refresh(api_key)
30
+ return api_key, plain_key
31
+
32
+ @staticmethod
33
+ def get_active_api_key(db: Session, plain_key: str) -> Optional[APIKey]:
34
+ api_key = (
35
+ db.query(APIKey)
36
+ .filter(
37
+ APIKey.api_key_hash == APIKeyService.hash_key(plain_key),
38
+ APIKey.is_active.is_(True),
39
+ )
40
+ .first()
41
+ )
42
+
43
+ if api_key:
44
+ api_key.last_used_at = datetime.now(timezone.utc)
45
+ db.commit()
46
+ db.refresh(api_key)
47
+
48
+ return api_key
49
+
50
+ @staticmethod
51
+ def get_tenant_actor_user(db: Session, tenant_id: UUID) -> User:
52
+ user = (
53
+ db.query(User)
54
+ .filter(User.tenant_id == tenant_id, User.is_active.is_(True))
55
+ .order_by(User.created_at.asc())
56
+ .first()
57
+ )
58
+ if not user:
59
+ raise ValueError("No active user found for API key tenant")
60
+ return user
61
+
62
+ @staticmethod
63
+ def list_api_keys(db: Session, tenant_id: UUID) -> list[APIKey]:
64
+ return (
65
+ db.query(APIKey)
66
+ .filter(APIKey.tenant_id == tenant_id)
67
+ .order_by(APIKey.created_at.desc())
68
+ .all()
69
+ )
70
+
71
+ @staticmethod
72
+ def deactivate_api_key(db: Session, tenant_id: UUID, api_key_id: UUID) -> APIKey:
73
+ api_key = (
74
+ db.query(APIKey)
75
+ .filter(APIKey.tenant_id == tenant_id, APIKey.id == api_key_id)
76
+ .first()
77
+ )
78
+ if not api_key:
79
+ raise ValueError("API key not found")
80
+ api_key.is_active = False
81
+ db.commit()
82
+ db.refresh(api_key)
83
+ return api_key
84
+
85
+ @staticmethod
86
+ def list_user_api_keys(db: Session, tenant_id: UUID, user_id: UUID) -> list[APIKey]:
87
+ return (
88
+ db.query(APIKey)
89
+ .filter(APIKey.tenant_id == tenant_id, APIKey.user_id == user_id)
90
+ .order_by(APIKey.created_at.desc())
91
+ .all()
92
+ )
93
+
94
+ @staticmethod
95
+ def deactivate_user_api_key(db: Session, tenant_id: UUID, user_id: UUID, api_key_id: UUID) -> APIKey:
96
+ api_key = (
97
+ db.query(APIKey)
98
+ .filter(
99
+ APIKey.tenant_id == tenant_id,
100
+ APIKey.user_id == user_id,
101
+ APIKey.id == api_key_id,
102
+ )
103
+ .first()
104
+ )
105
+ if not api_key:
106
+ raise ValueError("API key not found")
107
+ api_key.is_active = False
108
+ db.commit()
109
+ db.refresh(api_key)
110
+ return api_key
backend/app/services/auth_service.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Authentication service"""
2
+ import logging
3
+ from uuid import UUID
4
+ from sqlalchemy.orm import Session
5
+ from sqlalchemy import and_
6
+
7
+ from app.core.security import hash_password, verify_password, create_access_token, create_refresh_token
8
+ from app.models import User, Tenant, UserRole
9
+ from app.core.config import settings
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class AuthService:
15
+ """Authentication business logic"""
16
+
17
+ @staticmethod
18
+ def register_user(
19
+ db: Session,
20
+ email: str,
21
+ password: str,
22
+ full_name: str,
23
+ tenant_id: UUID,
24
+ role: UserRole = UserRole.USER
25
+ ) -> User:
26
+ """Register a new user"""
27
+ # Check if user already exists
28
+ existing_user = db.query(User).filter(
29
+ and_(
30
+ User.tenant_id == tenant_id,
31
+ User.email == email
32
+ )
33
+ ).first()
34
+
35
+ if existing_user:
36
+ raise ValueError(f"User with email {email} already exists in this tenant")
37
+
38
+ # Create new user
39
+ hashed_password = hash_password(password)
40
+ user = User(
41
+ tenant_id=tenant_id,
42
+ email=email,
43
+ password_hash=hashed_password,
44
+ full_name=full_name,
45
+ role=role
46
+ )
47
+
48
+ db.add(user)
49
+ db.commit()
50
+ db.refresh(user)
51
+
52
+ logger.info(f"User registered: {email} (tenant: {tenant_id})")
53
+ return user
54
+
55
+ @staticmethod
56
+ def authenticate_user(db: Session, email: str, password: str, tenant_id: UUID) -> User:
57
+ """Authenticate user with email and password"""
58
+ user = db.query(User).filter(
59
+ and_(
60
+ User.email == email,
61
+ User.tenant_id == tenant_id
62
+ )
63
+ ).first()
64
+
65
+ if not user or not verify_password(password, user.password_hash):
66
+ raise ValueError("Invalid email or password")
67
+
68
+ if not user.is_active:
69
+ raise ValueError("User account is inactive")
70
+
71
+ logger.info(f"User authenticated: {email}")
72
+ return user
73
+
74
+ @staticmethod
75
+ def get_user_by_id(db: Session, user_id: UUID, tenant_id: UUID) -> User:
76
+ """Get user by ID with tenant isolation"""
77
+ user = db.query(User).filter(
78
+ and_(
79
+ User.id == user_id,
80
+ User.tenant_id == tenant_id
81
+ )
82
+ ).first()
83
+
84
+ if not user:
85
+ raise ValueError("User not found")
86
+
87
+ return user
88
+
89
+ @staticmethod
90
+ def get_user_by_email(db: Session, email: str, tenant_id: UUID) -> User:
91
+ """Get user by email with tenant isolation"""
92
+ user = db.query(User).filter(
93
+ and_(
94
+ User.email == email,
95
+ User.tenant_id == tenant_id
96
+ )
97
+ ).first()
98
+
99
+ if not user:
100
+ raise ValueError("User not found")
101
+
102
+ return user
103
+
104
+ @staticmethod
105
+ def create_tokens(user: User) -> dict:
106
+ """Create access and refresh tokens for user"""
107
+ access_token = create_access_token({
108
+ "sub": str(user.id),
109
+ "tenant_id": str(user.tenant_id),
110
+ "email": user.email,
111
+ "role": user.role.value
112
+ })
113
+
114
+ refresh_token = create_refresh_token(str(user.id), str(user.tenant_id))
115
+
116
+ return {
117
+ "access_token": access_token,
118
+ "refresh_token": refresh_token,
119
+ "token_type": "bearer",
120
+ "expires_in": settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60
121
+ }
122
+
123
+ @staticmethod
124
+ def refresh_access_token(refresh_token: str) -> dict:
125
+ """Generate new access token from refresh token"""
126
+ from app.core.security import decode_token
127
+
128
+ payload = decode_token(refresh_token)
129
+
130
+ if payload.get("type") != "refresh":
131
+ raise ValueError("Invalid token type")
132
+
133
+ user_id = payload.get("sub")
134
+ tenant_id = payload.get("tenant_id")
135
+
136
+ access_token = create_access_token({
137
+ "sub": user_id,
138
+ "tenant_id": tenant_id,
139
+ "type": "access"
140
+ })
141
+
142
+ return {
143
+ "access_token": access_token,
144
+ "token_type": "bearer",
145
+ "expires_in": settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60
146
+ }
147
+
148
+
149
+ class TenantService:
150
+ """Tenant business logic"""
151
+
152
+ @staticmethod
153
+ def create_tenant(db: Session, name: str, plan: str = "free") -> Tenant:
154
+ """Create a new tenant"""
155
+ existing_tenant = db.query(Tenant).filter(Tenant.name == name).first()
156
+
157
+ if existing_tenant:
158
+ raise ValueError(f"Tenant with name {name} already exists")
159
+
160
+ tenant = Tenant(name=name, plan=plan)
161
+ db.add(tenant)
162
+ db.commit()
163
+ db.refresh(tenant)
164
+
165
+ logger.info(f"Tenant created: {name}")
166
+ return tenant
167
+
168
+ @staticmethod
169
+ def get_tenant_by_id(db: Session, tenant_id: UUID) -> Tenant:
170
+ """Get tenant by ID"""
171
+ tenant = db.query(Tenant).filter(Tenant.id == tenant_id).first()
172
+
173
+ if not tenant:
174
+ raise ValueError("Tenant not found")
175
+
176
+ return tenant
177
+
178
+ @staticmethod
179
+ def list_tenants(db: Session, skip: int = 0, limit: int = 100) -> list:
180
+ """List all tenants (admin only)"""
181
+ return db.query(Tenant).offset(skip).limit(limit).all()
backend/app/services/billing_service.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Billing and usage metering (Stripe integration placeholder)."""
2
+ from datetime import datetime, timezone
3
+ from typing import Optional
4
+ from uuid import UUID
5
+
6
+ from sqlalchemy.orm import Session
7
+
8
+ from app.models import UsageMeter
9
+
10
+
11
+ class BillingService:
12
+ """Usage metering for monthly billing."""
13
+
14
+ @staticmethod
15
+ def _current_period() -> str:
16
+ now = datetime.now(timezone.utc)
17
+ return f"{now.year:04d}-{now.month:02d}"
18
+
19
+ @staticmethod
20
+ def _get_or_create_meter(
21
+ db: Session,
22
+ tenant_id: UUID,
23
+ user_id: Optional[UUID] = None,
24
+ period: Optional[str] = None,
25
+ ) -> UsageMeter:
26
+ period_value = period or BillingService._current_period()
27
+ meter = (
28
+ db.query(UsageMeter)
29
+ .filter(
30
+ UsageMeter.tenant_id == tenant_id,
31
+ UsageMeter.user_id == user_id,
32
+ UsageMeter.period == period_value,
33
+ )
34
+ .first()
35
+ )
36
+ if meter:
37
+ return meter
38
+ meter = UsageMeter(tenant_id=tenant_id, user_id=user_id, period=period_value)
39
+ db.add(meter)
40
+ db.commit()
41
+ db.refresh(meter)
42
+ return meter
43
+
44
+ @staticmethod
45
+ def record_successful_recognition(db: Session, tenant_id: UUID, user_id: Optional[UUID]) -> UsageMeter:
46
+ meter = BillingService._get_or_create_meter(db, tenant_id, user_id)
47
+ meter.successful_recognitions += 1
48
+ db.commit()
49
+ db.refresh(meter)
50
+ return meter
51
+
52
+ @staticmethod
53
+ def record_api_call(db: Session, tenant_id: UUID, user_id: Optional[UUID]) -> UsageMeter:
54
+ meter = BillingService._get_or_create_meter(db, tenant_id, user_id)
55
+ meter.api_calls += 1
56
+ db.commit()
57
+ db.refresh(meter)
58
+ return meter
59
+
60
+ @staticmethod
61
+ def get_usage(db: Session, tenant_id: UUID, period: Optional[str] = None, user_id: Optional[UUID] = None) -> UsageMeter:
62
+ meter = BillingService._get_or_create_meter(db, tenant_id, user_id, period)
63
+ return meter
backend/app/services/qdrant_service.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Qdrant vector storage service"""
2
+ import logging
3
+ from typing import Optional
4
+ from uuid import UUID
5
+
6
+ import numpy as np
7
+ from qdrant_client import QdrantClient
8
+ from qdrant_client.http import models as qmodels
9
+
10
+ from app.core.config import settings
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class QdrantService:
16
+ _client: Optional[QdrantClient] = None
17
+
18
+ @classmethod
19
+ def client(cls) -> Optional[QdrantClient]:
20
+ if not settings.QDRANT_ENABLE or not settings.QDRANT_URL:
21
+ return None
22
+ if cls._client is None:
23
+ cls._client = QdrantClient(url=settings.QDRANT_URL, api_key=settings.QDRANT_API_KEY)
24
+ return cls._client
25
+
26
+ @classmethod
27
+ def ensure_collection(cls, vector_size: int) -> None:
28
+ client = cls.client()
29
+ if client is None:
30
+ return
31
+ try:
32
+ existing = client.get_collections().collections
33
+ names = {collection.name for collection in existing}
34
+ if settings.QDRANT_COLLECTION in names:
35
+ return
36
+ client.create_collection(
37
+ collection_name=settings.QDRANT_COLLECTION,
38
+ vectors_config=qmodels.VectorParams(size=vector_size, distance=qmodels.Distance.COSINE),
39
+ )
40
+ except Exception as exc:
41
+ logger.warning("Failed to ensure Qdrant collection: %s", exc)
42
+
43
+ @classmethod
44
+ def upsert_embedding(
45
+ cls,
46
+ *,
47
+ embedding_id: UUID,
48
+ tenant_id: UUID,
49
+ vector: np.ndarray,
50
+ person_id: str,
51
+ name: str,
52
+ ) -> None:
53
+ client = cls.client()
54
+ if client is None:
55
+ return
56
+ cls.ensure_collection(vector_size=len(vector))
57
+ payload = {
58
+ "tenant_id": str(tenant_id),
59
+ "person_id": person_id,
60
+ "name": name,
61
+ "embedding_id": str(embedding_id),
62
+ }
63
+ try:
64
+ client.upsert(
65
+ collection_name=settings.QDRANT_COLLECTION,
66
+ points=[
67
+ qmodels.PointStruct(
68
+ id=str(embedding_id),
69
+ vector=vector.astype(np.float32).tolist(),
70
+ payload=payload,
71
+ )
72
+ ],
73
+ )
74
+ except Exception as exc:
75
+ logger.warning("Failed to upsert vector into Qdrant: %s", exc)
76
+
77
+ @classmethod
78
+ def delete_embedding(cls, embedding_id: UUID) -> None:
79
+ client = cls.client()
80
+ if client is None:
81
+ return
82
+ try:
83
+ client.delete(
84
+ collection_name=settings.QDRANT_COLLECTION,
85
+ points_selector=qmodels.PointIdsList(points=[str(embedding_id)]),
86
+ )
87
+ except Exception as exc:
88
+ logger.warning("Failed to delete vector from Qdrant: %s", exc)
89
+
90
+ @classmethod
91
+ def search_best_match(
92
+ cls,
93
+ *,
94
+ tenant_id: UUID,
95
+ vector: np.ndarray,
96
+ limit: int = 1,
97
+ ) -> Optional[qmodels.ScoredPoint]:
98
+ client = cls.client()
99
+ if client is None:
100
+ return None
101
+ cls.ensure_collection(vector_size=len(vector))
102
+ try:
103
+ results = client.search(
104
+ collection_name=settings.QDRANT_COLLECTION,
105
+ query_vector=vector.astype(np.float32).tolist(),
106
+ limit=limit,
107
+ query_filter=qmodels.Filter(
108
+ must=[
109
+ qmodels.FieldCondition(
110
+ key="tenant_id",
111
+ match=qmodels.MatchValue(value=str(tenant_id)),
112
+ )
113
+ ]
114
+ ),
115
+ )
116
+ return results[0] if results else None
117
+ except Exception as exc:
118
+ logger.warning("Failed to search Qdrant: %s", exc)
119
+ return None
backend/app/services/recognition_service.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Face and embedding services"""
2
+ import logging
3
+ from uuid import UUID
4
+ from typing import List, Optional, Tuple
5
+ import numpy as np
6
+ from sqlalchemy.orm import Session
7
+ from sqlalchemy import and_, func
8
+
9
+ from app.models import FaceEmbedding, RecognitionLog, User
10
+ from app.core.config import settings
11
+ from app.services.qdrant_service import QdrantService
12
+ from app.services.billing_service import BillingService
13
+ from app.services.webhook_service import WebhookService
14
+ from app.utils.common import ImageUtils, FaceUtils
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class EmbeddingService:
20
+ """Face embedding management"""
21
+
22
+ @staticmethod
23
+ def person_id_exists(db: Session, tenant_id: UUID, person_id: str) -> bool:
24
+ return (
25
+ db.query(FaceEmbedding)
26
+ .filter(
27
+ and_(
28
+ FaceEmbedding.tenant_id == tenant_id,
29
+ FaceEmbedding.person_id == person_id,
30
+ )
31
+ )
32
+ .first()
33
+ is not None
34
+ )
35
+
36
+ @staticmethod
37
+ def create_embedding(
38
+ db: Session,
39
+ tenant_id: UUID,
40
+ user_id: UUID,
41
+ person_id: str,
42
+ name: str,
43
+ embedding_vector: np.ndarray,
44
+ image_url: Optional[str] = None,
45
+ image_hash: Optional[str] = None,
46
+ face_quality_score: Optional[float] = None,
47
+ face_angle: Optional[str] = None,
48
+ metadata: Optional[str] = None
49
+ ) -> FaceEmbedding:
50
+ """Create a new face embedding"""
51
+
52
+ existing_person = db.query(FaceEmbedding).filter(
53
+ and_(
54
+ FaceEmbedding.tenant_id == tenant_id,
55
+ FaceEmbedding.person_id == person_id,
56
+ )
57
+ ).first()
58
+ if existing_person:
59
+ raise ValueError("This person ID is already occupied")
60
+
61
+ # Check for duplicate embedding
62
+ if image_hash:
63
+ existing = db.query(FaceEmbedding).filter(
64
+ and_(
65
+ FaceEmbedding.tenant_id == tenant_id,
66
+ FaceEmbedding.image_hash == image_hash
67
+ )
68
+ ).first()
69
+
70
+ if existing:
71
+ logger.warning(f"Duplicate image detected: {image_hash}")
72
+ raise ValueError("This face image already exists")
73
+
74
+ # Convert numpy array to binary
75
+ embedding_bytes = embedding_vector.astype(np.float32).tobytes()
76
+
77
+ embedding = FaceEmbedding(
78
+ tenant_id=tenant_id,
79
+ user_id=user_id,
80
+ person_id=person_id,
81
+ name=name,
82
+ embedding_vector=embedding_bytes,
83
+ embedding_dim=len(embedding_vector),
84
+ image_url=image_url,
85
+ image_hash=image_hash,
86
+ face_quality_score=face_quality_score,
87
+ face_angle=face_angle,
88
+ metadata_json=metadata
89
+ )
90
+
91
+ db.add(embedding)
92
+ db.commit()
93
+ db.refresh(embedding)
94
+
95
+ QdrantService.upsert_embedding(
96
+ embedding_id=embedding.id,
97
+ tenant_id=tenant_id,
98
+ vector=embedding_vector,
99
+ person_id=person_id,
100
+ name=name,
101
+ )
102
+
103
+ events = WebhookService.emit_event(
104
+ db,
105
+ tenant_id,
106
+ "face.registered",
107
+ {
108
+ "person_id": person_id,
109
+ "name": name,
110
+ "embedding_id": str(embedding.id),
111
+ },
112
+ )
113
+ WebhookService.schedule_deliveries(events)
114
+
115
+ logger.info(f"Embedding created: {person_id} (tenant: {tenant_id})")
116
+ return embedding
117
+
118
+ @staticmethod
119
+ def get_embedding(db: Session, embedding_id: UUID, tenant_id: UUID) -> FaceEmbedding:
120
+ """Get embedding by ID with tenant isolation"""
121
+ embedding = db.query(FaceEmbedding).filter(
122
+ and_(
123
+ FaceEmbedding.id == embedding_id,
124
+ FaceEmbedding.tenant_id == tenant_id
125
+ )
126
+ ).first()
127
+
128
+ if not embedding:
129
+ raise ValueError("Embedding not found")
130
+
131
+ return embedding
132
+
133
+ @staticmethod
134
+ def get_tenant_embeddings(
135
+ db: Session,
136
+ tenant_id: UUID,
137
+ person_id: Optional[str] = None,
138
+ skip: int = 0,
139
+ limit: int = 100
140
+ ) -> List[FaceEmbedding]:
141
+ """Get all embeddings for a tenant with optional filtering"""
142
+ query = db.query(FaceEmbedding).filter(FaceEmbedding.tenant_id == tenant_id)
143
+
144
+ if person_id:
145
+ query = query.filter(FaceEmbedding.person_id == person_id)
146
+
147
+ return query.offset(skip).limit(limit).all()
148
+
149
+ @staticmethod
150
+ def delete_embedding(db: Session, embedding_id: UUID, tenant_id: UUID) -> bool:
151
+ """Delete an embedding with tenant isolation"""
152
+ embedding = db.query(FaceEmbedding).filter(
153
+ and_(
154
+ FaceEmbedding.id == embedding_id,
155
+ FaceEmbedding.tenant_id == tenant_id
156
+ )
157
+ ).first()
158
+
159
+ if not embedding:
160
+ raise ValueError("Embedding not found")
161
+
162
+ db.delete(embedding)
163
+ db.commit()
164
+
165
+ QdrantService.delete_embedding(embedding_id)
166
+
167
+ logger.info(f"Embedding deleted: {embedding_id}")
168
+ return True
169
+
170
+ @staticmethod
171
+ def embedding_bytes_to_array(embedding_bytes: bytes, embedding_dim: int) -> np.ndarray:
172
+ """Convert stored bytes back to numpy array"""
173
+ return np.frombuffer(embedding_bytes, dtype=np.float32).reshape(embedding_dim)
174
+
175
+
176
+ class RecognitionService:
177
+ """Face recognition and matching"""
178
+
179
+ @staticmethod
180
+ def compute_cosine_similarity(vec1: np.ndarray, vec2: np.ndarray) -> float:
181
+ """Compute cosine similarity between two vectors"""
182
+ norm1 = np.linalg.norm(vec1)
183
+ norm2 = np.linalg.norm(vec2)
184
+
185
+ if norm1 == 0 or norm2 == 0:
186
+ return 0.0
187
+
188
+ return float(np.dot(vec1, vec2) / (norm1 * norm2))
189
+
190
+ @staticmethod
191
+ def find_best_match(
192
+ db: Session,
193
+ query_embedding: np.ndarray,
194
+ tenant_id: UUID,
195
+ threshold: float = 0.5
196
+ ) -> Optional[Tuple[FaceEmbedding, float]]:
197
+ """Find best matching embedding for a query embedding"""
198
+
199
+ # Prefer Qdrant when configured
200
+ scored = QdrantService.search_best_match(
201
+ tenant_id=tenant_id,
202
+ vector=query_embedding,
203
+ limit=1,
204
+ )
205
+ if scored is not None:
206
+ embedding = db.query(FaceEmbedding).filter(FaceEmbedding.id == scored.id).first()
207
+ if embedding and scored.score >= threshold:
208
+ return (embedding, float(scored.score))
209
+
210
+ # Fallback to SQL scan
211
+ embeddings = db.query(FaceEmbedding).filter(FaceEmbedding.tenant_id == tenant_id).all()
212
+ if not embeddings:
213
+ return None
214
+
215
+ best_match = None
216
+ best_score = 0.0
217
+ for embedding in embeddings:
218
+ stored_vector = EmbeddingService.embedding_bytes_to_array(
219
+ embedding.embedding_vector,
220
+ embedding.embedding_dim,
221
+ )
222
+ similarity = RecognitionService.compute_cosine_similarity(query_embedding, stored_vector)
223
+ if similarity > best_score:
224
+ best_score = similarity
225
+ best_match = embedding
226
+
227
+ if best_match and best_score >= threshold:
228
+ return (best_match, best_score)
229
+ return None
230
+
231
+ @staticmethod
232
+ def log_recognition(
233
+ db: Session,
234
+ tenant_id: UUID,
235
+ user_id: UUID,
236
+ recognized_person_id: str,
237
+ confidence: float,
238
+ source: str = "api",
239
+ embedding_id: Optional[UUID] = None,
240
+ image_url: Optional[str] = None
241
+ ) -> RecognitionLog:
242
+ """Log a recognition event"""
243
+
244
+ log = RecognitionLog(
245
+ tenant_id=tenant_id,
246
+ user_id=user_id,
247
+ recognized_person_id=recognized_person_id,
248
+ recognized_embedding_id=embedding_id,
249
+ confidence=confidence,
250
+ source=source,
251
+ image_url=image_url
252
+ )
253
+
254
+ db.add(log)
255
+ db.commit()
256
+ db.refresh(log)
257
+ return log
258
+
259
+ @staticmethod
260
+ def recognize_from_bytes(
261
+ *,
262
+ db: Session,
263
+ image_bytes: bytes,
264
+ tenant_id: UUID,
265
+ user_id: UUID,
266
+ threshold: float,
267
+ return_bboxes: bool,
268
+ source: str,
269
+ ) -> dict:
270
+ BillingService.record_api_call(db, tenant_id, user_id)
271
+
272
+ if not ImageUtils.validate_image(image_bytes, settings.MAX_UPLOAD_SIZE // (1024 * 1024)):
273
+ raise ValueError("Invalid or too large image")
274
+
275
+ pil_image = ImageUtils.load_image_from_bytes(image_bytes)
276
+ pil_image = ImageUtils.resize_image(pil_image)
277
+ image_array = np.array(pil_image)
278
+
279
+ FaceUtils.init_detector()
280
+ faces = FaceUtils.detect_faces(image_array)
281
+
282
+ recognized_faces = []
283
+ unrecognized_count = 0
284
+
285
+ for face in faces:
286
+ try:
287
+ embedding = FaceUtils.get_face_embedding(image_array, face)
288
+ match = RecognitionService.find_best_match(
289
+ db=db,
290
+ query_embedding=embedding,
291
+ tenant_id=tenant_id,
292
+ threshold=threshold,
293
+ )
294
+ if match:
295
+ matched_embedding, confidence = match
296
+ RecognitionService.log_recognition(
297
+ db=db,
298
+ tenant_id=tenant_id,
299
+ user_id=user_id,
300
+ recognized_person_id=matched_embedding.person_id,
301
+ confidence=confidence,
302
+ source=source,
303
+ embedding_id=matched_embedding.id,
304
+ )
305
+ BillingService.record_successful_recognition(db, tenant_id, user_id)
306
+ recognized_faces.append(
307
+ {
308
+ "person_id": matched_embedding.person_id,
309
+ "name": matched_embedding.name,
310
+ "confidence": confidence,
311
+ "embedding_id": matched_embedding.id,
312
+ "bbox": FaceUtils.get_face_bbox(face) if return_bboxes else None,
313
+ }
314
+ )
315
+ else:
316
+ unrecognized_count += 1
317
+ except Exception:
318
+ unrecognized_count += 1
319
+
320
+ if recognized_faces:
321
+ events = WebhookService.emit_event(
322
+ db,
323
+ tenant_id,
324
+ "face.recognized",
325
+ {"recognized": recognized_faces, "source": source},
326
+ )
327
+ WebhookService.schedule_deliveries(events)
328
+
329
+ return {
330
+ "faces_detected": len(faces),
331
+ "recognized": recognized_faces,
332
+ "unrecognized_count": unrecognized_count,
333
+ }
334
+
335
+ @staticmethod
336
+ def get_recognition_logs(
337
+ db: Session,
338
+ tenant_id: UUID,
339
+ user_id: Optional[UUID] = None,
340
+ skip: int = 0,
341
+ limit: int = 100
342
+ ) -> List[RecognitionLog]:
343
+ """Get recognition logs with tenant isolation"""
344
+ query = db.query(RecognitionLog).filter(RecognitionLog.tenant_id == tenant_id)
345
+
346
+ if user_id:
347
+ query = query.filter(RecognitionLog.user_id == user_id)
348
+
349
+ return query.order_by(RecognitionLog.timestamp.desc()).offset(skip).limit(limit).all()
350
+
351
+ @staticmethod
352
+ def get_analytics(db: Session, tenant_id: UUID) -> dict:
353
+ """Get recognition analytics for a tenant"""
354
+
355
+ total_logs = db.query(func.count(RecognitionLog.id)).filter(
356
+ RecognitionLog.tenant_id == tenant_id
357
+ ).scalar() or 0
358
+
359
+ total_embeddings = db.query(func.count(FaceEmbedding.id)).filter(
360
+ FaceEmbedding.tenant_id == tenant_id
361
+ ).scalar() or 0
362
+
363
+ total_users = db.query(func.count(User.id)).filter(
364
+ User.tenant_id == tenant_id
365
+ ).scalar() or 0
366
+
367
+ avg_confidence = db.query(func.avg(RecognitionLog.confidence)).filter(
368
+ RecognitionLog.tenant_id == tenant_id
369
+ ).scalar() or 0.0
370
+
371
+ return {
372
+ "total_recognition_logs": total_logs,
373
+ "total_face_embeddings": total_embeddings,
374
+ "total_users": total_users,
375
+ "average_confidence": float(avg_confidence)
376
+ }
backend/app/services/webhook_service.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Webhook management and delivery scheduling."""
2
+ import json
3
+ from datetime import datetime, timezone
4
+ from typing import List, Optional
5
+ from uuid import UUID
6
+
7
+ from sqlalchemy.orm import Session
8
+
9
+ from app.models import WebhookEndpoint, WebhookEvent
10
+
11
+
12
+ class WebhookService:
13
+ @staticmethod
14
+ def create_endpoint(db: Session, tenant_id: UUID, url: str, secret: Optional[str]) -> WebhookEndpoint:
15
+ endpoint = WebhookEndpoint(tenant_id=tenant_id, url=url, secret=secret)
16
+ db.add(endpoint)
17
+ db.commit()
18
+ db.refresh(endpoint)
19
+ return endpoint
20
+
21
+ @staticmethod
22
+ def list_endpoints(db: Session, tenant_id: UUID) -> List[WebhookEndpoint]:
23
+ return (
24
+ db.query(WebhookEndpoint)
25
+ .filter(WebhookEndpoint.tenant_id == tenant_id)
26
+ .order_by(WebhookEndpoint.created_at.desc())
27
+ .all()
28
+ )
29
+
30
+ @staticmethod
31
+ def delete_endpoint(db: Session, tenant_id: UUID, endpoint_id: UUID) -> None:
32
+ endpoint = (
33
+ db.query(WebhookEndpoint)
34
+ .filter(WebhookEndpoint.tenant_id == tenant_id, WebhookEndpoint.id == endpoint_id)
35
+ .first()
36
+ )
37
+ if not endpoint:
38
+ raise ValueError("Webhook endpoint not found")
39
+ db.delete(endpoint)
40
+ db.commit()
41
+
42
+ @staticmethod
43
+ def emit_event(db: Session, tenant_id: UUID, event_type: str, payload: dict) -> List[WebhookEvent]:
44
+ endpoints = (
45
+ db.query(WebhookEndpoint)
46
+ .filter(WebhookEndpoint.tenant_id == tenant_id, WebhookEndpoint.is_active.is_(True))
47
+ .all()
48
+ )
49
+ events: List[WebhookEvent] = []
50
+ for endpoint in endpoints:
51
+ event = WebhookEvent(
52
+ tenant_id=tenant_id,
53
+ endpoint_id=endpoint.id,
54
+ event_type=event_type,
55
+ payload=json.dumps(payload),
56
+ )
57
+ db.add(event)
58
+ events.append(event)
59
+ db.commit()
60
+ for event in events:
61
+ db.refresh(event)
62
+ return events
63
+
64
+ @staticmethod
65
+ def schedule_deliveries(events: List[WebhookEvent]) -> None:
66
+ try:
67
+ from app.workers.tasks import deliver_webhook_task
68
+ except Exception:
69
+ return
70
+
71
+ for event in events:
72
+ deliver_webhook_task.delay(str(event.id))
73
+
74
+ @staticmethod
75
+ def mark_delivered(db: Session, event: WebhookEvent, status_code: int) -> None:
76
+ event.last_status_code = status_code
77
+ event.delivered_at = datetime.now(timezone.utc)
78
+ db.commit()
79
+ db.refresh(event)
80
+
81
+ @staticmethod
82
+ def increment_attempt(db: Session, event: WebhookEvent, status_code: Optional[int]) -> None:
83
+ event.attempt_count += 1
84
+ event.last_status_code = status_code
85
+ db.commit()
86
+ db.refresh(event)
backend/app/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Utils init"""
backend/app/utils/common.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for image processing and face detection"""
2
+ import logging
3
+ from typing import Optional, Tuple, List
4
+ import numpy as np
5
+ from PIL import Image
6
+ import io
7
+ import hashlib
8
+ import base64
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class ImageUtils:
14
+ """Image processing utilities"""
15
+
16
+ @staticmethod
17
+ def load_image_from_bytes(image_bytes: bytes) -> Image.Image:
18
+ """Load PIL Image from bytes"""
19
+ return Image.open(io.BytesIO(image_bytes))
20
+
21
+ @staticmethod
22
+ def load_image_from_base64(base64_str: str) -> Image.Image:
23
+ """Load PIL Image from base64 string"""
24
+ if base64_str.startswith("data:"):
25
+ base64_str = base64_str.split(",")[1]
26
+
27
+ image_bytes = base64.b64decode(base64_str)
28
+ return Image.open(io.BytesIO(image_bytes))
29
+
30
+ @staticmethod
31
+ def image_to_bytes(image: Image.Image, format: str = "PNG") -> bytes:
32
+ """Convert PIL Image to bytes"""
33
+ byte_arr = io.BytesIO()
34
+ image.save(byte_arr, format=format)
35
+ byte_arr.seek(0)
36
+ return byte_arr.getvalue()
37
+
38
+ @staticmethod
39
+ def compute_image_hash(image_bytes: bytes) -> str:
40
+ """Compute SHA256 hash of image for duplicate detection"""
41
+ return hashlib.sha256(image_bytes).hexdigest()
42
+
43
+ @staticmethod
44
+ def resize_image(image: Image.Image, max_size: int = 640) -> Image.Image:
45
+ """Resize image while maintaining aspect ratio"""
46
+ image.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
47
+ return image
48
+
49
+ @staticmethod
50
+ def validate_image(image_bytes: bytes, max_size_mb: int = 10) -> bool:
51
+ """Validate image"""
52
+ # Check file size
53
+ if len(image_bytes) > max_size_mb * 1024 * 1024:
54
+ logger.error(f"Image too large: {len(image_bytes)} bytes")
55
+ return False
56
+
57
+ try:
58
+ # Try to open image
59
+ Image.open(io.BytesIO(image_bytes))
60
+ return True
61
+ except Exception as e:
62
+ logger.error(f"Invalid image: {str(e)}")
63
+ return False
64
+
65
+
66
+ class FaceUtils:
67
+ """Face detection and processing utilities"""
68
+
69
+ # Placeholder for InsightFace initialization (will be done in service layer)
70
+ _detector = None
71
+
72
+ @classmethod
73
+ def init_detector(cls):
74
+ """Initialize InsightFace detector (lazy loading)"""
75
+ if cls._detector is None:
76
+ try:
77
+ from insightface.app import FaceAnalysis
78
+ from app.core.config import settings
79
+ import onnxruntime
80
+
81
+ # insightface==0.2.1: FaceAnalysis(name, root) only — no 'providers' kwarg.
82
+ # GPU vs CPU is controlled via ctx_id in prepare():
83
+ # ctx_id=0 → CUDA GPU
84
+ # ctx_id=-1 → CPU
85
+ ctx_id = -1 # default: CPU
86
+ if settings.INSIGHTFACE_GPU_AUTO:
87
+ available = onnxruntime.get_available_providers()
88
+ if "CUDAExecutionProvider" in available:
89
+ ctx_id = 0
90
+ elif settings.INSIGHTFACE_GPU:
91
+ ctx_id = 0
92
+
93
+ cls._detector = FaceAnalysis(name=settings.INSIGHTFACE_MODEL)
94
+ cls._detector.prepare(ctx_id=ctx_id)
95
+
96
+ logger.info(
97
+ f"Face detector initialized: model={settings.INSIGHTFACE_MODEL}, "
98
+ f"ctx_id={ctx_id} ({'GPU' if ctx_id == 0 else 'CPU'})"
99
+ )
100
+ except Exception as e:
101
+ logger.error(f"Failed to initialize face detector: {str(e)}")
102
+ raise
103
+
104
+ @classmethod
105
+ def detect_faces(cls, image: np.ndarray) -> List[dict]:
106
+ """Detect faces in image using InsightFace"""
107
+ if cls._detector is None:
108
+ cls.init_detector()
109
+
110
+ try:
111
+ faces = cls._detector.get(image)
112
+ return faces
113
+ except Exception as e:
114
+ logger.error(f"Face detection failed: {str(e)}")
115
+ return []
116
+
117
+ @classmethod
118
+ def get_face_embedding(cls, image: np.ndarray, face) -> np.ndarray:
119
+ """Extract embedding for a detected face"""
120
+ if cls._detector is None:
121
+ cls.init_detector()
122
+
123
+ try:
124
+ embedding = face.embedding
125
+ return embedding
126
+ except Exception as e:
127
+ logger.error(f"Embedding extraction failed: {str(e)}")
128
+ raise
129
+
130
+ @staticmethod
131
+ def get_face_quality(face) -> float:
132
+ """Get quality score for a face (0-1)"""
133
+ # This is a placeholder - actual quality can be computed from face landmarks
134
+ try:
135
+ if hasattr(face, 'det_score'):
136
+ return float(face.det_score)
137
+ except Exception:
138
+ pass
139
+
140
+ return 0.9 # Default high quality
141
+
142
+ @staticmethod
143
+ def get_face_angle(face) -> str:
144
+ """Determine face angle (frontal, profile, etc.)"""
145
+ try:
146
+ if hasattr(face, 'pose'):
147
+ pose = face.pose # [pitch, roll, yaw]
148
+ yaw = float(pose[2]) if len(pose) > 2 else 0
149
+ abs_yaw = abs(yaw)
150
+
151
+ if abs_yaw < 20:
152
+ return "frontal"
153
+ elif abs_yaw < 55:
154
+ return "left-half-profile" if yaw < 0 else "right-half-profile"
155
+ else:
156
+ return "left-profile" if yaw < 0 else "right-profile"
157
+ except Exception:
158
+ pass
159
+
160
+ return "unknown"
161
+
162
+ @staticmethod
163
+ def get_face_bbox(face) -> Optional[Tuple[float, float, float, float]]:
164
+ """Get bounding box for face [x1, y1, x2, y2]"""
165
+ try:
166
+ if hasattr(face, 'bbox'):
167
+ bbox = face.bbox
168
+ return tuple(bbox)
169
+ except Exception:
170
+ pass
171
+
172
+ return None
173
+
174
+
175
+ class ValidationUtils:
176
+ """Validation utilities"""
177
+
178
+ @staticmethod
179
+ def validate_email(email: str) -> bool:
180
+ """Validate email format"""
181
+ import re
182
+ pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
183
+ return re.match(pattern, email) is not None
184
+
185
+ @staticmethod
186
+ def validate_person_id(person_id: str) -> bool:
187
+ """Validate person_id format"""
188
+ # Can contain alphanumeric, underscore, hyphen
189
+ import re
190
+ pattern = r'^[a-zA-Z0-9_-]+$'
191
+ return len(person_id) > 0 and re.match(pattern, person_id) is not None
192
+
193
+ @staticmethod
194
+ def validate_password(password: str) -> Tuple[bool, str]:
195
+ """Validate password strength"""
196
+ if len(password) < 8:
197
+ return False, "Password must be at least 8 characters"
198
+
199
+ if not any(c.isupper() for c in password):
200
+ return False, "Password must contain at least one uppercase letter"
201
+
202
+ if not any(c.islower() for c in password):
203
+ return False, "Password must contain at least one lowercase letter"
204
+
205
+ if not any(c.isdigit() for c in password):
206
+ return False, "Password must contain at least one digit"
207
+
208
+ return True, "Password is valid"
backend/app/workers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Worker package."""
backend/app/workers/celery_app.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Celery application setup"""
2
+ from celery import Celery
3
+
4
+ from app.core.config import settings
5
+
6
+ celery_app = Celery(
7
+ "fmproject",
8
+ broker=settings.CELERY_BROKER_URL,
9
+ backend=settings.CELERY_RESULT_BACKEND,
10
+ )
11
+
12
+ celery_app.conf.update(
13
+ task_serializer="json",
14
+ result_serializer="json",
15
+ accept_content=["json"],
16
+ timezone="UTC",
17
+ enable_utc=True,
18
+ )
backend/app/workers/tasks.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Celery tasks for recognition and webhooks."""
2
+ import base64
3
+ from typing import Optional
4
+ from uuid import UUID
5
+
6
+ from app.core.database import SessionLocal
7
+ from app.services.recognition_service import RecognitionService
8
+ from app.workers.celery_app import celery_app
9
+
10
+
11
+ @celery_app.task(name="recognize_face")
12
+ def recognize_face_task(
13
+ image_b64: str,
14
+ tenant_id: str,
15
+ user_id: str,
16
+ threshold: float,
17
+ return_bboxes: bool,
18
+ ):
19
+ image_bytes = base64.b64decode(image_b64)
20
+ db = SessionLocal()
21
+ try:
22
+ return RecognitionService.recognize_from_bytes(
23
+ db=db,
24
+ image_bytes=image_bytes,
25
+ tenant_id=UUID(tenant_id),
26
+ user_id=UUID(user_id),
27
+ threshold=threshold,
28
+ return_bboxes=return_bboxes,
29
+ source="async_queue",
30
+ )
31
+ finally:
32
+ db.close()
33
+
34
+
35
+ @celery_app.task(name="deliver_webhook")
36
+ def deliver_webhook_task(event_id: str):
37
+ from app.services.webhook_service import WebhookService
38
+ from app.models import WebhookEvent, WebhookEndpoint
39
+ import httpx
40
+ from app.core.config import settings
41
+
42
+ db = SessionLocal()
43
+ try:
44
+ event = db.query(WebhookEvent).filter(WebhookEvent.id == UUID(event_id)).first()
45
+ if not event:
46
+ return
47
+ endpoint = db.query(WebhookEndpoint).filter(WebhookEndpoint.id == event.endpoint_id).first()
48
+ if not endpoint or not endpoint.is_active:
49
+ return
50
+
51
+ payload = event.payload
52
+ headers = {"Content-Type": "application/json"}
53
+ if endpoint.secret:
54
+ headers["X-Webhook-Secret"] = endpoint.secret
55
+
56
+ try:
57
+ with httpx.Client(timeout=settings.WEBHOOK_TIMEOUT_SECONDS) as client:
58
+ response = client.post(endpoint.url, content=payload, headers=headers)
59
+ if 200 <= response.status_code < 300:
60
+ WebhookService.mark_delivered(db, event, response.status_code)
61
+ else:
62
+ WebhookService.increment_attempt(db, event, response.status_code)
63
+ except Exception:
64
+ WebhookService.increment_attempt(db, event, None)
65
+ finally:
66
+ db.close()
backend/conftest.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test configuration and fixtures"""
2
+ import pytest
3
+ from sqlalchemy import create_engine
4
+ from sqlalchemy.orm import sessionmaker
5
+ from fastapi.testclient import TestClient
6
+
7
+ from app.main import app
8
+ from app.core.database import Base, get_db
9
+ from app.core.config import settings
10
+
11
+
12
+ # Test database setup
13
+ TEST_DATABASE_URL = "sqlite:///test.db"
14
+
15
+ engine = create_engine(
16
+ TEST_DATABASE_URL,
17
+ connect_args={"check_same_thread": False},
18
+ )
19
+ TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
20
+
21
+
22
+ def override_get_db():
23
+ """Override get_db for testing"""
24
+ try:
25
+ db = TestingSessionLocal()
26
+ yield db
27
+ finally:
28
+ db.close()
29
+
30
+
31
+ @pytest.fixture(scope="function")
32
+ def test_db():
33
+ """Create test database and tables"""
34
+ Base.metadata.create_all(bind=engine)
35
+ yield
36
+ Base.metadata.drop_all(bind=engine)
37
+
38
+
39
+ @pytest.fixture(scope="function")
40
+ def client(test_db):
41
+ """Create test client with overridden database"""
42
+ app.dependency_overrides[get_db] = override_get_db
43
+
44
+ with TestClient(app) as test_client:
45
+ yield test_client
46
+
47
+ app.dependency_overrides.clear()
48
+
49
+
50
+ @pytest.fixture
51
+ def test_user_data():
52
+ """Test user registration data"""
53
+ return {
54
+ "email": "test@example.com",
55
+ "password": "TestPassword123",
56
+ "full_name": "Test User"
57
+ }
58
+
59
+
60
+ @pytest.fixture
61
+ def test_login_data():
62
+ """Test login credentials"""
63
+ return {
64
+ "email": "test@example.com",
65
+ "password": "TestPassword123"
66
+ }
backend/docker-compose.yml ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ # MySQL Database
5
+ mysql:
6
+ image: mysql:8.0
7
+ container_name: fmproject_mysql
8
+ environment:
9
+ MYSQL_USER: fmproject
10
+ MYSQL_PASSWORD: fmproject_password
11
+ MYSQL_DATABASE: fmproject_db
12
+ MYSQL_ROOT_PASSWORD: fmproject_root_password
13
+ volumes:
14
+ - mysql_data:/var/lib/mysql
15
+ ports:
16
+ - "3306:3306"
17
+ healthcheck:
18
+ test: ["CMD-SHELL", "mysqladmin ping -h localhost -u fmproject -pfmproject_password"]
19
+ interval: 10s
20
+ timeout: 5s
21
+ retries: 5
22
+
23
+ # Redis Cache
24
+ redis:
25
+ image: redis:7-alpine
26
+ container_name: fmproject_redis
27
+ ports:
28
+ - "6379:6379"
29
+ volumes:
30
+ - redis_data:/data
31
+ healthcheck:
32
+ test: ["CMD", "redis-cli", "ping"]
33
+ interval: 10s
34
+ timeout: 5s
35
+ retries: 5
36
+
37
+ # MinIO S3-compatible Storage
38
+ minio:
39
+ image: minio/minio:latest
40
+ container_name: fmproject_minio
41
+ environment:
42
+ MINIO_ROOT_USER: minioadmin
43
+ MINIO_ROOT_PASSWORD: minioadmin
44
+ ports:
45
+ - "9000:9000"
46
+ - "9001:9001"
47
+ volumes:
48
+ - minio_data:/data
49
+ command: server /data --console-address ":9001"
50
+ healthcheck:
51
+ test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
52
+ interval: 30s
53
+ timeout: 20s
54
+ retries: 3
55
+
56
+ # FastAPI Backend
57
+ backend:
58
+ build:
59
+ context: .
60
+ dockerfile: Dockerfile
61
+ container_name: fmproject_backend
62
+ environment:
63
+ DATABASE_URL: mysql+pymysql://fmproject:fmproject_password@mysql:3306/fmproject_db
64
+ REDIS_URL: redis://redis:6379
65
+ CELERY_BROKER_URL: redis://redis:6379
66
+ CELERY_RESULT_BACKEND: redis://redis:6379
67
+ SECRET_KEY: your-super-secret-key-change-in-production
68
+ DEBUG: "False"
69
+ S3_ENDPOINT: http://minio:9000
70
+ S3_ACCESS_KEY: minioadmin
71
+ S3_SECRET_KEY: minioadmin
72
+ INSIGHTFACE_GPU: "False"
73
+ INSIGHTFACE_GPU_AUTO: "True"
74
+ QDRANT_URL: ""
75
+ QDRANT_API_KEY: ""
76
+ QDRANT_COLLECTION: face_embeddings
77
+ QDRANT_ENABLE: "True"
78
+ STRIPE_ENABLED: "False"
79
+ STRIPE_SECRET_KEY: ""
80
+ STRIPE_WEBHOOK_SECRET: ""
81
+ ports:
82
+ - "8000:8000"
83
+ depends_on:
84
+ mysql:
85
+ condition: service_healthy
86
+ redis:
87
+ condition: service_healthy
88
+ minio:
89
+ condition: service_healthy
90
+ volumes:
91
+ - .:/app
92
+ command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
93
+ healthcheck:
94
+ test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
95
+ interval: 30s
96
+ timeout: 10s
97
+ retries: 3
98
+
99
+ # Nginx Reverse Proxy
100
+ nginx:
101
+ image: nginx:alpine
102
+ container_name: fmproject_nginx
103
+ ports:
104
+ - "80:80"
105
+ - "443:443"
106
+ volumes:
107
+ - ./nginx.conf:/etc/nginx/nginx.conf:ro
108
+ depends_on:
109
+ - backend
110
+ healthcheck:
111
+ test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/health"]
112
+ interval: 30s
113
+ timeout: 10s
114
+ retries: 3
115
+
116
+ volumes:
117
+ mysql_data:
118
+ redis_data:
119
+ minio_data:
120
+
121
+ networks:
122
+ default:
123
+ name: fmproject_network
backend/init_app.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Startup and initialization script for the Face Inference Platform."""
2
+ import logging
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).parent))
7
+
8
+ from app.core.database import SessionLocal, init_db
9
+ from app.core.config import settings
10
+ from app.core.security import hash_password
11
+ from app.models import Tenant, User, UserRole
12
+ from app.services.auth_service import AuthService, TenantService
13
+
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def init_application():
19
+ """Create database tables and default development admin."""
20
+ logger.info("Initializing Face Inference Platform...")
21
+
22
+ logger.info("Initializing database...")
23
+ init_db()
24
+
25
+ db = SessionLocal()
26
+ try:
27
+ tenant = db.query(Tenant).filter(Tenant.name == "development").first()
28
+ if not tenant:
29
+ logger.info("Creating default development tenant...")
30
+ tenant = TenantService.create_tenant(
31
+ db=db,
32
+ name="development",
33
+ plan="enterprise",
34
+ )
35
+
36
+ admin_email = settings.ADMIN_DEFAULT_EMAIL
37
+ admin_password = settings.ADMIN_DEFAULT_PASSWORD
38
+
39
+ admin = (
40
+ db.query(User)
41
+ .filter(
42
+ User.tenant_id == tenant.id,
43
+ User.role == UserRole.ADMIN,
44
+ )
45
+ .order_by(User.created_at.asc())
46
+ .first()
47
+ )
48
+
49
+ if not admin:
50
+ logger.info("Creating default admin user...")
51
+ admin = AuthService.register_user(
52
+ db=db,
53
+ email=admin_email,
54
+ password=admin_password,
55
+ full_name="Admin User",
56
+ tenant_id=tenant.id,
57
+ role=UserRole.ADMIN,
58
+ )
59
+ logger.info("Default admin user created: %s", admin.email)
60
+ else:
61
+ admin.email = admin_email
62
+ admin.password_hash = hash_password(admin_password)
63
+ admin.role = UserRole.ADMIN
64
+ admin.is_active = True
65
+ db.commit()
66
+ db.refresh(admin)
67
+ logger.info("Default admin user reset: %s", admin.email)
68
+
69
+ logger.info("Default credentials for testing:")
70
+ logger.info(" Email: %s", admin_email)
71
+ logger.info(" Password: %s", admin_password)
72
+ logger.info("Application ready. API docs: http://localhost:8000/docs")
73
+ except Exception as exc:
74
+ logger.error("Error initializing application: %s", exc)
75
+ raise
76
+ finally:
77
+ db.close()
78
+
79
+
80
+ if __name__ == "__main__":
81
+ init_application()
backend/insightface-0.7.3.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:693059dcdcc5320cf40623955527782d490321b47c28a3b870f52c1f28e3bf24
3
+ size 111281
backend/insightface-0.7.3/PKG-INFO ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: insightface
3
+ Version: 0.7.3
4
+ Summary: InsightFace Python Library
5
+ Home-page: https://github.com/deepinsight/insightface
6
+ Author: InsightFace Contributors
7
+ Author-email: contact@insightface.ai
8
+ License: MIT
9
+ Description: InsightFace Python Library
10
+ ==========================
11
+
12
+ License
13
+ -------
14
+
15
+ The code of InsightFace Python Library is released under the MIT
16
+ License. There is no limitation for both academic and commercial usage.
17
+
18
+ **The pretrained models we provided with this library are available for
19
+ non-commercial research purposes only, including both auto-downloading
20
+ models and manual-downloading models.**
21
+
22
+ Install
23
+ -------
24
+
25
+ Install Inference Backend
26
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
27
+
28
+ For ``insightface<=0.1.5``, we use MXNet as inference backend.
29
+
30
+ Starting from insightface>=0.2, we use onnxruntime as inference backend.
31
+
32
+ You have to install ``onnxruntime-gpu`` manually to enable GPU
33
+ inference, or install ``onnxruntime`` to use CPU only inference.
34
+
35
+ Change Log
36
+ ----------
37
+
38
+ [0.7.1] - 2022-12-14
39
+ ~~~~~~~~~~~~~~~~~~~~
40
+
41
+ Changed
42
+ ^^^^^^^
43
+
44
+ - Change model downloading provider to cloudfront.
45
+
46
+ .. _section-1:
47
+
48
+ [0.7] - 2022-11-28
49
+ ~~~~~~~~~~~~~~~~~~
50
+
51
+ Added
52
+ ^^^^^
53
+
54
+ - Add face swapping model and example.
55
+
56
+ .. _changed-1:
57
+
58
+ Changed
59
+ ^^^^^^^
60
+
61
+ - Set default ORT provider to CUDA and CPU.
62
+
63
+ .. _section-2:
64
+
65
+ [0.6] - 2022-01-29
66
+ ~~~~~~~~~~~~~~~~~~
67
+
68
+ .. _added-1:
69
+
70
+ Added
71
+ ^^^^^
72
+
73
+ - Add pose estimation in face-analysis app.
74
+
75
+ .. _changed-2:
76
+
77
+ Changed
78
+ ^^^^^^^
79
+
80
+ - Change model automated downloading url, to ucloud.
81
+
82
+ Quick Example
83
+ -------------
84
+
85
+ ::
86
+
87
+ import cv2
88
+ import numpy as np
89
+ import insightface
90
+ from insightface.app import FaceAnalysis
91
+ from insightface.data import get_image as ins_get_image
92
+
93
+ app = FaceAnalysis(providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
94
+ app.prepare(ctx_id=0, det_size=(640, 640))
95
+ img = ins_get_image('t1')
96
+ faces = app.get(img)
97
+ rimg = app.draw_on(img, faces)
98
+ cv2.imwrite("./t1_output.jpg", rimg)
99
+
100
+ This quick example will detect faces from the ``t1.jpg`` image and draw
101
+ detection results on it.
102
+
103
+ Model Zoo
104
+ ---------
105
+
106
+ In the latest version of insightface library, we provide following model
107
+ packs:
108
+
109
+ Name in **bold** is the default model pack. **Auto** means we can
110
+ download the model pack through the python library directly.
111
+
112
+ Once you manually downloaded the zip model pack, unzip it under
113
+ ``~/.insightface/models/`` first before you call the program.
114
+
115
+ +-----+------+--------+----+---+---+---------------------------+-----+
116
+ | Nam | Dete | Recogn | Al | A | M | Link | Aut |
117
+ | e | ctio | ition | ig | t | o | | o |
118
+ | | n | Model | nm | t | d | | |
119
+ | | Mode | | en | r | e | | |
120
+ | | l | | t | i | l | | |
121
+ | | | | | b | - | | |
122
+ | | | | | u | S | | |
123
+ | | | | | t | i | | |
124
+ | | | | | e | z | | |
125
+ | | | | | s | e | | |
126
+ +=====+======+========+====+===+===+===========================+=====+
127
+ | ant | SCRF | ResNet | 2d | G | 4 | `link <https://drive.goog | N |
128
+ | elo | D-10 | 100@Gl | 10 | e | 0 | le.com/file/d/18wEUfMNohB | |
129
+ | pev | GF | int360 | 6 | n | 7 | J4K3Ly5wpTejPfDzp-8fI8/vi | |
130
+ | 2 | | K | & | d | M | ew?usp=sharing>`__ | |
131
+ | | | | 3d | e | B | | |
132
+ | | | | 68 | r | | | |
133
+ | | | | | & | | | |
134
+ | | | | | A | | | |
135
+ | | | | | g | | | |
136
+ | | | | | e | | | |
137
+ +-----+------+--------+----+---+---+---------------------------+-----+
138
+ | **b | SCRF | ResNet | 2d | G | 3 | `link <https://drive.goog | Y |
139
+ | uff | D-10 | 50@Web | 10 | e | 2 | le.com/file/d/1qXsQJ8ZT42 | |
140
+ | alo | GF | Face60 | 6 | n | 6 | _xSmWIYy85IcidpiZudOCB/vi | |
141
+ | _l* | | 0K | & | d | M | ew?usp=sharing>`__ | |
142
+ | * | | | 3d | e | B | | |
143
+ | | | | 68 | r | | | |
144
+ | | | | | & | | | |
145
+ | | | | | A | | | |
146
+ | | | | | g | | | |
147
+ | | | | | e | | | |
148
+ +-----+------+--------+----+---+---+---------------------------+-----+
149
+ | buf | SCRF | ResNet | 2d | G | 3 | `link <https://drive.goog | N |
150
+ | fal | D-2. | 50@Web | 10 | e | 1 | le.com/file/d/1net68yNxF3 | |
151
+ | o_m | 5GF | Face60 | 6 | n | 3 | 3NNV6WP7k56FS6V53tq-64/vi | |
152
+ | | | 0K | & | d | M | ew?usp=sharing>`__ | |
153
+ | | | | 3d | e | B | | |
154
+ | | | | 68 | r | | | |
155
+ | | | | | & | | | |
156
+ | | | | | A | | | |
157
+ | | | | | g | | | |
158
+ | | | | | e | | | |
159
+ +-----+------+--------+----+---+---+---------------------------+-----+
160
+ | buf | SCRF | MBF@We | 2d | G | 1 | `link <https://drive.goog | N |
161
+ | fal | D-50 | bFace6 | 10 | e | 5 | le.com/file/d/1pKIusApEfo | |
162
+ | o_s | 0MF | 00K | 6 | n | 9 | HKDjeBTXYB3yOQ0EtTonNE/vi | |
163
+ | | | | & | d | M | ew?usp=sharing>`__ | |
164
+ | | | | 3d | e | B | | |
165
+ | | | | 68 | r | | | |
166
+ | | | | | & | | | |
167
+ | | | | | A | | | |
168
+ | | | | | g | | | |
169
+ | | | | | e | | | |
170
+ +-----+------+--------+----+---+---+---------------------------+-----+
171
+ | buf | SCRF | MBF@We | - | - | 1 | `link <https://drive.goog | N |
172
+ | fal | D-50 | bFace6 | | | 6 | le.com/file/d/19I-MZdctYK | |
173
+ | o_s | 0MF | 00K | | | M | mVf3nu5Da3HS6KH5LBfdzG/vi | |
174
+ | c | | | | | B | ew?usp=sharing>`__ | |
175
+ +-----+------+--------+----+---+---+---------------------------+-----+
176
+
177
+ Recognition Accuracy:
178
+
179
+ +-------+----+-----+-------+--------+--------+---+----+------+-------+
180
+ | Name | MR | Afr | Cauca | South | East | L | CF | AgeD | IJB-C |
181
+ | | -A | ica | sian | Asian | Asian | F | P- | B-30 | (E4) |
182
+ | | LL | n | | | | W | FP | | |
183
+ +=======+====+=====+=======+========+========+===+====+======+=======+
184
+ | buffa | 91 | 90. | 94.70 | 93.16 | 74.96 | 9 | 99 | 98.2 | 97.25 |
185
+ | lo_l | .2 | 29 | | | | 9 | .3 | 3 | |
186
+ | | 5 | | | | | . | 3 | | |
187
+ | | | | | | | 8 | | | |
188
+ | | | | | | | 3 | | | |
189
+ +-------+----+-----+-------+--------+--------+---+----+------+-------+
190
+ | buffa | 71 | 69. | 80.45 | 73.39 | 51.03 | 9 | 98 | 96.5 | 95.02 |
191
+ | lo_s | .8 | 45 | | | | 9 | .0 | 8 | |
192
+ | | 7 | | | | | . | 0 | | |
193
+ | | | | | | | 7 | | | |
194
+ | | | | | | | 0 | | | |
195
+ +-------+----+-----+-------+--------+--------+---+----+------+-------+
196
+
197
+ *buffalo_m has the same accuracy with buffalo_l.*
198
+
199
+ *buffalo_sc has the same accuracy with buffalo_s.*
200
+
201
+ **Note that these models are available for non-commercial research
202
+ purposes only.**
203
+
204
+ For insightface>=0.3.3, models will be downloaded automatically once we
205
+ init ``app = FaceAnalysis()`` instance.
206
+
207
+ For insightface==0.3.2, you must first download the model package by
208
+ command:
209
+
210
+ ::
211
+
212
+ insightface-cli model.download buffalo_l
213
+
214
+ Use Your Own Licensed Model
215
+ ---------------------------
216
+
217
+ You can simply create a new model directory under
218
+ ``~/.insightface/models/`` and replace the pretrained models we provide
219
+ with your own models. And then call
220
+ ``app = FaceAnalysis(name='your_model_zoo')`` to load these models.
221
+
222
+ Call Models
223
+ -----------
224
+
225
+ The latest insightface libary only supports onnx models. Once you have
226
+ trained detection or recognition models by PyTorch, MXNet or any other
227
+ frameworks, you can convert it to the onnx format and then they can be
228
+ called with insightface library.
229
+
230
+ Call Detection Models
231
+ ~~~~~~~~~~~~~~~~~~~~~
232
+
233
+ ::
234
+
235
+ import cv2
236
+ import numpy as np
237
+ import insightface
238
+ from insightface.app import FaceAnalysis
239
+ from insightface.data import get_image as ins_get_image
240
+
241
+ # Method-1, use FaceAnalysis
242
+ app = FaceAnalysis(allowed_modules=['detection']) # enable detection model only
243
+ app.prepare(ctx_id=0, det_size=(640, 640))
244
+
245
+ # Method-2, load model directly
246
+ detector = insightface.model_zoo.get_model('your_detection_model.onnx')
247
+ detector.prepare(ctx_id=0, input_size=(640, 640))
248
+
249
+ Call Recognition Models
250
+ ~~~~~~~~~~~~~~~~~~~~~~~
251
+
252
+ ::
253
+
254
+ import cv2
255
+ import numpy as np
256
+ import insightface
257
+ from insightface.app import FaceAnalysis
258
+ from insightface.data import get_image as ins_get_image
259
+
260
+ handler = insightface.model_zoo.get_model('your_recognition_model.onnx')
261
+ handler.prepare(ctx_id=0)
262
+
263
+
264
+ Platform: UNKNOWN
265
+ Description-Content-Type: text/markdown
backend/insightface-0.7.3/README.md ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # InsightFace Python Library
2
+
3
+ ## License
4
+
5
+ The code of InsightFace Python Library is released under the MIT License. There is no limitation for both academic and commercial usage.
6
+
7
+ **The pretrained models we provided with this library are available for non-commercial research purposes only, including both auto-downloading models and manual-downloading models.**
8
+
9
+ ## Install
10
+
11
+ ### Install Inference Backend
12
+
13
+ For ``insightface<=0.1.5``, we use MXNet as inference backend.
14
+
15
+ Starting from insightface>=0.2, we use onnxruntime as inference backend.
16
+
17
+ You have to install ``onnxruntime-gpu`` manually to enable GPU inference, or install ``onnxruntime`` to use CPU only inference.
18
+
19
+ ## Change Log
20
+
21
+ ### [0.7.1] - 2022-12-14
22
+
23
+ #### Changed
24
+
25
+ - Change model downloading provider to cloudfront.
26
+
27
+ ### [0.7] - 2022-11-28
28
+
29
+ #### Added
30
+
31
+ - Add face swapping model and example.
32
+
33
+ #### Changed
34
+
35
+ - Set default ORT provider to CUDA and CPU.
36
+
37
+ ### [0.6] - 2022-01-29
38
+
39
+ #### Added
40
+
41
+ - Add pose estimation in face-analysis app.
42
+
43
+ #### Changed
44
+
45
+ - Change model automated downloading url, to ucloud.
46
+
47
+
48
+ ## Quick Example
49
+
50
+ ```
51
+ import cv2
52
+ import numpy as np
53
+ import insightface
54
+ from insightface.app import FaceAnalysis
55
+ from insightface.data import get_image as ins_get_image
56
+
57
+ app = FaceAnalysis(providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
58
+ app.prepare(ctx_id=0, det_size=(640, 640))
59
+ img = ins_get_image('t1')
60
+ faces = app.get(img)
61
+ rimg = app.draw_on(img, faces)
62
+ cv2.imwrite("./t1_output.jpg", rimg)
63
+ ```
64
+
65
+ This quick example will detect faces from the ``t1.jpg`` image and draw detection results on it.
66
+
67
+
68
+
69
+ ## Model Zoo
70
+
71
+ In the latest version of insightface library, we provide following model packs:
72
+
73
+ Name in **bold** is the default model pack. **Auto** means we can download the model pack through the python library directly.
74
+
75
+ Once you manually downloaded the zip model pack, unzip it under `~/.insightface/models/` first before you call the program.
76
+
77
+ | Name | Detection Model | Recognition Model | Alignment | Attributes | Model-Size | Link | Auto |
78
+ | ------------- | --------------- | -------------------- | ------------ | ---------- | ---------- | ------------------------------------------------------------ | ------------- |
79
+ | antelopev2 | SCRFD-10GF | ResNet100@Glint360K | 2d106 & 3d68 | Gender&Age | 407MB | [link](https://drive.google.com/file/d/18wEUfMNohBJ4K3Ly5wpTejPfDzp-8fI8/view?usp=sharing) | N |
80
+ | **buffalo_l** | SCRFD-10GF | ResNet50@WebFace600K | 2d106 & 3d68 | Gender&Age | 326MB | [link](https://drive.google.com/file/d/1qXsQJ8ZT42_xSmWIYy85IcidpiZudOCB/view?usp=sharing) | Y |
81
+ | buffalo_m | SCRFD-2.5GF | ResNet50@WebFace600K | 2d106 & 3d68 | Gender&Age | 313MB | [link](https://drive.google.com/file/d/1net68yNxF33NNV6WP7k56FS6V53tq-64/view?usp=sharing) | N |
82
+ | buffalo_s | SCRFD-500MF | MBF@WebFace600K | 2d106 & 3d68 | Gender&Age | 159MB | [link](https://drive.google.com/file/d/1pKIusApEfoHKDjeBTXYB3yOQ0EtTonNE/view?usp=sharing) | N |
83
+ | buffalo_sc | SCRFD-500MF | MBF@WebFace600K | - | - | 16MB | [link](https://drive.google.com/file/d/19I-MZdctYKmVf3nu5Da3HS6KH5LBfdzG/view?usp=sharing) | N |
84
+
85
+
86
+
87
+ Recognition Accuracy:
88
+
89
+ | Name | MR-ALL | African | Caucasian | South Asian | East Asian | LFW | CFP-FP | AgeDB-30 | IJB-C(E4) |
90
+ | :-------- | ------ | ------- | --------- | ----------- | ---------- | ----- | ------ | -------- | --------- |
91
+ | buffalo_l | 91.25 | 90.29 | 94.70 | 93.16 | 74.96 | 99.83 | 99.33 | 98.23 | 97.25 |
92
+ | buffalo_s | 71.87 | 69.45 | 80.45 | 73.39 | 51.03 | 99.70 | 98.00 | 96.58 | 95.02 |
93
+
94
+ *buffalo_m has the same accuracy with buffalo_l.*
95
+
96
+ *buffalo_sc has the same accuracy with buffalo_s.*
97
+
98
+
99
+
100
+ **Note that these models are available for non-commercial research purposes only.**
101
+
102
+
103
+
104
+ For insightface>=0.3.3, models will be downloaded automatically once we init ``app = FaceAnalysis()`` instance.
105
+
106
+ For insightface==0.3.2, you must first download the model package by command:
107
+
108
+ ```
109
+ insightface-cli model.download buffalo_l
110
+ ```
111
+
112
+ ## Use Your Own Licensed Model
113
+
114
+ You can simply create a new model directory under ``~/.insightface/models/`` and replace the pretrained models we provide with your own models. And then call ``app = FaceAnalysis(name='your_model_zoo')`` to load these models.
115
+
116
+ ## Call Models
117
+
118
+ The latest insightface libary only supports onnx models. Once you have trained detection or recognition models by PyTorch, MXNet or any other frameworks, you can convert it to the onnx format and then they can be called with insightface library.
119
+
120
+ ### Call Detection Models
121
+
122
+ ```
123
+ import cv2
124
+ import numpy as np
125
+ import insightface
126
+ from insightface.app import FaceAnalysis
127
+ from insightface.data import get_image as ins_get_image
128
+
129
+ # Method-1, use FaceAnalysis
130
+ app = FaceAnalysis(allowed_modules=['detection']) # enable detection model only
131
+ app.prepare(ctx_id=0, det_size=(640, 640))
132
+
133
+ # Method-2, load model directly
134
+ detector = insightface.model_zoo.get_model('your_detection_model.onnx')
135
+ detector.prepare(ctx_id=0, input_size=(640, 640))
136
+
137
+ ```
138
+
139
+ ### Call Recognition Models
140
+
141
+ ```
142
+ import cv2
143
+ import numpy as np
144
+ import insightface
145
+ from insightface.app import FaceAnalysis
146
+ from insightface.data import get_image as ins_get_image
147
+
148
+ handler = insightface.model_zoo.get_model('your_recognition_model.onnx')
149
+ handler.prepare(ctx_id=0)
150
+
151
+ ```
152
+
153
+
backend/insightface-0.7.3/insightface/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+ # pylint: disable=wrong-import-position
3
+ """InsightFace: A Face Analysis Toolkit."""
4
+ from __future__ import absolute_import
5
+
6
+ try:
7
+ #import mxnet as mx
8
+ import onnxruntime
9
+ except ImportError:
10
+ raise ImportError(
11
+ "Unable to import dependency onnxruntime. "
12
+ )
13
+
14
+ __version__ = '0.7.3'
15
+
16
+ from . import model_zoo
17
+ from . import utils
18
+ from . import app
19
+ from . import data
20
+ from . import thirdparty
21
+
backend/insightface-0.7.3/insightface/app/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .face_analysis import *
2
+ from .mask_renderer import *
backend/insightface-0.7.3/insightface/app/common.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from numpy.linalg import norm as l2norm
3
+ #from easydict import EasyDict
4
+
5
+ class Face(dict):
6
+
7
+ def __init__(self, d=None, **kwargs):
8
+ if d is None:
9
+ d = {}
10
+ if kwargs:
11
+ d.update(**kwargs)
12
+ for k, v in d.items():
13
+ setattr(self, k, v)
14
+ # Class attributes
15
+ #for k in self.__class__.__dict__.keys():
16
+ # if not (k.startswith('__') and k.endswith('__')) and not k in ('update', 'pop'):
17
+ # setattr(self, k, getattr(self, k))
18
+
19
+ def __setattr__(self, name, value):
20
+ if isinstance(value, (list, tuple)):
21
+ value = [self.__class__(x)
22
+ if isinstance(x, dict) else x for x in value]
23
+ elif isinstance(value, dict) and not isinstance(value, self.__class__):
24
+ value = self.__class__(value)
25
+ super(Face, self).__setattr__(name, value)
26
+ super(Face, self).__setitem__(name, value)
27
+
28
+ __setitem__ = __setattr__
29
+
30
+ def __getattr__(self, name):
31
+ return None
32
+
33
+ @property
34
+ def embedding_norm(self):
35
+ if self.embedding is None:
36
+ return None
37
+ return l2norm(self.embedding)
38
+
39
+ @property
40
+ def normed_embedding(self):
41
+ if self.embedding is None:
42
+ return None
43
+ return self.embedding / self.embedding_norm
44
+
45
+ @property
46
+ def sex(self):
47
+ if self.gender is None:
48
+ return None
49
+ return 'M' if self.gender==1 else 'F'