hamaadayubkhan commited on
Commit
fa0c5f1
·
verified ·
1 Parent(s): d995eb3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -74
app.py CHANGED
@@ -2,20 +2,14 @@ import streamlit as st
2
  from PIL import Image
3
  import numpy as np
4
  import torch
5
- from transformers import ViTForImageClassification, pipeline
6
- import io
7
 
8
- # Load the Hugging Face model for ECG classification
9
- model_name = "adilsaleem/ecg-image-multilabel-classification"
10
- try:
11
- model = ViTForImageClassification.from_pretrained(model_name)
12
- model.eval() # Set the model to evaluation mode
13
- except Exception as e:
14
- st.error(f"Error loading model: {str(e)}")
15
- st.stop()
16
 
17
- # Load the Hugging Face Q&A model
18
- qa_model = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad")
19
 
20
  # CSS for styling
21
  st.markdown(
@@ -56,77 +50,66 @@ st.markdown(
56
  st.markdown('<div class="title">ECG READER</div>', unsafe_allow_html=True)
57
  st.markdown('<div class="subtitle">Created by Hamaad Ayub Khan</div>', unsafe_allow_html=True)
58
 
59
- def preprocess_image(image):
60
- try:
 
61
  image = image.convert("RGB")
62
  image = image.resize((224, 224))
63
  image_array = np.array(image) / 255.0
64
  image_array = np.transpose(image_array, (2, 0, 1))
65
- return torch.tensor(image_array).unsqueeze(0)
66
- except Exception as e:
67
- st.error(f"Error processing image: {str(e)}")
68
- return None
69
 
70
- def classify_ecg(image):
71
- processed_image = preprocess_image(image)
72
- if processed_image is None:
73
- return "Error in image processing."
74
-
75
- try:
76
- with torch.no_grad():
77
- outputs = model(processed_image)
78
- logits = outputs.logits
79
- predicted_class = torch.argmax(logits, dim=1).item()
80
-
81
- return "Clear" if predicted_class == 1 else "Unclear"
82
- except Exception as e:
83
- st.error(f"Error during model inference: {str(e)}")
84
- return "Error in classification."
85
 
86
- def get_ecg_explanation(status):
87
- explanations = {
88
- "Clear": "A clear ECG indicates normal heart activity without significant issues.",
89
- "Unclear": "An unclear ECG may indicate possible abnormalities; further evaluation is recommended."
90
- }
91
- return explanations.get(status, "No explanation available.")
92
 
93
  # Streamlit UI for ECG Upload
94
- st.write("Upload your ECG image.")
95
-
96
- uploaded_file = st.file_uploader("Select an ECG image", type=["jpg", "jpeg", "png"])
97
-
98
- if uploaded_file:
99
- # Check if the uploaded file is an ECG image
100
- try:
101
- # Check the MIME type of the uploaded file
102
- image_type = uploaded_file.type
103
- if image_type not in ["image/jpeg", "image/png"]:
104
- st.error("Please upload a valid ECG image file (JPG or PNG).")
105
- else:
106
- image = Image.open(uploaded_file)
107
- st.image(image, caption="Uploaded ECG Image.", use_column_width=True)
108
-
109
- # Make predictions using the Hugging Face model
110
- heart_status = classify_ecg(image)
111
- st.write(f"Predicted heart status: {heart_status}")
112
-
113
- # Get explanation based on the status
114
- explanation = get_ecg_explanation(heart_status)
115
- st.write(f"Explanation: {explanation}")
116
-
117
- except Exception as e:
118
- st.error(f"Error uploading or displaying image: {str(e)}")
119
-
120
- # Q&A Section
121
- user_question = st.text_input("Ask any question about your ECG result", key="user_question")
 
 
 
 
122
  if user_question:
123
- try:
124
- # Context based on predicted status
125
- context = f"The ECG result is {heart_status}. {explanation}"
126
- answer = qa_model(question=user_question, context=context)
127
- st.write("Response:", answer['answer'])
128
- except Exception as e:
129
- st.error(f"Error answering question: {str(e)}")
130
 
131
  # About Us Section
132
  with st.expander("About the App"):
 
2
  from PIL import Image
3
  import numpy as np
4
  import torch
5
+ from transformers import AutoImageProcessor, AutoModelForImageClassification, pipeline
 
6
 
7
+ # Load the ECG classification model and processor
8
+ processor = AutoImageProcessor.from_pretrained("adilsaleem/ecg-image-multilabel-classification")
9
+ model = AutoModelForImageClassification.from_pretrained("adilsaleem/ecg-image-multilabel-classification")
 
 
 
 
 
10
 
11
+ # Load the text generation model
12
+ text_generator = pipeline("text-generation", model="gpt2") # You can choose any other model
13
 
14
  # CSS for styling
15
  st.markdown(
 
50
  st.markdown('<div class="title">ECG READER</div>', unsafe_allow_html=True)
51
  st.markdown('<div class="subtitle">Created by Hamaad Ayub Khan</div>', unsafe_allow_html=True)
52
 
53
+ def preprocess_images(images):
54
+ processed_images = []
55
+ for image in images:
56
  image = image.convert("RGB")
57
  image = image.resize((224, 224))
58
  image_array = np.array(image) / 255.0
59
  image_array = np.transpose(image_array, (2, 0, 1))
60
+ processed_images.append(torch.tensor(image_array).unsqueeze(0))
61
+ return torch.cat(processed_images)
 
 
62
 
63
+ def classify_ecg(images):
64
+ processed_images = preprocess_images(images)
65
+
66
+ with torch.no_grad():
67
+ outputs = model(processed_images)
68
+ logits = outputs.logits
69
+ predictions = torch.argmax(logits, dim=1)
70
+
71
+ return predictions
 
 
 
 
 
 
72
 
73
+ def get_response_from_model(user_question):
74
+ response = text_generator(user_question, max_length=50, num_return_sequences=1)
75
+ return response[0]['generated_text']
 
 
 
76
 
77
  # Streamlit UI for ECG Upload
78
+ st.write("Upload 3 to 5 ECG images.")
79
+
80
+ uploaded_files = st.file_uploader("Select ECG images", type=["jpg", "jpeg", "png"], accept_multiple_files=True)
81
+
82
+ if uploaded_files:
83
+ if len(uploaded_files) < 3 or len(uploaded_files) > 5:
84
+ st.error("Please upload between 3 and 5 ECG images.")
85
+ else:
86
+ ecg_images = []
87
+ valid_upload = True
88
+
89
+ for uploaded_file in uploaded_files:
90
+ image_type = uploaded_file.type
91
+ if image_type not in ["image/jpeg", "image/png"]:
92
+ st.error("Please upload valid ECG image files (JPG or PNG).")
93
+ valid_upload = False
94
+ break
95
+ else:
96
+ image = Image.open(uploaded_file)
97
+ ecg_images.append(image)
98
+
99
+ if valid_upload:
100
+ # Display uploaded ECG images
101
+ st.image(ecg_images, caption=["Uploaded ECG Image"] * len(ecg_images), use_column_width=True)
102
+
103
+ # Classify the ECG images
104
+ predictions = classify_ecg(ecg_images)
105
+ status_results = ["Clear" if pred == 1 else "Unclear" for pred in predictions]
106
+ st.write(f"Predicted heart status: {status_results}")
107
+
108
+ # User Question Section
109
+ user_question = st.text_input("Ask a question related to your ECG results", key="user_question")
110
  if user_question:
111
+ response = get_response_from_model(user_question)
112
+ st.write("Response:", response)
 
 
 
 
 
113
 
114
  # About Us Section
115
  with st.expander("About the App"):