-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathview_data.py
More file actions
264 lines (214 loc) Β· 9.36 KB
/
Copy pathview_data.py
File metadata and controls
264 lines (214 loc) Β· 9.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python3
"""
CardioPredict Pro - Data Viewer
View and analyze stored predictions from Supabase database
"""
import os
import requests
import pandas as pd
from datetime import datetime
from dotenv import load_dotenv
import json
# Load environment variables
load_dotenv()
class SupabaseDataViewer:
def __init__(self):
self.supabase_url = os.getenv('SUPABASE_URL')
self.supabase_key = os.getenv('SUPABASE_ANON_KEY')
if not self.supabase_url or not self.supabase_key:
print("β Missing Supabase credentials in .env file")
self.connected = False
return
self.headers = {
'apikey': self.supabase_key,
'Authorization': f'Bearer {self.supabase_key}',
'Content-Type': 'application/json'
}
self.connected = self.test_connection()
def test_connection(self):
"""Test connection to Supabase"""
try:
response = requests.get(
f"{self.supabase_url}/rest/v1/predictions?select=count",
headers=self.headers,
timeout=10
)
return response.status_code == 200
except:
return False
def get_all_predictions(self):
"""Get all predictions from database"""
if not self.connected:
print("β Not connected to database")
return []
try:
response = requests.get(
f"{self.supabase_url}/rest/v1/predictions?select=*&order=timestamp.desc",
headers=self.headers,
timeout=30
)
if response.status_code == 200:
data = response.json()
print(f"β
Retrieved {len(data)} predictions from database")
return data
else:
print(f"β Error fetching data: {response.status_code}")
return []
except Exception as e:
print(f"β Database error: {e}")
return []
def get_recent_predictions(self, limit=10):
"""Get recent predictions"""
if not self.connected:
print("β Not connected to database")
return []
try:
response = requests.get(
f"{self.supabase_url}/rest/v1/predictions?select=*&order=timestamp.desc&limit={limit}",
headers=self.headers,
timeout=10
)
if response.status_code == 200:
return response.json()
return []
except Exception as e:
print(f"β Database error: {e}")
return []
def display_summary(self):
"""Display summary statistics"""
predictions = self.get_all_predictions()
if not predictions:
print("π No predictions found in database")
return
df = pd.DataFrame(predictions)
print("\n" + "="*60)
print("π CARDIOPREDICT PRO - DATABASE SUMMARY")
print("="*60)
# Basic statistics
print(f"π Total Predictions: {len(df)}")
print(f"π
Date Range: {df['timestamp'].min()} to {df['timestamp'].max()}")
# Risk level distribution
if 'overall_result' in df.columns:
print("\nπ― Risk Level Distribution:")
risk_counts = df['overall_result'].value_counts()
for risk, count in risk_counts.items():
percentage = (count / len(df)) * 100
print(f" {risk}: {count} ({percentage:.1f}%)")
# Confidence levels
if 'confidence_level' in df.columns:
print("\nπ Confidence Levels:")
conf_counts = df['confidence_level'].value_counts()
for conf, count in conf_counts.items():
percentage = (count / len(df)) * 100
print(f" {conf}: {count} ({percentage:.1f}%)")
# Demographics
if 'patient_age' in df.columns:
print(f"\nπ₯ Patient Demographics:")
print(f" Average Age: {df['patient_age'].mean():.1f} years")
print(f" Age Range: {df['patient_age'].min()} - {df['patient_age'].max()}")
if 'patient_sex' in df.columns:
sex_counts = df['patient_sex'].value_counts()
print(f" Gender Distribution:")
for sex, count in sex_counts.items():
percentage = (count / len(df)) * 100
print(f" {sex}: {count} ({percentage:.1f}%)")
print("="*60)
def display_recent_predictions(self, limit=5):
"""Display recent predictions in a readable format"""
predictions = self.get_recent_predictions(limit)
if not predictions:
print("π No recent predictions found")
return
print(f"\nπ LAST {len(predictions)} PREDICTIONS")
print("-" * 80)
for i, pred in enumerate(predictions, 1):
print(f"\nπ₯ Prediction #{i}")
print(f" Patient: {pred.get('patient_name', 'Unknown')}")
print(f" Date: {pred.get('timestamp', '').split('T')[0]}")
print(f" Age: {pred.get('patient_age')} | Sex: {pred.get('patient_sex')}")
print(f" Result: {pred.get('overall_result')}")
print(f" Confidence: {pred.get('confidence_level')}")
print(f" Recommendation: {pred.get('recommendation', '')[:50]}...")
def export_to_csv(self, filename=None):
"""Export all data to CSV file"""
predictions = self.get_all_predictions()
if not predictions:
print("β No data to export")
return
if filename is None:
filename = f"cardiopredict_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
df = pd.DataFrame(predictions)
df.to_csv(filename, index=False)
print(f"β
Data exported to: {filename}")
print(f"π Exported {len(df)} records")
def search_by_risk_level(self, risk_level):
"""Search predictions by risk level"""
if not self.connected:
print("β Not connected to database")
return []
try:
response = requests.get(
f"{self.supabase_url}/rest/v1/predictions?select=*&overall_result=ilike.%{risk_level}%&order=timestamp.desc",
headers=self.headers,
timeout=10
)
if response.status_code == 200:
data = response.json()
print(f"π Found {len(data)} predictions with '{risk_level}' risk")
return data
return []
except Exception as e:
print(f"β Search error: {e}")
return []
def main():
"""Main function with interactive menu"""
viewer = SupabaseDataViewer()
if not viewer.connected:
print("β Cannot connect to database. Check your .env file.")
return
print("π« CardioPredict Pro - Data Viewer")
print("Connected to Supabase database β
")
while True:
print("\n" + "="*40)
print("SELECT AN OPTION:")
print("1. π View summary statistics")
print("2. π View recent predictions")
print("3. π Export all data to CSV")
print("4. π Search by risk level")
print("5. ποΈ View all data (raw)")
print("6. πͺ Exit")
print("="*40)
choice = input("\nEnter choice (1-6): ").strip()
if choice == '1':
viewer.display_summary()
elif choice == '2':
limit = input("How many recent predictions? (default 5): ").strip()
try:
limit = int(limit) if limit else 5
except:
limit = 5
viewer.display_recent_predictions(limit)
elif choice == '3':
filename = input("Enter filename (or press Enter for auto): ").strip()
viewer.export_to_csv(filename if filename else None)
elif choice == '4':
risk = input("Enter risk level (High/Moderate/Low): ").strip()
results = viewer.search_by_risk_level(risk)
if results:
df = pd.DataFrame(results)
print(f"\nπ Results for '{risk}' risk:")
for i, pred in enumerate(results[:5], 1):
print(f" {i}. {pred.get('patient_name')} - {pred.get('timestamp', '').split('T')[0]}")
elif choice == '5':
predictions = viewer.get_all_predictions()
if predictions:
df = pd.DataFrame(predictions)
print(f"\nπ ALL DATA ({len(predictions)} records):")
print(df.to_string())
elif choice == '6':
print("π Goodbye!")
break
else:
print("β Invalid choice. Please try again.")
if __name__ == "__main__":
main()