ECG / appold
Nayefleb's picture
Rename app.py to appold
9abee58 verified
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()