-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
481 lines (380 loc) · 15.4 KB
/
Copy pathapp.py
File metadata and controls
481 lines (380 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
"""
Flask Web Application for House Price Prediction
Integrates the trained ML model with a beautiful web interface
"""
from flask import Flask, render_template, request, jsonify, session, redirect, url_for, flash
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
from functools import wraps
import pandas as pd
import numpy as np
from predict import HousePricePredictor, format_price
from database import db, User
import json
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
app = Flask(__name__)
# Security configuration
app.secret_key = os.getenv('SECRET_KEY', 'dev-key-change-in-production')
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
# HTTPS/Security settings - enable in production
FLASK_ENV = os.getenv('FLASK_ENV', 'development')
if FLASK_ENV == 'production':
app.config['SESSION_COOKIE_SECURE'] = True
else:
app.config['SESSION_COOKIE_SECURE'] = False
# Database configuration
DATABASE_URL = os.getenv('DATABASE_URL', 'sqlite:///users.db')
# Fix PostgreSQL URI format for SQLAlchemy
if DATABASE_URL.startswith('postgres://'):
DATABASE_URL = DATABASE_URL.replace('postgres://', 'postgresql://', 1)
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Initialize database
db.init_app(app)
# Create database tables
with app.app_context():
db.create_all()
# Initialize Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'signin'
login_manager.login_message = 'Please sign in to access this page.'
login_manager.login_message_category = 'info'
# Initialize the predictor
predictor = HousePricePredictor('house_price_model.pkl')
# Load dataset for location data
df = pd.read_csv('Delhi_v2.csv')
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route('/')
def index():
"""Landing page - redirect to dashboard or signin"""
# Show a friendly landing page to unauthenticated users.
if current_user.is_authenticated:
return redirect(url_for('dashboard'))
# Render the new landing page for visitors
return render_template('landing.html')
@app.route('/signup', methods=['GET', 'POST'])
def signup():
"""Sign up page"""
if current_user.is_authenticated:
return redirect(url_for('dashboard'))
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
confirm_password = request.form.get('confirm_password')
full_name = request.form.get('full_name')
role = request.form.get('role', 'buyer')
# Validation
if not email or not password or not full_name:
flash('All fields are required', 'danger')
return render_template('signup.html')
if password != confirm_password:
flash('Passwords do not match', 'danger')
return render_template('signup.html')
if len(password) < 6:
flash('Password must be at least 6 characters long', 'danger')
return render_template('signup.html')
# Check if user already exists
existing_user = User.query.filter_by(email=email).first()
if existing_user:
flash('Email already registered. Please sign in.', 'warning')
return redirect(url_for('signin'))
# Create new user
new_user = User(email=email, full_name=full_name, role=role)
new_user.set_password(password)
try:
db.session.add(new_user)
db.session.commit()
flash('Account created successfully! Please sign in.', 'success')
return redirect(url_for('signin'))
except Exception as e:
db.session.rollback()
flash('An error occurred. Please try again.', 'danger')
print(f"Error creating user: {e}")
return render_template('signup.html')
return render_template('signup.html')
@app.route('/signin', methods=['GET', 'POST'])
def signin():
"""Sign in page"""
if current_user.is_authenticated:
return redirect(url_for('dashboard'))
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
remember = request.form.get('remember_me')
if not email or not password:
flash('Email and password are required', 'danger')
return render_template('signin.html')
# Find user in database
user = User.query.filter_by(email=email).first()
if user and user.check_password(password):
login_user(user, remember=bool(remember))
flash(f'Welcome back, {user.full_name}!', 'success')
# Redirect to next page or dashboard
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('dashboard'))
else:
flash('Invalid email or password', 'danger')
return render_template('signin.html')
return render_template('signin.html')
@app.route('/logout')
@login_required
def logout():
"""Logout user"""
logout_user()
flash('You have been logged out successfully', 'success')
return redirect(url_for('signin'))
@app.route('/dashboard')
def dashboard():
"""Main dashboard page - accessible to all, but shows different content for authenticated users"""
return render_template('dashboard_premium.html', user=current_user)
@app.route('/emi-calculator')
@login_required
def emi_calculator():
"""EMI Calculator page"""
return render_template('emi_calculator.html', user=current_user)
@app.route('/loan-eligibility')
@login_required
def loan_eligibility():
"""Loan Eligibility Calculator page"""
return render_template('loan_eligibility.html', user=current_user)
@app.route('/budget-calculator')
@login_required
def budget_calculator():
"""Budget Calculator page"""
return render_template('budget_calculator.html', user=current_user)
@app.route('/area-converter')
@login_required
def area_converter():
"""Area Unit Converter page"""
return render_template('area_converter.html', user=current_user)
@app.route('/contact', methods=['GET', 'POST'])
def contact():
"""Contact page"""
if request.method == 'POST':
name = request.form.get('name')
email = request.form.get('email')
phone = request.form.get('phone')
subject = request.form.get('subject')
message = request.form.get('message')
if all([name, email, phone, subject, message]):
# In production, save to database or send email
flash('Thank you! We will contact you soon.', 'success')
return redirect(url_for('contact'))
else:
flash('All fields are required', 'danger')
return render_template('contact.html', user=current_user)
@app.route('/price-prediction')
@login_required
def price_prediction():
"""Price prediction page - requires authentication"""
# Get unique locations from dataset
locations = df.groupby(['latitude', 'longitude']).first().reset_index()[['latitude', 'longitude']].head(50).to_dict('records')
return render_template('price_prediction.html', locations=locations, user=current_user)
@app.route('/api/predict', methods=['POST'])
@login_required
def api_predict():
"""API endpoint for price prediction"""
try:
data = request.json
# Extract features from request
area = float(data.get('area', 1000))
latitude = float(data.get('latitude', 28.6))
longitude = float(data.get('longitude', 77.4))
bedrooms = float(data.get('bedrooms', 2))
bathrooms = float(data.get('bathrooms', 2))
balcony = float(data.get('balcony', 1)) if data.get('balcony') else None
status = data.get('status')
neworold = data.get('neworold')
parking = float(data.get('parking', 0)) if data.get('parking') else None
furnished_status = data.get('furnished_status')
lift = float(data.get('lift', 0)) if data.get('lift') else None
type_of_building = data.get('type_of_building', 'Flat')
# Make prediction
predicted_price = predictor.predict_single(
area=area,
latitude=latitude,
longitude=longitude,
bedrooms=bedrooms,
bathrooms=bathrooms,
balcony=balcony,
status=status,
neworold=neworold,
parking=parking,
furnished_status=furnished_status,
lift=lift,
type_of_building=type_of_building
)
return jsonify({
'success': True,
'predicted_price': float(predicted_price),
'formatted_price': format_price(predicted_price)
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route('/api/locations')
@login_required
def api_locations():
"""Get available locations for dropdown"""
# Get unique locations with addresses
locations_df = df[['latitude', 'longitude', 'Address']].drop_duplicates().head(100)
locations = locations_df.to_dict('records')
return jsonify(locations)
@app.route('/api/heatmap-data')
@login_required
def api_heatmap_data():
"""Get data for heatmap visualization"""
# Sample data points for heatmap (latitude, longitude, price)
heatmap_data = df[['latitude', 'longitude', 'price']].dropna().head(500)
# Normalize prices for intensity
max_price = heatmap_data['price'].max()
heatmap_data['intensity'] = heatmap_data['price'] / max_price
data = heatmap_data.to_dict('records')
return jsonify(data)
@app.route('/api/search-addresses')
@login_required
def api_search_addresses():
"""Search addresses based on query"""
query = request.args.get('q', '').lower()
if not query or len(query) < 2:
return jsonify([])
# Get unique addresses from dataset
addresses = df[['Address', 'latitude', 'longitude']].drop_duplicates()
# Filter addresses that contain the query
filtered = addresses[addresses['Address'].str.lower().str.contains(query, na=False)]
# Limit to 10 results
results = filtered.head(10).to_dict('records')
return jsonify(results)
@app.route('/api/property/<int:property_id>')
@login_required
def api_property_details(property_id):
"""Get detailed property information"""
if property_id >= len(df):
return jsonify({'success': False, 'error': 'Property not found'}), 404
property_data = df.iloc[property_id].to_dict()
# Convert NaN to None for JSON serialization
property_data = {k: (None if pd.isna(v) else v) for k, v in property_data.items()}
return jsonify({
'success': True,
'property': property_data
})
@app.route('/api/filter-properties')
@login_required
def api_filter_properties():
"""Filter properties based on criteria"""
# Get filter parameters
min_price = request.args.get('min_price', type=float)
max_price = request.args.get('max_price', type=float)
bedrooms = request.args.get('bedrooms', type=int)
property_type = request.args.get('property_type', '')
location = request.args.get('location', '')
# Start with full dataset
filtered_df = df.copy()
# Apply filters
if min_price:
filtered_df = filtered_df[filtered_df['price'] >= min_price]
if max_price:
filtered_df = filtered_df[filtered_df['price'] <= max_price]
if bedrooms:
filtered_df = filtered_df[filtered_df['Bedrooms'] == bedrooms]
if property_type:
filtered_df = filtered_df[filtered_df['type_of_building'].str.contains(property_type, case=False, na=False)]
if location:
filtered_df = filtered_df[filtered_df['Address'].str.contains(location, case=False, na=False)]
# Get first 20 results
results = filtered_df.head(20).to_dict('records')
# Convert NaN to None
results = [{k: (None if pd.isna(v) else v) for k, v in prop.items()} for prop in results]
return jsonify({
'success': True,
'count': len(filtered_df),
'properties': results
})
@app.route('/api/calculate-emi', methods=['POST'])
@login_required
def api_calculate_emi():
"""Calculate EMI"""
try:
data = request.json
principal = float(data.get('principal', 5000000))
rate = float(data.get('rate', 8.5)) / 100 / 12 # Monthly rate
tenure = int(data.get('tenure', 20)) * 12 # Months
# EMI calculation formula
emi = principal * rate * ((1 + rate) ** tenure) / (((1 + rate) ** tenure) - 1)
total_amount = emi * tenure
total_interest = total_amount - principal
return jsonify({
'success': True,
'emi': round(emi, 2),
'total_amount': round(total_amount, 2),
'total_interest': round(total_interest, 2),
'principal': round(principal, 2)
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 400
@app.route('/map-view')
@login_required
def map_view():
"""Map view with heatmap"""
# Get lat/lng from query params if provided
lat = request.args.get('lat', 28.6139)
lng = request.args.get('lng', 77.2090)
zoom = request.args.get('zoom', 11)
return render_template('map_view.html', user=current_user, lat=lat, lng=lng, zoom=zoom)
def init_database():
"""Initialize database and create tables"""
with app.app_context():
db.create_all()
print("✅ Database tables created successfully!")
# Check if demo users already exist
if User.query.filter_by(email='demo@delhihouse.com').first() is None:
# Create demo buyer account
demo_buyer = User(
email='demo@delhihouse.com',
full_name='Demo Buyer',
role='buyer'
)
demo_buyer.set_password('demo123')
db.session.add(demo_buyer)
# Create demo seller account
demo_seller = User(
email='seller@delhihouse.com',
full_name='Demo Seller',
role='seller'
)
demo_seller.set_password('seller123')
db.session.add(demo_seller)
db.session.commit()
print("✅ Demo accounts created successfully!")
else:
print("ℹ️ Demo accounts already exist")
if __name__ == '__main__':
# Create templates and static folders if they don't exist
os.makedirs('templates', exist_ok=True)
os.makedirs('static/css', exist_ok=True)
os.makedirs('static/js', exist_ok=True)
os.makedirs('static/images', exist_ok=True)
# Initialize database
init_database()
print("="*80)
print(" AASHIYANA - AI-POWERED PROPERTY PLATFORM")
print("="*80)
print("\n🚀 Starting Flask server...")
print("\n📧 Demo Accounts:")
print(" Buyer: demo@homeai.com | Password: demo123")
print(" Seller: seller@homeai.com | Password: seller123")
print("\n🌐 Open in browser: http://localhost:5000")
print("="*80 + "\n")
# Get port from environment variable or default to 5000
port = int(os.getenv('PORT', 5000))
app.run(debug=False, host='0.0.0.0', port=port)