File size: 2,132 Bytes
86fe3d8 |
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 |
import gradio as gr
import numpy as np
import pandas as pd
import wfdb
import tensorflow as tf
from scipy import signal
import os
# Load the pre-trained model (adjust path as needed)
model = tf.keras.models.load_model("model.h5")
# Function to preprocess ECG data (simplified from the repo)
def preprocess_ecg(file_path):
# Read ECG file (assuming WFDB format like .dat)
record = wfdb.rdrecord(file_path.replace(".dat", ""))
ecg_signal = record.p_signal[:, 0] # Use first lead for simplicity
# Resample to 360 Hz (common ECG frequency)
target_fs = 360
num_samples = int(len(ecg_signal) * target_fs / record.fs)
ecg_resampled = signal.resample(ecg_signal, num_samples)
# Normalize
ecg_normalized = (ecg_resampled - np.mean(ecg_resampled)) / np.std(ecg_resampled)
# Segment into fixed length (e.g., 3600 samples = 10 seconds at 360 Hz)
if len(ecg_normalized) < 3600:
ecg_normalized = np.pad(ecg_normalized, (0, 3600 - len(ecg_normalized)), "constant")
else:
ecg_normalized = ecg_normalized[:3600]
# Reshape for model input (assuming model expects [1, 3600, 1])
ecg_input = ecg_normalized.reshape(1, 3600, 1)
return ecg_input
# Prediction function
def predict_ecg(file):
# Extract file path from uploaded file
file_path = file.name
# Preprocess the ECG data
ecg_data = preprocess_ecg(file_path)
# Make prediction
prediction = model.predict(ecg_data)
# Assuming binary classification (e.g., Normal vs. Abnormal)
label = "Abnormal" if prediction[0][0] > 0.5 else "Normal"
confidence = float(prediction[0][0]) if label == "Abnormal" else float(1 - prediction[0][0])
return f"Prediction: {label}\nConfidence: {confidence:.2%}"
# Gradio interface
interface = gr.Interface(
fn=predict_ecg,
inputs=gr.File(label="Upload ECG File (.dat format)"),
outputs=gr.Textbox(label="ECG Interpretation"),
title="Automated ECG Interpretation",
description="Upload an ECG file in WFDB format (.dat) to get an automated interpretation."
)
# Launch the app
interface.launch() |