Spaces:
Sleeping
Sleeping
File size: 6,798 Bytes
17a1aea cb17bf6 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 17a1aea 31b6ae7 |
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 |
---
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** |