phxdev commited on
Commit
ea6ba10
·
verified ·
1 Parent(s): 29f2127

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -153
app.py CHANGED
@@ -122,42 +122,41 @@ def _generate_response(formatted_prompt: str, max_new_tokens: int = 200) -> str:
122
  traceback.print_exc()
123
  return error_msg
124
 
125
- def psychology_support(message: str) -> str:
126
- """Main psychology support function"""
 
127
  if not message.strip():
128
  return "Please share what's on your mind."
129
 
130
- # Frame it as completing psychology content that happens to be conversational
131
  formatted_prompt = f"A person with boundary issues says: \"{message}\"\n\nA supportive response that helps with boundary setting:"
132
-
133
  return _generate_response(formatted_prompt, max_new_tokens=150)
134
 
135
- def trauma_support(message: str) -> str:
136
- """Trauma-informed support"""
137
  if not message.strip():
138
  return "I'm here to listen. What would help you feel safer right now?"
139
 
140
  formatted_prompt = f"You are a trauma-informed friend who helps people feel safe. Draw on your vast experience of supporting trauma survivors. Someone dealing with trauma just told you: \"{message}\"\n\nRespond to help them feel safer:"
141
  return _generate_response(formatted_prompt, max_new_tokens=180)
142
 
143
- def panic_support(message: str) -> str:
144
- """Immediate panic attack support"""
145
  if not message.strip():
146
  return "I can help you through this. What are you experiencing right now?"
147
 
148
  formatted_prompt = f"You are a calm, grounding friend who helps with panic attacks. Draw on your vast experience of helping people through panic and anxiety. Someone having panic symptoms just told you: \"{message}\"\n\nRespond to help them through this moment:"
149
  return _generate_response(formatted_prompt, max_new_tokens=160)
150
 
151
- def process_emotion(message: str) -> str:
152
- """Emotion processing and validation"""
153
  if not message.strip():
154
  return "What emotion are you working through right now?"
155
 
156
  formatted_prompt = f"You are an emotionally intelligent friend who helps people understand their feelings. Draw on your vast experience of emotional support and validation. Someone struggling with emotions just told you: \"{message}\"\n\nRespond to help them process what they're feeling:"
157
  return _generate_response(formatted_prompt, max_new_tokens=170)
158
 
159
- def crisis_resources() -> str:
160
- """Get immediate crisis intervention resources"""
161
  return """🆘 **IMMEDIATE CRISIS RESOURCES**
162
 
163
  **Emergency:** Call 911 or your local emergency number
@@ -176,8 +175,8 @@ def crisis_resources() -> str:
176
 
177
  You are not alone. Help is available 24/7."""
178
 
179
- def mindfulness_exercise() -> str:
180
- """Guided mindfulness exercise"""
181
  return """🧘 **5-MINUTE GROUNDING EXERCISE**
182
 
183
  **Right now, notice:**
@@ -195,157 +194,157 @@ def mindfulness_exercise() -> str:
195
 
196
  You've got this. One breath at a time."""
197
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
  # Apply GPU optimization if available
199
  if HAS_SPACES:
200
- psychology_support = spaces.GPU(psychology_support)
201
- trauma_support = spaces.GPU(trauma_support)
202
- panic_support = spaces.GPU(panic_support)
203
- process_emotion = spaces.GPU(process_emotion)
 
 
 
204
 
205
  # Initialize model
206
  print("🚀 Starting Psychology Personal Agent...")
207
  model_loaded = load_model()
208
 
209
  if model_loaded:
210
- print("✅ Creating interface...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
- with gr.Blocks(title="🧠 Personal Agent - Psychology Support", theme=gr.themes.Soft()) as demo:
 
 
 
 
 
 
 
 
 
213
 
214
- # Safety modal
215
- with gr.Column(visible=True, elem_id="safety_modal") as safety_modal:
216
- gr.Markdown("# ⚠️ IMPORTANT SAFETY INFORMATION")
217
-
218
- gr.Markdown("""## 🆘 CRISIS RESOURCES - AVAILABLE 24/7
219
-
220
- **If you're in immediate danger, call 911 or your local emergency number.**
221
-
222
- **24/7 Crisis Support:**
223
- • **988 Suicide & Crisis Lifeline**: Call or text 988 (US)
224
- • **Crisis Text Line**: Text HOME to 741741 (US)
225
- • **Emergency Services**: Call 911 for immediate emergency
226
-
227
- ## ⚠️ MEDICAL DISCLAIMER
228
-
229
- **THIS IS NOT MEDICAL ADVICE.** This AI provides general support only.
230
-
231
- **If you are in crisis or considering harm, seek immediate medical attention.**
232
-
233
- This is not a substitute for professional care. Always consult qualified healthcare providers for medical/mental health concerns.""")
234
-
235
- safety_acknowledged = gr.Checkbox(
236
- label="I understand this is not medical advice and will seek professional help for serious concerns.",
237
- value=False
238
- )
239
-
240
- continue_button = gr.Button("Continue to Psychology Support", variant="primary", size="lg")
241
 
242
- # Main interface
243
- with gr.Column(visible=False) as main_interface:
244
- gr.Markdown("# 🧠 Personal Agent - Psychology Support")
245
- gr.Markdown("*Specialized mental health support • Evidence-based • Always here*")
246
-
247
- with gr.Tab("General Support"):
248
- message_input = gr.Textbox(
249
- label="What's on your mind?",
250
- placeholder="Share your thoughts, concerns, or struggles...",
251
- lines=3
252
- )
253
- support_output = gr.Textbox(label="Personal Agent Response", lines=6)
254
- support_button = gr.Button("Get Support", variant="primary")
255
-
256
- support_button.click(
257
- fn=psychology_support,
258
- inputs=message_input,
259
- outputs=support_output
260
- )
261
-
262
- gr.Examples(
263
- examples=[
264
- "I've been having panic attacks at work",
265
- "I can't stop worrying about everything",
266
- "I feel like I'm not good enough",
267
- "I'm going through a major life change",
268
- "I have trouble setting boundaries"
269
- ],
270
- inputs=message_input
271
- )
272
-
273
- with gr.Tab("Trauma Support"):
274
- trauma_input = gr.Textbox(
275
- label="Share what feels safe to share",
276
- placeholder="I'm here to help you feel safer...",
277
- lines=3
278
- )
279
- trauma_output = gr.Textbox(label="Trauma-Informed Response", lines=6)
280
- trauma_button = gr.Button("Get Trauma Support", variant="secondary")
281
-
282
- trauma_button.click(
283
- fn=trauma_support,
284
- inputs=trauma_input,
285
- outputs=trauma_output
286
- )
287
-
288
- with gr.Tab("Panic Support"):
289
- panic_input = gr.Textbox(
290
- label="What are you experiencing?",
291
- placeholder="I can help you through this...",
292
- lines=2
293
- )
294
- panic_output = gr.Textbox(label="Immediate Support", lines=6)
295
- panic_button = gr.Button("Get Panic Support", variant="stop")
296
-
297
- panic_button.click(
298
- fn=panic_support,
299
- inputs=panic_input,
300
- outputs=panic_output
301
- )
302
-
303
- with gr.Tab("Process Emotions"):
304
- emotion_input = gr.Textbox(
305
- label="What emotion are you experiencing?",
306
- placeholder="Describe what you're feeling...",
307
- lines=2
308
- )
309
- emotion_output = gr.Textbox(label="Emotion Guidance", lines=6)
310
- emotion_button = gr.Button("Process Emotion", variant="secondary")
311
-
312
- emotion_button.click(
313
- fn=process_emotion,
314
- inputs=emotion_input,
315
- outputs=emotion_output
316
- )
317
-
318
- # Resource tabs
319
- with gr.Tab("Crisis Resources"):
320
- crisis_button = gr.Button("Show Crisis Resources", variant="stop")
321
- crisis_output = gr.Textbox(label="24/7 Crisis Resources", lines=10)
322
-
323
- crisis_button.click(
324
- fn=crisis_resources,
325
- outputs=crisis_output
326
- )
327
-
328
- with gr.Tab("Mindfulness"):
329
- mindfulness_button = gr.Button("Get Grounding Exercise", variant="secondary")
330
- mindfulness_output = gr.Textbox(label="Mindfulness Exercise", lines=10)
331
-
332
- mindfulness_button.click(
333
- fn=mindfulness_exercise,
334
- outputs=mindfulness_output
335
- )
336
 
337
- # Modal behavior
338
- def show_main_interface(acknowledged):
339
- if acknowledged:
340
- return gr.update(visible=False), gr.update(visible=True)
341
- else:
342
- return gr.update(visible=True), gr.update(visible=False)
343
 
344
- continue_button.click(
345
- fn=show_main_interface,
346
- inputs=[safety_acknowledged],
347
- outputs=[safety_modal, main_interface]
348
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
 
350
  if __name__ == "__main__":
351
  demo.launch(
@@ -359,7 +358,7 @@ This is not a substitute for professional care. Always consult qualified healthc
359
  else:
360
  print("❌ Failed to load psychology model")
361
 
362
- def error_response(x):
363
  return "⚠️ Model loading error. Please check console logs and try restarting."
364
 
365
  demo = gr.Interface(
 
122
  traceback.print_exc()
123
  return error_msg
124
 
125
+ # EXPOSED MCP FUNCTIONS
126
+ def psychology_support_exposed(message: str) -> str:
127
+ """Main psychology support function - EXPOSED TO MCP"""
128
  if not message.strip():
129
  return "Please share what's on your mind."
130
 
 
131
  formatted_prompt = f"A person with boundary issues says: \"{message}\"\n\nA supportive response that helps with boundary setting:"
 
132
  return _generate_response(formatted_prompt, max_new_tokens=150)
133
 
134
+ def trauma_support_exposed(message: str) -> str:
135
+ """Trauma-informed support - EXPOSED TO MCP"""
136
  if not message.strip():
137
  return "I'm here to listen. What would help you feel safer right now?"
138
 
139
  formatted_prompt = f"You are a trauma-informed friend who helps people feel safe. Draw on your vast experience of supporting trauma survivors. Someone dealing with trauma just told you: \"{message}\"\n\nRespond to help them feel safer:"
140
  return _generate_response(formatted_prompt, max_new_tokens=180)
141
 
142
+ def panic_support_exposed(message: str) -> str:
143
+ """Immediate panic attack support - EXPOSED TO MCP"""
144
  if not message.strip():
145
  return "I can help you through this. What are you experiencing right now?"
146
 
147
  formatted_prompt = f"You are a calm, grounding friend who helps with panic attacks. Draw on your vast experience of helping people through panic and anxiety. Someone having panic symptoms just told you: \"{message}\"\n\nRespond to help them through this moment:"
148
  return _generate_response(formatted_prompt, max_new_tokens=160)
149
 
150
+ def process_emotion_exposed(message: str) -> str:
151
+ """Emotion processing and validation - EXPOSED TO MCP"""
152
  if not message.strip():
153
  return "What emotion are you working through right now?"
154
 
155
  formatted_prompt = f"You are an emotionally intelligent friend who helps people understand their feelings. Draw on your vast experience of emotional support and validation. Someone struggling with emotions just told you: \"{message}\"\n\nRespond to help them process what they're feeling:"
156
  return _generate_response(formatted_prompt, max_new_tokens=170)
157
 
158
+ def crisis_resources_exposed() -> str:
159
+ """Get immediate crisis intervention resources - EXPOSED TO MCP"""
160
  return """🆘 **IMMEDIATE CRISIS RESOURCES**
161
 
162
  **Emergency:** Call 911 or your local emergency number
 
175
 
176
  You are not alone. Help is available 24/7."""
177
 
178
+ def mindfulness_exercise_exposed() -> str:
179
+ """Guided mindfulness exercise - EXPOSED TO MCP"""
180
  return """🧘 **5-MINUTE GROUNDING EXERCISE**
181
 
182
  **Right now, notice:**
 
194
 
195
  You've got this. One breath at a time."""
196
 
197
+ def sentiment_analysis_exposed(text: str) -> str:
198
+ """Analyze sentiment and emotional content of text - EXPOSED TO MCP"""
199
+ if not text.strip():
200
+ return "Please provide text to analyze."
201
+
202
+ formatted_prompt = f"You are an expert in emotional analysis and psychology. Analyze the emotional content, sentiment, and psychological patterns in this text: \"{text}\"\n\nProvide a detailed psychological analysis including mood, emotional state, potential concerns, and supportive insights:"
203
+ return _generate_response(formatted_prompt, max_new_tokens=200)
204
+
205
+ def relationship_analysis_exposed(message: str) -> str:
206
+ """Analyze relationship dynamics and patterns - EXPOSED TO MCP"""
207
+ if not message.strip():
208
+ return "Please describe the relationship situation you'd like analyzed."
209
+
210
+ formatted_prompt = f"You are a relationship therapist analyzing interpersonal dynamics. Someone described this relationship situation: \"{message}\"\n\nProvide insights on relationship patterns, communication dynamics, and healthy approaches:"
211
+ return _generate_response(formatted_prompt, max_new_tokens=180)
212
+
213
+ def coping_strategies_exposed(situation: str) -> str:
214
+ """Generate personalized coping strategies - EXPOSED TO MCP"""
215
+ if not situation.strip():
216
+ return "Please describe what you're dealing with so I can suggest coping strategies."
217
+
218
+ formatted_prompt = f"You are a mental health counselor specializing in coping strategies. Someone is dealing with: \"{situation}\"\n\nProvide specific, practical coping strategies and techniques:"
219
+ return _generate_response(formatted_prompt, max_new_tokens=200)
220
+
221
  # Apply GPU optimization if available
222
  if HAS_SPACES:
223
+ psychology_support_exposed = spaces.GPU(psychology_support_exposed)
224
+ trauma_support_exposed = spaces.GPU(trauma_support_exposed)
225
+ panic_support_exposed = spaces.GPU(panic_support_exposed)
226
+ process_emotion_exposed = spaces.GPU(process_emotion_exposed)
227
+ sentiment_analysis_exposed = spaces.GPU(sentiment_analysis_exposed)
228
+ relationship_analysis_exposed = spaces.GPU(relationship_analysis_exposed)
229
+ coping_strategies_exposed = spaces.GPU(coping_strategies_exposed)
230
 
231
  # Initialize model
232
  print("🚀 Starting Psychology Personal Agent...")
233
  model_loaded = load_model()
234
 
235
  if model_loaded:
236
+ print("✅ Creating MCP-exposed interfaces...")
237
+
238
+ # Create individual interfaces for each function
239
+ psychology_interface = gr.Interface(
240
+ fn=psychology_support_exposed,
241
+ inputs=gr.Textbox(label="Message", placeholder="Share what's on your mind..."),
242
+ outputs=gr.Textbox(label="Psychology Support Response"),
243
+ title="Psychology Support",
244
+ description="General psychological support and guidance"
245
+ )
246
+
247
+ trauma_interface = gr.Interface(
248
+ fn=trauma_support_exposed,
249
+ inputs=gr.Textbox(label="Message", placeholder="Share what feels safe..."),
250
+ outputs=gr.Textbox(label="Trauma Support Response"),
251
+ title="Trauma Support",
252
+ description="Trauma-informed care and support"
253
+ )
254
+
255
+ panic_interface = gr.Interface(
256
+ fn=panic_support_exposed,
257
+ inputs=gr.Textbox(label="Message", placeholder="What are you experiencing?"),
258
+ outputs=gr.Textbox(label="Panic Support Response"),
259
+ title="Panic Support",
260
+ description="Immediate support for panic and anxiety"
261
+ )
262
+
263
+ emotion_interface = gr.Interface(
264
+ fn=process_emotion_exposed,
265
+ inputs=gr.Textbox(label="Message", placeholder="Describe your emotions..."),
266
+ outputs=gr.Textbox(label="Emotion Processing Response"),
267
+ title="Emotion Processing",
268
+ description="Help processing and understanding emotions"
269
+ )
270
+
271
+ sentiment_interface = gr.Interface(
272
+ fn=sentiment_analysis_exposed,
273
+ inputs=gr.Textbox(label="Text to Analyze", placeholder="Enter text for sentiment analysis..."),
274
+ outputs=gr.Textbox(label="Sentiment Analysis"),
275
+ title="Sentiment Analysis",
276
+ description="Analyze emotional content and psychological patterns"
277
+ )
278
+
279
+ relationship_interface = gr.Interface(
280
+ fn=relationship_analysis_exposed,
281
+ inputs=gr.Textbox(label="Relationship Situation", placeholder="Describe the relationship dynamics..."),
282
+ outputs=gr.Textbox(label="Relationship Analysis"),
283
+ title="Relationship Analysis",
284
+ description="Analyze relationship patterns and dynamics"
285
+ )
286
+
287
+ coping_interface = gr.Interface(
288
+ fn=coping_strategies_exposed,
289
+ inputs=gr.Textbox(label="Situation", placeholder="What are you dealing with?"),
290
+ outputs=gr.Textbox(label="Coping Strategies"),
291
+ title="Coping Strategies",
292
+ description="Personalized coping strategies and techniques"
293
+ )
294
+
295
+ crisis_interface = gr.Interface(
296
+ fn=crisis_resources_exposed,
297
+ inputs=[],
298
+ outputs=gr.Textbox(label="Crisis Resources"),
299
+ title="Crisis Resources",
300
+ description="24/7 crisis intervention resources"
301
+ )
302
 
303
+ mindfulness_interface = gr.Interface(
304
+ fn=mindfulness_exercise_exposed,
305
+ inputs=[],
306
+ outputs=gr.Textbox(label="Mindfulness Exercise"),
307
+ title="Mindfulness Exercise",
308
+ description="Guided grounding and mindfulness techniques"
309
+ )
310
+
311
+ # Main tabbed interface
312
+ with gr.Blocks(title="🧠 Psychology Personal Agent - Full Suite", theme=gr.themes.Soft()) as demo:
313
 
314
+ # Safety warning
315
+ gr.Markdown("# ⚠️ SAFETY NOTICE")
316
+ gr.Markdown("""**THIS IS NOT MEDICAL ADVICE.** For crisis situations, call 911 or 988.
317
+ This AI provides supportive guidance only - always consult professionals for serious concerns.""")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
 
319
+ gr.Markdown("# 🧠 Psychology Personal Agent - Complete Suite")
320
+ gr.Markdown("*Advanced psychological support with multiple specialized functions*")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
 
322
+ with gr.Tab("🗣️ General Support"):
323
+ psychology_interface.render()
 
 
 
 
324
 
325
+ with gr.Tab("🛡️ Trauma Support"):
326
+ trauma_interface.render()
327
+
328
+ with gr.Tab("⚡ Panic Support"):
329
+ panic_interface.render()
330
+
331
+ with gr.Tab("💭 Emotion Processing"):
332
+ emotion_interface.render()
333
+
334
+ with gr.Tab("📊 Sentiment Analysis"):
335
+ sentiment_interface.render()
336
+
337
+ with gr.Tab("👥 Relationship Analysis"):
338
+ relationship_interface.render()
339
+
340
+ with gr.Tab("🎯 Coping Strategies"):
341
+ coping_interface.render()
342
+
343
+ with gr.Tab("🆘 Crisis Resources"):
344
+ crisis_interface.render()
345
+
346
+ with gr.Tab("🧘 Mindfulness"):
347
+ mindfulness_interface.render()
348
 
349
  if __name__ == "__main__":
350
  demo.launch(
 
358
  else:
359
  print("❌ Failed to load psychology model")
360
 
361
+ def error_response(x=""):
362
  return "⚠️ Model loading error. Please check console logs and try restarting."
363
 
364
  demo = gr.Interface(