StevesInfinityDrive commited on
Commit
fa66de2
·
verified ·
1 Parent(s): c8b783b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -0
app.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ sys.path.append(os.path.abspath(os.path.dirname(__file__)))
2
+ import sys
3
+ import os
4
+ import json
5
+ import logging
6
+ import uuid
7
+ import streamlit as st
8
+ from src.chatbot import generate_response_with_history, COUNTRY_HELPLINES, get_helpline_for_country
9
+
10
+ # --- Setup ---
11
+ sys.path.append(os.path.abspath("src"))
12
+ logging.basicConfig(filename="safeguard_logs.txt", level=logging.INFO)
13
+ METRICS_FILE = "user_metrics.json"
14
+
15
+ # --- Custom Color Theme (BAC7D8/D75D72/101920) ---
16
+ CUSTOM_CSS = f"""
17
+ <style>
18
+ .stApp {{
19
+ background-color: #101920;
20
+ color: #BAC7D8;
21
+ }}
22
+ .stTextInput, .stSelectbox, .stButton {{
23
+ background-color: #1A242E !important;
24
+ border-color: #D75D72 !important;
25
+ }}
26
+ h1, h2, h3 {{
27
+ color: #D75D72 !important;
28
+ }}
29
+ .stMarkdown {{
30
+ color: #BAC7D8;
31
+ }}
32
+ .stAlert {{
33
+ background-color: #1A242E !important;
34
+ }}
35
+ </style>
36
+ """
37
+ st.markdown(CUSTOM_CSS, unsafe_allow_html=True)
38
+
39
+ # --- Initialize Session State ---
40
+ def init_session():
41
+ if "metrics" not in st.session_state:
42
+ st.session_state.metrics = load_metrics()
43
+ if "session_id" not in st.session_state:
44
+ st.session_state.session_id = str(uuid.uuid4())[:8]
45
+ if "chat_history" not in st.session_state:
46
+ st.session_state.chat_history = []
47
+
48
+ # --- Data Handling ---
49
+ def load_metrics():
50
+ if os.path.exists(METRICS_FILE):
51
+ try:
52
+ with open(METRICS_FILE, "r") as f:
53
+ return json.load(f)
54
+ except Exception as e:
55
+ st.error(f"Error loading metrics: {e}")
56
+ return {"sessions": [], "feedback": {"thumbs_up": 0, "thumbs_down": 0}, "harmful_content": []}
57
+
58
+ def save_metrics():
59
+ try:
60
+ with open(METRICS_FILE, "w") as f:
61
+ json.dump(st.session_state.metrics, f, indent=4)
62
+ except Exception as e:
63
+ st.error(f"Error saving metrics: {e}")
64
+
65
+ # --- UI Components ---
66
+ def render_chat_message(role, content):
67
+ with st.chat_message(role):
68
+ st.markdown(f"**{'You' if role == 'user' else 'Bot'}:** {content}")
69
+
70
+ def render_helpline():
71
+ with st.sidebar:
72
+ st.subheader("🌍 Country Support")
73
+ selected_country = st.selectbox(
74
+ "Select your country:",
75
+ options=list(COUNTRY_HELPLINES.keys()),
76
+ index=0
77
+ )
78
+ st.markdown(f"**📞 {selected_country} Helpline:** \n{get_helpline_for_country(selected_country)}")
79
+
80
+ # --- Main App ---
81
+ def main():
82
+ st.title("JoyCloud Mental Health Assistant 🧠")
83
+ st.markdown("---")
84
+
85
+ # Sidebar Components
86
+ with st.sidebar:
87
+ st.markdown("### Session Info")
88
+ st.write(f"Session ID: `{st.session_state.session_id}`")
89
+ st.markdown("---")
90
+ st.markdown("**Disclaimer:** \nThis is a prototype chatbot. For emergencies, contact a professional.")
91
+
92
+ # Main Chat Interface
93
+ render_helpline()
94
+
95
+ # Chat History Display
96
+ for msg in st.session_state.chat_history:
97
+ render_chat_message(msg["role"], msg["content"])
98
+
99
+ # User Input
100
+ prompt = st.chat_input("Type your message...")
101
+ if prompt:
102
+ try:
103
+ # Append user message
104
+ st.session_state.chat_history.append({"role": "user", "content": prompt})
105
+ render_chat_message("user", prompt)
106
+
107
+ # Generate response
108
+ with st.spinner("Thinking..."):
109
+ response = generate_response_with_history(
110
+ st.session_state.chat_history,
111
+ st.session_state.selected_country
112
+ )
113
+
114
+ # Append bot response
115
+ st.session_state.chat_history.append({"role": "bot", "content": response})
116
+ render_chat_message("bot", response)
117
+
118
+ except Exception as e:
119
+ st.error(f"Error generating response: {e}")
120
+ logging.error(f"Session {st.session_state.session_id}: {str(e)}")
121
+
122
+ # Feedback System (Floating at Bottom)
123
+ st.markdown("---")
124
+ col1, col2 = st.columns(2)
125
+ with col1:
126
+ if st.button("👍 Helpful", use_container_width=True, type="primary"):
127
+ st.session_state.metrics["feedback"]["thumbs_up"] += 1
128
+ save_metrics()
129
+ st.toast("Thank you for your feedback!")
130
+ with col2:
131
+ if st.button("👎 Needs Improvement", use_container_width=True, type="secondary"):
132
+ st.session_state.metrics["feedback"]["thumbs_down"] += 1
133
+ save_metrics()
134
+ st.toast("We'll use this to improve!")
135
+
136
+ # --- Run App ---
137
+ if __name__ == "__main__":
138
+ init_session()
139
+ main()