Update app.py
Browse files
app.py
CHANGED
@@ -5,35 +5,39 @@ import streamlit as st
|
|
5 |
from datetime import datetime
|
6 |
from PIL import Image
|
7 |
|
8 |
-
#
|
9 |
-
KNOWN_FACES_DIR = "known_faces"
|
|
|
|
|
|
|
10 |
os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
|
11 |
|
12 |
-
# Retrieve the Hugging Face token from
|
13 |
-
hf_token = os.getenv("upload") #
|
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
|
18 |
api = HfApi()
|
19 |
|
20 |
-
# Repository Details
|
21 |
-
REPO_NAME = "face_and_emotion_detection" # Replace with your
|
22 |
-
REPO_ID = "LovnishVerma/" + REPO_NAME #
|
23 |
-
REPO_TYPE = "space" #
|
24 |
|
25 |
-
# Ensure repository exists
|
26 |
try:
|
27 |
-
# Specify space_sdk as 'streamlit' for a Streamlit-based Hugging Face Space
|
28 |
api.create_repo(repo_id=REPO_ID, repo_type=REPO_TYPE, space_sdk="streamlit", token=hf_token, exist_ok=True)
|
29 |
st.success(f"Repository '{REPO_NAME}' is ready on Hugging Face!")
|
30 |
except Exception as e:
|
31 |
st.error(f"Error creating repository: {e}")
|
32 |
|
33 |
# Database setup
|
34 |
-
DATABASE = "students.db"
|
35 |
-
|
36 |
def initialize_database():
|
|
|
|
|
|
|
|
|
37 |
conn = sqlite3.connect(DATABASE)
|
38 |
cursor = conn.cursor()
|
39 |
cursor.execute("""
|
@@ -49,6 +53,15 @@ def initialize_database():
|
|
49 |
conn.close()
|
50 |
|
51 |
def save_to_database(name, roll_no, image_path):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
conn = sqlite3.connect(DATABASE)
|
53 |
cursor = conn.cursor()
|
54 |
try:
|
@@ -63,19 +76,34 @@ def save_to_database(name, roll_no, image_path):
|
|
63 |
finally:
|
64 |
conn.close()
|
65 |
|
66 |
-
def save_image_to_hugging_face(image, roll_no):
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
local_path = os.path.join(KNOWN_FACES_DIR, filename)
|
|
|
|
|
69 |
image.save(local_path)
|
70 |
|
71 |
-
#
|
72 |
try:
|
73 |
api.upload_file(
|
74 |
path_or_fileobj=local_path,
|
75 |
path_in_repo=filename,
|
76 |
repo_id=REPO_ID,
|
77 |
repo_type=REPO_TYPE,
|
78 |
-
token=hf_token # Pass the token directly
|
79 |
)
|
80 |
st.success(f"Image uploaded to Hugging Face: {filename}")
|
81 |
except Exception as e:
|
@@ -83,30 +111,31 @@ def save_image_to_hugging_face(image, roll_no):
|
|
83 |
|
84 |
return local_path
|
85 |
|
86 |
-
# Initialize database
|
87 |
initialize_database()
|
88 |
|
89 |
-
# Streamlit
|
90 |
st.title("Student Registration with Hugging Face Image Upload")
|
91 |
|
92 |
-
# Input details
|
93 |
name = st.text_input("Enter your name")
|
94 |
roll_no = st.text_input("Enter your roll number")
|
95 |
|
96 |
-
# Choose image
|
97 |
capture_mode = st.radio("Choose an option to upload your image", ["Use Webcam", "Upload File"])
|
98 |
|
|
|
99 |
if capture_mode == "Use Webcam":
|
100 |
try:
|
101 |
-
picture = st.camera_input("Take a picture")
|
102 |
except Exception as e:
|
103 |
st.error(f"Error accessing webcam: {e}")
|
104 |
picture = None
|
105 |
|
106 |
elif capture_mode == "Upload File":
|
107 |
-
picture = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
|
108 |
|
109 |
-
# Save and process
|
110 |
if st.button("Register"):
|
111 |
if not name or not roll_no:
|
112 |
st.error("Please fill in both name and roll number.")
|
@@ -114,18 +143,19 @@ if st.button("Register"):
|
|
114 |
st.error("Please upload or capture an image.")
|
115 |
else:
|
116 |
try:
|
|
|
117 |
if capture_mode == "Use Webcam" and picture:
|
118 |
image = Image.open(picture)
|
119 |
elif capture_mode == "Upload File" and picture:
|
120 |
image = Image.open(picture)
|
121 |
|
122 |
-
# Save locally and upload to Hugging Face
|
123 |
-
image_path = save_image_to_hugging_face(image, roll_no)
|
124 |
save_to_database(name, roll_no, image_path)
|
125 |
except Exception as e:
|
126 |
st.error(f"An error occurred: {e}")
|
127 |
|
128 |
-
# Display
|
129 |
if st.checkbox("Show registered students"):
|
130 |
conn = sqlite3.connect(DATABASE)
|
131 |
cursor = conn.cursor()
|
@@ -138,4 +168,3 @@ if st.checkbox("Show registered students"):
|
|
138 |
name, roll_no, image_path, timestamp = row
|
139 |
st.write(f"**Name:** {name}, **Roll No:** {roll_no}, **Timestamp:** {timestamp}")
|
140 |
st.image(image_path, caption=f"{name} ({roll_no})", use_column_width=True)
|
141 |
-
|
|
|
5 |
from datetime import datetime
|
6 |
from PIL import Image
|
7 |
|
8 |
+
# Constants
|
9 |
+
KNOWN_FACES_DIR = "known_faces" # Directory to save user images
|
10 |
+
DATABASE = "students.db" # SQLite database file to store student information
|
11 |
+
|
12 |
+
# Ensure the directory exists
|
13 |
os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
|
14 |
|
15 |
+
# Retrieve the Hugging Face token from environment variable
|
16 |
+
hf_token = os.getenv("upload") # The key must match the secret name set in Hugging Face
|
17 |
if not hf_token:
|
18 |
raise ValueError("Hugging Face token not found. Ensure it's set as a secret in the Hugging Face Space.")
|
19 |
|
20 |
+
# Initialize Hugging Face API
|
21 |
api = HfApi()
|
22 |
|
23 |
+
# Repository Details on Hugging Face
|
24 |
+
REPO_NAME = "face_and_emotion_detection" # Replace with your Hugging Face repository name
|
25 |
+
REPO_ID = "LovnishVerma/" + REPO_NAME # Replace "LovnishVerma" with your Hugging Face username
|
26 |
+
REPO_TYPE = "space" # 'space' type for Streamlit-based projects
|
27 |
|
28 |
+
# Ensure the repository exists or create it
|
29 |
try:
|
|
|
30 |
api.create_repo(repo_id=REPO_ID, repo_type=REPO_TYPE, space_sdk="streamlit", token=hf_token, exist_ok=True)
|
31 |
st.success(f"Repository '{REPO_NAME}' is ready on Hugging Face!")
|
32 |
except Exception as e:
|
33 |
st.error(f"Error creating repository: {e}")
|
34 |
|
35 |
# Database setup
|
|
|
|
|
36 |
def initialize_database():
|
37 |
+
"""
|
38 |
+
Initializes the SQLite database by creating a table to store student data
|
39 |
+
such as name, roll number, image path, and registration timestamp.
|
40 |
+
"""
|
41 |
conn = sqlite3.connect(DATABASE)
|
42 |
cursor = conn.cursor()
|
43 |
cursor.execute("""
|
|
|
53 |
conn.close()
|
54 |
|
55 |
def save_to_database(name, roll_no, image_path):
|
56 |
+
"""
|
57 |
+
Saves the student's information (name, roll number, image path) to the SQLite database.
|
58 |
+
Ensures roll number is unique.
|
59 |
+
|
60 |
+
Args:
|
61 |
+
name (str): The name of the student.
|
62 |
+
roll_no (str): The roll number of the student.
|
63 |
+
image_path (str): Path to the stored image of the student.
|
64 |
+
"""
|
65 |
conn = sqlite3.connect(DATABASE)
|
66 |
cursor = conn.cursor()
|
67 |
try:
|
|
|
76 |
finally:
|
77 |
conn.close()
|
78 |
|
79 |
+
def save_image_to_hugging_face(image, name, roll_no):
|
80 |
+
"""
|
81 |
+
Saves the captured image locally in the 'known_faces' directory and uploads it to Hugging Face.
|
82 |
+
The image is renamed using the format 'UserName_RollNo.jpg'.
|
83 |
+
|
84 |
+
Args:
|
85 |
+
image (PIL Image): The image object captured by the user.
|
86 |
+
name (str): The name of the student.
|
87 |
+
roll_no (str): The roll number of the student.
|
88 |
+
|
89 |
+
Returns:
|
90 |
+
str: The local path where the image is saved.
|
91 |
+
"""
|
92 |
+
# Rename the image using the format 'UserName_RollNo.jpg'
|
93 |
+
filename = f"{name}_{roll_no}.jpg"
|
94 |
local_path = os.path.join(KNOWN_FACES_DIR, filename)
|
95 |
+
|
96 |
+
# Save the image locally to the known_faces directory
|
97 |
image.save(local_path)
|
98 |
|
99 |
+
# Try uploading the image to Hugging Face
|
100 |
try:
|
101 |
api.upload_file(
|
102 |
path_or_fileobj=local_path,
|
103 |
path_in_repo=filename,
|
104 |
repo_id=REPO_ID,
|
105 |
repo_type=REPO_TYPE,
|
106 |
+
token=hf_token # Pass the Hugging Face token directly
|
107 |
)
|
108 |
st.success(f"Image uploaded to Hugging Face: {filename}")
|
109 |
except Exception as e:
|
|
|
111 |
|
112 |
return local_path
|
113 |
|
114 |
+
# Initialize the database when the app starts
|
115 |
initialize_database()
|
116 |
|
117 |
+
# Streamlit user interface (UI)
|
118 |
st.title("Student Registration with Hugging Face Image Upload")
|
119 |
|
120 |
+
# Input fields for student details
|
121 |
name = st.text_input("Enter your name")
|
122 |
roll_no = st.text_input("Enter your roll number")
|
123 |
|
124 |
+
# Choose input method for the image (webcam or file upload)
|
125 |
capture_mode = st.radio("Choose an option to upload your image", ["Use Webcam", "Upload File"])
|
126 |
|
127 |
+
# Handle webcam capture or file upload
|
128 |
if capture_mode == "Use Webcam":
|
129 |
try:
|
130 |
+
picture = st.camera_input("Take a picture") # Capture image using webcam
|
131 |
except Exception as e:
|
132 |
st.error(f"Error accessing webcam: {e}")
|
133 |
picture = None
|
134 |
|
135 |
elif capture_mode == "Upload File":
|
136 |
+
picture = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"]) # Upload image from file system
|
137 |
|
138 |
+
# Save data and process image on button click
|
139 |
if st.button("Register"):
|
140 |
if not name or not roll_no:
|
141 |
st.error("Please fill in both name and roll number.")
|
|
|
143 |
st.error("Please upload or capture an image.")
|
144 |
else:
|
145 |
try:
|
146 |
+
# Open the image based on capture mode
|
147 |
if capture_mode == "Use Webcam" and picture:
|
148 |
image = Image.open(picture)
|
149 |
elif capture_mode == "Upload File" and picture:
|
150 |
image = Image.open(picture)
|
151 |
|
152 |
+
# Save the image locally and upload it to Hugging Face
|
153 |
+
image_path = save_image_to_hugging_face(image, name, roll_no)
|
154 |
save_to_database(name, roll_no, image_path)
|
155 |
except Exception as e:
|
156 |
st.error(f"An error occurred: {e}")
|
157 |
|
158 |
+
# Display registered student data
|
159 |
if st.checkbox("Show registered students"):
|
160 |
conn = sqlite3.connect(DATABASE)
|
161 |
cursor = conn.cursor()
|
|
|
168 |
name, roll_no, image_path, timestamp = row
|
169 |
st.write(f"**Name:** {name}, **Roll No:** {roll_no}, **Timestamp:** {timestamp}")
|
170 |
st.image(image_path, caption=f"{name} ({roll_no})", use_column_width=True)
|
|