update
Browse files- app.py +4 -152
- model/crime_type_grid.csv +0 -0
app.py
CHANGED
|
@@ -15,11 +15,11 @@ from sklearn.preprocessing import LabelEncoder
|
|
| 15 |
warnings.filterwarnings('ignore')
|
| 16 |
|
| 17 |
app = Flask(__name__)
|
| 18 |
-
CORS(app)
|
|
|
|
| 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,133 +143,6 @@ load_models()
|
|
| 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,10 +338,6 @@ def predict_crime():
|
|
| 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,7 +384,6 @@ def predict_crime():
|
|
| 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,12 +396,6 @@ def predict_crime():
|
|
| 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,21 +460,10 @@ def search_location():
|
|
| 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
|
|
@@ -625,4 +476,5 @@ if __name__ == '__main__':
|
|
| 625 |
print("\n" + "="*60)
|
| 626 |
print("โ
Starting OpenSight API Server")
|
| 627 |
print("="*60 + "\n")
|
| 628 |
-
app.run(
|
|
|
|
|
|
| 15 |
warnings.filterwarnings('ignore')
|
| 16 |
|
| 17 |
app = Flask(__name__)
|
| 18 |
+
CORS(app, resources={r"/api/*": {"origins": "*"}})
|
| 19 |
+
|
| 20 |
|
| 21 |
# ============================================================================
|
| 22 |
# FIX: Use raw strings or forward slashes for Windows paths
|
|
|
|
| 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 |
def is_in_bengaluru(lat, lon):
|
| 147 |
"""Check if coordinates are within Bengaluru bounds"""
|
| 148 |
return LAT_MIN <= lat <= LAT_MAX and LON_MIN <= lon <= LON_MAX
|
|
|
|
| 338 |
|
| 339 |
print(f"๐ฎ Prediction request: location={location_name}, date={date_str}")
|
| 340 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
if location_name and not latitude:
|
| 342 |
location_coords = {
|
| 343 |
'koramangala': (12.9352, 77.6245),
|
|
|
|
| 384 |
crime_count = len(nearby_crimes)
|
| 385 |
risk_level = calculate_risk_level(crime_count)
|
| 386 |
|
|
|
|
| 387 |
# Get crime types - check for CrimeHead_Name or CrimeType column
|
| 388 |
crime_types = {}
|
| 389 |
if len(nearby_crimes) > 0:
|
|
|
|
| 396 |
elif 'CrimeHead_Name' in nearby_crimes.columns:
|
| 397 |
crime_types = nearby_crimes['CrimeHead_Name'].value_counts().head(10).to_dict()
|
| 398 |
print(f" Found {len(crime_types)} crime types from CrimeHead_Name")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
|
| 400 |
# Calculate confidence
|
| 401 |
confidence = min(95, 60 + (crime_count / max(len(df), 1) * 100))
|
|
|
|
| 460 |
traceback.print_exc()
|
| 461 |
return jsonify({'results': []})
|
| 462 |
|
|
|
|
| 463 |
@app.errorhandler(404)
|
| 464 |
def not_found(e):
|
| 465 |
return jsonify({'error': 'Endpoint not found'}), 404
|
| 466 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 467 |
@app.errorhandler(500)
|
| 468 |
def server_error(e):
|
| 469 |
return jsonify({'error': 'Internal server error'}), 500
|
|
|
|
| 476 |
print("\n" + "="*60)
|
| 477 |
print("โ
Starting OpenSight API Server")
|
| 478 |
print("="*60 + "\n")
|
| 479 |
+
app.run(host="0.0.0.0",port=int(os.environ.get("PORT", 7860)),debug=False)
|
| 480 |
+
|
model/crime_type_grid.csv
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|