Unmeshraj commited on
Commit
280da7e
·
1 Parent(s): b098d78

Add application file

Browse files
Files changed (1) hide show
  1. app.py +202 -0
app.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Crime Hotspot Prediction API Server
3
+ Backend Flask application for serving crime predictions and hotspot data
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ from datetime import datetime, timedelta
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ from flask import Flask, jsonify, request
13
+ from flask_cors import CORS
14
+
15
+ # Add backend code directory to path
16
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'code'))
17
+
18
+ app = Flask(__name__)
19
+ CORS(app)
20
+
21
+ # Configuration
22
+ app.config['JSON_SORT_KEYS'] = False
23
+ BACKEND_PORT = int(os.getenv('BACKEND_PORT', 5000))
24
+ BACKEND_DEBUG = os.getenv('BACKEND_DEBUG', 'False') == 'True'
25
+
26
+ # Mock data generators (replace with actual model inference later)
27
+ def generate_mock_hotspots(city: str, threshold: float = 0.5):
28
+ """Generate mock hotspot data for demonstration"""
29
+ cities_data = {
30
+ 'bangalore': {
31
+ 'center': [12.9716, 77.5946],
32
+ 'hotspots': [
33
+ {'lat': 12.9352, 'lon': 77.6245, 'risk': 0.85},
34
+ {'lat': 12.9716, 'lon': 77.5946, 'risk': 0.72},
35
+ {'lat': 12.935, 'lon': 77.62, 'risk': 0.68},
36
+ {'lat': 13.0027, 'lon': 77.5914, 'risk': 0.61},
37
+ {'lat': 12.9142, 'lon': 77.6391, 'risk': 0.55},
38
+ ]
39
+ },
40
+ 'delhi': {
41
+ 'center': [28.7041, 77.1025],
42
+ 'hotspots': [
43
+ {'lat': 28.7041, 'lon': 77.1025, 'risk': 0.89},
44
+ {'lat': 28.6328, 'lon': 77.2197, 'risk': 0.76},
45
+ ]
46
+ },
47
+ 'mumbai': {
48
+ 'center': [19.0760, 72.8777],
49
+ 'hotspots': [
50
+ {'lat': 19.0760, 'lon': 72.8777, 'risk': 0.82},
51
+ {'lat': 19.0176, 'lon': 72.8479, 'risk': 0.71},
52
+ ]
53
+ },
54
+ 'newyork': {
55
+ 'center': [40.7128, -74.0060],
56
+ 'hotspots': [
57
+ {'lat': 40.7128, 'lon': -74.0060, 'risk': 0.88},
58
+ {'lat': 40.7580, 'lon': -73.9855, 'risk': 0.75},
59
+ {'lat': 40.6892, 'lon': -74.0445, 'risk': 0.63},
60
+ ]
61
+ }
62
+ }
63
+
64
+ city_data = cities_data.get(city.lower(), cities_data['bangalore'])
65
+ hotspots = []
66
+
67
+ for idx, hs in enumerate(city_data['hotspots']):
68
+ if hs['risk'] >= threshold:
69
+ risk_level = 'high' if hs['risk'] >= 0.75 else ('medium' if hs['risk'] >= 0.6 else 'low')
70
+ hotspots.append({
71
+ 'id': f'hotspot-{city}-{idx}',
72
+ 'latitude': hs['lat'],
73
+ 'longitude': hs['lon'],
74
+ 'riskLevel': risk_level,
75
+ 'crimeCount': int(50 * hs['risk']) + 10,
76
+ })
77
+
78
+ return hotspots
79
+
80
+ def generate_mock_statistics(city: str):
81
+ """Generate mock statistics for demonstration"""
82
+ hotspots = generate_mock_hotspots(city, threshold=0.0)
83
+
84
+ total_crimes = sum(hs['crimeCount'] for hs in hotspots)
85
+ avg_risk = np.mean([0.85, 0.72, 0.68, 0.61, 0.55])
86
+
87
+ # Generate mock time series data
88
+ time_series = []
89
+ base_date = datetime.now() - timedelta(days=30)
90
+ for i in range(30):
91
+ date = (base_date + timedelta(days=i)).strftime('%Y-%m-%d')
92
+ crimes = int(total_crimes / 30 + np.random.normal(0, 5))
93
+ predicted = int(total_crimes / 30 + np.random.normal(0, 3))
94
+ time_series.append({
95
+ 'date': date,
96
+ 'crimes': max(0, crimes),
97
+ 'predicted': max(0, predicted)
98
+ })
99
+
100
+ return {
101
+ 'hotspotsCount': len(hotspots),
102
+ 'totalCrimes': total_crimes,
103
+ 'averageRiskLevel': float(avg_risk),
104
+ 'predictionAccuracy': 0.85,
105
+ 'timeSeriesData': time_series
106
+ }
107
+
108
+ # API Routes
109
+
110
+ @app.route('/api/health', methods=['GET'])
111
+ def health():
112
+ """Health check endpoint"""
113
+ return jsonify({
114
+ 'status': 'healthy',
115
+ 'timestamp': datetime.now().isoformat()
116
+ })
117
+
118
+ @app.route('/api/hotspots', methods=['GET'])
119
+ def get_hotspots():
120
+ """Get crime hotspots for a city and threshold"""
121
+ try:
122
+ city = request.args.get('city', 'bangalore')
123
+ threshold = float(request.args.get('threshold', 0.5))
124
+ date = request.args.get('date')
125
+
126
+ hotspots = generate_mock_hotspots(city, threshold)
127
+
128
+ return jsonify({
129
+ 'city': city,
130
+ 'threshold': threshold,
131
+ 'date': date or datetime.now().strftime('%Y-%m-%d'),
132
+ 'hotspots': hotspots,
133
+ 'count': len(hotspots)
134
+ })
135
+
136
+ except Exception as e:
137
+ return jsonify({'error': str(e)}), 500
138
+
139
+ @app.route('/api/predictions', methods=['GET'])
140
+ def get_predictions():
141
+ """Get model predictions for a city"""
142
+ try:
143
+ city = request.args.get('city', 'bangalore')
144
+ time_window = request.args.get('timeWindow', 'current')
145
+
146
+ # In production, this would call the actual ML model
147
+ predictions = {
148
+ 'city': city,
149
+ 'timeWindow': time_window,
150
+ 'timestamp': datetime.now().isoformat(),
151
+ 'data': generate_mock_hotspots(city, 0.0)
152
+ }
153
+
154
+ return jsonify(predictions)
155
+
156
+ except Exception as e:
157
+ return jsonify({'error': str(e)}), 500
158
+
159
+ @app.route('/api/statistics', methods=['GET'])
160
+ def get_statistics():
161
+ """Get statistics and insights for a city"""
162
+ try:
163
+ city = request.args.get('city', 'bangalore')
164
+
165
+ stats = generate_mock_statistics(city)
166
+
167
+ return jsonify(stats)
168
+
169
+ except Exception as e:
170
+ return jsonify({'error': str(e)}), 500
171
+
172
+ @app.route('/api/train', methods=['POST'])
173
+ def train_model():
174
+ """Trigger model retraining (placeholder)"""
175
+ try:
176
+ data = request.get_json()
177
+ city = data.get('city', 'bangalore')
178
+
179
+ return jsonify({
180
+ 'status': 'training_started',
181
+ 'city': city,
182
+ 'message': 'Model training initiated. Check back later for results.',
183
+ 'timestamp': datetime.now().isoformat()
184
+ })
185
+
186
+ except Exception as e:
187
+ return jsonify({'error': str(e)}), 500
188
+
189
+ @app.errorhandler(404)
190
+ def not_found(error):
191
+ """Handle 404 errors"""
192
+ return jsonify({'error': 'Endpoint not found'}), 404
193
+
194
+ @app.errorhandler(500)
195
+ def server_error(error):
196
+ """Handle 500 errors"""
197
+ return jsonify({'error': 'Internal server error'}), 500
198
+
199
+ if __name__ == '__main__':
200
+ print("Starting Crime Hotspot Prediction API Server...")
201
+ print(f"Running on http://localhost:{BACKEND_PORT}")
202
+ app.run(host='0.0.0.0', port=BACKEND_PORT, debug=BACKEND_DEBUG)