ecg-real-time / app.py
samyak152002's picture
Update app.py
27ee864 verified
raw
history blame contribute delete
No virus
2.17 kB
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
import numpy as np
# Load and preprocess the ECG data
df = pd.read_csv("mitbih_train.csv", header=None)
# Preprocess the data
M = df.values
X = M[:, :-1]
y = M[:, -1].astype(int)
# Identify indices for different categories
C0 = np.argwhere(y == 0).flatten()
C1 = np.argwhere(y == 1).flatten()
C2 = np.argwhere(y == 2).flatten()
C3 = np.argwhere(y == 3).flatten()
C4 = np.argwhere(y == 4).flatten()
# Time axis
x = np.arange(0, 187) * 8 / 1000
# Initialize Dash app
app = dash.Dash(__name__)
# Expose the Flask server instance for Gunicorn
server = app.server
# App layout with live graph and interval for updates
app.layout = html.Div([
html.H1("Real-Time ECG Visualization"),
dcc.Graph(id='live-ecg-graph'),
dcc.Interval(id='interval-component', interval=1000, n_intervals=0), # Update every second
])
# Callback to update the ECG plot in real-time
@app.callback(Output('live-ecg-graph', 'figure'),
[Input('interval-component', 'n_intervals')])
def update_graph_live(n_intervals):
# Simulate real-time update by cycling through data for each category
idx = n_intervals % len(C0)
# Plot for each category (replace with actual streaming data if needed)
fig = go.Figure()
fig.add_trace(go.Scatter(x=x, y=X[C0[idx], :], mode='lines', name="Cat. N"))
fig.add_trace(go.Scatter(x=x, y=X[C1[idx], :], mode='lines', name="Cat. S"))
fig.add_trace(go.Scatter(x=x, y=X[C2[idx], :], mode='lines', name="Cat. V"))
fig.add_trace(go.Scatter(x=x, y=X[C3[idx], :], mode='lines', name="Cat. F"))
fig.add_trace(go.Scatter(x=x, y=X[C4[idx], :], mode='lines', name="Cat. Q"))
# Update layout
fig.update_layout(
title="Real-Time ECG for Every Category",
xaxis_title="Time (ms)",
yaxis_title="Amplitude",
legend_title="Category",
height=600,
margin=dict(l=50, r=50, t=50, b=50),
)
return fig
# Run the server
if __name__ == '__main__':
app.run_server(debug=True, host='0.0.0.0', port=8080) # Changed to port 8080