Uddancode commited on
Commit
51d6f5f
·
verified ·
1 Parent(s): b88f082

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -104
app.py CHANGED
@@ -1,115 +1,53 @@
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
 
 
 
 
1
  import streamlit as st
2
  import cv2
3
  from deepface import DeepFace
4
+ import numpy as np
5
+
6
+ # Streamlit app title
7
+ st.title("Face Emotion Detection App")
8
+
9
+ # Upload an image or video
10
+ uploaded_file = st.file_uploader("Upload an image or video", type=["jpg", "jpeg", "png", "mp4"])
11
+
12
+ # Product suggestions based on emotions
13
+ emotion_to_product = {
14
+ "happy": "Product A - Happiness Booster",
15
+ "sad": "Product B - Comfort Blanket",
16
+ "angry": "Product C - Stress Relief Ball",
17
+ "surprise": "Product D - Mystery Box",
18
+ "fear": "Product E - Confidence Potion",
19
+ "disgust": "Product F - Aroma Diffuser",
20
+ "neutral": "Product G - Everyday Essentials",
21
+ "Unknown": "Product H - General Item"
 
 
22
  }
23
 
24
+ if uploaded_file is not None:
25
+ # If the uploaded file is an image
26
+ if uploaded_file.type in ["image/jpeg", "image/png"]:
27
+ image = np.array(bytearray(uploaded_file.read()), dtype=np.uint8)
28
+ image = cv2.imdecode(image, cv2.IMREAD_COLOR)
29
+
30
+ # Convert frame to RGB for DeepFace
31
+ rgb_frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ # Analyze emotions using DeepFace
34
+ result = DeepFace.analyze(rgb_frame, actions=['emotion'], enforce_detection=False)
35
+ emotion = result[0]['dominant_emotion'] # Extract dominant emotion
36
 
37
+ # Display the uploaded image
38
+ st.image(rgb_frame, channels="RGB")
 
 
39
 
40
+ # Display the detected emotion
41
+ st.subheader(f"Detected Emotion: {emotion}")
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ # Display the suggested product
44
+ product = emotion_to_product.get(emotion, "Product H - General Item")
45
+ st.subheader(f"Recommended Product: {product}")
46
 
47
+ # If the uploaded file is a video
48
+ elif uploaded_file.type == "video/mp4":
49
+ st.video(uploaded_file)
50
+ # You can add code to analyze frames from the video if needed
51
 
52
+ else:
53
+ st.info("Please upload an image or video file.")