Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -4,76 +4,77 @@ import numpy as np
|
|
4 |
import pandas as pd
|
5 |
import tensorflow as tf
|
6 |
from tensorflow.keras.models import load_model
|
7 |
-
|
8 |
-
from werkzeug.utils import secure_filename
|
9 |
import biosppy.signals.ecg as ecg
|
|
|
|
|
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 |
-
csv_path = os.path.join(app.config['UPLOAD_FOLDER'], 'converted_signal.csv')
|
62 |
-
df = pd.DataFrame(signal, columns=[' Sample Value'])
|
63 |
-
df.to_csv(csv_path, index=False)
|
64 |
-
|
65 |
-
return csv_path
|
66 |
|
67 |
-
def model_predict(
|
68 |
-
|
69 |
-
|
|
|
70 |
APC, NORMAL, LBB, PVC, PAB, RBB, VEB = [], [], [], [], [], [], []
|
71 |
-
output.append(str(path))
|
72 |
result = {"APC": APC, "Normal": NORMAL, "LBB": LBB, "PAB": PAB, "PVC": PVC, "RBB": RBB, "VEB": VEB}
|
73 |
|
74 |
-
kernel = np.ones((4,4), np.uint8)
|
75 |
-
csv = pd.read_csv(
|
76 |
-
csv_data = csv[
|
77 |
data = np.array(csv_data)
|
78 |
signals = []
|
79 |
count = 1
|
@@ -97,49 +98,64 @@ def model_predict(uploaded_files, model):
|
|
97 |
img[i, int(signal[i] / 10)] = 255
|
98 |
img = cv2.dilate(img, kernel, iterations=1)
|
99 |
img = img.reshape(128, 128, 1)
|
100 |
-
prediction = model.predict(np.array([img])).argmax()
|
101 |
-
classes = [
|
102 |
result[classes[prediction]].append(index)
|
103 |
|
104 |
-
output.append(result)
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
@app.route('/', methods=['GET'])
|
109 |
-
def index():
|
110 |
-
return render_template('index.html')
|
111 |
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
|
|
|
|
|
|
124 |
file.save(file_path)
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
141 |
|
142 |
-
if __name__ ==
|
143 |
-
|
144 |
-
os.makedirs(UPLOAD_FOLDER)
|
145 |
-
app.run(debug=True, host='0.0.0.0', port=5000)
|
|
|
4 |
import pandas as pd
|
5 |
import tensorflow as tf
|
6 |
from tensorflow.keras.models import load_model
|
7 |
+
import gradio as gr
|
|
|
8 |
import biosppy.signals.ecg as ecg
|
9 |
+
from PIL import Image
|
10 |
+
import traceback
|
11 |
|
12 |
+
# Create uploads directory
|
13 |
+
UPLOAD_FOLDER = "/tmp/uploads"
|
14 |
+
if not os.path.exists(UPLOAD_FOLDER):
|
15 |
+
os.makedirs(UPLOAD_FOLDER)
|
16 |
|
17 |
+
# Load the pre-trained model (assumes ecgScratchEpoch2.hdf5 is in the root directory)
|
18 |
+
try:
|
19 |
+
model = load_model("ecgScratchEpoch2.hdf5")
|
20 |
+
except Exception as e:
|
21 |
+
raise Exception(f"Failed to load model: {str(e)}")
|
22 |
|
23 |
+
def image_to_signal(image):
|
24 |
+
"""Convert an ECG image to a 1D signal and save as CSV."""
|
25 |
+
try:
|
26 |
+
# Convert Gradio image (PIL) to OpenCV format
|
27 |
+
img = np.array(image)
|
28 |
+
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
29 |
+
|
30 |
+
# Resize to a standard size
|
31 |
+
img = cv2.resize(img, (1000, 500))
|
32 |
+
|
33 |
+
# Apply thresholding to isolate waveform
|
34 |
+
_, binary = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY_INV)
|
35 |
+
|
36 |
+
# Find contours
|
37 |
+
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
38 |
+
if not contours:
|
39 |
+
raise ValueError("No waveform detected in the image")
|
40 |
+
|
41 |
+
# Use the largest contour
|
42 |
+
contour = max(contours, key=cv2.contourArea)
|
43 |
+
|
44 |
+
# Extract y-coordinates along x-axis
|
45 |
+
signal = []
|
46 |
+
width = img.shape[1]
|
47 |
+
for x in range(width):
|
48 |
+
column = contour[contour[:, :, 0] == x]
|
49 |
+
if len(column) > 0:
|
50 |
+
y = np.mean(column[:, :, 1])
|
51 |
+
signal.append(y)
|
52 |
+
else:
|
53 |
+
signal.append(signal[-1] if signal else 0)
|
54 |
+
|
55 |
+
# Normalize signal
|
56 |
+
signal = np.array(signal)
|
57 |
+
signal = (signal - np.min(signal)) / (np.max(signal) - np.min(signal)) * 1000
|
58 |
+
|
59 |
+
# Save to CSV
|
60 |
+
csv_path = os.path.join(UPLOAD_FOLDER, "converted_signal.csv")
|
61 |
+
df = pd.DataFrame(signal, columns=[" Sample Value"])
|
62 |
+
df.to_csv(csv_path, index=False)
|
63 |
+
|
64 |
+
return csv_path
|
65 |
+
except Exception as e:
|
66 |
+
raise Exception(f"Image processing error: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
+
def model_predict(csv_path):
|
69 |
+
"""Predict ECG arrhythmia classes from a CSV file."""
|
70 |
+
try:
|
71 |
+
output = []
|
72 |
APC, NORMAL, LBB, PVC, PAB, RBB, VEB = [], [], [], [], [], [], []
|
|
|
73 |
result = {"APC": APC, "Normal": NORMAL, "LBB": LBB, "PAB": PAB, "PVC": PVC, "RBB": RBB, "VEB": VEB}
|
74 |
|
75 |
+
kernel = np.ones((4, 4), np.uint8)
|
76 |
+
csv = pd.read_csv(csv_path)
|
77 |
+
csv_data = csv[" Sample Value"]
|
78 |
data = np.array(csv_data)
|
79 |
signals = []
|
80 |
count = 1
|
|
|
98 |
img[i, int(signal[i] / 10)] = 255
|
99 |
img = cv2.dilate(img, kernel, iterations=1)
|
100 |
img = img.reshape(128, 128, 1)
|
101 |
+
prediction = model.predict(np.array([img]), verbose=0).argmax()
|
102 |
+
classes = ["Normal", "APC", "LBB", "PAB", "PVC", "RBB", "VEB"]
|
103 |
result[classes[prediction]].append(index)
|
104 |
|
105 |
+
output.append({"file": csv_path, "results": result})
|
106 |
+
return output
|
107 |
+
except Exception as e:
|
108 |
+
raise Exception(f"Prediction error: {str(e)}")
|
|
|
|
|
|
|
109 |
|
110 |
+
def classify_ecg(file):
|
111 |
+
"""Main function to handle file uploads (CSV or image)."""
|
112 |
+
try:
|
113 |
+
if file is None:
|
114 |
+
return "No file uploaded."
|
115 |
+
|
116 |
+
# Save uploaded file
|
117 |
+
file_path = os.path.join(UPLOAD_FOLDER, "uploaded_file")
|
118 |
+
if isinstance(file, str): # CSV file path
|
119 |
+
file_path += ".csv"
|
120 |
+
with open(file_path, "wb") as f:
|
121 |
+
with open(file, "rb") as src:
|
122 |
+
f.write(src.read())
|
123 |
+
else: # Image file (PIL Image from Gradio)
|
124 |
+
file_path += ".png"
|
125 |
file.save(file_path)
|
126 |
+
|
127 |
+
# Check file type
|
128 |
+
ext = file_path.rsplit(".", 1)[1].lower()
|
129 |
+
if ext in ["png", "jpg", "jpeg"]:
|
130 |
+
csv_path = image_to_signal(file)
|
131 |
+
elif ext == "csv":
|
132 |
+
csv_path = file_path
|
133 |
+
else:
|
134 |
+
return "Unsupported file type. Use CSV, PNG, or JPG."
|
135 |
+
|
136 |
+
# Run prediction
|
137 |
+
results = model_predict(csv_path)
|
138 |
+
|
139 |
+
# Format output
|
140 |
+
output = ""
|
141 |
+
for result in results:
|
142 |
+
output += f"File: {result['file']}\n"
|
143 |
+
for key, value in result["results"].items():
|
144 |
+
if value:
|
145 |
+
output += f"{key}: {value}\n"
|
146 |
+
|
147 |
+
return output
|
148 |
+
except Exception as e:
|
149 |
+
return f"Error: {str(e)}\n{traceback.format_exc()}"
|
150 |
+
|
151 |
+
# Gradio interface
|
152 |
+
iface = gr.Interface(
|
153 |
+
fn=classify_ecg,
|
154 |
+
inputs=gr.File(label="Upload ECG Image (PNG/JPG) or CSV"),
|
155 |
+
outputs=gr.Textbox(label="Classification Results"),
|
156 |
+
title="ECG Arrhythmia Classification",
|
157 |
+
description="Upload an ECG image (PNG/JPG) or CSV file to classify arrhythmias. Images will be converted to CSV before processing.",
|
158 |
+
)
|
159 |
|
160 |
+
if __name__ == "__main__":
|
161 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|