File size: 26,749 Bytes
bb86403
 
 
 
 
 
 
6d64cfb
bb86403
 
a7697db
8c204aa
 
 
 
 
 
 
 
 
 
 
 
 
 
76802bc
8c204aa
 
 
 
 
 
 
 
 
 
 
 
76802bc
8c204aa
 
 
 
 
 
 
a7697db
4cea933
a7697db
4cea933
604d53b
4cea933
8c204aa
 
 
8b66798
8c204aa
 
 
 
8b66798
604d53b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c204aa
604d53b
8c204aa
 
 
 
 
 
604d53b
8c204aa
604d53b
8c204aa
604d53b
 
 
 
 
 
8c204aa
604d53b
8c204aa
604d53b
8c204aa
 
 
 
 
 
 
 
604d53b
 
 
 
 
8c204aa
604d53b
 
 
8c204aa
 
 
 
 
 
 
 
604d53b
 
 
 
 
 
 
8c204aa
604d53b
 
 
 
 
8c204aa
604d53b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cea933
604d53b
 
8c204aa
a7697db
8c204aa
 
 
 
 
 
 
 
 
 
604d53b
 
4cea933
604d53b
4cea933
604d53b
4cea933
604d53b
 
8c204aa
604d53b
 
 
 
 
 
6d64cfb
8c204aa
6d64cfb
604d53b
a7697db
604d53b
 
 
4cea933
6d64cfb
 
 
 
8c204aa
 
6d64cfb
 
 
 
 
 
 
 
 
 
 
72f87bd
617ca3d
 
 
604d53b
 
 
 
3f4c90b
6d64cfb
4cea933
604d53b
4cea933
 
72f87bd
604d53b
 
 
4cea933
604d53b
4cea933
 
 
604d53b
4cea933
 
 
 
 
604d53b
 
 
4cea933
8c204aa
617ca3d
604d53b
 
 
617ca3d
 
 
 
604d53b
 
 
 
 
 
 
8c204aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
604d53b
8c204aa
604d53b
 
 
 
 
 
 
 
617ca3d
72f87bd
8c204aa
604d53b
 
3079b37
72f87bd
604d53b
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
---
title: HeartFlow OS Backend
emoji: πŸ«€
colorFrom: gray
colorTo: red
sdk: docker
pinned: false
app_port: 8000
---

<div align="center">

```
  β–ˆβ–ˆβ•—  β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•—      β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•—    β–ˆβ–ˆβ•—     β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—
  β–ˆβ–ˆβ•‘  β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β•šβ•β•β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•”β•β•β•β•β•β–ˆβ–ˆβ•‘     β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘    β–ˆβ–ˆβ•‘    β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•
  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•   β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—  β–ˆβ–ˆβ•‘     β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ•— β–ˆβ–ˆβ•‘    β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—
  β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•  β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—   β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•”β•β•β•  β–ˆβ–ˆβ•‘     β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘    β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘β•šβ•β•β•β•β–ˆβ–ˆβ•‘
  β–ˆβ–ˆβ•‘  β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘  β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘  β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘   β–ˆβ–ˆβ•‘     β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β•šβ–ˆβ–ˆβ–ˆβ•”β–ˆβ–ˆβ–ˆβ•”β•    β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•‘
  β•šβ•β•  β•šβ•β•β•šβ•β•β•β•β•β•β•β•šβ•β•  β•šβ•β•β•šβ•β•  β•šβ•β•   β•šβ•β•   β•šβ•β•     β•šβ•β•β•β•β•β•β• β•šβ•β•β•β•β•β•  β•šβ•β•β•β•šβ•β•β•      β•šβ•β•β•β•β•β• β•šβ•β•β•β•β•β•β•
```

### **Clinical Cardiovascular Telemetry & Distributed Edge TinyML Transpilation Engine**

<p>
  <a href="https://huggingface.co/spaces/IDKHowToCodeFr/tinyml-backend" target="_blank">
    <img src="https://img.shields.io/badge/HuggingFace-Live_Spaces_Backend-FFD21E.svg?style=for-the-badge&logo=huggingface" alt="Hugging Face Space" />
  </a>
  <a href="https://idkhowtocodefr-tinyml-backend.hf.space/docs" target="_blank">
    <img src="https://img.shields.io/badge/FastAPI-Interactive_Swagger_Docs-009688.svg?style=for-the-badge&logo=fastapi&logoColor=white" alt="Hugging Face API Docs" />
  </a>
  <a href="https://github.com/rachit-mangawa/HEARTFLOW_OS" target="_blank">
    <img src="https://img.shields.io/badge/GitHub-Repository-141413.svg?style=for-the-badge&logo=github" alt="GitHub Repository" />
  </a>
</p>

<p>
  <img src="https://img.shields.io/badge/Edge_Latency-%3C_20_%C2%B5s-blue.svg?style=for-the-badge&logo=speedtest&logoColor=white" alt="Latency" />
  <img src="https://img.shields.io/badge/Memory_ABI-Zero--Malloc_C99-purple.svg?style=for-the-badge" alt="Zero-Malloc" />
  <img src="https://img.shields.io/badge/Quantization-INT8_(--76.4%25_SRAM)-9F2F2D.svg?style=for-the-badge" alt="Quantization" />
  <img src="https://img.shields.io/badge/CI_Tests-58%2F58_Passing-success.svg?style=for-the-badge&logo=githubactions&logoColor=white" alt="Tests" />
  <img src="https://img.shields.io/badge/Next.js-16.3-black.svg?style=for-the-badge&logo=next.js" alt="Next.js" />
  <img src="https://img.shields.io/badge/React-19-61DAFB.svg?style=for-the-badge&logo=react&logoColor=black" alt="React" />
  <img src="https://img.shields.io/badge/TailwindCSS-v4-38B2AC.svg?style=for-the-badge&logo=tailwind-css" alt="Tailwind CSS v4" />
  <img src="https://img.shields.io/badge/License-MIT-green.svg?style=for-the-badge" alt="License" />
</p>

</div>

---

## Executive Architectural Summary

HeartFlow OS is a distributed Edge AI clinical intelligence architecture engineered to decouple real-time physiological diagnostics from cloud computing dependency. The platform bridges clinical cloud machine learning pipelines with resource-constrained, bare-metal microcontrollers (**ESP32-S3, ARM Cortex-M4, RP2040, nRF52840**).

Continuous multi-channel physiological vitals are evaluated across a calibrated **5-model weighted soft-voting ensemble** (Random Forest, Linear SVM, Logistic Regression, MLP Neural Network, and KNN), providing **sub-20Β΅s in-browser anomaly classification**, automated INT8 fixed-point quantization, 250 Hz Lead-II ECG waveform streaming, and zero-malloc C99 embedded transpilation.

> [!NOTE]
> **Complete Technical Documentation**:
> - πŸ“„ **[ARCHITECTURE.md](ARCHITECTURE.md)**: Unified canonical architecture specification (v3.4.0), mathematical calibration proofs, embedded C99 hardware ABI, MLOps continuum, and telemetry engine specifications.
> - 🌐 **Interactive Docs**: Hosted live in the application at `/docs` with interactive in-browser API testing consoles.

---

## Dual-Plane System Architecture

```
+───────────────────────────────────────────────────────────────────────────────────────────────+
|                                  PHYSICAL HARDWARE LAYER                                      |
|  [ AD8232 Lead-II ECG ]  ──(250 Hz Analog)──>  [ ESP32-S3 Microcontroller (12-bit SAR ADC) ]  |
|  [ MAX30102 PPG SpO2  ]  ──(I2C 400 kHz  )──>  [ firmware/src/main.cpp - PlatformIO C99     ]  |
+───────────────────────────────────────────────────────┬───────────────────────────────────────+
                                                        β”‚
                                                        β”‚ UART Serial Frame: $HR,SPO2,SYS,DIA,TEMP*CRC\n
                                                        β”‚ Baud Rate: 115,200 bps
                                                        β–Ό
+───────────────────────────────────────────────────────────────────────────────────────────────+
|                                    CLINICAL BROWSER CLIENT                                    |
|                                (Next.js 16 + React 19 + Tailwind v4)                          |
|                                                                                               |
|   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   |
|   β”‚ Web Serial API Bridge    β”‚ ──> β”‚ Lead-II ECG Oscilloscope   β”‚ ──> β”‚ Telemetry Monitor β”‚   |
|   β”‚ (W3C navigator.serial)   β”‚     β”‚ (60 FPS Canvas GPU Render) β”‚     β”‚ (/monitor)        β”‚   |
|   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   |
|                 β”‚                                                                             |
|                 β–Ό                                                                             |
|   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   |
|   β”‚                   PRIMARY PLANE: ZERO-CLOUD CLIENT TINYML RUNTIME                     β”‚   |
|   β”‚                         Latency: < 20 Β΅s | Egress: 0.0 KB                             β”‚   |
|   β”‚                                                                                       β”‚   |
|   β”‚   Feature Preprocessor ──> Scaler Normalization + Risk_Severity Feature Synthesis     β”‚   |
|   β”‚                                    β”‚                                                  β”‚   |
|   β”‚                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                               β”‚   |
|   β”‚                 β–Ό                                     β–Ό                               β”‚   |
|   β”‚        [ INT8 Quantized Weights ]            [ 5-Model Soft-Voting ]                  β”‚   |
|   β”‚        β€’ RF (30 Trees, Depth 5)              β€’ P(Healthy | X)                         β”‚   |
|   β”‚        β€’ Linear SVM Hyperplane               β€’ P(Hypertension | X)                    β”‚   |
|   β”‚        β€’ Logistic Regression (L2)            β€’ P(Heart Disease | X)                   β”‚   |
|   β”‚        β€’ Small-NN MLP (16x8 ReLU)            β€’ P(Asthma | X)                          β”‚   |
|   β”‚        β€’ KNN (k=5 Distance Weighted)         β€’ P(Diabetes | X)                        β”‚   |
|   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   |
+────────────────────────────────────────────┼──────────────────────────────────────────────────+
                                             β”‚
                                             β”‚ Fallback Tunnel / Cloud REST / Telemetry Ingest
                                             β”‚ HTTP POST / WebSocket (/ws/feed)
                                             β–Ό
+───────────────────────────────────────────────────────────────────────────────────────────────+
|                                  SECONDARY CLOUD BACKEND                                      |
|                               (FastAPI + Uvicorn Async Core)                                  |
|                                                                                               |
|   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   |
|   β”‚ REST & WS Gateways       β”‚ ──> β”‚ MLOps Retrain Pipeline     β”‚ ──> β”‚ Model Registry    β”‚   |
|   β”‚ /predict, /ws/feed, etc. β”‚     β”‚ CSV Ingest & Validation    β”‚     β”‚ 5 .pkl Estimators β”‚   |
|   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   |
|                 β”‚                                                                             |
|                 β–Ό                                                                             |
|   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   |
|   β”‚ AST C99 Code Exporter (/export_tinyml) ──> Zero-Malloc Header (model.h) for Embedded  β”‚   |
|   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   |
+───────────────────────────────────────────────────────────────────────────────────────────────+
```

---

## Performance & Latency Benchmark Matrix

Measured across 10,000 synthetic patient telemetry vectors:

| Execution Target | Runtime Architecture | Latency ($p_{50}$) | Throughput | Visual Latency Comparison |
| :--- | :--- | :---: | :---: | :--- |
| **ESP32-S3 (Bare-Metal)** | PlatformIO C99 Static Header | **18.4 Β΅s** | **54,340 vec/sec** | `β–ˆ` **(1,902x faster than cloud REST)** |
| **Client In-Browser** | TinyML V8 / SpiderMonkey | **120.0 Β΅s** | **8,330 vec/sec** | `β–ˆβ–ˆ` **(291x faster than cloud REST)** |
| **Cloud Container** | FastAPI + Uvicorn (HF Spaces) | **35.0 ms** | **28 req/sec** | `β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ` (Baseline) |
| **Legacy Cloud** | Standard PyTorch Container | **160.0 ms** | **6 req/sec** | `β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ` |

### Deterministic SLA Guarantees
- **Local TinyML Execution**: Guaranteed `< 20 Β΅s` processing budget per telemetry frame.
- **Microcontroller Jitter ($p_{99}$)**: `Β± 1.2 Β΅s` deterministic execution variance without heap allocation (`malloc`-free).
- **Network Egress**: `0.0 KB/s` client data transmission in primary offline mode.

---

## SRAM Footprint & INT8 Fixed-Point Quantization

Continuous 32-bit floating point weights ($W \in \mathbb{R}$) are quantized to signed 8-bit integers ($Q \in [-128, 127]$) using affine scaling:

$$Q = \text{clamp}\left( \text{round}\left( \frac{W}{\text{scale}} \right), -128, 127 \right) \quad \text{where} \quad \text{scale} = \frac{\max(|W|)}{127}$$

| Estimator Architecture | FP32 Footprint | INT8 Quantized | SRAM Savings | Visual Compression | MCU Compatibility |
| :--- | :---: | :---: | :---: | :--- | :--- |
| **Random Forest (30 Trees, D=5)** | 16,384 bytes | 4,096 bytes | **-75.0%** | `β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘` 75.0% | ESP32-S3, RP2040, M4 |
| **Small-NN (MLP 16x8 ReLU)** | 7,168 bytes | 1,792 bytes | **-75.0%** | `β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘` 75.0% | ESP32-S3, RP2040, M4 |
| **Linear Support Vector Machine** | 3,584 bytes | 896 bytes | **-75.0%** | `β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘` 75.0% | ESP32-S3, RP2040, M4 |
| **Logistic Regression (L2)** | 3,072 bytes | 768 bytes | **-75.0%** | `β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘` 75.0% | ESP32-S3, RP2040, M4 |
| **k-Nearest Neighbors ($k=5$)** | 4,400 bytes | 600 bytes | **-86.4%** | `β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘` 86.4% | ESP32-S3, RP2040, M4 |
| **COMPOSITE ENSEMBLE TOTAL** | **34,608 bytes** | **8,152 bytes** | **-76.4%** | `β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘` **-76.4%** | **All MCUs (> 16KB SRAM)** |

---

## Calibrated 5-Model Ensemble Arbitration

Individual estimator posterior probabilities are aggregated using weighted soft-voting to cancel estimator-specific variance:

$$P(\text{Class}_c \mid X) = \frac{\sum_{i=1}^{5} w_i \cdot P_i(\text{Class}_c \mid X)}{\sum_{i=1}^{5} w_i}$$

| Model ID | Estimator Architecture | Weight ($w_i$) | Accuracy | Macro $F_1$ | Primary Architectural Advantage |
| :---: | :--- | :---: | :---: | :---: | :--- |
| `rf` | **Random Forest (30 trees, depth 5)** | **25%** | 95.4% | 0.938 | Captures non-linear physiological interactions |
| `small_nn` | **MLP Neural Net (16-8 hidden layers)** | **25%** | 94.9% | 0.931 | Smooth continuous decision manifold |
| `logreg` | **Logistic Regression (L2 Regularized)** | **20%** | 92.2% | 0.904 | Robust linear baseline calibration |
| `svm` | **Linear SVM (Platt Calibrated)** | **15%** | 93.5% | 0.912 | Maximum-margin class separation hyperplane |
| `knn` | **k-Nearest Neighbors ($k=5$, Weighted)** | **15%** | 91.8% | 0.897 | Localized density anomaly cluster identification |
| **ENSEMBLE** | **Composite Soft-Voting Classifier** | **100%** | **96.2%** | **0.948** | **-42.6% variance reduction vs single tree** |

---

## Hardware Sensor Bridge & UART Protocol

The ESP32 firmware continuously polls the AD8232 ECG analog pin and MAX30102 $I^2C$ registers, assembling packets in NMEA-style ASCII framing:

```text
FORMAT:  $HR,SPO2,SYS_BP,DIA_BP,TEMP*CHECKSUM\n
EXAMPLE: $84,97.5,132,86,37.1*4F\n
```

### Microcontroller Pinout (ESP32-S3)

```
  ESP32-S3 DevKit                      AD8232 ECG Sensor
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚         3V3  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ 3.3V         β”‚
  β”‚         GND  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ GND          β”‚
  β”‚       GPIO4  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ OUTPUT (ADC) β”‚
  β”‚       GPIO5  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ LO+ (LeadOff)β”‚
  β”‚       GPIO6  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ LO- (LeadOff)β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

  ESP32-S3 DevKit                      MAX30102 PPG Sensor
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚         3V3  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ VIN          β”‚
  β”‚         GND  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ GND          β”‚
  β”‚       GPIO8  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ SDA (I2C)    β”‚
  β”‚       GPIO9  β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ SCL (I2C)    β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## Workspace Navigation & Interactive Clinical Routes

| Route | View Name | Clinical & Engineering Purpose |
| :--- | :--- | :--- |
| **`/`** | **Landing Hub** | Engineering telemetry badges, core specs ticker, and architecture feature overview. |
| **`/monitor`** | **Clinical Telemetry** | 60 FPS Lead-II ECG canvas, vitals monitors, auto-healing WebSocket feed, and SHAP attribution. |
| **`/simulator`** | **Physiological Simulator** | Interactive patient vitals simulator, arrhythmia state machine triggers, and edge inference. |
| **`/dataset`** | **Dataset Explorer** | 60,000 observation ground-truth engine: 9Γ—9 Pearson correlation heatmap, 12-bin continuous histograms, balanced disease cohorts, and 25-row paginated inspector. |
| **`/edge`** | **TinyML Edge Compiler** | In-browser & cloud C99 generator for ESP32/Cortex-M with INT8 quantization & zero-malloc memory guarantee. |
| **`/mlops`** | **MLOps Registry & Retrain** | Batch CSV ingestion, schema alias sanitization, F1-macro automated validation gates, and hot-swapping. |
| **`/architecture`** | **Pipeline Topology** | Native architectural schematic detailing client, API, MLOps, and persistence subsystems. |
| **`/history`** | **Clinical Audit Logs** | Local session telemetry history with chronological diagnostic records and risk indicators. |
| **`/analytics`** | **Longitudinal Analytics** | Population distributions, correlation matrices, and model weight arbitration diagnostics. |
| **`/docs`** | **System & API Specs** | Interactive endpoint reference, SVG topology diagrams, latency benchmarks, and live test console. |

---

## API Specifications Contract

Interactive documentation with live in-browser testing is hosted at `/docs`.

| Method | Endpoint | Latency SLA | Description |
| :---: | :--- | :---: | :--- |
| `POST` | `/predict` | `< 20 Β΅s` (Edge) / `< 35 ms` (Cloud) | Evaluates 5 vitals against calibrated 5-model ensemble. |
| `WS` | `/ws/feed` | `< 5 ms` / frame | 60 Hz bidirectional telemetry streaming with concurrent predictions. |
| `GET` | `/export_tinyml` | `< 2 ms` | Transpiles trained models to standalone zero-malloc C99 header (`model.h`). |
| `POST` | `/explain` | `< 15 ms` | TreeExplainer SHAP game-theoretic feature attribution. |
| `POST` | `/retrain` | `< 3.5 s` | Batch CSV upload, alias resolution, refitting, and zero-downtime hot-swap. |
| `GET` | `/metrics` | `< 10 ms` | Accuracy, F1 macro, per-model weights, and edge latency benchmarks. |
| `GET` | `/history` | `< 5 ms` | Returns isolated chronological session telemetry audit records. |
| `GET` | `/dataset/summary` | `< 5 ms` | Precomputed statistical profiling across 60,000 observations (99.8% bandwidth reduction). |
| `GET` | `/dataset` | `< 5 ms` | Dual-mode: legacy list when unparameterized; windowed 25-row records when parameterized. |
| `GET` | `/dataset/download` | `< 100 ms` | Direct streaming download of the verified 4.49 MB ground-truth CSV corpus. |
| `GET` | `/health` | `< 1 ms` | Verifies FastAPI readiness and model memory residency. |

---

## Quickstart Guide

### Option 1: Live Cloud Hugging Face Space (Zero Local Install)

The backend is deployed and running live on Hugging Face Spaces:
- **Hugging Face Space**: [https://huggingface.co/spaces/IDKHowToCodeFr/tinyml-backend](https://huggingface.co/spaces/IDKHowToCodeFr/tinyml-backend)
- **Direct REST API Gateway**: `https://idkhowtocodefr-tinyml-backend.hf.space`
- **Interactive Swagger OpenAPI Docs**: `https://idkhowtocodefr-tinyml-backend.hf.space/docs`
- **WebSocket Telemetry Stream**: `wss://idkhowtocodefr-tinyml-backend.hf.space/ws/feed`

To connect the Next.js frontend to the live cloud backend, set:
```bash
NEXT_PUBLIC_API_URL=https://idkhowtocodefr-tinyml-backend.hf.space
NEXT_PUBLIC_WS_URL=wss://idkhowtocodefr-tinyml-backend.hf.space/ws/feed
```

---

### Option 2: Docker Compose (Full Stack Local)

```bash
docker compose up --build
```
- **Web App**: [http://localhost:3000](http://localhost:3000)
- **FastAPI OpenAPI Docs**: [http://localhost:8000/docs](http://localhost:8000/docs)

---

### Option 3: Local Development Setup

#### 1. Backend (Python 3.10+)
```bash
cd backend
python -m venv .venv
source .venv/bin/activate       # Linux / macOS
.\.venv\Scripts\activate        # Windows PowerShell

pip install -r requirements.txt
python models.py                # Train initial baseline ensemble
uvicorn main:app --reload --port 8000
```

#### 2. Frontend (Node.js 20+)
```bash
cd frontend
npm install
npm run dev
```
Open [http://localhost:3000](http://localhost:3000) in your browser.

---

### Option 4: Hardware Firmware Deployment (ESP32)

1. Open `/edge` in the application or call `/export_tinyml?model_name=rf&quantize=true`.
2. Save the emitted C header to `firmware/src/model.h`.
3. Compile and upload via PlatformIO:

```bash
cd firmware
pio run -t upload
pio device monitor -b 115200
```

---

## Test Verification Suite

The repository is validated against a 58-test automated verification suite (`58/58 passing in ~5.5s`) enforcing strict clinical, mathematical, and safety invariants across all layers.

### Backend Unit & Integration Tests (58/58 passing)

| Test Module | Subsystem Tested | Tests | Key Edge Cases & Invariants Tested |
| :--- | :--- | :---: | :--- |
| **[`test_api.py`](tests/test_api.py)** | REST Gateways & Routes | **21** | β€’ `GET /health` service readiness<br/>β€’ Normal and acute vital sign evaluations (`POST /predict`)<br/>β€’ Game-theoretic SHAP TreeExplainer attributions (`POST /explain`)<br/>β€’ Parameterized C99 exporter queries across all models (`GET /export_tinyml`)<br/>β€’ Dual-mode dataset list & 25-row windowed inspector (`GET /dataset`)<br/>β€’ Statistical moments and CSV download streaming |
| **[`test_export.py`](tests/test_export.py)** | C99 Transpiler & Zero-Malloc ABI | **7** | β€’ Transpilation for all 5 models (`rf`, `svm`, `logreg`, `small_nn`, `knn`)<br/>β€’ FP32 double and INT8 fixed-point quantization<br/>β€’ Zero-Malloc guarantee: static verification that no dynamic allocation calls exist (`malloc`, `calloc`, `realloc`, `free`)<br/>β€’ Balanced braces (`{` == `}`) and include guard integrity<br/>β€’ INT8 saturation clipping $[-128, 127]$ and error handling for null/invalid models |
| **[`test_dataset_analytics.py`](tests/test_dataset_analytics.py)** | Dataset Profiler & Explorer | **8** | β€’ 9Γ—9 Pearson correlation matrix calculation & 12-bin continuous histograms<br/>β€’ In-memory caching by file modification time (`mtime`)<br/>β€’ Boundary clamping (`page <= 0` clamped to 1, `limit > 100` clamped to 100)<br/>β€’ Out-of-bounds page handling (`rows: []`) and case-insensitive cohort filtering |
| **[`test_mlops.py`](tests/test_mlops.py)** | Schema Ingestion & Validation | **6** | β€’ Case-insensitive alias mapping across 40+ header variations (`HR`, `hr`, `sys_bp`, `temp`)<br/>β€’ Corrupt character encoding auto-repair (`\ufffd` $\to$ `Β°C`)<br/>β€’ Missing mandatory signal detection (`ValueError`) and all-NaN row dropping<br/>β€’ Auto-population of optional canonical metadata |
| **[`test_simulator.py`](tests/test_simulator.py)** | Telemetry Physics Simulator | **5** | β€’ Physiological clamping boundaries under extreme vitals (HR $\in [50, 180]$, $SpO_2 \in [80, 100]$, Temp $\in [36.0, 39.0]$)<br/>β€’ State machine transitions across all 5 conditions (`asthma`, `hypertension`, `heart_disease`, `diabetes`, `normal`)<br/>β€’ Physics drift convergence and 1-decimal place precision rounding |
| **[`test_preprocessing.py`](tests/test_preprocessing.py)** | Feature Engineering & Scaler | **4** | β€’ StandardScaler affine transform and artifact serialization<br/>β€’ Target leakage prevention and Risk Severity synthesis heuristic |
| **[`test_database.py`](tests/test_database.py)** | SQLite Audit Logger | **3** | β€’ Asynchronous schema creation and chronological prediction history logging |
| **[`test_backend.py`](tests/test_backend.py)** | Root & Schema Validation | **2** | β€’ Docs redirect and HTTP 422 Unprocessable Entity type validation |
| **[`test_ensemble.py`](tests/test_ensemble.py)** | 5-Model Soft-Voting Ensemble | **2** | β€’ Model loading and probability arbitration variance reduction |
| **TOTAL** | **Full Verification Suite** | **58** | **58/58 Passing (100% Green in ~5.5s)** |

```bash
# Execute full backend test verification suite
pytest tests -v
```

### Frontend Typechecking & Static Build
```bash
cd frontend
npx tsc --noEmit
npm run build
```


---

## License

Distributed under the MIT License. See [LICENSE](LICENSE) for full details.