Spaces:
Sleeping
Sleeping
File size: 11,183 Bytes
832c7c0 d48c40a 832c7c0 66609d0 ce2ce33 832c7c0 4014e2e 832c7c0 d48c40a 832c7c0 d48c40a 832c7c0 ce2ce33 832c7c0 ce2ce33 d48c40a ce2ce33 d48c40a ce2ce33 d48c40a ce2ce33 d48c40a ce2ce33 d48c40a ce2ce33 d48c40a ce2ce33 832c7c0 d48c40a 832c7c0 d48c40a ce2ce33 d48c40a ce2ce33 d48c40a ce2ce33 d48c40a ce2ce33 d48c40a 832c7c0 d48c40a 832c7c0 ce2ce33 832c7c0 d48c40a ce2ce33 832c7c0 d48c40a 832c7c0 d48c40a 832c7c0 d48c40a 832c7c0 d48c40a 832c7c0 d48c40a 832c7c0 ce2ce33 d48c40a ce2ce33 d48c40a ce2ce33 d48c40a 832c7c0 ce2ce33 d48c40a 832c7c0 ce2ce33 d48c40a ce2ce33 832c7c0 ce2ce33 832c7c0 ce2ce33 832c7c0 d48c40a 832c7c0 d48c40a 832c7c0 66609d0 ce2ce33 | 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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | import torch
import torch.nn as nn
from torchvision import transforms
from torchvision.models import efficientnet_b0, mobilenet_v2, resnet18
import gradio as gr
import numpy as np
from PIL import Image
import joblib
import os
# Constants
NUM_CLASSES = 4
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
CLASS_NAMES = ['Cracked_road', 'Flooded_muddy', 'Good_condition', 'Potholes']
# Model paths with fallbacks for different deployment environments
MODEL_PATHS = {
"efficientnet": [
"best_efficientnet_model.pth",
"models/best_efficientnet_model.pth",
"assign2_Latest/models/best_efficientnet_model.pth"
],
"mobilenet": [
"best_mobilenetv2_model.pth",
"models/best_mobilenetv2_model.pth",
"assign2_Latest/models/best_mobilenetv2_model.pth"
],
"resnet": [
"best_resnet18_model.pth",
"models/best_resnet18_model.pth",
"assign2_Latest/models/best_resnet18_model.pth"
],
"rf": [
"rf_model.pkl",
"models/rf_model.pkl",
"assign2_Latest/models/rf_model.pkl"
]
}
# Build EfficientNet model
def build_efficientnet(num_classes=NUM_CLASSES):
"""Build EfficientNet-B0 based model"""
model = efficientnet_b0(weights=None)
# Replace classifier
in_features = model.classifier[1].in_features
model.classifier = nn.Sequential(
nn.Linear(in_features, 256),
nn.BatchNorm1d(256),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(256, num_classes)
)
return model
# Build MobileNetV2 model
def build_mobilenet(num_classes=NUM_CLASSES):
"""Build MobileNetV2 model"""
model = mobilenet_v2(weights=None)
# Replace classifier
last_channel = model.last_channel
model.classifier = nn.Sequential(
nn.Dropout(p=0.2),
nn.Linear(last_channel, 512),
nn.BatchNorm1d(512),
nn.LeakyReLU(0.2),
nn.Dropout(p=0.2),
nn.Linear(512, 256),
nn.BatchNorm1d(256),
nn.LeakyReLU(0.2),
nn.Dropout(p=0.1),
nn.Linear(256, num_classes)
)
return model
# Build ResNet18 model
def build_resnet(num_classes=NUM_CLASSES):
"""Build ResNet18 model"""
model = resnet18(weights=None)
# Replace classifier
in_features = model.fc.in_features
model.fc = nn.Sequential(
nn.Linear(in_features, 256),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(256, num_classes)
)
return model
# Load model with fallback paths
def load_model(model_type):
"""Load trained model with fallback paths"""
if model_type == "efficientnet":
model = build_efficientnet()
elif model_type == "mobilenet":
model = build_mobilenet()
elif model_type == "resnet":
model = build_resnet()
elif model_type == "rf":
# For Random Forest, handled differently below
return load_rf_model()
else:
raise ValueError(f"Unknown model type: {model_type}")
# Try loading from various possible paths
paths = MODEL_PATHS[model_type]
model_loaded = False
for path in paths:
if os.path.exists(path):
try:
model.load_state_dict(torch.load(path, map_location=DEVICE))
model_loaded = True
print(f"{model_type} model loaded from {path}")
break
except Exception as e:
print(f"Failed to load {model_type} from {path}: {e}")
continue
if not model_loaded:
raise FileNotFoundError(f"Could not find or load {model_type} model file")
model.to(DEVICE)
model.eval()
return model
# Load Random Forest model
def load_rf_model():
"""Load Random Forest model"""
paths = MODEL_PATHS["rf"]
for path in paths:
if os.path.exists(path):
try:
model = joblib.load(path)
print(f"Random Forest model loaded from {path}")
return model
except Exception as e:
print(f"Failed to load RF model from {path}: {e}")
continue
raise FileNotFoundError("Could not find or load Random Forest model file")
# Extract features for Random Forest
def extract_features_single(model, image_tensor):
"""Extract features from a single image for Random Forest"""
model.eval()
# Create feature extractor (using EfficientNet)
feature_extractor = nn.Sequential(
model.features,
model.avgpool,
nn.Flatten()
).to(DEVICE)
with torch.no_grad():
features = feature_extractor(image_tensor).cpu().numpy()
return features
# Preprocess image for neural networks
def preprocess_image(image):
"""Preprocess image for model prediction"""
preprocess = transforms.Compose([
transforms.Resize((224, 224)),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
return preprocess(image).unsqueeze(0)
# Prediction function
def predict(img, model_choice, models):
"""Make prediction using selected model"""
if img is None:
return "No image provided", "Please upload an image"
try:
# Convert to RGB if needed
if img.mode != "RGB":
img = img.convert("RGB")
# Preprocess image
img_tensor = preprocess_image(img)
img_tensor = img_tensor.to(DEVICE)
if model_choice == "EfficientNet":
model = models["efficientnet"]
# Make prediction
with torch.no_grad():
outputs = model(img_tensor)
probabilities = torch.nn.functional.softmax(outputs, dim=1)[0]
predicted_class = torch.argmax(probabilities).item()
# Format confidence scores
confidence_scores = {CLASS_NAMES[i]: f"{probabilities[i].item()*100:.2f}%"
for i in range(len(CLASS_NAMES))}
confidence_text = "\n".join([f"{cls}: {score}" for cls, score in confidence_scores.items()])
return CLASS_NAMES[predicted_class], confidence_text
elif model_choice == "MobileNetV2":
model = models["mobilenet"]
# Make prediction
with torch.no_grad():
outputs = model(img_tensor)
probabilities = torch.nn.functional.softmax(outputs, dim=1)[0]
predicted_class = torch.argmax(probabilities).item()
# Format confidence scores
confidence_scores = {CLASS_NAMES[i]: f"{probabilities[i].item()*100:.2f}%"
for i in range(len(CLASS_NAMES))}
confidence_text = "\n".join([f"{cls}: {score}" for cls, score in confidence_scores.items()])
return CLASS_NAMES[predicted_class], confidence_text
elif model_choice == "ResNet18":
model = models["resnet"]
# Make prediction
with torch.no_grad():
outputs = model(img_tensor)
probabilities = torch.nn.functional.softmax(outputs, dim=1)[0]
predicted_class = torch.argmax(probabilities).item()
# Format confidence scores
confidence_scores = {CLASS_NAMES[i]: f"{probabilities[i].item()*100:.2f}%"
for i in range(len(CLASS_NAMES))}
confidence_text = "\n".join([f"{cls}: {score}" for cls, score in confidence_scores.items()])
return CLASS_NAMES[predicted_class], confidence_text
elif model_choice == "Random Forest":
# Extract features using EfficientNet
features = extract_features_single(models["efficientnet"], img_tensor)
# Make prediction with Random Forest
rf_model = models["rf"]
predicted_class = rf_model.predict(features)[0]
probabilities = rf_model.predict_proba(features)[0]
# Format confidence scores
confidence_scores = {CLASS_NAMES[i]: f"{probabilities[i]*100:.2f}%"
for i in range(len(CLASS_NAMES))}
confidence_text = "\n".join([f"{cls}: {score}" for cls, score in confidence_scores.items()])
return CLASS_NAMES[predicted_class], confidence_text
else:
return "Invalid model selection", "Please select a valid model"
except Exception as e:
return f"Error: {str(e)}", "An error occurred during prediction."
# Initialize models
print("Loading models...")
models = {}
try:
models["efficientnet"] = load_model("efficientnet")
models["mobilenet"] = load_model("mobilenet")
models["resnet"] = load_model("resnet")
models["rf"] = load_model("rf")
print("All models loaded successfully!")
except Exception as e:
print(f"Error loading models: {e}")
# In case of error, models will be empty or partial
# Create Gradio interface
with gr.Blocks(title="Road Surface Classification") as demo:
gr.Markdown("# Road Surface Classification")
gr.Markdown("Upload an image of a road surface to classify its condition using various models.")
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Upload Road Image")
model_selector = gr.Radio(
choices=["EfficientNet", "MobileNetV2", "ResNet18", "Random Forest"],
value="EfficientNet",
label="Select Model"
)
classify_btn = gr.Button("Classify", variant="primary")
with gr.Column():
label_output = gr.Textbox(label="Predicted Class", interactive=False)
confidence_output = gr.Textbox(
label="Confidence Scores",
lines=5,
interactive=False
)
# Event handler
classify_btn.click(
fn=lambda img, model_choice: predict(img, model_choice, models),
inputs=[image_input, model_selector],
outputs=[label_output, confidence_output]
)
# Add information about classes and models
with gr.Row():
with gr.Column():
gr.Markdown("### Classes")
gr.Markdown("- **Cracked_road**: Roads with visible cracks")
gr.Markdown("- **Flooded_muddy**: Roads affected by flooding or mud")
gr.Markdown("- **Good_condition**: Roads in good condition")
gr.Markdown("- **Potholes**: Roads with potholes")
with gr.Column():
gr.Markdown("### Models")
gr.Markdown("- **EfficientNet**: Efficient deep learning model")
gr.Markdown("- **MobileNetV2**: Lightweight mobile-friendly model")
gr.Markdown("- **ResNet18**: Residual network architecture")
gr.Markdown("- **Random Forest**: Traditional ML using CNN features")
# Launch the app
if __name__ == "__main__":
demo.launch() |