# santhosh071/ecg-arrhythmia-detection architecture

> Architecture diagram of the GitHub repository santhosh071/ecg-arrhythmia-detection, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-03). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/santhosh071/ecg-arrhythmia-detection
- Repository: https://github.com/santhosh071/ecg-arrhythmia-detection

## Overview

1. **Overall shape**
   - This repo is a layered ECG decision-support system, not just a model project.
   - The main runtime path is: raw MIT-BIH ECG data → preprocessing → beat-level inference → session risk scoring → clinical agent/actions → API/dashboard presentation.
   - There is a clear split between **offline work** (data prep, training, evaluation) and **online work** (FastAPI serving, Streamlit UI, agent tools, persistence).

2. **Layer 1: data acquisition**
   - `src/layer1_data/download_mitbih.py` handles fetching the MIT-BIH Arrhythmia dataset.
   - The raw dataset is the source boundary for the system; everything downstream assumes 360 Hz ECG recordings from PhysioNet/MIT-BIH.

3. **Layer 2: preprocessing**
   - `src/layer2_preprocessing/preprocess_mitbih.py` converts raw ECG into model-ready beat windows.
   - The README describes the key signal-processing steps: bandpass filtering, baseline correction, R-peak detection, beat segmentation, and normalization.
   - This is the bridge from continuous ECG waveforms to per-beat tensors used by the classifiers and autoencoder.

4. **Layer 3: model inference core**
   - `src/layer3_models/cnn.py` is the main 8-class beat classifier.
   - `src/layer3_models/transformer_ae.py`, `lstm_ae.py`, and `vae.py` support anomaly-detection research and baselines.
   - `src/layer3_models/inference/` is the production inference boundary:
     - `model_loader.py` loads trained artifacts,
     - `preprocess.py` prepares incoming beats,
     - `predict.py` runs classification/anomaly scoring,
     - `result_schema.py` standardizes outputs for the API and dashboard.
   - The core decision rule is dual-path: CNN class prediction plus autoencoder reconstruction error, then merged into a single anomaly/session result.

5. **Model/decision flow**
   - The system does not stop at classifying one beat.
   - Beat outputs are aggregated into a session-level assessment: anomaly rate, dominant arrhythmia patterns, and final risk tier.
   - The README’s risk logic is part of the architecture: the classifier/AE feed a rule-based risk layer that escalates to Low/Medium/High/Critical.

6. **Layer 4: clinical agent**
   - `src/layer4_agent/agent.py` is the orchestration layer for clinical reasoning and action selection.
   - `agent_tools.py` exposes the system’s functional tools, such as risk assessment, history lookup, trend monitoring, sensor-quality checks, alerting, and report generation.
   - `llm_config.py` suggests the LLM backend is configurable, with online Groq/LLaMA3 usage and an offline fallback described in the README.
   - `memory.py` provides short-term conversation state, while long-term context is persisted externally via storage.

7. **Layer 5: dashboard/UI**
   - `src/layer5_dashboard/app.py` is the Streamlit entrypoint.
   - Supporting modules split the UI into focused panels: ECG waveform plotting, alert feed, patient history/trends, and clinician chat.
   - This layer is a consumer of backend outputs; it visualizes beat classifications, anomaly flags, risk state, chat responses, and report-ready summaries.

8. **API boundary**
   - `api/main.py` is the FastAPI backend entrypoint.
   - `api/dependencies.py` likely wires shared objects such as loaded models, the agent, config, and storage access into request handlers.
   - `api/schemas.py` defines request/response contracts for endpoints like prediction, agent query, report generation, signal quality, and history lookup.
   - This is the main integration boundary between external clients and the internal model/agent layers.

9. **Persistence and artifacts**
   - The README describes SQLite-backed patient sessions, alerts, trends, and agent logs, plus filesystem outputs for alerts and PDF reports.
   - Even though `src/layer6_storage/` is minimal in the tree, storage is an explicit architectural concern: long-term state lives outside the request process.
   - This separates transient inference/chat memory from durable clinical history.

10. **Evaluation and offline experimentation**
   - `evaluation/evaluate_models.py` and `evaluation/evaluation_report.py` are offline analysis tools for model metrics and report generation.
   - The notebooks under `notebooks/` are training workspaces for CNN, LSTM AE, Transformer AE, and VAE experiments.
   - These are not part of the serving path; they produce the model artifacts and metrics that the runtime depends on.

11. **Configuration and operational concerns**
   - `config/config.py` and `config/logger.py` centralize environment-driven settings and logging.
   - `.env.template` shows the main runtime dependencies: Groq API key/model, project paths, model paths, and DB location.
   - `run.py` is the top-level orchestration entrypoint for launching the system together.

12. **Tests and validation boundaries**
   - The test suite is organized around the architecture: inference tests, agent tests, and full integration tests.
   - `tests/test_inference.py`, `tests/test_agent.py`, and `tests/test_integration.py` verify the critical pipeline seams rather than just isolated functions.
   - That makes the repo’s diagram best drawn as a pipeline of distinct layers with explicit integration points at preprocessing, inference, agent tools, API, and storage.

Main entry points: [`src/layer3_models/inference/predict.py`](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/inference/predict.py) (Predict), [`api/main.py`](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/api/main.py) (FastAPI app), [`src/layer4_agent/agent.py`](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer4_agent/agent.py) (Clinical agent), [`src/layer5_dashboard/app.py`](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer5_dashboard/app.py) (Streamlit app)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_group_offline["Offline work"]
  node_node_download["MIT-BIH fetch<br/>data acquisition<br/>[download_mitbih.py]"]
  node_node_preprocess["Beat prep<br/>signal preprocessing"]
  node_node_cnn["CNN classifer<br/>beat model<br/>[cnn.py]"]
  node_node_ae_models{{"AE models<br/>anomaly models<br/>[lstm_ae.py]"}}
  node_node_eval["Evaluation<br/>offline metrics<br/>[evaluate_models.py]"]
end

subgraph group_group_runtime["Runtime core"]
  node_node_loader["Model loader<br/>runtime loader<br/>[model_loader.py]"]
  node_node_inf_prep["Inference prep<br/>serving preprocess<br/>[preprocess.py]"]
  node_node_predict["Predict<br/>decision engine<br/>[predict.py]"]
  node_node_schema["Result schema<br/>contracts<br/>[result_schema.py]"]
  node_node_agent["Clinical agent<br/>orchestrator<br/>[agent.py]"]
  node_node_tools["Agent tools<br/>tooling layer<br/>[agent_tools.py]"]
  node_node_memory[("Memory<br/>conversation state<br/>[memory.py]")]
  node_node_storage[("Storage<br/>durable state<br/>[__init__.py]")]
end

subgraph group_group_ui["Presentation"]
  node_node_api["FastAPI app<br/>backend entrypoint<br/>[main.py]"]
  node_node_api_schemas["API schemas<br/>request contracts<br/>[schemas.py]"]
  node_node_dashboard["Streamlit app<br/>dashboard entrypoint<br/>[app.py]"]
  node_node_panels["UI panels<br/>visualization views<br/>[ecg_plot.py]"]
end

node_node_run(("Run entry<br/>launcher<br/>[run.py]"))
node_node_config["Config<br/>runtime settings<br/>[config.py]"]

node_node_download -->|"raw ECG"| node_node_preprocess
node_node_preprocess -->|"beat tensors"| node_node_cnn
node_node_preprocess -->|"anomaly inputs"| node_node_ae_models
node_node_cnn -->|"class scores"| node_node_predict
node_node_ae_models -->|"recon error"| node_node_predict
node_node_loader -->|"loaded artifacts"| node_node_predict
node_node_inf_prep -->|"serving features"| node_node_predict
node_node_predict -->|"results"| node_node_schema
node_node_predict -->|"risk signal"| node_node_agent
node_node_tools -->|"tools"| node_node_agent
node_node_memory -->|"context"| node_node_agent
node_node_agent -->|"persist state"| node_node_storage
node_node_api -->|"contracts"| node_node_schema
node_node_api -->|"agent query"| node_node_agent
node_node_api -->|"prediction"| node_node_predict
node_node_dashboard -->|"client calls"| node_node_api
node_node_panels -->|"views"| node_node_dashboard
node_node_config -->|"settings"| node_node_api
node_node_config -->|"llm config"| node_node_agent
node_node_config -->|"ui config"| node_node_dashboard
node_node_run -->|"launch"| node_node_api
node_node_run -->|"launch"| node_node_dashboard
node_node_eval -->|"metrics"| node_node_cnn
node_node_eval -->|"metrics"| node_node_ae_models

click node_node_download "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer1_data/download_mitbih.py"
click node_node_preprocess "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer2_preprocessing/preprocess_mitbih.py"
click node_node_cnn "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/cnn.py"
click node_node_ae_models "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/lstm_ae.py"
click node_node_eval "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/evaluation/evaluate_models.py"
click node_node_loader "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/inference/model_loader.py"
click node_node_inf_prep "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/inference/preprocess.py"
click node_node_predict "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/inference/predict.py"
click node_node_schema "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/inference/result_schema.py"
click node_node_agent "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer4_agent/agent.py"
click node_node_tools "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer4_agent/agent_tools.py"
click node_node_memory "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer4_agent/memory.py"
click node_node_storage "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer6_storage/__init__.py"
click node_node_api "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/api/main.py"
click node_node_api_schemas "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/api/schemas.py"
click node_node_dashboard "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer5_dashboard/app.py"
click node_node_panels "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer5_dashboard/ecg_plot.py"
click node_node_run "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/run.py"
click node_node_config "https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/config/config.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_node_download,node_node_preprocess,node_node_cnn,node_node_ae_models,node_node_eval toneBlue
class node_node_loader,node_node_inf_prep,node_node_predict,node_node_schema,node_node_agent,node_node_tools,node_node_memory,node_node_storage toneAmber
class node_node_api,node_node_api_schemas,node_node_dashboard,node_node_panels toneMint
class node_node_run,node_node_config toneNeutral
```

## Components

### Offline work

Data acquisition, preprocessing, training, and evaluation

- [MIT-BIH fetch](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer1_data/download_mitbih.py): data acquisition · Downloads the raw MIT-BIH Arrhythmia dataset as the source ECG boundary · `src/layer1_data/download_mitbih.py`
- [Beat prep](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer2_preprocessing/preprocess_mitbih.py): signal preprocessing · Filters, detects R-peaks, segments beats, and normalizes ECG windows · `src/layer2_preprocessing/preprocess_mitbih.py`
- [CNN classifer](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/cnn.py): beat model · Main multi-class beat classifier used for arrhythmia detection · `src/layer3_models/cnn.py`
- [AE models](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/lstm_ae.py): anomaly models · Alternative anomaly-detection models and baselines: LSTM AE, Transformer AE, and VAE · `src/layer3_models/lstm_ae.py`
- [Evaluation](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/evaluation/evaluate_models.py): offline metrics · Model evaluation and report generation for trained artifacts · `evaluation/evaluate_models.py`

### Runtime core

Serving-time inference, agent orchestration, and persistence

- [Model loader](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/inference/model_loader.py): runtime loader · Loads trained model artifacts for serving · `src/layer3_models/inference/model_loader.py`
- [Inference prep](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/inference/preprocess.py): serving preprocess · Prepares incoming beats for prediction-time inference · `src/layer3_models/inference/preprocess.py`
- [Predict](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/inference/predict.py): decision engine · Runs CNN classification and reconstruction-error scoring to produce beat-level results · `src/layer3_models/inference/predict.py`
- [Result schema](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer3_models/inference/result_schema.py): contracts · Standardizes inference outputs for API and dashboard consumers · `src/layer3_models/inference/result_schema.py`
- [Clinical agent](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer4_agent/agent.py): orchestrator · Coordinates clinical reasoning and action selection · `src/layer4_agent/agent.py`
- [Agent tools](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer4_agent/agent_tools.py): tooling layer · Exposes risk assessment, history lookup, trend monitoring, alerting, and report generation · `src/layer4_agent/agent_tools.py`
- [Memory](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer4_agent/memory.py): conversation state · Maintains short-term conversational context for the agent · `src/layer4_agent/memory.py`
- [Storage](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer6_storage/__init__.py): durable state · Persists patient sessions, alerts, trends, and logs outside the request process · `src/layer6_storage/__init__.py`

### Presentation

API and dashboard entrypoints

- [FastAPI app](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/api/main.py): backend entrypoint · Main HTTP serving boundary for prediction, agent, report, and history requests · `api/main.py`
- [API schemas](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/api/schemas.py): request contracts · Defines request and response shapes for external clients · `api/schemas.py`
- [Streamlit app](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer5_dashboard/app.py): dashboard entrypoint · Interactive clinician UI for ECG, alerts, history, and chat · `src/layer5_dashboard/app.py`
- [UI panels](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/src/layer5_dashboard/ecg_plot.py): visualization views · Waveform plotting, alert feed, history charts, and chat interface components · `src/layer5_dashboard/ecg_plot.py`

### Other components

- [Run entry](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/run.py): launcher · Top-level orchestration entrypoint for launching the system · `run.py`
- [Config](https://github.com/santhosh071/ecg-arrhythmia-detection/blob/main/config/config.py): runtime settings · Central environment-driven configuration and logging support · `config/config.py`

## Connections

- MIT-BIH fetch → Beat prep: raw ECG · Raw MIT-BIH recordings are converted into model-ready beat windows
- Beat prep → CNN classifer: beat tensors · Preprocessed beat windows feed the main classifier
- Beat prep → AE models: anomaly inputs · The same beat windows support anomaly-detection models
- CNN classifer → Predict: class scores · Classifier outputs are consumed by the serving decision layer
- AE models → Predict: recon error · Autoencoder-style models contribute anomaly scoring signals
- Model loader → Predict: loaded artifacts · Serving uses loaded trained models and associated assets
- Inference prep → Predict: serving features · Incoming ECG data is normalized into inference-ready features
- Predict → Result schema: results · Prediction outputs are standardized for downstream consumers
- Predict → Clinical agent: risk signal · Beat/session risk and anomaly findings are handed to the clinical agent
- Agent tools → Clinical agent: tools · The agent invokes domain tools for reasoning and actions
- Memory → Clinical agent: context · Short-term conversation state informs agent responses
- Clinical agent → Storage: persist state · Clinical interactions and session artifacts are written durably
- FastAPI app → Result schema: contracts · HTTP endpoints expose the shared response shapes
- FastAPI app → Clinical agent: agent query · API requests can trigger clinical reasoning and action selection
- FastAPI app → Predict: prediction · API requests can invoke the serving inference path
- Streamlit app → FastAPI app: client calls · The UI consumes backend services for data and actions
- UI panels → Streamlit app: views · Dashboard is composed of specialized clinical panels
- Config → FastAPI app: settings · Configuration is shared by the backend runtime
- Config → Clinical agent: llm config · Agent behavior depends on configurable LLM/runtime settings
- Config → Streamlit app: ui config · Dashboard behavior depends on shared configuration
- Run entry → FastAPI app: launch · Top-level execution can start the backend service
- Run entry → Streamlit app: launch · Top-level execution can start the clinician dashboard
- Evaluation → CNN classifer: metrics · Offline evaluation assesses trained model quality
- Evaluation → AE models: metrics · Offline evaluation also covers anomaly-model experiments
