MohammedAH commited on
Commit
ca6858a
·
verified ·
1 Parent(s): b1597d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -36
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # app.py
2
- import gradio as gr
3
  import numpy as np
4
  import os
5
  import tensorflow as tf
@@ -10,6 +10,14 @@ from PIL import Image
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
 
 
 
 
 
 
 
 
13
  # Disable GPU to save memory
14
  tf.config.set_visible_devices([], 'GPU')
15
  logger.info("TensorFlow configured for CPU-only")
@@ -17,8 +25,9 @@ logger.info("TensorFlow configured for CPU-only")
17
  # ===== Model Loading =====
18
  MODEL_FILE = "final_combined_model.keras"
19
 
 
20
  def load_model():
21
- """Load TensorFlow model from local file"""
22
  try:
23
  # Verify file exists
24
  if not os.path.exists(MODEL_FILE):
@@ -51,7 +60,7 @@ model = load_model()
51
  def preprocess_image(image):
52
  """Preprocess image for model prediction"""
53
  try:
54
- # Convert to PIL Image if it's a numpy array
55
  if isinstance(image, np.ndarray):
56
  img = Image.fromarray(image.astype('uint8'))
57
  else:
@@ -69,7 +78,8 @@ def preprocess_image(image):
69
  return None
70
 
71
  # ===== Prediction Function =====
72
- def predict(age, tumor_size, image):
 
73
  if model is None:
74
  return "Model failed to load", "Check logs", None
75
 
@@ -92,40 +102,117 @@ def predict(age, tumor_size, image):
92
  logger.error(error_msg)
93
  return error_msg, "Try again", image
94
 
95
- # ===== Gradio Interface =====
96
- with gr.Blocks(theme=gr.themes.Soft(), title="Breast Cancer Prediction") as demo:
97
- # Header
98
- gr.Markdown("# 🩺 Breast Cancer Prediction")
99
- gr.Markdown("Upload a breast medical image for cancer prediction")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
- # Status indicator
102
- status = gr.Textbox(value=" Ready" if model else "❌ Model not loaded",
103
- label="System Status", interactive=False)
104
 
105
- # Main interface
106
- with gr.Row():
107
- with gr.Column():
108
- inputs = [
109
- gr.Number(label="Patient Age", minimum=18, maximum=100, value=45),
110
- gr.Number(label="Tumor Size (mm)", minimum=0.1, value=15.0),
111
- gr.Image(label="Medical Image", type="filepath", sources=["upload"])
112
- ]
113
- submit_btn = gr.Button("Analyze", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
- with gr.Column():
116
- outputs = [
117
- gr.Label(label="Diagnosis"),
118
- gr.Label(label="Confidence"),
119
- gr.Image(label="Preview", interactive=False)
120
- ]
 
121
 
122
- # Callback
123
- submit_btn.click(
124
- fn=predict,
125
- inputs=inputs,
126
- outputs=outputs
127
- )
128
 
129
- # Launch the app
130
- if __name__ == "__main__":
131
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  # app.py
2
+ import streamlit as st
3
  import numpy as np
4
  import os
5
  import tensorflow as tf
 
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
+ # Set page configuration
14
+ st.set_page_config(
15
+ page_title="Breast Cancer Prediction",
16
+ page_icon="🩺",
17
+ layout="wide",
18
+ initial_sidebar_state="expanded"
19
+ )
20
+
21
  # Disable GPU to save memory
22
  tf.config.set_visible_devices([], 'GPU')
23
  logger.info("TensorFlow configured for CPU-only")
 
25
  # ===== Model Loading =====
26
  MODEL_FILE = "final_combined_model.keras"
27
 
28
+ @st.cache_resource(show_spinner=False)
29
  def load_model():
30
+ """Load TensorFlow model from local file with caching"""
31
  try:
32
  # Verify file exists
33
  if not os.path.exists(MODEL_FILE):
 
60
  def preprocess_image(image):
61
  """Preprocess image for model prediction"""
62
  try:
63
+ # Convert to PIL Image
64
  if isinstance(image, np.ndarray):
65
  img = Image.fromarray(image.astype('uint8'))
66
  else:
 
78
  return None
79
 
80
  # ===== Prediction Function =====
81
+ def predict(image):
82
+ """Make prediction using the loaded model"""
83
  if model is None:
84
  return "Model failed to load", "Check logs", None
85
 
 
102
  logger.error(error_msg)
103
  return error_msg, "Try again", image
104
 
105
+ # ===== Streamlit UI =====
106
+
107
+ # Custom CSS for styling
108
+ st.markdown("""
109
+ <style>
110
+ .stApp {
111
+ background-color: #f0f2f6;
112
+ }
113
+ .header {
114
+ color: #2c3e50;
115
+ text-align: center;
116
+ padding: 1rem;
117
+ }
118
+ .result-box {
119
+ border-radius: 10px;
120
+ padding: 1.5rem;
121
+ margin: 1rem 0;
122
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
123
+ }
124
+ .malignant {
125
+ background-color: #ffcccc;
126
+ border-left: 5px solid #e74c3c;
127
+ }
128
+ .benign {
129
+ background-color: #ccffcc;
130
+ border-left: 5px solid #2ecc71;
131
+ }
132
+ .stButton>button {
133
+ background-color: #3498db;
134
+ color: white;
135
+ border-radius: 5px;
136
+ padding: 0.5rem 1rem;
137
+ width: 100%;
138
+ }
139
+ .stButton>button:hover {
140
+ background-color: #2980b9;
141
+ }
142
+ </style>
143
+ """, unsafe_allow_html=True)
144
+
145
+ # Header
146
+ st.markdown("<h1 class='header'>🩺 Breast Cancer Prediction</h1>", unsafe_allow_html=True)
147
+ st.markdown("Upload a breast medical image for cancer prediction")
148
+
149
+ # Status indicator
150
+ status = "✅ Model loaded successfully" if model else "❌ Model failed to load"
151
+ st.info(status)
152
+
153
+ # Create two columns for layout
154
+ col1, col2 = st.columns([1, 1])
155
+
156
+ # Input column
157
+ with col1:
158
+ st.subheader("Patient Information")
159
 
160
+ # Input fields
161
+ age = st.number_input("Patient Age", min_value=18, max_value=100, value=45)
162
+ tumor_size = st.number_input("Tumor Size (mm)", min_value=0.1, value=15.0)
163
 
164
+ # Image upload
165
+ uploaded_file = st.file_uploader(
166
+ "Upload Medical Image",
167
+ type=["jpg", "jpeg", "png"],
168
+ help="Supported formats: JPG, JPEG, PNG"
169
+ )
170
+
171
+ # Predict button
172
+ predict_btn = st.button("Analyze Image")
173
+
174
+ # Results column
175
+ with col2:
176
+ st.subheader("Prediction Results")
177
+
178
+ # Initialize session state for results
179
+ if 'result' not in st.session_state:
180
+ st.session_state.result = None
181
+ st.session_state.confidence = None
182
+ st.session_state.image = None
183
+
184
+ # Process image when button is clicked
185
+ if predict_btn and uploaded_file is not None:
186
+ try:
187
+ image = Image.open(uploaded_file)
188
+ st.session_state.result, st.session_state.confidence, st.session_state.image = predict(image)
189
+ except Exception as e:
190
+ st.error(f"Error processing image: {str(e)}")
191
+
192
+ # Display results if available
193
+ if st.session_state.result:
194
+ # Result box with color coding
195
+ result_class = "malignant" if st.session_state.result == "Malignant" else "benign"
196
+ st.markdown(
197
+ f"<div class='result-box {result_class}'>"
198
+ f"<h3>Diagnosis: {st.session_state.result}</h3>"
199
+ f"<p>Confidence: {st.session_state.confidence}</p>"
200
+ "</div>",
201
+ unsafe_allow_html=True
202
+ )
203
 
204
+ # Display image
205
+ if st.session_state.image:
206
+ st.image(
207
+ st.session_state.image,
208
+ caption="Uploaded Image",
209
+ use_container_width=True
210
+ )
211
 
212
+ # Show placeholder if no results
213
+ elif not predict_btn:
214
+ st.info("Upload an image and click 'Analyze Image' to get prediction")
 
 
 
215
 
216
+ # Footer
217
+ st.markdown("---")
218
+ st.caption("This tool is for research purposes only. Consult a medical professional for clinical diagnosis.")