Skip to content

Commit 88aa436

Browse files
Fix: Integrated mood-aware journaling correctly
1 parent babcc05 commit 88aa436

File tree

9 files changed

+191
-141
lines changed

9 files changed

+191
-141
lines changed

TalkHeal.py

Lines changed: 41 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,79 @@
11
# --- 0. IMPORTS ---
2+
import uuid # standard library import
23
import streamlit as st
3-
import google.generativeai as genai
44

5-
# --- 1. FIRST COMMAND: PAGE CONFIG ---
5+
# --- 1. PAGE CONFIG FIRST ---
66
from core.config import PAGE_CONFIG
7-
st.set_page_config(**PAGE_CONFIG)
8-
9-
GEMINI_API_KEY = st.secrets["GEMINI_API_KEY"]
7+
st.set_page_config(**PAGE_CONFIG)
8+
from css.styles import apply_custom_css
109

11-
# --- 2. CONTINUED IMPORTS ---
12-
from core.utils import save_conversations, load_conversations, get_current_time, create_new_conversation
1310
from core.config import configure_gemini, get_tone_prompt, get_selected_mood
14-
from css.styles import apply_custom_css
11+
from core.utils import save_conversations, load_conversations, get_current_time, create_new_conversation
12+
1513
from components.header import render_header
1614
from components.sidebar import render_sidebar
1715
from components.chat_interface import render_chat_interface, handle_chat_input
1816
from components.emergency_page import render_emergency_page
1917

20-
# --- 3. SESSION STATE INITIALIZATION ---
21-
if "chat_history" not in st.session_state:
22-
st.session_state.chat_history = []
23-
if "conversations" not in st.session_state:
24-
st.session_state.conversations = load_conversations()
25-
if "active_conversation" not in st.session_state:
26-
st.session_state.active_conversation = -1
27-
if "show_emergency_page" not in st.session_state:
28-
st.session_state.show_emergency_page = False
29-
if "sidebar_state" not in st.session_state:
30-
st.session_state.sidebar_state = "expanded"
31-
if "mental_disorders" not in st.session_state:
32-
st.session_state.mental_disorders = [
18+
# --- 1. PAGE CONFIG & CSS ---
19+
apply_custom_css()
20+
21+
# --- 2. SESSION STATE INITIALIZATION ---
22+
default_values = {
23+
"conversations": [],
24+
"active_conversation": -1,
25+
"send_chat_message": False,
26+
"pre_filled_chat_input": "",
27+
"selected_mood_context": "",
28+
"current_mood_val": "",
29+
"chat_history": [],
30+
"show_emergency_page": False,
31+
"sidebar_state": "expanded",
32+
"mental_disorders": [
3333
"Depression & Mood Disorders", "Anxiety & Panic Disorders", "Bipolar Disorder",
3434
"PTSD & Trauma", "OCD & Related Disorders", "Eating Disorders",
3535
"Substance Use Disorders", "ADHD & Neurodevelopmental", "Personality Disorders",
3636
"Sleep Disorders"
37-
]
38-
if "selected_tone" not in st.session_state:
39-
st.session_state.selected_tone = "Compassionate Listener"
40-
if "selected_mood" not in st.session_state:
41-
st.session_state.selected_mood = "🙂" # Default emoji mood
37+
],
38+
"selected_tone": "Compassionate Listener",
39+
"selected_mood": "🙂"
40+
}
4241

43-
# --- 4. STYLES & GEMINI SETUP ---
44-
apply_custom_css()
42+
for key, val in default_values.items():
43+
if key not in st.session_state:
44+
st.session_state[key] = val
45+
46+
# --- 3. GEMINI MODEL SETUP ---
4547
model = configure_gemini()
4648

47-
# --- 5. SIDEBAR ---
49+
# --- 4. SIDEBAR ---
4850
render_sidebar()
4951

50-
# --- 6. MAIN PAGE ROUTING LOGIC ---
52+
# --- 5. MAIN LOGIC CONTAINER ---
5153
main_area = st.container()
5254

53-
# Load conversations or start a new one
55+
# --- 6. Load or Start Conversation ---
5456
if not st.session_state.conversations:
55-
saved_convos = load_conversations()
56-
if saved_convos:
57-
st.session_state.conversations = saved_convos
57+
saved = load_conversations()
58+
if saved:
59+
st.session_state.conversations = saved
5860
if st.session_state.active_conversation == -1:
5961
st.session_state.active_conversation = 0
6062
else:
6163
create_new_conversation()
6264
st.session_state.active_conversation = 0
6365
st.rerun()
6466

65-
# --- 7. MAIN VIEW DISPLAY ---
66-
if st.session_state.get("show_emergency_page"):
67-
with main_area:
67+
# --- 7. ROUTING ---
68+
with main_area:
69+
if st.session_state.get("show_emergency_page"):
6870
render_emergency_page()
69-
else:
70-
with main_area:
71+
else:
7172
render_header()
7273
st.subheader(f"🗣️ Current Chatbot Tone: **{st.session_state['selected_tone']}**")
7374
st.markdown(f"**🧠 Mood Selected:** {get_selected_mood()}")
7475
render_chat_interface()
75-
handle_chat_input(model, system_prompt=get_tone_prompt())
76+
handle_chat_input(model=model, system_prompt=get_tone_prompt())
7677

7778
# --- 8. AUTO SCROLL SCRIPT ---
7879
st.markdown("""

api.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import google.generativeai as genai
2+
genai.configure(api_key="AIzaSyAgtTtPjJzTaNSrXaWFkMEJKIpMiFI3QNw")
3+
model = genai.GenerativeModel("gemini-1.5-flash")
4+
response = model.generate_content("Hello!")
5+
print(response.text)

components/chat_interface.py

Lines changed: 42 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,82 +1,53 @@
11
import streamlit as st
2-
import streamlit.components.v1 as components
3-
from datetime import datetime
4-
from core.utils import get_current_time, get_ai_response, save_conversations
5-
6-
# Inject JS to get user's local time zone
7-
def set_user_time_in_session():
8-
if "user_time_offset" not in st.session_state:
9-
components.html("""
10-
<script>
11-
const offset = new Date().getTimezoneOffset();
12-
const time = new Date().toLocaleString();
13-
const data = {offset: offset, time: time};
14-
window.parent.postMessage({type: 'USER_TIME', data: data}, '*');
15-
</script>
16-
""", height=0)
17-
18-
st.markdown("""
19-
<script>
20-
window.addEventListener("message", (event) => {
21-
if (event.data.type === "USER_TIME") {
22-
const payload = JSON.stringify(event.data.data);
23-
fetch("/", {
24-
method: "POST",
25-
headers: {"Content-Type": "application/json"},
26-
body: payload
27-
}).then(() => location.reload());
28-
}
29-
});
30-
</script>
31-
""", unsafe_allow_html=True)
32-
33-
set_user_time_in_session()
34-
35-
# Display chat messages
36-
def render_chat_interface():
37-
if st.session_state.active_conversation >= 0:
38-
active_convo = st.session_state.conversations[st.session_state.active_conversation]
39-
40-
if not active_convo["messages"]:
41-
st.markdown(f"""
42-
<div class="welcome-message">
43-
<strong>Hello! I'm TalkHeal, your mental health companion 🤗</strong><br>
44-
How are you feeling today? You can write below or start a new topic.
45-
<div class="message-time">{get_current_time()}</div>
46-
</div>
47-
""", unsafe_allow_html=True)
48-
49-
for msg in active_convo["messages"]:
50-
css_class = "user-message" if msg["sender"] == "user" else "bot-message"
51-
st.markdown(f"""
52-
<div class="{css_class}">
53-
{msg["message"]}
54-
<div class="message-time">{msg["time"]}</div>
55-
</div>
56-
""", unsafe_allow_html=True)
57-
58-
# Handle chat input and generate AI response
2+
from core.utils import save_conversations, get_current_time
3+
from core.gemini import get_ai_response
4+
5+
def render_chat_interface():
6+
st.markdown("### 🗨️ TalkHeal Conversation")
7+
8+
active_index = st.session_state.get("active_conversation", -1)
9+
if active_index == -1 or active_index >= len(st.session_state.conversations):
10+
st.info("Start a conversation to see messages here.")
11+
return
12+
13+
conversation = st.session_state.conversations[active_index]
14+
15+
for msg in conversation["messages"]:
16+
sender = msg["sender"]
17+
message = msg["message"]
18+
time = msg["time"]
19+
20+
if sender == "user":
21+
with st.chat_message("user", avatar="🧍‍♀️"):
22+
st.markdown(f"**You:** {message}\n\n<sub>{time}</sub>", unsafe_allow_html=True)
23+
else:
24+
with st.chat_message("assistant", avatar="💬"):
25+
st.markdown(f"{message}\n\n<sub>{time}</sub>", unsafe_allow_html=True)
26+
27+
5928
def handle_chat_input(model, system_prompt):
60-
if "pre_filled_chat_input" not in st.session_state:
61-
st.session_state.pre_filled_chat_input = ""
62-
initial_value = st.session_state.pre_filled_chat_input
29+
pre_filled = st.session_state.get("pre_filled_chat_input", "")
6330
st.session_state.pre_filled_chat_input = ""
6431

65-
with st.form(key="chat_form", clear_on_submit=True):
32+
form_key = f"chat_form_{st.session_state.get('active_conversation', 0)}"
33+
34+
with st.form(key=form_key, clear_on_submit=True):
6635
col1, col2 = st.columns([5, 1])
6736
with col1:
6837
user_input = st.text_input(
6938
"Share your thoughts...",
7039
key="message_input",
7140
label_visibility="collapsed",
7241
placeholder="Type your message here...",
73-
value=initial_value
42+
value=pre_filled
7443
)
7544
with col2:
7645
send_pressed = st.form_submit_button("Send", use_container_width=True)
7746

78-
if (send_pressed or st.session_state.get("send_chat_message", False)) and user_input.strip():
79-
if 'send_chat_message' in st.session_state:
47+
auto_send = st.session_state.get("send_chat_message", False)
48+
49+
if (send_pressed or auto_send) and user_input.strip():
50+
if auto_send:
8051
st.session_state.send_chat_message = False
8152

8253
if st.session_state.active_conversation >= 0:
@@ -90,32 +61,31 @@ def handle_chat_input(model, system_prompt):
9061
"time": current_time
9162
})
9263

93-
# Set title if it's the first message
9464
if len(active_convo["messages"]) == 1:
9565
title = user_input[:30] + "..." if len(user_input) > 30 else user_input
9666
active_convo["title"] = title
9767

9868
save_conversations(st.session_state.conversations)
9969

100-
# Format memory
10170
def format_memory(convo_history, max_turns=10):
10271
context = ""
103-
for msg in convo_history[-max_turns*2:]: # user + bot per turn
72+
for msg in convo_history[-max_turns*2:]:
10473
sender = "User" if msg["sender"] == "user" else "Bot"
10574
context += f"{sender}: {msg['message']}\n"
10675
return context
10776

10877
try:
10978
with st.spinner("TalkHeal is thinking..."):
11079
memory = format_memory(active_convo["messages"])
111-
mood = st.session_state.get("selected_mood", "😊 Happy")
80+
mood = st.session_state.get("selected_mood_context") or st.session_state.get("current_mood_val", "okay")
81+
11282
prompt = (
11383
f"{system_prompt}\n\n"
114-
f"The user is currently feeling: {mood}. Consider this mood while responding empathetically.\n\n"
84+
f"User is feeling {mood}. Respond empathetically.\n\n"
11585
f"{memory}\nUser: {user_input.strip()}\nBot:"
11686
)
11787

118-
ai_response = get_ai_response(prompt, model)
88+
ai_response = get_ai_response(prompt, "gemini-1.5-flash")
11989

12090
active_convo["messages"].append({
12191
"sender": "bot",
@@ -133,3 +103,5 @@ def format_memory(convo_history, max_turns=10):
133103

134104
save_conversations(st.session_state.conversations)
135105
st.rerun()
106+
107+
__all__ = ["render_chat_interface", "handle_chat_input"]

0 commit comments

Comments
 (0)