Kamala28 commited on
Commit
3f63f6e
·
verified ·
1 Parent(s): 377bd95

Upload 7 files

Browse files
Files changed (7) hide show
  1. app.py +75 -0
  2. feature_cols.txt +21 -0
  3. grid_lookup.csv +0 -0
  4. label_encoder.pkl +3 -0
  5. requirements.txt +7 -0
  6. runtime.txt +1 -0
  7. safety_model.pkl +3 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, jsonify, request
2
+ import joblib
3
+ import pandas as pd
4
+ import numpy as np
5
+ import requests
6
+ import os
7
+
8
+ app = Flask(__name__)
9
+
10
+ model = joblib.load("safety_model.pkl")
11
+ le = joblib.load("label_encoder.pkl")
12
+ grid = pd.read_csv("grid_lookup.csv")
13
+ FEATURE_COLS = open("feature_cols.txt").read().strip().split("\n")
14
+
15
+ FAST2SMS_KEY = "YOUR_FAST2SMS_API_KEY"
16
+ GUARDIAN_PHONE = "91XXXXXXXXXX"
17
+
18
+ def send_sms(lat, lon, risk_score):
19
+ message = (
20
+ f"SAFETY ALERT! Unsafe location detected. "
21
+ f"Location: https://maps.google.com/?q={lat},{lon} "
22
+ f"Risk Score: {risk_score:.2f}. Please check immediately!"
23
+ )
24
+ url = "https://www.fast2sms.com/dev/bulkV2"
25
+ payload = {
26
+ "route" : "v3",
27
+ "sender_id": "TXTIND",
28
+ "message" : message,
29
+ "language" : "english",
30
+ "flash" : 0,
31
+ "numbers" : GUARDIAN_PHONE
32
+ }
33
+ headers = {"authorization": FAST2SMS_KEY, "Content-Type": "application/json"}
34
+ try:
35
+ resp = requests.post(url, json=payload, headers=headers, timeout=10)
36
+ return resp.json()
37
+ except Exception as e:
38
+ return {"error": str(e)}
39
+
40
+ @app.route("/predict", methods=["GET"])
41
+ def predict():
42
+ try:
43
+ lat = float(request.args.get("lat"))
44
+ lon = float(request.args.get("lon"))
45
+ except (TypeError, ValueError):
46
+ return jsonify({"error": "Missing or invalid lat/lon"}), 400
47
+
48
+ distances = np.sqrt((grid["latitude"] - lat)**2 + (grid["longitude"] - lon)**2)
49
+ nearest_row = grid.iloc[distances.idxmin()]
50
+ features = pd.DataFrame([nearest_row[FEATURE_COLS].values], columns=FEATURE_COLS)
51
+
52
+ prediction = int(model.predict(features)[0])
53
+ risk_score = round(float(model.predict_proba(features)[0][1]), 4)
54
+
55
+ sms_sent = False
56
+ if prediction == 1:
57
+ send_sms(lat, lon, risk_score)
58
+ sms_sent = True
59
+
60
+ return jsonify({
61
+ "latitude" : lat,
62
+ "longitude" : lon,
63
+ "label" : "UNSAFE" if prediction == 1 else "SAFE",
64
+ "risk_score": risk_score,
65
+ "sms_sent" : sms_sent,
66
+ "area_id" : nearest_row["area_id"]
67
+ })
68
+
69
+ @app.route("/", methods=["GET"])
70
+ def home():
71
+ return jsonify({"status": "Women Safety API is running", "usage": "/predict?lat=13.05&lon=80.25"})
72
+
73
+ if __name__ == "__main__":
74
+ port = int(os.environ.get("PORT", 5000))
75
+ app.run(host="0.0.0.0", port=port, debug=False)
feature_cols.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ latitude
2
+ longitude
3
+ total_incidents
4
+ incidents_5yr
5
+ night_incidents
6
+ sexual_offences
7
+ harassment_count
8
+ assault_count
9
+ avg_severity
10
+ repeat_offender_cases
11
+ street_lighting
12
+ cctv_density
13
+ proximity_transit
14
+ population_density
15
+ slum_density
16
+ nightlife_density
17
+ incident_density
18
+ weighted_risk_score
19
+ trend_12month
20
+ risk_index
21
+ area_type_enc
grid_lookup.csv ADDED
The diff for this file is too large to render. See raw diff
 
label_encoder.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b97bc2f6c50067e6fde16dbb96fbe5c918a36e25dd1d95da477b3c9d33db7354
3
+ size 525
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ flask
2
+ scikit-learn
3
+ pandas
4
+ numpy
5
+ joblib
6
+ requests
7
+ gunicorn
runtime.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ python-3.11.0
safety_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7177c4d5a005cc4efe0255c5b87ea701ea6cd81182887541759365f1288d911
3
+ size 196809