ecg-fm-api / README.md
mystic_CBK
Deploy ECG-FM Dual Model API v2.0.0
31b6ae7
---
title: ECG-FM API
emoji: πŸ«€
colorFrom: blue
# FORCE REBUILD: Import logic fix for fairseq_signals deployed at 2025-08-25 08:50 UTC - AGGRESSIVE CACHE INVALIDATION - Build trigger attempt #3 - HF Spaces cache issue detected
colorTo: purple
sdk: docker
sdk_version: "latest"
app_file: server.py
pinned: false
---
# πŸ₯ ECG-FM Dual Model Production API
## πŸš€ **Production-Ready ECG Analysis with Clinical Interpretation**
A comprehensive ECG analysis API using **ECG-FM (ECG Foundation Model)** with dual-model architecture for clinical diagnosis and physiological parameter extraction.
## 🌟 **Key Features**
### **βœ… Clinical ECG Interpretation**
- **17 Clinical Labels** from MIMIC-IV-ECG dataset
- **Rhythm Classification** (Normal, AF, Bradycardia, etc.)
- **Abnormality Detection** (MI, BBB, AV blocks, etc.)
- **Clinical Confidence Scores**
### **βœ… Physiological Parameter Extraction**
- **Heart Rate (BPM)**: 30-200 range
- **QRS Duration (ms)**: 40-200 range
- **QT Interval (ms)**: 300-600 range
- **PR Interval (ms)**: 100-300 range
- **QRS Axis (degrees)**: -180 to +180 range
### **βœ… Rich ECG Features**
- **1024+ Dimensional Embeddings**
- **Temporal Patterns** (rhythm characteristics)
- **Morphological Features** (waveform analysis)
- **Spatial Relationships** (12-lead correlations)
## πŸ—οΈ **Architecture**
### **Dual Model Strategy**
1. **`mimic_iv_ecg_finetuned.pt`** (1.08 GB)
- Clinical classifier with 17 labels
- Priority loading for immediate clinical availability
2. **`mimic_iv_ecg_physionet_pretrained.pt`** (1.09 GB)
- Feature extractor for physiological parameters
- Secondary loading for comprehensive analysis
### **API Endpoints**
- **`/health`** - Health check and model status
- **`/analyze`** - Full ECG analysis (both models)
- **`/extract_features`** - Feature extraction (pretrained model)
- **`/assess_quality`** - Signal quality assessment
## πŸš€ **Quick Start**
### **API Base URL**
```
https://mystic-cbk-ecg-fm-api.hf.space
```
### **Health Check**
```bash
curl https://mystic-cbk-ecg-fm-api.hf.space/health
```
### **Full ECG Analysis**
```python
import requests
import json
# Load your ECG data
ecg_signal = [[...], [...], ...] # 12 leads
payload = {
"signal": ecg_signal,
"fs": 500,
"lead_names": ["I", "II", "III", "aVR", "aVL", "aVF", "V1", "V2", "V3", "V4", "V5", "V6"],
"recording_duration": len(ecg_signal[0]) / 500.0
}
response = requests.post(
"https://mystic-cbk-ecg-fm-api.hf.space/analyze",
json=payload
)
if response.status_code == 200:
result = response.json()
print(f"Rhythm: {result['clinical_analysis']['rhythm']}")
print(f"Heart Rate: {result['clinical_analysis']['heart_rate']} BPM")
print(f"QRS Duration: {result['clinical_analysis']['qrs_duration']} ms")
print(f"QT Interval: {result['clinical_analysis']['qt_interval']} ms")
print(f"Signal Quality: {result['signal_quality']}")
print(f"Features: {len(result['features'])} dimensions")
```
## πŸ“Š **Response Format**
### **Clinical Analysis**
```json
{
"clinical_analysis": {
"rhythm": "Normal Sinus Rhythm",
"heart_rate": 72.5,
"qrs_duration": 85.2,
"qt_interval": 420.1,
"pr_interval": 165.3,
"axis_deviation": "Normal",
"abnormalities": [],
"confidence": 0.89,
"physiological_parameters": {
"heart_rate": 72.5,
"qrs_duration": 85.2,
"qt_interval": 420.1,
"pr_interval": 165.3,
"qrs_axis": 15.2
}
},
"features": [0.123, -0.456, ...],
"signal_quality": "Excellent",
"processing_time": 2.45
}
```
## πŸ”¬ **Clinical Labels (17)**
The model detects these clinical conditions:
1. **Poor data quality**
2. **Sinus rhythm**
3. **Premature ventricular contraction**
4. **Tachycardia**
5. **Ventricular tachycardia**
6. **Supraventricular tachycardia with aberrancy**
7. **Atrial fibrillation**
8. **Atrial flutter**
9. **Bradycardia**
10. **Accessory pathway conduction**
11. **Atrioventricular block**
12. **1st degree atrioventricular block**
13. **Bifascicular block**
14. **Right bundle branch block**
15. **Left bundle branch block**
16. **Infarction**
17. **Electronic pacemaker**
## ⚑ **Performance**
- **Startup Time**: 5-10 minutes (first deployment)
- **Inference Time**: 2-5 seconds per ECG
- **Memory Usage**: ~2.5GB total
- **Concurrent Requests**: 10+ simultaneous analyses
## πŸ› οΈ **Technical Details**
### **Dependencies**
- **PyTorch 2.1.0** with CUDA 11.x compatibility
- **fairseq-signals** for ECG-FM model loading
- **FastAPI** for high-performance API
- **NumPy 1.26.4** for compatibility
### **Model Loading Strategy**
- **Direct HF Loading**: Models downloaded from `wanglab/ecg-fm`
- **Cache Persistence**: Uses `/app/.cache/huggingface`
- **Priority Loading**: Clinical model first, feature model second
### **Docker Configuration**
- **Base Image**: Python 3.9-slim
- **Port**: 7860 (HF Spaces standard)
- **Cache**: Persistent HF model cache
## πŸ“ˆ **Use Cases**
### **Clinical Research**
- **Population Studies**: Analyze large ECG datasets
- **Clinical Trials**: Automated ECG interpretation
- **Medical Education**: ECG analysis training
### **Healthcare**
- **Screening Programs**: Mass ECG analysis
- **Telemedicine**: Remote ECG interpretation
- **Emergency Medicine**: Rapid ECG assessment
### **Research & Development**
- **Feature Engineering**: Extract 1024+ dimensional features
- **Model Training**: Use features for custom classifiers
- **Validation Studies**: Compare with expert interpretations
## πŸ”§ **Deployment**
### **Hugging Face Spaces**
- **Automatic Deployment**: Git push triggers build
- **Model Caching**: Persistent between restarts
- **Scalability**: Handles multiple concurrent requests
### **Local Deployment**
```bash
# Clone repository
git clone https://huggingface.co/spaces/mystic-cbk/mystic-cbk-ecg-fm-api
# Install dependencies
pip install -r requirements_hf_spaces.txt
# Run server
uvicorn server:app --host 0.0.0.0 --port 7860
```
## πŸ“š **Documentation**
- **API Reference**: `/docs` (Swagger UI)
- **ReDoc**: `/redoc` (Alternative documentation)
- **Health Check**: `/health` (System status)
## 🀝 **Contributing**
This API is based on the official **ECG-FM** model from:
- **Repository**: [wanglab/ECG-FM](https://github.com/bowang-lab/ECG-FM)
- **Paper**: [ECG-FM: A Foundation Model for ECG Analysis](https://arxiv.org/abs/2308.08487)
- **License**: MIT License
## πŸ“„ **License**
MIT License - See LICENSE file for details.
## πŸ†˜ **Support**
- **Issues**: Report via GitHub Issues
- **Documentation**: Check `/docs` endpoint
- **Health Status**: Monitor `/health` endpoint
---
**Built with ❀️ using ECG-FM Foundation Model**
**Deployed on Hugging Face Spaces for global accessibility**