Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,133 +1,137 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
-
from torchvision import transforms
|
| 4 |
-
from torchvision.models import efficientnet_b0
|
| 5 |
-
import gradio as gr
|
| 6 |
-
import numpy as np
|
| 7 |
-
import pickle
|
| 8 |
-
import os
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
model
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
nn.
|
| 26 |
-
nn.
|
| 27 |
-
nn.
|
| 28 |
-
nn.
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
model.
|
| 34 |
-
model.
|
| 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 |
-
with gr.Column():
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
demo.launch()
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from torchvision import transforms
|
| 4 |
+
from torchvision.models import efficientnet_b0
|
| 5 |
+
import gradio as gr
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pickle
|
| 8 |
+
import os
|
| 9 |
+
import joblib
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
# Constants
|
| 13 |
+
NUM_CLASSES = 4
|
| 14 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 15 |
+
CLASS_NAMES = ["Good_condition", "Potholes", "Cracked_road", "Flooded_muddy"]
|
| 16 |
+
|
| 17 |
+
# Load the CNN model
|
| 18 |
+
def load_cnn_model():
|
| 19 |
+
# Build model architecture (same as in train_cnn.py)
|
| 20 |
+
model = efficientnet_b0(weights=None)
|
| 21 |
+
|
| 22 |
+
# Replace classifier
|
| 23 |
+
in_features = model.classifier[1].in_features
|
| 24 |
+
model.classifier = nn.Sequential(
|
| 25 |
+
nn.Linear(in_features, 256),
|
| 26 |
+
nn.BatchNorm1d(256),
|
| 27 |
+
nn.ReLU(),
|
| 28 |
+
nn.Dropout(p=0.2),
|
| 29 |
+
nn.Linear(256, NUM_CLASSES)
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Load the saved weights
|
| 33 |
+
model.load_state_dict(torch.load("best_cnn_model.pth", map_location=DEVICE))
|
| 34 |
+
model.to(DEVICE)
|
| 35 |
+
model.eval()
|
| 36 |
+
return model
|
| 37 |
+
|
| 38 |
+
# Load the Random Forest model
|
| 39 |
+
def load_rf_model():
|
| 40 |
+
try:
|
| 41 |
+
return joblib.load("rf_model.pkl")
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"Error loading RF model: {e}")
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
# Preprocess image for CNN
|
| 47 |
+
def preprocess_image_cnn(image):
|
| 48 |
+
preprocess = transforms.Compose([
|
| 49 |
+
transforms.Resize((224, 224)),
|
| 50 |
+
transforms.ToTensor(),
|
| 51 |
+
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
|
| 52 |
+
])
|
| 53 |
+
return preprocess(image).unsqueeze(0)
|
| 54 |
+
|
| 55 |
+
# Preprocess image for RF
|
| 56 |
+
def preprocess_image_rf(image):
|
| 57 |
+
# Convert to numpy, resize, and flatten
|
| 58 |
+
image = image.resize((64, 64))
|
| 59 |
+
image_array = np.array(image)
|
| 60 |
+
# If grayscale, expand to RGB
|
| 61 |
+
if len(image_array.shape) == 2:
|
| 62 |
+
image_array = np.stack([image_array] * 3, axis=2)
|
| 63 |
+
# Flatten the image
|
| 64 |
+
return image_array.reshape(1, -1)
|
| 65 |
+
|
| 66 |
+
# Prediction function
|
| 67 |
+
def predict(img, model_choice, cnn_model, rf_model):
|
| 68 |
+
if img is None:
|
| 69 |
+
return "No image provided", "Please upload an image"
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
if model_choice == "CNN":
|
| 73 |
+
# Preprocess for CNN
|
| 74 |
+
img_tensor = preprocess_image_cnn(img)
|
| 75 |
+
img_tensor = img_tensor.to(DEVICE)
|
| 76 |
+
|
| 77 |
+
# Get prediction
|
| 78 |
+
with torch.no_grad():
|
| 79 |
+
outputs = cnn_model(img_tensor)
|
| 80 |
+
probabilities = torch.nn.functional.softmax(outputs, dim=1)[0]
|
| 81 |
+
predicted_class = torch.argmax(probabilities).item()
|
| 82 |
+
|
| 83 |
+
# Format confidence scores
|
| 84 |
+
confidence_scores = {CLASS_NAMES[i]: f"{probabilities[i].item()*100:.2f}%"
|
| 85 |
+
for i in range(len(CLASS_NAMES))}
|
| 86 |
+
confidence_text = "\n".join([f"{cls}: {score}" for cls, score in confidence_scores.items()])
|
| 87 |
+
|
| 88 |
+
return CLASS_NAMES[predicted_class], confidence_text
|
| 89 |
+
|
| 90 |
+
else: # Random Forest
|
| 91 |
+
# Preprocess for RF
|
| 92 |
+
img_features = preprocess_image_rf(img)
|
| 93 |
+
|
| 94 |
+
# Get prediction
|
| 95 |
+
predicted_class = rf_model.predict(img_features)[0]
|
| 96 |
+
probabilities = rf_model.predict_proba(img_features)[0]
|
| 97 |
+
|
| 98 |
+
# Format confidence scores
|
| 99 |
+
confidence_scores = {CLASS_NAMES[i]: f"{probabilities[i]*100:.2f}%"
|
| 100 |
+
for i in range(len(CLASS_NAMES))}
|
| 101 |
+
confidence_text = "\n".join([f"{cls}: {score}" for cls, score in confidence_scores.items()])
|
| 102 |
+
|
| 103 |
+
return CLASS_NAMES[predicted_class], confidence_text
|
| 104 |
+
|
| 105 |
+
except Exception as e:
|
| 106 |
+
return f"Error: {str(e)}", "An error occurred during prediction."
|
| 107 |
+
|
| 108 |
+
# Load models
|
| 109 |
+
cnn_model = load_cnn_model()
|
| 110 |
+
rf_model = load_rf_model()
|
| 111 |
+
|
| 112 |
+
# Create Gradio interface
|
| 113 |
+
with gr.Blocks() as demo:
|
| 114 |
+
gr.Markdown("## Road Surface Classification")
|
| 115 |
+
|
| 116 |
+
with gr.Row():
|
| 117 |
+
with gr.Column():
|
| 118 |
+
image_input = gr.Image(type="pil", label="Upload Road Image")
|
| 119 |
+
model_selector = gr.Radio(choices=["CNN", "Random Forest"], value="CNN", label="Select Model")
|
| 120 |
+
classify_btn = gr.Button("Classify")
|
| 121 |
+
with gr.Column():
|
| 122 |
+
label_output = gr.Textbox(label="Predicted Class")
|
| 123 |
+
confidence_output = gr.Textbox(label="Confidence Scores", lines=5)
|
| 124 |
+
|
| 125 |
+
classify_btn.click(
|
| 126 |
+
fn=lambda img, model_choice: predict(img, model_choice, cnn_model, rf_model),
|
| 127 |
+
inputs=[image_input, model_selector],
|
| 128 |
+
outputs=[label_output, confidence_output]
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
gr.Markdown("### How to use")
|
| 132 |
+
gr.Markdown("1. Upload a road image")
|
| 133 |
+
gr.Markdown("2. Select either CNN or Random Forest model")
|
| 134 |
+
gr.Markdown("3. Click 'Classify' to get the prediction")
|
| 135 |
+
|
| 136 |
+
# Launch the app
|
| 137 |
demo.launch()
|