-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
552 lines (485 loc) · 21.7 KB
/
app.py
File metadata and controls
552 lines (485 loc) · 21.7 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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
"""
app.py — PathSeeker v4
-----------------------
Auth, per-user DB, saved places, preferences, trip planner, geocode,
community hub, plan-aware chatbot, offline data export.
"""
from flask import Flask, render_template, jsonify, request, session
import requests, math, time, sqlite3, json, hashlib, os, secrets
from dotenv import load_dotenv
from ai import generate_chat_response, classify_user_intent, plan_trip, chat_with_plan_context
from weather import get_weather
load_dotenv()
app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY", secrets.token_hex(32))
DB_PATH = "pathseeker.db"
CACHE = {}
CACHE_TTL = 300
# ── DB ─────────────────────────────────────────────────────────────────────────
def get_db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def init_db():
conn = get_db()
conn.executescript("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS preferences (
user_id INTEGER PRIMARY KEY REFERENCES users(id),
transport TEXT DEFAULT 'any',
budget TEXT DEFAULT 'mid',
interests TEXT DEFAULT '[]',
language TEXT DEFAULT 'en',
home_city TEXT DEFAULT '',
updated_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS saved_places (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER REFERENCES users(id),
name TEXT NOT NULL,
latitude REAL NOT NULL,
longitude REAL NOT NULL,
category TEXT DEFAULT '',
comfort_score REAL DEFAULT 0,
narrative TEXT DEFAULT '',
note TEXT DEFAULT '',
status TEXT DEFAULT 'saved',
saved_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS trips (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER REFERENCES users(id),
title TEXT NOT NULL,
from_place TEXT,
to_place TEXT,
transport TEXT DEFAULT 'any',
plan_json TEXT DEFAULT '{}',
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS communities (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT DEFAULT '',
category TEXT DEFAULT 'general',
created_by INTEGER REFERENCES users(id),
member_count INTEGER DEFAULT 1,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS community_members (
community_id INTEGER REFERENCES communities(id),
user_id INTEGER REFERENCES users(id),
joined_at TEXT DEFAULT (datetime('now')),
PRIMARY KEY (community_id, user_id)
);
CREATE TABLE IF NOT EXISTS community_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
community_id INTEGER REFERENCES communities(id),
user_id INTEGER REFERENCES users(id),
user_name TEXT NOT NULL,
content TEXT NOT NULL,
image_url TEXT DEFAULT '',
likes INTEGER DEFAULT 0,
created_at TEXT DEFAULT (datetime('now'))
);
""")
conn.commit(); conn.close()
def hash_pw(pw): return hashlib.sha256(pw.encode()).hexdigest()
def uid(): return session.get("user_id")
def need_login():
if not uid(): return jsonify({"error":"Not logged in"}), 401
return None
def haversine(lat1, lon1, lat2, lon2):
R = 6371
dlat = math.radians(float(lat2)-float(lat1))
dlon = math.radians(float(lon2)-float(lon1))
a = math.sin(dlat/2)**2 + math.cos(math.radians(float(lat1)))*math.cos(math.radians(float(lat2)))*math.sin(dlon/2)**2
return round(R*2*math.atan2(math.sqrt(a),math.sqrt(1-a)), 2)
def get_user_prefs(user_id):
conn = get_db()
row = conn.execute("SELECT * FROM preferences WHERE user_id=?", (user_id,)).fetchone()
conn.close()
if not row: return {"transport":"any","budget":"mid","interests":[],"language":"en","home_city":""}
return {"transport":row["transport"],"budget":row["budget"],
"interests":json.loads(row["interests"] or "[]"),
"language":row["language"],"home_city":row["home_city"]}
# ── PAGES ──────────────────────────────────────────────────────────────────────
@app.route("/")
def home():
return render_template("map.html",
user_id=uid() or 0,
user_name=session.get("user_name",""))
# ── AUTH ───────────────────────────────────────────────────────────────────────
@app.route("/api/auth/register", methods=["POST"])
def register():
d = request.json or {}
name = d.get("name","").strip()
email = d.get("email","").strip().lower()
pw = d.get("password","")
if not name or not email or not pw:
return jsonify({"error":"All fields required"}), 400
if len(pw) < 6:
return jsonify({"error":"Password must be 6+ characters"}), 400
conn = get_db()
try:
conn.execute("INSERT INTO users (name,email,password) VALUES (?,?,?)",
(name, email, hash_pw(pw)))
conn.commit()
row = conn.execute("SELECT id FROM users WHERE email=?", (email,)).fetchone()
conn.execute("INSERT OR IGNORE INTO preferences (user_id) VALUES (?)", (row["id"],))
conn.commit()
session["user_id"] = row["id"]
session["user_name"] = name
return jsonify({"ok":True,"name":name,"user_id":row["id"]})
except sqlite3.IntegrityError:
return jsonify({"error":"Email already registered"}), 409
finally:
conn.close()
@app.route("/api/auth/login", methods=["POST"])
def login():
d = request.json or {}
email = d.get("email","").strip().lower()
pw = d.get("password","")
conn = get_db()
row = conn.execute("SELECT id,name FROM users WHERE email=? AND password=?",
(email, hash_pw(pw))).fetchone()
conn.close()
if not row: return jsonify({"error":"Invalid email or password"}), 401
session["user_id"] = row["id"]
session["user_name"] = row["name"]
return jsonify({"ok":True,"name":row["name"],"user_id":row["id"]})
@app.route("/api/auth/logout", methods=["POST"])
def logout():
session.clear()
return jsonify({"ok":True})
@app.route("/api/auth/me")
def me():
u = uid()
if not u: return jsonify({"logged_in":False})
conn = get_db()
row = conn.execute("SELECT name,email FROM users WHERE id=?", (u,)).fetchone()
conn.close()
return jsonify({"logged_in":True,"user_id":u,"name":row["name"],"email":row["email"]})
# ── PREFERENCES ────────────────────────────────────────────────────────────────
@app.route("/api/preferences", methods=["GET"])
def get_prefs():
e = need_login()
if e: return e
return jsonify(get_user_prefs(uid()))
@app.route("/api/preferences", methods=["POST"])
def save_prefs():
e = need_login()
if e: return e
d = request.json or {}
conn = get_db()
conn.execute("""INSERT INTO preferences (user_id,transport,budget,interests,language,home_city,updated_at)
VALUES (?,?,?,?,?,?,datetime('now'))
ON CONFLICT(user_id) DO UPDATE SET
transport=excluded.transport,budget=excluded.budget,
interests=excluded.interests,language=excluded.language,
home_city=excluded.home_city,updated_at=excluded.updated_at""",
(uid(), d.get("transport","any"), d.get("budget","mid"),
json.dumps(d.get("interests",[])), d.get("language","en"),
d.get("home_city","")))
conn.commit(); conn.close()
return jsonify({"ok":True})
# ── SAVED PLACES ───────────────────────────────────────────────────────────────
@app.route("/api/saved", methods=["GET"])
def get_saved():
e = need_login()
if e: return e
conn = get_db()
rows = conn.execute("SELECT * FROM saved_places WHERE user_id=? ORDER BY saved_at DESC",
(uid(),)).fetchall()
conn.close()
return jsonify([dict(r) for r in rows])
@app.route("/api/saved", methods=["POST"])
def save_place():
e = need_login()
if e: return e
d = request.json or {}
if not d.get("name") or d.get("latitude") is None:
return jsonify({"error":"name and latitude required"}), 400
conn = get_db()
cur = conn.execute("""INSERT INTO saved_places
(user_id,name,latitude,longitude,category,comfort_score,narrative,note,status)
VALUES (?,?,?,?,?,?,?,?,?)""",
(uid(), d["name"], d["latitude"], d["longitude"],
d.get("category",""), d.get("comfort_score",0),
d.get("narrative",""), d.get("note",""), d.get("status","saved")))
conn.commit()
new_id = cur.lastrowid
conn.close()
return jsonify({"ok":True,"id":new_id})
@app.route("/api/saved/<int:pid>", methods=["DELETE"])
def delete_saved(pid):
e = need_login()
if e: return e
conn = get_db()
conn.execute("DELETE FROM saved_places WHERE id=? AND user_id=?", (pid, uid()))
conn.commit(); conn.close()
return jsonify({"ok":True})
@app.route("/api/saved/<int:pid>", methods=["PATCH"])
def update_saved(pid):
e = need_login()
if e: return e
d = request.json or {}
conn = get_db()
conn.execute("UPDATE saved_places SET note=?,status=? WHERE id=? AND user_id=?",
(d.get("note",""), d.get("status","saved"), pid, uid()))
conn.commit(); conn.close()
return jsonify({"ok":True})
# ── GEOCODE ────────────────────────────────────────────────────────────────────
@app.route("/api/geocode")
def geocode():
q = request.args.get("q","").strip()
if not q: return jsonify({"error":"Query required"}), 400
cache_key = "geo:" + q.lower()
if cache_key in CACHE:
data, ts = CACHE[cache_key]
if time.time()-ts < 3600: return jsonify(data)
try:
r = requests.get("https://nominatim.openstreetmap.org/search",
params={"q":q,"format":"json","limit":5,"addressdetails":1},
headers={"User-Agent":"PathSeekerApp/3.0"}, timeout=10)
data = [{"name":x.get("display_name","")[:80],"lat":float(x["lat"]),
"lon":float(x["lon"]),"type":x.get("type","")} for x in r.json()]
CACHE[cache_key] = (data, time.time())
return jsonify(data)
except Exception as e:
return jsonify({"error":str(e)}), 500
# ── TRIP PLANNER ───────────────────────────────────────────────────────────────
@app.route("/api/trip-plan", methods=["POST"])
def trip_plan():
e = need_login()
if e: return e
d = request.json or {}
from_place = d.get("from","").strip()
to_place = d.get("to","").strip()
if not from_place or not to_place:
return jsonify({"error":"from and to required"}), 400
prefs = get_user_prefs(uid())
if d.get("transport"): prefs["transport"] = d["transport"]
if d.get("budget"): prefs["budget"] = d["budget"]
if d.get("interests"): prefs["interests"] = d["interests"]
conn = get_db()
saved_rows = conn.execute(
"SELECT name,category FROM saved_places WHERE user_id=? LIMIT 10", (uid(),)
).fetchall()
conn.close()
saved_names = [r["name"] for r in saved_rows]
plan = plan_trip(from_place=from_place, to_place=to_place,
preferences=prefs, days=int(d.get("days",2)),
saved_places=saved_names)
conn = get_db()
conn.execute("INSERT INTO trips (user_id,title,from_place,to_place,transport,plan_json) VALUES (?,?,?,?,?,?)",
(uid(), f"{from_place} → {to_place}", from_place, to_place,
prefs.get("transport","any"), json.dumps(plan)))
conn.commit(); conn.close()
return jsonify(plan)
@app.route("/api/trips", methods=["GET"])
def get_trips():
e = need_login()
if e: return e
conn = get_db()
rows = conn.execute(
"SELECT id,title,from_place,to_place,transport,created_at FROM trips WHERE user_id=? ORDER BY created_at DESC LIMIT 10",
(uid(),)).fetchall()
conn.close()
return jsonify([dict(r) for r in rows])
# ── OSM / WEATHER / CHAT / AI-MAP ─────────────────────────────────────────────
@app.route("/api/places")
def get_places():
lat=request.args.get("lat"); lon=request.args.get("lon")
category=request.args.get("category","attraction"); radius=request.args.get("radius",5000)
if not lat or not lon: return jsonify({"error":"Location required"}),400
ck = f"{lat}-{lon}-{category}-{radius}"
if ck in CACHE:
data,ts=CACHE[ck]
if time.time()-ts<CACHE_TTL: return jsonify(data)
tag_map={"temple":'"amenity"="place_of_worship"',"waterfall":'"waterway"="waterfall"',
"park":'"leisure"="park"',"museum":'"tourism"="museum"',
"attraction":'"tourism"="attraction"',"fort":'"historic"="fort"',
"beach":'"natural"="beach"',"cafe":'"amenity"="cafe"',
"restaurant":'"amenity"="restaurant"',"viewpoint":'"tourism"="viewpoint"',
"bar":'"amenity"="bar"',"nightclub":'"amenity"="nightclub"'}
tf = tag_map.get(category,'"tourism"="attraction"')
query = f'[out:json];node[{tf}](around:{radius},{lat},{lon});out;'
try:
r=requests.get("https://overpass-api.de/api/interpreter",params={"data":query},
headers={"User-Agent":"PathSeekerApp/3.0"},timeout=25)
places=[]
for el in r.json().get("elements",[]):
places.append({"name":el.get("tags",{}).get("name","Unknown"),
"latitude":el["lat"],"longitude":el["lon"],
"distance_km":haversine(lat,lon,el["lat"],el["lon"])})
places.sort(key=lambda x:x["distance_km"])
CACHE[ck]=(places,time.time())
return jsonify(places)
except Exception as e: return jsonify({"error":str(e)}),500
@app.route("/api/weather")
def weather():
lat=request.args.get("lat"); lon=request.args.get("lon")
if not lat or not lon: return jsonify({"error":"Location required"}),400
return jsonify(get_weather(lat,lon))
@app.route("/api/chat", methods=["POST"])
def chat():
d=request.json or {}
msg=d.get("message"); loc=d.get("location")
if not msg: return jsonify({"error":"Message required"}),400
prefs = get_user_prefs(uid()) if uid() else {}
reply = generate_chat_response(msg, context=loc, prefs=prefs)
return jsonify({"reply":reply})
@app.route("/api/ai-map", methods=["POST"])
def ai_map():
d=request.json or {}
message=d.get("message"); lat=d.get("lat"); lon=d.get("lon"); radius=d.get("radius",3000)
if not message or lat is None or lon is None:
return jsonify({"error":"Missing required data"}),400
if "1 km" in message: radius=1000
elif "2 km" in message: radius=2000
elif "5 km" in message: radius=5000
elif "10 km" in message: radius=10000
prefs = get_user_prefs(uid()) if uid() else {}
try:
result=classify_user_intent(message,lat=lat,lon=lon,radius=radius,prefs=prefs)
return jsonify({"places":result.get("places",[]),"reply":result.get("reply",""),
"category":result.get("category",""),"intent":result.get("intent",{}),
"total_scanned":result.get("total_scanned",0)})
except Exception as e: return jsonify({"error":str(e)}),500
# ── PLAN-AWARE CHAT ────────────────────────────────────────────────────────────
@app.route("/api/chat/plan", methods=["POST"])
def chat_plan():
"""Chat that knows the current trip plan and can suggest modifications."""
d = request.json or {}
msg = d.get("message","").strip()
plan = d.get("plan", {}) # the full plan JSON from the front-end
loc = d.get("location","")
if not msg:
return jsonify({"error":"Message required"}), 400
prefs = get_user_prefs(uid()) if uid() else {}
reply = chat_with_plan_context(msg, plan=plan, context=loc, prefs=prefs)
return jsonify({"reply": reply})
# ── OFFLINE TRIP DATA ──────────────────────────────────────────────────────────
@app.route("/api/trips/<int:tid>/offline", methods=["GET"])
def trip_offline(tid):
"""Return full trip JSON for offline caching."""
e = need_login()
if e: return e
conn = get_db()
row = conn.execute(
"SELECT * FROM trips WHERE id=? AND user_id=?", (tid, uid())
).fetchone()
conn.close()
if not row:
return jsonify({"error": "Trip not found"}), 404
plan = json.loads(row["plan_json"] or "{}")
return jsonify({
"id": row["id"],
"title": row["title"],
"from_place": row["from_place"],
"to_place": row["to_place"],
"transport": row["transport"],
"created_at": row["created_at"],
"plan": plan,
"offline_saved_at": time.strftime("%Y-%m-%d %H:%M:%S")
})
# ── COMMUNITY ──────────────────────────────────────────────────────────────────
@app.route("/api/communities", methods=["GET"])
def list_communities():
conn = get_db()
rows = conn.execute("""
SELECT c.*, u.name as creator_name,
CASE WHEN cm.user_id IS NOT NULL THEN 1 ELSE 0 END as is_member
FROM communities c
LEFT JOIN users u ON c.created_by = u.id
LEFT JOIN community_members cm ON cm.community_id=c.id AND cm.user_id=?
ORDER BY c.member_count DESC, c.created_at DESC
""", (uid() or 0,)).fetchall()
conn.close()
return jsonify([dict(r) for r in rows])
@app.route("/api/communities", methods=["POST"])
def create_community():
e = need_login()
if e: return e
d = request.json or {}
name = d.get("name","").strip()
if not name:
return jsonify({"error": "Community name required"}), 400
conn = get_db()
try:
cur = conn.execute(
"INSERT INTO communities (name,description,category,created_by) VALUES (?,?,?,?)",
(name, d.get("description",""), d.get("category","general"), uid())
)
cid = cur.lastrowid
conn.execute("INSERT INTO community_members (community_id,user_id) VALUES (?,?)", (cid, uid()))
conn.commit()
return jsonify({"ok": True, "id": cid})
except Exception as ex:
return jsonify({"error": str(ex)}), 500
finally:
conn.close()
@app.route("/api/communities/<int:cid>/join", methods=["POST"])
def join_community(cid):
e = need_login()
if e: return e
conn = get_db()
try:
conn.execute("INSERT OR IGNORE INTO community_members (community_id,user_id) VALUES (?,?)", (cid, uid()))
conn.execute("UPDATE communities SET member_count = (SELECT COUNT(*) FROM community_members WHERE community_id=?) WHERE id=?", (cid, cid))
conn.commit()
return jsonify({"ok": True})
finally:
conn.close()
@app.route("/api/communities/<int:cid>/leave", methods=["POST"])
def leave_community(cid):
e = need_login()
if e: return e
conn = get_db()
try:
conn.execute("DELETE FROM community_members WHERE community_id=? AND user_id=?", (cid, uid()))
conn.execute("UPDATE communities SET member_count = MAX(0,(SELECT COUNT(*) FROM community_members WHERE community_id=?)) WHERE id=?", (cid, cid))
conn.commit()
return jsonify({"ok": True})
finally:
conn.close()
@app.route("/api/communities/<int:cid>/posts", methods=["GET"])
def get_posts(cid):
conn = get_db()
rows = conn.execute(
"SELECT * FROM community_posts WHERE community_id=? ORDER BY created_at DESC LIMIT 50", (cid,)
).fetchall()
conn.close()
return jsonify([dict(r) for r in rows])
@app.route("/api/communities/<int:cid>/posts", methods=["POST"])
def create_post(cid):
e = need_login()
if e: return e
d = request.json or {}
content = d.get("content","").strip()
if not content:
return jsonify({"error": "Content required"}), 400
conn = get_db()
row = conn.execute("SELECT name FROM users WHERE id=?", (uid(),)).fetchone()
uname = row["name"] if row else "User"
conn.execute(
"INSERT INTO community_posts (community_id,user_id,user_name,content) VALUES (?,?,?,?)",
(cid, uid(), uname, content)
)
conn.commit(); conn.close()
return jsonify({"ok": True})
@app.route("/api/communities/<int:cid>/posts/<int:pid>/like", methods=["POST"])
def like_post(pid, cid):
conn = get_db()
conn.execute("UPDATE community_posts SET likes=likes+1 WHERE id=?", (pid,))
conn.commit(); conn.close()
return jsonify({"ok": True})
if __name__ == "__main__":
init_db()
app.run(debug=True)