pleaes
Browse files- app.py +150 -0
- model/dataset_cleaned.csv +2 -2
- requirements.txt +10 -0
app.py
CHANGED
|
@@ -19,6 +19,7 @@ CORS(app)
|
|
| 19 |
|
| 20 |
# ============================================================================
|
| 21 |
# FIX: Use raw strings or forward slashes for Windows paths
|
|
|
|
| 22 |
# ================================================
|
| 23 |
# Base directory = where app.py lives
|
| 24 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
@@ -142,6 +143,133 @@ load_models()
|
|
| 142 |
LAT_MIN, LAT_MAX = 12.70, 13.30
|
| 143 |
LON_MIN, LON_MAX = 77.30, 78.00
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
def is_in_bengaluru(lat, lon):
|
| 146 |
"""Check if coordinates are within Bengaluru bounds"""
|
| 147 |
return LAT_MIN <= lat <= LAT_MAX and LON_MIN <= lon <= LON_MAX
|
|
@@ -337,6 +465,10 @@ def predict_crime():
|
|
| 337 |
|
| 338 |
print(f"๐ฎ Prediction request: location={location_name}, date={date_str}")
|
| 339 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
if location_name and not latitude:
|
| 341 |
location_coords = {
|
| 342 |
'koramangala': (12.9352, 77.6245),
|
|
@@ -383,6 +515,7 @@ def predict_crime():
|
|
| 383 |
crime_count = len(nearby_crimes)
|
| 384 |
risk_level = calculate_risk_level(crime_count)
|
| 385 |
|
|
|
|
| 386 |
# Get crime types - check for CrimeHead_Name or CrimeType column
|
| 387 |
crime_types = {}
|
| 388 |
if len(nearby_crimes) > 0:
|
|
@@ -395,6 +528,12 @@ def predict_crime():
|
|
| 395 |
elif 'CrimeHead_Name' in nearby_crimes.columns:
|
| 396 |
crime_types = nearby_crimes['CrimeHead_Name'].value_counts().head(10).to_dict()
|
| 397 |
print(f" Found {len(crime_types)} crime types from CrimeHead_Name")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
|
| 399 |
# Calculate confidence
|
| 400 |
confidence = min(95, 60 + (crime_count / max(len(df), 1) * 100))
|
|
@@ -459,10 +598,21 @@ def search_location():
|
|
| 459 |
traceback.print_exc()
|
| 460 |
return jsonify({'results': []})
|
| 461 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
@app.errorhandler(404)
|
| 463 |
def not_found(e):
|
| 464 |
return jsonify({'error': 'Endpoint not found'}), 404
|
| 465 |
|
|
|
|
| 466 |
@app.errorhandler(500)
|
| 467 |
def server_error(e):
|
| 468 |
return jsonify({'error': 'Internal server error'}), 500
|
|
|
|
| 19 |
|
| 20 |
# ============================================================================
|
| 21 |
# FIX: Use raw strings or forward slashes for Windows paths
|
| 22 |
+
<<<<<<< HEAD
|
| 23 |
# ================================================
|
| 24 |
# Base directory = where app.py lives
|
| 25 |
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
| 143 |
LAT_MIN, LAT_MAX = 12.70, 13.30
|
| 144 |
LON_MIN, LON_MAX = 77.30, 78.00
|
| 145 |
|
| 146 |
+
=======
|
| 147 |
+
# ============================================================================
|
| 148 |
+
|
| 149 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 150 |
+
DATASET_PATH = os.path.join(BASE_DIR, '..', 'model', 'dataset_cleaned.csv')
|
| 151 |
+
MODEL_DIR = os.path.join(BASE_DIR, '..', 'model')
|
| 152 |
+
|
| 153 |
+
# Convert to absolute paths and normalize
|
| 154 |
+
DATASET_PATH = os.path.abspath(DATASET_PATH)
|
| 155 |
+
MODEL_DIR = os.path.abspath(MODEL_DIR)
|
| 156 |
+
|
| 157 |
+
print(f"\n๐ BASE_DIR: {BASE_DIR}")
|
| 158 |
+
print(f"๐ DATASET_PATH: {DATASET_PATH}")
|
| 159 |
+
print(f"๐ MODEL_DIR: {MODEL_DIR}")
|
| 160 |
+
print(f"โ Dataset exists: {os.path.exists(DATASET_PATH)}")
|
| 161 |
+
print(f"โ Model dir exists: {os.path.exists(MODEL_DIR)}\n")
|
| 162 |
+
|
| 163 |
+
df = None
|
| 164 |
+
model1 = None
|
| 165 |
+
model2 = None
|
| 166 |
+
le = None
|
| 167 |
+
|
| 168 |
+
def load_dataset():
|
| 169 |
+
"""Load the crime dataset"""
|
| 170 |
+
global df
|
| 171 |
+
try:
|
| 172 |
+
if not os.path.exists(DATASET_PATH):
|
| 173 |
+
print(f"โ Dataset not found at: {DATASET_PATH}")
|
| 174 |
+
df = pd.DataFrame()
|
| 175 |
+
return False
|
| 176 |
+
|
| 177 |
+
df = pd.read_csv(DATASET_PATH)
|
| 178 |
+
print(f"โ
Dataset loaded: {len(df)} records")
|
| 179 |
+
print(f" Columns: {list(df.columns)}")
|
| 180 |
+
return True
|
| 181 |
+
except Exception as e:
|
| 182 |
+
print(f"โ Error loading dataset: {e}")
|
| 183 |
+
traceback.print_exc()
|
| 184 |
+
df = pd.DataFrame()
|
| 185 |
+
return False
|
| 186 |
+
|
| 187 |
+
def load_models():
|
| 188 |
+
"""Load trained models with fallback options"""
|
| 189 |
+
global model1, model2, le
|
| 190 |
+
|
| 191 |
+
print("\n๐ฆ Attempting to load models...")
|
| 192 |
+
print(f" Looking in: {MODEL_DIR}\n")
|
| 193 |
+
|
| 194 |
+
model1_path = os.path.join(MODEL_DIR, 'model1.pkl')
|
| 195 |
+
model2_path = os.path.join(MODEL_DIR, 'model2.pkl')
|
| 196 |
+
le_path = os.path.join(MODEL_DIR, 'label_encoder.pkl')
|
| 197 |
+
|
| 198 |
+
print(f"Model1 path: {model1_path} (exists: {os.path.exists(model1_path)})")
|
| 199 |
+
print(f"Model2 path: {model2_path} (exists: {os.path.exists(model2_path)})")
|
| 200 |
+
print(f"LE path: {le_path} (exists: {os.path.exists(le_path)})\n")
|
| 201 |
+
|
| 202 |
+
# Try Model 1
|
| 203 |
+
if os.path.exists(model1_path):
|
| 204 |
+
try:
|
| 205 |
+
model1 = joblib.load(model1_path)
|
| 206 |
+
print(f"โ
Model1 loaded successfully")
|
| 207 |
+
except Exception as e:
|
| 208 |
+
print(f"โ ๏ธ Joblib failed for model1: {e}")
|
| 209 |
+
try:
|
| 210 |
+
with open(model1_path, 'rb') as f:
|
| 211 |
+
model1 = pickle.load(f)
|
| 212 |
+
print(f"โ
Model1 loaded with pickle")
|
| 213 |
+
except Exception as e2:
|
| 214 |
+
print(f"โ Failed to load model1: {e2}")
|
| 215 |
+
model1 = None
|
| 216 |
+
else:
|
| 217 |
+
print(f"โ ๏ธ Model1 not found")
|
| 218 |
+
|
| 219 |
+
# Try Model 2
|
| 220 |
+
if os.path.exists(model2_path):
|
| 221 |
+
try:
|
| 222 |
+
model2 = joblib.load(model2_path)
|
| 223 |
+
print(f"โ
Model2 loaded successfully")
|
| 224 |
+
except Exception as e:
|
| 225 |
+
print(f"โ ๏ธ Joblib failed for model2: {e}")
|
| 226 |
+
try:
|
| 227 |
+
with open(model2_path, 'rb') as f:
|
| 228 |
+
model2 = pickle.load(f)
|
| 229 |
+
print(f"โ
Model2 loaded with pickle")
|
| 230 |
+
except Exception as e2:
|
| 231 |
+
print(f"โ Failed to load model2: {e2}")
|
| 232 |
+
model2 = None
|
| 233 |
+
else:
|
| 234 |
+
print(f"โ ๏ธ Model2 not found")
|
| 235 |
+
|
| 236 |
+
# Try LabelEncoder
|
| 237 |
+
if os.path.exists(le_path):
|
| 238 |
+
try:
|
| 239 |
+
le = joblib.load(le_path)
|
| 240 |
+
print(f"โ
LabelEncoder loaded successfully")
|
| 241 |
+
except Exception as e:
|
| 242 |
+
print(f"โ ๏ธ Joblib failed for LabelEncoder: {e}")
|
| 243 |
+
try:
|
| 244 |
+
with open(le_path, 'rb') as f:
|
| 245 |
+
le = pickle.load(f)
|
| 246 |
+
print(f"โ
LabelEncoder loaded with pickle")
|
| 247 |
+
except Exception as e2:
|
| 248 |
+
print(f"โ Failed to load LabelEncoder: {e2}")
|
| 249 |
+
le = None
|
| 250 |
+
else:
|
| 251 |
+
print(f"โ ๏ธ LabelEncoder not found")
|
| 252 |
+
|
| 253 |
+
if not model1 and not model2:
|
| 254 |
+
print("\nโ ๏ธ Using MOCK predictions (models not available)")
|
| 255 |
+
else:
|
| 256 |
+
print("\nโ
Models ready for predictions")
|
| 257 |
+
|
| 258 |
+
# Load on startup
|
| 259 |
+
print("\n" + "="*60)
|
| 260 |
+
print("๐ OPENSIGHT API INITIALIZATION")
|
| 261 |
+
print("="*60)
|
| 262 |
+
load_dataset()
|
| 263 |
+
load_models()
|
| 264 |
+
|
| 265 |
+
# ============================================================================
|
| 266 |
+
# BENGALURU CONFIGURATION
|
| 267 |
+
# ============================================================================
|
| 268 |
+
|
| 269 |
+
LAT_MIN, LAT_MAX = 12.70, 13.30
|
| 270 |
+
LON_MIN, LON_MAX = 77.30, 78.00
|
| 271 |
+
|
| 272 |
+
>>>>>>> f23833a (PUSHED EVRYTHING)
|
| 273 |
def is_in_bengaluru(lat, lon):
|
| 274 |
"""Check if coordinates are within Bengaluru bounds"""
|
| 275 |
return LAT_MIN <= lat <= LAT_MAX and LON_MIN <= lon <= LON_MAX
|
|
|
|
| 465 |
|
| 466 |
print(f"๐ฎ Prediction request: location={location_name}, date={date_str}")
|
| 467 |
|
| 468 |
+
<<<<<<< HEAD
|
| 469 |
+
=======
|
| 470 |
+
# Resolve location name to coordinates
|
| 471 |
+
>>>>>>> f23833a (PUSHED EVRYTHING)
|
| 472 |
if location_name and not latitude:
|
| 473 |
location_coords = {
|
| 474 |
'koramangala': (12.9352, 77.6245),
|
|
|
|
| 515 |
crime_count = len(nearby_crimes)
|
| 516 |
risk_level = calculate_risk_level(crime_count)
|
| 517 |
|
| 518 |
+
<<<<<<< HEAD
|
| 519 |
# Get crime types - check for CrimeHead_Name or CrimeType column
|
| 520 |
crime_types = {}
|
| 521 |
if len(nearby_crimes) > 0:
|
|
|
|
| 528 |
elif 'CrimeHead_Name' in nearby_crimes.columns:
|
| 529 |
crime_types = nearby_crimes['CrimeHead_Name'].value_counts().head(10).to_dict()
|
| 530 |
print(f" Found {len(crime_types)} crime types from CrimeHead_Name")
|
| 531 |
+
=======
|
| 532 |
+
# Get crime types
|
| 533 |
+
crime_types = {}
|
| 534 |
+
if len(nearby_crimes) > 0 and 'CrimeType' in nearby_crimes.columns:
|
| 535 |
+
crime_types = nearby_crimes['CrimeType'].value_counts().head(5).to_dict()
|
| 536 |
+
>>>>>>> f23833a (PUSHED EVRYTHING)
|
| 537 |
|
| 538 |
# Calculate confidence
|
| 539 |
confidence = min(95, 60 + (crime_count / max(len(df), 1) * 100))
|
|
|
|
| 598 |
traceback.print_exc()
|
| 599 |
return jsonify({'results': []})
|
| 600 |
|
| 601 |
+
<<<<<<< HEAD
|
| 602 |
+
@app.errorhandler(404)
|
| 603 |
+
def not_found(e):
|
| 604 |
+
return jsonify({'error': 'Endpoint not found'}), 404
|
| 605 |
+
|
| 606 |
+
=======
|
| 607 |
+
# ============================================================================
|
| 608 |
+
# ERROR HANDLERS
|
| 609 |
+
# ============================================================================
|
| 610 |
+
|
| 611 |
@app.errorhandler(404)
|
| 612 |
def not_found(e):
|
| 613 |
return jsonify({'error': 'Endpoint not found'}), 404
|
| 614 |
|
| 615 |
+
>>>>>>> f23833a (PUSHED EVRYTHING)
|
| 616 |
@app.errorhandler(500)
|
| 617 |
def server_error(e):
|
| 618 |
return jsonify({'error': 'Internal server error'}), 500
|
model/dataset_cleaned.csv
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:efbc3e8d31e67cc706d95f596e568ac2aa9ee1a0f8f623be43d0308ad3566630
|
| 3 |
+
size 41960106
|
requirements.txt
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
Flask==2.3.0
|
| 2 |
Flask-CORS==4.0.0
|
| 3 |
pandas==2.0.0
|
|
@@ -6,3 +7,12 @@ scikit-learn==1.2.0
|
|
| 6 |
joblib==1.2.0
|
| 7 |
python-dotenv==1.0.0
|
| 8 |
xgboost==1.7.6
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<<<<<<< HEAD
|
| 2 |
Flask==2.3.0
|
| 3 |
Flask-CORS==4.0.0
|
| 4 |
pandas==2.0.0
|
|
|
|
| 7 |
joblib==1.2.0
|
| 8 |
python-dotenv==1.0.0
|
| 9 |
xgboost==1.7.6
|
| 10 |
+
=======
|
| 11 |
+
Flask==2.3.0
|
| 12 |
+
Flask-CORS==4.0.0
|
| 13 |
+
pandas==2.0.0
|
| 14 |
+
numpy==1.23.0
|
| 15 |
+
scikit-learn==1.2.0
|
| 16 |
+
joblib==1.2.0
|
| 17 |
+
python-dotenv==1.0.0
|
| 18 |
+
>>>>>>> f23833a (PUSHED EVRYTHING)
|