Update app.py
Browse files
app.py
CHANGED
|
@@ -1,265 +1,155 @@
|
|
| 1 |
-
import io
|
| 2 |
-
import cv2
|
| 3 |
import gradio as gr
|
| 4 |
-
import matplotlib
|
| 5 |
-
matplotlib.use("Agg")
|
| 6 |
-
|
| 7 |
import matplotlib.pyplot as plt
|
| 8 |
-
import torch
|
| 9 |
import numpy as np
|
| 10 |
-
import sqlite3
|
| 11 |
-
import pandas as pd
|
| 12 |
-
import pytesseract
|
| 13 |
-
|
| 14 |
from PIL import Image
|
| 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 |
-
def
|
| 51 |
-
global
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
return BASE_AMT * 0.9
|
| 63 |
-
return BASE_AMT
|
| 64 |
-
|
| 65 |
-
def classify_plate_color(plate_img):
|
| 66 |
-
try:
|
| 67 |
-
img = np.array(plate_img)
|
| 68 |
-
img = cv2.GaussianBlur(img, (5,5), 0)
|
| 69 |
-
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
|
| 70 |
-
|
| 71 |
-
green_mask = cv2.inRange(hsv, (35, 40, 40), (85, 255, 255))
|
| 72 |
-
yellow_mask = cv2.inRange(hsv, (15, 50, 50), (35, 255, 255))
|
| 73 |
-
white_mask = cv2.inRange(hsv, (0, 0, 200), (180, 40, 255))
|
| 74 |
-
|
| 75 |
-
green = np.sum(green_mask)
|
| 76 |
-
yellow = np.sum(yellow_mask)
|
| 77 |
-
white = np.sum(white_mask)
|
| 78 |
-
|
| 79 |
-
if green > yellow and green > white:
|
| 80 |
-
return "EV"
|
| 81 |
-
elif yellow > green and yellow > white:
|
| 82 |
-
return "Commercial"
|
| 83 |
-
elif white > green and white > yellow:
|
| 84 |
-
return "Personal"
|
| 85 |
-
else:
|
| 86 |
-
return "Unknown"
|
| 87 |
-
|
| 88 |
-
except Exception as e:
|
| 89 |
-
return "Unknown"
|
| 90 |
-
|
| 91 |
-
def read_plate(plate_img):
|
| 92 |
-
try:
|
| 93 |
-
gray = cv2.cvtColor(np.array(plate_img), cv2.COLOR_RGB2GRAY)
|
| 94 |
-
gray = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY)[1]
|
| 95 |
-
|
| 96 |
-
text = pytesseract.image_to_string(
|
| 97 |
-
gray,
|
| 98 |
-
config="--psm 7 -c tessedit_char_whitelist=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
| 99 |
-
)
|
| 100 |
-
return text.strip() if text.strip() else "UNKNOWN"
|
| 101 |
-
except:
|
| 102 |
-
return "UNKNOWN"
|
| 103 |
-
|
| 104 |
-
def make_prediction(img):
|
| 105 |
-
processor, model = load_model()
|
| 106 |
-
inputs = processor(images=img, return_tensors="pt")
|
| 107 |
-
|
| 108 |
-
with torch.no_grad():
|
| 109 |
-
outputs = model(**inputs)
|
| 110 |
-
|
| 111 |
-
img_size = torch.tensor([img.size[::-1]])
|
| 112 |
-
results = processor.post_process_object_detection(
|
| 113 |
-
outputs, threshold=0.3, target_sizes=img_size
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
return results[0], model.config.id2label
|
| 117 |
-
|
| 118 |
-
# ---------------- VISUALIZATION ----------------
|
| 119 |
-
|
| 120 |
-
def visualize(img, output, id2label, threshold):
|
| 121 |
-
try:
|
| 122 |
-
keep = output["scores"] > threshold
|
| 123 |
-
boxes = output["boxes"][keep]
|
| 124 |
-
labels = output["labels"][keep]
|
| 125 |
-
|
| 126 |
-
fig, ax = plt.subplots(figsize=(6,6))
|
| 127 |
-
ax.imshow(img)
|
| 128 |
-
results_text = []
|
| 129 |
|
| 130 |
-
|
| 131 |
-
label_name = id2label[label.item()].lower()
|
| 132 |
-
|
| 133 |
-
if "plate" not in label_name:
|
| 134 |
-
continue
|
| 135 |
-
|
| 136 |
-
x1,y1,x2,y2 = map(int, box.tolist())
|
| 137 |
-
plate_img = img.crop((x1,y1,x2,y2))
|
| 138 |
-
|
| 139 |
-
plate = read_plate(plate_img)
|
| 140 |
-
vtype = classify_plate_color(plate_img)
|
| 141 |
-
toll = compute_discount(vtype)
|
| 142 |
|
| 143 |
-
cursor.execute(
|
| 144 |
-
"INSERT INTO vehicles VALUES (?, ?, ?, datetime('now'))",
|
| 145 |
-
(plate, vtype, toll)
|
| 146 |
-
)
|
| 147 |
-
conn.commit()
|
| 148 |
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
-
|
| 152 |
-
plt.Rectangle((x1,y1), x2-x1, y2-y1,
|
| 153 |
-
fill=False, color="red", linewidth=2)
|
| 154 |
-
)
|
| 155 |
-
ax.text(x1, y1-5, f"{plate} ({vtype})",
|
| 156 |
-
color="yellow", fontsize=8)
|
| 157 |
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
-
|
| 161 |
-
|
| 162 |
|
| 163 |
-
|
| 164 |
|
| 165 |
-
|
| 166 |
-
return None, f"Error: {str(e)}"
|
| 167 |
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
-
|
| 171 |
-
df = pd.read_sql("SELECT * FROM vehicles", conn)
|
| 172 |
-
fig, ax = plt.subplots(figsize=(8,5))
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
-
|
| 185 |
-
ax.set_xlabel("Vehicle Type")
|
| 186 |
-
ax.set_ylabel("Number of Vehicles")
|
| 187 |
-
ax.tick_params(axis='x', rotation=30)
|
| 188 |
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
-
def detect_image(img, threshold):
|
| 193 |
-
if img is None:
|
| 194 |
-
return None, "No image provided"
|
| 195 |
-
output, id2label = make_prediction(img)
|
| 196 |
-
return visualize(img, output, id2label, threshold)
|
| 197 |
|
| 198 |
-
#
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
|
| 201 |
-
gr.Markdown("## π¦ Smart Vehicle Classification System")
|
| 202 |
|
| 203 |
-
slider = gr.Slider(0.3, 1.0, 0.5, label="Confidence Threshold")
|
| 204 |
|
| 205 |
with gr.Row():
|
| 206 |
-
img_input = gr.Image(type="pil")
|
| 207 |
-
img_output = gr.Plot()
|
| 208 |
-
|
| 209 |
-
result_box = gr.Textbox(label="Detection Result", lines=4)
|
| 210 |
|
| 211 |
-
|
| 212 |
-
detect_btn.click(
|
| 213 |
-
detect_image,
|
| 214 |
-
inputs=[img_input, slider],
|
| 215 |
-
outputs=[img_output, result_box, dashboard_plot]
|
| 216 |
-
)
|
| 217 |
-
|
| 218 |
-
gr.Markdown("### Feedback")
|
| 219 |
-
feedback_radio = gr.Radio(["Correct", "Incorrect"], label="Prediction correct?")
|
| 220 |
-
feedback_btn = gr.Button("Submit Feedback")
|
| 221 |
-
feedback_msg = gr.Textbox(label="Feedback Status")
|
| 222 |
-
|
| 223 |
-
feedback_btn.click(
|
| 224 |
-
submit_feedback,
|
| 225 |
-
inputs=[result_box, feedback_radio],
|
| 226 |
-
outputs=feedback_msg
|
| 227 |
-
)
|
| 228 |
-
|
| 229 |
-
gr.Markdown("### Model Accuracy")
|
| 230 |
-
accuracy_btn = gr.Button("Show Accuracy")
|
| 231 |
-
accuracy_box = gr.Textbox(label="Accuracy")
|
| 232 |
-
|
| 233 |
-
accuracy_btn.click(show_accuracy, outputs=accuracy_box)
|
| 234 |
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
-
|
| 239 |
|
| 240 |
-
|
| 241 |
-
if not result_text:
|
| 242 |
-
return "No result available."
|
| 243 |
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
)
|
| 248 |
-
conn.commit()
|
| 249 |
-
return "Feedback recorded!"
|
| 250 |
-
|
| 251 |
-
def show_accuracy():
|
| 252 |
-
df = pd.read_sql("SELECT * FROM feedback", conn)
|
| 253 |
-
|
| 254 |
-
if df.empty:
|
| 255 |
-
return "No feedback yet."
|
| 256 |
-
|
| 257 |
-
correct = len(df[df["feedback"] == "Correct"])
|
| 258 |
-
total = len(df)
|
| 259 |
-
|
| 260 |
-
accuracy = (correct / total) * 100
|
| 261 |
-
return f"Accuracy (User Feedback Based): {accuracy:.2f}%"
|
| 262 |
-
|
| 263 |
-
# ---------------- CALLBACK ----------------
|
| 264 |
|
| 265 |
demo.launch()
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 2 |
import matplotlib.pyplot as plt
|
|
|
|
| 3 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from PIL import Image
|
| 5 |
+
import random
|
| 6 |
+
|
| 7 |
+
# -------------------------------
|
| 8 |
+
# Global Counters
|
| 9 |
+
# -------------------------------
|
| 10 |
+
total_vehicles = 0
|
| 11 |
+
ev_count = 0
|
| 12 |
+
total_co2_saved = 0 # in kg
|
| 13 |
+
|
| 14 |
+
# -------------------------------
|
| 15 |
+
# CO2 Assumptions
|
| 16 |
+
# -------------------------------
|
| 17 |
+
DISTANCE_KM = 10
|
| 18 |
+
CO2_PER_KM_PETROL = 0.150 # 150g = 0.15kg per km
|
| 19 |
+
CO2_SAVED_PER_EV = DISTANCE_KM * CO2_PER_KM_PETROL # 1.5 kg
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# -------------------------------
|
| 23 |
+
# Dummy Vehicle Classifier
|
| 24 |
+
# Replace this with your YOLO model
|
| 25 |
+
# -------------------------------
|
| 26 |
+
def classify_vehicle():
|
| 27 |
+
vehicle_types = [
|
| 28 |
+
"Car",
|
| 29 |
+
"Bus",
|
| 30 |
+
"Truck",
|
| 31 |
+
"Motorcycle",
|
| 32 |
+
"Electric Vehicle"
|
| 33 |
+
]
|
| 34 |
+
return random.choice(vehicle_types)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# -------------------------------
|
| 38 |
+
# Dashboard Plot
|
| 39 |
+
# -------------------------------
|
| 40 |
+
def generate_dashboard():
|
| 41 |
+
global total_vehicles, ev_count, total_co2_saved
|
| 42 |
+
|
| 43 |
+
non_ev = total_vehicles - ev_count
|
| 44 |
+
|
| 45 |
+
fig, ax = plt.subplots()
|
| 46 |
+
labels = ["EV", "Non-EV"]
|
| 47 |
+
values = [ev_count, non_ev]
|
| 48 |
+
|
| 49 |
+
ax.bar(labels, values)
|
| 50 |
+
ax.set_title("Vehicle Distribution")
|
| 51 |
+
ax.set_ylabel("Count")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
return fig
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
# -------------------------------
|
| 57 |
+
# Main Detection Function
|
| 58 |
+
# -------------------------------
|
| 59 |
+
def detect_image(image, threshold):
|
| 60 |
|
| 61 |
+
global total_vehicles, ev_count, total_co2_saved
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
if image is None:
|
| 64 |
+
return None, "Please upload an image.", \
|
| 65 |
+
"### π Total Vehicles: 0", \
|
| 66 |
+
"### β‘ EV Vehicles: 0", \
|
| 67 |
+
"### π EV Adoption Rate: 0%", \
|
| 68 |
+
"### π± COβ Saved: 0 kg", \
|
| 69 |
+
generate_dashboard()
|
| 70 |
|
| 71 |
+
# Simulated detection
|
| 72 |
+
vehicle_type = classify_vehicle()
|
| 73 |
|
| 74 |
+
total_vehicles += 1
|
| 75 |
|
| 76 |
+
co2_saved_this = 0
|
|
|
|
| 77 |
|
| 78 |
+
if vehicle_type.lower() == "electric vehicle":
|
| 79 |
+
ev_count += 1
|
| 80 |
+
co2_saved_this = CO2_SAVED_PER_EV
|
| 81 |
+
total_co2_saved += co2_saved_this
|
| 82 |
|
| 83 |
+
ev_percent = (ev_count / total_vehicles) * 100
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
# Create dummy detection visualization
|
| 86 |
+
fig, ax = plt.subplots()
|
| 87 |
+
ax.imshow(image)
|
| 88 |
+
ax.set_title(f"Detected: {vehicle_type}")
|
| 89 |
+
ax.axis("off")
|
| 90 |
|
| 91 |
+
result_text = f"""
|
| 92 |
+
Vehicle Type: {vehicle_type}
|
| 93 |
+
Confidence Threshold Used: {threshold}
|
| 94 |
+
COβ Saved (This Vehicle): {co2_saved_this:.2f} kg
|
| 95 |
+
"""
|
| 96 |
|
| 97 |
+
total_card = f"### π Total Vehicles: {total_vehicles}"
|
| 98 |
+
ev_card = f"### β‘ EV Vehicles: {ev_count}"
|
| 99 |
+
percent_card = f"### π EV Adoption Rate: {ev_percent:.2f}%"
|
| 100 |
+
co2_card = f"### π± COβ Saved: {total_co2_saved:.2f} kg"
|
| 101 |
|
| 102 |
+
dashboard_fig = generate_dashboard()
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
return (
|
| 105 |
+
fig,
|
| 106 |
+
result_text,
|
| 107 |
+
total_card,
|
| 108 |
+
ev_card,
|
| 109 |
+
percent_card,
|
| 110 |
+
co2_card,
|
| 111 |
+
dashboard_fig
|
| 112 |
+
)
|
| 113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
# -------------------------------
|
| 116 |
+
# Gradio UI
|
| 117 |
+
# -------------------------------
|
| 118 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 119 |
|
| 120 |
+
gr.Markdown("## π¦ Smart Vehicle Classification & EV COβ Analytics Dashboard")
|
|
|
|
| 121 |
|
| 122 |
+
slider = gr.Slider(0.3, 1.0, 0.5, step=0.05, label="Confidence Threshold")
|
| 123 |
|
| 124 |
with gr.Row():
|
| 125 |
+
img_input = gr.Image(type="pil", label="Upload Vehicle Image")
|
| 126 |
+
img_output = gr.Plot(label="Detection Output")
|
|
|
|
|
|
|
| 127 |
|
| 128 |
+
result_box = gr.Textbox(label="Detection Result", lines=5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
# Metric Cards
|
| 131 |
+
with gr.Row():
|
| 132 |
+
total_card = gr.Markdown("### π Total Vehicles: 0")
|
| 133 |
+
ev_card = gr.Markdown("### β‘ EV Vehicles: 0")
|
| 134 |
+
percent_card = gr.Markdown("### π EV Adoption Rate: 0%")
|
| 135 |
+
co2_card = gr.Markdown("### π± COβ Saved: 0 kg")
|
| 136 |
|
| 137 |
+
dashboard_plot = gr.Plot(label="Analytics Dashboard")
|
| 138 |
|
| 139 |
+
detect_btn = gr.Button("π Detect Vehicle")
|
|
|
|
|
|
|
| 140 |
|
| 141 |
+
detect_btn.click(
|
| 142 |
+
fn=detect_image,
|
| 143 |
+
inputs=[img_input, slider],
|
| 144 |
+
outputs=[
|
| 145 |
+
img_output,
|
| 146 |
+
result_box,
|
| 147 |
+
total_card,
|
| 148 |
+
ev_card,
|
| 149 |
+
percent_card,
|
| 150 |
+
co2_card,
|
| 151 |
+
dashboard_plot
|
| 152 |
+
]
|
| 153 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
demo.launch()
|