Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- .gitattributes +1 -0
- app.py +146 -0
- final_model.keras +3 -0
- requirements.txt +7 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
final_model.keras filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import tensorflow as tf
|
| 7 |
+
from tensorflow.keras.models import load_model
|
| 8 |
+
from scipy.signal import butter, filtfilt
|
| 9 |
+
import pywt
|
| 10 |
+
import tempfile
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
# Load model
|
| 14 |
+
model = load_model("final_model.keras")
|
| 15 |
+
|
| 16 |
+
label_map = {0: "Bradycardia", 1: "Tachycardia", 2: "VFib", 3: "VTach", 4: "Normal"}
|
| 17 |
+
color_map = {
|
| 18 |
+
"Bradycardia": "blue",
|
| 19 |
+
"Tachycardia": "orange",
|
| 20 |
+
"VFib": "red",
|
| 21 |
+
"VTach": "purple",
|
| 22 |
+
"Normal": "green"
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
def preprocess_signal(sig, fs):
|
| 26 |
+
b, a = butter(4, [0.5, 8], btype='bandpass', fs=fs)
|
| 27 |
+
filtered = filtfilt(b, a, sig)
|
| 28 |
+
smoothed = np.convolve(filtered, np.ones(5)/5, mode='same')
|
| 29 |
+
coeffs = pywt.wavedec(smoothed, 'db4', level=4)
|
| 30 |
+
coeffs[-1] = np.zeros_like(coeffs[-1])
|
| 31 |
+
cleaned = pywt.waverec(coeffs, 'db4')
|
| 32 |
+
norm = (cleaned - np.median(cleaned)) / (np.max(cleaned) - np.min(cleaned) + 1e-8)
|
| 33 |
+
return norm
|
| 34 |
+
|
| 35 |
+
def segment_signal(ppg, ecg, fs, win_sec=20, overlap_sec=10):
|
| 36 |
+
win_len = fs * win_sec
|
| 37 |
+
stride = fs * overlap_sec
|
| 38 |
+
segments = []
|
| 39 |
+
for start in range(0, len(ppg) - win_len + 1, stride):
|
| 40 |
+
end = start + win_len
|
| 41 |
+
seg_ppg = preprocess_signal(ppg[start:end], fs)
|
| 42 |
+
seg_ecg = preprocess_signal(ecg[start:end], fs)
|
| 43 |
+
if len(seg_ppg) >= 2500 and len(seg_ecg) >= 2500:
|
| 44 |
+
segments.append((seg_ppg[:2500], seg_ecg[:2500]))
|
| 45 |
+
return segments
|
| 46 |
+
|
| 47 |
+
def analyze_file(file, show_plot):
|
| 48 |
+
try:
|
| 49 |
+
df = pd.read_csv(file.name)
|
| 50 |
+
df.columns = df.columns.str.strip().str.upper()
|
| 51 |
+
ecg_col = next((c for c in ["ECG", "II", "III", "AVF", "V", "I"] if c in df.columns), None)
|
| 52 |
+
ppg_col = next((c for c in ["PPG", "PLETH"] if c in df.columns), None)
|
| 53 |
+
if not ecg_col or not ppg_col:
|
| 54 |
+
return f"❌ ECG or PPG column missing in {file.name}", None, None, None
|
| 55 |
+
|
| 56 |
+
fs = 250
|
| 57 |
+
if "TIME" in df.columns:
|
| 58 |
+
diffs = df["TIME"].diff().dropna().values
|
| 59 |
+
if len(diffs) > 0:
|
| 60 |
+
fs = int(round(1 / np.median(diffs)))
|
| 61 |
+
|
| 62 |
+
ecg = df[ecg_col].values
|
| 63 |
+
ppg = df[ppg_col].values
|
| 64 |
+
|
| 65 |
+
segments = segment_signal(ppg, ecg, fs)
|
| 66 |
+
if not segments:
|
| 67 |
+
return f"❌ Insufficient signal duration in {file.name}", None, None, None
|
| 68 |
+
|
| 69 |
+
ppg_input = np.array([s[0] for s in segments])[:, :, np.newaxis]
|
| 70 |
+
ecg_input = np.array([s[1] for s in segments])[:, :, np.newaxis]
|
| 71 |
+
preds = model.predict([ppg_input, ecg_input], verbose=0)
|
| 72 |
+
pred_classes = np.argmax(preds, axis=1)
|
| 73 |
+
counts = pd.Series(pred_classes).value_counts()
|
| 74 |
+
majority_class = counts.idxmax()
|
| 75 |
+
confidence = round(100 * counts.max() / len(pred_classes), 2)
|
| 76 |
+
final_label = label_map[majority_class]
|
| 77 |
+
color = color_map[final_label]
|
| 78 |
+
|
| 79 |
+
summary = (
|
| 80 |
+
f"✅ <b>File:</b> <code>{os.path.basename(file.name)}</code><br>"
|
| 81 |
+
f"🔍 <b>Prediction:</b> <b><span style='color:{color};'>{final_label}</span></b><br>"
|
| 82 |
+
f"📊 <b>Confidence:</b> {confidence}%<br>"
|
| 83 |
+
f"🧪 <b>Segments Used:</b> {len(pred_classes)}"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
segment_df = pd.DataFrame({
|
| 87 |
+
"Segment #": list(range(1, len(pred_classes)+1)),
|
| 88 |
+
"Predicted Class": [label_map[c] for c in pred_classes],
|
| 89 |
+
"Confidence": preds.max(axis=1)
|
| 90 |
+
})
|
| 91 |
+
segment_df.insert(0, "File", os.path.basename(file.name))
|
| 92 |
+
|
| 93 |
+
fig = None
|
| 94 |
+
if show_plot:
|
| 95 |
+
fig, ax = plt.subplots(2, 1, figsize=(12, 5), sharex=True)
|
| 96 |
+
ax[0].plot(ppg[:fs*10], color='blue')
|
| 97 |
+
ax[0].set_title(f"PPG Signal (First 10s) - {os.path.basename(file.name)}")
|
| 98 |
+
ax[1].plot(ecg[:fs*10], color='red')
|
| 99 |
+
ax[1].set_title(f"ECG Signal (First 10s) - {os.path.basename(file.name)}")
|
| 100 |
+
plt.tight_layout()
|
| 101 |
+
|
| 102 |
+
return summary, segment_df, fig
|
| 103 |
+
|
| 104 |
+
except Exception as e:
|
| 105 |
+
return f"❌ Error in {file.name}: {e}", None, None, None
|
| 106 |
+
|
| 107 |
+
def batch_predict(files, show_plot):
|
| 108 |
+
results = []
|
| 109 |
+
all_segments = []
|
| 110 |
+
all_image_paths = []
|
| 111 |
+
|
| 112 |
+
for file in files:
|
| 113 |
+
summary, df_segment, fig = analyze_file(file, show_plot)
|
| 114 |
+
results.append(summary + "<hr>")
|
| 115 |
+
if isinstance(df_segment, pd.DataFrame):
|
| 116 |
+
all_segments.append(df_segment)
|
| 117 |
+
if fig:
|
| 118 |
+
tmp_path = tempfile.NamedTemporaryFile(delete=False, suffix=".png").name
|
| 119 |
+
fig.savefig(tmp_path)
|
| 120 |
+
plt.close(fig)
|
| 121 |
+
all_image_paths.append(tmp_path)
|
| 122 |
+
|
| 123 |
+
final_df = pd.concat(all_segments, ignore_index=True) if all_segments else None
|
| 124 |
+
temp_csv = None
|
| 125 |
+
if final_df is not None:
|
| 126 |
+
temp_csv = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
|
| 127 |
+
final_df.to_csv(temp_csv.name, index=False)
|
| 128 |
+
|
| 129 |
+
return "\n\n---\n".join(results), final_df, temp_csv.name if temp_csv else None, all_image_paths if show_plot else None
|
| 130 |
+
|
| 131 |
+
gr.Interface(
|
| 132 |
+
fn=batch_predict,
|
| 133 |
+
inputs=[
|
| 134 |
+
gr.File(file_types=[".csv"], file_count="multiple", label="Upload ECG + PPG CSV(s)"),
|
| 135 |
+
gr.Checkbox(label="Show signal plot preview (first 10 seconds)", value=True)
|
| 136 |
+
],
|
| 137 |
+
outputs=[
|
| 138 |
+
gr.HTML(label="🧠 Final Prediction Summary"),
|
| 139 |
+
gr.Dataframe(label="📄 Segment-wise Predictions"),
|
| 140 |
+
gr.File(label="⬇️ Download Segment Report"),
|
| 141 |
+
gr.Gallery(label="📈 Signal Plots (Optional)", show_label=True, visible=True)
|
| 142 |
+
],
|
| 143 |
+
title="🩺 Arrhythmia Detection using ECG + PPG",
|
| 144 |
+
description="Upload CSV files with Time, PPG/Pleth, ECG (or II/III/AVF). Model: CNN+LSTM",
|
| 145 |
+
allow_flagging="never"
|
| 146 |
+
).launch()
|
final_model.keras
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:884214b83040ded0d50f9fcbbae64f2404f4a9476478480272fe4fc603ee6b9d
|
| 3 |
+
size 205201368
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
pandas
|
| 3 |
+
numpy
|
| 4 |
+
matplotlib
|
| 5 |
+
tensorflow
|
| 6 |
+
pywt
|
| 7 |
+
scipy
|