GarimaSharma75 commited on
Commit
96b0b03
·
verified ·
1 Parent(s): 12d2035

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -140
app.py DELETED
@@ -1,140 +0,0 @@
1
- import os
2
- os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
3
-
4
- import streamlit as st
5
- import numpy as np
6
- import os
7
- import pickle
8
- import zipfile
9
- import matplotlib.pyplot as plt
10
- from tensorflow.keras.models import load_model
11
- from tensorflow.keras.preprocessing import image
12
-
13
- # --- CONFIG ---
14
- st.set_page_config(page_title="Leukemia Subtype Detector", layout="centered")
15
-
16
- st.markdown("""
17
- <div style='background-color:#57068c;padding:20px;border-radius:10px'>
18
- <h2 style='color:white;text-align:center'>🧬 Leukemia Subtype Detection</h2>
19
- <p style='color:white;text-align:center'>
20
- Uses an ensemble of 4 models: <b>DenseNet121</b>, <b>MobileNetV2</b>, <b>VGG16</b>, and <b>Custom CNN</b>.<br>
21
- Predicts: <i>Benign</i>, <i>Pre</i>, <i>Pro</i>, <i>Early</i>.
22
- </p>
23
- </div>
24
- """, unsafe_allow_html=True)
25
-
26
- # --- CONSTANTS ---
27
- IMG_HEIGHT, IMG_WIDTH = 224, 224
28
- CLASS_NAMES = ['Benign', 'Pre', 'Pro', 'Early']
29
- SAVE_DIR = 'saved_leukemia_ensemble'
30
- MODEL_ZIPS = {
31
- "DenseNet121": "DenseNet121_model.zip",
32
- "MobileNetV2": "MobileNetV2_model.zip",
33
- "VGG16": "VGG16_model.zip",
34
- "CustomCNN": "CustomCNN_model.zip"
35
- }
36
- ENSEMBLE_WEIGHTS = {
37
- "DenseNet121": 0.28,
38
- "MobileNetV2": 0.30,
39
- "VGG16": 0.22,
40
- "CustomCNN": 0.20
41
- }
42
- HISTORY_PATHS = {
43
- name: os.path.join(SAVE_DIR, f"{name}_history.pkl") for name in MODEL_ZIPS
44
- }
45
-
46
- # --- UTIL FUNCTION ---
47
- def extract_model_if_needed(zip_path, output_path):
48
- if not os.path.exists(output_path):
49
- with zipfile.ZipFile(zip_path, 'r') as zip_ref:
50
- zip_ref.extractall(os.path.dirname(output_path))
51
-
52
- # --- LOAD MODELS ---
53
- @st.cache_resource
54
- def load_all_models():
55
- models = {}
56
- for name, zip_file in MODEL_ZIPS.items():
57
- zip_path = os.path.join(SAVE_DIR, zip_file)
58
- keras_path = zip_path.replace(".zip", ".keras")
59
-
60
- extract_model_if_needed(zip_path, keras_path)
61
-
62
- if os.path.exists(keras_path):
63
- models[name] = load_model(keras_path, compile=False)
64
- else:
65
- st.warning(f"❌ Model not found: {keras_path}")
66
- return models
67
-
68
- models = load_all_models()
69
-
70
- # --- UPLOAD IMAGE ---
71
- uploaded_file = st.file_uploader("📁 Upload a blood smear image", type=["jpg", "jpeg", "png"])
72
-
73
- if uploaded_file:
74
- st.image(uploaded_file, caption="Uploaded Image", use_container_width=True)
75
-
76
- if st.button("🔍 Enter"):
77
- with st.spinner("⏳ Please wait while results are being computed..."):
78
- try:
79
- img = image.load_img(uploaded_file, target_size=(IMG_HEIGHT, IMG_WIDTH))
80
- img_array = image.img_to_array(img) / 255.0
81
- img_array = np.expand_dims(img_array, axis=0)
82
-
83
- st.markdown("### 🧪 Model Predictions:")
84
- col1, col2 = st.columns(2)
85
- individual_preds = {}
86
-
87
- for i, (name, model) in enumerate(models.items()):
88
- pred = model.predict(img_array)
89
- individual_preds[name] = pred
90
- cls = CLASS_NAMES[np.argmax(pred)]
91
- conf = pred[0][np.argmax(pred)]
92
- with [col1, col2][i % 2]:
93
- st.info(f"**{name}** ➜ `{cls}` ({conf:.2%})")
94
-
95
- ensemble_pred = sum(ENSEMBLE_WEIGHTS[name] * pred for name, pred in individual_preds.items())
96
- final_class = CLASS_NAMES[np.argmax(ensemble_pred)]
97
- final_conf = float(np.max(ensemble_pred))
98
-
99
- st.markdown(f"""
100
- <div style="background-color:#c6f6d5;padding:15px;border-radius:10px">
101
- <h4 style="color:#2f855a">✅ Ensemble Prediction: <b>{final_class}</b></h4>
102
- <p style="font-size:16px;color:#22543d">Confidence: <b>{final_conf:.2%}</b></p>
103
- </div>
104
- """, unsafe_allow_html=True)
105
-
106
- st.bar_chart({CLASS_NAMES[i]: float(ensemble_pred[0][i]) for i in range(4)})
107
-
108
- except Exception as e:
109
- st.error(f"⚠️ Error: {e}")
110
- else:
111
- st.info("👈 Please upload an image to begin.")
112
-
113
- # --- OPTIONAL TRAINING VISUALIZATION ---
114
- st.markdown("---")
115
- st.subheader("📈 Model Training History")
116
-
117
- if st.checkbox("Show training curves"):
118
- for name, path in HISTORY_PATHS.items():
119
- if os.path.exists(path):
120
- with open(path, "rb") as f:
121
- hist = pickle.load(f)
122
- acc = hist['accuracy']
123
- val_acc = hist['val_accuracy']
124
- loss = hist['loss']
125
- val_loss = hist['val_loss']
126
-
127
- fig, ax = plt.subplots(1, 2, figsize=(12, 4))
128
- ax[0].plot(acc, label='Train Acc')
129
- ax[0].plot(val_acc, label='Val Acc')
130
- ax[0].set_title(f'{name} Accuracy')
131
- ax[0].legend()
132
-
133
- ax[1].plot(loss, label='Train Loss')
134
- ax[1].plot(val_loss, label='Val Loss')
135
- ax[1].set_title(f'{name} Loss')
136
- ax[1].legend()
137
-
138
- st.pyplot(fig)
139
- else:
140
- st.warning(f"No training history found for {name}")