sakshusat commited on
Commit
1379d8e
Β·
0 Parent(s):

first commit

Browse files
Files changed (5) hide show
  1. .gitattributes +1 -0
  2. README.md +38 -0
  3. face_service.py +131 -0
  4. requirements.txt +6 -0
  5. setup.md +101 -0
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.onnx filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Face Recognition Service
2
+
3
+ This is a FastAPI-based microservice for face detection and verification using DeepFace.
4
+
5
+ ## Prerequisites
6
+
7
+ - Python 3.8+
8
+ - pip
9
+
10
+ ## Installation
11
+
12
+ 1. Navigate to this directory:
13
+ ```bash
14
+ cd face-recognition-service
15
+ ```
16
+
17
+ 2. Install dependencies:
18
+ ```bash
19
+ pip install -r requirements.txt
20
+ ```
21
+
22
+ *Note: DeepFace may require additional system dependencies depending on your OS.*
23
+
24
+ ## Running the Service
25
+
26
+ Start the server using uvicorn:
27
+
28
+ ```bash
29
+ uvicorn face_service:app --reload --port 8000
30
+ ```
31
+
32
+ The service will be available at `http://localhost:8000`.
33
+
34
+ ## API Endpoints
35
+
36
+ - `GET /` - Health check.
37
+ - `POST /detect` - Detect faces in a base64 encoded image.
38
+ - `POST /verify` - Verify a live face against a list of stored face images.
face_service.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from fastapi import FastAPI, HTTPException
3
+ from pydantic import BaseModel
4
+ import uvicorn
5
+ import base64
6
+ import cv2
7
+ import numpy as np
8
+ from deepface import DeepFace
9
+ import os
10
+ import tempfile
11
+ import logging
12
+
13
+ # Setup logging
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ app = FastAPI()
18
+
19
+ class VerifyRequest(BaseModel):
20
+ live: str
21
+ stored: list[str] = []
22
+
23
+ def base64_to_image(b64_string):
24
+ try:
25
+ if "," in b64_string:
26
+ b64_string = b64_string.split(",")[1]
27
+
28
+ # Decode base64 string to bytes
29
+ img_bytes = base64.b64decode(b64_string)
30
+
31
+ # Convert bytes to numpy array
32
+ nparr = np.frombuffer(img_bytes, np.uint8)
33
+
34
+ # Decode image
35
+ img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
36
+ return img
37
+ except Exception as e:
38
+ logger.error(f"Error converting base64 to image: {str(e)}")
39
+ return None
40
+
41
+ @app.post("/detect")
42
+ def detect_face(data: VerifyRequest):
43
+ # We use the 'live' image from request for detection check
44
+ # We can reuse VerifyRequest or make a new one. VerifyRequest has 'stored' too.
45
+ # Let's handle generic inputs or just ignore 'stored'.
46
+ try:
47
+ img = base64_to_image(data.live)
48
+ if img is None:
49
+ raise HTTPException(status_code=400, detail="Invalid image")
50
+
51
+ # extract_faces returns a list of detected faces
52
+ # enforce_detection=True is default. If no face, it raises ValueError
53
+ faces = DeepFace.extract_faces(img_path=img, detector_backend="opencv", enforce_detection=True)
54
+ return {"detected": True, "count": len(faces)}
55
+ except ValueError:
56
+ return {"detected": False, "count": 0}
57
+ except Exception as e:
58
+ logger.error(f"Detection error: {str(e)}")
59
+ # If error is generic, return false
60
+ return {"detected": False, "error": str(e)}
61
+
62
+ @app.post("/verify")
63
+ def verify_face(data: VerifyRequest):
64
+ try:
65
+ img_live = base64_to_image(data.live)
66
+ if img_live is None:
67
+ raise HTTPException(status_code=400, detail="Invalid live image")
68
+
69
+ if not data.stored:
70
+ raise HTTPException(status_code=400, detail="No stored images for verification")
71
+
72
+ best_result = None
73
+ best_distance = float('inf')
74
+
75
+ # Check against stored images
76
+ # Optimization: Return immediately if we find a match (Early Exit)
77
+ for stored_b64 in data.stored:
78
+ img_stored = base64_to_image(stored_b64)
79
+ if img_stored is None:
80
+ continue
81
+
82
+ try:
83
+ result = DeepFace.verify(
84
+ img1_path=img_live,
85
+ img2_path=img_stored,
86
+ model_name="VGG-Face",
87
+ enforce_detection=False,
88
+ detector_backend="opencv"
89
+ )
90
+
91
+ # If verified, return immediately (Speed optimization)
92
+ if result['verified']:
93
+ logger.info(f"Match found! Early exit. Distance: {result['distance']}")
94
+ return {
95
+ "verified": True,
96
+ "distance": float(result['distance']),
97
+ "threshold": float(result['threshold']),
98
+ "model": "VGG-Face"
99
+ }
100
+
101
+ # Keep the best match (lowest distance) just in case none pass 'verified' check
102
+ # but we want to return the closest failure? Or just fail.
103
+ if result['distance'] < best_distance:
104
+ best_distance = result['distance']
105
+ best_result = result
106
+ except Exception as match_error:
107
+ logger.error(f"Single pair verification failed: {match_error}")
108
+ continue
109
+
110
+ if not best_result:
111
+ raise HTTPException(status_code=400, detail="Verification failed for all images (or no valid stored images)")
112
+
113
+ logger.info(f"Best verification result: {best_result}")
114
+
115
+ return {
116
+ "verified": bool(best_result['verified']),
117
+ "distance": float(best_result['distance']),
118
+ "threshold": float(best_result['threshold']),
119
+ "model": "VGG-Face"
120
+ }
121
+
122
+ except Exception as e:
123
+ logger.error(f"Verification error: {str(e)}")
124
+ raise HTTPException(status_code=500, detail=str(e))
125
+
126
+ @app.get("/")
127
+ def home():
128
+ return {"status": "Face Service is running"}
129
+
130
+ if __name__ == "__main__":
131
+ uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ pydantic
4
+ numpy
5
+ opencv-python
6
+ deepface
setup.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SIH Project Setup Guide
2
+
3
+ ## Quick Start
4
+
5
+ ### 1. Backend Server Setup
6
+ ```bash
7
+ cd server
8
+ npm install
9
+ # Create .env file with:
10
+ # PORT=5000
11
+ # MONGODB_URI=mongodb://localhost:27017/sih_attendance
12
+ npm run dev
13
+ ```
14
+
15
+ ### 2. Student Mobile App Setup
16
+ ```bash
17
+ cd app
18
+ npm install
19
+ npx expo start
20
+ # Scan QR code with Expo Go app
21
+ ```
22
+
23
+ ### 3. Admin Web App Setup
24
+ ```bash
25
+ cd admin
26
+ npm install
27
+ npm start
28
+ # Open http://localhost:3000
29
+ ```
30
+
31
+ ### 4. Face Recognition Service Setup
32
+ ```bash
33
+ cd face-recognition-service
34
+ pip install -r requirements.txt
35
+ python face_service.py
36
+ # Reference Server runs on http://localhost:8000
37
+ ```
38
+
39
+ ## Demo Credentials
40
+
41
+ ### Student Login
42
+ - Student ID: STU001
43
+ - Password: password123
44
+
45
+ ### Admin Login
46
+ - Username: admin
47
+ - Password: admin123
48
+
49
+ ## Features Implemented
50
+
51
+ βœ… Student login with dummy authentication
52
+ βœ… Profile page with navigation
53
+ βœ… QR code scanner for attendance (expo-camera)
54
+ βœ… Attendance percentage view
55
+ βœ… Timetable view with API integration
56
+ βœ… Free time slot suggestions
57
+ βœ… Tests/Exams view with dummy data
58
+ βœ… AsyncStorage for device ID storage
59
+ βœ… Axios for API calls
60
+ βœ… Admin login (dummy)
61
+ βœ… QR code generation with auto-refresh
62
+ βœ… Attendance list management
63
+ βœ… Timetable management
64
+ βœ… Express API routes for all features
65
+ βœ… MongoDB models and integration
66
+ βœ… Dummy data for 2 students with complete schedules
67
+
68
+ ## API Endpoints
69
+
70
+ - POST /api/auth/login
71
+ - POST /api/attendance/generate-qr
72
+ - POST /api/attendance/mark
73
+ - GET /api/attendance/:studentId
74
+ - GET /api/timetable/:studentId
75
+ - GET /api/freetime/:studentId
76
+ - GET /api/tests/:studentId
77
+
78
+ ## Project Structure
79
+
80
+ ```
81
+ SIH/
82
+ β”œβ”€β”€ app/ # Expo React Native App
83
+ β”‚ β”œβ”€β”€ src/
84
+ β”‚ β”‚ β”œβ”€β”€ screens/ # All app screens
85
+ β”‚ β”‚ β”œβ”€β”€ services/ # API services
86
+ β”‚ β”‚ └── context/ # Auth context
87
+ β”‚ └── package.json
88
+ β”œβ”€β”€ admin/ # React Web App
89
+ β”‚ β”œβ”€β”€ src/
90
+ β”‚ β”‚ β”œβ”€β”€ components/ # React components
91
+ β”‚ β”‚ └── services/ # API services
92
+ β”‚ └── package.json
93
+ └── server/ # Node.js Backend
94
+ β”œβ”€β”€ models/ # MongoDB models
95
+ β”œβ”€β”€ server.js # Main server file
96
+ └── package.json
97
+ ```
98
+
99
+ ## Ready to Use!
100
+
101
+ The project is fully functional with all requested features implemented. Start the backend server first, then the admin app, and finally the mobile app to test the complete system.