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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import folium
|
3 |
+
from streamlit_folium import folium_static
|
4 |
+
import requests
|
5 |
+
import json
|
6 |
+
from datetime import datetime
|
7 |
+
|
8 |
+
# API Keys
|
9 |
+
GROQ_API_KEY = "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"
|
10 |
+
HERE_API_KEY = "Z-INy7MKiZwfH6mAchEr0QPFaYuuo5QKqGxSnHxcKTY"
|
11 |
+
|
12 |
+
# Initialize session states
|
13 |
+
if 'chat_history' not in st.session_state:
|
14 |
+
st.session_state.chat_history = []
|
15 |
+
if 'user_input' not in st.session_state:
|
16 |
+
st.session_state.user_input = ""
|
17 |
+
if 'location_history' not in st.session_state:
|
18 |
+
st.session_state.location_history = []
|
19 |
+
if 'current_map' not in st.session_state:
|
20 |
+
st.session_state.current_map = None
|
21 |
+
|
22 |
+
# Page configuration
|
23 |
+
st.set_page_config(
|
24 |
+
page_title="TrafficWise AI Planner",
|
25 |
+
page_icon="π¦",
|
26 |
+
layout="wide"
|
27 |
+
)
|
28 |
+
|
29 |
+
def geocode_address(address):
|
30 |
+
"""Convert address to coordinates using HERE Geocoding API"""
|
31 |
+
url = f"https://geocode.search.hereapi.com/v1/geocode"
|
32 |
+
params = {
|
33 |
+
'q': address,
|
34 |
+
'apiKey': HERE_API_KEY
|
35 |
+
}
|
36 |
+
try:
|
37 |
+
response = requests.get(url, params=params)
|
38 |
+
response.raise_for_status()
|
39 |
+
data = response.json()
|
40 |
+
if data['items']:
|
41 |
+
position = data['items'][0]['position']
|
42 |
+
address_label = data['items'][0].get('address', {}).get('label', address)
|
43 |
+
return position['lat'], position['lng'], address_label
|
44 |
+
return None, None, None
|
45 |
+
except Exception as e:
|
46 |
+
st.error(f"Geocoding error: {str(e)}")
|
47 |
+
return None, None, None
|
48 |
+
|
49 |
+
def get_traffic_incidents(lat, lon, radius=1000):
|
50 |
+
"""Fetch traffic incidents from HERE API"""
|
51 |
+
url = "https://data.traffic.hereapi.com/v7/incidents"
|
52 |
+
params = {
|
53 |
+
'apiKey': HERE_API_KEY,
|
54 |
+
'in': f"circle:{lat},{lon};r={radius}",
|
55 |
+
'locationReferencing': 'polyline'
|
56 |
+
}
|
57 |
+
try:
|
58 |
+
response = requests.get(url, params=params)
|
59 |
+
response.raise_for_status()
|
60 |
+
return response.json()
|
61 |
+
except Exception as e:
|
62 |
+
# st.warning(f"Note: Traffic data may be limited in this area")
|
63 |
+
return None
|
64 |
+
|
65 |
+
def generate_traffic_map(center_lat=30.3753, center_lng=69.3451):
|
66 |
+
"""Generate map with traffic data"""
|
67 |
+
m = folium.Map(location=[center_lat, center_lng], zoom_start=13)
|
68 |
+
|
69 |
+
# Add marker for searched location
|
70 |
+
folium.Marker(
|
71 |
+
[center_lat, center_lng],
|
72 |
+
popup="Selected Location",
|
73 |
+
icon=folium.Icon(color='red', icon='info-sign')
|
74 |
+
).add_to(m)
|
75 |
+
|
76 |
+
# Add traffic incidents if available
|
77 |
+
incidents = get_traffic_incidents(center_lat, center_lng)
|
78 |
+
if incidents and 'results' in incidents:
|
79 |
+
for incident in incidents['results']:
|
80 |
+
try:
|
81 |
+
# Get incident details
|
82 |
+
description = incident.get('description', {}).get('value', 'Traffic Incident')
|
83 |
+
severity = incident.get('severity', {}).get('value', 'minor')
|
84 |
+
|
85 |
+
# Color based on severity
|
86 |
+
color = {
|
87 |
+
'minor': 'green',
|
88 |
+
'moderate': 'orange',
|
89 |
+
'major': 'red'
|
90 |
+
}.get(severity, 'blue')
|
91 |
+
|
92 |
+
# Get location
|
93 |
+
location = incident.get('location', {})
|
94 |
+
if 'polyline' in location:
|
95 |
+
coordinates = []
|
96 |
+
points = location['polyline'].get('points', [])
|
97 |
+
for point in points:
|
98 |
+
lat = point.get('lat')
|
99 |
+
lng = point.get('lng')
|
100 |
+
if lat and lng:
|
101 |
+
coordinates.append([lat, lng])
|
102 |
+
|
103 |
+
if coordinates:
|
104 |
+
# Add incident to map
|
105 |
+
folium.PolyLine(
|
106 |
+
coordinates,
|
107 |
+
color=color,
|
108 |
+
weight=4,
|
109 |
+
opacity=0.8,
|
110 |
+
tooltip=description
|
111 |
+
).add_to(m)
|
112 |
+
|
113 |
+
# Add marker at start of incident
|
114 |
+
folium.CircleMarker(
|
115 |
+
coordinates[0],
|
116 |
+
radius=8,
|
117 |
+
color=color,
|
118 |
+
fill=True,
|
119 |
+
popup=description
|
120 |
+
).add_to(m)
|
121 |
+
|
122 |
+
except Exception as e:
|
123 |
+
continue
|
124 |
+
|
125 |
+
return m
|
126 |
+
|
127 |
+
# Sidebar configuration
|
128 |
+
st.sidebar.title("π¦ TrafficWise AI Planner")
|
129 |
+
st.sidebar.markdown("Your AI Assistant for Traffic & Urban Planning")
|
130 |
+
|
131 |
+
# Previous locations section
|
132 |
+
if st.session_state.location_history:
|
133 |
+
st.sidebar.subheader("Recent Searches")
|
134 |
+
for idx, (loc, timestamp) in enumerate(reversed(st.session_state.location_history[-5:])):
|
135 |
+
if st.sidebar.button(f"π {loc} ({timestamp})", key=f"prev_loc_{idx}"):
|
136 |
+
coordinates = geocode_address(loc)
|
137 |
+
if coordinates[0]:
|
138 |
+
st.session_state.current_map = generate_traffic_map(coordinates[0], coordinates[1])
|
139 |
+
|
140 |
+
# Location input
|
141 |
+
st.sidebar.subheader("Search Location")
|
142 |
+
location_input = st.sidebar.text_input(
|
143 |
+
"Enter city or address:",
|
144 |
+
key="location_input",
|
145 |
+
placeholder="e.g., London, New York, Tokyo"
|
146 |
+
)
|
147 |
+
|
148 |
+
# Map container
|
149 |
+
map_container = st.sidebar.container()
|
150 |
+
map_container.subheader("Traffic Map")
|
151 |
+
|
152 |
+
if location_input:
|
153 |
+
lat, lng, address_label = geocode_address(location_input)
|
154 |
+
if lat and lng:
|
155 |
+
# Update location history
|
156 |
+
timestamp = datetime.now().strftime("%H:%M")
|
157 |
+
if address_label not in [loc for loc, _ in st.session_state.location_history]:
|
158 |
+
st.session_state.location_history.append((address_label, timestamp))
|
159 |
+
# Generate and store map
|
160 |
+
st.session_state.current_map = generate_traffic_map(lat, lng)
|
161 |
+
st.sidebar.success(f"π Showing Map for: {address_label}")
|
162 |
+
else:
|
163 |
+
st.sidebar.error("Location not found. Please try another address.")
|
164 |
+
|
165 |
+
# Display current map
|
166 |
+
with map_container:
|
167 |
+
if st.session_state.current_map:
|
168 |
+
folium_static(st.session_state.current_map, width=300, height=400)
|
169 |
+
else:
|
170 |
+
folium_static(generate_traffic_map(), width=300, height=400)
|
171 |
+
|
172 |
+
# Temperature slider
|
173 |
+
temperature = st.sidebar.slider(
|
174 |
+
"AI Response Variation:",
|
175 |
+
min_value=0.0,
|
176 |
+
max_value=1.0,
|
177 |
+
value=0.7,
|
178 |
+
step=0.1,
|
179 |
+
help="Higher values provide more varied suggestions, lower values offer more consistent advice"
|
180 |
+
)
|
181 |
+
|
182 |
+
# Main chat interface
|
183 |
+
st.title("π¦ TrafficWise AI Planner")
|
184 |
+
st.markdown("""
|
185 |
+
### Your AI Assistant for:
|
186 |
+
- π Traffic Route Optimization
|
187 |
+
- π Urban Congestion Solutions
|
188 |
+
- π¦ Traffic Flow Analysis
|
189 |
+
- π£ Infrastructure Planning
|
190 |
+
""")
|
191 |
+
|
192 |
+
def chat_with_traffic_planner(user_message, temperature):
|
193 |
+
"""Send a message to Groq API's model and return the response."""
|
194 |
+
enhanced_prompt = f"""As a traffic and urban planning expert, help with the following question
|
195 |
+
about traffic routes, urban congestion, or city planning: {user_message}
|
196 |
+
"""
|
197 |
+
headers = {
|
198 |
+
"Authorization": f"Bearer {GROQ_API_KEY}",
|
199 |
+
"Content-Type": "application/json"
|
200 |
+
}
|
201 |
+
payload = {
|
202 |
+
"model": "llama3-8b-8192",
|
203 |
+
"messages": [{"role": "user", "content": enhanced_prompt}],
|
204 |
+
"temperature": temperature
|
205 |
+
}
|
206 |
+
try:
|
207 |
+
response = requests.post(
|
208 |
+
"https://api.groq.com/openai/v1/chat/completions",
|
209 |
+
headers=headers,
|
210 |
+
json=payload,
|
211 |
+
timeout=30
|
212 |
+
)
|
213 |
+
response.raise_for_status()
|
214 |
+
return response.json()["choices"][0]["message"]["content"]
|
215 |
+
except requests.exceptions.RequestException as e:
|
216 |
+
return f"Error: Unable to connect to the API - {str(e)}"
|
217 |
+
except Exception as e:
|
218 |
+
return f"Error: {str(e)}"
|
219 |
+
|
220 |
+
def clear_chat():
|
221 |
+
st.session_state.chat_history = []
|
222 |
+
|
223 |
+
for message in st.session_state.chat_history:
|
224 |
+
role = message["role"]
|
225 |
+
content = message["content"]
|
226 |
+
st.markdown(f"π€ You:** {content}" if role == "user" else f"π¦ TrafficWise:** {content}")
|
227 |
+
st.markdown("---")
|
228 |
+
|
229 |
+
def submit_message():
|
230 |
+
if st.session_state.user_input:
|
231 |
+
user_message = st.session_state.user_input
|
232 |
+
st.session_state.chat_history.append({"role": "user", "content": user_message})
|
233 |
+
with st.spinner('Analyzing traffic patterns...'):
|
234 |
+
bot_response = chat_with_traffic_planner(user_message, temperature)
|
235 |
+
st.session_state.chat_history.append({"role": "assistant", "content": bot_response})
|
236 |
+
st.session_state.user_input = ""
|
237 |
+
|
238 |
+
st.text_input(
|
239 |
+
"Ask about traffic routes, urban planning, or congestion solutions...",
|
240 |
+
key="user_input",
|
241 |
+
on_change=submit_message,
|
242 |
+
placeholder="Example: What are the best routes to reduce congestion during peak hours?"
|
243 |
+
)
|
244 |
+
|
245 |
+
if st.button("π Clear Chat"):
|
246 |
+
clear_chat()
|
247 |
+
|
248 |
+
st.sidebar.markdown("""
|
249 |
+
### π Traffic Guidelines:
|
250 |
+
1. π Peak Hours
|
251 |
+
- Morning: 7-9 AM
|
252 |
+
- Evening: 4-7 PM
|
253 |
+
|
254 |
+
2. πΈ Safety First
|
255 |
+
- Follow speed limits
|
256 |
+
- Watch for pedestrians
|
257 |
+
|
258 |
+
3. π Eco-Friendly Options
|
259 |
+
- Consider public transport
|
260 |
+
- Use carpooling
|
261 |
+
|
262 |
+
4. π¦ Smart Route Planning
|
263 |
+
- Check traffic updates
|
264 |
+
- Use alternative routes
|
265 |
+
|
266 |
+
5. π± Stay Informed
|
267 |
+
- Monitor traffic alerts
|
268 |
+
- Check weather conditions
|
269 |
+
""")
|