Johan713 commited on
Commit
3ffdcf5
Β·
verified Β·
1 Parent(s): ade39be

Update pages/ai_buddy.py

Browse files
Files changed (1) hide show
  1. pages/ai_buddy.py +423 -367
pages/ai_buddy.py CHANGED
@@ -1,368 +1,424 @@
1
- import streamlit as st
2
- import random
3
- from langchain.chat_models import ChatOpenAI
4
- from langchain.schema import HumanMessage, SystemMessage
5
- import os
6
- from dotenv import load_dotenv
7
- import pandas as pd
8
- from datetime import datetime
9
- import plotly.express as px
10
- import json
11
- import speech_recognition as sr
12
- from gtts import gTTS
13
- import pygame
14
- from io import BytesIO
15
-
16
- # Load environment variables
17
- load_dotenv()
18
-
19
- AI71_BASE_URL = "https://api.ai71.ai/v1/"
20
- AI71_API_KEY = "api71-api-92fc2ef9-9f3c-47e5-a019-18e257b04af2"
21
-
22
- # Initialize the Falcon model
23
- chat = ChatOpenAI(
24
- model="tiiuae/falcon-180B-chat",
25
- api_key=AI71_API_KEY,
26
- base_url=AI71_BASE_URL,
27
- streaming=True,
28
- )
29
-
30
- # Expanded Therapy techniques
31
- THERAPY_TECHNIQUES = {
32
- "CBT": "Use Cognitive Behavioral Therapy techniques to help the user identify and change negative thought patterns.",
33
- "Mindfulness": "Guide the user through mindfulness exercises to promote present-moment awareness and reduce stress.",
34
- "Solution-Focused": "Focus on the user's strengths and resources to help them find solutions to their problems.",
35
- "Emotion-Focused": "Help the user identify, experience, and regulate their emotions more effectively.",
36
- "Psychodynamic": "Explore the user's past experiences and unconscious patterns to gain insight into current issues.",
37
- "ACT": "Use Acceptance and Commitment Therapy to help the user accept their thoughts and feelings while committing to positive changes.",
38
- "DBT": "Apply Dialectical Behavior Therapy techniques to help the user manage intense emotions and improve relationships.",
39
- "Gestalt": "Use Gestalt therapy techniques to focus on the present moment and increase self-awareness.",
40
- "Existential": "Explore existential themes such as meaning, freedom, and responsibility to help the user find purpose.",
41
- "Narrative": "Use storytelling and narrative techniques to help the user reframe their life experiences and create new meaning.",
42
- }
43
-
44
- def get_ai_response(user_input, buddy_config, therapy_technique=None):
45
- system_message = f"You are {buddy_config['name']}, an AI companion with the following personality: {buddy_config['personality']}. "
46
- system_message += f"Additional details about you: {buddy_config['details']}. "
47
-
48
- if therapy_technique:
49
- system_message += f"In this conversation, {THERAPY_TECHNIQUES[therapy_technique]}"
50
-
51
- messages = [
52
- SystemMessage(content=system_message),
53
- HumanMessage(content=user_input)
54
- ]
55
- response = chat.invoke(messages).content
56
- return response
57
-
58
- def show_progress_dashboard():
59
- st.subheader("Your Progress Dashboard")
60
-
61
- # Placeholder data for demonstration
62
- mood_logs = [{"date": "2023-08-01", "mood": 7}, {"date": "2023-08-02", "mood": 8}, {"date": "2023-08-03", "mood": 6}]
63
-
64
- # Mood trend
65
- if mood_logs:
66
- df = pd.DataFrame(mood_logs)
67
- fig = px.line(df, x="date", y="mood", title="Mood Trend")
68
- st.plotly_chart(fig)
69
- else:
70
- st.info("No mood data available yet. Start logging your mood!")
71
-
72
- # Journal entries
73
- st.subheader("Recent Journal Entries")
74
- journal_entries = [
75
- {"date": "2023-08-03", "entry": "Had a productive day at work..."},
76
- {"date": "2023-08-02", "entry": "Feeling a bit stressed about..."},
77
- {"date": "2023-08-01", "entry": "Started a new book today..."}
78
- ]
79
- for entry in journal_entries[-5:]:
80
- st.text(f"{entry['date']}: {entry['entry'][:50]}...")
81
-
82
- # Goals progress
83
- st.subheader("Goals Progress")
84
- goals = [
85
- {"description": "Exercise 3 times a week", "progress": 60},
86
- {"description": "Read 2 books this month", "progress": 75},
87
- {"description": "Learn Python programming", "progress": 40}
88
- ]
89
- for goal in goals:
90
- st.progress(goal['progress'])
91
- st.text(f"{goal['description']}: {goal['progress']}% complete")
92
-
93
- def show_goal_setting_interface():
94
- st.subheader("Set Your Goals")
95
- goal_description = st.text_input("Describe your goal")
96
- goal_progress = st.slider("Initial progress", 0, 100, 0)
97
-
98
- if st.button("Add Goal"):
99
- st.success("Goal added successfully!")
100
-
101
- def show_meditation_timer():
102
- st.subheader("Meditation Timer")
103
- duration = st.slider("Select duration (minutes)", 1, 60, 5)
104
- if st.button("Start Meditation"):
105
- progress_bar = st.progress(0)
106
- for i in range(duration * 60):
107
- progress_bar.progress((i + 1) / (duration * 60))
108
- st.empty().text(f"Time remaining: {duration - (i // 60)}:{59 - (i % 60):02d}")
109
- time.sleep(1)
110
- st.success("Meditation complete!")
111
-
112
- def show_community_forum():
113
- st.subheader("Community Forum")
114
- st.warning("This feature is not yet implemented. Check back soon!")
115
-
116
- def show_personalized_recommendations():
117
- st.subheader("Personalized Recommendations")
118
-
119
- # Placeholder for demonstration
120
- avg_mood = 6
121
-
122
- if avg_mood < 4:
123
- st.markdown("Based on your recent mood, we recommend:")
124
- st.markdown("- Practice daily gratitude journaling")
125
- st.markdown("- Try a guided meditation for stress relief")
126
- st.markdown("- Read 'The Happiness Trap' by Russ Harris")
127
- elif avg_mood < 7:
128
- st.markdown("To maintain and improve your mood, consider:")
129
- st.markdown("- Start a new hobby or learn a new skill")
130
- st.markdown("- Practice mindfulness meditation")
131
- st.markdown("- Read 'Atomic Habits' by James Clear")
132
- else:
133
- st.markdown("Great job maintaining a positive mood! To keep it up:")
134
- st.markdown("- Share your positivity with others")
135
- st.markdown("- Set ambitious goals for personal growth")
136
- st.markdown("- Read 'Flow' by Mihaly Csikszentmihalyi")
137
-
138
- def start_voice_interaction():
139
- st.subheader("Voice Interaction")
140
- if st.button("Start Voice Recognition"):
141
- r = sr.Recognizer()
142
- with sr.Microphone() as source:
143
- st.info("Listening... Speak now!")
144
- audio = r.listen(source)
145
- try:
146
- text = r.recognize_google(audio)
147
- st.success(f"You said: {text}")
148
-
149
- # Get AI response
150
- buddy_config = {
151
- "name": st.session_state.buddy_name,
152
- "personality": st.session_state.buddy_personality,
153
- "details": st.session_state.buddy_details
154
- }
155
- response = get_ai_response(text, buddy_config)
156
-
157
- # Convert response to speech
158
- tts = gTTS(text=response, lang='en')
159
- fp = BytesIO()
160
- tts.write_to_fp(fp)
161
- fp.seek(0)
162
-
163
- # Play the response
164
- pygame.mixer.init()
165
- pygame.mixer.music.load(fp)
166
- pygame.mixer.music.play()
167
- while pygame.mixer.music.get_busy():
168
- pygame.time.Clock().tick(10)
169
-
170
- st.success(f"AI response: {response}")
171
- except sr.UnknownValueError:
172
- st.error("Sorry, I couldn't understand what you said.")
173
- except sr.RequestError as e:
174
- st.error(f"Could not request results; {e}")
175
-
176
- def show_daily_challenge():
177
- st.subheader("Daily Personal Growth Challenge")
178
- challenges = [
179
- "Write down three things you're grateful for today.",
180
- "Reach out to a friend or family member you haven't spoken to in a while.",
181
- "Try a new healthy recipe for dinner tonight.",
182
- "Take a 15-minute walk in nature and practice mindfulness.",
183
- "Learn five new words in a language you're interested in.",
184
- "Declutter one area of your living space.",
185
- "Practice active listening in your next conversation.",
186
- "Try a new form of exercise or physical activity.",
187
- "Write a short story or poem expressing your current emotions.",
188
- "Perform a random act of kindness for someone."
189
- ]
190
-
191
- if 'daily_challenge' not in st.session_state:
192
- st.session_state.daily_challenge = random.choice(challenges)
193
-
194
- st.info(f"Your challenge for today: {st.session_state.daily_challenge}")
195
-
196
- if st.button("Complete Challenge"):
197
- st.success("Great job completing today's challenge! Keep up the good work.")
198
- st.session_state.daily_challenge = random.choice(challenges)
199
-
200
- def show_therapist_scheduling_interface():
201
- st.subheader("Schedule a Video Therapy Session")
202
- st.warning("This feature would integrate with a real therapist booking system. For demonstration purposes, we'll use a simplified version.")
203
-
204
- therapists = ["Dr. Smith", "Dr. Johnson", "Dr. Williams", "Dr. Brown"]
205
- selected_therapist = st.selectbox("Choose a therapist", therapists)
206
-
207
- date = st.date_input("Select a date")
208
- time = st.time_input("Select a time")
209
-
210
- if st.button("Schedule Session"):
211
- st.success(f"Session scheduled with {selected_therapist} on {date} at {time}. You will receive a confirmation email with further details.")
212
-
213
- def main():
214
- st.set_page_config(page_title="S.H.E.R.L.O.C.K. AI Buddy", page_icon="πŸ•΅οΈ", layout="wide")
215
-
216
- # Custom CSS for improved styling
217
- st.markdown("""
218
- <style>
219
- .stApp {
220
- background-color: #f0f2f6;
221
- }
222
- .stButton>button {
223
- background-color: #4CAF50;
224
- color: white;
225
- font-weight: bold;
226
- }
227
- .stTextInput>div>div>input {
228
- background-color: #ffffff;
229
- }
230
- </style>
231
- """, unsafe_allow_html=True)
232
-
233
- st.title("πŸ•΅οΈ S.H.E.R.L.O.C.K. AI Buddy")
234
- st.markdown("Your personalized AI companion for conversation, therapy, and personal growth.")
235
-
236
- # Initialize session state
237
- if 'buddy_name' not in st.session_state:
238
- st.session_state.buddy_name = "Sherlock"
239
- if 'buddy_personality' not in st.session_state:
240
- st.session_state.buddy_personality = "Friendly, empathetic, and insightful"
241
- if 'buddy_details' not in st.session_state:
242
- st.session_state.buddy_details = "Knowledgeable about various therapy techniques and always ready to listen"
243
- if 'messages' not in st.session_state:
244
- st.session_state.messages = []
245
-
246
- # Sidebar for AI Buddy configuration
247
- with st.sidebar:
248
- st.header("πŸ€– Configure Your AI Buddy")
249
- st.session_state.buddy_name = st.text_input("Name your AI Buddy", value=st.session_state.buddy_name)
250
- st.session_state.buddy_personality = st.text_area("Describe your buddy's personality", value=st.session_state.buddy_personality)
251
- st.session_state.buddy_details = st.text_area("Additional details about your buddy", value=st.session_state.buddy_details)
252
-
253
- st.header("🧘 Therapy Session")
254
- therapy_mode = st.checkbox("Enable Therapy Mode")
255
- if therapy_mode:
256
- therapy_technique = st.selectbox("Select Therapy Technique", list(THERAPY_TECHNIQUES.keys()))
257
- else:
258
- therapy_technique = None
259
-
260
- st.markdown("---")
261
- st.markdown("Powered by Falcon-180B and Streamlit")
262
-
263
- # Main content area
264
- tab1, tab2, tab3, tab4, tab5 = st.tabs(["Chat", "Progress", "Goals", "Community", "Tools"])
265
-
266
- with tab1:
267
- # Chat interface
268
- st.header("πŸ—¨οΈ Chat with Your AI Buddy")
269
- chat_container = st.container()
270
- with chat_container:
271
- for message in st.session_state.messages[-5:]: # Display last 5 messages
272
- with st.chat_message(message["role"]):
273
- st.markdown(message["content"])
274
-
275
- # User input
276
- if prompt := st.chat_input("What's on your mind?"):
277
- st.session_state.messages.append({"role": "user", "content": prompt})
278
- with st.chat_message("user"):
279
- st.markdown(prompt)
280
-
281
- buddy_config = {
282
- "name": st.session_state.buddy_name,
283
- "personality": st.session_state.buddy_personality,
284
- "details": st.session_state.buddy_details
285
- }
286
-
287
- with st.chat_message("assistant"):
288
- message_placeholder = st.empty()
289
- full_response = ""
290
- for chunk in chat.stream(get_ai_response(prompt, buddy_config, therapy_technique)):
291
- full_response += chunk.content
292
- message_placeholder.markdown(full_response + "β–Œ")
293
- message_placeholder.markdown(full_response)
294
- st.session_state.messages.append({"role": "assistant", "content": full_response})
295
-
296
- with tab2:
297
- show_progress_dashboard()
298
-
299
- with tab3:
300
- show_goal_setting_interface()
301
-
302
- with tab4:
303
- show_community_forum()
304
-
305
- with tab5:
306
- tool_choice = st.selectbox("Select a tool", ["Meditation Timer", "Recommendations", "Voice Interaction", "Daily Challenge", "Schedule Therapy"])
307
- if tool_choice == "Meditation Timer":
308
- show_meditation_timer()
309
- elif tool_choice == "Recommendations":
310
- show_personalized_recommendations()
311
- elif tool_choice == "Voice Interaction":
312
- start_voice_interaction()
313
- elif tool_choice == "Daily Challenge":
314
- show_daily_challenge()
315
- elif tool_choice == "Schedule Therapy":
316
- show_therapist_scheduling_interface()
317
-
318
- # Mood tracker
319
- st.sidebar.markdown("---")
320
- st.sidebar.header("😊 Mood Tracker")
321
- mood = st.sidebar.slider("How are you feeling today?", 1, 10, 5)
322
- if st.sidebar.button("Log Mood"):
323
- st.sidebar.success(f"Mood logged: {mood}/10")
324
- st.balloons()
325
-
326
- # Journaling feature
327
- st.sidebar.markdown("---")
328
- st.sidebar.header("πŸ“” Daily Journal")
329
- journal_entry = st.sidebar.text_area("Write your thoughts for today")
330
- if st.sidebar.button("Save Journal Entry"):
331
- st.sidebar.success("Journal entry saved!")
332
- st.toast("Journal entry saved successfully!", icon="βœ…")
333
-
334
- # Resources and Emergency Contact
335
- st.sidebar.markdown("---")
336
- st.sidebar.header("πŸ†˜ Resources")
337
- st.sidebar.info("If you're in crisis, please reach out for help:")
338
- st.sidebar.markdown("- [Mental Health Resources](https://www.mentalhealth.gov/get-help/immediate-help)")
339
- st.sidebar.markdown("- Emergency Contact: 911 or your local emergency number")
340
-
341
- # Inspiration Quote
342
- st.sidebar.markdown("---")
343
- st.sidebar.header("πŸ’‘ Daily Inspiration")
344
- if st.sidebar.button("Get Inspirational Quote"):
345
- quotes = [
346
- "The only way to do great work is to love what you do. - Steve Jobs",
347
- "Believe you can and you're halfway there. - Theodore Roosevelt",
348
- "The future belongs to those who believe in the beauty of their dreams. - Eleanor Roosevelt",
349
- "Strive not to be a success, but rather to be of value. - Albert Einstein",
350
- "The only limit to our realization of tomorrow will be our doubts of today. - Franklin D. Roosevelt"
351
- ]
352
- random_quote = random.choice(quotes)
353
- st.sidebar.success(random_quote)
354
-
355
- # Chat Export
356
- st.sidebar.markdown("---")
357
- if st.sidebar.button("Export Chat History"):
358
- chat_history = "\n".join([f"{msg['role']}: {msg['content']}" for msg in st.session_state.messages])
359
- st.sidebar.download_button(
360
- label="Download Chat History",
361
- data=chat_history,
362
- file_name="ai_buddy_chat_history.txt",
363
- mime="text/plain"
364
- )
365
- st.sidebar.success("Chat history ready for download!")
366
-
367
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
  main()
 
1
+ import streamlit as st
2
+ import random
3
+ from langchain.chat_models import ChatOpenAI
4
+ from langchain.schema import HumanMessage, SystemMessage
5
+ import os
6
+ from dotenv import load_dotenv
7
+ import pandas as pd
8
+ from datetime import datetime
9
+ import plotly.express as px
10
+ import json
11
+ import time
12
+ from playsound import playsound
13
+
14
+ # Load environment variables
15
+ load_dotenv()
16
+
17
+ AI71_BASE_URL = "https://api.ai71.ai/v1/"
18
+ AI71_API_KEY = "api71-api-92fc2ef9-9f3c-47e5-a019-18e257b04af2"
19
+
20
+ # Initialize the Falcon model
21
+ chat = ChatOpenAI(
22
+ model="tiiuae/falcon-180B-chat",
23
+ api_key=AI71_API_KEY,
24
+ base_url=AI71_BASE_URL,
25
+ streaming=True,
26
+ )
27
+
28
+ # Expanded Therapy techniques
29
+ THERAPY_TECHNIQUES = {
30
+ "CBT": "Use Cognitive Behavioral Therapy techniques to help the user identify and change negative thought patterns.",
31
+ "Mindfulness": "Guide the user through mindfulness exercises to promote present-moment awareness and reduce stress.",
32
+ "Solution-Focused": "Focus on the user's strengths and resources to help them find solutions to their problems.",
33
+ "Emotion-Focused": "Help the user identify, experience, and regulate their emotions more effectively.",
34
+ "Psychodynamic": "Explore the user's past experiences and unconscious patterns to gain insight into current issues.",
35
+ "ACT": "Use Acceptance and Commitment Therapy to help the user accept their thoughts and feelings while committing to positive changes.",
36
+ "DBT": "Apply Dialectical Behavior Therapy techniques to help the user manage intense emotions and improve relationships.",
37
+ "Gestalt": "Use Gestalt therapy techniques to focus on the present moment and increase self-awareness.",
38
+ "Existential": "Explore existential themes such as meaning, freedom, and responsibility to help the user find purpose.",
39
+ "Narrative": "Use storytelling and narrative techniques to help the user reframe their life experiences and create new meaning.",
40
+ }
41
+
42
+ def get_ai_response(user_input, buddy_config, therapy_technique=None):
43
+ system_message = f"You are {buddy_config['name']}, an AI companion with the following personality: {buddy_config['personality']}. "
44
+ system_message += f"Additional details about you: {buddy_config['details']}. "
45
+
46
+ if therapy_technique:
47
+ system_message += f"In this conversation, {THERAPY_TECHNIQUES[therapy_technique]}"
48
+
49
+ messages = [
50
+ SystemMessage(content=system_message),
51
+ HumanMessage(content=user_input)
52
+ ]
53
+ response = chat.invoke(messages).content
54
+ return response
55
+
56
+ def show_meditation_timer():
57
+ st.subheader("πŸ§˜β€β™€οΈ Enhanced Meditation Timer")
58
+ col1, col2 = st.columns(2)
59
+
60
+ with col1:
61
+ duration = st.slider("Select duration (minutes)", 1, 60, 5)
62
+ background_options = ["Forest", "Beach", "Rain", "White Noise"]
63
+ background_sound = st.selectbox("Background Sound", background_options)
64
+
65
+ with col2:
66
+ interval_options = ["None", "Every 5 minutes", "Every 10 minutes"]
67
+ interval_reminder = st.selectbox("Interval Reminders", interval_options)
68
+ end_sound_options = ["Gentle Chime", "Tibetan Singing Bowl", "Ocean Wave"]
69
+ end_sound = st.selectbox("End of Session Sound", end_sound_options)
70
+
71
+ if st.button("Start Meditation", key="start_meditation"):
72
+ progress_bar = st.progress(0)
73
+ status_text = st.empty()
74
+
75
+ # Play background sound
76
+ background_sound_file = f"sounds/{background_sound.lower().replace(' ', '_')}.mp3"
77
+ playsound(background_sound_file, block=False)
78
+
79
+ for i in range(duration * 60):
80
+ progress_bar.progress((i + 1) / (duration * 60))
81
+ mins, secs = divmod(duration * 60 - i - 1, 60)
82
+ status_text.text(f"Time remaining: {mins:02d}:{secs:02d}")
83
+
84
+ if interval_reminder != "None":
85
+ interval = 5 if interval_reminder == "Every 5 minutes" else 10
86
+ if i > 0 and i % (interval * 60) == 0:
87
+ st.toast(f"{interval} minutes passed", icon="⏰")
88
+
89
+ time.sleep(1)
90
+
91
+ # Stop background sound (you may need to implement this depending on how playsound works)
92
+ # stop_sound(background_sound_file)
93
+
94
+ st.success("Meditation complete!")
95
+ st.balloons()
96
+
97
+ # Play end of session sound
98
+ end_sound_file = f"sounds/{end_sound.lower().replace(' ', '_')}.mp3"
99
+ playsound(end_sound_file)
100
+
101
+ if 'achievements' not in st.session_state:
102
+ st.session_state.achievements = set()
103
+ st.session_state.achievements.add("Zen Master")
104
+ st.success("Achievement Unlocked: Zen Master πŸ§˜β€β™€οΈ")
105
+
106
+ def show_personalized_recommendations():
107
+ st.subheader("🎯 Personalized Recommendations")
108
+
109
+ recommendation_categories = [
110
+ "Mental Health",
111
+ "Physical Health",
112
+ "Personal Development",
113
+ "Relationships",
114
+ "Career",
115
+ "Hobbies",
116
+ ]
117
+
118
+ selected_category = st.selectbox("Choose a category", recommendation_categories)
119
+
120
+ recommendations = {
121
+ "Mental Health": [
122
+ "Practice daily gratitude journaling",
123
+ "Try a guided meditation for stress relief",
124
+ "Explore cognitive behavioral therapy techniques",
125
+ "Start a mood tracking journal",
126
+ "Learn about mindfulness practices",
127
+ ],
128
+ "Physical Health": [
129
+ "Start a 30-day yoga challenge",
130
+ "Try intermittent fasting",
131
+ "Begin a couch to 5K running program",
132
+ "Experiment with new healthy recipes",
133
+ "Create a sleep hygiene routine",
134
+ ],
135
+ "Personal Development": [
136
+ "Start learning a new language",
137
+ "Read personal development books",
138
+ "Take an online course in a subject you're interested in",
139
+ "Practice public speaking",
140
+ "Start a daily writing habit",
141
+ ],
142
+ "Relationships": [
143
+ "Practice active listening techniques",
144
+ "Plan regular date nights or friend meetups",
145
+ "Learn about love languages",
146
+ "Practice expressing gratitude to loved ones",
147
+ "Join a local community or interest group",
148
+ ],
149
+ "Career": [
150
+ "Update your resume and LinkedIn profile",
151
+ "Network with professionals in your industry",
152
+ "Set SMART career goals",
153
+ "Learn a new skill relevant to your field",
154
+ "Start a side project or freelance work",
155
+ ],
156
+ "Hobbies": [
157
+ "Start a garden or learn about plant care",
158
+ "Try a new art form like painting or sculpting",
159
+ "Learn to play a musical instrument",
160
+ "Start a DIY home improvement project",
161
+ "Explore photography or videography",
162
+ ],
163
+ }
164
+
165
+ st.write("Here are some personalized recommendations for you:")
166
+ for recommendation in recommendations[selected_category]:
167
+ st.markdown(f"- {recommendation}")
168
+
169
+ if st.button("Get More Recommendations"):
170
+ st.write("More tailored recommendations:")
171
+ additional_recs = random.sample(recommendations[selected_category], 3)
172
+ for rec in additional_recs:
173
+ st.markdown(f"- {rec}")
174
+
175
+ def main():
176
+ st.set_page_config(page_title="S.H.E.R.L.O.C.K. AI Buddy", page_icon="πŸ•΅οΈ", layout="wide")
177
+
178
+ # Custom CSS for improved styling
179
+ st.markdown("""
180
+ <style>
181
+ .stApp {
182
+ background-color: #f0f2f6;
183
+ }
184
+ .stButton>button {
185
+ background-color: #4CAF50;
186
+ color: white;
187
+ font-weight: bold;
188
+ }
189
+ .stTextInput>div>div>input {
190
+ background-color: #ffffff;
191
+ }
192
+ </style>
193
+ """, unsafe_allow_html=True)
194
+
195
+ st.title("πŸ•΅οΈ S.H.E.R.L.O.C.K. AI Buddy")
196
+ st.markdown("Your personalized AI companion for conversation, therapy, and personal growth.")
197
+
198
+ # Initialize session state
199
+ if 'buddy_name' not in st.session_state:
200
+ st.session_state.buddy_name = "Sherlock"
201
+ if 'buddy_personality' not in st.session_state:
202
+ st.session_state.buddy_personality = "Friendly, empathetic, and insightful"
203
+ if 'buddy_details' not in st.session_state:
204
+ st.session_state.buddy_details = "Knowledgeable about various therapy techniques and always ready to listen"
205
+ if 'messages' not in st.session_state:
206
+ st.session_state.messages = []
207
+
208
+ # Sidebar for AI Buddy configuration and additional features
209
+ with st.sidebar:
210
+ st.header("πŸ€– Configure Your AI Buddy")
211
+ st.session_state.buddy_name = st.text_input("Name your AI Buddy", value=st.session_state.buddy_name)
212
+ st.session_state.buddy_personality = st.text_area("Describe your buddy's personality", value=st.session_state.buddy_personality)
213
+ st.session_state.buddy_details = st.text_area("Additional details about your buddy", value=st.session_state.buddy_details)
214
+
215
+ st.header("🧘 Therapy Session")
216
+ therapy_mode = st.checkbox("Enable Therapy Mode")
217
+ if therapy_mode:
218
+ therapy_technique = st.selectbox("Select Therapy Technique", list(THERAPY_TECHNIQUES.keys()))
219
+ else:
220
+ therapy_technique = None
221
+
222
+ st.markdown("---")
223
+
224
+ st.subheader("πŸ“‹ Todo List")
225
+ if 'todos' not in st.session_state:
226
+ st.session_state.todos = []
227
+
228
+ new_todo = st.text_input("Add a new todo:")
229
+ if st.button("Add Todo", key="add_todo"):
230
+ if new_todo:
231
+ st.session_state.todos.append({"task": new_todo, "completed": False})
232
+ st.success("Todo added successfully!")
233
+ else:
234
+ st.warning("Please enter a todo item.")
235
+
236
+ for i, todo in enumerate(st.session_state.todos):
237
+ col1, col2, col3 = st.columns([0.05, 0.8, 0.15])
238
+ with col1:
239
+ todo['completed'] = st.checkbox("", todo['completed'], key=f"todo_{i}")
240
+ with col2:
241
+ st.write(todo['task'], key=f"todo_text_{i}")
242
+ with col3:
243
+ if st.button("πŸ—‘οΈ", key=f"delete_{i}", help="Delete todo"):
244
+ st.session_state.todos.pop(i)
245
+ st.experimental_rerun()
246
+
247
+ st.subheader("⏱️ Pomodoro Timer")
248
+ pomodoro_duration = st.slider("Pomodoro Duration (minutes)", 1, 60, 25)
249
+ if st.button("Start Pomodoro"):
250
+ progress_bar = st.progress(0)
251
+ for i in range(pomodoro_duration * 60):
252
+ time.sleep(1)
253
+ progress_bar.progress((i + 1) / (pomodoro_duration * 60))
254
+ st.success("Pomodoro completed!")
255
+ if 'achievements' not in st.session_state:
256
+ st.session_state.achievements = set()
257
+ st.session_state.achievements.add("Consistent Learner")
258
+
259
+ st.markdown("---")
260
+ st.markdown("Powered by Falcon-180B and Streamlit")
261
+
262
+ st.markdown("---")
263
+ st.header("πŸ“” Daily Journal")
264
+ journal_entry = st.text_area("Write your thoughts for today")
265
+ if st.button("Save Journal Entry"):
266
+ if 'journal_entries' not in st.session_state:
267
+ st.session_state.journal_entries = []
268
+ st.session_state.journal_entries.append({
269
+ 'date': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
270
+ 'entry': journal_entry
271
+ })
272
+ st.success("Journal entry saved!")
273
+ st.toast("Journal entry saved successfully!", icon="βœ…")
274
+
275
+ if 'journal_entries' in st.session_state and st.session_state.journal_entries:
276
+ st.subheader("Previous Entries")
277
+ for entry in st.session_state.journal_entries[-5:]: # Show last 5 entries
278
+ st.text(entry['date'])
279
+ st.write(entry['entry'])
280
+ st.markdown("---")
281
+
282
+ # Main content area
283
+ tab1, tab2 = st.tabs(["Chat", "Tools"])
284
+
285
+ with tab1:
286
+ # Chat interface
287
+ st.header("πŸ—¨οΈ Chat with Your AI Buddy")
288
+
289
+ # Display chat history
290
+ chat_container = st.container()
291
+ with chat_container:
292
+ for message in st.session_state.messages:
293
+ with st.chat_message(message["role"]):
294
+ st.markdown(message["content"])
295
+
296
+ # Clear chat history button
297
+ if st.button("Clear Chat History"):
298
+ st.session_state.messages = []
299
+ st.experimental_rerun()
300
+
301
+ # User input
302
+ if prompt := st.chat_input("What's on your mind?"):
303
+ st.session_state.messages.append({"role": "user", "content": prompt})
304
+ with st.chat_message("user"):
305
+ st.markdown(prompt)
306
+
307
+ buddy_config = {
308
+ "name": st.session_state.buddy_name,
309
+ "personality": st.session_state.buddy_personality,
310
+ "details": st.session_state.buddy_details
311
+ }
312
+
313
+ with st.chat_message("assistant"):
314
+ message_placeholder = st.empty()
315
+ full_response = ""
316
+ for chunk in chat.stream(get_ai_response(prompt, buddy_config, therapy_technique)):
317
+ full_response += chunk.content
318
+ message_placeholder.markdown(full_response + "β–Œ")
319
+ message_placeholder.markdown(full_response)
320
+ st.session_state.messages.append({"role": "assistant", "content": full_response})
321
+
322
+ with tab2:
323
+ tool_choice = st.selectbox("Select a tool", ["Meditation Timer", "Recommendations"])
324
+ if tool_choice == "Meditation Timer":
325
+ show_meditation_timer()
326
+ elif tool_choice == "Recommendations":
327
+ show_personalized_recommendations()
328
+
329
+ # Mood tracker
330
+ st.sidebar.markdown("---")
331
+ st.sidebar.header("😊 Mood Tracker")
332
+ mood = st.sidebar.slider("How are you feeling today?", 1, 10, 5)
333
+ if st.sidebar.button("Log Mood"):
334
+ st.sidebar.success(f"Mood logged: {mood}/10")
335
+ st.balloons()
336
+
337
+ # Resources and Emergency Contact
338
+ st.sidebar.markdown("---")
339
+ st.sidebar.header("πŸ†˜ Resources")
340
+ st.sidebar.info("If you're in crisis, please reach out for help:")
341
+ st.sidebar.markdown("- [Mental Health Resources](https://www.mentalhealth.gov/get-help/immediate-help)")
342
+ st.sidebar.markdown("- Emergency Contact: 911 or your local emergency number")
343
+
344
+ # Inspiration Quote
345
+ st.sidebar.markdown("---")
346
+ st.sidebar.header("πŸ’‘ Daily Inspiration")
347
+ if st.sidebar.button("Get Inspirational Quote"):
348
+ quotes = [
349
+ "The only way to do great work is to love what you do. - Steve Jobs",
350
+ "Believe you can and you're halfway there. - Theodore Roosevelt",
351
+ "The future belongs to those who believe in the beauty of their dreams. - Eleanor Roosevelt",
352
+ "Strive not to be a success, but rather to be of value. - Albert Einstein",
353
+ "The only limit to our realization of tomorrow will be our doubts of today. - Franklin D. Roosevelt",
354
+ "Do not wait to strike till the iron is hot; but make it hot by striking. - William Butler Yeats",
355
+ "What lies behind us and what lies before us are tiny matters compared to what lies within us. - Ralph Waldo Emerson",
356
+ "Success is not final, failure is not fatal: It is the courage to continue that counts. - Winston Churchill",
357
+ "Life is what happens when you're busy making other plans. - John Lennon",
358
+ "You miss 100% of the shots you don't take. - Wayne Gretzky",
359
+ "The best way to predict the future is to create it. - Peter Drucker",
360
+ "It is not the strongest of the species that survive, nor the most intelligent, but the one most responsive to change. - Charles Darwin",
361
+ "Whether you think you can or you think you can't, you're right. - Henry Ford",
362
+ "The only place where success comes before work is in the dictionary. - Vidal Sassoon",
363
+ "Do what you can, with what you have, where you are. - Theodore Roosevelt",
364
+ "The purpose of our lives is to be happy. - Dalai Lama",
365
+ "Success usually comes to those who are too busy to be looking for it. - Henry David Thoreau",
366
+ "Your time is limited, so don't waste it living someone else's life. - Steve Jobs",
367
+ "Don't be afraid to give up the good to go for the great. - John D. Rockefeller",
368
+ "I find that the harder I work, the more luck I seem to have. - Thomas Jefferson",
369
+ "Success is not the key to happiness. Happiness is the key to success. - Albert Schweitzer",
370
+ "It does not matter how slowly you go, as long as you do not stop. - Confucius",
371
+ "If you set your goals ridiculously high and it's a failure, you will fail above everyone else's success. - James Cameron",
372
+ "Don't watch the clock; do what it does. Keep going. - Sam Levenson",
373
+ "Hardships often prepare ordinary people for an extraordinary destiny. - C.S. Lewis",
374
+ "Don't count the days, make the days count. - Muhammad Ali",
375
+ "The best revenge is massive success. - Frank Sinatra",
376
+ "The only impossible journey is the one you never begin. - Tony Robbins",
377
+ "Act as if what you do makes a difference. It does. - William James",
378
+ "You are never too old to set another goal or to dream a new dream. - C.S. Lewis",
379
+ "If you're going through hell, keep going. - Winston Churchill",
380
+ "Dream big and dare to fail. - Norman Vaughan",
381
+ "In the middle of every difficulty lies opportunity. - Albert Einstein",
382
+ "What we achieve inwardly will change outer reality. - Plutarch",
383
+ "I have not failed. I've just found 10,000 ways that won't work. - Thomas Edison",
384
+ "It always seems impossible until it's done. - Nelson Mandela",
385
+ "The future depends on what you do today. - Mahatma Gandhi",
386
+ "Don't wait. The time will never be just right. - Napoleon Hill",
387
+ "Quality is not an act, it is a habit. - Aristotle",
388
+ "Your life does not get better by chance, it gets better by change. - Jim Rohn",
389
+ "The only thing standing between you and your goal is the story you keep telling yourself as to why you can't achieve it. - Jordan Belfort",
390
+ "Challenges are what make life interesting; overcoming them is what makes life meaningful. - Joshua J. Marine",
391
+ "Opportunities don't happen, you create them. - Chris Grosser",
392
+ "I can't change the direction of the wind, but I can adjust my sails to always reach my destination. - Jimmy Dean",
393
+ "Start where you are. Use what you have. Do what you can. - Arthur Ashe",
394
+ "The secret of getting ahead is getting started. - Mark Twain",
395
+ "You don’t have to be great to start, but you have to start to be great. - Zig Ziglar",
396
+ "Keep your eyes on the stars, and your feet on the ground. - Theodore Roosevelt",
397
+ "The only way to achieve the impossible is to believe it is possible. - Charles Kingsleigh"
398
+ ]
399
+
400
+ random_quote = random.choice(quotes)
401
+ st.sidebar.success(random_quote)
402
+
403
+ # Chat Export
404
+ st.sidebar.markdown("---")
405
+ if st.sidebar.button("Export Chat History"):
406
+ chat_history = "\n".join([f"{msg['role']}: {msg['content']}" for msg in st.session_state.messages])
407
+ st.sidebar.download_button(
408
+ label="Download Chat History",
409
+ data=chat_history,
410
+ file_name="ai_buddy_chat_history.txt",
411
+ mime="text/plain"
412
+ )
413
+
414
+ st.sidebar.success("Chat history ready for download!")
415
+
416
+ # Display achievements
417
+ if 'achievements' in st.session_state and st.session_state.achievements:
418
+ st.sidebar.markdown("---")
419
+ st.sidebar.header("πŸ† Achievements")
420
+ for achievement in st.session_state.achievements:
421
+ st.sidebar.success(f"Unlocked: {achievement}")
422
+
423
+ if __name__ == "__main__":
424
  main()