Lucasstranger1 commited on
Commit
3f51327
·
verified ·
1 Parent(s): 2bbfd62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -42
app.py CHANGED
@@ -1,56 +1,42 @@
1
  #############################################################################################################################
2
  # Filename : app.py
3
  # Description: A Streamlit application to detect facial expressions from images and provide responses.
4
- # Author : [Your Name]
5
  #
6
- # Copyright © 2024 by [Your Name]
7
  #############################################################################################################################
8
 
9
  # Import libraries.
10
  import os # Load environment variable(s).
11
- import requests # Send HTTP GET request to Hugging Face models for inference.
12
  import streamlit as st # Build the GUI of the application.
13
  from PIL import Image # Handle image operations.
14
  from dotenv import load_dotenv # Load environment variables.
15
- import torch # For tensor operations.
16
- from transformers import AutoProcessor, AutoModelForImageClassification # Hugging Face models.
17
  import openai # OpenAI API for generating text responses.
18
 
19
  #############################################################################################################################
20
  # Load environment variable(s).
21
  load_dotenv()
22
 
23
- # Set up the Hugging Face API for emotion detection.
24
- HUGGINGFACE_API_TOKEN = os.getenv("HUGGINGFACE_API_TOKEN")
25
  # Set up OpenAI API key.
26
  openai.api_key = os.getenv('OPENAI_API_KEY')
27
 
28
- # Load the processor and model for facial expression recognition.
29
- processor = AutoProcessor.from_pretrained("trpakov/vit-face-expression")
30
- model = AutoModelForImageClassification.from_pretrained("trpakov/vit-face-expression")
31
-
32
  #############################################################################################################################
33
- # Function to query the facial expression recognition model.
34
  def query_emotion(image):
35
- # Preprocess the image.
36
- inputs = processor(images=image, return_tensors="pt")
37
-
38
- # Perform inference.
39
- with torch.no_grad():
40
- outputs = model(**inputs)
41
-
42
- # Get predicted class index (the class with the highest logit).
43
- logits = outputs.logits
44
- predicted_class_idx = torch.argmax(logits, dim=-1).item()
45
-
46
- # Retrieve the label names from the model.
47
- label_names = model.config.id2label # Mapping of indices to emotion labels.
48
- predicted_label = label_names[predicted_class_idx] # Get the predicted label.
49
-
50
- return predicted_label
51
 
52
  #############################################################################################################################
53
- # Function to generate a response using OpenAI based on detected emotion and user preference.
54
  def generate_text_based_on_mood(emotion, response_type):
55
  try:
56
  if response_type == "Joke":
@@ -103,23 +89,24 @@ def main():
103
 
104
  # Detect facial expression.
105
  emotion = query_emotion(image)
106
- st.write(f"Detected emotion: {emotion}")
 
107
 
108
- # Dropdown for selecting response type.
109
- response_type = st.selectbox("Select the type of response:", ["Joke", "Motivational Message"])
110
 
111
- # Generate text based on detected emotion and user preference.
112
- if st.button("Get Response"):
113
- message = generate_text_based_on_mood(emotion, response_type)
114
- st.write("Here's your response:")
115
- st.write(message)
116
 
117
- # Convert the generated message to audio.
118
- audio_file = text_to_speech(message)
119
 
120
- # Provide an audio player in the Streamlit app if audio file exists.
121
- if audio_file:
122
- st.audio(audio_file) # Streamlit will handle playback.
123
 
124
  #############################################################################################################################
125
  # Run the application.
 
1
  #############################################################################################################################
2
  # Filename : app.py
3
  # Description: A Streamlit application to detect facial expressions from images and provide responses.
4
+ # Author : Lucas Yao
5
  #
6
+ # Copyright © 2024 by Lucas Yao
7
  #############################################################################################################################
8
 
9
  # Import libraries.
10
  import os # Load environment variable(s).
 
11
  import streamlit as st # Build the GUI of the application.
12
  from PIL import Image # Handle image operations.
13
  from dotenv import load_dotenv # Load environment variables.
14
+ from fer import FER # Import the FER model for facial expression recognition.
 
15
  import openai # OpenAI API for generating text responses.
16
 
17
  #############################################################################################################################
18
  # Load environment variable(s).
19
  load_dotenv()
20
 
 
 
21
  # Set up OpenAI API key.
22
  openai.api_key = os.getenv('OPENAI_API_KEY')
23
 
 
 
 
 
24
  #############################################################################################################################
25
+ # Function to query the facial expression recognition model using FER.
26
  def query_emotion(image):
27
+ detector = FER()
28
+ emotions = detector.detect_emotions(image)
29
+
30
+ if emotions:
31
+ # Get the emotion with the highest score.
32
+ dominant_emotion = max(emotions[0]['emotions'], key=emotions[0]['emotions'].get)
33
+ return dominant_emotion
34
+ else:
35
+ st.error("Could not detect any emotion.")
36
+ return None
 
 
 
 
 
 
37
 
38
  #############################################################################################################################
39
+ # Function to generate a response using OpenAI based on detected emotion.
40
  def generate_text_based_on_mood(emotion, response_type):
41
  try:
42
  if response_type == "Joke":
 
89
 
90
  # Detect facial expression.
91
  emotion = query_emotion(image)
92
+ if emotion:
93
+ st.write(f"Detected emotion: {emotion}")
94
 
95
+ # Dropdown for selecting response type.
96
+ response_type = st.selectbox("Select the type of response:", ["Joke", "Motivational Message"])
97
 
98
+ # Generate text based on detected emotion and user preference.
99
+ if st.button("Get Response"):
100
+ message = generate_text_based_on_mood(emotion, response_type)
101
+ st.write("Here's your response:")
102
+ st.write(message)
103
 
104
+ # Convert the generated message to audio.
105
+ audio_file = text_to_speech(message)
106
 
107
+ # Provide an audio player in the Streamlit app if audio file exists.
108
+ if audio_file:
109
+ st.audio(audio_file) # Streamlit will handle playback.
110
 
111
  #############################################################################################################################
112
  # Run the application.