Uddancode commited on
Commit
8bf3411
·
verified ·
1 Parent(s): 7926348

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +115 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cv2
3
+ from deepface import DeepFace
4
+ import pandas as pd
5
+ import os
6
+ from datetime import datetime
7
+
8
+ # Initialize face detector
9
+ faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
10
+
11
+ # Prepare CSV file
12
+ csv_file = 'face_emotions.csv'
13
+ csv_data = []
14
+
15
+ # Define emotion to product mapping
16
+ emotion_to_products = {
17
+ "happy": ["Joyful Juice", "Cheerful Chocolate", "Happy Hoodie"],
18
+ "sad": ["Comfort Blanket", "Warm Tea", "Inspirational Book"],
19
+ "angry": ["Stress Ball", "Calming Tea", "Meditation App"],
20
+ "surprised": ["Exciting Gadgets", "Adventure Gear", "Surprise Box"],
21
+ "neutral": ["Laptop- www.google.com ❤️‍🔥", "Healthy Snacks", "Relaxing Music"],
22
+ "fear": ["Safety Kit", "Comfort Food", "Stress Relief Kit"],
23
+ "disgust": ["Refreshing Drink", "Cleanser", "Aromatherapy Kit"]
24
+ }
25
+
26
+ def detect_emotion(frame):
27
+ emotion = "Unknown"
28
+ products = []
29
+ try:
30
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
31
+ result = DeepFace.analyze(rgb_frame, actions=['emotion'])
32
+ emotion = result[0]['dominant_emotion'] # Extract dominant emotion
33
+ products = emotion_to_products.get(emotion, ["No products available"])
34
+ except Exception as e:
35
+ st.error(f"Error analyzing frame: {e}")
36
+ return emotion, products
37
+
38
+ def detect_faces_and_emotions():
39
+ # Create a directory to store images if it doesn't exist
40
+ if not os.path.exists('saved_faces'):
41
+ os.makedirs('saved_faces')
42
+
43
+ # Start video capture
44
+ cap = cv2.VideoCapture(0)
45
+ if not cap.isOpened():
46
+ st.error("Cannot open webcam!")
47
+ return
48
+
49
+ stframe = st.empty()
50
+ while True:
51
+ ret, frame = cap.read()
52
+ if not ret:
53
+ break
54
+
55
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
56
+ faces = faceCascade.detectMultiScale(gray, 1.1, 4)
57
+
58
+ emotion, products = detect_emotion(frame)
59
+
60
+ for (x, y, w, h) in faces:
61
+ cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
62
+
63
+ font = cv2.FONT_HERSHEY_SIMPLEX
64
+ cv2.putText(frame, emotion, (50, 50), font, 1, (0, 0, 255), 2, cv2.LINE_4)
65
+ stframe.image(frame, channels="BGR")
66
+
67
+ st.write(f"*Emotion Detected:* {emotion}")
68
+ st.write("*Recommended Products:*")
69
+ st.write(", ".join(products))
70
+
71
+ # Button for saving image with unique key
72
+ if st.button("Save Image", key=f"save_image_{datetime.now().strftime('%Y%m%d%H%M%S')}"):
73
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
74
+ face_filename = f'saved_faces/face_{timestamp}.jpg'
75
+ cv2.imwrite(face_filename, frame)
76
+
77
+ csv_data.append({
78
+ 'Timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
79
+ 'Emotion': emotion,
80
+ 'File Path': face_filename
81
+ })
82
+ print(f"Image saved and data logged to CSV: {face_filename}")
83
+
84
+ if st.button("Quit", key="quit_app_button"):
85
+ break
86
+
87
+ cap.release()
88
+ cv2.destroyAllWindows()
89
+
90
+ # Save CSV file with emotion and product data
91
+ df = pd.DataFrame(csv_data)
92
+ df.to_csv(csv_file, index=False)
93
+ st.success(f"Data saved to {csv_file}")
94
+
95
+ def display_csv_data():
96
+ if os.path.exists(csv_file):
97
+ # Check if the file is empty
98
+ if os.path.getsize(csv_file) > 0:
99
+ try:
100
+ df = pd.read_csv(csv_file)
101
+ st.write("### Logged Emotions and Product Recommendations")
102
+ st.dataframe(df)
103
+ except pd.errors.EmptyDataError:
104
+ st.write("The file is empty or cannot be read.")
105
+ else:
106
+ st.write("The file is empty.")
107
+ else:
108
+ st.write("No data available. Start detection to log emotions.")
109
+
110
+ st.title("Welcome To NeuroSphere!!")
111
+ st.write("This web app detects emotions from a live webcam feed and suggests products based on the detected emotion. To make your shopping experience happy and more reliable")
112
+
113
+ if st.button("Start Detection", key="start_detection_button"):
114
+ detect_faces_and_emotions()
115
+
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ streamlit
2
+ numpy
3
+ pandas
4
+ opencv-python
5
+ deepface
6
+ tf-keras