LovnishVerma commited on
Commit
62baa62
·
verified ·
1 Parent(s): ae4e42c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -37
app.py CHANGED
@@ -5,23 +5,35 @@ import numpy as np
5
  from keras.models import load_model
6
  from PIL import Image
7
  import sqlite3
8
- import requests
9
- from io import BytesIO
10
 
11
  # Constants
12
  DB_FILE = "students.db"
13
  KNOWN_FACES_DIR = "known_faces"
14
  EMOTION_MODEL_FILE = "CNN_Model_acc_75.h5"
15
- HUGGING_FACE_TOKEN = os.getenv("HUGGING_FACE_TOKEN")
16
- HUGGING_FACE_REPO = "username/repo_name"
17
-
18
- # Emotion Labels
19
  EMOTION_LABELS = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
20
 
21
- # Create directories
 
 
 
 
22
  os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
23
 
24
- # Load models
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  try:
26
  emotion_model = load_model(EMOTION_MODEL_FILE)
27
  except Exception as e:
@@ -30,8 +42,7 @@ except Exception as e:
30
  # Database Functions
31
  def create_table():
32
  with sqlite3.connect(DB_FILE) as conn:
33
- cursor = conn.cursor()
34
- cursor.execute("""
35
  CREATE TABLE IF NOT EXISTS students (
36
  id INTEGER PRIMARY KEY AUTOINCREMENT,
37
  name TEXT NOT NULL,
@@ -44,33 +55,13 @@ def create_table():
44
  def insert_student(name, roll_number, image_path):
45
  try:
46
  with sqlite3.connect(DB_FILE) as conn:
47
- cursor = conn.cursor()
48
- cursor.execute("INSERT INTO students (name, roll_number, image_path) VALUES (?, ?, ?)",
49
- (name, roll_number, image_path))
50
  conn.commit()
51
  except sqlite3.IntegrityError:
52
  st.warning("Roll number already exists!")
53
 
54
- # Hugging Face Functions
55
- def upload_to_hugging_face(file_path, file_name):
56
- if not HUGGING_FACE_TOKEN:
57
- st.error("Hugging Face token not found.")
58
- return
59
-
60
- url = f"https://huggingface.co/api/repos/{HUGGING_FACE_REPO}/uploads/{file_name}"
61
- headers = {"Authorization": f"Bearer {HUGGING_FACE_TOKEN}"}
62
-
63
- try:
64
- with open(file_path, "rb") as file:
65
- response = requests.post(url, headers=headers, files={"file": file})
66
- if response.status_code == 200:
67
- st.success(f"Uploaded {file_name} to Hugging Face!")
68
- else:
69
- st.error(f"Failed to upload: {response.content}")
70
- except Exception as e:
71
- st.error(f"Error uploading file: {e}")
72
-
73
- # Image Processing Functions
74
  def detect_faces_and_emotions(image):
75
  gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
76
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
@@ -84,7 +75,6 @@ def detect_faces_and_emotions(image):
84
  emotion_prediction = emotion_model.predict(reshaped_face)
85
  emotion_label = np.argmax(emotion_prediction)
86
  return EMOTION_LABELS[emotion_label]
87
-
88
  return None
89
 
90
  # UI Design
@@ -110,7 +100,6 @@ if choice == "Register Student":
110
  img_path = os.path.join(KNOWN_FACES_DIR, f"{roll_number}.png")
111
  img.save(img_path)
112
  insert_student(name, roll_number, img_path)
113
- upload_to_hugging_face(img_path, f"{roll_number}.png")
114
  st.success("Student Registered Successfully!")
115
  except Exception as e:
116
  st.error(f"Error: {e}")
@@ -129,7 +118,7 @@ elif choice == "Face Recognition and Emotion Detection":
129
  img = Image.open(uploaded_file)
130
  img_array = np.array(img)
131
  emotion_label = detect_faces_and_emotions(img_array)
132
- if emotion_label is not None:
133
  st.success(f"Emotion Detected: {emotion_label}")
134
  else:
135
  st.warning("No face detected.")
@@ -144,7 +133,7 @@ elif choice == "Face Recognition and Emotion Detection":
144
  img = Image.open(camera_image)
145
  img_array = np.array(img)
146
  emotion_label = detect_faces_and_emotions(img_array)
147
- if emotion_label is not None:
148
  st.success(f"Emotion Detected: {emotion_label}")
149
  else:
150
  st.warning("No face detected.")
 
5
  from keras.models import load_model
6
  from PIL import Image
7
  import sqlite3
8
+ from huggingface_hub import HfApi
 
9
 
10
  # Constants
11
  DB_FILE = "students.db"
12
  KNOWN_FACES_DIR = "known_faces"
13
  EMOTION_MODEL_FILE = "CNN_Model_acc_75.h5"
 
 
 
 
14
  EMOTION_LABELS = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
15
 
16
+ # Hugging Face Repository Details
17
+ REPO_NAME = "face_and_emotion_detection"
18
+ REPO_ID = f"LovnishVerma/{REPO_NAME}" # Replace with your Hugging Face username and repository name
19
+
20
+ # Ensure Directories
21
  os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
22
 
23
+ # Load Hugging Face Token
24
+ hf_token = os.getenv("HUGGING_FACE_TOKEN")
25
+ if not hf_token:
26
+ st.error("Hugging Face token not found. Please set the environment variable.")
27
+
28
+ # Initialize Hugging Face API
29
+ api = HfApi()
30
+ try:
31
+ api.create_repo(repo_id=REPO_ID, repo_type="space", space_sdk="streamlit", token=hf_token, exist_ok=True)
32
+ st.success(f"Repository '{REPO_NAME}' is ready on Hugging Face!")
33
+ except Exception as e:
34
+ st.error(f"Error creating Hugging Face repository: {e}")
35
+
36
+ # Load Emotion Model
37
  try:
38
  emotion_model = load_model(EMOTION_MODEL_FILE)
39
  except Exception as e:
 
42
  # Database Functions
43
  def create_table():
44
  with sqlite3.connect(DB_FILE) as conn:
45
+ conn.execute("""
 
46
  CREATE TABLE IF NOT EXISTS students (
47
  id INTEGER PRIMARY KEY AUTOINCREMENT,
48
  name TEXT NOT NULL,
 
55
  def insert_student(name, roll_number, image_path):
56
  try:
57
  with sqlite3.connect(DB_FILE) as conn:
58
+ conn.execute("INSERT INTO students (name, roll_number, image_path) VALUES (?, ?, ?)",
59
+ (name, roll_number, image_path))
 
60
  conn.commit()
61
  except sqlite3.IntegrityError:
62
  st.warning("Roll number already exists!")
63
 
64
+ # Face and Emotion Detection
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  def detect_faces_and_emotions(image):
66
  gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
67
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
 
75
  emotion_prediction = emotion_model.predict(reshaped_face)
76
  emotion_label = np.argmax(emotion_prediction)
77
  return EMOTION_LABELS[emotion_label]
 
78
  return None
79
 
80
  # UI Design
 
100
  img_path = os.path.join(KNOWN_FACES_DIR, f"{roll_number}.png")
101
  img.save(img_path)
102
  insert_student(name, roll_number, img_path)
 
103
  st.success("Student Registered Successfully!")
104
  except Exception as e:
105
  st.error(f"Error: {e}")
 
118
  img = Image.open(uploaded_file)
119
  img_array = np.array(img)
120
  emotion_label = detect_faces_and_emotions(img_array)
121
+ if emotion_label:
122
  st.success(f"Emotion Detected: {emotion_label}")
123
  else:
124
  st.warning("No face detected.")
 
133
  img = Image.open(camera_image)
134
  img_array = np.array(img)
135
  emotion_label = detect_faces_and_emotions(img_array)
136
+ if emotion_label:
137
  st.success(f"Emotion Detected: {emotion_label}")
138
  else:
139
  st.warning("No face detected.")