BlueSR commited on
Commit
832c7c0
·
verified ·
1 Parent(s): 046ee85

Update app.py

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