LovnishVerma commited on
Commit
76ea4a3
·
verified ·
1 Parent(s): 56a50b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -90
app.py CHANGED
@@ -1,98 +1,124 @@
1
  import os
2
- import cv2
 
3
  import streamlit as st
4
  from datetime import datetime
 
5
 
6
- # Constants
7
  KNOWN_FACES_DIR = "known_faces"
8
  os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
9
 
10
- # Global State
11
- if "activity_log" not in st.session_state:
12
- st.session_state.activity_log = []
13
-
14
- # Streamlit App Title
15
- st.title("Face Detection and Registration App")
16
-
17
- st.sidebar.header("Navigation")
18
- page = st.sidebar.radio("Choose an option:", ["Real-time Face Detection", "Register New Face", "View Registered Faces", "Recent Activity"])
19
-
20
- # Initialize Cascade Classifier
21
- face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
22
-
23
- # Helper Function for Real-time Face Detection
24
- def start_camera(register_mode=False, face_name=None):
25
- cap = cv2.VideoCapture(0) # Open the camera
26
-
27
- if not cap.isOpened():
28
- st.error("Unable to access the camera. Please check your webcam or permissions.")
29
- return
30
-
31
- stframe = st.empty() # Streamlit placeholder for video frames
32
-
33
- while cap.isOpened():
34
- ret, frame = cap.read()
35
- if not ret:
36
- st.error("Failed to grab frame from camera.")
37
- break
38
-
39
- gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
40
- faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(50, 50))
41
-
42
- for (x, y, w, h) in faces:
43
- # Draw rectangle
44
- cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
45
-
46
- if register_mode and face_name:
47
- # Save the cropped face image
48
- face_img = frame[y:y + h, x:x + w]
49
- face_filename = f"{face_name}_{datetime.now().strftime('%Y%m%d%H%M%S')}.jpg"
50
- face_path = os.path.join(KNOWN_FACES_DIR, face_filename)
51
- cv2.imwrite(face_path, face_img)
52
-
53
- st.session_state.activity_log.append(
54
- f"Registered face: {face_name} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
55
- )
56
- st.success(f"Face registered successfully as {face_name}!")
57
- return # Stop after registering
58
-
59
- stframe.image(frame, channels="BGR", use_column_width=True)
60
-
61
- cap.release()
62
- cv2.destroyAllWindows()
63
-
64
- # Pages
65
- if page == "Real-time Face Detection":
66
- st.header("Real-time Face Detection")
67
- if st.button("Start Camera"):
68
- start_camera()
69
-
70
- elif page == "Register New Face":
71
- st.header("Register New Face")
72
- name = st.text_input("Enter a name for the face:")
73
-
74
- if st.button("Start Registration"):
75
- if name.strip():
76
- st.info(f"Looking for face to register as '{name}'...")
77
- start_camera(register_mode=True, face_name=name)
78
- else:
79
- st.error("Please enter a valid name!")
80
-
81
- elif page == "View Registered Faces":
82
- st.header("Registered Faces")
83
- faces = os.listdir(KNOWN_FACES_DIR)
84
-
85
- if faces:
86
- st.write(f"*Total Registered Faces: {len(faces)}*")
87
- for face_file in faces:
88
- st.write(face_file)
 
 
 
 
 
 
 
 
89
  else:
90
- st.write("No registered faces found.")
91
-
92
- elif page == "Recent Activity":
93
- st.header("Recent Activity Log")
94
- if st.session_state.activity_log:
95
- for log in reversed(st.session_state.activity_log):
96
- st.write(log)
97
- else:
98
- st.write("No recent activity to display.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import sqlite3
3
+ from huggingface_hub import HfApi
4
  import streamlit as st
5
  from datetime import datetime
6
+ from PIL import Image
7
 
8
+ # Directories and Hugging Face Token
9
  KNOWN_FACES_DIR = "known_faces"
10
  os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
11
 
12
+ # Retrieve the token from the environment
13
+ hf_token = os.getenv("token") # Ensure the key matches the name in Hugging Face secrets
14
+ if not hf_token:
15
+ raise ValueError("Hugging Face token not found. Ensure it's set as a secret in the Hugging Face Space.")
16
+
17
+ # Initialize the Hugging Face API
18
+ api = HfApi()
19
+ api.set_access_token(hf_token)
20
+
21
+ # Database setup
22
+ DATABASE = "students.db"
23
+
24
+ def initialize_database():
25
+ conn = sqlite3.connect(DATABASE)
26
+ cursor = conn.cursor()
27
+ cursor.execute("""
28
+ CREATE TABLE IF NOT EXISTS students (
29
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
30
+ name TEXT NOT NULL,
31
+ roll_no TEXT NOT NULL UNIQUE,
32
+ image_path TEXT NOT NULL,
33
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
34
+ )
35
+ """)
36
+ conn.commit()
37
+ conn.close()
38
+
39
+ def save_to_database(name, roll_no, image_path):
40
+ conn = sqlite3.connect(DATABASE)
41
+ cursor = conn.cursor()
42
+ try:
43
+ cursor.execute("""
44
+ INSERT INTO students (name, roll_no, image_path)
45
+ VALUES (?, ?, ?)
46
+ """, (name, roll_no, image_path))
47
+ conn.commit()
48
+ st.success("Data saved successfully!")
49
+ except sqlite3.IntegrityError:
50
+ st.error("Roll number already exists!")
51
+ finally:
52
+ conn.close()
53
+
54
+ def save_image_to_hugging_face(image, roll_no):
55
+ filename = f"{roll_no}_{datetime.now().strftime('%Y%m%d%H%M%S')}.jpg"
56
+ local_path = os.path.join(KNOWN_FACES_DIR, filename)
57
+ image.save(local_path)
58
+
59
+ # Upload to Hugging Face
60
+ try:
61
+ repo_name = "LovnishVerma/face_and_emotion_detection" # Replace with your repo details
62
+ api.upload_file(
63
+ path_or_fileobj=local_path,
64
+ path_in_repo=filename,
65
+ repo_id=repo_name,
66
+ repo_type="dataset"
67
+ )
68
+ st.success(f"Image uploaded to Hugging Face: {filename}")
69
+ except Exception as e:
70
+ st.error(f"Error uploading image to Hugging Face: {e}")
71
+
72
+ return local_path
73
+
74
+ # Initialize database
75
+ initialize_database()
76
+
77
+ # Streamlit app
78
+ st.title("Student Registration with Hugging Face Image Upload")
79
+
80
+ # Input details
81
+ name = st.text_input("Enter your name")
82
+ roll_no = st.text_input("Enter your roll number")
83
+
84
+ # Choose image input method
85
+ capture_mode = st.radio("Choose an option to upload your image", ["Use Webcam", "Upload File"])
86
+
87
+ if capture_mode == "Use Webcam":
88
+ picture = st.camera_input("Take a picture")
89
+
90
+ elif capture_mode == "Upload File":
91
+ picture = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
92
+
93
+ # Save and process data
94
+ if st.button("Register"):
95
+ if not name or not roll_no:
96
+ st.error("Please fill in both name and roll number.")
97
+ elif not picture:
98
+ st.error("Please upload or capture an image.")
99
  else:
100
+ try:
101
+ if capture_mode == "Use Webcam":
102
+ image = Image.open(picture)
103
+ else:
104
+ image = Image.open(picture)
105
+
106
+ # Save locally and upload to Hugging Face
107
+ image_path = save_image_to_hugging_face(image, roll_no)
108
+ save_to_database(name, roll_no, image_path)
109
+ except Exception as e:
110
+ st.error(f"An error occurred: {e}")
111
+
112
+ # Display stored data
113
+ if st.checkbox("Show registered students"):
114
+ conn = sqlite3.connect(DATABASE)
115
+ cursor = conn.cursor()
116
+ cursor.execute("SELECT name, roll_no, image_path, timestamp FROM students")
117
+ rows = cursor.fetchall()
118
+ conn.close()
119
+
120
+ st.write("### Registered Students")
121
+ for row in rows:
122
+ name, roll_no, image_path, timestamp = row
123
+ st.write(f"**Name:** {name}, **Roll No:** {roll_no}, **Timestamp:** {timestamp}")
124
+ st.image(image_path, caption=f"{name} ({roll_no})", use_column_width=True)