ruanhelansantos's picture
Upload app.py
f9e1b5b verified
Raw History Blame Contribute Delete
3.37 kB
# app.py
# ECG Condition Classifier
# ARIN 460 - Unit 8 Final Project
# Author: Ruan Dos Santos
import gradio as gr
from utils import load_and_preprocess, validate_image
from model import run_inference, get_top_prediction
from explainer import generate_explanation, format_top3, match_condition
def classify_ecg(image):
is_valid, message = validate_image(image)
if not is_valid:
return message, "Please upload a valid ECG image.", ""
try:
processed_image = load_and_preprocess(image)
except Exception as e:
return f"Preprocessing error: {str(e)}", "", ""
try:
results = run_inference(processed_image, top_k=5)
except Exception as e:
return f"Model inference error: {str(e)}", "", ""
label, confidence = get_top_prediction(results)
condition = match_condition(label)
full_name = condition.get("summary", label)
explanation_text, urgency = generate_explanation(label, confidence)
top3_text = format_top3(results)
urgency_icon = {
"Routine": "βœ…",
"Elevated": "⚠️",
"Moderate": "⚠️",
"URGENT": "🚨",
"Unknown": "❓",
}.get(urgency, "❓")
result_text = (
f"{urgency_icon} Predicted: {full_name}\n"
f"Raw Label: {label}\n"
f"Confidence: {confidence:.1f}%\n"
f"Urgency: {urgency}"
)
return result_text, explanation_text, top3_text
examples_description = """
**How to use this tool:**
1. Upload a 12-lead ECG image (PNG, JPG, or TIFF)
2. The AI will classify the ECG and generate a clinical explanation
3. Review the confidence scores and urgency level
**Supported Conditions:**
- **NORM** β€” Normal Sinus Rhythm
- **AFIB** β€” Atrial Fibrillation
- **MI** β€” Myocardial Infarction
- **STTC** β€” ST/T-Wave Changes
- **CD** β€” Conduction Disturbance
"""
with gr.Blocks(title="ECG Condition Classifier") as demo:
gr.Markdown("# πŸ«€ ECG Condition Classifier")
gr.Markdown(
"**Multimodal AI system for cardiac rhythm detection** | "
"ARIN 460 Final Project β€” Ruan Dos Santos"
)
gr.Markdown(
"> ⚠️ **DISCLAIMER:** This tool is for **educational purposes only**. "
"It does not constitute medical advice. Always consult a qualified healthcare provider."
)
with gr.Row():
with gr.Column(scale=1):
image_input = gr.Image(type="pil", label="Upload ECG Image")
submit_btn = gr.Button("πŸ” Analyze ECG", variant="primary")
gr.Markdown(examples_description)
with gr.Column(scale=1):
result_output = gr.Textbox(
label="Classification Result", lines=4, interactive=False)
explanation_output = gr.Textbox(
label="Clinical Explanation", lines=10, interactive=False)
top3_output = gr.Textbox(
label="Confidence Breakdown", lines=6, interactive=False)
submit_btn.click(
fn=classify_ecg,
inputs=[image_input],
outputs=[result_output, explanation_output, top3_output]
)
gr.Markdown("---")
gr.Markdown(
"**Model:** Vision Transformer (ViT) fine-tuned on PTB-XL ECG images | "
"**Dataset:** PTB-XL (PhysioNet) | "
"**Framework:** Hugging Face Transformers + Gradio"
)
if __name__ == "__main__":
demo.launch()