File size: 5,409 Bytes
56a50b1 a4d9380 94a1319 c5f6154 94a1319 56a50b1 4b17a12 94a1319 4b17a12 94a1319 56a50b1 94a1319 76ea4a3 94a1319 76ea4a3 94a1319 76ea4a3 94a1319 76ea4a3 94a1319 76ea4a3 94a1319 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 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 |
import streamlit as st
import cv2
import os
import numpy as np
from keras.models import load_model
from PIL import Image
import sqlite3
import requests
from io import BytesIO
# Constants
DB_FILE = "students.db"
KNOWN_FACES_DIR = "known_faces"
EMOTION_MODEL_FILE = "CNN_Model_acc_75.h5"
HUGGING_FACE_TOKEN = os.getenv("HUGGING_FACE_TOKEN")
HUGGING_FACE_REPO = "username/repo_name"
# Create directories
os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
# Load models
try:
emotion_model = load_model(EMOTION_MODEL_FILE)
except Exception as e:
st.error(f"Error loading emotion model: {e}")
# Database Functions
def create_table():
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
roll_number TEXT NOT NULL UNIQUE,
image_path TEXT NOT NULL
)
""")
conn.commit()
def insert_student(name, roll_number, image_path):
try:
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute("INSERT INTO students (name, roll_number, image_path) VALUES (?, ?, ?)",
(name, roll_number, image_path))
conn.commit()
except sqlite3.IntegrityError:
st.warning("Roll number already exists!")
# Hugging Face Functions
def upload_to_hugging_face(file_path, file_name):
if not HUGGING_FACE_TOKEN:
st.error("Hugging Face token not found.")
return
url = f"https://huggingface.co/api/repos/{HUGGING_FACE_REPO}/uploads/{file_name}"
headers = {"Authorization": f"Bearer {HUGGING_FACE_TOKEN}"}
try:
with open(file_path, "rb") as file:
response = requests.post(url, headers=headers, files={"file": file})
if response.status_code == 200:
st.success(f"Uploaded {file_name} to Hugging Face!")
else:
st.error(f"Failed to upload: {response.content}")
except Exception as e:
st.error(f"Error uploading file: {e}")
# Image Processing Functions
def detect_faces_and_emotions(image):
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.3, minNeighbors=5)
for (x, y, w, h) in faces:
face = gray_image[y:y+h, x:x+w]
resized_face = cv2.resize(face, (48, 48))
normalized_face = resized_face / 255.0
reshaped_face = np.reshape(normalized_face, (1, 48, 48, 1))
emotion_prediction = emotion_model.predict(reshaped_face)
emotion_label = np.argmax(emotion_prediction)
return emotion_label
return None
# UI Design
st.title("Student Registration and Emotion Detection")
create_table()
menu = ["Register Student", "Face Recognition and Emotion Detection"]
choice = st.sidebar.selectbox("Menu", menu)
if choice == "Register Student":
st.subheader("Register a New Student")
with st.form("register_form"):
name = st.text_input("Name")
roll_number = st.text_input("Roll Number")
image_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
submitted = st.form_submit_button("Register")
if submitted:
if name and roll_number and image_file:
try:
img = Image.open(image_file)
img_path = os.path.join(KNOWN_FACES_DIR, f"{roll_number}.png")
img.save(img_path)
insert_student(name, roll_number, img_path)
upload_to_hugging_face(img_path, f"{roll_number}.png")
st.success("Student Registered Successfully!")
except Exception as e:
st.error(f"Error: {e}")
else:
st.warning("Please fill in all fields and upload an image.")
elif choice == "Face Recognition and Emotion Detection":
st.subheader("Recognize Faces and Detect Emotions")
action = st.radio("Choose Action", ["Upload Image", "Use Webcam"])
if action == "Upload Image":
uploaded_file = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
if uploaded_file:
try:
img = Image.open(uploaded_file)
img_array = np.array(img)
emotion_label = detect_faces_and_emotions(img_array)
if emotion_label is not None:
st.success(f"Emotion Detected: {emotion_label}")
else:
st.warning("No face detected.")
except Exception as e:
st.error(f"Error: {e}")
elif action == "Use Webcam":
cap = cv2.VideoCapture(0)
if st.button("Start Webcam"):
while True:
ret, frame = cap.read()
if not ret:
break
emotion_label = detect_faces_and_emotions(frame)
if emotion_label is not None:
st.success(f"Emotion Detected: {emotion_label}")
cv2.imshow("Webcam", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
|