-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai.py
More file actions
625 lines (551 loc) · 28.4 KB
/
ai.py
File metadata and controls
625 lines (551 loc) · 28.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
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
"""
ai.py — PathSeeker AI Layer v3
--------------------------------
Functions exported:
generate_chat_response(message, context, prefs)
classify_user_intent(message, lat, lon, radius, prefs)
plan_trip(from_place, to_place, preferences, days, saved_places)
"""
import os, json, math, requests
from datetime import datetime
from google import genai
from dotenv import load_dotenv
load_dotenv()
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
OPENTRIPMAP_API_KEY = os.getenv("OPENTRIPMAP_API_KEY", "")
GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
GROQ_MODEL = "llama-3.1-8b-instant"
OTM_BASE = "https://api.opentripmap.com/0.1/en/places"
client = genai.Client(api_key=GEMINI_API_KEY)
SEASON_MAP = {1:"winter",2:"winter",3:"summer",4:"summer",5:"summer",
6:"monsoon",7:"monsoon",8:"monsoon",9:"monsoon",
10:"winter",11:"winter",12:"winter"}
IDEAL_SEASON = {"waterfall":"monsoon","beach":"winter","trek":"winter",
"nature_reserve":"winter","park":"winter","fort":"winter",
"museum":"any","cafe":"any","temple":"any","place_of_worship":"any"}
INFRA_BASE = {"museum":75,"cafe":80,"restaurant":80,"park":65,"temple":70,
"place_of_worship":65,"fort":55,"waterfall":40,"beach":60,
"trek":35,"nature_reserve":40,"village":35,"viewpoint":50}
OSM_TAG_MAP = {
"temple": [("amenity","place_of_worship")],
"waterfall": [("waterway","waterfall"),("natural","waterfall")],
"park": [("leisure","park"),("leisure","garden")],
"museum": [("tourism","museum")],
"attraction": [("tourism","attraction")],
"fort": [("historic","fort"),("historic","castle")],
"beach": [("natural","beach")],
"cafe": [("amenity","cafe")],
"restaurant": [("amenity","restaurant")],
"viewpoint": [("tourism","viewpoint")],
"historic": [("historic","monument"),("historic","ruins")],
"nightclub": [("amenity","nightclub"),("amenity","bar"),("amenity","pub")],
"bar": [("amenity","bar"),("amenity","pub")],
}
OTM_KINDS_MAP = {
"temple":"religion","fort":"historic,fortifications","museum":"museums",
"waterfall":"natural,water","beach":"beaches","park":"parks,gardens_and_parks",
"viewpoint":"natural,interesting_places","attraction":"interesting_places",
"historic":"historic,archaeology","nightclub":"bars","bar":"bars",
"cafe":"cafes","restaurant":"restaurants",
}
LANG_INSTR = {
"en":"Write in warm, vivid English.",
"hi":"Write entirely in Hindi (Devanagari). Simple, conversational.",
"ta":"Write entirely in Tamil script. Simple, conversational.",
"te":"Write entirely in Telugu script.",
"kn":"Write entirely in Kannada script.",
"ml":"Write entirely in Malayalam script.",
}
# ══════════════════════════════════════════════════════════════════════
# 1. CHAT (Gemini, personalised with prefs)
# ══════════════════════════════════════════════════════════════════════
def generate_chat_response(user_message, context=None, prefs=None):
prefs = prefs or {}
pref_ctx = ""
if prefs:
pref_ctx = (f"\nUser preferences — transport: {prefs.get('transport','any')}, "
f"budget: {prefs.get('budget','mid')}, "
f"language: {prefs.get('language','en')}.")
prompt = f"""You are PathSeeker AI, a travel assistant specialising in hidden gems across India.
User location: {context}{pref_ctx}
Tailor your answer to the user's budget and transport preference.
Answer clearly and concisely.
User question: {user_message}"""
try:
r = client.models.generate_content(model="gemini-2.5-flash", contents=prompt)
return r.text.strip()
except Exception as e:
return f"AI Error: {str(e)}"
def chat_with_plan_context(user_message, plan=None, context=None, prefs=None):
"""
Plan-aware chat: understands the generated trip plan and can
suggest cheaper alternatives, modify itinerary, answer doubts.
"""
prefs = prefs or {}
plan = plan or {}
pref_ctx = ""
if prefs:
pref_ctx = (f"User budget: {prefs.get('budget','mid')}, "
f"transport preference: {prefs.get('transport','any')}.")
plan_ctx = ""
if plan:
plan_ctx = f"""
CURRENT TRIP PLAN:
- Route: {plan.get('from','')} → {plan.get('to','')}
- Days: {plan.get('days','')}
- Recommended transport: {plan.get('recommended_transport','')}
- Estimated total cost: ₹{plan.get('estimated_total_cost_inr',0):,}
- Cost breakdown: {json.dumps(plan.get('cost_breakdown',{}))}
- Transport options: {json.dumps(plan.get('transport_options',[]))}
- Best time: {plan.get('best_time_to_visit','')}
- Itinerary summary:
{chr(10).join([f" Day {d.get('day')}: {d.get('title','')}" for d in plan.get('itinerary',[])])}
"""
prompt = f"""You are PathSeeker AI, a smart travel assistant for India.
You have full context of the user's current trip plan.
{plan_ctx}
{pref_ctx}
Location context: {context}
Your capabilities:
1. Answer doubts about the trip (permits, safety, weather, best routes)
2. Suggest CHEAPER alternatives for cafes, hotels, restaurants with approximate prices
3. Modify parts of the plan (e.g. "skip Day 2 afternoon", "suggest budget hotel instead")
4. Compare transport costs and help pick the best option
5. Give precise local transport info (auto rates, local bus numbers, shared cabs)
Be specific with names, prices in INR, distances, and timings.
If suggesting cheaper options, give 2-3 concrete alternatives with approximate costs.
User question: {user_message}"""
try:
r = client.models.generate_content(model="gemini-2.5-flash", contents=prompt)
return r.text.strip()
except Exception as e:
return f"AI Error: {str(e)}"
# ══════════════════════════════════════════════════════════════════════
# 2. DISCOVER PIPELINE
# ══════════════════════════════════════════════════════════════════════
def classify_user_intent(user_message, lat=None, lon=None, radius=3000, prefs=None):
prefs = prefs or {}
intent = _extract_intent(user_message, prefs)
category = intent.get("category","attraction")
categories = intent.get("categories",[category])
if lat is None or lon is None:
return {"category":category,"places":[],"reply":"Location required."}
osm = _query_osm(lat, lon, radius, categories)
otm = _query_opentripmap(lat, lon, radius, categories)
all_places = _deduplicate(osm + otm, lat, lon)
if not all_places:
return {"category":category,"places":[],
"reply":f"No {category}s found within {radius//1000} km. Try a larger radius."}
scored = _score_all(all_places)
scored.sort(key=lambda x: x["comfort_score"], reverse=True)
top = scored[:8]
gems = _generate_narratives(top, intent, user_message)
return {"category":category,"places":gems,
"reply":_build_reply(gems, category, radius),
"intent":intent,"total_scanned":len(all_places)}
# ══════════════════════════════════════════════════════════════════════
# 3. TRIP PLANNER (new)
# ══════════════════════════════════════════════════════════════════════
TRANSPORT_INFO = {
"train": {
"emoji":"🚂","name":"Train",
"speed_kmh":80,"cost_per_km":0.8,
"note":"Book on IRCTC. Rajdhani/Shatabdi for faster routes."
},
"flight": {
"emoji":"✈️","name":"Flight",
"speed_kmh":700,"cost_per_km":6,
"note":"Check IndiGo, Air India, SpiceJet. Book 2+ weeks ahead."
},
"bus": {
"emoji":"🚌","name":"Bus",
"speed_kmh":55,"cost_per_km":0.5,
"note":"State KSRTC/TNSTC or private Volvo buses."
},
"car": {
"emoji":"🚗","name":"Self-drive / Cab",
"speed_kmh":60,"cost_per_km":2.5,
"note":"Ola/Uber outstation or self-drive. Factor in fuel & tolls."
},
"any": {
"emoji":"🗺️","name":"Best option",
"speed_kmh":80,"cost_per_km":1.5,
"note":"We'll recommend the best fit for distance & budget."
},
}
BUDGET_DAILY = {"budget":800, "mid":2000, "premium":5000} # INR per day per person
def plan_trip(from_place, to_place, preferences=None, days=2, saved_places=None):
"""
Build a complete personalised trip plan using Gemini.
Returns structured dict with transport options, cost, itinerary.
"""
prefs = preferences or {}
saved_places = saved_places or []
transport = prefs.get("transport","any")
budget_tier = prefs.get("budget","mid")
interests = prefs.get("interests",[])
language = prefs.get("language","en")
daily_budget = BUDGET_DAILY.get(budget_tier, 2000)
# Build transport recommendations block
transport_block = _build_transport_block(from_place, to_place, transport)
saved_ctx = ""
if saved_places:
saved_ctx = f"\nThe user has previously saved these places: {', '.join(saved_places[:6])}. Incorporate relevant ones."
interests_ctx = f"\nUser interests: {', '.join(interests)}." if interests else ""
prompt = f"""You are PathSeeker AI trip planner for India.
Plan a {days}-day trip from {from_place} to {to_place}.
USER PROFILE:
- Preferred transport: {transport}
- Budget tier: {budget_tier} (~₹{daily_budget}/person/day)
- Language preference: {language}{interests_ctx}{saved_ctx}
TRANSPORT ANALYSIS:
{transport_block}
IMPORTANT: For transport_options, be VERY PRECISE:
- For trains: include the train name, train number (e.g. 12345 Rajdhani Express), departure/arrival station full names, departure time, platform (if known), class available, and reservation process on IRCTC.
- For flights: include airline recommendations (IndiGo/Air India), approximate departure times, nearest airports with airport codes (e.g. MAA for Chennai), tip to arrive 2hrs early.
- For buses: include which state SRTC (e.g. KSRTC/TNSTC), Volvo vs ordinary, typical departure points (bus stand name), journey duration, whether AC/non-AC.
- For cars/cabs: mention Ola Outstation, Uber, specific highway/NH numbers to take, approximate toll costs, fuel cost estimate at current rates.
- LOCAL TRANSPORT in destination: include auto-rickshaw rates, local bus numbers if known, metro/share-cab options, typical cost from station/airport to city centre.
Return ONLY valid JSON in exactly this structure — no markdown, no extra text:
{{
"from": "{from_place}",
"to": "{to_place}",
"days": {days},
"transport_options": [
{{
"mode": "train",
"emoji": "🚂",
"train_name": "12345 Pandian Express",
"departure_station": "Chennai Egmore (MS)",
"arrival_station": "Madurai Junction (MDU)",
"departure_time": "21:40",
"arrival_time": "05:30+1",
"duration": "7 hrs 50 min",
"cost_inr": 850,
"cost_note": "Sleeper class. 2A: ₹2100, 3A: ₹1400",
"book_via": "IRCTC app or irctc.co.in — book 90 days in advance",
"local_note": "From Madurai station: auto to hotel ₹80–120",
"recommended": true
}}
],
"recommended_transport": "train",
"local_transport": {{
"auto_base_fare": "₹30 flag-off + ₹12/km",
"local_bus": "TNSTC routes connect major sites. Avg ₹15–40/trip.",
"share_cab": "shared cabs from bus stand to tourist spots: ~₹60–120",
"notes": "Negotiate auto fares in advance. Ola/Uber available in city."
}},
"estimated_total_cost_inr": 4500,
"cost_breakdown": {{
"transport": 1700,
"accommodation": 1800,
"food": 600,
"activities": 400
}},
"itinerary": [
{{
"day": 1,
"title": "Arrival & First Impressions",
"morning": "Arrive by train at 05:30. Take auto (₹100) to hotel near city centre. Check-in and rest.",
"afternoon": "Visit Meenakshi Amman Temple (open 5am-12:30pm & 4pm-9:30pm, entry free, camera ₹50). Auto from hotel ₹40.",
"evening": "Street food at Puthu Mandapam — try parotta ₹40, filter coffee ₹15. Walk to Gandhi Museum (free).",
"stay": "Hotel near temple area — e.g. Hotel Sree Devi (₹800–1200/night), book via MakeMyTrip",
"tips": "Buy temple entry ticket of Rs 50 online. Wear formals/traditional attire."
}}
],
"best_time_to_visit": "October to February",
"packing_tips": ["Light cotton clothes", "Comfortable walking shoes"],
"emergency_contacts": {{
"police": "100",
"tourist_helpline": "1363",
"nearest_hospital": "Ask at hotel"
}},
"personalised_note": "Based on your interest in history, we included..."
}}"""
try:
r = client.models.generate_content(model="gemini-2.5-flash", contents=prompt)
text = r.text.strip()
if "```" in text:
text = text.split("```")[1].lstrip("json").strip()
plan = json.loads(text)
plan["generated_by"] = "gemini"
return plan
except Exception as e:
# Structured fallback
return _fallback_plan(from_place, to_place, transport, days, daily_budget, str(e))
def _build_transport_block(from_place, to_place, preferred):
"""
Build a text summary of transport options to feed into the prompt.
Uses rough distance estimation via Nominatim geocoding if possible.
"""
options = []
for mode, info in TRANSPORT_INFO.items():
if mode == "any": continue
options.append(f"- {info['emoji']} {info['name']}: ~₹{info['cost_per_km']}/km, "
f"~{info['speed_kmh']}km/h. {info['note']}")
block = "\n".join(options)
if preferred != "any":
block += f"\n\nUser PREFERS: {preferred.upper()}. Prioritise this mode."
return block
def _fallback_plan(from_p, to_p, transport, days, daily_budget, err=""):
mode_info = TRANSPORT_INFO.get(transport, TRANSPORT_INFO["any"])
return {
"from": from_p,
"to": to_p,
"days": days,
"transport_options": [{
"mode": transport,
"emoji": mode_info["emoji"],
"duration": "Depends on distance",
"cost_inr": 0,
"cost_note": "Check current rates",
"book_via": "Local operator",
"recommended": True,
}],
"recommended_transport": transport,
"local_transport": {
"auto_base_fare": "₹30 + ₹12/km (approx)",
"local_bus": "Check local SRTC services",
"share_cab": "Available at major transit points",
"notes": "Negotiate fares before boarding."
},
"estimated_total_cost_inr": daily_budget * days,
"cost_breakdown": {
"transport": round(daily_budget * days * 0.35),
"accommodation": round(daily_budget * days * 0.40),
"food": round(daily_budget * days * 0.15),
"activities": round(daily_budget * days * 0.10),
},
"itinerary": [{"day":i+1,"title":f"Day {i+1}","morning":"TBD",
"afternoon":"TBD","evening":"TBD","stay":"TBD","tips":""}
for i in range(days)],
"best_time_to_visit": "October to February",
"packing_tips": ["Light cotton clothes","Comfortable walking shoes","Water bottle"],
"emergency_contacts": {"police":"100","tourist_helpline":"1363"},
"personalised_note": f"Could not generate AI plan ({err}). Basic structure provided.",
"generated_by": "fallback",
}
# ══════════════════════════════════════════════════════════════════════
# STAGE 1 — INTENT
# ══════════════════════════════════════════════════════════════════════
def _extract_intent(message, prefs=None):
prefs = prefs or {}
if GROQ_API_KEY:
return _groq_intent(message)
return _gemini_intent(message)
def _groq_intent(message):
system = """Extract travel intent. Return ONLY JSON:
{"category":"temple","categories":["temple"],"mood":"any","language":"en","budget":"any","season":"any"}
category must be: temple,waterfall,park,museum,attraction,fort,beach,cafe,restaurant,viewpoint,historic,nightclub,bar"""
try:
r = requests.post(GROQ_URL,
headers={"Authorization":f"Bearer {GROQ_API_KEY}","Content-Type":"application/json"},
json={"model":GROQ_MODEL,
"messages":[{"role":"system","content":system},{"role":"user","content":message}],
"temperature":0.1,"max_tokens":150},timeout=8)
r.raise_for_status()
text = r.json()["choices"][0]["message"]["content"].strip()
if "```" in text: text = text.split("```")[1].lstrip("json").strip()
return json.loads(text)
except Exception:
return _gemini_intent(message)
def _gemini_intent(message):
prompt = f"""Classify travel query. Return ONLY JSON:
{{"category":"temple","categories":["temple"],"mood":"any","language":"en","budget":"any","season":"any"}}
Valid: temple,waterfall,park,museum,attraction,fort,beach,cafe,restaurant,viewpoint,historic,nightclub,bar
Query: "{message}" """
try:
r = client.models.generate_content(model="gemini-2.5-flash", contents=prompt)
text = r.text.strip().replace("```json","").replace("```","").strip()
return json.loads(text)
except Exception:
return {"category":"attraction","categories":["attraction"],"mood":"any","language":"en"}
# ══════════════════════════════════════════════════════════════════════
# STAGE 2 — OSM + OTM
# ══════════════════════════════════════════════════════════════════════
def _query_osm(lat, lon, radius, categories):
tag_pairs = []
for cat in categories:
tag_pairs.extend(OSM_TAG_MAP.get(cat,[("tourism","attraction")]))
tag_pairs = list(dict.fromkeys(tag_pairs))
parts = [f'node["{k}"="{v}"](around:{radius},{lat},{lon});way["{k}"="{v}"](around:{radius},{lat},{lon});'
for k,v in tag_pairs]
query = f"[out:json][timeout:20];\n(\n{''.join(parts)}\n);\nout body center;"
try:
r = requests.post("https://overpass-api.de/api/interpreter",data={"data":query},timeout=25)
r.raise_for_status()
elements = r.json().get("elements",[])
except Exception:
return []
places, seen = [], set()
for el in elements:
tags = el.get("tags",{})
name = tags.get("name","").strip()
if not name or name.lower() in seen: continue
seen.add(name.lower())
p_lat = el.get("lat") or el.get("center",{}).get("lat")
p_lon = el.get("lon") or el.get("center",{}).get("lon")
if not p_lat: continue
places.append({"name":name,"latitude":p_lat,"longitude":p_lon,
"distance_km":_hav(lat,lon,p_lat,p_lon),
"category":_detect_cat(tags),"source":"osm",
"opening_hours":tags.get("opening_hours",""),
"website":tags.get("website","")})
places.sort(key=lambda x:x["distance_km"])
return places[:40]
def _query_opentripmap(lat, lon, radius, categories):
if not OPENTRIPMAP_API_KEY: return []
kinds = ",".join({k.strip() for cat in categories
for k in OTM_KINDS_MAP.get(cat,"interesting_places").split(",")}
| {"interesting_places"})
try:
r = requests.get(f"{OTM_BASE}/radius",
params={"radius":radius,"lon":lon,"lat":lat,"kinds":kinds,
"limit":40,"rate":"2","format":"json","apikey":OPENTRIPMAP_API_KEY},timeout=12)
r.raise_for_status()
raw = r.json()
except Exception:
return []
places, seen = [], set()
for p in raw:
name = p.get("name","").strip()
if not name or len(name)<3 or name.lower() in seen: continue
seen.add(name.lower())
p_lat = p.get("point",{}).get("lat")
p_lon = p.get("point",{}).get("lon")
if not p_lat: continue
places.append({"name":name,"latitude":p_lat,"longitude":p_lon,
"distance_km":_hav(lat,lon,p_lat,p_lon),
"category":_kinds_to_cat(p.get("kinds","")),
"source":"opentripmap","opening_hours":"","website":""})
places.sort(key=lambda x:x["distance_km"])
return places[:40]
def _deduplicate(places, ulat, ulon, dedup_m=80):
kept, seen = [], set()
prio = {"osm":2,"opentripmap":1}
for poi in places:
key = _norm(poi["name"])
if key in seen: continue
dupe = False
for i, ex in enumerate(kept):
if _hav(poi["latitude"],poi["longitude"],ex["latitude"],ex["longitude"])*1000 <= dedup_m:
if prio.get(poi["source"],0) > prio.get(ex["source"],0):
kept[i]=poi; seen.discard(_norm(ex["name"])); seen.add(key)
dupe=True; break
if not dupe: kept.append(poi); seen.add(key)
kept.sort(key=lambda x:x["distance_km"])
return kept[:60]
# ══════════════════════════════════════════════════════════════════════
# STAGE 3 — COMFORT SCORE
# ══════════════════════════════════════════════════════════════════════
def _score_all(places):
season = SEASON_MAP.get(datetime.now().month,"winter")
weights={"safety":0.25,"infrastructure":0.20,"accessibility":0.20,"seasonal":0.20,"amenities":0.15}
for p in places:
scores={"safety":_s_safety(p),"infrastructure":_s_infra(p),
"accessibility":_s_access(p),"seasonal":_s_seasonal(p,season),"amenities":60.0}
comfort=sum(scores[f]*weights[f] for f in weights)
p["comfort_score"]=round(comfort,1)
p["score_breakdown"]={k:round(v,1) for k,v in scores.items()}
p["comfort_tier"]=("high" if comfort>=80 else "moderate" if comfort>=60 else "low")
return places
def _s_safety(p): return 72.0 if p.get("source")=="osm" else 62.0
def _s_infra(p):
base=float(INFRA_BASE.get(p.get("category","place"),50))
if p.get("opening_hours"): base=min(100,base+5)
if p.get("website"): base=min(100,base+5)
return base
def _s_access(p):
d=p.get("distance_km",5)
return 95 if d<=0.5 else 85 if d<=1 else 75 if d<=2 else 65 if d<=3 else 55 if d<=5 else 40
def _s_seasonal(p,season):
ideal=IDEAL_SEASON.get(p.get("category","place"),"any")
return 75.0 if ideal=="any" else (95.0 if ideal==season else 40.0)
# ══════════════════════════════════════════════════════════════════════
# STAGE 4 — NARRATIVES
# ══════════════════════════════════════════════════════════════════════
def _generate_narratives(places, intent, prompt):
if GROQ_API_KEY: return _groq_narratives(places, intent, prompt)
return _gemini_narratives(places, intent)
def _groq_narratives(places, intent, original_prompt):
language = intent.get("language","en")
lang_instr = LANG_INSTR.get(language, LANG_INSTR["en"])
system=(f"You are PathSeeker's travel narrator for Indian hidden gems. "
f"Write 2-sentence vivid descriptions. {lang_instr} "
f"Number them 1. 2. 3. Never say 'hidden gem' or 'must-visit'.")
places_text="\n".join(f"Place {i+1}: {p['name']} | {p['category']} | {p['distance_km']}km | Comfort:{p['comfort_score']}"
for i,p in enumerate(places))
try:
r=requests.post(GROQ_URL,
headers={"Authorization":f"Bearer {GROQ_API_KEY}","Content-Type":"application/json"},
json={"model":GROQ_MODEL,
"messages":[{"role":"system","content":system},
{"role":"user","content":f'User: "{original_prompt}"\n{places_text}'}],
"temperature":0.75,"max_tokens":800},timeout=18)
r.raise_for_status()
raw=r.json()["choices"][0]["message"]["content"].strip()
narratives=_parse_narratives(raw,len(places))
except Exception:
narratives=[_fb_narrative(p) for p in places]
for i,p in enumerate(places):
p["narrative"]=narratives[i] if i<len(narratives) else _fb_narrative(p)
return places
def _gemini_narratives(places, intent):
for p in places:
try:
r=client.models.generate_content(model="gemini-2.5-flash",
contents=f"One vivid sentence about {p['name']} ({p['category']}) in India. Specific. No 'hidden gem'.")
p["narrative"]=r.text.strip()
except Exception:
p["narrative"]=_fb_narrative(p)
return places
def _parse_narratives(text, count):
lines=text.split("\n"); narratives,current=[],[]
for line in lines:
s=line.strip()
if s and s[0].isdigit() and len(s)>2 and s[1] in ".)":
if current: narratives.append(" ".join(current).strip())
current=[s[2:].strip()]
elif s and current: current.append(s)
if current: narratives.append(" ".join(current).strip())
return narratives[:count]
def _fb_narrative(p):
tier={"high":"Easy to visit","moderate":"Some planning needed","low":"For adventurous travellers"}
return f"{p['name']} is a {p['category']} {p['distance_km']}km away. {tier.get(p.get('comfort_tier','moderate'),'')}."
def _build_reply(gems, category, radius):
if not gems: return f"No {category}s found within {radius//1000} km."
em={"high":"✅","moderate":"⚠️","low":"🔴"}
lines=[f"Found {len(gems)} {category}(s) within {radius//1000} km:\n"]
for p in gems:
lines.append(f"{em.get(p.get('comfort_tier','moderate'),'⚠️')} {p['name']} — {p['distance_km']}km | Comfort: {p['comfort_score']}/100")
if p.get("narrative"): lines.append(f" {p['narrative'][:120]}")
return "\n".join(lines)
# ══════════════════════════════════════════════════════════════════════
# UTILITIES
# ══════════════════════════════════════════════════════════════════════
def _hav(lat1,lon1,lat2,lon2):
R=6371
d1=math.radians(float(lat2)-float(lat1)); d2=math.radians(float(lon2)-float(lon1))
a=math.sin(d1/2)**2+math.cos(math.radians(float(lat1)))*math.cos(math.radians(float(lat2)))*math.sin(d2/2)**2
return round(R*2*math.atan2(math.sqrt(a),math.sqrt(1-a)),2)
def _detect_cat(tags):
for k in ["amenity","leisure","tourism","historic","natural","waterway"]:
if v:=tags.get(k): return v
return "place"
def _kinds_to_cat(kinds):
k=kinds.lower()
if "religion" in k: return "temple"
if "fort" in k: return "fort"
if "museum" in k: return "museum"
if "water" in k: return "waterfall"
if "beach" in k: return "beach"
if "mountain" in k: return "viewpoint"
if "historic" in k: return "historic"
if "bar" in k: return "bar"
if "restaurant" in k: return "restaurant"
if "cafe" in k: return "cafe"
if "garden" in k: return "park"
return "attraction"
def _norm(name):
return "".join(c.lower() for c in name if c.isalnum() or c.isspace()).strip()