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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
|
3 |
+
from geopy.geocoders import Nominatim
|
4 |
+
|
5 |
+
|
6 |
+
###################################################
|
7 |
+
# Functions we want to articulate (APIs calls): ###
|
8 |
+
###################################################
|
9 |
+
|
10 |
+
########################################################################################
|
11 |
+
# Functions called in the articulated functions (not directly called by the model): ###
|
12 |
+
########################################################################################
|
13 |
+
|
14 |
+
geolocator = Nominatim(user_agent="MyApp")
|
15 |
+
|
16 |
+
def find_precise_place(lat, lon):
|
17 |
+
location = geolocator.reverse(str(lat) +", " + str(lon))
|
18 |
+
return location.raw.get('display_name', {})
|
19 |
+
|
20 |
+
def find_coordinates(address):
|
21 |
+
coord = geolocator.geocode(address)
|
22 |
+
lat = coord.latitude
|
23 |
+
lon = coord.longitude
|
24 |
+
return(lat,lon)
|
25 |
+
|
26 |
+
|
27 |
+
def check_city_coordinates(lat = "", lon = "", city = "", **kwargs):
|
28 |
+
"""
|
29 |
+
:param lat: latitude
|
30 |
+
:param lon: longitude
|
31 |
+
:param city: name of the city
|
32 |
+
|
33 |
+
Checks if the coordinates correspond to the city, if not update the coordinate to correspond to the city
|
34 |
+
"""
|
35 |
+
if lat != "0" and lon != "0":
|
36 |
+
reverse = partial(geolocator.reverse, language="en")
|
37 |
+
location = reverse(f"{lat}, {lon}")
|
38 |
+
address = location.raw.get('address', {})
|
39 |
+
city = address.get('city') or address.get('town') or address.get('village') or address.get('county')
|
40 |
+
else :
|
41 |
+
reverse = partial(geolocator.reverse, language="en")
|
42 |
+
location = reverse(f"{lat}, {lon}")
|
43 |
+
address = location.raw.get('address', {})
|
44 |
+
city_name = address.get('city') or address.get('town') or address.get('village') or address.get('county')
|
45 |
+
if city_name is None :
|
46 |
+
city_name = 'not_found'
|
47 |
+
print(city_name)
|
48 |
+
if city_name.lower() != city.lower():
|
49 |
+
coord = geolocator.geocode(city )
|
50 |
+
if coord is None:
|
51 |
+
coord = geolocator.geocode(city)
|
52 |
+
lat = coord.latitude
|
53 |
+
lon = coord.longitude
|
54 |
+
return lat, lon, city
|
55 |
+
|
56 |
+
# Select coordinates at equal distance, including the last one
|
57 |
+
def select_equally_spaced_coordinates(coords, number_of_points=10):
|
58 |
+
n = len(coords)
|
59 |
+
selected_coords = []
|
60 |
+
interval = max((n - 1) / (number_of_points - 1), 1)
|
61 |
+
for i in range(number_of_points):
|
62 |
+
# Calculate the index, ensuring it doesn't exceed the bounds of the list
|
63 |
+
index = int(round(i * interval))
|
64 |
+
if index < n:
|
65 |
+
selected_coords.append(coords[index])
|
66 |
+
return selected_coords
|
67 |
+
|
68 |
+
def find_points_of_interest(lat="0", lon="0", city="", type_of_poi="restaurant", **kwargs):
|
69 |
+
"""
|
70 |
+
Return some of the closest points of interest for a specific location and type of point of interest. The more parameters there are, the more precise.
|
71 |
+
:param lat (string): latitude
|
72 |
+
:param lon (string): longitude
|
73 |
+
:param city (string): Required. city
|
74 |
+
:param type_of_poi (string): Required. type of point of interest depending on what the user wants to do.
|
75 |
+
"""
|
76 |
+
lat, lon, city = check_city_coordinates(lat,lon,city)
|
77 |
+
|
78 |
+
r = requests.get(f'https://api.tomtom.com/search/2/search/{type_of_poi}'
|
79 |
+
'.json?key={0}&lat={1}&lon={2}&radius=10000&idxSet=POI&limit=100'.format(
|
80 |
+
TOMTOM_KEY,
|
81 |
+
lat,
|
82 |
+
lon
|
83 |
+
))
|
84 |
+
|
85 |
+
# Parse JSON from the response
|
86 |
+
data = r.json()
|
87 |
+
#print(data)
|
88 |
+
# Extract results
|
89 |
+
results = data['results']
|
90 |
+
|
91 |
+
# Sort the results based on distance
|
92 |
+
sorted_results = sorted(results, key=lambda x: x['dist'])
|
93 |
+
#print(sorted_results)
|
94 |
+
|
95 |
+
# Format and limit to top 5 results
|
96 |
+
formatted_results = [
|
97 |
+
f"The {type_of_poi} {result['poi']['name']} is {int(result['dist'])} meters away"
|
98 |
+
for result in sorted_results[:5]
|
99 |
+
]
|
100 |
+
|
101 |
+
|
102 |
+
return ". ".join(formatted_results)
|
103 |
+
|
104 |
+
def find_route(lat_depart="0", lon_depart="0", city_depart="", address_destination="", depart_time ="", **kwargs):
|
105 |
+
"""
|
106 |
+
Return the distance and the estimated time to go to a specific destination from the current place, at a specified depart time.
|
107 |
+
:param lat_depart (string): latitude of depart
|
108 |
+
:param lon_depart (string): longitude of depart
|
109 |
+
:param city_depart (string): Required. city of depart
|
110 |
+
:param address_destination (string): Required. The destination
|
111 |
+
:param depart_time (string): departure hour, in the format '08:00:20'.
|
112 |
+
"""
|
113 |
+
print(address_destination)
|
114 |
+
date = "2025-03-29T"
|
115 |
+
departure_time = '2024-02-01T' + depart_time
|
116 |
+
lat, lon, city = check_city_coordinates(lat_depart,lon_depart,city_depart)
|
117 |
+
lat_dest, lon_dest = find_coordinates(address_destination)
|
118 |
+
#print(lat_dest, lon_dest)
|
119 |
+
|
120 |
+
#print(departure_time)
|
121 |
+
|
122 |
+
r = requests.get('https://api.tomtom.com/routing/1/calculateRoute/{0},{1}:{2},{3}/json?key={4}&departAt={5}'.format(
|
123 |
+
lat_depart,
|
124 |
+
lon_depart,
|
125 |
+
lat_dest,
|
126 |
+
lon_dest,
|
127 |
+
TOMTOM_KEY,
|
128 |
+
departure_time
|
129 |
+
))
|
130 |
+
|
131 |
+
# Parse JSON from the response
|
132 |
+
data = r.json()
|
133 |
+
#print(data)
|
134 |
+
|
135 |
+
#print(data)
|
136 |
+
|
137 |
+
result = data['routes'][0]['summary']
|
138 |
+
|
139 |
+
# Calculate distance in kilometers (1 meter = 0.001 kilometers)
|
140 |
+
distance_km = result['lengthInMeters'] * 0.001
|
141 |
+
|
142 |
+
# Calculate travel time in minutes (1 second = 1/60 minutes)
|
143 |
+
time_minutes = result['travelTimeInSeconds'] / 60
|
144 |
+
if time_minutes < 60:
|
145 |
+
time_display = f"{time_minutes:.0f} minutes"
|
146 |
+
else:
|
147 |
+
hours = int(time_minutes / 60)
|
148 |
+
minutes = int(time_minutes % 60)
|
149 |
+
time_display = f"{hours} hours" + (f" and {minutes} minutes" if minutes > 0 else "")
|
150 |
+
|
151 |
+
# Extract arrival time from the JSON structure
|
152 |
+
arrival_time_str = result['arrivalTime']
|
153 |
+
|
154 |
+
# Convert string to datetime object
|
155 |
+
arrival_time = datetime.fromisoformat(arrival_time_str)
|
156 |
+
|
157 |
+
# Extract and display the arrival hour in HH:MM format
|
158 |
+
arrival_hour_display = arrival_time.strftime("%H:%M")
|
159 |
+
|
160 |
+
|
161 |
+
# return the distance and time
|
162 |
+
return(f"The route to go to {address_destination} is {distance_km:.2f} km and {time_display}. Leaving now, the arrival time is estimated at {arrival_hour_display} " )
|
163 |
+
|
164 |
+
|
165 |
+
# Sort the results based on distance
|
166 |
+
#sorted_results = sorted(results, key=lambda x: x['dist'])
|
167 |
+
|
168 |
+
#return ". ".join(formatted_results)
|
169 |
+
|
170 |
+
|
171 |
+
def search_along_route(latitude_depart, longitude_depart, city_destination, type_of_poi):
|
172 |
+
"""
|
173 |
+
Return some of the closest points of interest along the route from the depart point, specified by its coordinates and a city destination.
|
174 |
+
:param latitude_depart (string): Required. Latitude of depart location
|
175 |
+
:param longitude_depart (string): Required. Longitude of depart location
|
176 |
+
:param city_destination (string): Required. City destination
|
177 |
+
:param type_of_poi (string): Required. type of point of interest depending on what the user wants to do.
|
178 |
+
"""
|
179 |
+
|
180 |
+
lat_dest, lon_dest = find_coordinates(city_destination)
|
181 |
+
print(lat_dest)
|
182 |
+
|
183 |
+
r = requests.get('https://api.tomtom.com/routing/1/calculateRoute/{0},{1}:{2},{3}/json?key={4}'.format(
|
184 |
+
latitude_depart,
|
185 |
+
longitude_depart,
|
186 |
+
lat_dest,
|
187 |
+
lon_dest,
|
188 |
+
TOMTOM_KEY
|
189 |
+
))
|
190 |
+
|
191 |
+
coord_route = select_equally_spaced_coordinates(r.json()['routes'][0]['legs'][0]['points'])
|
192 |
+
|
193 |
+
# The API endpoint for searching along a route
|
194 |
+
url = f'https://api.tomtom.com/search/2/searchAlongRoute/{type_of_poi}.json?key={TOMTOM_KEY}&maxDetourTime=700&limit=20&sortBy=detourTime'
|
195 |
+
|
196 |
+
# The data payload
|
197 |
+
payload = {
|
198 |
+
"route": {
|
199 |
+
"points": [
|
200 |
+
{"lat": float(latitude_depart), "lon": float(longitude_depart)},
|
201 |
+
{"lat": float(coord_route[1]['latitude']), "lon": float(coord_route[1]['longitude'])},
|
202 |
+
{"lat": float(coord_route[2]['latitude']), "lon": float(coord_route[2]['longitude'])},
|
203 |
+
{"lat": float(coord_route[3]['latitude']), "lon": float(coord_route[3]['longitude'])},
|
204 |
+
{"lat": float(coord_route[4]['latitude']), "lon": float(coord_route[4]['longitude'])},
|
205 |
+
{"lat": float(coord_route[5]['latitude']), "lon": float(coord_route[5]['longitude'])},
|
206 |
+
{"lat": float(coord_route[6]['latitude']), "lon": float(coord_route[6]['longitude'])},
|
207 |
+
{"lat": float(coord_route[7]['latitude']), "lon": float(coord_route[7]['longitude'])},
|
208 |
+
{"lat": float(coord_route[8]['latitude']), "lon": float(coord_route[8]['longitude'])},
|
209 |
+
{"lat": float(lat_dest), "lon": float(lon_dest)},
|
210 |
+
]
|
211 |
+
}
|
212 |
+
}
|
213 |
+
|
214 |
+
# Make the POST request
|
215 |
+
response = requests.post(url, json=payload)
|
216 |
+
|
217 |
+
# Check if the request was successful
|
218 |
+
if response.status_code == 200:
|
219 |
+
# Parse the JSON response
|
220 |
+
data = response.json()
|
221 |
+
print(json.dumps(data, indent=4))
|
222 |
+
else:
|
223 |
+
print('Failed to retrieve data:', response.status_code)
|
224 |
+
answer = ""
|
225 |
+
for result in data['results']:
|
226 |
+
name = result['poi']['name']
|
227 |
+
address = result['address']['freeformAddress']
|
228 |
+
detour_time = result['detourTime']
|
229 |
+
answer = answer + f" \nAlong the route to {city_destination}, there is the {name} at {address} that would represent a detour of {int(detour_time/60)} minutes."
|
230 |
+
|
231 |
+
return answer
|
232 |
+
|
233 |
+
|
234 |
+
#current weather API
|
235 |
+
def get_weather(city_name:str= "", **kwargs):
|
236 |
+
"""
|
237 |
+
Returns the CURRENT weather in a specified city.
|
238 |
+
Args:
|
239 |
+
city_name (string) : Required. The name of the city.
|
240 |
+
"""
|
241 |
+
# The endpoint URL provided by WeatherAPI
|
242 |
+
url = f"http://api.weatherapi.com/v1/current.json?key={WEATHER_API_KEY}&q={city_name}&aqi=no"
|
243 |
+
|
244 |
+
# Make the API request
|
245 |
+
response = requests.get(url)
|
246 |
+
|
247 |
+
if response.status_code == 200:
|
248 |
+
# Parse the JSON response
|
249 |
+
weather_data = response.json()
|
250 |
+
|
251 |
+
# Extracting the necessary pieces of data
|
252 |
+
location = weather_data['location']['name']
|
253 |
+
region = weather_data['location']['region']
|
254 |
+
country = weather_data['location']['country']
|
255 |
+
time = weather_data['location']['localtime']
|
256 |
+
temperature_c = weather_data['current']['temp_c']
|
257 |
+
condition_text = weather_data['current']['condition']['text']
|
258 |
+
wind_mph = weather_data['current']['wind_mph']
|
259 |
+
humidity = weather_data['current']['humidity']
|
260 |
+
feelslike_c = weather_data['current']['feelslike_c']
|
261 |
+
|
262 |
+
# Formulate the sentences
|
263 |
+
weather_sentences = (
|
264 |
+
f"The current weather in {location}, {region}, {country} is {condition_text} "
|
265 |
+
f"with a temperature of {temperature_c}°C that feels like {feelslike_c}°C. "
|
266 |
+
f"Humidity is at {humidity}%. "
|
267 |
+
f"Wind speed is {wind_mph} mph."
|
268 |
+
)
|
269 |
+
return weather_sentences
|
270 |
+
else:
|
271 |
+
# Handle errors
|
272 |
+
return f"Failed to get weather data: {response.status_code}, {response.text}"
|
273 |
+
|
274 |
+
|
275 |
+
|
276 |
+
#weather forecast API
|
277 |
+
def get_forecast(city_name:str= "", when = 0, **kwargs):
|
278 |
+
"""
|
279 |
+
Returns the weather forecast in a specified number of days for a specified city .
|
280 |
+
Args:
|
281 |
+
city_name (string) : Required. The name of the city.
|
282 |
+
when (int) : Required. in number of days (until the day for which we want to know the forecast) (example: tomorrow is 1, in two days is 2, etc.)
|
283 |
+
"""
|
284 |
+
#print(when)
|
285 |
+
when +=1
|
286 |
+
# The endpoint URL provided by WeatherAPI
|
287 |
+
url = f"http://api.weatherapi.com/v1/forecast.json?key={WEATHER_API_KEY}&q={city_name}&days={str(when)}&aqi=no"
|
288 |
+
|
289 |
+
|
290 |
+
# Make the API request
|
291 |
+
response = requests.get(url)
|
292 |
+
|
293 |
+
if response.status_code == 200:
|
294 |
+
# Parse the JSON response
|
295 |
+
data = response.json()
|
296 |
+
|
297 |
+
# Initialize an empty string to hold our result
|
298 |
+
forecast_sentences = ""
|
299 |
+
|
300 |
+
# Extract city information
|
301 |
+
location = data.get('location', {})
|
302 |
+
city_name = location.get('name', 'the specified location')
|
303 |
+
|
304 |
+
#print(data)
|
305 |
+
|
306 |
+
|
307 |
+
# Extract the forecast days
|
308 |
+
forecast_days = data.get('forecast', {}).get('forecastday', [])[when-1:]
|
309 |
+
#number = 0
|
310 |
+
|
311 |
+
#print (forecast_days)
|
312 |
+
|
313 |
+
for day in forecast_days:
|
314 |
+
date = day.get('date', 'a specific day')
|
315 |
+
conditions = day.get('day', {}).get('condition', {}).get('text', 'weather conditions')
|
316 |
+
max_temp_c = day.get('day', {}).get('maxtemp_c', 'N/A')
|
317 |
+
min_temp_c = day.get('day', {}).get('mintemp_c', 'N/A')
|
318 |
+
chance_of_rain = day.get('day', {}).get('daily_chance_of_rain', 'N/A')
|
319 |
+
|
320 |
+
if when == 1:
|
321 |
+
number_str = 'today'
|
322 |
+
elif when == 2:
|
323 |
+
number_str = 'tomorrow'
|
324 |
+
else:
|
325 |
+
number_str = f'in {when-1} days'
|
326 |
+
|
327 |
+
# Generate a sentence for the day's forecast
|
328 |
+
forecast_sentence = f"On {date} ({number_str}) in {city_name}, the weather will be {conditions} with a high of {max_temp_c}°C and a low of {min_temp_c}°C. There's a {chance_of_rain}% chance of rain. "
|
329 |
+
|
330 |
+
#number = number + 1
|
331 |
+
# Add the sentence to the result
|
332 |
+
forecast_sentences += forecast_sentence
|
333 |
+
return forecast_sentences
|
334 |
+
else:
|
335 |
+
# Handle errors
|
336 |
+
print( f"Failed to get weather data: {response.status_code}, {response.text}")
|
337 |
+
return f'error {response.status_code}'
|
338 |
+
|
339 |
+
|
car_assistant_slim.ipynb
CHANGED
The diff for this file is too large to render.
See raw diff
|
|
requirements.txt
CHANGED
@@ -13,4 +13,5 @@ numpy
|
|
13 |
openai-whisper
|
14 |
geopy
|
15 |
langchain
|
16 |
-
text_generation
|
|
|
|
13 |
openai-whisper
|
14 |
geopy
|
15 |
langchain
|
16 |
+
text_generation
|
17 |
+
python-dotenv
|