aaravlovescodes commited on
Commit
a001a28
Β·
verified Β·
1 Parent(s): 557e11f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -71
app.py CHANGED
@@ -1,4 +1,3 @@
1
- # Import libraries and dependencies for the UI and deep learning model
2
  import streamlit as st
3
  import tensorflow as tf
4
  import numpy as np
@@ -6,85 +5,101 @@ from PIL import Image
6
  from tensorflow import keras
7
  import os
8
  import warnings
9
- import random
10
 
11
- # Suppress warnings and configure TensorFlow settings
12
- warnings.filterwarnings("ignore")
13
  os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
14
 
15
- # Set up Streamlit page configuration
16
- st.set_page_config(
17
- page_title="PNEUMONIA Disease Detection",
18
- page_icon=":skull:",
19
- initial_sidebar_state="auto",
20
- )
21
 
22
- # Hide Streamlit's main menu and footer
23
- st.markdown("""
24
- <style>
25
- #MainMenu {visibility: hidden;}
26
- footer {visibility: hidden;}
27
- </style>
28
- """, unsafe_allow_html=True)
 
 
 
 
 
 
 
29
 
30
- # Define a function to map model predictions to their class names
31
- def prediction_class(prediction):
32
- for label, class_index in class_names.items():
33
- if np.argmax(prediction) == class_index:
34
- return label
35
 
36
- # Configure sidebar content with description
37
- with st.sidebar:
38
- st.title("Disease Detection")
39
- st.markdown(
40
- "Accurate detection of diseases in X-ray images. This helps users easily detect diseases and understand their potential causes."
41
- )
 
 
 
 
 
 
 
 
 
42
 
43
- # Set file upload options
44
- st.set_option("deprecation.showfileUploaderEncoding", False)
 
 
45
 
46
- # Load the model from Hugging Face Hub, with caching for optimization
47
- @st.cache_resource()
48
- def load_model():
49
- from huggingface_hub import from_pretrained_keras
50
- keras.utils.set_random_seed(42)
51
- model = from_pretrained_keras("ryefoxlime/PneumoniaDetection")
52
- return model
53
 
54
- # Display loading spinner while model is being loaded
55
- with st.spinner("Model is being loaded.."):
56
- model = load_model()
 
57
 
58
- # Set up file uploader to accept image files (JPEG or PNG)
59
- file = st.file_uploader(" ", type=["jpg", "png"])
 
 
 
 
 
 
 
 
 
60
 
61
- # Preprocess and run the model on uploaded image
62
- def import_and_predict(image_data, model):
63
- img_array = keras.preprocessing.image.img_to_array(image_data)
64
- img_array = np.expand_dims(img_array, axis=0) / 255.0
65
- predictions = model.predict(img_array)
66
- return predictions
67
 
68
- # If no file is uploaded, prompt the user
69
- if file is None:
70
- st.text("Please upload an image file")
71
- else:
72
- # Display uploaded image and run predictions
73
- image = keras.preprocessing.image.load_img(file, target_size=(224, 224), color_mode='rgb')
74
- st.image(image, caption="Uploaded Image.", use_column_width=True)
75
- predictions = import_and_predict(image, model)
76
-
77
- # Generate a random accuracy display
78
- np.random.seed(42)
79
- accuracy = random.randint(98, 99) + random.randint(0, 99) * 0.01
80
- st.error("Accuracy: " + str(accuracy) + "%")
81
-
82
- # Define class names and display prediction results
83
- class_names = ["Normal", "PNEUMONIA"]
84
- prediction_label = class_names[np.argmax(predictions)]
85
-
86
- if prediction_label == "Normal":
87
- st.balloons()
88
- st.success("Detected Disease: " + prediction_label)
89
- else:
90
- st.warning("Detected Disease: " + prediction_label)
 
 
1
  import streamlit as st
2
  import tensorflow as tf
3
  import numpy as np
 
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()