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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
OralGuard AI - Prediction Utilities for Hugging Face Spaces
|
| 3 |
+
Handles image preprocessing, prediction, and ensemble logic
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
from PIL import Image
|
| 10 |
+
import numpy as np
|
| 11 |
+
import time
|
| 12 |
+
import streamlit as st
|
| 13 |
+
|
| 14 |
+
class OralGuardPredictor:
|
| 15 |
+
"""
|
| 16 |
+
Handles predictions for OralGuard AI models with on-demand loading
|
| 17 |
+
"""
|
| 18 |
+
def __init__(self, model_loader, img_size=224):
|
| 19 |
+
self.model_loader = model_loader
|
| 20 |
+
self.img_size = img_size
|
| 21 |
+
self.device = model_loader.device
|
| 22 |
+
self.class_names = ['Normal', 'OSCC']
|
| 23 |
+
|
| 24 |
+
# Define transforms
|
| 25 |
+
self.transform = transforms.Compose([
|
| 26 |
+
transforms.Resize((img_size, img_size)),
|
| 27 |
+
transforms.ToTensor(),
|
| 28 |
+
transforms.Normalize(
|
| 29 |
+
mean=[0.485, 0.456, 0.406],
|
| 30 |
+
std=[0.229, 0.224, 0.225]
|
| 31 |
+
)
|
| 32 |
+
])
|
| 33 |
+
|
| 34 |
+
def preprocess_image(self, image):
|
| 35 |
+
"""
|
| 36 |
+
Preprocess a PIL Image for model input
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
image: PIL Image
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
Preprocessed tensor
|
| 43 |
+
"""
|
| 44 |
+
# Convert to RGB if necessary
|
| 45 |
+
if image.mode != 'RGB':
|
| 46 |
+
image = image.convert('RGB')
|
| 47 |
+
|
| 48 |
+
# Apply transforms
|
| 49 |
+
img_tensor = self.transform(image)
|
| 50 |
+
|
| 51 |
+
# Add batch dimension
|
| 52 |
+
img_tensor = img_tensor.unsqueeze(0)
|
| 53 |
+
|
| 54 |
+
return img_tensor.to(self.device)
|
| 55 |
+
|
| 56 |
+
def predict_single_model(self, image, model_type, magnification):
|
| 57 |
+
"""
|
| 58 |
+
Get prediction from a single model (loads on-demand)
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
image: PIL Image
|
| 62 |
+
model_type: 'efficientnet', 'vgg16', or 'vit'
|
| 63 |
+
magnification: '100x' or '400x'
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
Dictionary with prediction results
|
| 67 |
+
"""
|
| 68 |
+
start_time = time.time()
|
| 69 |
+
|
| 70 |
+
# Load model (downloads if needed)
|
| 71 |
+
model = self.model_loader.load_model(model_type, magnification)
|
| 72 |
+
|
| 73 |
+
# Preprocess image
|
| 74 |
+
img_tensor = self.preprocess_image(image)
|
| 75 |
+
|
| 76 |
+
# Make prediction
|
| 77 |
+
with torch.no_grad():
|
| 78 |
+
outputs = model(img_tensor)
|
| 79 |
+
probabilities = F.softmax(outputs, dim=1)
|
| 80 |
+
confidence, predicted = torch.max(probabilities, 1)
|
| 81 |
+
|
| 82 |
+
inference_time = time.time() - start_time
|
| 83 |
+
|
| 84 |
+
# Convert to numpy
|
| 85 |
+
probs = probabilities.cpu().numpy()[0]
|
| 86 |
+
pred_class = predicted.cpu().item()
|
| 87 |
+
conf_score = confidence.cpu().item()
|
| 88 |
+
|
| 89 |
+
return {
|
| 90 |
+
'prediction': self.class_names[pred_class],
|
| 91 |
+
'confidence': float(conf_score),
|
| 92 |
+
'probabilities': {
|
| 93 |
+
'Normal': float(probs[0]),
|
| 94 |
+
'OSCC': float(probs[1])
|
| 95 |
+
},
|
| 96 |
+
'inference_time': inference_time,
|
| 97 |
+
'model': f"{model_type}_{magnification}"
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
def predict_ensemble(self, image, magnification, weights=None):
|
| 101 |
+
"""
|
| 102 |
+
Get ensemble prediction from all three models
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
image: PIL Image
|
| 106 |
+
magnification: '100x' or '400x'
|
| 107 |
+
weights: Optional weights for models [efficientnet, vgg16, vit]
|
| 108 |
+
|
| 109 |
+
Returns:
|
| 110 |
+
Dictionary with ensemble prediction results
|
| 111 |
+
"""
|
| 112 |
+
start_time = time.time()
|
| 113 |
+
|
| 114 |
+
# Default equal weights
|
| 115 |
+
if weights is None:
|
| 116 |
+
weights = [1/3, 1/3, 1/3]
|
| 117 |
+
|
| 118 |
+
# Get predictions from all models
|
| 119 |
+
model_types = ['efficientnet', 'vgg16', 'vit']
|
| 120 |
+
all_probs = []
|
| 121 |
+
individual_results = {}
|
| 122 |
+
|
| 123 |
+
progress_bar = st.progress(0)
|
| 124 |
+
status_text = st.empty()
|
| 125 |
+
|
| 126 |
+
for idx, model_type in enumerate(model_types):
|
| 127 |
+
status_text.text(f"Loading and running {model_type}...")
|
| 128 |
+
|
| 129 |
+
result = self.predict_single_model(image, model_type, magnification)
|
| 130 |
+
all_probs.append([
|
| 131 |
+
result['probabilities']['Normal'],
|
| 132 |
+
result['probabilities']['OSCC']
|
| 133 |
+
])
|
| 134 |
+
individual_results[model_type] = result
|
| 135 |
+
|
| 136 |
+
progress_bar.progress((idx + 1) / len(model_types))
|
| 137 |
+
|
| 138 |
+
progress_bar.empty()
|
| 139 |
+
status_text.empty()
|
| 140 |
+
|
| 141 |
+
# Weighted average of probabilities
|
| 142 |
+
all_probs = np.array(all_probs)
|
| 143 |
+
weights = np.array(weights).reshape(-1, 1)
|
| 144 |
+
ensemble_probs = (all_probs * weights).sum(axis=0)
|
| 145 |
+
|
| 146 |
+
# Get prediction
|
| 147 |
+
pred_class = np.argmax(ensemble_probs)
|
| 148 |
+
confidence = float(ensemble_probs[pred_class])
|
| 149 |
+
|
| 150 |
+
inference_time = time.time() - start_time
|
| 151 |
+
|
| 152 |
+
return {
|
| 153 |
+
'prediction': self.class_names[pred_class],
|
| 154 |
+
'confidence': confidence,
|
| 155 |
+
'probabilities': {
|
| 156 |
+
'Normal': float(ensemble_probs[0]),
|
| 157 |
+
'OSCC': float(ensemble_probs[1])
|
| 158 |
+
},
|
| 159 |
+
'inference_time': inference_time,
|
| 160 |
+
'model': f'ensemble_{magnification}',
|
| 161 |
+
'individual_results': individual_results,
|
| 162 |
+
'ensemble_weights': {
|
| 163 |
+
'efficientnet': float(weights[0][0]),
|
| 164 |
+
'vgg16': float(weights[1][0]),
|
| 165 |
+
'vit': float(weights[2][0])
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
def predict_batch(self, images, model_type, magnification):
|
| 170 |
+
"""
|
| 171 |
+
Predict on a batch of images
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
images: List of PIL Images
|
| 175 |
+
model_type: 'efficientnet', 'vgg16', 'vit', or 'ensemble'
|
| 176 |
+
magnification: '100x' or '400x'
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
List of prediction results
|
| 180 |
+
"""
|
| 181 |
+
results = []
|
| 182 |
+
|
| 183 |
+
progress_bar = st.progress(0)
|
| 184 |
+
status_text = st.empty()
|
| 185 |
+
|
| 186 |
+
for idx, image in enumerate(images):
|
| 187 |
+
try:
|
| 188 |
+
status_text.text(f"Processing image {idx+1}/{len(images)}...")
|
| 189 |
+
|
| 190 |
+
if model_type == 'ensemble':
|
| 191 |
+
result = self.predict_ensemble(image, magnification)
|
| 192 |
+
else:
|
| 193 |
+
result = self.predict_single_model(image, model_type, magnification)
|
| 194 |
+
|
| 195 |
+
result['image_index'] = idx
|
| 196 |
+
result['status'] = 'success'
|
| 197 |
+
results.append(result)
|
| 198 |
+
|
| 199 |
+
except Exception as e:
|
| 200 |
+
results.append({
|
| 201 |
+
'image_index': idx,
|
| 202 |
+
'status': 'error',
|
| 203 |
+
'error': str(e)
|
| 204 |
+
})
|
| 205 |
+
|
| 206 |
+
progress_bar.progress((idx + 1) / len(images))
|
| 207 |
+
|
| 208 |
+
progress_bar.empty()
|
| 209 |
+
status_text.empty()
|
| 210 |
+
|
| 211 |
+
return results
|
| 212 |
+
|
| 213 |
+
def get_risk_level(self, prediction, confidence):
|
| 214 |
+
"""
|
| 215 |
+
Determine risk level based on prediction and confidence
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
prediction: 'Normal' or 'OSCC'
|
| 219 |
+
confidence: confidence score (0-1)
|
| 220 |
+
|
| 221 |
+
Returns:
|
| 222 |
+
Risk level and color
|
| 223 |
+
"""
|
| 224 |
+
if prediction == 'Normal':
|
| 225 |
+
if confidence >= 0.9:
|
| 226 |
+
return 'Low Risk', 'green'
|
| 227 |
+
elif confidence >= 0.7:
|
| 228 |
+
return 'Low-Medium Risk', 'lightgreen'
|
| 229 |
+
else:
|
| 230 |
+
return 'Uncertain', 'orange'
|
| 231 |
+
else: # OSCC
|
| 232 |
+
if confidence >= 0.9:
|
| 233 |
+
return 'High Risk', 'red'
|
| 234 |
+
elif confidence >= 0.7:
|
| 235 |
+
return 'Medium-High Risk', 'orange'
|
| 236 |
+
else:
|
| 237 |
+
return 'Uncertain', 'orange'
|
| 238 |
+
|
| 239 |
+
def format_result_for_display(self, result):
|
| 240 |
+
"""
|
| 241 |
+
Format prediction result for display
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
result: Prediction result dictionary
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
Formatted dictionary
|
| 248 |
+
"""
|
| 249 |
+
risk_level, risk_color = self.get_risk_level(
|
| 250 |
+
result['prediction'],
|
| 251 |
+
result['confidence']
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
formatted = {
|
| 255 |
+
'Prediction': result['prediction'],
|
| 256 |
+
'Confidence': f"{result['confidence']*100:.2f}%",
|
| 257 |
+
'Risk Level': risk_level,
|
| 258 |
+
'Risk Color': risk_color,
|
| 259 |
+
'Probability (Normal)': f"{result['probabilities']['Normal']*100:.2f}%",
|
| 260 |
+
'Probability (OSCC)': f"{result['probabilities']['OSCC']*100:.2f}%",
|
| 261 |
+
'Inference Time': f"{result['inference_time']:.3f}s",
|
| 262 |
+
'Model Used': result['model']
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
# Add individual results for ensemble
|
| 266 |
+
if 'individual_results' in result:
|
| 267 |
+
formatted['Individual Models'] = {}
|
| 268 |
+
for model, res in result['individual_results'].items():
|
| 269 |
+
formatted['Individual Models'][model] = {
|
| 270 |
+
'prediction': res['prediction'],
|
| 271 |
+
'confidence': f"{res['confidence']*100:.2f}%"
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
return formatted
|