Spaces:
Runtime error
Runtime error
File size: 11,390 Bytes
ccd9d98 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | """
π³ Tree Classification App
Multi-stage hierarchical AI pipeline for tree species and growth stage detection.
Uses 4 trained models + Grad-CAM heatmaps.
"""
import streamlit as st
from PIL import Image
import torch
import numpy as np
from utils.model_loader import load_all_models
from utils.predictor import predict_tree, predict_species, predict_stage
from utils.gradcam import generate_gradcam
# ββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE CONFIGURATION
# ββββββββββββββββββββββββββββββββββββββββββββββ
st.set_page_config(
page_title="π³ Tree Classifier",
page_icon="π³",
layout="wide",
initial_sidebar_state="expanded"
)
# ββββββββββββββββββββββββββββββββββββββββββββββ
# CUSTOM CSS STYLING
# ββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown("""
<style>
.main-title {
font-size: 2.5rem;
font-weight: 800;
color: #2d6a4f;
text-align: center;
padding: 1rem 0;
}
.subtitle {
font-size: 1.1rem;
color: #52796f;
text-align: center;
margin-bottom: 2rem;
}
.result-box {
background: #f0f7f4;
border-left: 5px solid #2d6a4f;
padding: 1rem 1.5rem;
border-radius: 0 8px 8px 0;
margin: 1rem 0;
}
.warning-box {
background: #fff3cd;
border-left: 5px solid #ffc107;
padding: 1rem 1.5rem;
border-radius: 0 8px 8px 0;
margin: 1rem 0;
}
.stage-badge {
display: inline-block;
background: #2d6a4f;
color: white;
padding: 0.3rem 1rem;
border-radius: 20px;
font-weight: 700;
font-size: 1.1rem;
}
</style>
""", unsafe_allow_html=True)
# ββββββββββββββββββββββββββββββββββββββββββββββ
# HEADER
# ββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown('<div class="main-title">π³ Tree Species & Growth Stage Classifier</div>', unsafe_allow_html=True)
st.markdown('<div class="subtitle">Upload a tree photo to identify its species and growth stage using AI</div>', unsafe_allow_html=True)
# ββββββββββββββββββββββββββββββββββββββββββββββ
# SIDEBAR β INFO PANEL
# ββββββββββββββββββββββββββββββββββββββββββββββ
with st.sidebar:
st.header("π How It Works")
st.markdown("""
This app uses **4 AI models** in sequence:
1. π **Tree Detection** β Is it a tree?
2. πΏ **Species Detection** β Mango or White Gum?
3. π **Stage Classification** β What growth stage?
Each step also shows a **Grad-CAM heatmap** β a visualization of which part of the image the AI focused on.
""")
st.divider()
st.header("β οΈ System Limitations")
st.markdown("""
This system is currently trained only on:
- π₯ **Mango Trees**
- πΏ **White Gum / Eucalyptus Trees**
Upload images of these species for accurate results.
""")
st.divider()
st.header("π Growth Stages")
st.markdown("""
- π± **Seedling** β Very young, just sprouted
- πΏ **Sapling** β Young, growing
- π³ **Mature** β Fully grown
- π **Overmature** β Past peak, aging
""")
# ββββββββββββββββββββββββββββββββββββββββββββββ
# MODEL LOADING (cached so it only runs once)
# ββββββββββββββββββββββββββββββββββββββββββββββ
@st.cache_resource
def get_models():
"""Load all 4 models once and cache them in memory."""
with st.spinner("Loading AI models... (this only happens once)"):
models = load_all_models()
return models
try:
models = get_models()
st.sidebar.success("β
All models loaded successfully")
except Exception as e:
st.error(f"β Failed to load models: {e}")
st.info("Make sure your model files are in the `models/` folder.")
st.stop()
# ββββββββββββββββββββββββββββββββββββββββββββββ
# IMAGE UPLOAD
# ββββββββββββββββββββββββββββββββββββββββββββββ
st.divider()
uploaded_file = st.file_uploader(
"π€ Upload a tree image (JPG, PNG, JPEG)",
type=["jpg", "jpeg", "png"],
help="For best results, use a clear photo of a single tree."
)
if uploaded_file is None:
# Show a friendly placeholder when no image is uploaded
st.info("π Upload an image above to start the classification pipeline.")
st.markdown("""
### π§ What happens after you upload:
| Step | What the AI does |
|------|-----------------|
| Step 1 | Checks if the image contains a tree |
| Step 2 | Identifies if it's a Mango or White Gum tree |
| Step 3 | Predicts the tree's growth stage |
| All steps | Shows a Grad-CAM heatmap highlighting AI focus areas |
""")
st.stop()
# ββββββββββββββββββββββββββββββββββββββββββββββ
# IMAGE DISPLAY
# ββββββββββββββββββββββββββββββββββββββββββββββ
image = Image.open(uploaded_file).convert("RGB")
col_img, col_info = st.columns([1, 1])
with col_img:
st.subheader("π· Uploaded Image")
st.image(image, caption="Your uploaded image", use_container_width=True)
with col_info:
st.subheader("π¬ Analysis Pipeline")
st.markdown("""
The image will be processed through the following stages:
```
Image
β
βΌ
[1] Tree vs Non-Tree
β (if tree detected)
βΌ
[2] Species: Mango or White Gum?
β
βΌ
[3] Growth Stage Classification
```
Each step outputs a **confidence score** and a **Grad-CAM heatmap**.
""")
# ββββββββββββββββββββββββββββββββββββββββββββββ
# PIPELINE EXECUTION
# ββββββββββββββββββββββββββββββββββββββββββββββ
st.divider()
st.header("π€ AI Classification Results")
with st.spinner("π Running analysis..."):
# ββ PHASE 1: Tree vs Non-Tree ββββββββββββββββββ
st.subheader("Phase 1 β Tree Detection")
try:
tree_label, tree_conf, tree_tensor = predict_tree(image, models["tree_vs_nontree"])
tree_heatmap = generate_gradcam(image, models["tree_vs_nontree"], tree_tensor)
except Exception as e:
st.error(f"Error in tree detection: {e}")
st.stop()
col1, col2 = st.columns(2)
with col1:
st.image(image, caption="Original Image", use_container_width=True)
with col2:
st.image(tree_heatmap, caption="Grad-CAM: Where the model looked", use_container_width=True)
if tree_label == "Non-Tree":
st.markdown(f"""
<div class="result-box">
β <b>Result:</b> Non-Tree detected ({tree_conf:.1%} confidence)<br>
The pipeline has stopped. Please upload an image containing a tree.
</div>
""", unsafe_allow_html=True)
st.stop()
else:
st.markdown(f"""
<div class="result-box">
β
<b>Result:</b> Tree detected ({tree_conf:.1%} confidence) β Proceeding to species detection.
</div>
""", unsafe_allow_html=True)
# ββ PHASE 2: Species Detection ββββββββββββββββββ
st.divider()
st.subheader("Phase 2 β Species Detection")
st.markdown("""
<div class="warning-box">
β οΈ <b>Note:</b> This system is trained only on <b>Mango</b> and <b>White Gum (Eucalyptus)</b> trees.
Please upload images of these species for accurate results.
</div>
""", unsafe_allow_html=True)
try:
species_label, species_conf, species_tensor = predict_species(image, models["species"])
species_heatmap = generate_gradcam(image, models["species"], species_tensor)
except Exception as e:
st.error(f"Error in species detection: {e}")
st.stop()
col3, col4 = st.columns(2)
with col3:
st.image(image, caption="Original Image", use_container_width=True)
with col4:
st.image(species_heatmap, caption="Grad-CAM: Species focus area", use_container_width=True)
species_icon = "π₯" if species_label == "Mango" else "πΏ"
st.markdown(f"""
<div class="result-box">
{species_icon} <b>Detected Species:</b> {species_label} ({species_conf:.1%} confidence)
</div>
""", unsafe_allow_html=True)
# ββ PHASE 3: Growth Stage Classification ββββββββ
st.divider()
st.subheader("Phase 3 β Growth Stage Classification")
# Route to the correct stage model based on species
if species_label == "Mango":
stage_model = models["mango_stage"]
model_name = "Mango Stage Model"
else:
stage_model = models["gum_stage"]
model_name = "White Gum Stage Model"
st.info(f"π Routing to: **{model_name}**")
try:
stage_label, stage_conf, stage_tensor = predict_stage(image, stage_model, species_label)
stage_heatmap = generate_gradcam(image, stage_model, stage_tensor)
except Exception as e:
st.error(f"Error in stage classification: {e}")
st.stop()
col5, col6 = st.columns(2)
with col5:
st.image(image, caption="Original Image", use_container_width=True)
with col6:
st.image(stage_heatmap, caption="Grad-CAM: Stage focus area", use_container_width=True)
stage_icons = {"Seedling": "π±", "Sapling": "πΏ", "Mature": "π³", "Overmature": "π"}
stage_icon = stage_icons.get(stage_label, "π²")
st.markdown(f"""
<div class="result-box">
{stage_icon} <b>Growth Stage:</b> <span class="stage-badge">{stage_label}</span>
({stage_conf:.1%} confidence)
</div>
""", unsafe_allow_html=True)
# ββ FINAL SUMMARY ββββββββββββββββββββββββββββββββ
st.divider()
st.subheader("π Summary")
summary_col1, summary_col2, summary_col3 = st.columns(3)
with summary_col1:
st.metric("π Detection", "Tree", f"{tree_conf:.1%}")
with summary_col2:
st.metric(f"{species_icon} Species", species_label, f"{species_conf:.1%}")
with summary_col3:
st.metric(f"{stage_icon} Growth Stage", stage_label, f"{stage_conf:.1%}")
|