iamstrong commited on
Commit
21d232e
·
verified ·
1 Parent(s): 605ab3f

Upload 3 files

Browse files
Files changed (1) hide show
  1. app.py +113 -104
app.py CHANGED
@@ -2,139 +2,148 @@ import gradio as gr
2
  from gtts import gTTS
3
  import tempfile
4
  import datetime
 
5
 
 
 
 
 
6
  user_info = {"name": "", "age": "", "gender": "", "language": "english"}
7
  chat_history = []
8
  journal_entries = []
9
 
10
- def save_user_info(name, age, gender, language):
11
- user_info.update({"name": name, "age": age, "gender": gender, "language": language})
12
- return f"Welcome, {name}!"
13
-
14
- def generate_response(input_text):
15
- # Simulating GPT-based response (freeform, not word-based)
16
- if "?" in input_text:
17
- response = "That's a thoughtful question. Let's explore it together."
18
- elif len(input_text.split()) <= 3:
19
- response = "Could you share a little more?"
20
- else:
21
- response = "I'm here for you. That sounds like a lot — want to talk more about it?"
22
- chat_history.append({"user": input_text, "bot": response})
23
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  def text_to_speech(text):
26
- tts = gTTS(text)
27
- with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
28
  tts.save(fp.name)
29
  return fp.name
30
 
31
- def chat_function(user_input):
32
- response = generate_response(user_input)
33
- audio_path = text_to_speech(response)
34
- return response, audio_path
35
-
36
- def view_chat_history():
37
- return "\n".join([f"You: {c['user']}\nAI: {c['bot']}" for c in chat_history])
38
 
 
39
  def save_journal(entry):
40
- now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
41
- journal_entries.append(f"{now} - {entry}")
42
- return "Entry saved."
43
-
44
- def view_journal():
45
- return "\n\n".join(journal_entries)
46
-
47
- calm_tips = [
48
- "Take a deep breath in... and out.",
49
- "Look around you and find something beautiful.",
50
- "Gently stretch your arms and shoulders.",
51
- "Drink a glass of water slowly.",
52
- "Think of one thing you’re grateful for.",
53
- "Close your eyes for 10 seconds.",
54
- "Smile — even a little one.",
55
- "Sit back and relax your neck.",
56
- "Imagine a peaceful place.",
57
- "You're doing better than you think."
58
- ]
59
-
60
- def get_calm_tip(index=[0]):
61
- tip = calm_tips[index[0] % len(calm_tips)]
62
- index[0] += 1
63
  return tip
64
 
65
- study_tips = [
66
- "Use the Pomodoro technique: 25 mins study, 5 mins break.",
67
- "Keep a distraction list nearby.",
68
- "Teach what you learn.",
69
- "Stay hydrated and take eye breaks.",
70
- "Review your notes before sleeping.",
71
- "Use flashcards for quick revision.",
72
- "Take handwritten notes.",
73
- "Use colored pens or highlighters.",
74
- "Keep your phone on silent while studying.",
75
- "Revise daily instead of cramming."
76
- ]
77
 
78
- def get_study_tip(index=[0]):
79
- tip = study_tips[index[0] % len(study_tips)]
80
- index[0] += 1
81
- return tip
82
 
83
- with gr.Blocks(theme=gr.themes.Soft()) as app:
84
- gr.Markdown("## 🧠 StrongMind Therapist 2.0")
85
- gr.Markdown("Welcome to your peaceful space to talk, journal, and focus.")
86
 
 
 
87
  with gr.Tabs():
88
- with gr.Tab("Login"):
89
  name = gr.Textbox(label="Name")
90
  age = gr.Textbox(label="Age")
91
- gender = gr.Dropdown(["Male", "Female", "Other"], label="Gender")
92
- language = gr.Dropdown(["english", "hindi"], label="Preferred Language")
93
- login_btn = gr.Button("Login")
94
- welcome_msg = gr.Textbox(label="Welcome Message", interactive=False)
95
- login_btn.click(save_user_info, inputs=[name, age, gender, language], outputs=welcome_msg)
96
-
97
- with gr.Tab("Personal Info"):
98
- def display_info():
99
- now = datetime.datetime.now().strftime("%A, %d %B %Y")
100
- return f"{now}\nName: {user_info['name']}\nAge: {user_info['age']}\nGender: {user_info['gender']}\nLanguage: {user_info['language']}"
101
- info_display = gr.Textbox(label="User Info", interactive=False)
102
- gr.Button("Show Info").click(display_info, outputs=info_display)
103
 
104
  with gr.Tab("Chat"):
105
- gr.Markdown("🗨️ Talk to me. How was your day?")
106
- user_input = gr.Textbox(label="You")
107
- bot_response = gr.Textbox(label="Therapist", interactive=False)
108
- bot_audio = gr.Audio(label="Voice", interactive=False, type="filepath")
109
- chat_btn = gr.Button("Send")
110
- chat_btn.click(chat_function, inputs=user_input, outputs=[bot_response, bot_audio])
111
-
112
- with gr.Tab("Chat History"):
113
- history_output = gr.Textbox(label="Past Chats", lines=10)
114
- gr.Button("View").click(view_chat_history, outputs=history_output)
115
 
116
  with gr.Tab("Journal"):
117
- journal_input = gr.Textbox(label="Your Entry", lines=5)
118
- journal_output = gr.Textbox(label="Save Status")
119
- gr.Button("Save Entry").click(save_journal, inputs=journal_input, outputs=journal_output)
 
120
 
121
  with gr.Tab("Journal History"):
122
- journal_view = gr.Textbox(label="All Entries", lines=10)
123
- gr.Button("View").click(view_journal, outputs=journal_view)
 
124
 
125
- with gr.Tab("Pomodoro Timer"):
126
- gr.Markdown("⏲️ 25 min focus + 5 min break. Set your timer!")
127
-
128
- with gr.Tab("Calm Space"):
129
- calm_output = gr.Textbox(label="Calm Tip", interactive=False)
130
- gr.Button("Show Calm Tip").click(get_calm_tip, outputs=calm_output)
131
 
132
  with gr.Tab("Study Tips"):
133
- tip_output = gr.Textbox(label="Tip", interactive=False)
134
- gr.Button("Study Tip").click(get_study_tip, outputs=tip_output)
 
 
 
 
 
 
135
 
136
  with gr.Tab("Games"):
137
- gr.Markdown("🎮 Memory | Dress Up | Driving | Relaxing")
138
- gr.HTML("""<iframe src="https://www.crazygames.com" width="100%" height="500px"></iframe>""")
 
 
 
 
 
 
 
 
 
 
139
 
140
- app.launch()
 
 
2
  from gtts import gTTS
3
  import tempfile
4
  import datetime
5
+ import openai
6
 
7
+ # Replace with your OpenAI GPT-4o key
8
+ openai.api_key = "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"
9
+
10
+ # User data
11
  user_info = {"name": "", "age": "", "gender": "", "language": "english"}
12
  chat_history = []
13
  journal_entries = []
14
 
15
+ # Calm tips
16
+ calm_tips = [
17
+ "Take 3 deep breaths.", "Listen to nature.", "Stretch your body.",
18
+ "Drink water.", "Think of one happy moment.",
19
+ "Close your eyes and count to 10.", "Smile, even if just a little.",
20
+ "Look outside and notice one peaceful thing.", "Take a short walk.",
21
+ "Say something kind to yourself."
22
+ ]
23
+
24
+ # Study tips
25
+ study_tips = [
26
+ "Break study time into chunks.", "Use mind maps for better recall.",
27
+ "Teach someone what you learned.", "Take short breaks.",
28
+ "Use the Pomodoro technique.", "Keep your study space clean.",
29
+ "Avoid multitasking.", "Revise regularly.", "Set clear goals.",
30
+ "Reward yourself after studying."
31
+ ]
32
+
33
+ # Chatbot
34
+ def respond(message):
35
+ chat_history.append(("You", message))
36
+ try:
37
+ response = openai.ChatCompletion.create(
38
+ model="gpt-4o",
39
+ messages=[{"role": "system", "content": "You are a kind AI therapist."}] +
40
+ [{"role": "user", "content": m[1]} for m in chat_history if m[0] == "You"],
41
+ max_tokens=150
42
+ )
43
+ reply = response.choices[0].message.content.strip()
44
+ except Exception as e:
45
+ reply = "Sorry, there was an error connecting to the AI."
46
+ chat_history.append(("Therapist", reply))
47
+ return reply
48
 
49
  def text_to_speech(text):
50
+ tts = gTTS(text=text, lang='en')
51
+ with tempfile.NamedTemporaryFile(delete=True, suffix=".mp3") as fp:
52
  tts.save(fp.name)
53
  return fp.name
54
 
55
+ def chat_interface(user_input):
56
+ reply = respond(user_input)
57
+ audio_path = text_to_speech(reply)
58
+ return reply, audio_path
 
 
 
59
 
60
+ # Journal
61
  def save_journal(entry):
62
+ now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
63
+ journal_entries.append((now, entry))
64
+ return f"Saved at {now}"
65
+
66
+ def show_journal_history():
67
+ return "\n\n".join([f"{t}\n{e}" for t, e in journal_entries]) or "No entries yet."
68
+
69
+ # Calm Tips
70
+ calm_index = {"value": 0}
71
+ def next_calm_tip():
72
+ tip = calm_tips[calm_index["value"] % len(calm_tips)]
73
+ calm_index["value"] += 1
 
 
 
 
 
 
 
 
 
 
 
74
  return tip
75
 
76
+ # Personal Info
77
+ def save_personal_info(name, age, gender, language):
78
+ user_info.update({"name": name, "age": age, "gender": gender, "language": language})
79
+ return f"Info saved: {name}, {age}, {gender}, {language}"
 
 
 
 
 
 
 
 
80
 
81
+ # Game iframe
82
+ def game_iframe():
83
+ return '<iframe src="https://onlinegames.io/" width="100%" height="600px" frameborder="0"></iframe>'
 
84
 
85
+ # Pomodoro Timer
86
+ def pomodoro_timer():
87
+ return "Use an external timer or focus for 25 minutes, then rest for 5 minutes. Repeat."
88
 
89
+ # TABS
90
+ with gr.Blocks(theme=gr.themes.Soft(), css="body {background-color: black; color: white;} .gr-button {background-color: pink;}") as main_app:
91
  with gr.Tabs():
92
+ with gr.Tab("Personal Info"):
93
  name = gr.Textbox(label="Name")
94
  age = gr.Textbox(label="Age")
95
+ gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
96
+ language = gr.Dropdown(["English", "Hindi"], label="Language", value="English")
97
+ save_btn = gr.Button("Save Info")
98
+ output = gr.Textbox(label="Saved Info")
99
+ save_btn.click(save_personal_info, inputs=[name, age, gender, language], outputs=output)
 
 
 
 
 
 
 
100
 
101
  with gr.Tab("Chat"):
102
+ chat_input = gr.Textbox(label="How do you feel today?")
103
+ chat_output = gr.Textbox(label="Therapist says:")
104
+ audio_output = gr.Audio(label="Voice Response", autoplay=True)
105
+ send_btn = gr.Button("Send")
106
+ send_btn.click(chat_interface, inputs=chat_input, outputs=[chat_output, audio_output])
 
 
 
 
 
107
 
108
  with gr.Tab("Journal"):
109
+ journal_input = gr.Textbox(label="Write your thoughts here...", lines=5)
110
+ save_journal_btn = gr.Button("Save Entry")
111
+ save_status = gr.Textbox(label="Status")
112
+ save_journal_btn.click(save_journal, inputs=journal_input, outputs=save_status)
113
 
114
  with gr.Tab("Journal History"):
115
+ history_output = gr.Textbox(label="Your Journal Entries", lines=10)
116
+ show_btn = gr.Button("Show History")
117
+ show_btn.click(show_journal_history, outputs=history_output)
118
 
119
+ with gr.Tab("Calm Tips"):
120
+ calm_output = gr.Textbox(label="Try this...")
121
+ next_btn = gr.Button("Next Tip")
122
+ next_btn.click(next_calm_tip, outputs=calm_output)
 
 
123
 
124
  with gr.Tab("Study Tips"):
125
+ tip_output = gr.Textbox(label="Study Tip")
126
+ tip_btn = gr.Button("Get Tip")
127
+ tip_btn.click(lambda: study_tips[datetime.datetime.now().second % len(study_tips)], outputs=tip_output)
128
+
129
+ with gr.Tab("Pomodoro Timer"):
130
+ pomo_output = gr.Textbox(label="Pomodoro Info")
131
+ pomo_btn = gr.Button("Show Timer Tip")
132
+ pomo_btn.click(pomodoro_timer, outputs=pomo_output)
133
 
134
  with gr.Tab("Games"):
135
+ gr.HTML(game_iframe())
136
+
137
+ # WELCOME SCREEN
138
+ with gr.Blocks(theme=gr.themes.Soft(), css="body {background-color: black; color: white;} .gr-button {background-color: pink;}") as welcome_screen:
139
+ gr.Markdown("<h1 style='text-align: center; color: white;'>StrongMind Therapist 2.0</h1>")
140
+ gr.Markdown("<h3 style='text-align: center; color: white;'>🧠 Welcome to StrongMind Therapist! Your peaceful space to talk, journal, and focus.</h3>")
141
+ get_started_btn = gr.Button("Get Started", elem_id="get-started", scale=2)
142
+
143
+ def show_main_app():
144
+ main_app.launch(share=False)
145
+
146
+ get_started_btn.click(fn=None, inputs=None, outputs=None, _js="() => { document.body.innerHTML = ''; }", queue=False).then(fn=show_main_app)
147
 
148
+ # RUN APP
149
+ welcome_screen.launch()