Anupam251272 commited on
Commit
451eebe
1 Parent(s): cc9101b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +290 -0
app.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ from sklearn.preprocessing import StandardScaler
5
+ from sklearn.model_selection import train_test_split
6
+ from tensorflow.keras.models import Sequential
7
+ from tensorflow.keras.layers import Dense, Dropout, LSTM
8
+ import tensorflow as tf
9
+ import json
10
+ import datetime
11
+ import os
12
+ import plotly.express as px
13
+ import logging
14
+ from typing import Dict, List, Optional
15
+
16
+ # Set up logging
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format='%(asctime)s - %(levelname)s - %(message)s'
20
+ )
21
+ logger = logging.getLogger(__name__)
22
+
23
+ class VRTherapySystem:
24
+ def __init__(self):
25
+ """Initialize the VR Therapy System"""
26
+ try:
27
+ self.data_dir = "vr_therapy_data"
28
+ os.makedirs(self.data_dir, exist_ok=True)
29
+ self.session_data = self._load_or_create_session_data()
30
+ self.user_profiles = self._load_or_create_user_profiles()
31
+ logger.info("VR Therapy System initialized successfully")
32
+ except Exception as e:
33
+ logger.error(f"Error initializing VR Therapy System: {str(e)}")
34
+ raise
35
+
36
+ def _load_or_create_session_data(self) -> pd.DataFrame:
37
+ """Load existing session data or create new DataFrame"""
38
+ try:
39
+ file_path = os.path.join(self.data_dir, 'session_data.csv')
40
+ if os.path.exists(file_path):
41
+ return pd.read_csv(file_path)
42
+ else:
43
+ df = pd.DataFrame(columns=[
44
+ 'user_id', 'timestamp', 'session_duration',
45
+ 'pain_reduction', 'mobility_improvement'
46
+ ])
47
+ df.to_csv(file_path, index=False)
48
+ return df
49
+ except Exception as e:
50
+ logger.error(f"Error loading session data: {str(e)}")
51
+ return pd.DataFrame()
52
+
53
+ def _load_or_create_user_profiles(self) -> pd.DataFrame:
54
+ """Load existing user profiles or create new DataFrame"""
55
+ try:
56
+ file_path = os.path.join(self.data_dir, 'user_profiles.csv')
57
+ if os.path.exists(file_path):
58
+ return pd.read_csv(file_path)
59
+ else:
60
+ df = pd.DataFrame(columns=[
61
+ 'user_id', 'age', 'condition', 'therapy_goals'
62
+ ])
63
+ df.to_csv(file_path, index=False)
64
+ return df
65
+ except Exception as e:
66
+ logger.error(f"Error loading user profiles: {str(e)}")
67
+ return pd.DataFrame()
68
+
69
+ def save_user_profile(self, user_id: str, age: int, condition: str,
70
+ therapy_goals: str) -> str:
71
+ """Save or update user profile"""
72
+ try:
73
+ new_profile = pd.DataFrame([{
74
+ 'user_id': user_id,
75
+ 'age': age,
76
+ 'condition': condition,
77
+ 'therapy_goals': therapy_goals
78
+ }])
79
+
80
+ # Update existing or append new
81
+ if user_id in self.user_profiles['user_id'].values:
82
+ self.user_profiles.loc[
83
+ self.user_profiles['user_id'] == user_id
84
+ ] = new_profile.iloc[0]
85
+ else:
86
+ self.user_profiles = pd.concat(
87
+ [self.user_profiles, new_profile],
88
+ ignore_index=True
89
+ )
90
+
91
+ # Save to CSV
92
+ self.user_profiles.to_csv(
93
+ os.path.join(self.data_dir, 'user_profiles.csv'),
94
+ index=False
95
+ )
96
+ logger.info(f"Profile saved successfully for user {user_id}")
97
+ return "Profile saved successfully"
98
+ except Exception as e:
99
+ error_msg = f"Error saving user profile: {str(e)}"
100
+ logger.error(error_msg)
101
+ return error_msg
102
+
103
+ def generate_therapy_session(self, user_id: str, pain_level: int,
104
+ mobility_score: int) -> str:
105
+ """Generate a personalized therapy session"""
106
+ try:
107
+ difficulty = self._calculate_difficulty(pain_level, mobility_score)
108
+ session = self._create_session_plan(difficulty)
109
+ logger.info(f"Therapy session generated for user {user_id}")
110
+ return json.dumps(session, indent=2)
111
+ except Exception as e:
112
+ error_msg = f"Error generating therapy session: {str(e)}"
113
+ logger.error(error_msg)
114
+ return json.dumps({"error": error_msg})
115
+
116
+ def _calculate_difficulty(self, pain_level: int, mobility_score: int) -> str:
117
+ """Calculate session difficulty"""
118
+ try:
119
+ score = (10 - pain_level) * 0.3 + mobility_score * 0.7
120
+ if score < 4:
121
+ return "basic"
122
+ elif score < 7:
123
+ return "intermediate"
124
+ else:
125
+ return "advanced"
126
+ except Exception as e:
127
+ logger.error(f"Error calculating difficulty: {str(e)}")
128
+ return "basic"
129
+
130
+ def _create_session_plan(self, difficulty: str) -> Dict:
131
+ """Create a therapy session plan"""
132
+ exercises = {
133
+ "basic": [
134
+ "Guided Breathing",
135
+ "Gentle Stretching",
136
+ "Simple Range of Motion"
137
+ ],
138
+ "intermediate": [
139
+ "Balance Training",
140
+ "Strength Exercises",
141
+ "Coordination Tasks"
142
+ ],
143
+ "advanced": [
144
+ "Complex Movement Patterns",
145
+ "Endurance Training",
146
+ "Dynamic Balance"
147
+ ]
148
+ }
149
+
150
+ return {
151
+ "difficulty": difficulty,
152
+ "exercises": exercises.get(difficulty, exercises["basic"]),
153
+ "duration": 30,
154
+ "rest_periods": "As needed",
155
+ "modifications": "Available upon request"
156
+ }
157
+
158
+ def log_session_progress(self, user_id: str, session_duration: int,
159
+ pain_reduction: int, mobility_improvement: int) -> str:
160
+ """Log therapy session progress"""
161
+ try:
162
+ new_session = pd.DataFrame([{
163
+ 'user_id': user_id,
164
+ 'timestamp': datetime.datetime.now().isoformat(),
165
+ 'session_duration': session_duration,
166
+ 'pain_reduction': pain_reduction,
167
+ 'mobility_improvement': mobility_improvement
168
+ }])
169
+
170
+ self.session_data = pd.concat(
171
+ [self.session_data, new_session],
172
+ ignore_index=True
173
+ )
174
+
175
+ # Save to CSV
176
+ self.session_data.to_csv(
177
+ os.path.join(self.data_dir, 'session_data.csv'),
178
+ index=False
179
+ )
180
+ logger.info(f"Session progress logged for user {user_id}")
181
+ return "Session progress logged successfully"
182
+ except Exception as e:
183
+ error_msg = f"Error logging session progress: {str(e)}"
184
+ logger.error(error_msg)
185
+ return error_msg
186
+
187
+ def get_user_analytics(self, user_id: str) -> str:
188
+ """Generate user analytics"""
189
+ try:
190
+ user_sessions = self.session_data[
191
+ self.session_data['user_id'] == user_id
192
+ ]
193
+
194
+ if len(user_sessions) == 0:
195
+ return json.dumps({"message": "No sessions found for this user"})
196
+
197
+ analytics = {
198
+ "total_sessions": len(user_sessions),
199
+ "average_duration": user_sessions['session_duration'].mean(),
200
+ "average_pain_reduction": user_sessions['pain_reduction'].mean(),
201
+ "average_mobility_improvement": user_sessions['mobility_improvement'].mean(),
202
+ "progress_trend": user_sessions['mobility_improvement'].tolist()
203
+ }
204
+
205
+ logger.info(f"Analytics generated for user {user_id}")
206
+ return json.dumps(analytics, indent=2)
207
+ except Exception as e:
208
+ error_msg = f"Error generating analytics: {str(e)}"
209
+ logger.error(error_msg)
210
+ return json.dumps({"error": error_msg})
211
+
212
+ # Create Gradio interface
213
+ def create_interface():
214
+ try:
215
+ vr_system = VRTherapySystem()
216
+
217
+ with gr.Blocks(title="VR Therapy System") as interface:
218
+ gr.Markdown("# VR Therapy and Rehabilitation System")
219
+
220
+ with gr.Tab("User Profile"):
221
+ with gr.Row():
222
+ user_id = gr.Textbox(label="User ID")
223
+ age = gr.Number(label="Age")
224
+ condition = gr.Textbox(label="Medical Condition")
225
+ therapy_goals = gr.TextArea(label="Therapy Goals")
226
+ save_profile_btn = gr.Button("Save Profile")
227
+ profile_output = gr.Textbox(label="Profile Status")
228
+
229
+ with gr.Tab("Therapy Session"):
230
+ with gr.Row():
231
+ session_user_id = gr.Textbox(label="User ID")
232
+ pain_level = gr.Slider(1, 10, label="Pain Level")
233
+ mobility_score = gr.Slider(1, 10, label="Mobility Score")
234
+ generate_btn = gr.Button("Generate Session")
235
+ session_output = gr.JSON(label="Session Plan")
236
+
237
+ with gr.Tab("Progress Logging"):
238
+ with gr.Row():
239
+ log_user_id = gr.Textbox(label="User ID")
240
+ duration = gr.Number(label="Session Duration (minutes)")
241
+ pain_reduction = gr.Slider(0, 10, label="Pain Reduction")
242
+ mobility_improvement = gr.Slider(0, 10, label="Mobility Improvement")
243
+ log_btn = gr.Button("Log Progress")
244
+ log_output = gr.Textbox(label="Logging Status")
245
+
246
+ with gr.Tab("Analytics"):
247
+ analytics_user_id = gr.Textbox(label="User ID")
248
+ analytics_btn = gr.Button("Generate Analytics")
249
+ analytics_output = gr.JSON(label="User Analytics")
250
+
251
+ # Connect interface functions
252
+ save_profile_btn.click(
253
+ vr_system.save_user_profile,
254
+ inputs=[user_id, age, condition, therapy_goals],
255
+ outputs=profile_output
256
+ )
257
+
258
+ generate_btn.click(
259
+ vr_system.generate_therapy_session,
260
+ inputs=[session_user_id, pain_level, mobility_score],
261
+ outputs=session_output
262
+ )
263
+
264
+ log_btn.click(
265
+ vr_system.log_session_progress,
266
+ inputs=[log_user_id, duration, pain_reduction, mobility_improvement],
267
+ outputs=log_output
268
+ )
269
+
270
+ analytics_btn.click(
271
+ vr_system.get_user_analytics,
272
+ inputs=analytics_user_id,
273
+ outputs=analytics_output
274
+ )
275
+
276
+ return interface
277
+
278
+ except Exception as e:
279
+ logger.error(f"Error creating interface: {str(e)}")
280
+ raise
281
+
282
+ # Launch the application
283
+ if __name__ == "__main__":
284
+ try:
285
+ interface = create_interface()
286
+ interface.launch(share=True)
287
+ logger.info("VR Therapy System launched successfully")
288
+ except Exception as e:
289
+ logger.error(f"Error launching application: {str(e)}")
290
+ print(f"Error: {str(e)}")