NitinBot001 commited on
Commit
b93b52b
·
verified ·
1 Parent(s): b2ff0a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +251 -84
app.py CHANGED
@@ -1,114 +1,281 @@
1
  from flask import Flask, request, jsonify, render_template_string
2
  import sqlite3
3
  import datetime
4
- import json
5
 
6
  app = Flask(__name__)
 
7
 
8
- HTML_TEMPLATE = """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  <!DOCTYPE html>
10
  <html>
11
  <head>
12
- <title>Rover Vitals Dashboard</title>
13
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
14
  <style>
15
- body { font-family: 'Segoe UI', Tahoma, sans-serif; background-color: #f4f7f6; padding: 20px; }
16
- h1 { text-align: center; color: #2c3e50; }
17
- .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 20px; max-width: 1200px; margin: auto; }
18
- .card { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
19
- .card h2 { margin-top: 0; color: #34495e; border-bottom: 2px solid #3498db; padding-bottom: 10px; }
20
- .vitals { display: flex; justify-content: space-between; margin-bottom: 15px; font-weight: bold; font-size: 18px;}
21
- canvas { max-height: 250px; }
 
 
 
 
 
 
 
 
22
  </style>
23
  </head>
24
  <body>
25
- <h1>🏥 Autonomous Rover Vitals Dashboard</h1>
26
- <div class="grid">
27
- {% for row in rows %}
28
- <div class="card">
29
- <h2>Patient Bed: {{ row[1] }} <span style="float:right; font-size:14px; color:gray">{{ row[6] }}</span></h2>
30
- <div class="vitals">
31
- <span style="color:#e74c3c">BPM: {{ row[2] }}</span>
32
- <span style="color:#3498db">SpO2: {{ row[3] }}%</span>
33
- <span style="color:#f39c12">Temp: {{ row[4] }}°C</span>
34
- </div>
35
- <canvas id="ecgChart{{ row[0] }}"></canvas>
36
- <script>
37
- const ctx{{ row[0] }} = document.getElementById('ecgChart{{ row[0] }}').getContext('2d');
38
- const ecgData{{ row[0] }} = JSON.parse('{{ row[5] }}');
39
- new Chart(ctx{{ row[0] }}, {
40
- type: 'line',
41
- data: {
42
- labels: Array.from({length: ecgData{{ row[0] }}.length}, (_, i) => i),
43
- datasets: [{
44
- label: 'ECG Trace',
45
- data: ecgData{{ row[0] }},
46
- borderColor: '#2ecc71',
47
- borderWidth: 1.5,
48
- pointRadius: 0,
49
- tension: 0.3
50
- }]
51
- },
52
- options: { responsive: true, maintainAspectRatio: false, scales: { x: { display: false } } }
53
- });
54
- </script>
55
  </div>
56
- {% endfor %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  </body>
59
  </html>
60
- """
61
 
62
- def init_db():
63
- conn = sqlite3.connect('hospital_vitals.db')
 
64
  c = conn.cursor()
65
- # Added ecg_data column
66
- c.execute('''CREATE TABLE IF NOT EXISTS patient_records (
67
- id INTEGER PRIMARY KEY AUTOINCREMENT,
68
- bed_id INTEGER, bpm INTEGER, spo2 INTEGER, temp_c REAL,
69
- ecg_data TEXT, timestamp TEXT
70
- )''')
71
- conn.commit()
72
  conn.close()
 
73
 
74
- @app.route('/api/vitals', methods=['POST'])
75
- def receive_vitals():
76
- try:
77
- # Get JSON safely
78
- data = request.get_json(silent=True)
79
- if data is None:
80
- print("❌ ERROR: Received Invalid or Incomplete JSON from ESP32!")
81
- print("Raw Data:", request.get_data())
82
- return jsonify({"status": "error", "message": "Invalid JSON"}), 400
83
-
84
- bed_id, bpm, spo2, temp = data.get('bed_id'), data.get('bpm'), data.get('spo2'), data.get('temp')
85
- ecg_array = data.get('ecg', [])
86
-
87
- ecg_json_str = json.dumps(ecg_array)
88
- timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
89
-
90
- conn = sqlite3.connect('hospital_vitals.db')
91
- c = conn.cursor()
92
- c.execute("INSERT INTO patient_records (bed_id, bpm, spo2, temp_c, ecg_data, timestamp) VALUES (?, ?, ?, ?, ?, ?)",
93
- (bed_id, bpm, spo2, temp, ecg_json_str, timestamp))
94
- conn.commit()
95
  conn.close()
96
- print(f"✅ [{timestamp}] Saved -> Bed: {bed_id} | ECG Points: {len(ecg_array)}")
97
- return jsonify({"status": "success"}), 201
 
 
 
 
 
98
 
99
- except Exception as e:
100
- print(f"❌ DATABASE/SERVER ERROR: {str(e)}")
101
- return jsonify({"status": "error", "message": str(e)}), 400
 
 
 
 
 
 
102
 
103
- @app.route('/')
104
- def dashboard():
105
- conn = sqlite3.connect('hospital_vitals.db')
106
  c = conn.cursor()
107
- c.execute("SELECT * FROM patient_records ORDER BY id DESC")
108
- rows = c.fetchall()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  conn.close()
110
- return render_template_string(HTML_TEMPLATE, rows=rows)
111
 
112
  if __name__ == '__main__':
113
- init_db()
114
  app.run(host='0.0.0.0', port=7860)
 
1
  from flask import Flask, request, jsonify, render_template_string
2
  import sqlite3
3
  import datetime
 
4
 
5
  app = Flask(__name__)
6
+ DB_NAME = "hospital.db"
7
 
8
+ def init_db():
9
+ conn = sqlite3.connect(DB_NAME)
10
+ c = conn.cursor()
11
+ c.execute('''CREATE TABLE IF NOT EXISTS patients
12
+ (bed_id INTEGER PRIMARY KEY, name TEXT, age INTEGER, gender TEXT, disease TEXT)''')
13
+ c.execute('''CREATE TABLE IF NOT EXISTS vitals
14
+ (id INTEGER PRIMARY KEY AUTOINCREMENT, bed_id INTEGER, bpm REAL, spo2 REAL, temp REAL, ecg TEXT, timestamp TEXT)''')
15
+ conn.commit()
16
+ conn.close()
17
+
18
+ init_db()
19
+
20
+ # --- MAIN DASHBOARD TEMPLATE ---
21
+ HTML_TEMPLATE = '''
22
+ <!DOCTYPE html>
23
+ <html>
24
+ <head>
25
+ <title>Hospital Ward Control Dashboard</title>
26
+ <style>
27
+ body { font-family: 'Segoe UI', sans-serif; background-color: #f4f6f9; padding: 20px; }
28
+ .container { max-width: 1000px; margin: 0 auto; background: white; padding: 25px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
29
+ table { width: 100%; border-collapse: collapse; margin-top: 15px; margin-bottom: 30px; }
30
+ th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
31
+ th { background-color: #3498db; color: white; }
32
+ input, select { padding: 10px; border: 1px solid #ccc; border-radius: 4px; width: 140px; }
33
+ button { background-color: #2ecc71; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
34
+ .btn-view { background-color: #f39c12; color: white; padding: 6px 12px; text-decoration: none; border-radius: 4px; font-weight: bold; font-size: 14px; }
35
+ .btn-remove { color: red; font-weight: bold; text-decoration: none; margin-left: 15px; font-size: 14px; }
36
+ </style>
37
+ </head>
38
+ <body>
39
+ <div class="container">
40
+ <h2>🏥 Autonomous Medical Assistant - Ward Dashboard</h2>
41
+
42
+ <h3>Assign Patient to Bed</h3>
43
+ <form action="/add_patient" method="POST" style="margin-bottom: 30px;">
44
+ Bed No: <input type="number" name="bed_id" min="1" style="width:60px;" required>
45
+ Name: <input type="text" name="name" required>
46
+ Age: <input type="number" name="age" style="width:60px;" required>
47
+ Gen: <select name="gender" style="width:60px;"><option>M</option><option>F</option></select>
48
+ Disease: <input type="text" name="disease" required>
49
+ <button type="submit">Assign Patient</button>
50
+ </form>
51
+
52
+ <h3>Active Patients in Ward</h3>
53
+ <table>
54
+ <tr><th>Bed No</th><th>Patient Name</th><th>Age</th><th>Gender</th><th>Diagnosed Disease</th><th>Actions</th></tr>
55
+ {% for p in patients %}
56
+ <tr>
57
+ <td><b>Bed {{ p[0] }}</b></td><td>{{ p[1] }}</td><td>{{ p[2] }}</td><td>{{ p[3] }}</td><td>{{ p[4] }}</td>
58
+ <td>
59
+ <a class="btn-view" href="/report/{{ p[0] }}">View Report</a>
60
+ <a class="btn-remove" href="/remove/{{ p[0] }}">Discharge</a>
61
+ </td>
62
+ </tr>
63
+ {% endfor %}
64
+ {% if not patients %}
65
+ <tr><td colspan="6" style="text-align: center; color: #7f8c8d;">No active patients in the ward.</td></tr>
66
+ {% endif %}
67
+ </table>
68
+ </div>
69
+ </body>
70
+ </html>
71
+ '''
72
+
73
+ # --- PATIENT REPORT TEMPLATE (NOW WITH CHART.JS FOR ECG) ---
74
+ REPORT_TEMPLATE = '''
75
  <!DOCTYPE html>
76
  <html>
77
  <head>
78
+ <title>Patient Report - Bed {{ bed_id }}</title>
79
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
80
  <style>
81
+ body { font-family: 'Segoe UI', sans-serif; background-color: #f4f6f9; padding: 20px; }
82
+ .container { max-width: 900px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
83
+ .header-card { background: #34495e; color: white; padding: 20px; border-radius: 8px; margin-bottom: 25px; }
84
+ .header-card h2 { margin: 0 0 10px 0; color: #ecf0f1; }
85
+ .header-card p { margin: 5px 0; font-size: 16px; color: #bdc3c7; }
86
+ .header-card span { color: #fff; font-weight: bold; }
87
+ table { width: 100%; border-collapse: collapse; margin-top: 15px; }
88
+ th, td { border: 1px solid #ddd; padding: 12px; text-align: center; }
89
+ th { background-color: #2c3e50; color: white; }
90
+ tr:nth-child(even) { background-color: #f9f9f9; }
91
+ .btn-back { display: inline-block; background-color: #3498db; color: white; padding: 10px 20px; text-decoration: none; border-radius: 4px; margin-bottom: 20px; font-weight: bold; }
92
+ .btn-graph { background-color: #e74c3c; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-weight: bold; }
93
+ .btn-graph:hover { background-color: #c0392b; }
94
+ .graph-row { display: none; background-color: #fff !important; }
95
+ .canvas-container { width: 100%; height: 250px; }
96
  </style>
97
  </head>
98
  <body>
99
+ <div class="container">
100
+ <a href="/" class="btn-back">⬅ Back to Dashboard</a>
101
+
102
+ <div class="header-card">
103
+ <h2>Patient Portfolio - Bed {{ bed_id }}</h2>
104
+ <p>Name: <span>{{ patient[1] }}</span> &nbsp;|&nbsp; Age: <span>{{ patient[2] }}</span> &nbsp;|&nbsp; Gender: <span>{{ patient[3] }}</span></p>
105
+ <p>Diagnosis: <span>{{ patient[4] }}</span></p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  </div>
107
+
108
+ <h3>Vitals History</h3>
109
+ <table>
110
+ <tr><th>Timestamp</th><th>Heart Rate</th><th>SpO2 Level</th><th>Temperature</th><th>ECG Trace</th></tr>
111
+ {% for v in vitals %}
112
+ <tr>
113
+ <td>{{ v[6] }}</td>
114
+ <td><b>{% if v[2] > 0 %}{{ v[2] }} BPM{% else %}None{% endif %}</b></td>
115
+ <td><b>{% if v[3] > 0 %}{{ v[3] }} %{% else %}None{% endif %}</b></td>
116
+ <td><b>{% if v[4] > 0 %}{{ v[4] }} °C{% else %}None{% endif %}</b></td>
117
+ <td>
118
+ {% if v[5] == '[0]' or v[5] == '0' %}
119
+ <span style="color:#7f8c8d;">Not Recorded</span>
120
+ {% else %}
121
+ <button class="btn-graph" onclick="toggleGraph('ecgRow{{ v[0] }}', 'ecgCanvas{{ v[0] }}', {{ v[5] }})">View Graph</button>
122
+ {% endif %}
123
+ </td>
124
+ </tr>
125
+
126
+ {% if v[5] != '[0]' and v[5] != '0' %}
127
+ <tr id="ecgRow{{ v[0] }}" class="graph-row">
128
+ <td colspan="5">
129
+ <div class="canvas-container">
130
+ <canvas id="ecgCanvas{{ v[0] }}"></canvas>
131
+ </div>
132
+ </td>
133
+ </tr>
134
+ {% endif %}
135
+
136
+ {% endfor %}
137
+
138
+ {% if not vitals %}
139
+ <tr><td colspan="5" style="text-align: center; color: #7f8c8d;">No vitals recorded yet.</td></tr>
140
+ {% endif %}
141
+ </table>
142
  </div>
143
+
144
+ <script>
145
+ // Object to store chart instances so we don't recreate them on every click
146
+ const charts = {};
147
+
148
+ function toggleGraph(rowId, canvasId, ecgData) {
149
+ const row = document.getElementById(rowId);
150
+ const canvas = document.getElementById(canvasId);
151
+
152
+ if (row.style.display === "none" || row.style.display === "") {
153
+ row.style.display = "table-row";
154
+
155
+ // Draw chart only if it hasn't been drawn yet
156
+ if (!charts[canvasId]) {
157
+ const ctx = canvas.getContext('2d');
158
+
159
+ // Generate X-axis labels (just numbers from 1 to 500)
160
+ const labels = Array.from({length: ecgData.length}, (_, i) => i + 1);
161
+
162
+ charts[canvasId] = new Chart(ctx, {
163
+ type: 'line',
164
+ data: {
165
+ labels: labels,
166
+ datasets: [{
167
+ label: 'ECG Signal (20s Trace)',
168
+ data: ecgData,
169
+ borderColor: '#2ecc71',
170
+ borderWidth: 1.5,
171
+ pointRadius: 0, // Hides the dots to make it look like a smooth medical wave
172
+ fill: false,
173
+ tension: 0.1
174
+ }]
175
+ },
176
+ options: {
177
+ responsive: true,
178
+ maintainAspectRatio: false,
179
+ plugins: {
180
+ legend: { display: true }
181
+ },
182
+ scales: {
183
+ x: { display: false }, // Hide numbers on X axis
184
+ y: {
185
+ suggestedMin: 0,
186
+ suggestedMax: 4095,
187
+ title: { display: true, text: 'ADC Value (0-4095)' }
188
+ }
189
+ }
190
+ }
191
+ });
192
+ }
193
+ } else {
194
+ row.style.display = "none";
195
+ }
196
+ }
197
+ </script>
198
  </body>
199
  </html>
200
+ '''
201
 
202
+ @app.route('/')
203
+ def index():
204
+ conn = sqlite3.connect(DB_NAME)
205
  c = conn.cursor()
206
+ c.execute("SELECT * FROM patients ORDER BY bed_id ASC")
207
+ patients = c.fetchall()
 
 
 
 
 
208
  conn.close()
209
+ return render_template_string(HTML_TEMPLATE, patients=patients)
210
 
211
+ @app.route('/report/<int:bed_id>')
212
+ def view_report(bed_id):
213
+ conn = sqlite3.connect(DB_NAME)
214
+ c = conn.cursor()
215
+
216
+ c.execute("SELECT * FROM patients WHERE bed_id=?", (bed_id,))
217
+ patient = c.fetchone()
218
+
219
+ if not patient:
 
 
 
 
 
 
 
 
 
 
 
 
220
  conn.close()
221
+ return "Patient not found. They might have been discharged.", 404
222
+
223
+ c.execute("SELECT * FROM vitals WHERE bed_id=? ORDER BY timestamp DESC", (bed_id,))
224
+ vitals = c.fetchall()
225
+ conn.close()
226
+
227
+ return render_template_string(REPORT_TEMPLATE, patient=patient, vitals=vitals, bed_id=bed_id)
228
 
229
+ @app.route('/add_patient', methods=['POST'])
230
+ def add_patient():
231
+ conn = sqlite3.connect(DB_NAME)
232
+ c = conn.cursor()
233
+ c.execute("REPLACE INTO patients (bed_id, name, age, gender, disease) VALUES (?, ?, ?, ?, ?)",
234
+ (request.form['bed_id'], request.form['name'][:15], request.form['age'], request.form['gender'], request.form['disease'][:15]))
235
+ conn.commit()
236
+ conn.close()
237
+ return index()
238
 
239
+ @app.route('/remove/<int:bed_id>')
240
+ def remove_patient(bed_id):
241
+ conn = sqlite3.connect(DB_NAME)
242
  c = conn.cursor()
243
+ c.execute("DELETE FROM patients WHERE bed_id=?", (bed_id,))
244
+ c.execute("DELETE FROM vitals WHERE bed_id=?", (bed_id,))
245
+ conn.commit()
246
+ conn.close()
247
+ return index()
248
+
249
+ @app.route('/api/system_status', methods=['GET'])
250
+ def get_status():
251
+ conn = sqlite3.connect(DB_NAME)
252
+ c = conn.cursor()
253
+ c.execute("SELECT COUNT(*) FROM patients")
254
+ count = c.fetchone()[0]
255
+ conn.close()
256
+ return jsonify({"total_patients": count})
257
+
258
+ @app.route('/api/patient/<int:bed_id>', methods=['GET'])
259
+ def get_patient(bed_id):
260
+ conn = sqlite3.connect(DB_NAME)
261
+ c = conn.cursor()
262
+ c.execute("SELECT name, age, gender, disease FROM patients WHERE bed_id=?", (bed_id,))
263
+ row = c.fetchone()
264
+ conn.close()
265
+ if row: return jsonify({"found": True, "name": row[0], "age": row[1], "gender": row[2], "disease": row[3]})
266
+ return jsonify({"found": False})
267
+
268
+ @app.route('/api/vitals', methods=['POST'])
269
+ def save_vitals():
270
+ data = request.json
271
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
272
+ conn = sqlite3.connect(DB_NAME)
273
+ c = conn.cursor()
274
+ c.execute("INSERT INTO vitals (bed_id, bpm, spo2, temp, ecg, timestamp) VALUES (?, ?, ?, ?, ?, ?)",
275
+ (data['bed_id'], data['bpm'], data['spo2'], data['temp'], str(data['ecg']), timestamp))
276
+ conn.commit()
277
  conn.close()
278
+ return jsonify({"status": "success"})
279
 
280
  if __name__ == '__main__':
 
281
  app.run(host='0.0.0.0', port=7860)