Spaces:
Sleeping
Sleeping
Samantha Hipple
commited on
Commit
·
91c8e31
1
Parent(s):
82df73b
init app
Browse files- app.py +24 -0
- beluga.py +150 -0
- emodeepface.py +55 -0
- requirements.txt +5 -0
app.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
|
3 |
+
from beluga import load_model, process_emotions, generate_prompt
|
4 |
+
from emodeepface import check_image_rotation, process_photo
|
5 |
+
|
6 |
+
# Title webpage
|
7 |
+
st.title("Affective Journaling Assistant")
|
8 |
+
|
9 |
+
# User instructions
|
10 |
+
st.write("""
|
11 |
+
Welcome to the Affective Journaling Assistant!
|
12 |
+
|
13 |
+
For a tailored journaling experience, we analyze your facial expressions to gauge your emotions.
|
14 |
+
To proceed:
|
15 |
+
|
16 |
+
1. Ensure the image is well-lit and of high quality.
|
17 |
+
2. Your face should be fully visible without obstructions (e.g., no sunglasses or hats).
|
18 |
+
3. By uploading, you acknowledge and consent to our data processing.
|
19 |
+
|
20 |
+
Let's get started!
|
21 |
+
""")
|
22 |
+
|
23 |
+
# User image upload
|
24 |
+
file_name = st.file_uploader("Please upload your photo.")
|
beluga.py
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# import required libraries
|
2 |
+
import torch
|
3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
4 |
+
|
5 |
+
def load_model():
|
6 |
+
# define the tokenizer for preprocessing any inputs
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained("stabilityai/StableBeluga-7B", use_fast=False)
|
8 |
+
# define the LLM model for the generating output
|
9 |
+
model = AutoModelForCausalLM.from_pretrained("stabilityai/StableBeluga-7B", torch_dtype=torch.float16, low_cpu_mem_usage=True, device_map="auto")
|
10 |
+
return (model, tokenizer)
|
11 |
+
|
12 |
+
def process_emotions(model, tokenizer, emotion_data):
|
13 |
+
# ensure emotion_data is a dictionary
|
14 |
+
if not isinstance(emotion_data, dict):
|
15 |
+
raise ValueError("Expected emotion_data to be a dictionary.")
|
16 |
+
# convert emotion_data dictionary to string format
|
17 |
+
emotions = ', '.join(f"{k}: {v:.2f}%" for k, v in emotion_data.items())
|
18 |
+
# prompt-engineering instead of fine-tuning
|
19 |
+
system_prompt = """### System:
|
20 |
+
You are StableBeluga, an AI programmed to follow instructions with high accuracy. Your current task is to assist with enhancing human emotional regulation and intelligence. You will receive information about the emotional ratios of a client. Your task is to identify the one or two emotions with the highest values from the information provided, and create a one or two-sentence original journal prompt for the client's self-reflection and emotional exploration. Do not discuss the emotions or their scores, and do not include any other introductory or explanatory text. Only provide the journal prompt, and ensure it is based on the emotions with the highest values. Here are examples of the desired format:
|
21 |
+
|
22 |
+
Example 1: 'Reflect on a recent situation when you felt anger. What was the trigger and how did it affect your actions?'
|
23 |
+
|
24 |
+
Example 2: 'Write about a moment when you felt sad. What thoughts or events led to this emotion and how did it impact your day?'
|
25 |
+
|
26 |
+
Provide a prompt following this format, based on the emotions with the highest values from the data provided.
|
27 |
+
"""
|
28 |
+
# user input will come from deepface FER results
|
29 |
+
prompt = f"{system_prompt}### User: {emotions}\n\n### Assistant:\n"
|
30 |
+
# preprocess the inputs
|
31 |
+
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
|
32 |
+
output = model.generate(**inputs, do_sample=True, top_p=0.95, top_k=0, max_new_tokens=256)
|
33 |
+
result = tokenizer.decode(output[0], skip_special_tokens=True)
|
34 |
+
# return decoded output
|
35 |
+
return result
|
36 |
+
|
37 |
+
def generate_prompt(result):
|
38 |
+
# split the text by the "Assistant:" label
|
39 |
+
response = result.split("### Assistant:")[1].strip()
|
40 |
+
# check if response includes uneeded prompt indifier (e.g., Journal prompt: ..., etc.)
|
41 |
+
if ":" in response:
|
42 |
+
split_response = response.split(":", 1)
|
43 |
+
response = split_response[1].strip()
|
44 |
+
return response
|
45 |
+
|
46 |
+
|
47 |
+
|
48 |
+
# sample data
|
49 |
+
# message = { 'angry': 13.207298517227173,
|
50 |
+
# 'disgust': 0.12863066513091326,
|
51 |
+
# 'fear': 0.11500244727358222,
|
52 |
+
# 'happy': 18.36708039045334,
|
53 |
+
# 'sad': 62.15316653251648,
|
54 |
+
# 'surprise': 0.025137534248642623,
|
55 |
+
# 'neutral': 6.003682315349579 }
|
56 |
+
|
57 |
+
# prompt engineering data
|
58 |
+
|
59 |
+
# prompt #1
|
60 |
+
# ### System:
|
61 |
+
# You are StableBeluga, an AI programmed to follow instructions with high accuracy. Your current task is to assist with enhancing human emotional regulation and intelligence. You will receive information about the emotional ratios of a client. Based on that information, please provide exactly one original and creative journal prompt to facilitate the client's self-reflection and emotional exploration.
|
62 |
+
|
63 |
+
# ### User: {'angry': 13.207298517227173, 'disgust': 0.12863066513091326, 'fear': 0.11500244727358222, 'happy': 18.36708039045334, 'sad': 62.15316653251648, 'surprise': 0.025137534248642623, 'neutral': 6.003682315349579}
|
64 |
+
|
65 |
+
# ### Assistant:
|
66 |
+
# Here is a journal prompt designed to help the client explore the different emotions they are experiencing and gain a better understanding of their current emotional state:
|
67 |
+
|
68 |
+
# List three significant events or experiences that have been recent triggers for each of the emotions you observe in your chart. Then, for each of those events or experiences, describe how the event makes you feel and if it leads to an increased or decreased ratio of that emotion. This reflection will enable the client to understand their emotions better and perhaps find ways to improve their emotional regulation.
|
69 |
+
|
70 |
+
|
71 |
+
|
72 |
+
# prompt #2
|
73 |
+
# ### System:
|
74 |
+
# You are StableBeluga, an AI programmed to follow instructions with high accuracy. Your current task is to assist with enhancing human emotional regulation and intelligence. You will receive information about the emotional ratios of a client. Please identify the one or two emotions with the highest values. Based on those emotions, provide exactly one original and creative journal prompt to facilitate the client's self-reflection and emotional exploration. Do not create prompts based on emotions with lower values.
|
75 |
+
|
76 |
+
# ### User: {'angry': 13.207298517227173, 'disgust': 0.12863066513091326, 'fear': 0.11500244727358222, 'happy': 18.36708039045334, 'sad': 62.15316653251648, 'surprise': 0.025137534248642623, 'neutral': 6.003682315349579}
|
77 |
+
|
78 |
+
# ### Assistant:
|
79 |
+
# Based on the emotions with the highest values in the client's emotional ratios, it appears that 'happy' and 'sad' are particularly prominent in their emotional landscape. To facilitate their self-reflection and emotional exploration, an original and creative journal prompt could be:
|
80 |
+
|
81 |
+
# Prompt:
|
82 |
+
|
83 |
+
# What makes you feel happy, and how can you incorporate that into your daily routine? How can you cultivate a more balanced emotional state by fostering positive emotions like happiness, even when faced with the inevitable challenges and negative emotions like sadness?
|
84 |
+
|
85 |
+
|
86 |
+
|
87 |
+
# prompt #3
|
88 |
+
# ### System:
|
89 |
+
# You are StableBeluga, an AI programmed to follow instructions with high accuracy. Your current task is to assist with enhancing human emotional regulation and intelligence. You will receive information about the emotional ratios of a client. Identify the one or two emotions with the highest values. Without discussing or reiterating these emotions or their scores, create exactly one original and creative journal prompt to facilitate the client's self-reflection and emotional exploration. Focus solely on creating the prompt.
|
90 |
+
|
91 |
+
# ### User: {'angry': 13.207298517227173, 'disgust': 0.12863066513091326, 'fear': 0.11500244727358222, 'happy': 18.36708039045334, 'sad': 62.15316653251648, 'surprise': 0.025137534248642623, 'neutral': 6.003682315349579}
|
92 |
+
|
93 |
+
# ### Assistant:
|
94 |
+
# To enhance your emotional regulation and intelligence, consider exploring the emotions with the highest values in your current emotional state. Consider journaling about your thoughts and feelings surrounding these dominant emotions. This could be done by asking yourself the following original and creative journal prompt:
|
95 |
+
|
96 |
+
# What are the roots or origins of the dominant emotions in my life, and how do they impact my overall well-being and relationships? How can I shift my perspective to gain more control over these emotions and find a more balanced emotional state?
|
97 |
+
|
98 |
+
|
99 |
+
|
100 |
+
# prompt #4
|
101 |
+
### System:
|
102 |
+
# You are StableBeluga, an AI programmed to follow instructions with high accuracy. Your current task is to assist with enhancing human emotional regulation and intelligence. You will receive information about the emotional ratios of a client. Using the one or two emotions with the highest values, create a one or two-sentence journal prompt for the client's self-reflection and emotional exploration. Do not discuss the emotions or their scores, only provide the prompt.
|
103 |
+
|
104 |
+
# ### User: {'angry': 13.207298517227173, 'disgust': 0.12863066513091326, 'fear': 0.11500244727358222, 'happy': 18.36708039045334, 'sad': 62.15316653251648, 'surprise': 0.025137534248642623, 'neutral': 6.003682315349579}
|
105 |
+
|
106 |
+
# ### Assistant:
|
107 |
+
# Journal prompt: When does anger typically arise for you, and how can understanding your triggers and reactions help you manage and cope with such situations more effectively in the future?
|
108 |
+
|
109 |
+
|
110 |
+
|
111 |
+
# prompt #5
|
112 |
+
# ### System:
|
113 |
+
# You are StableBeluga, an AI programmed to follow instructions with high accuracy. Your current task is to assist with enhancing human emotional regulation and intelligence. You will receive information about the emotional ratios of a client. Using the one or two emotions with the highest values, create a one or two-sentence journal prompt for the client's self-reflection and emotional exploration. Do not discuss the emotions or their scores, only provide the prompt. Here are some examples of what the prompt should look like:
|
114 |
+
|
115 |
+
# Example 1: 'Reflect on a recent situation when you felt anger. What was the trigger and how did it affect your actions?'
|
116 |
+
# Example 2: 'Write about a moment when you felt sad. What thoughts or events led to this emotion and how did it impact your day?'
|
117 |
+
|
118 |
+
# Please provide a similar prompt based on the emotions provided.
|
119 |
+
|
120 |
+
# ### User: {'angry': 13.207298517227173, 'disgust': 0.12863066513091326, 'fear': 0.11500244727358222, 'happy': 18.36708039045334, 'sad': 62.15316653251648, 'surprise': 0.025137534248642623, 'neutral': 6.003682315349579}
|
121 |
+
|
122 |
+
# output 1
|
123 |
+
# ### Assistant:
|
124 |
+
# Based on the provided emotional ratios:
|
125 |
+
|
126 |
+
# "Write about a recent experience when you felt surprised. Describe the event and how it made you feel."
|
127 |
+
|
128 |
+
# output 2
|
129 |
+
# Assistant:\n Journal prompt based on the emotions provided: Reflect on a situation when you felt more than one strong emotion, like surprise and fear. Identify the trigger and describe how your emotions influenced each other and the actions you took in response.
|
130 |
+
|
131 |
+
|
132 |
+
|
133 |
+
# # prompt #6
|
134 |
+
# ### System:
|
135 |
+
# You are StableBeluga, an AI programmed to follow instructions with high accuracy. Your current task is to assist with enhancing human emotional regulation and intelligence. You will receive information about the emotional ratios of a client. Your task is to identify the one or two emotions with the highest values from the information provided, and create a one or two-sentence original journal prompt for the client's self-reflection and emotional exploration. Do not discuss the emotions or their scores, and do not include any other introductory or explanatory text. Only provide the journal prompt, and ensure it is based on the emotions with the highest values. Here are examples of the desired format:
|
136 |
+
|
137 |
+
# Example 1: 'Reflect on a recent situation when you felt anger. What was the trigger and how did it affect your actions?'
|
138 |
+
# Example 2: 'Write about a moment when you felt sad. What thoughts or events led to this emotion and how did it impact your day?'
|
139 |
+
|
140 |
+
# Provide a prompt following this format, based on the emotions with the highest values from the data provided.
|
141 |
+
|
142 |
+
# ### User: angry: 13.21%, disgust: 0.13%, fear: 0.12%, happy: 18.37%, sad: 62.15%, surprise: 0.03%, neutral: 6.00%
|
143 |
+
|
144 |
+
# # output 1
|
145 |
+
# ### Assistant:
|
146 |
+
# Journal prompt: Think back to a time when you experienced sadness and explore the events that led to that emotion, as well as the impact it had on your thoughts and actions.
|
147 |
+
# # output 2
|
148 |
+
# Assistant:\n Journal Prompt: In a recent day, think back to a situation where you felt extreme happiness. Describe the events or people that led to this emotion, and how it made you feel throughout the day.
|
149 |
+
# # output 3
|
150 |
+
# Assistant:\n Reflect on a time when you experienced a high percentage of anger, and explore the events or circumstances that contributed to its manifestation.
|
emodeepface.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from deepface import DeepFace
|
2 |
+
import numpy as np
|
3 |
+
from PIL import Image, ExifTags
|
4 |
+
|
5 |
+
# used to raise custom exceptions
|
6 |
+
class ImageProcessingError(Exception):
|
7 |
+
pass
|
8 |
+
|
9 |
+
# used to ensure upright photo orientation for face detection
|
10 |
+
def check_image_rotation(image_path):
|
11 |
+
try:
|
12 |
+
image = Image.open(image_path)
|
13 |
+
for orientation in ExifTags.TAGS.keys():
|
14 |
+
if ExifTags.TAGS[orientation] == 'Orientation':
|
15 |
+
break
|
16 |
+
exif = image._getexif()
|
17 |
+
if exif is not None:
|
18 |
+
if orientation in exif:
|
19 |
+
if exif[orientation] == 3:
|
20 |
+
image = image.rotate(180, expand=True)
|
21 |
+
elif exif[orientation] == 6:
|
22 |
+
image = image.rotate(270, expand=True)
|
23 |
+
elif exif[orientation] == 8:
|
24 |
+
image = image.rotate(90, expand=True)
|
25 |
+
return image
|
26 |
+
except (AttributeError, KeyError, IndexError):
|
27 |
+
# If the orientation tag is not found or any other error occurs, return the original image
|
28 |
+
return Image.open(image_path)
|
29 |
+
|
30 |
+
# used to process photo through deepface emotion model
|
31 |
+
def process_photo(file_name):
|
32 |
+
backends = ['opencv', 'mtcnn', 'retinaface', 'mediapipe', 'ssd']
|
33 |
+
attempt = 0
|
34 |
+
|
35 |
+
if file_name is not None:
|
36 |
+
image = check_image_rotation(file_name)
|
37 |
+
image_data = np.array(image)
|
38 |
+
|
39 |
+
while attempt < len(backends):
|
40 |
+
try:
|
41 |
+
predictions = DeepFace.analyze(image_data, actions=['emotion'], detector_backend=backends[attempt])
|
42 |
+
if len(predictions) > 1:
|
43 |
+
faces = [(face, face['region']['w'] * face['region']['h']) for face in predictions]
|
44 |
+
new_predictions = sorted(faces, key=lambda x: x[1], reverse=True)[0][0]
|
45 |
+
emotion_dict = new_predictions['emotion']
|
46 |
+
return emotion_dict
|
47 |
+
return predictions['emotion']
|
48 |
+
except Exception as e:
|
49 |
+
if attempt == len(backends) - 1:
|
50 |
+
error_message = f"Failed to analyze image after attempting all detector backends available. Please upload a new image."
|
51 |
+
raise ImageProcessingError(error_message)
|
52 |
+
else:
|
53 |
+
# log the error message for each failed backend here:
|
54 |
+
print(f"Retrying with backend `{backends[attempt+1]}` due to error: {str(e)}")
|
55 |
+
attempt += 1
|
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
accelerate
|
2 |
+
deepface
|
3 |
+
sentencepiece
|
4 |
+
torch
|
5 |
+
transformers
|