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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import cv2
|
| 4 |
+
from joblib import load
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# --- Configuration & Model Loading ---
|
| 8 |
+
MODEL_PATH = "orb_bow_svm.joblib"
|
| 9 |
+
|
| 10 |
+
# --- Model Constants (should match your training environment) ---
|
| 11 |
+
IMG_SIZE = (200, 200)
|
| 12 |
+
VOCAB_SIZE = 300
|
| 13 |
+
orb = cv2.ORB_create(nfeatures=500)
|
| 14 |
+
|
| 15 |
+
# Default classes
|
| 16 |
+
DEFAULT_CLASSES = [
|
| 17 |
+
"Non Demented",
|
| 18 |
+
"Very mild Dementia",
|
| 19 |
+
"Mild Dementia",
|
| 20 |
+
"Moderate Dementia"
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
# --- FINAL CORRECTED & EXPANDED EXAMPLE FILES (MUST MATCH UPLOADED FILES IN ROOT) ---
|
| 24 |
+
EXAMPLE_IMAGES = [
|
| 25 |
+
"mild_9.jpg",
|
| 26 |
+
"moderate_7.jpg",
|
| 27 |
+
"non_93.jpg",
|
| 28 |
+
"verymild_986.jpg",
|
| 29 |
+
"moderate_36.jpg",
|
| 30 |
+
"verymild_795.jpg",
|
| 31 |
+
"verymild_8.jpg"
|
| 32 |
+
]
|
| 33 |
+
# -----------------------------------------------------------------------------
|
| 34 |
+
|
| 35 |
+
# Attempt to load the model components
|
| 36 |
+
kmeans, scaler, svm = None, None, None
|
| 37 |
+
classes = DEFAULT_CLASSES
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
print(f"Attempting to load model from: {MODEL_PATH}")
|
| 41 |
+
model_data = load(MODEL_PATH)
|
| 42 |
+
kmeans = model_data["kmeans"]
|
| 43 |
+
scaler = model_data["scaler"]
|
| 44 |
+
svm = model_data["svm"]
|
| 45 |
+
classes = model_data["classes"]
|
| 46 |
+
print("Model loaded successfully!")
|
| 47 |
+
except FileNotFoundError:
|
| 48 |
+
print(f"ERROR: Model file '{MODEL_PATH}' not found.")
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"ERROR: An unexpected error occurred during model loading: {e}.")
|
| 51 |
+
|
| 52 |
+
# Define real/dummy functions based on successful load
|
| 53 |
+
if svm is None:
|
| 54 |
+
def encode(descriptors, kmeans_model): return np.zeros(VOCAB_SIZE)
|
| 55 |
+
def gradio_predict(input_img):
|
| 56 |
+
return "β οΈ Model not loaded. Cannot perform prediction.", {cls: 0.0 for cls in DEFAULT_CLASSES}
|
| 57 |
+
else:
|
| 58 |
+
def encode(descriptors, kmeans_model):
|
| 59 |
+
if descriptors is None or len(descriptors) == 0:
|
| 60 |
+
return np.zeros(VOCAB_SIZE)
|
| 61 |
+
words = kmeans_model.predict(descriptors)
|
| 62 |
+
hist, _ = np.histogram(words, bins=np.arange(VOCAB_SIZE + 1))
|
| 63 |
+
return hist
|
| 64 |
+
|
| 65 |
+
def gradio_predict(input_img):
|
| 66 |
+
# Preprocessing
|
| 67 |
+
img = cv2.cvtColor(input_img, cv2.COLOR_RGB2GRAY)
|
| 68 |
+
img = cv2.resize(img, IMG_SIZE)
|
| 69 |
+
|
| 70 |
+
# Feature Extraction
|
| 71 |
+
kps, des = orb.detectAndCompute(img, None)
|
| 72 |
+
feat = encode(des, kmeans).reshape(1, -1)
|
| 73 |
+
feat_scaled = scaler.transform(feat)
|
| 74 |
+
|
| 75 |
+
# Prediction
|
| 76 |
+
prediction_index = svm.predict(feat_scaled)[0]
|
| 77 |
+
probabilities = svm.predict_proba(feat_scaled)[0]
|
| 78 |
+
|
| 79 |
+
# Format output
|
| 80 |
+
predicted_class = classes[prediction_index]
|
| 81 |
+
confidence_score = probabilities[prediction_index] * 100
|
| 82 |
+
|
| 83 |
+
output_message = f"**Diagnosis: {predicted_class}**\n" \
|
| 84 |
+
f"Confidence: {confidence_score:.2f}%"
|
| 85 |
+
|
| 86 |
+
prob_dict = {cls: prob for cls, prob in zip(classes, probabilities)}
|
| 87 |
+
|
| 88 |
+
return output_message, prob_dict
|
| 89 |
+
|
| 90 |
+
# --- Gradio Interface Definition ---
|
| 91 |
+
|
| 92 |
+
colorful_theme = gr.Theme.from_hub("gradio/seafoam")
|
| 93 |
+
|
| 94 |
+
with gr.Blocks(theme=colorful_theme, title="DementiaScan-Predict π§ ") as demo:
|
| 95 |
+
|
| 96 |
+
# ------------------------------------------------
|
| 97 |
+
# INTRODUCTORY TEXT (UPDATED)
|
| 98 |
+
# ------------------------------------------------
|
| 99 |
+
gr.Markdown(
|
| 100 |
+
"""
|
| 101 |
+
# π§ DementiaScan-Predict: Rapid Stage Classification π
|
| 102 |
+
|
| 103 |
+
Welcome! This tool offers **rapid, preliminary classification of dementia stages** from MRI brain scans. Our core innovation is providing highly **efficient and accessible AI diagnostics**, perfect for deployment in resource-constrained environments.
|
| 104 |
+
|
| 105 |
+
---
|
| 106 |
+
### π How It Works:
|
| 107 |
+
1. **Upload an MRI Scan** (T1-weighted image).
|
| 108 |
+
2. **Click 'Classify Scan'** to trigger the analysis.
|
| 109 |
+
3. **Get Instant Results** for the predicted dementia stage and confidence.
|
| 110 |
+
|
| 111 |
+
---
|
| 112 |
+
"""
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
with gr.Row(variant="panel"):
|
| 116 |
+
# Input Column
|
| 117 |
+
with gr.Column(scale=1):
|
| 118 |
+
gr.Markdown("## π€ Input Image")
|
| 119 |
+
image_input = gr.Image(
|
| 120 |
+
type="numpy",
|
| 121 |
+
label="Upload MRI Brain Scan Image",
|
| 122 |
+
height=350,
|
| 123 |
+
width=350,
|
| 124 |
+
interactive=True
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# Action Button
|
| 128 |
+
submit_btn = gr.Button("β¨ Classify Scan β¨", variant="primary", size="lg")
|
| 129 |
+
gr.Markdown("---")
|
| 130 |
+
gr.Markdown(
|
| 131 |
+
"""
|
| 132 |
+
### π‘ Quick Test Examples:
|
| 133 |
+
Click on any image below to load and classify it instantly!
|
| 134 |
+
"""
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
gr.Examples(
|
| 138 |
+
examples=EXAMPLE_IMAGES,
|
| 139 |
+
inputs=image_input,
|
| 140 |
+
outputs=[gr.Textbox(), gr.Label()],
|
| 141 |
+
fn=gradio_predict,
|
| 142 |
+
cache_examples=True,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# Output Column
|
| 147 |
+
with gr.Column(scale=2):
|
| 148 |
+
gr.Markdown("## β
Prediction Results")
|
| 149 |
+
output_text = gr.Textbox(
|
| 150 |
+
label="Predicted Dementia Stage & Confidence",
|
| 151 |
+
value="Upload an image and click 'Classify Scan' to see the results.",
|
| 152 |
+
lines=3,
|
| 153 |
+
show_copy_button=True,
|
| 154 |
+
elem_id="prediction_output_box"
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
output_label = gr.Label(
|
| 158 |
+
label="Detailed Probability Distribution",
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# ------------------------------------------------
|
| 162 |
+
# METHODOLOGY TEXT (UPDATED)
|
| 163 |
+
# ------------------------------------------------
|
| 164 |
+
gr.Markdown(
|
| 165 |
+
"""
|
| 166 |
+
---
|
| 167 |
+
### π Methodology: ORB-BoVW-SVM
|
| 168 |
+
We employ a fast, classical Computer Vision pipeline for efficiency:
|
| 169 |
+
* **Feature Detection:** **ORB** detects key visual points on the brain scan.
|
| 170 |
+
* **Feature Encoding:** **Bag of Visual Words (BoVW)** converts these features into a compact, fixed-size histogram (vector).
|
| 171 |
+
* **Classification:** The resulting vector is classified using a **Support Vector Machine (SVM)**.
|
| 172 |
+
|
| 173 |
+
This approach ensures excellent **speed and low computational overhead** compared to standard deep learning models.
|
| 174 |
+
"""
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# Connect the button to the prediction function
|
| 178 |
+
submit_btn.click(
|
| 179 |
+
fn=gradio_predict,
|
| 180 |
+
inputs=[image_input],
|
| 181 |
+
outputs=[output_text, output_label]
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
# Launch the Gradio app
|
| 185 |
+
demo.launch(share=True)
|