invincible-jha commited on
Commit
5a6069c
·
1 Parent(s): 7f28651

Fix Gradio compatibility issues and update interface

Browse files
Files changed (1) hide show
  1. interface/app.py +126 -168
interface/app.py CHANGED
@@ -1,198 +1,156 @@
1
  import gradio as gr
2
- from typing import Dict, List
3
- import os
 
4
 
5
  class WellnessInterface:
6
- def __init__(self, config: Dict):
7
  self.config = config
8
- self.interface = None
 
 
9
  self.setup_interface()
10
 
11
  def setup_interface(self):
12
- """Set up the Gradio interface"""
13
- with gr.Blocks(theme=gr.themes.Soft()) as self.interface:
14
- gr.Markdown("# Mental Wellness Support Platform")
15
- gr.Markdown("Welcome to your AI-powered mental wellness support system. "
16
- "Please note that this is not a substitute for professional mental health care.")
17
-
18
- with gr.Row():
19
- with gr.Column(scale=3):
20
- # Chat interface
21
- self.chatbot = gr.Chatbot(
22
- label="Conversation",
23
- height=400
24
- )
25
- with gr.Row():
26
- self.msg = gr.Textbox(
27
- label="Type your message",
28
- placeholder="Share what's on your mind...",
29
- scale=4
30
- )
31
- self.send = gr.Button("Send", scale=1)
32
-
33
- # Voice input
34
- self.audio_input = gr.Audio(
35
- label="Voice Input",
36
- source="microphone",
37
- type="filepath"
38
- )
39
-
40
- with gr.Column(scale=1):
41
- # Wellness tools
42
- with gr.Tab("Tools"):
43
- gr.Markdown("### Wellness Tools")
44
- self.meditation_btn = gr.Button("Start Meditation")
45
- self.assessment_btn = gr.Button("Mental Health Check-in")
46
- self.resources_btn = gr.Button("View Resources")
47
-
48
- # Session analytics
49
- with gr.Tab("Analytics"):
50
- self.analytics_display = gr.JSON(
51
- label="Session Analytics",
52
- value={}
53
- )
54
- self.update_analytics_btn = gr.Button("Update Analytics")
55
-
56
- # File upload for image/video
57
- with gr.Row():
58
- self.file_upload = gr.File(
59
- label="Upload Image/Video",
60
- file_types=["image", "video"]
61
- )
62
-
63
- # Emergency resources
64
- with gr.Row():
65
- gr.Markdown("""
66
- ### Emergency Resources
67
- If you're experiencing a mental health emergency:
68
- - Emergency Services: 911 (US)
69
- - National Crisis Hotline: 988
70
- - Crisis Text Line: Text HOME to 741741
71
- """)
72
-
73
- # Set up event handlers
74
- self.send.click(
75
- fn=self._handle_text_input,
76
- inputs=[self.msg, self.chatbot],
77
- outputs=[self.msg, self.chatbot]
78
  )
79
 
80
- self.audio_input.change(
81
- fn=self._handle_voice_input,
82
- inputs=[self.audio_input, self.chatbot],
83
- outputs=[self.chatbot]
 
84
  )
85
 
86
- self.file_upload.change(
87
- fn=self._handle_file_upload,
88
- inputs=[self.file_upload, self.chatbot],
89
- outputs=[self.chatbot]
 
90
  )
91
 
92
- self.update_analytics_btn.click(
93
- fn=self._update_analytics,
94
- inputs=[],
95
- outputs=[self.analytics_display]
96
  )
97
 
98
- # Wellness tool handlers
99
- self.meditation_btn.click(
100
- fn=self._start_meditation,
101
- inputs=[self.chatbot],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  outputs=[self.chatbot]
103
  )
104
 
105
- self.assessment_btn.click(
106
- fn=self._start_assessment,
107
- inputs=[self.chatbot],
108
  outputs=[self.chatbot]
109
  )
110
 
111
- self.resources_btn.click(
112
- fn=self._show_resources,
113
- inputs=[self.chatbot],
114
  outputs=[self.chatbot]
115
  )
116
 
117
- def _handle_text_input(self, message: str, history: list) -> tuple:
118
- """Handle text input from user"""
119
- if message:
120
- # For now, just echo the message
121
- response = f"You said: {message}"
122
- history.append((message, response))
123
- return "", history
124
- return message, history
125
-
126
- def _handle_voice_input(self, audio_path: str, history: list) -> list:
127
- """Handle voice input from user"""
128
- if audio_path:
129
- response = "Voice message received! (Voice processing coming soon)"
130
- history.append(("🎤 Voice message", response))
131
- return history
132
-
133
- def _handle_file_upload(self, file: gr.File, history: list) -> list:
134
- """Handle file upload from user"""
135
- if file:
136
- response = f"Received file: {file.name} (Media processing coming soon)"
137
- history.append((f"📎 Uploaded: {file.name}", response))
138
- return history
139
-
140
- def _update_analytics(self) -> Dict:
141
- """Update analytics display"""
142
- return {
143
- "sessions": 1,
144
- "messages": len(self.chatbot.value) if self.chatbot.value else 0,
145
- "status": "Demo Mode"
146
- }
147
-
148
- def _start_meditation(self, history: list) -> list:
149
- """Start meditation session"""
150
- response = """Let's begin a simple breathing exercise:
151
- 1. Find a comfortable position
152
- 2. Close your eyes or maintain a soft gaze
153
- 3. We'll practice deep breathing together
154
-
155
- Are you ready to start? (Reply 'yes' when ready)"""
156
- history.append(("🧘 Started meditation session", response))
157
- return history
158
-
159
- def _start_assessment(self, history: list) -> list:
160
- """Start mental health assessment"""
161
- response = """I'll help you with a quick mental health check-in.
162
- We'll use standard screening tools to understand how you're feeling.
163
-
164
- Would you like to:
165
- 1. Check anxiety levels (GAD-7)
166
- 2. Check mood/depression (PHQ-9)
167
- 3. General well-being assessment
168
-
169
- Please choose a number (1-3)."""
170
- history.append(("📋 Started assessment", response))
171
- return history
172
-
173
- def _show_resources(self, history: list) -> list:
174
- """Show mental health resources"""
175
- response = """Here are some helpful resources:
176
-
177
- 📱 Quick Tools:
178
- - Breathing exercises
179
- - Grounding techniques
180
- - Meditation guides
181
 
182
- 📚 Educational Resources:
183
- - Understanding anxiety
184
- - Stress management
185
- - Building resilience
186
 
187
- 🤝 Support Services:
188
- - Find local therapists
189
- - Support groups
190
- - Crisis hotlines
 
 
 
 
 
 
 
 
191
 
192
- Which would you like to learn more about?"""
193
- history.append(("📚 Resource guide", response))
194
- return history
195
 
196
  def launch(self, **kwargs):
197
- """Launch the Gradio interface"""
 
198
  self.interface.launch(**kwargs)
 
1
  import gradio as gr
2
+ import logging
3
+ from utils.log_manager import LogManager
4
+ from utils.analytics_logger import AnalyticsLogger
5
 
6
  class WellnessInterface:
7
+ def __init__(self, config):
8
  self.config = config
9
+ self.log_manager = LogManager()
10
+ self.logger = self.log_manager.get_agent_logger("interface")
11
+ self.analytics = AnalyticsLogger()
12
  self.setup_interface()
13
 
14
  def setup_interface(self):
15
+ """Setup the Gradio interface components"""
16
+ self.logger.info("Setting up interface components")
17
+
18
+ try:
19
+ # Chat interface
20
+ self.chatbot = gr.Chatbot(
21
+ label="Mental Wellness Assistant",
22
+ type="messages", # Using new message format
23
+ height=400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  )
25
 
26
+ # Text input
27
+ self.text_input = gr.Textbox(
28
+ label="Type your message",
29
+ placeholder="Enter your message here...",
30
+ lines=2
31
  )
32
 
33
+ # Audio input
34
+ self.audio_input = gr.Audio(
35
+ label="Voice Input",
36
+ type="filepath", # Using filepath instead of source
37
+ format="wav"
38
  )
39
 
40
+ # Image input
41
+ self.image_input = gr.Image(
42
+ label="Image Upload",
43
+ type="filepath"
44
  )
45
 
46
+ # Control buttons
47
+ self.submit_btn = gr.Button("Send")
48
+ self.clear_btn = gr.Button("Clear Chat")
49
+ self.emergency_btn = gr.Button("Emergency Help", variant="secondary")
50
+
51
+ # Setup interface layout
52
+ self.interface = gr.Interface(
53
+ fn=self.process_input,
54
+ inputs=[
55
+ self.text_input,
56
+ self.audio_input,
57
+ self.image_input,
58
+ self.chatbot
59
+ ],
60
+ outputs=[self.chatbot],
61
+ title="Mental Wellness Support",
62
+ description="A safe space for mental health support and guidance.",
63
+ theme=self.config["INTERFACE_CONFIG"]["theme"],
64
+ allow_flagging="never"
65
+ )
66
+
67
+ # Setup event handlers
68
+ self.submit_btn.click(
69
+ fn=self.process_input,
70
+ inputs=[
71
+ self.text_input,
72
+ self.audio_input,
73
+ self.image_input,
74
+ self.chatbot
75
+ ],
76
  outputs=[self.chatbot]
77
  )
78
 
79
+ self.clear_btn.click(
80
+ fn=self.clear_chat,
81
+ inputs=[],
82
  outputs=[self.chatbot]
83
  )
84
 
85
+ self.emergency_btn.click(
86
+ fn=self.emergency_help,
87
+ inputs=[],
88
  outputs=[self.chatbot]
89
  )
90
 
91
+ self.logger.info("Interface setup completed successfully")
92
+
93
+ except Exception as e:
94
+ self.logger.error(f"Error setting up interface: {str(e)}")
95
+ raise
96
+
97
+ def process_input(self, text, audio, image, history):
98
+ """Process user input from various sources"""
99
+ try:
100
+ # Log the interaction start
101
+ self.analytics.log_user_interaction(
102
+ user_id="anonymous",
103
+ interaction_type="message",
104
+ agent_type="interface",
105
+ duration=0,
106
+ success=True,
107
+ details={"input_types": {
108
+ "text": bool(text),
109
+ "audio": bool(audio),
110
+ "image": bool(image)
111
+ }}
112
+ )
113
+
114
+ # Process the input (placeholder)
115
+ response = "I understand and I'm here to help. Could you tell me more about how you're feeling?"
116
+
117
+ # Add to chat history using the new message format
118
+ history.append({"role": "user", "content": text if text else "Sent media"})
119
+ history.append({"role": "assistant", "content": response})
120
+
121
+ return history
122
+
123
+ except Exception as e:
124
+ self.logger.error(f"Error processing input: {str(e)}")
125
+ return history + [
126
+ {"role": "assistant", "content": "I apologize, but I encountered an error. Please try again."}
127
+ ]
128
+
129
+ def clear_chat(self):
130
+ """Clear the chat history"""
131
+ self.logger.info("Clearing chat history")
132
+ return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
+ def emergency_help(self):
135
+ """Provide emergency help information"""
136
+ self.logger.info("Emergency help requested")
 
137
 
138
+ emergency_message = [
139
+ {"role": "assistant", "content": """
140
+ If you're experiencing a mental health emergency:
141
+
142
+ 🚨 Emergency Services: 911 (US)
143
+ 🆘 National Crisis Hotline: 988
144
+ 💭 Crisis Text Line: Text HOME to 741741
145
+
146
+ These services are available 24/7 and are staffed by trained professionals.
147
+ Your life matters, and help is available.
148
+ """}
149
+ ]
150
 
151
+ return emergency_message
 
 
152
 
153
  def launch(self, **kwargs):
154
+ """Launch the interface"""
155
+ self.logger.info("Launching interface")
156
  self.interface.launch(**kwargs)