have to fix bug

swadhinbiswas committed 2 years ago
f5f0447
1 parent 6b2116d
commit f5f0447
28 files changed
+1045 -53
▼.gitignore
+1-1
152
152
153
153
# Cython debug symbols
154
154
cython_debug/
155
-
155
+serviceAccountKey.json
156
156
# PyCharm
157
157
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
158
158
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
159
159
▼backend/app/api/__init__.py → backend/app/admin/__init__.py
+0-0
0
0
▼backend/app/admin/handelars.py
+93-0
1
+from fastapi import Depends, HTTPException, status,UploadFile,File
2
+from app.models.studentmodel import StudentModelshema
3
+from fastapi import APIRouter
4
+from app.settings.connectdb import Firebase
5
+from typing import Dict,Any,Optional
6
+from datetime import datetime
7
+from app.functions.encodeGenarator import EndcodeGenarator
8
+
9
+
10
+db_add=APIRouter()
11
+db=Firebase()
12
+imagepath=EndcodeGenarator().imagepath
13
+picklepath=EndcodeGenarator().picklepath
14
+
15
+
16
+@db_add.post("/create")
17
+async def add_to_db(Student:StudentModelshema):
18
+
19
+ data={
20
+ Student.id: {
21
+ "name": Student.name,
22
+ "email": Student.email,
23
+ "status": Student.status,
24
+ "Department": Student.Department,
25
+ "Semester": Student.Semester,
26
+ "Section": Student.Section,
27
+ "Total_Attendance": Student.Total_Attendance,
28
+ "last_seen": f"{datetime.now().strftime('%d-%m-%Y %H:%M:%S')}",
29
+ }
30
+ }
31
+ x=db.set_data(data)
32
+ return x
33
+
34
+@db_add.get("/getstudents")
35
+async def get_from_db():
36
+ data=db.get_data()
37
+ return data
38
+
39
+@db_add.get("/getstudent/{id}")
40
+async def get_from_db(id:str):
41
+ data=db.get_data_by_key(id)
42
+ return data
43
+
44
+@db_add.put("/updatestudent/{id}")
45
+async def update_db(id:str,data:Dict[str,Any])->Dict[str,Any]:
46
+ x=db.update_data(id,data)
47
+ return x
48
+
49
+@db_add.delete("/deletestudent/{id}")
50
+async def delete_from_db(id:str):
51
+ x=db.delete_data(id)
52
+ return x
53
+
54
+@db_add.get("/getstudentbydepartment/{department}")
55
+async def get_from_db(department:str):
56
+ data=db.get_data_by_child_value("Department",department)
57
+ return data
58
+@db_add.get("/getpresentstudents")
59
+async def get_from_db():
60
+ data=db.get_data_by_present()
61
+ return data
62
+@db_add.get("/getstudentbyrange/{start}/{end}")
63
+async def get_from_db(start:int,end:int):
64
+ data=db.get_data_by_child_range("Total_Attendance",start,end)
65
+ return data
66
+
67
+@db_add.get("/getstudentbylimit/{limit}")
68
+async def get_from_db(limit:int):
69
+ data=db.get_data_by_child_limit("Total_Attendance",limit)
70
+ return data
71
+
72
+@db_add.get("/uploadimage")
73
+async def uploadimage(img:UploadFile=File(...)):
74
+ try:
75
+ content = await img.read()
76
+ with open(imagepath, "wb") as file:
77
+ file.write(content)
78
+ return {"message":"Image uploaded"}
79
+
80
+ except Exception as e:
81
+ return {"message":str(e)}
82
+ finally:
83
+ file.close()
84
+@db_add.get("/encoding")
85
+async def encoding():
86
+ x=EndcodeGenarator().findencoding()
87
+ return x
88
+
89
+
90
+
91
+
92
+
93
+
0
94
▼backend/app/admin/pathtest.py
+2-0
1
+import os
2
+
0
3
▼backend/app/api/handelars.py
+0-28
1
-from fastapi import Depends, HTTPException, status
2
-from app.models.studentmodel import StudentModel
3
-from fastapi import APIRouter
4
-from app.settings.connectdb import Firebase
5
-
6
-
7
-
8
-db_add=APIRouter()
9
-
10
-
11
-@db_add.post("/create")
12
-async def add_to_db(Student:StudentModel):
13
- ref=Firebase.ref
14
- data={
15
- Student.id: {
16
- "name": Student.name,
17
- "email": Student.email,
18
- "status": Student.status,
19
- "Department": Student.Department,
20
- "Semester": Student.Semester,
21
- "Section": Student.Section,
22
- "Total_Attendance": Student.Total_Attendance,
23
- "last_seen": Student.last_seen,
24
- }
25
- }
26
-
27
- ref.push(data)
28
- return {data:data}
29
0
▼backend/app/functions/encodeGenarator.py
+214-0
1
+import os
2
+import pickle
3
+import face_recognition
4
+import cv2
5
+from app.settings.connectdb import Firebase
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+class EndcodeGenarator:
14
+ def __init__(self):
15
+ self.known_face_encodings = []
16
+ self.studentids = []
17
+ self.encodings = []
18
+ self.pathlist = os.listdir(os.path.join(os.path.dirname(__file__), "pictures"))
19
+ self.picklepath = os.path.join(os.path.dirname(__file__), "encodings.pickle")
20
+ self.imagepath = os.path.join(os.path.dirname(__file__), "pictures")
21
+ self.ref = Firebase().ref
22
+ self.bucket = Firebase().bucket
23
+ self.idsref = Firebase().idsref
24
+ imagepath=self.imagepath
25
+ picklepath=self.picklepath
26
+ pathlist=self.pathlist
27
+
28
+ def findencoding(self):
29
+ imageList=self.pathlist
30
+ for img in imageList:
31
+ bucket=self.bucket
32
+ ref=self.ref
33
+ if not bucket.get_blob(f"faceappimage/{img}"):
34
+ with open(f"{self.imagepath}/{img}","rb") as file:
35
+ bucket.blob(f"faceappimage/{img}").upload_from_file(file)
36
+ id=img.split(".")[0]
37
+ self.studentids.append(id)
38
+ if not ref.child(id).get():
39
+ if img.endswith(".jpg") or img.endswith(".png") or img.endswith(".jpeg"):
40
+ cv2img=cv2.imread(f"{self.imagepath}/{img}")
41
+ img=cv2.cvtColor(cv2img,cv2.COLOR_BGR2RGB)
42
+ encode=face_recognition.face_encodings(img)[0]
43
+ self.encodings.append(encode)
44
+ self.idsref.child(id).set(encode.tolist())
45
+
46
+
47
+ encodeKnowlist=[self.encodings,self.studentids]
48
+ file=open(self.picklepath,"wb")
49
+ pickle.dump(encodeKnowlist,file)
50
+ file.close()
51
+
52
+ return {
53
+ "message":"encoding done",
54
+ "status":"success",
55
+ "data":"Knowlist saved in pickle file and Stored in firebase",
56
+ }
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+# phots_path = os.path.join(os.path.dirname(__file__), "pictures")
74
+
75
+# pickle_path = os.path.join(os.path.dirname(__file__), "encodings.pickle")
76
+
77
+# pathlist = os.listdir(phots_path)
78
+# print(pathlist)
79
+
80
+# print(phots_path)
81
+
82
+
83
+
84
+
85
+# class EncodeGenarator:
86
+ # def __init__(self):
87
+ # self.known_face_encodings = []
88
+ # self.known_face_names = []
89
+ # self.path = os.path.join(os.path.dirname(__file__), "encodings.pickle")
90
+ # self.load_encodings()
91
+
92
+ # def load_encodings(self):
93
+ # if os.path.exists(self.path):
94
+ # with open(self.path, "rb") as f:
95
+ # self.known_face_encodings, self.known_face_names = pickle.load(f)
96
+
97
+ # def save_encodings(self):
98
+ # with open(self.path, "wb") as f:
99
+ # pickle.dump([self.known_face_encodings, self.known_face_names], f)
100
+
101
+ # def add_encoding(self, name: str, face_encoding: np.ndarray):
102
+ # self.known_face_encodings.append(face_encoding)
103
+ # self.known_face_names.append(name)
104
+ # self.save_encodings()
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+
145
+
146
+
147
+
148
+
149
+
150
+
151
+
152
+
153
+
154
+
155
+
156
+
157
+
158
+
159
+
160
+
161
+
162
+
163
+
164
+
165
+
166
+
167
+
168
+
169
+
170
+
171
+
172
+
173
+
174
+
175
+
176
+
177
+
178
+ # def __init__(self):
179
+ # self.known_face_encodings = []
180
+ # self.known_face_names = []
181
+ # self.path = os.path.join(os.path.dirname(__file__), "encodings.pickle")
182
+ # self.load_encodings()
183
+
184
+ # def load_encodings(self):
185
+ # if os.path.exists(self.path):
186
+ # with open(self.path, "rb") as f:
187
+ # self.known_face_encodings, self.known_face_names = pickle.load(f)
188
+
189
+ # def save_encodings(self):
190
+ # with open(self.path, "wb") as f:
191
+ # pickle.dump([self.known_face_encodings, self.known_face_names], f)
192
+
193
+ # def add_encoding(self, name: str, face_encoding: np.ndarray):
194
+ # self.known_face_encodings.append(face_encoding)
195
+ # self.known_face_names.append(name)
196
+ # self.save_encodings()
197
+
198
+ # def get_face_encodings(self, image: np.ndarray) -> Dict[str, Any]:
199
+ # face_locations = face_recognition.face_locations(image)
200
+ # face_encodings = face_recognition.face_encodings(image, face_locations)
201
+ # face_names = []
202
+ # for face_encoding in face_encodings:
203
+ # matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding, setting.TOLERANCE)
204
+ # name = "Unknown"
205
+ # if True in matches:
206
+ # first_match_index = matches.index(True)
207
+ # name = self.known_face_names[first_match_index]
208
+ # face_names.append(name)
209
+ # return {"face_locations": face_locations, "face_names": face_names}
210
+
211
+ # def get_face_encodings_from_image(self, image_path: str) -> Dict[str, Any]:
212
+ # image = cv2.imread(image_path)
213
+ # rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
214
+ # return self.get_face_encodings(rgb_image)
0
215
▼backend/app/functions/encodings.pickle
+0-0
Binary file not shown.
▼backend/app/functions/face.py
+58-0
1
+import os
2
+import pickle
3
+import cv2
4
+import numpy as np
5
+
6
+
7
+from face_recognition import face_locations, face_encodings, compare_faces, face_distance
8
+class Face:
9
+ def __init__(self,frame):
10
+ self.frame=frame
11
+ self.ids=[]
12
+ def facedefine(self):
13
+ frame=self.frame
14
+ filepath=os.path.join(os.path.dirname(__file__), "encodings.pickle")
15
+ file = open(filepath, 'rb')
16
+ encodeListKnownWithIds = pickle.load(file)
17
+
18
+ encodeListKnown, studentIds = encodeListKnownWithIds
19
+ imgs=cv2.resize(frame,(0,0),None,0.25,0.25)
20
+ imgs=cv2.cvtColor(imgs,cv2.COLOR_BGR2RGB)
21
+ faceCurFrame=face_locations(imgs)
22
+ encodeCurFrame=face_encodings(imgs,faceCurFrame)
23
+ if faceCurFrame:
24
+ for encodeFace,faceLoc in zip(encodeCurFrame,faceCurFrame):
25
+ matches=compare_faces(encodeListKnown,encodeFace)
26
+ faceDis=face_distance(encodeListKnown,encodeFace)
27
+ matchIndex=np.argmin(faceDis)
28
+ if matches[matchIndex]:
29
+ x=matches[matchIndex]
30
+ y1,x2,y2,x1=faceLoc
31
+ y1,x2,y2,x1=y1*4,x2*4,y2*4,x1*4
32
+ bbox=55+x1,162+y1,x2-x1,y2-y1
33
+ cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),2)
34
+ cv2.rectangle(frame,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)
35
+ cv2.putText(frame,studentIds[matchIndex],(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
36
+ self.ids.append(studentIds[matchIndex])
37
+ print(self.ids)
38
+
39
+
40
+ return frame
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
0
59
▼backend/app/functions/facedefine.py
+0-0
0
0
▼backend/app/functions/pictures/222156097.jpg
+0-0
Binary file not shown.
▼backend/app/functions/pictures/222156116.jpg
+0-0
Binary file not shown.
▼backend/app/functions/pictures/222156163.jpg
+0-0
Binary file not shown.
▼backend/app/functions/pictures/222156259.jpeg
+0-0
Binary file not shown.
▼backend/app/functions/pictures/222156288.jpeg
+0-0
Binary file not shown.
▼backend/app/functions/pictures/222156469.png
+0-0
Binary file not shown.
▼backend/app/functions/videoapp.py
+40-14
1
1
import cv2
2
-from app.settings import setting
2
+import numpy as np
3
+from fastapi import APIRouter
4
+from fastapi.responses import StreamingResponse
5
+from app.functions.face import Face
6
+import streamlit as st
7
+# from app.settings import setting
8
+# camip=setting.CAM_IP
9
+camip="192.168.0.100"
3
10
4
-class Camera:
5
- def __init__(self):
6
- self.cam = cv2.VideoCapture(f"http://{setting.CAM_IP}:{setting.CAM_PORT}/video")
11
+
12
+
13
+videorouter = APIRouter()
14
+
15
+
16
+
17
+
18
+def video_feed():
19
+ cap = cv2.VideoCapture("http://"+camip+":8080/video")
20
+ cap.set(3, 640)
21
+ cap.set(4, 480)
22
+
23
+ while True:
24
+ success, img = cap.read()
25
+ x=Face(img)
26
+ frame=x.facedefine()
27
+ if not success:
28
+ break
29
+ ret, buffer = cv2.imencode('.jpg', frame)
7
30
8
- def get_frame(self):
9
- ret, frame = self.cam.read()
10
- if ret:
11
- ret, jpeg = cv2.imencode('.jpg', frame)
12
- return jpeg.tobytes()
13
- else:
14
- return None
15
-
16
- def __del__(self):
17
- self.cam.release()
31
+ frame = buffer.tobytes()
32
+ yield (b'--frame\r\n'
33
+ b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
18
34
35
+
36
+
37
+@videorouter.get("/video_feed")
38
+def stream():
39
+ return StreamingResponse(video_feed(), media_type="multipart/x-mixed-replace; boundary=frame")
40
+def fetch():
41
+ st.write("hello")
42
+ return "hello"
43
+
44
+
19
45
▼backend/app/models/studentmodel.py
+1-2
1
1
from pydantic import BaseModel
2
2
3
-class StudentModel(BaseModel):
3
+class StudentModelshema(BaseModel):
4
4
name: str
5
5
email: str
6
6
status: str
8
8
Semester: str
9
9
Section: str
10
10
Total_Attendance: str
11
- last_seen: str
12
11
id: str
13
12
14
13
▼backend/app/api/routes.py → backend/app/routes/__init__.py
+0-0
0
0
▼backend/app/routes/routesadd.py
+8-0
1
+from fastapi import APIRouter
2
+from app.admin.handelars import db_add
3
+from app.functions.videoapp import videorouter
4
+router = APIRouter()
5
+
6
+router.include_router(db_add, prefix="/admin", tags=["Admin"])
7
+router.include_router(videorouter, prefix="/video", tags=["Video"])
8
+
0
9
▼backend/app/settings/connectdb.py
+80-3
1
1
import firebase_admin
2
+from typing import Dict,Any
2
3
from firebase_admin import credentials
3
-from firebase_admin import db
4
+from firebase_admin import db,storage
5
+import firebase_admin
4
6
import os
7
+# from app.settings import setting
8
+
5
9
6
10
class Firebase:
7
- path=os.path.join(os.path.dirname(__file__), "path/to/your/firebase/credentials.json")
11
+
12
+ firebase_url="https://database-faceapp-default-rtdb.asia-southeast1.firebasedatabase.app/"
13
+ path=os.path.join(os.path.dirname(__file__), "serviceAccountKey.json")
8
14
cred = credentials.Certificate(path)
9
15
firebase_admin.initialize_app(cred,{
10
- 'databaseURL': 'https://database-faceapp-default-rtdb.asia-southeast1.firebasedatabase.app/'
16
+ 'databaseURL': f'{firebase_url}',
17
+ 'storageBucket': "database-faceapp.appspot.com"
11
18
})
12
19
ref=db.reference('students')
20
+ idsref=db.reference('ids')
21
+ bucket=storage.bucket()
22
+
23
+
24
+ def get_data(self)->Dict[str,Any]:
25
+ return self.ref.get()
26
+
27
+
28
+ def set_data(self,data:Dict[str,Any])->Dict[str,Any]:
29
+ for key,value in data.items():
30
+ self.ref.child(key).set(value)
31
+ return {"message":"Data Added Successfully",
32
+ "data":data}
33
+
34
+
35
+
36
+ def update_data(self,key:str,data:Dict[str,Any])->Dict[str,Any]:
37
+ self.ref.child(key).update(data)
38
+ new_data=self.ref.child(key).get()
39
+ return {
40
+ "message":"Data Updated Successfully",
41
+ "data":new_data
42
+ }
43
+
44
+
45
+ def delete_data(self,key:str)->Dict[str,Any]:
46
+ self.ref.child(key).delete()
47
+ return {"message":"Data Deleted Successfully"}
48
+
49
+ def get_data_by_key(self,key:str)->Dict[str,Any]:
50
+ return self.ref.child(key).get()
51
+
52
+ def get_data_by_child(self,child:str)->Dict[str,Any]:
53
+ return self.ref.order_by_child(child).get()
54
+
55
+ def get_data_by_child_value(self,child:str,value:str)->Dict[str,Any]:
56
+ return self.ref.order_by_child(child).equal_to(value).get()
57
+
58
+ def get_data_by_child_range(self,child:str,start:int,end:int)->Dict[str,Any]:
59
+ return self.ref.order_by_child(child).start_at(start).end_at(end).get()
60
+
61
+ def get_data_by_child_limit(self,child:str,limit:int)->Dict[str,Any]:
62
+ return self.ref.order_by_child(child).limit_to_first(limit).get()
13
63
64
+ def get_data_by_present(self)->Dict[str,Any]:
65
+ return self.ref.order_by_child("status").equal_to("Present").get()
66
+
67
+
68
+ def get_picture(self,img:str)->Dict[str,Any]:
69
+ bucket=storage.bucket()
70
+ return bucket.get_blob(f"faceappimage/{img}")
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+# # Example
84
+# ref=db.reference('students')
85
+# data=ref.get()
86
+# print(data)
87
+
88
+# # Example
89
+
90
+# ref=db.reference('students')
14
91
15
92
16
93
17
94
▼backend/app/settings/example .env
+18-0
1
+DATABASEURL=
2
+SECRET_KEY=
3
+HASH_KEY=
4
+ALGROTHIM=
5
+FIREBASE_API_KEY=
6
+FIREBASE_AUTH_DOMAIN=
7
+FIREBASE_DATABASE_URL=
8
+FIREBASE_PROJECT_ID=
9
+FIREBASE_STORAGE_BUCKET=
10
+FIREBASE_MESSAGING_SENDER_ID=
11
+FIREBASE_APP_ID=
12
+FIREBASE_MEASUREMENT_ID=
13
+CAMERA_ID=
14
+CAM_IP=
15
+CAM_PORT=
16
+CAM_USER=
17
+CAM_PASS=
18
+
0
19
▼backend/funnytest.py
+13-0
1
+import os
2
+
3
+
4
+filepath=os.listdir("/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/functions/pictures")
5
+ids=[]
6
+for file in filepath:
7
+
8
+ id=file.split(".")[0]
9
+ ids.append(id)
10
+
11
+
12
+print(ids)
13
+
0
14
▼backend/main.py
+8-3
1
-from app.functions.videoapp import Camera
2
-from fastapi import FastAPI, Response
3
-from app.models.studentmodel import StudentModel
1
+
2
+
3
+from fastapi import FastAPI, APIRouter
4
+from app.routes.routesadd import router
5
+
6
+# from app.models.studentmodel import StudentModel
4
7
from app.settings.connectdb import Firebase
5
8
6
9
app=FastAPI()
7
10
11
+app.include_router(router)
12
+
8
13
9
14
@app.get("/")
10
15
async def home():
11
16
▼cdn.html
+15-2
1
1
2
-<img src="https://demos.pixinvent.com/vuexy-nextjs-admin-template/demo-1/images/illustrations/auth/v2-login-light.png" alt="login" class="img-fluid" width="400" height="300" />
3
-<img src="https://demos.pixinvent.com/vuexy-nextjs-admin-template/demo-1/images/pages/auth-mask-light.png"/>
2
+<!-- <img src="https://demos.pixinvent.com/vuexy-nextjs-admin-template/demo-1/images/illustrations/auth/v2-login-light.png" alt="login" class="img-fluid" width="400" height="300" />
3
+<img src="https://demos.pixinvent.com/vuexy-nextjs-admin-template/demo-1/images/pages/auth-mask-light.png"/> -->
4
+
5
+<html>
6
+ <head>
7
+ <title>CDN</title>
8
+ </head>
9
+ <body>
10
+ <h1>CDN</h1>
11
+ <p>CDN is a content delivery network that helps to load the website faster.</p>
12
+
13
+ <video width="320" height="240">
14
+ <source src="http://127.0.0.1:8000/video_feed"/>
15
+ Your browser does not support the video tag.
16
+ </body>
4
17
▼functionstest.py
+304-0
1
+# import os
2
+# import cv2
3
+# import face_recognition
4
+# from firebase_admin import credentials
5
+# from firebase_admin import db,storage
6
+# import firebase_admin
7
+
8
+
9
+# image_dir=os.listdir("/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/functions/pictures")
10
+
11
+
12
+# from firebase_admin import credentials
13
+# from firebase_admin import db
14
+
15
+
16
+# imagepath="/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/functions/pictures"
17
+
18
+# firbaseurl="https://database-faceapp-default-rtdb.asia-southeast1.firebasedatabase.app/"
19
+# servicekey="/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/settings/serviceAccountKey.json"
20
+
21
+
22
+# cred=credentials.Certificate(servicekey)
23
+
24
+# firebase_admin.initialize_app(cred,{
25
+# 'databaseURL': f'{firbaseurl}',
26
+# 'storageBucket': 'database-faceapp.appspot.com',
27
+# })
28
+# # imagelist=os.listdir(imagepath)
29
+# # print(imagelist)
30
+# # buket=storage.bucket()
31
+
32
+# # for img in imagelist:
33
+# # images=buket.get_blob(f"faceappimage/{img}")
34
+# # print(img)
35
+# # if not images:
36
+# # with open(f"{imagepath}/{img}","rb") as file:
37
+# # buket.blob(f"faceappimage/{img}").upload_from_file(file)
38
+
39
+# # x=buket.list_blobs()
40
+# # print(x)
41
+
42
+# # ref=db.reference('ids')
43
+
44
+# # x=ref.get()
45
+# # print(x)
46
+
47
+# # imageList=os.listdir(imagepath)
48
+
49
+
50
+
51
+# # for img in imageList:
52
+
53
+# # id=img.split(".")[0]
54
+# # if not ref.child(id).get():
55
+# # if img.endswith(".jpg") or img.endswith(".png") or img.endswith(".jpeg"):
56
+# # cv2img=cv2.imread(f"{imagepath}/{img}")
57
+# # img=cv2.cvtColor(cv2img,cv2.COLOR_BGR2RGB)
58
+# # encode=face_recognition.face_encodings(img)[0]
59
+# # ref.child(id).set(encode.tolist())
60
+
61
+
62
+
63
+
64
+
65
+
66
+# # test={
67
+# # "img1":"swadhin",
68
+# # "img2":"swadhin",
69
+# # "img3":"swadhin",
70
+# # "img4":"swadhin",
71
+# # "img5":"swadhin",
72
+# # }
73
+
74
+# # x=test.keys()
75
+# # for i in x:
76
+# # print(i)
77
+
78
+
79
+# # ids=['1','2','3','4','5','6','7','8','9','10']
80
+
81
+# # id=[[1],[23],[4],5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
82
+# # known_face_encodings = [ids,id]
83
+
84
+# # print(known_face_encodings)
85
+
86
+
87
+# imageList=os.listdir(imagepath)
88
+# for img in imageList:
89
+# bucket=storage.bucket()
90
+# if not bucket.get_blob(f"faceappimage/{img}"):
91
+# with open(f"{imagepath}/{img}","rb") as file:
92
+# x=bucket.blob(f"faceappimage/{img}").upload_from_file(file)
93
+# print(x)
94
+
95
+
96
+# import os
97
+# import pickle
98
+# import face_recognition
99
+# import cv2
100
+# import numpy as np
101
+# import cvzone
102
+# from typing import Dict,Any
103
+
104
+
105
+
106
+
107
+# cap=cv2.VideoCapture(0)
108
+
109
+# cap.set(3,640)
110
+# cap.set(4,480)
111
+# cap.set(10,100)
112
+
113
+# while True:
114
+# _,img=cap.read()
115
+# cv2.imshow("FaceApp",img)
116
+# if cv2.waitKey(1) & 0xFF==ord('q'):
117
+# break
118
+# cap.release()
119
+
120
+# cv2.destroyAllWindows()
121
+
122
+
123
+
124
+# import cv2
125
+# import time
126
+# import uvicorn
127
+# from fastapi import FastAPI, Request,WebSocket, WebSocketDisconnect
128
+# from fastapi.templating import Jinja2Templates
129
+# from fastapi.responses import StreamingResponse
130
+
131
+
132
+
133
+
134
+
135
+
136
+# from fastapi import FastAPI, StreamingResponse
137
+
138
+
139
+# app = FastAPI()
140
+
141
+# def generate_frames(cap):
142
+# while True:
143
+# success, frame = cap.read()
144
+# if not success:
145
+# break
146
+# ret, buffer = cv2.imencode('.jpg', frame)
147
+# frame = buffer.tobytes()
148
+# yield (b'--frame\r\n'
149
+# b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
150
+
151
+# @app.get("/video_feed")
152
+# async def video_feed():
153
+# cap = cv2.VideoCapture("https://192.168.0.103:3030/video") # 0 for default webcam
154
+# return StreamingResponse(generate_frames(cap), media_type="multipart/x-mixed-replace;boundary=frame")
155
+
156
+# if __name__ == '__main__':
157
+# uvicorn.run(app, host='127.0.0.1', port=8000)
158
+
159
+
160
+# app=FastAPI()
161
+
162
+# face_cascade=cv2.CascadeClassifier(cv2.data.haarcascades+'haarcascade_frontalface_default.xml')
163
+
164
+# async def get_frame():
165
+# camera=cv2.VideoCapture("https://192.168.0.103:3030/video")
166
+# while True:
167
+# success,frame=camera.read()
168
+# if not success:
169
+# break
170
+# else:
171
+# ret,buffer=cv2.imencode('.jpg',frame)
172
+# frame=buffer.tobytes()
173
+# yield(b'--frame\r\n'
174
+# b'Content-Type: image/jpeg\r\n\r\n'+frame+b'\r\n')
175
+# time.sleep(0.01)
176
+
177
+# @app.get('/')
178
+# async def index():
179
+
180
+# return StreamingResponse(get_frame(),media_type='multipart/x-mixed-replace; boundary=frame')
181
+
182
+
183
+# from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
184
+# from fastapi.responses import HTMLResponse
185
+# from websockets.exceptions import ConnectionClosed
186
+# from fastapi.templating import Jinja2Templates
187
+# import uvicorn
188
+# import asyncio
189
+# import cv2
190
+
191
+
192
+# app = FastAPI()
193
+# camera = cv2.VideoCapture(0,cv2.CAP_DSHOW)
194
+
195
+
196
+
197
+# @app.get('/')
198
+# def index(request: Request):
199
+
200
+# return HTMLResponse("""
201
+# <!DOCTYPE html>
202
+# <html>
203
+# <head>
204
+# <title>Live Streaming</title>
205
+# </head>
206
+# <body>
207
+# <img id="frame" src="">
208
+# <script>
209
+# let ws = new WebSocket("ws://localhost:8000/ws");
210
+# let image = document.getElementById("frame");
211
+# image.onload = function(){
212
+# URL.revokeObjectURL(this.src); // release the blob URL once the image is loaded
213
+# }
214
+# ws.onmessage = function(event) {
215
+# image.src = URL.createObjectURL(event.data);
216
+# };
217
+# </script>
218
+# </body>
219
+# </html>
220
+
221
+# """)
222
+
223
+
224
+# @app.websocket("/ws")
225
+# async def get_stream(websocket: WebSocket):
226
+# await websocket.accept()
227
+# try:
228
+# while True:
229
+# success, frame = camera.read()
230
+# if not success:
231
+# break
232
+# else:
233
+# ret, buffer = cv2.imencode('.jpg', frame)
234
+# await websocket.send_bytes(buffer.tobytes())
235
+# await asyncio.sleep(0.03)
236
+# except (WebSocketDisconnect, ConnectionClosed):
237
+# print("Client disconnected")
238
+
239
+
240
+# if __name__ == '__main__':
241
+# uvicorn.run(app, host='127.0.0.1', port=8000)
242
+
243
+
244
+# img=cv2.cvtColor(cv2img,cv2.COLOR_BGR2RGB)
245
+# encode=face_recognition.face_encodings(img)[0]
246
+# encodeListknown=[encode,'222156259']
247
+# success, frame = cap.read()
248
+# imagesmall=cv2.resize(frame,(0,0),None,0.25,0.25)
249
+# imagesmall=cv2.cvtColor(imagesmall,cv2.COLOR_BGR2RGB)
250
+# facesCurFrame=face_recognition.face_locations(imagesmall)
251
+# encodecurrentframe=face_recognition.face_encodings(imagesmall,facesCurFrame)
252
+# if facesCurFrame:
253
+# for encodeface,faceloc in zip(encodecurrentframe,facesCurFrame):
254
+# matches=face_recognition.compare_faces(encodeListknown,encodeface)
255
+# facedis=face_recognition.face_distance(encodeListknown,encodeface)
256
+# matchindex=np.argmin(facedis)
257
+# if matches[matchindex]:
258
+# name="Swadhin"
259
+# y1,x2,y2,x1=faceloc
260
+# y1,x2,y2,x1=y1*4,x2*4,y2*4,x1*4
261
+# cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),2)
262
+# cv2.rectangle(frame,(x1,y2-35),(x2,y2),(0,255,0),cv2.FILLED)
263
+# cv2.putText(frame,name,(x1+6,y2-6),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
264
+
265
+
266
+import cv2
267
+import numpy as np
268
+from face_recognition import face_encodings, face_locations, compare_faces, face_distance
269
+
270
+
271
+path="/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/functions/pictures/222156259.jpeg"
272
+img=cv2.resize(cv2.imread(path),(0,0),None,0.25,0.25)
273
+encodex=face_encodings(img)[0]
274
+
275
+frame="/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/functions/pictures/222156259.jpeg"
276
+
277
+def detect_and_recognize_face(frame,encode):
278
+ # Convert frame to RGB for face recognition
279
+ frame=cv2.imread(frame)
280
+ cut_frame=cv2.resize(frame,(0,0),None,0.25,0.25)
281
+ rgb_frame = cv2.cvtColor(cut_frame, cv2.COLOR_BGR2RGB)
282
+ frameencode=face_encodings(rgb_frame)
283
+
284
+
285
+
286
+
287
+ # Find all faces and their encodings
288
+ face_locations_list = face_locations(rgb_frame)
289
+ currentfaceencode = face_encodings(frameencode, face_locations_list)
290
+
291
+ if face_locations_list:
292
+
293
+ # Loop through each detected face
294
+ for face_encoding, face_location in zip(currentfaceencode, face_locations_list):
295
+ # Compare face encoding with encodings in database/pickle file
296
+ matches = compare_faces(encode, face_encoding)
297
+ facedistance=face_distance(encode,face_encoding)
298
+
299
+ matchindex=np.argmin(facedistance)
300
+ print(matchindex)
301
+
302
+
303
+
304
+detect_and_recognize_face(frame,encodex)
0
305
▼requirements.txt
+2-0
1
+cmake <=3.27.4
2
+
0
3
▼test2.py
+121-0
1
+
2
+import cv2
3
+import streamlit as st
4
+from fastapi import FastAPI
5
+import face_recognition
6
+import numpy as np
7
+import time
8
+import os
9
+from fastapi.responses import StreamingResponse
10
+app = FastAPI()
11
+from face_recognition import face_locations, face_encodings
12
+from firebase_admin import db ,credentials
13
+
14
+import firebase_admin
15
+
16
+
17
+imagepath="/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/functions/pictures"
18
+piclepath="/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/functions/encodings.pickle"
19
+
20
+firbaseurl="https://database-faceapp-default-rtdb.asia-southeast1.firebasedatabase.app/"
21
+servicekey="/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/settings/serviceAccountKey.json"
22
+
23
+
24
+cred=credentials.Certificate(servicekey)
25
+
26
+firebase_admin.initialize_app(cred,{
27
+ 'databaseURL': f'{firbaseurl}',
28
+ 'storageBucket': 'database-faceapp.appspot.com',
29
+})
30
+
31
+path="/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/functions/pictures/222156259.jpeg"
32
+img=cv2.imread(path)
33
+encodex=face_encodings(img)[0]
34
+print(encodex)
35
+
36
+@st.cache_resource
37
+def get_cap():
38
+ return 0
39
+
40
+def detect_and_recognize_face(frame,encode):
41
+ # Convert frame to RGB for face recognition
42
+
43
+ cut_frame=cv2.resize(frame,(0,0),None,0.25,0.25)
44
+ rgb_frame = cv2.cvtColor(cut_frame, cv2.COLOR_BGR2RGB)
45
+ frameencode=face_encodings(rgb_frame)
46
+
47
+
48
+
49
+
50
+ # Find all faces and their encodings
51
+ face_locations_list = face_locations(rgb_frame)
52
+ currentfaceencode = face_encodings(frameencode, face_locations_list)
53
+
54
+ if face_locations_list:
55
+
56
+ # Loop through each detected face
57
+ for face_encoding, face_location in zip(currentfaceencode, face_locations_list):
58
+ # Compare face encoding with encodings in database/pickle file
59
+ matches = face_recognition.compare_faces(encode, face_encoding)
60
+ facedistance=face_recognition.face_distance(encode,face_encoding)
61
+ print(facedistance)
62
+ name = "Unknown"
63
+ matchindex=np.argmin(facedistance)
64
+ print(matchindex)
65
+
66
+ # Draw rectangle and name around the face
67
+ top, right, bottom, left = face_location
68
+ cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
69
+ cv2.putText(frame, name, (left + 6, top - 6), cv2.FONT_HERSHEY_DUPLEX, 0.8, (255, 255, 255), 1)
70
+
71
+ return frame
72
+
73
+def generate_frames():
74
+ cap=cv2.VideoCapture("https://192.168.0.100:8080/video")
75
+ cap.set(3,640)
76
+ cap.set(4,480)
77
+ while True:
78
+
79
+ success, frame = cap.read() # read the camera frame
80
+
81
+ frame=detect_and_recognize_face(frame,encode=encodex)
82
+
83
+ if not success:
84
+ break
85
+ ret, buffer = cv2.imencode('.jpg', frame)
86
+ frame = buffer.tobytes()
87
+ yield (b'--frame\r\n'
88
+ b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
89
+
90
+ # save_image=cv2.imwrite(os.path.join(/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/functions/screens)"test.jpg",x)
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+# def video_feed():
102
+# cap = get_cap() # 0 for default webcam
103
+# return StreamingResponse(generate_frames(cap), media_type="multipart/x-mixed-replace; boundary=frame")
104
+
105
+@app.get("/")
106
+async def home():
107
+ return {"message":"Welcome to the Live Attendance System"}
108
+
109
+
110
+@app.get("/video_feed")
111
+async def video_feed():
112
+ return StreamingResponse(generate_frames(), media_type="multipart/x-mixed-replace;boundary=frame")
113
+
114
+def main():
115
+ app.run()
116
+
117
+if __name__ == '__main__':
118
+ import uvicorn
119
+
120
+ uvicorn.run(app, host="localhost", port=8000)
121
+
0
122
▼test3.py
+67-0
1
+import cv2
2
+import time
3
+import numpy as np
4
+
5
+import pickle
6
+from face_recognition import face_locations, face_encodings, compare_faces, face_distance
7
+
8
+folderpath="/home/swadhin/GitHubproject/liveattendence_with_anti_cheat/backend/app/functions/pictures/222156259.jpeg"
9
+
10
+pic=cv2.imread(folderpath)
11
+pic=cv2.resize(pic,(0,0),None,0.25,0.25)
12
+encode=face_encodings(pic)[0]
13
+studentIds = ['222156259']
14
+encodelist=[]
15
+encodelist.append(encode)
16
+incodelistnown=[encodelist,studentIds]
17
+file=open('EncodeFile.p','wb')
18
+pickle.dump(incodelistnown,file)
19
+file.close()
20
+
21
+
22
+cap = cv2.VideoCapture("https://192.168.0.100:8080/video")
23
+cap.set(3, 640)
24
+cap.set(4, 480)
25
+
26
+file = open('EncodeFile.p', 'rb')
27
+encodeListKnownWithIds = pickle.load(file)
28
+
29
+encodeListKnown, studentIds = encodeListKnownWithIds
30
+
31
+
32
+while True:
33
+ success, img = cap.read()
34
+ imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)
35
+ imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
36
+ faceCurFrame = face_locations(imgS)
37
+ encodeCurFrame =face_encodings(imgS, faceCurFrame)
38
+ if faceCurFrame:
39
+ for encodeFace, faceLoc in zip(encodeCurFrame, faceCurFrame):
40
+ matches = compare_faces(encodeListKnown, encodeFace)
41
+ faceDis = face_distance(encodeListKnown, encodeFace)
42
+ matchIndex = np.argmin(faceDis)
43
+ if matches[matchIndex]:
44
+ y1, x2, y2, x1 = faceLoc
45
+ y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
46
+ bbox = 55 + x1, 162 + y1, x2 - x1, y2 - y1
47
+ cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
48
+ cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
49
+ cv2.putText(img, studentIds[matchIndex], (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
50
+ cv2.imshow('Webcam', img)
51
+ if cv2.waitKey(1) & 0xFF == ord('q'):
52
+ break
53
+cap.release()
54
+
55
+cv2.destroyAllWindows()
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
0
68