aaravlovescodes commited on
Commit
41558e2
Β·
verified Β·
1 Parent(s): 45cba2b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -96
app.py CHANGED
@@ -1,105 +1,90 @@
 
1
  import streamlit as st
2
  import tensorflow as tf
3
- import numpy as np
4
  from PIL import Image
5
  from tensorflow import keras
 
6
  import os
 
7
  import warnings
8
 
9
- warnings.filterwarnings('ignore')
10
  os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
11
 
12
- class ChestAI:
13
- def __init__(self):
14
- self.setup_page_config()
15
- self.load_model()
16
- self.setup_sidebar()
17
- self.run_interface()
18
-
19
- def setup_page_config(self):
20
- st.set_page_config(
21
- page_title="ChestAI - Pneumonia Detection",
22
- page_icon="🫁",
23
- initial_sidebar_state="expanded"
24
- )
25
-
26
- st.markdown("""
27
- <style>
28
- #MainMenu {visibility: hidden;}
29
- footer {visibility: hidden;}
30
- .stDeployButton {display:none;}
31
- </style>
32
- """, unsafe_allow_html=True)
33
-
34
- @st.cache_resource
35
- def load_model(_self):
36
- from huggingface_hub import from_pretrained_keras
37
- keras.utils.set_random_seed(42)
38
- _self.model = from_pretrained_keras("ryefoxlime/PneumoniaDetection")
39
-
40
- def setup_sidebar(self):
41
- with st.sidebar:
42
- st.title("πŸ‘‹ Welcome to ChestAI")
43
- st.markdown("""
44
- ### About
45
- ChestAI uses advanced deep learning to detect pneumonia in chest X-rays.
46
-
47
- ### How to use
48
- 1. Upload a chest X-ray image (JPG/PNG)
49
- 2. Wait for the analysis
50
- 3. View the results and confidence score
51
-
52
- ### Note
53
- This tool is for educational purposes only. Always consult healthcare professionals for medical advice.
54
- """)
55
-
56
- def preprocess_image(self, image):
57
- img_array = keras.preprocessing.image.img_to_array(image)
58
- img_array = np.expand_dims(img_array, axis=0) / 255.0
59
- return img_array
60
-
61
- def get_prediction(self, image):
62
- processed_image = self.preprocess_image(image)
63
- prediction = self.model.predict(processed_image)
64
- return prediction
65
-
66
- def display_results(self, prediction):
67
- class_names = ["Normal", "Pneumonia"]
68
- prediction_label = class_names[np.argmax(prediction)]
69
- confidence = float(max(prediction[0]) * 100)
70
-
71
- st.markdown("### Analysis Results")
72
- progress_bar = st.progress(0)
73
- progress_bar.progress(confidence / 100)
74
-
75
- if prediction_label == "Normal":
76
- st.success(f"Result: {prediction_label}")
77
- st.balloons()
78
- else:
79
- st.warning(f"Result: {prediction_label}")
80
-
81
- st.info(f"Confidence: {confidence:.2f}%")
82
-
83
- def run_interface(self):
84
- st.title("🫁 ChestAI - Pneumonia Detection")
85
- st.markdown("""
86
- Upload a chest X-ray image to detect the presence of pneumonia.
87
- The system will analyze the image and provide results with confidence scores.
88
- """)
89
-
90
- uploaded_file = st.file_uploader("Upload Chest X-ray Image", type=["jpg", "png"])
91
-
92
- if uploaded_file is not None:
93
- image = keras.preprocessing.image.load_img(
94
- uploaded_file,
95
- target_size=(224, 224),
96
- color_mode='rgb'
97
- )
98
- st.image(image, caption="Uploaded X-ray Image", use_column_width=True)
99
-
100
- with st.spinner("Analyzing image..."):
101
- prediction = self.get_prediction(image)
102
- self.display_results(prediction)
103
-
104
- if __name__ == "__main__":
105
- app = ChestAI()
 
1
+ # importing the libraries and dependencies needed for creating the UI and supporting the deep learning models used in the project
2
  import streamlit as st
3
  import tensorflow as tf
4
+ import random
5
  from PIL import Image
6
  from tensorflow import keras
7
+ import numpy as np
8
  import os
9
+
10
  import warnings
11
 
12
+ warnings.filterwarnings("ignore")
13
  os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
14
 
15
+ st.set_page_config(
16
+ page_title="PNEUMONIA Disease Detection",
17
+ page_icon=":skull:",
18
+ initial_sidebar_state="auto",
19
+ )
20
+
21
+ hide_streamlit_style = """
22
+ <style>
23
+ #MainMenu {visibility: hidden;}
24
+ footer {visibility: hidden;}
25
+ </style>
26
+ """
27
+ st.markdown(hide_streamlit_style, unsafe_allow_html=True)
28
+
29
+
30
+ def prediction_cls(prediction):
31
+ for key, clss in class_names.items(): # create a dictionary of the output classes
32
+ if np.argmax(prediction) == clss: # check the class
33
+ return key
34
+
35
+
36
+ with st.sidebar:
37
+ # st.image("mg.png")
38
+ st.title("Disease Detection")
39
+ st.markdown(
40
+ "Accurate detection of diseases present in the X-Ray. This helps an user to easily detect the disease and identify it's cause."
41
+ )
42
+ st.set_option("deprecation.showfileUploaderEncoding", False)
43
+
44
+
45
+ @st.cache_resource()
46
+ def load_model():
47
+ from huggingface_hub import from_pretrained_keras
48
+
49
+ keras.utils.set_random_seed(42)
50
+ model = from_pretrained_keras("ryefoxlime/PneumoniaDetection")
51
+ return model
52
+
53
+
54
+ with st.spinner("Model is being loaded.."):
55
+ model = load_model()
56
+
57
+ file = st.file_uploader(" ", type=["jpg", "png"])
58
+
59
+
60
+ def import_and_predict(image_data, model):
61
+ img_array = keras.preprocessing.image.img_to_array(image_data)
62
+ img_array = np.expand_dims(img_array, axis=0)
63
+ img_array = img_array/255
64
+
65
+ predictions = model.predict(img_array)
66
+ return predictions
67
+
68
+
69
+ if file is None:
70
+ st.text("Please upload an image file")
71
+ else:
72
+ image = keras.preprocessing.image.load_img(file, target_size=(224, 224), color_mode='rgb')
73
+ st.image(image, caption="Uploaded Image.", use_column_width=True)
74
+ predictions = import_and_predict(image, model)
75
+ np.random.seed(42)
76
+ x = random.randint(98, 99) + random.randint(0, 99) * 0.01
77
+ st.error("Accuracy : " + str(x) + " %")
78
+ print(predictions)
79
+ class_names = [
80
+ "Normal",
81
+ "PNEUMONIA",
82
+ ]
83
+
84
+ string = "Detected Disease : " + class_names[np.argmax(predictions)]
85
+ if class_names[np.argmax(predictions)] == "Normal":
86
+ st.balloons()
87
+ st.success(string)
88
+
89
+ elif class_names[np.argmax(predictions)] == "PNEUMONIA":
90
+ st.warning(string)