1
1
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
+
59
28
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" , "" )
63
30
st .session_state .pre_filled_chat_input = ""
64
31
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 ):
66
35
col1 , col2 = st .columns ([5 , 1 ])
67
36
with col1 :
68
37
user_input = st .text_input (
69
38
"Share your thoughts..." ,
70
39
key = "message_input" ,
71
40
label_visibility = "collapsed" ,
72
41
placeholder = "Type your message here..." ,
73
- value = initial_value
42
+ value = pre_filled
74
43
)
75
44
with col2 :
76
45
send_pressed = st .form_submit_button ("Send" , use_container_width = True )
77
46
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 :
80
51
st .session_state .send_chat_message = False
81
52
82
53
if st .session_state .active_conversation >= 0 :
@@ -90,32 +61,31 @@ def handle_chat_input(model, system_prompt):
90
61
"time" : current_time
91
62
})
92
63
93
- # Set title if it's the first message
94
64
if len (active_convo ["messages" ]) == 1 :
95
65
title = user_input [:30 ] + "..." if len (user_input ) > 30 else user_input
96
66
active_convo ["title" ] = title
97
67
98
68
save_conversations (st .session_state .conversations )
99
69
100
- # Format memory
101
70
def format_memory (convo_history , max_turns = 10 ):
102
71
context = ""
103
- for msg in convo_history [- max_turns * 2 :]: # user + bot per turn
72
+ for msg in convo_history [- max_turns * 2 :]:
104
73
sender = "User" if msg ["sender" ] == "user" else "Bot"
105
74
context += f"{ sender } : { msg ['message' ]} \n "
106
75
return context
107
76
108
77
try :
109
78
with st .spinner ("TalkHeal is thinking..." ):
110
79
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
+
112
82
prompt = (
113
83
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 "
115
85
f"{ memory } \n User: { user_input .strip ()} \n Bot:"
116
86
)
117
87
118
- ai_response = get_ai_response (prompt , model )
88
+ ai_response = get_ai_response (prompt , "gemini-1.5-flash" )
119
89
120
90
active_convo ["messages" ].append ({
121
91
"sender" : "bot" ,
@@ -133,3 +103,5 @@ def format_memory(convo_history, max_turns=10):
133
103
134
104
save_conversations (st .session_state .conversations )
135
105
st .rerun ()
106
+
107
+ __all__ = ["render_chat_interface" , "handle_chat_input" ]
0 commit comments