IDKHowToCodeFr commited on
Commit
72f87bd
Β·
verified Β·
1 Parent(s): 05fba9e

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. ARCHITECTURE.md +65 -59
  2. DESIGN.md +0 -55
  3. LICENSE +21 -0
  4. README.md +41 -29
ARCHITECTURE.md CHANGED
@@ -1,13 +1,14 @@
1
- # HEARTFLOW_OS // System Architecture
2
 
3
- ## Overview
4
- HeartFlow OS is an end-to-end, edge-optimized clinical telemetry pipeline. The system bridges the gap between high-level cloud machine learning and low-level embedded hardware, enabling real-time clinical inference and automated C-code transpilation for resource-constrained microcontrollers (TinyML).
5
 
6
- The architecture adheres to a decoupled, modular design pattern split into three primary planes: **Client (Frontend)**, **Core (Backend)**, and **Edge (Hardware Compilation)**.
 
 
7
 
8
  ---
9
 
10
- ## Architecture Diagram
11
 
12
  ```mermaid
13
  graph TD
@@ -18,81 +19,86 @@ graph TD
18
  classDef edge_tech fill:#f3f3f2,stroke:#111,stroke-width:2px,color:#111,font-family:monospace;
19
  classDef data fill:#94a3b8,stroke:#475569,stroke-width:2px,color:#fff,font-family:monospace;
20
 
21
- subgraph Client [Client Application]
22
- UI[Next.js 16 UI / Dashboard]:::frontend
23
- WS_Client[WebSocket Client]:::frontend
24
- HTTP_Client[HTTP Client]:::frontend
25
  end
26
 
27
- subgraph Core [FastAPI Backend]
28
- WS_Server[WebSocket Feed / Generator]:::backend
29
- REST_API[REST API Router]:::backend
30
- Inference[Inference Engine / Preprocessor]:::backend
31
- MLOps[MLOps Pipeline]:::backend
32
- DB[(aiosqlite)]:::backend
33
  end
34
 
35
- subgraph ML_Layer [Intelligence Pipeline]
36
- Ensemble{Soft-Voting Ensemble}:::ml_node
37
  Models[RF, SVM, KNN, LogReg, MLP]:::ml_node
38
- SHAP[SHAP Explainer]:::ml_node
39
- EdgeCompiler[INT8 C-Compiler AST]:::ml_node
40
  end
41
 
42
- subgraph Hardware [Edge Target]
43
  HEADER((tinyml_model.h)):::edge_tech
44
- MCU[ESP32 / Cortex-M]:::edge_tech
45
  end
46
 
47
- subgraph Storage [Persistent Storage]
48
- ModelWeights[Trained Weights .pkl]:::data
49
- CSV[Patient Dataset .csv]:::data
50
  end
51
 
52
- %% Flow
53
- UI -->|React 19 / Framer| WS_Client
54
- UI -->|User Interaction| HTTP_Client
55
 
56
- WS_Client <-->|ws:// Live Telemetry| WS_Server
57
  HTTP_Client -->|POST /retrain, GET /export| REST_API
58
 
59
- WS_Server -->|Evaluates Vitals| Inference
60
- REST_API -->|Triggers Retrain| MLOps
61
- REST_API -->|Requests Header| EdgeCompiler
62
 
63
- Inference -->|Predicts| Ensemble
64
  Ensemble --> Models
65
  Ensemble --> SHAP
66
 
67
- MLOps -->|Writes| ModelWeights
68
- MLOps -->|Appends| CSV
69
- EdgeCompiler -->|Reads| Models
70
- Inference -->|Reads| ModelWeights
71
 
72
- EdgeCompiler -->|Transpiles| HEADER
73
- HEADER -.->|Flashed to| MCU
74
  ```
75
 
76
  ---
77
 
78
- ## 1. Client Plane (Frontend)
79
- Engineered using **Next.js 16 (App Router)** and **React 19**.
80
- - **Design System:** Strict Industrial Brutalist aesthetic utilizing hard grids, monochromatic blueprints (`bg-canvas-cream`, `text-ink`), and high-contrast hazard states.
81
- - **State Management:** React Context API manages high-frequency telemetry streams.
82
- - **Data Transport:** Real-time data is ingested via native WebSockets (`ws://`), bypassing HTTP overhead for continuous vital monitoring.
83
- - **Animations:** Hardware-accelerated SVG manipulations and layout transitions powered by `framer-motion`.
84
-
85
- ## 2. Core Plane (Backend)
86
- Built on **FastAPI** (Python 3.10+), maximizing asynchronous throughput.
87
- - **WebSocket Generator:** A state-machine driven data simulator generates correlated, volatile telemetry streams (simulating clinical episodes like Asthma or Heart Disease).
88
- - **Inference Preprocessor:** Live patient data is standardized and imputed using a persistent `SimpleImputer` and `StandardScaler` trained on the original dataset, ensuring inference dimensions perfectly match the training phase.
89
- - **Storage:** Employs `aiosqlite` for non-blocking, asynchronous database writes to track historical patient classifications without stalling the event loop.
90
-
91
- ## 3. Intelligence Pipeline (MLOps)
92
- - **Ensemble Architecture:** Achieves clinical-grade precision via a 5-model soft-voting ensemble (`RandomForest`, `SVM`, `KNN`, `LogisticRegression`, `MLPClassifier`).
93
- - **Batch Retraining:** Exposes a robust `/retrain` pipeline allowing direct CSV uploads. The pipeline safely joins the schemas, automatically updates `patient_dataset.csv`, fits new scalers/imputers, retraining all models in a `BackgroundTask` thread, and hot-swaps the `EnsembleModel` globally with zero downtime.
94
-
95
- ## 4. Edge Compilation (TinyML)
96
- - **Zero-Dep C-Headers:** The backend transpiles trained SciKit-Learn tree models directly into standalone `C` functions.
97
- - **INT8 Quantization:** Floating-point weights and decision thresholds are algorithmically compressed (quantized) into 8-bit integers, effectively shrinking the flashed payload by ~75%.
98
- - **Target:** Designed to run strictly on MCU SRAM without dynamic memory allocation (no `malloc`), perfect for resource-constrained nodes like the ESP32 or Cortex-M4.
 
 
 
 
 
 
1
+ # HEARTFLOW_OS // System Architecture & Engineering Topography
2
 
3
+ ## πŸ“Œ Executive Summary
 
4
 
5
+ HeartFlow OS is a distributed, edge-optimized telemetry pipeline designed for clinical-grade cardiovascular inference. The architecture addresses the inherent tension between heavy-compute machine learning paradigms and the constrained environments of low-power microcontrollers (TinyML).
6
+
7
+ By aggressively decoupling the presentation layer (Client), the orchestration and modeling engine (Core), and the physical target execution (Edge), the system achieves strict separation of concerns, high-throughput asynchronous concurrency, and near-zero downtime deployment of predictive models.
8
 
9
  ---
10
 
11
+ ## πŸ— High-Level Architecture Diagram
12
 
13
  ```mermaid
14
  graph TD
 
19
  classDef edge_tech fill:#f3f3f2,stroke:#111,stroke-width:2px,color:#111,font-family:monospace;
20
  classDef data fill:#94a3b8,stroke:#475569,stroke-width:2px,color:#fff,font-family:monospace;
21
 
22
+ subgraph Client [Client Application / Next.js 16]
23
+ UI[React 19 Dashboard]:::frontend
24
+ WS_Client[WebSocket Context]:::frontend
25
+ HTTP_Client[Axios/Fetch HTTP]:::frontend
26
  end
27
 
28
+ subgraph Core [FastAPI Core / Python 3.10+]
29
+ WS_Server[Async WebSocket Broker]:::backend
30
+ REST_API[RESTful API Router]:::backend
31
+ Inference[Stateful Inference Preprocessor]:::backend
32
+ MLOps[Background MLOps Engine]:::backend
33
+ DB[(aiosqlite Asynchronous DB)]:::backend
34
  end
35
 
36
+ subgraph ML_Layer [Intelligence Pipeline / Scikit-Learn]
37
+ Ensemble{Soft-Voting Aggregator}:::ml_node
38
  Models[RF, SVM, KNN, LogReg, MLP]:::ml_node
39
+ SHAP[SHAP Feature Explainer]:::ml_node
40
+ EdgeCompiler[INT8 AST C-Compiler]:::ml_node
41
  end
42
 
43
+ subgraph Hardware [Edge Target / Embedded Silicon]
44
  HEADER((tinyml_model.h)):::edge_tech
45
+ MCU[ESP32 / Cortex-M Node]:::edge_tech
46
  end
47
 
48
+ subgraph Storage [Persistent Persistence Layer]
49
+ ModelWeights[Serialized Weights / LRU .pkl]:::data
50
+ CSV[Immutable Patient Dataset .csv]:::data
51
  end
52
 
53
+ %% Edge Flows
54
+ UI -->|Framer Motion Layouts| WS_Client
55
+ UI -->|Config / Retrain Requests| HTTP_Client
56
 
57
+ WS_Client <-->|ws:// 60Hz Telemetry Stream| WS_Server
58
  HTTP_Client -->|POST /retrain, GET /export| REST_API
59
 
60
+ WS_Server -->|Event Loop Execution| Inference
61
+ REST_API -->|Threaded Task| MLOps
62
+ REST_API -->|Triggers Generation| EdgeCompiler
63
 
64
+ Inference -->|Standardized Vector| Ensemble
65
  Ensemble --> Models
66
  Ensemble --> SHAP
67
 
68
+ MLOps -->|LRU State Override| ModelWeights
69
+ MLOps -->|Append Only| CSV
70
+ EdgeCompiler -->|Parses Structure| Models
71
+ Inference -->|Reads Memory-Mapped| ModelWeights
72
 
73
+ EdgeCompiler -->|Emits Dependency-Free C| HEADER
74
+ HEADER -.->|Flash via UART| MCU
75
  ```
76
 
77
  ---
78
 
79
+ ## 1. The Presentation Layer (Client Plane)
80
+ Engineered using **Next.js 16 (App Router)** and **React 19**.
81
+
82
+ - **Rendering Strategy:** Heavily leverages React Server Components (RSC) where applicable, while isolating stateful, high-frequency telemetry updates to optimized Client Components.
83
+ - **WebSocket Triage:** Bypasses standard HTTP overhead by multiplexing telemetry streams via native WebSockets (`ws://`). The stream is mapped into a React Context provider, aggressively memoized using `useMemo` and `useCallback` to prevent unnecessary DOM re-renders and React thrashing at 60Hz.
84
+ - **Visual Engineering:** Implements an Industrial Brutalist design language. All animations and Layout Transitions are hardware-accelerated (`transform`/`opacity` driven) utilizing `framer-motion` to maintain 60fps even under heavy CPU charting loads.
85
+
86
+ ## 2. The Orchestration Engine (Core Plane)
87
+ Built entirely asynchronously on top of **FastAPI** (Python 3.10+).
88
+
89
+ - **Asynchronous Throughput:** Utilizing the `asyncio` event loop and `uvicorn`, the backend comfortably supports multiple concurrent clinical WebSocket connections. I/O-bound operations (database writes) are completely non-blocking.
90
+ - **Stateful Preprocessing:** Live data must match the exact multi-dimensional space the models were trained on. The backend retains a persistent `SimpleImputer` and `StandardScaler`, ensuring live inference vectors are identical in scale to the offline batch data without runtime data leakage.
91
+ - **Event-Driven Database:** Implements `aiosqlite` for non-blocking audit logging of predictions, ensuring the primary telemetry event loop is never stalled by disk I/O.
92
+
93
+ ## 3. Intelligence Pipeline & MLOps
94
+ Designed for precision and zero-downtime deployment.
95
+
96
+ - **Distributed Soft-Voting:** Rather than relying on a monolithic architecture, inference is distributed across five orthogonal models (`RandomForest`, `SVM`, `KNN`, `LogisticRegression`, `MLPClassifier`). A soft-voting aggregator calculates the weighted probability distribution, offering a confidence interval rather than a binary black-box output.
97
+ - **Live Background Retraining:** The `/retrain` pipeline exposes an API for ingesting new clinical datasets. Upon payload validation, it spins up a `fastapi.BackgroundTasks` thread. The system dynamically updates imputers, recalculates decision boundaries across all 5 models, serializes the updated weights to disk (`.pkl`), and criticallyβ€”hot-swaps the active `EnsembleModel` object in RAM. This ensures active patient telemetry sessions are never dropped during model redeployments.
98
+
99
+ ## 4. The Edge Compilation Pipeline (TinyML)
100
+ The most critical engineering bottleneck in telemetry is getting heavy Python models onto $2 silicon.
101
+
102
+ - **AST-Based C-Transpilation:** Instead of running a heavyweight Python interpreter (like MicroPython) on the edge device, the backend parses the scikit-learn model's internal Abstract Syntax Trees (AST) and transpiles them directly into pure, statically typed `C` functions.
103
+ - **Zero-Dependency Guarantee:** The resulting `tinyml_model.h` file requires no external libraries. It bypasses `malloc()` completely, relying entirely on static stack allocation, eliminating the risk of heap fragmentation or memory leaks in long-running embedded nodes.
104
+ - **INT8 Quantization:** 64-bit floating point weights are mathematically clamped and scaled into 8-bit integers (`int8_t`). This quantization dramatically reduces flash storage requirements by up to ~75% and massively accelerates inference execution time on ALU architectures lacking dedicated floating-point hardware (FPU).
DESIGN.md DELETED
@@ -1,55 +0,0 @@
1
- # Design System: HeartFlow OS
2
-
3
- ## 1. Visual Theme & Atmosphere
4
- A restrained, highly dense utilitarian interface engineered for clinical telemetry. The atmosphere is precise, unornamented, and cockpit-dense β€” like a modern piece of medical hardware. It abandons marketing fluff (drop shadows, massive radii, neon glows) in favor of absolute data legibility, 1px structural hairlines, and muted semantic pastels.
5
-
6
- - **DESIGN_VARIANCE: 6** β€” Asymmetric bento grids, strict baseline rhythms.
7
- - **MOTION_INTENSITY: 5** β€” Restrained. Staggered reveals and layout-fluidity for data changes, but no perpetual decorative loops.
8
- - **VISUAL_DENSITY: 8** β€” Cockpit-dense. Maximum data visibility without visual collision.
9
-
10
- ## 2. Color Palette & Roles
11
- - **Clinical Canvas** (`#FBFBFA`) β€” Primary background surface for the application root.
12
- - **Pure Surface** (`#FFFFFF`) β€” Card and container fill.
13
- - **Ink Black** (`#141413`) β€” Primary text, CTAs, and active focus rings.
14
- - **Slate Gray** (`#696969`) β€” Secondary text, metadata, tabular headers, and decorative icons.
15
- - **Whisper Border** (`#EAEAEA`) β€” Card borders, dividers, 1px structural lines. No shadows.
16
- - **Risk Pastel** (`#FDEBEC` bg / `#9F2F2D` text) β€” Semantic warning state (e.g., At-Risk predictions).
17
- - **Healthy Pastel** (`#EDF3EC` bg / `#346538` text) β€” Semantic success state.
18
- - **Soft Bone** (`#F4F4F4`) β€” Neutral tertiary state or loading badges.
19
-
20
- ## 3. Typography Rules
21
- - **Display:** `Geist` or `Outfit` (sans-serif) β€” Track-tight (`-0.02em`), controlled scale, weight-driven hierarchy (Medium 500 for headers).
22
- - **Body:** `Geist` or `Outfit` β€” Relaxed leading (`1.5`), `450` weight, Slate Gray.
23
- - **Data / Numbers:** `Geist Mono` or Tabular-Nums on the sans font β€” Mandatory for all live telemetry, timestamps, and confidence percentages to prevent horizontal layout jitter.
24
- - **Banned:** Generic serifs (`Times New Roman`, `Georgia`) are banned in this software UI. Generic `Inter` is discouraged in favor of `Geist` for a more precise technical aesthetic.
25
-
26
- ## 4. Component Stylings
27
- - **Buttons:** Flat, Ink Black fill. Border radius of `6px` or `8px`. Tactile `scale(0.98)` push feedback on active state. No neon outer glows, no massive pills (999px) in the dashboard.
28
- - **Cards (Bento Grid):** Crisp `12px` or `8px` corners. Strict `1px solid #EAEAEA` border. Absolutely zero drop shadows (`shadow-none`).
29
- - **Inputs & Navigation:** Focus states must use a harsh, highly-visible 2px ring (`focus-visible:ring-2 focus-visible:ring-[#141413]`). Label above, error below.
30
- - **Loaders:** Skeletal shimmer matching exact layout dimensions. No generic circular spinners.
31
- - **Status Pills:** Small, dense (`text-[11px]`), uppercase with wide tracking (`0.05em`), using the muted semantic pastels above.
32
-
33
- ## 5. Layout Principles
34
- - **Macro-Whitespace:** 8-point baseline grid. Generous internal padding inside cards (`p-8`), but tightly packed grids (`gap-6`).
35
- - **No Overlapping Elements:** Every element occupies its own clear spatial zone. No absolute-positioned content stacking.
36
- - **Bento Constraints:** The layout must adapt exactly to the number of data panels. No empty slots.
37
- - **Responsive Strictness:** Multi-column layouts must explicitly collapse to a single column below 768px. No horizontal scroll on mobile.
38
- - **Height Constraints:** Full-height views must use `min-h-[100dvh]` to avoid iOS Safari address bar jumps.
39
-
40
- ## 6. Motion & Interaction
41
- - **Physics Engine:** Spring physics for all interactive layout shifts (`stiffness: 100, damping: 20`). No linear easing.
42
- - **Staggered Orchestration:** List items and bento cards enter via a subtle `translateY(12px)` + `opacity: 0` staggered cascade. Never mount the full dashboard instantly.
43
- - **Hardware Acceleration:** Animate exclusively via `transform` and `opacity`.
44
- - **Accessibility Sync:** Interactive layout shifts must respect `prefers-reduced-motion`. Live data must have `aria-live="polite"` so motion isn't the only indicator of change.
45
-
46
- ## 7. Anti-Patterns (BANNED)
47
- - **NO emojis anywhere.** Use Phosphor, Lucide, or Radix UI icons.
48
- - **NO generic purple/blue neon glows** or gradient meshes.
49
- - **NO pure black** (`#000000`).
50
- - **NO drop shadows** (`shadow-md`, `shadow-lg`, etc.). Elevation is handled by 1px borders.
51
- - **NO fake placeholder names** (John Doe, Acme).
52
- - **NO unstyled focus states.**
53
- - **NO AI copywriting clichΓ©s** ("Elevate", "Seamless", "Unleash").
54
- - **NO "Inter" font** as the default assumption; enforce Geist/Outfit.
55
- - **NO non-tabular numbers** for live updating data.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 HeartFlow OS Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -7,9 +7,9 @@ sdk: docker
7
  pinned: false
8
  ---
9
 
10
- # HEARTFLOW_OS // TinyML Heart Health Telemetry
11
 
12
- A production-ready, edge-optimized application for real-time cardiovascular analytics. It bridges the gap between cloud-scale machine learning and low-level embedded hardware by deploying soft-voting ensembles and automated C-code transpilation for resource-constrained IoT systems.
13
 
14
  ![Next.js](https://img.shields.io/badge/Next.js-16+-black.svg?style=flat&logo=next.js)
15
  ![React](https://img.shields.io/badge/React-19-61DAFB.svg?style=flat&logo=react)
@@ -19,56 +19,68 @@ A production-ready, edge-optimized application for real-time cardiovascular anal
19
 
20
  ---
21
 
22
- ## Overview
23
 
24
- HEARTFLOW_OS is designed for clinical telemetry monitoring. It evaluates live patient vitals using an ensemble of classifiers, provides diagnostic probability distributions, and physically compresses these Python-trained models into raw C-code headers ready to be flashed directly onto edge silicon (e.g., ESP32, Arduino Nano).
25
 
26
  ### Key Engineering Features
27
 
28
- - **Industrial Brutalist Frontend**: A high-performance, cockpit-dense Next.js 16 UI using native WebSockets and React 19 to render 60fps SVG telemetry sweeps without dropping frames.
29
- - **Edge Computing & TinyML**: Transpiles complex Scikit-Learn models into highly optimized, dependency-free **C-code headers**. Bypasses dynamic memory allocation entirely.
30
- - **INT8 Quantization Engine**: Mathematically scales 64-bit floating-point weights down to 8-bit integers, shrinking the flash memory payload by **~75%** for constrained microcontrollers.
31
- - **Soft-Voting Ensemble**: Aggregates predictions across five independent models (Random Forest, SVM, KNN, Logistic Regression, MLP Neural Network) to output robust probability distributions rather than black-box binary answers.
32
- - **Zero-Downtime MLOps Pipeline**: Features a dedicated `/retrain` pipeline allowing dynamic CSV uploads. It validates schemas, imputes missing data, retrains the entire ensemble in a background thread, and hot-swaps the intelligence engine globally without dropping active WebSocket connections.
33
 
34
- ## Architecture
 
 
35
 
36
- The project follows a decoupled, modular design pattern split between a React Client, a FastAPI Core, and an Edge Compiler.
37
 
38
- For a comprehensive deep-dive into the data flows and system topography, refer to the [ARCHITECTURE.md](./ARCHITECTURE.md) document.
39
 
40
- ### Repository Structure
41
 
42
  ```text
43
  HEARTFLOW_OS/
44
- β”œβ”€β”€ backend/ # FastAPI server, ML pipelines, aiosqlite, Edge C-compiler
45
- β”‚ β”œβ”€β”€ ensemble.py # Core intelligence and prediction aggregations
46
- β”‚ β”œβ”€β”€ main.py # Websocket feeds, REST APIs, and background tasks
47
- β”‚ └── preprocessing.py # MLOps data imputation, scaling, and state preservation
48
- β”œβ”€β”€ frontend/ # Next.js 16 UI, React Context, framer-motion components
49
- β”‚ β”œβ”€β”€ src/app/ # Dashboard, Simulator, MLOps, and Architecture routes
50
- β”‚ └── src/components/ # Reusable brutalist UI components (Vitals, Graphs)
51
- β”œβ”€β”€ model/ # Local cache of serialized SciKit-Learn .pkl weights
52
- └── data/ # Base patient cohort CSVs for MLOps retraining pipelines
53
  ```
54
 
55
- ## Quickstart
 
 
56
 
57
- ### 1. Initialize Backend
 
58
  ```bash
59
  cd backend
60
- python -m venv venv
61
- source venv/bin/activate # Or `.\venv\Scripts\activate` on Windows
62
  pip install -r requirements.txt
63
- python models.py # Initial train of the base ensemble
64
  uvicorn main:app --reload --port 8000
65
  ```
66
 
67
- ### 2. Initialize Frontend
 
68
  ```bash
69
  cd frontend
70
  npm install
71
  npm run dev
72
  ```
73
 
74
- The system will boot on `localhost:3000`. Connect to view the live dashboard streams and access the MLOps retraining interfaces.
 
 
 
 
 
 
 
7
  pinned: false
8
  ---
9
 
10
+ # HEARTFLOW_OS // Edge-Native Cardiovascular Telemetry
11
 
12
+ A production-grade, edge-optimized application for real-time cardiovascular telemetry and predictive diagnostics. HeartFlow OS bridges cloud-scale machine learning with low-level embedded constraints by transpiling soft-voting ensembles directly into zero-dependency, statically allocated C-code for microcontroller deployment.
13
 
14
  ![Next.js](https://img.shields.io/badge/Next.js-16+-black.svg?style=flat&logo=next.js)
15
  ![React](https://img.shields.io/badge/React-19-61DAFB.svg?style=flat&logo=react)
 
19
 
20
  ---
21
 
22
+ ## πŸš€ Overview
23
 
24
+ HeartFlow OS is engineered for high-frequency clinical telemetry. It ingests live patient vitals via WebSockets, evaluates telemetry against an ensemble of distributed classifiers to compute diagnostic probability distributions, and physically compresses these complex mathematical models into raw C-code headers ready to be flashed onto constrained edge silicon (e.g., ESP32, Cortex-M series).
25
 
26
  ### Key Engineering Features
27
 
28
+ - **High-Throughput Telemetry Interface:** A highly optimized Next.js 16 dashboard utilizing native WebSockets and React 19 to render 60fps SVG telemetry sweeps with near-zero latency or dropped frames.
29
+ - **Edge Inference & TinyML:** Transpiles sophisticated `scikit-learn` models into highly optimized, dependency-free C-code. Designed with strict spatial and temporal constraints in mind, bypassing dynamic memory allocation entirely (`malloc`-free).
30
+ - **INT8 Quantization Engine:** Algorithmically scales 64-bit floating-point weights and biases down to 8-bit integers, effectively shrinking the flashed payload memory footprint by ~75% without significant accuracy degradation.
31
+ - **Soft-Voting Ensemble:** Fuses predictions from five discrete model architectures (Random Forest, SVM, KNN, Logistic Regression, MLP Neural Network) to generate resilient probability distributions, mitigating the variance and biases of individual black-box models.
32
+ - **Zero-Downtime MLOps:** Integrated `/retrain` pipeline allowing for real-time schema validation, data imputation, and background ensemble retraining. Hot-swaps the underlying intelligence engine globally without interrupting active clinical WebSocket streams.
33
 
34
+ ---
35
+
36
+ ## πŸ— System Architecture
37
 
38
+ The architecture adheres to a strictly decoupled, service-oriented design pattern split across the Client (React), the Core (FastAPI), and the Edge (C-Compiler).
39
 
40
+ For a deep-dive into system topography, data flows, and design rationale, see [ARCHITECTURE.md](./ARCHITECTURE.md).
41
 
42
+ ### Repository Topology
43
 
44
  ```text
45
  HEARTFLOW_OS/
46
+ β”œβ”€β”€ backend/ # FastAPI core, aiosqlite, async ML pipelines, C-compiler
47
+ β”‚ β”œβ”€β”€ ensemble.py # Core intelligence and soft-voting aggregations
48
+ β”‚ β”œβ”€β”€ main.py # Websocket ingress, REST APIs, and background routines
49
+ β”‚ └── preprocessing.py # State-preserving MLOps data imputation and scaling
50
+ β”œβ”€β”€ frontend/ # Next.js 16 UI, React Context, Framer Motion
51
+ β”‚ β”œβ”€β”€ src/app/ # Route segments (Dashboard, Simulator, Architecture)
52
+ β”‚ └── src/components/ # Memoized, brutalist UI components for 60fps rendering
53
+ β”œβ”€β”€ model/ # Local LRU cache of serialized model states (.pkl)
54
+ └── data/ # Immutable patient cohort datasets for MLOps
55
  ```
56
 
57
+ ---
58
+
59
+ ## πŸ›  Quickstart Guide
60
 
61
+ ### 1. Initialize the Core (Backend)
62
+ Requires Python 3.10+
63
  ```bash
64
  cd backend
65
+ python -m venv .venv
66
+ source .venv/bin/activate # Windows: `.\.venv\Scripts\activate`
67
  pip install -r requirements.txt
68
+ python models.py # Initialize database and train the baseline ensemble
69
  uvicorn main:app --reload --port 8000
70
  ```
71
 
72
+ ### 2. Initialize the Client (Frontend)
73
+ Requires Node.js 18+
74
  ```bash
75
  cd frontend
76
  npm install
77
  npm run dev
78
  ```
79
 
80
+ The system will boot on `localhost:3000`. Navigate to the dashboard to monitor live telemetry streams, access MLOps pipelines, and export INT8 TinyML headers.
81
+
82
+ ---
83
+
84
+ ## πŸ“„ License
85
+
86
+ Distributed under the MIT License. See `LICENSE` for more information.