iamstrong commited on
Commit
2e984b5
·
verified ·
1 Parent(s): b2e5310

Upload 3 files

Browse files
Files changed (1) hide show
  1. app.py +250 -155
app.py CHANGED
@@ -1,168 +1,263 @@
 
 
 
 
1
  import gradio as gr
2
  from gtts import gTTS
3
- import tempfile, json, datetime, random
4
-
5
- # --- Setup ---
 
6
 
7
- # Emotional triggers
8
- emotions = {
9
- # ... (include all 100+ triggers from previous version) ...
10
- "sad": "It’s okay to feel sad sometimes. Let’s breathe together 🌿",
11
- "anxiety": "Try slow breathing — in 4, hold 4, out 4.",
12
- "angry": "Anger is valid. Let’s cool off together.",
13
- # include all others here...
14
- }
15
-
16
- # Calm & Study Tips
17
  calm_tips = [
18
- "Breathe deeply and slowly 🌿", "Stretch your body 🧘",
19
- # ... total 10 ...
 
 
20
  ]
21
  study_tips = [
22
- "Use Pomodoro (25min on, 5min off)",
23
- # ... total 10 ...
 
 
24
  ]
25
- calm_idx = 0
26
- study_idx = 0
 
 
 
 
27
 
28
- def next_calm():
29
- global calm_idx
30
- tip = calm_tips[calm_idx % len(calm_tips)]
31
- calm_idx += 1
32
- return tip
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- def next_study():
35
- global study_idx
36
- tip = study_tips[study_idx % len(study_tips)]
37
- study_idx += 1
38
- return tip
39
 
40
- # User & memory
41
- user_info = {"language":"english"}
42
- chat_history = []
43
- journal_entries = []
 
 
 
 
 
44
 
45
- # Generate chatbot reply
46
- def generate_reply(text):
47
- low = text.lower()
48
- for k, resp in emotions.items():
49
- if k in low: return resp
50
- if "joke" in low:
51
- return "Why don’t scientists trust atoms? Because they make up everything!"
52
- if "advice" in low:
53
- return "🧠 Take 3 deep breaths. Want help making a plan?"
54
- return "Thanks for sharing. Keep talking 💬"
55
-
56
- def chat(audio, text):
57
- if audio:
58
  import whisper
59
- m = whisper.load_model("base")
60
- u = m.transcribe(audio)["text"]
 
61
  else:
62
- u = text
63
- r = generate_reply(u)
64
- t = datetime.datetime.now().isoformat()
65
- chat_history.append({"time":t,"user":u,"bot":r})
66
- with open("chat.json","w") as f: json.dump(chat_history,f,indent=2)
67
- tts = gTTS(r, lang="en")
68
- f = tempfile.NamedTemporaryFile(delete=False,suffix=".mp3")
69
- tts.save(f.name)
70
- return r, f.name
71
-
72
- def show_chat_hist():
73
- if not chat_history: return "No history yet."
74
- return "\n\n".join(f"{c['time']}\nYou: {c['user']}\nBot: {c['bot']}" for c in chat_history)
75
-
76
- def save_journal(txt):
77
- t = datetime.datetime.now().isoformat()
78
- journal_entries.append({"time":t,"entry":txt})
79
- with open("journals.json","w") as f: json.dump(journal_entries,f,indent=2)
80
- return "Saved!"
81
-
82
- def show_journal_hist():
83
- if not journal_entries: return "No entries yet."
84
- return "\n\n".join(f"{j['time']}\n{j['entry']}" for j in journal_entries)
85
-
86
- # --- Gradio UI ---
87
- css = """
88
- body { background-color:black; color:white; }
89
- .gr-button { background-color:pink; color:black; }
90
- .tabitem { background-color:pink !important; }
91
- """
92
-
93
- with gr.Blocks(css=css) as demo:
94
- gr.Markdown("# 🌸 StrongMind Therapist 2.0")
95
-
96
- with gr.Tab("💬 Chat"):
97
- gr.Markdown("**Describe your day in one word to begin:**")
98
- audio = gr.Audio(type="filepath", label="Speak")
99
- text = gr.Textbox(label="Or type here")
100
- btn = gr.Button("Send")
101
- out_txt = gr.Textbox(label="Bot says")
102
- out_voice = gr.Audio(label="Voice reply")
103
- btn.click(chat, inputs=[audio,text], outputs=[out_txt,out_voice])
104
-
105
- with gr.Tab("🍃 Calm Space"):
106
- calm_btn = gr.Button("Get Calm Tip")
107
- calm_out = gr.Textbox(label="Calm Tip")
108
- calm_btn.click(next_calm, outputs=calm_out)
109
-
110
- with gr.Tab("📚 Study Tips"):
111
- study_btn = gr.Button("Get Study Tip")
112
- study_out = gr.Textbox(label="Study Tip")
113
- study_btn.click(next_study, outputs=study_out)
114
-
115
- with gr.Tab("🎮 Games"):
116
- gr.Markdown("**Choose from these games:**")
117
- games = {
118
- "Memory": [
119
- "https://www.crazygames.com/game/memozor-memory",
120
- "https://www.crazygames.com/game/fancy-pants-adventure",
121
- "https://www.crazygames.com/game/brain-boosters-memory-match",
122
- "https://www.crazygames.com/game/jigsaw-puzzle",
123
- "https://www.crazygames.com/game/card-memory"
124
- ],
125
- "Dress Up": [
126
- "https://www.crazygames.com/game/fashion-tower",
127
- "https://www.crazygames.com/game/princess-stylist",
128
- "https://www.crazygames.com/game/dress-up-craze",
129
- "https://www.crazygames.com/game/barbie-doll-maker",
130
- "https://www.crazygames.com/game/dress-up-ragdoll"
131
- ],
132
- "Driving": [
133
- "https://www.crazygames.com/game/car-rush",
134
- "https://www.crazygames.com/game/moto-x3m",
135
- "https://www.crazygames.com/game/traffic-run",
136
- "https://www.crazygames.com/game/parking-fury",
137
- "https://www.crazygames.com/game/royal-truck"
138
- ],
139
- "Relaxing": [
140
- "https://www.crazygames.com/game/thisissand",
141
- "https://www.crazygames.com/game/ambient-sandbox",
142
- "https://www.crazygames.com/game/mandala-coloring",
143
- "https://www.crazygames.com/game/solitaire-relax",
144
- "https://www.crazygames.com/game/relax-pixel-art"
145
- ]
146
- }
147
- for cat, urls in games.items():
148
- gr.Markdown(f"### {cat}")
149
- for u in urls:
150
- gr.HTML(f'<iframe src="{u}" width="100%" height="400px"></iframe>')
151
-
152
- with gr.Tab("📜 Chat History"):
153
- hist_btn = gr.Button("Load History")
154
- hist_out = gr.Textbox(lines=15)
155
- hist_btn.click(show_chat_hist, outputs=hist_out)
156
-
157
- with gr.Tab("📝 Journal"):
158
- journal = gr.Textbox(label="Write your thoughts", lines=6)
159
- save_b = gr.Button("Save")
160
- save_res = gr.Textbox(label="Status")
161
- save_b.click(save_journal, inputs=journal, outputs=save_res)
162
-
163
- with gr.Tab("📖 Journal History"):
164
- load_j = gr.Button("Load Entries")
165
- j_out = gr.Textbox(lines=15)
166
- load_j.click(show_journal_hist, outputs=j_out)
167
-
168
- demo.launch()
 
1
+ # Placeholder: Final app.py style layout for StrongMind Therapist 2.0 with all features requested.
2
+ # Because of limitations, a fully working zip with embedded games cannot be handled here.
3
+ # You can copy the logic and UI below to a local Python environment.
4
+
5
  import gradio as gr
6
  from gtts import gTTS
7
+ import tempfile
8
+ import json
9
+ import datetime
10
+ import os
11
 
12
+ # Store user info and data
13
+ user_info = {"name": "", "age": "", "gender": "", "language": "english"}
14
+ chat_history = []
15
+ journal_entries = []
 
 
 
 
 
 
16
  calm_tips = [
17
+ "Take 3 deep breaths.", "Listen to nature.", "Stretch your body.", "Drink water.",
18
+ "Think of one good thing today.", "Close your eyes for 1 minute.",
19
+ "Write your feelings.", "Smile at yourself.", "Imagine a peaceful place.",
20
+ "Say a positive affirmation."
21
  ]
22
  study_tips = [
23
+ "Use Pomodoro: 25min study, 5min break", "Make a daily to-do list",
24
+ "Avoid multitasking", "Use color-coded notes", "Take 10-min exercise breaks",
25
+ "Sleep 7–9 hrs daily", "Drink water during study", "Use active recall",
26
+ "Study hardest topics first", "Test yourself often"
27
  ]
28
+ tip_index = {"calm": 0, "study": 0}
29
+ lang_codes = {
30
+ "english": "en", "hindi": "hi", "marathi": "mr", "bengali": "bn",
31
+ "tamil": "ta", "telugu": "te", "malayalam": "ml", "spanish": "es",
32
+ "french": "fr", "german": "de"
33
+ }
34
 
35
+ emotions = {
36
+ "sad": "It's okay to feel sad sometimes 🌧️", "anxiety": "Try breathing slowly 🧘",
37
+ "angry": "Take deep breaths. Anger is natural.", "lonely": "I'm here for you 💚",
38
+ "exams": "Let’s create a quick plan!", "friend": "Want to talk about them?",
39
+ "tired": "You’ve been carrying a lot. Rest isn’t lazy — it’s necessary 😴",
40
+ "overwhelmed": "Take one thing at a time. You're doing okay.",
41
+ "lost": "It's okay not to have all the answers. Let’s find your path slowly.",
42
+ "sad": "It’s okay to feel sad. Let yourself cry if you need to. I’m here for you.",
43
+ "anxiety": "Try a calming breath: in for 4, hold for 4, out for 4. You’ve got this.",
44
+ "angry": "Take a deep breath. Let’s find a peaceful way to express your feelings.",
45
+ "lonely": "You are not alone. Talking helps — I’m here to listen.",
46
+ "rejected": "Rejection hurts but it doesn’t define your worth.",
47
+ "exams": "Plan short sessions with breaks. You can do this!",
48
+ "parents": "Family pressure is real. Want to talk more about it?",
49
+ "money": "Finances are tough, but your value isn’t tied to them.",
50
+ "too much": "Pause. Let’s break it into small steps.",
51
+ "friend": "Friendship can be tricky. Want to share what happened?",
52
+ "love": "Love is powerful — and sometimes painful. I’m here to help you reflect.",
53
+ "forced": "You don’t have to do what doesn’t feel right.",
54
+ "compare": "You’re unique. Comparison steals joy.",
55
+ "numb": "It’s okay to feel nothing. Let’s gently bring you back.",
56
+ "instagram": "Let’s take a small break from social media together.",
57
+ "pretend": "You don’t need to pretend here. Be real, be you.",
58
+ "bullied": "You don’t deserve this. You are strong and valuable.",
59
+ "misunderstood": "That can feel frustrating. I understand you.",
60
+ "rainy": "Rainy days can be gloomy. A warm drink and chat may help.",
61
+ "unwell": "Rest, hydrate, and be kind to yourself today.",
62
+ "overthink": "Let’s try to focus on what’s in your control.",
63
+ "who am i": "Great question! Let’s explore that together.",
64
+ "climate": "You care — and that’s powerful. Even small actions help.",
65
+ "pointless": "Your life matters, even when it doesn’t feel like it.",
66
+ "ignored": "You are seen and heard here. Let’s talk.",
67
+ "can’t sleep": "Try breathing deeply. Would soft music help?",
68
+ "stuck": "Let’s look at one thing we *can* do today.",
69
+ "tired": "It’s okay to rest. You deserve it.",
70
+ "hopeless": "Even small steps forward are progress. Hope grows.",
71
+ "depressed": "You’re not alone in this. Let’s talk through it.",
72
+ "scared": "Let’s face this together, one moment at a time.",
73
+ "afraid": "Fear shows you care. Let’s understand it better.",
74
+ "confused": "It’s okay not to have all the answers yet.",
75
+ "guilty": "Guilt teaches us. Let’s grow from it, not drown in it.",
76
+ "ashamed": "You are more than your mistakes.",
77
+ "failure": "Failure means you tried. That’s strength.",
78
+ "panic": "Breathe with me. Ground yourself. You are okay.",
79
+ "stressed": "Let’s identify your stress and sort it gently.",
80
+ "bored": "Want to do something fun or creative together?",
81
+ "insecure": "You have strengths worth celebrating.",
82
+ "uncertain": "Uncertainty is part of growth. Let’s navigate it.",
83
+ "worried": "What are you worried about? Let’s untangle it.",
84
+ "homesick": "It’s okay to miss home. What comforts you?",
85
+ "crying": "Crying is healing. Let it out if needed.",
86
+ "lost": "Let’s start with one small direction to follow.",
87
+ "jealous": "Let’s explore what you truly desire.",
88
+ "envy": "You can build your own journey. You’re enough.",
89
+ "hate": "Let’s turn that strong emotion into understanding.",
90
+ "bitterness": "Bitterness is heavy. Want to release some of it?",
91
+ "regret": "We all have regrets. What can we learn from yours?",
92
+ "betrayed": "That hurts deeply. Let’s process it together.",
93
+ "heartbroken": "Healing takes time. Let’s take the first step.",
94
+ "alone": "You’re not alone here. I’m right with you.",
95
+ "trapped": "There’s always a way out. Let’s look for options.",
96
+ "disappointed": "Disappointment is valid. Let’s reflect and reset.",
97
+ "pressured": "You don’t have to carry it all. Let’s prioritize.",
98
+ "unloved": "You are lovable. Truly. Start with self-kindness.",
99
+ "exhausted": "Rest. That’s productive too.",
100
+ "withdrawn": "It’s okay to pull back. But don’t shut out support.",
101
+ "disrespected": "Respect matters. You deserve it.",
102
+ "avoided": "You matter. Let’s talk about what happened.",
103
+ "overwhelmed": "One deep breath. One small step.",
104
+ "insomnia": "Let’s try a gentle nighttime routine.",
105
+ "neglected": "You deserve care and attention.",
106
+ "nervous": "New things are scary. But you’re capable.",
107
+ "frustrated": "Let’s release that pressure gently.",
108
+ "humiliated": "That experience doesn’t define you.",
109
+ "unimportant": "You matter. Just by being you.",
110
+ "abandoned": "That’s painful. You’re not alone anymore.",
111
+ "defeated": "You’re still here. That’s strength.",
112
+ "shy": "Quiet doesn’t mean weak. Your voice matters.",
113
+ "paranoid": "Let’s ground our thoughts in facts and truth.",
114
+ "restless": "Let’s find a healthy outlet together.",
115
+ "gloomy": "Let’s look for a little light together.",
116
+ "anxious": "Let’s name the worry, then tame it.",
117
+ "worthless": "You are worthy — of love, peace, and joy.",
118
+ "invisible": "I see you. You matter.",
119
+ "lethargic": "Small movement helps. Try stretching.",
120
+ "annoyed": "Want to vent? I’m listening.",
121
+ "fomo": "It’s okay not to do everything. Your pace is right.",
122
+ "peer pressure": "Your choices are your own. Stand strong.",
123
+ "embarrassed": "Everyone messes up sometimes. Let it go.",
124
+ "unappreciated": "I appreciate you. Let’s celebrate your efforts.",
125
+ "hollow": "You may feel empty now — but you’re not.",
126
+ "resentful": "Let’s process it before it poisons your peace.",
127
+ "in pain": "Pain hurts, but talking eases it. Let’s talk.",
128
+ "drained": "Rest is fuel. It’s okay to pause.",
129
+ "moody": "Moods pass. Let’s ride this one out together.",
130
+ "isolated": "Let’s reconnect — even one small step helps.",
131
+ "fake": "You can be real here. No masks.",
132
+ "mentally tired": "Mental fatigue is real. Let’s rest and reset.",
133
+ "broken": "Cracks let the light in. You’re still whole inside.",
134
+ "crushed": "That sounds painful. Let’s unpack it together.",
135
+ "troubled": "Name the trouble, then tame it. I’m here.",
136
+ "underestimated": "You are more than they think. Show them. Gently.",
137
+ "burned out": "Burnout needs healing. Step back to move forward."
138
+ }
139
 
140
+ # Show number of emotions defined
141
+ len(emotion_advice)
 
 
 
142
 
143
+ }
144
+
145
+ def set_personal_info(name, age, gender, language):
146
+ user_info.update({"name": name, "age": age, "gender": gender, "language": language})
147
+ return f"Welcome {name}! Preferences saved."
148
+
149
+ def show_personal_data():
150
+ today = datetime.date.today().strftime("%Y-%m-%d (%A)")
151
+ return f"📅 {today}\n👤 Name: {user_info['name']}\n🎂 Age: {user_info['age']}\n⚧ Gender: {user_info['gender']}\n🌐 Language: {user_info['language']}"
152
 
153
+ def generate_reply(input_text):
154
+ text = input_text.lower()
155
+ for word, reply in emotions.items():
156
+ if word in text:
157
+ return reply
158
+ return "Tell me more about your day."
159
+
160
+ def chat_function(audio_input, text_input):
161
+ if audio_input:
 
 
 
 
162
  import whisper
163
+ model = whisper.load_model("base")
164
+ result = model.transcribe(audio_input)
165
+ user_text = result["text"]
166
  else:
167
+ user_text = text_input
168
+
169
+ reply = generate_reply(user_text)
170
+ chat_history.append({"user": user_text, "bot": reply})
171
+ lang_code = lang_codes.get(user_info["language"], "en")
172
+ tts = gTTS(reply, lang=lang_code)
173
+ audio_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
174
+ tts.save(audio_file.name)
175
+ return reply, audio_file.name
176
+
177
+ def get_chat_history():
178
+ if not chat_history:
179
+ return "No conversations yet."
180
+ return "\n\n".join([f"You: {c['user']}\nBot: {c['bot']}" for c in chat_history])
181
+
182
+ def save_journal(entry):
183
+ journal_entries.append(entry)
184
+ with open("journal.json", "w") as f:
185
+ json.dump(journal_entries, f)
186
+ return "Journal saved!"
187
+
188
+ def show_journal_history():
189
+ return "\n---\n".join(journal_entries) if journal_entries else "No journal entries yet."
190
+
191
+ def next_calm_tip():
192
+ tip = calm_tips[tip_index["calm"] % len(calm_tips)]
193
+ tip_index["calm"] += 1
194
+ return tip
195
+
196
+ def next_study_tip():
197
+ tip = study_tips[tip_index["study"] % len(study_tips)]
198
+ tip_index["study"] += 1
199
+ return tip
200
+
201
+ with gr.Blocks(title="StrongMind Therapist 2.0") as app:
202
+ with gr.Tab("1️⃣ Personal Info"):
203
+ name = gr.Textbox(label="Name")
204
+ age = gr.Textbox(label="Age")
205
+ gender = gr.Dropdown(["Male", "Female", "Other"], label="Gender")
206
+ language = gr.Dropdown(list(lang_codes.keys()), label="Preferred Language")
207
+ btn = gr.Button("Save Info")
208
+ output = gr.Textbox()
209
+ btn.click(set_personal_info, [name, age, gender, language], output)
210
+
211
+ with gr.Tab("2️⃣ Personal Info Data"):
212
+ show = gr.Button("Show My Info")
213
+ info_display = gr.Textbox(lines=6)
214
+ show.click(show_personal_data, outputs=info_display)
215
+
216
+ with gr.Tab("3️⃣ Chat"):
217
+ gr.Markdown("🗣️ Describe your day in one word.")
218
+ audio_input = gr.Audio(type="filepath", label="🎙️ Say something")
219
+ text_input = gr.Textbox(label="⌨️ Or type here")
220
+ send = gr.Button("Send")
221
+ bot_reply = gr.Textbox(label="🧠 Therapist")
222
+ voice = gr.Audio(label="🔊 Voice Reply")
223
+ send.click(chat_function, [audio_input, text_input], [bot_reply, voice])
224
+
225
+ with gr.Tab("4️⃣ Chat History"):
226
+ show_history = gr.Button("📜 Show Chats")
227
+ chat_out = gr.Textbox(lines=20, label="History")
228
+ show_history.click(get_chat_history, outputs=chat_out)
229
+
230
+ with gr.Tab("5️⃣ Journal"):
231
+ journal_input = gr.Textbox(lines=6, label="Write your thoughts")
232
+ save = gr.Button("Save")
233
+ journal_status = gr.Textbox()
234
+ save.click(save_journal, journal_input, journal_status)
235
+
236
+ with gr.Tab("6️⃣ Journal History"):
237
+ view = gr.Button("View Past Entries")
238
+ past = gr.Textbox(lines=15, label="Previous Journals")
239
+ view.click(show_journal_history, outputs=past)
240
+
241
+ with gr.Tab("7️⃣ Calm Space"):
242
+ tip_btn = gr.Button("🌿 Give Me a Calm Tip")
243
+ calm_text = gr.Textbox()
244
+ tip_btn.click(next_calm_tip, outputs=calm_text)
245
+
246
+ with gr.Tab("8️⃣ Study Tips"):
247
+ tip_btn2 = gr.Button("📚 Study Tip")
248
+ study_text = gr.Textbox()
249
+ tip_btn2.click(next_study_tip, outputs=study_text)
250
+
251
+ with gr.Tab("9️⃣ Pomodoro"):
252
+ gr.Markdown("⏱️ Use 25 min study + 5 min break cycles.\n(For real timer integration, use front-end JS)")
253
+
254
+ with gr.Tab("🔟 Games"):
255
+ gr.Markdown("🎮 Embedded Games: Play directly below!")
256
+
257
+ with gr.Accordion("🧠 2048 Puzzle", open=False):
258
+ gr.HTML('<iframe src="https://www.htmlgames.com/embed/2048" width="640" height="720" frameborder="0" allowfullscreen></iframe>')
259
+
260
+ with gr.Accordion("🟣 Bubble Tower 3D", open=False):
261
+ gr.HTML('<iframe src="https://www.htmlgames.com/embed/bubble-tower-3d" width="800" height="600" frameborder="0" allowfullscreen></iframe>')
262
+
263
+ app.launch()