Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -426,11 +426,47 @@ def predict_traffic_risk():
|
|
| 426 |
data = request.json
|
| 427 |
try:
|
| 428 |
if model_traffic is None: return jsonify({"error": "Tabular model missing"}), 500
|
| 429 |
-
|
| 430 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
status = "Major" if prob >= 70 else "Moderate" if prob >= 35 else "Minor"
|
|
|
|
| 432 |
return jsonify({"status": status, "risk_probability_percentage": prob})
|
| 433 |
-
except Exception as e:
|
|
|
|
|
|
|
| 434 |
|
| 435 |
@app.route('/favicon.ico')
|
| 436 |
@app.route('/app_logo')
|
|
|
|
| 426 |
data = request.json
|
| 427 |
try:
|
| 428 |
if model_traffic is None: return jsonify({"error": "Tabular model missing"}), 500
|
| 429 |
+
|
| 430 |
+
# 1. Enforce exact column names and order from the provided CSV file
|
| 431 |
+
csv_cols = [
|
| 432 |
+
'Weather', 'Road_Type', 'Time_of_Day', 'Traffic_Density', 'Speed_Limit',
|
| 433 |
+
'Number_of_Vehicles', 'Driver_Alcohol', 'Road_Condition', 'Vehicle_Type',
|
| 434 |
+
'Driver_Age', 'Driver_Experience', 'Road_Light_Condition'
|
| 435 |
+
]
|
| 436 |
+
|
| 437 |
+
# 2. Force correct data types to prevent silent DataFrame string failures
|
| 438 |
+
row_data = {}
|
| 439 |
+
for col in csv_cols:
|
| 440 |
+
val = data.get(col, "")
|
| 441 |
+
if col in ['Traffic_Density', 'Speed_Limit', 'Number_of_Vehicles', 'Driver_Alcohol', 'Driver_Age', 'Driver_Experience']:
|
| 442 |
+
try:
|
| 443 |
+
row_data[col] = float(val)
|
| 444 |
+
except (ValueError, TypeError):
|
| 445 |
+
row_data[col] = 0.0 # Strict numeric fallback
|
| 446 |
+
else:
|
| 447 |
+
row_data[col] = val if val != "" else "Unknown"
|
| 448 |
+
|
| 449 |
+
df = pd.DataFrame([row_data], columns=csv_cols)
|
| 450 |
+
|
| 451 |
+
# 3. Predict dynamically based on the model's actual class array indices
|
| 452 |
+
probs = model_traffic.predict_proba(df)[0]
|
| 453 |
+
model_classes = list(model_traffic.classes_)
|
| 454 |
+
|
| 455 |
+
if 'High' in model_classes:
|
| 456 |
+
prob = float(probs[model_classes.index('High')] * 100)
|
| 457 |
+
elif 'Major' in model_classes:
|
| 458 |
+
prob = float(probs[model_classes.index('Major')] * 100)
|
| 459 |
+
elif 1 in model_classes:
|
| 460 |
+
prob = float(probs[model_classes.index(1)] * 100)
|
| 461 |
+
else:
|
| 462 |
+
prob = float(probs[-1] * 100) # Safe fallback if classes are unnamed
|
| 463 |
+
|
| 464 |
status = "Major" if prob >= 70 else "Moderate" if prob >= 35 else "Minor"
|
| 465 |
+
|
| 466 |
return jsonify({"status": status, "risk_probability_percentage": prob})
|
| 467 |
+
except Exception as e:
|
| 468 |
+
print(f"Risk Predictor Error: {e}", flush=True)
|
| 469 |
+
return jsonify({"error": str(e)}), 500
|
| 470 |
|
| 471 |
@app.route('/favicon.ico')
|
| 472 |
@app.route('/app_logo')
|