Spaces:
Sleeping
Sleeping
File size: 10,685 Bytes
e679d69 |
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 |
# flake8: noqa: E501
import json
import os
from typing import Optional, Type
import aiohttp
import requests
from lagent.actions.base_action import AsyncActionMixin, BaseAction, tool_api
from lagent.actions.parser import BaseParser, JsonParser
class BINGMap(BaseAction):
"""BING Map plugin for looking up map information."""
def __init__(
self,
key: Optional[str] = None,
description: Optional[dict] = None,
parser: Type[BaseParser] = JsonParser,
) -> None:
super().__init__(description, parser)
key = os.environ.get('BING_MAP_KEY', key)
if key is None:
raise ValueError(
'Please set BING Map API key either in the environment '
'as BING_MAP_KEY or pass it as `key` parameter.')
self.key = key
self.base_url = 'http://dev.virtualearth.net/REST/V1/'
@tool_api(explode_return=True)
def get_distance(self, start: str, end: str) -> dict:
"""Get the distance between two locations in km.
Args:
start (:class:`str`): The start location
end (:class:`str`): The end location
Returns:
:class:`dict`: distance information
* distance (str): the distance in km.
"""
# Request URL
url = self.base_url + 'Routes/Driving?o=json&wp.0=' + start + '&wp.1=' + end + '&key=' + self.key
# GET request
r = requests.get(url)
# TODO check request status?
data = json.loads(r.text)
# Extract route information
route = data['resourceSets'][0]['resources'][0]
# Extract distance in miles
distance = route['travelDistance']
return dict(distance=distance)
@tool_api(explode_return=True)
def get_route(self, start: str, end: str) -> dict:
"""Get the route between two locations in km.
Args:
start (:class:`str`): The start location
end (:class:`str`): The end location
Returns:
:class:`dict`: route information
* route (list): the route, a list of actions.
"""
# Request URL
url = self.base_url + 'Routes/Driving?o=json&wp.0=' + start + '&wp.1=' + end + '&key=' + self.key
# GET request
r = requests.get(url)
data = json.loads(r.text)
# Extract route information
route = data['resourceSets'][0]['resources'][0]
itinerary = route['routeLegs'][0]['itineraryItems']
# Extract route text information
route_text = []
for item in itinerary:
if 'instruction' in item:
route_text.append(item['instruction']['text'])
return dict(route=route_text)
@tool_api(explode_return=True)
def get_coordinates(self, location: str) -> dict:
"""Get the coordinates of a location.
Args:
location (:class:`str`): the location need to get coordinates.
Returns:
:class:`dict`: coordinates information
* latitude (float): the latitude of the location.
* longitude (float): the longitude of the location.
"""
url = self.base_url + 'Locations'
params = {'query': location, 'key': self.key}
response = requests.get(url, params=params)
json_data = response.json()
coordinates = json_data['resourceSets'][0]['resources'][0]['point'][
'coordinates']
return dict(latitude=coordinates[0], longitude=coordinates[1])
@tool_api(explode_return=True)
def search_nearby(self,
search_term: str,
places: str = 'unknown',
latitude: float = 0.0,
longitude: float = 0.0,
radius: int = 5000) -> dict:
"""Search for places nearby a location, within a given radius, and return the results into a list. You can use either the places name or the latitude and longitude.
Args:
search_term (:class:`str`): the place name.
places (:class:`str`): the name of the location. Defaults to ``'unknown'``.
latitude (:class:`float`): the latitude of the location. Defaults to ``0.0``.
longitude (:class:`float`): the longitude of the location. Defaults to ``0.0``.
radius (:class:`int`): radius in meters. Defaults to ``5000``.
Returns:
:class:`dict`: places information
* places (list): the list of places, each place is a dict with name and address, at most 5 places.
"""
url = self.base_url + 'LocalSearch'
if places != 'unknown':
pos = self.get_coordinates(**{'location': places})
latitude, longitude = pos[1]['latitude'], pos[1]['longitude']
# Build the request query string
params = {
'query': search_term,
'userLocation': f'{latitude},{longitude}',
'radius': radius,
'key': self.key
}
# Make the request
response = requests.get(url, params=params)
# Parse the response
response_data = json.loads(response.content)
# Get the results
results = response_data['resourceSets'][0]['resources']
addresses = []
for result in results:
name = result['name']
address = result['Address']['formattedAddress']
addresses.append(dict(name=name, address=address))
if len(addresses) == 5:
break
return dict(place=addresses)
class AsyncBINGMap(AsyncActionMixin, BINGMap):
"""BING Map plugin for looking up map information."""
@tool_api(explode_return=True)
async def get_distance(self, start: str, end: str) -> dict:
"""Get the distance between two locations in km.
Args:
start (:class:`str`): The start location
end (:class:`str`): The end location
Returns:
:class:`dict`: distance information
* distance (str): the distance in km.
"""
# Request URL
url = self.base_url + 'Routes/Driving?o=json&wp.0=' + start + '&wp.1=' + end + '&key=' + self.key
# GET request
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
# TODO check request status?
data = await resp.json()
# Extract route information
route = data['resourceSets'][0]['resources'][0]
# Extract distance in miles
distance = route['travelDistance']
return dict(distance=distance)
@tool_api(explode_return=True)
async def get_route(self, start: str, end: str) -> dict:
"""Get the route between two locations in km.
Args:
start (:class:`str`): The start location
end (:class:`str`): The end location
Returns:
:class:`dict`: route information
* route (list): the route, a list of actions.
"""
# Request URL
url = self.base_url + 'Routes/Driving?o=json&wp.0=' + start + '&wp.1=' + end + '&key=' + self.key
# GET request
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
data = await resp.json()
# Extract route information
route = data['resourceSets'][0]['resources'][0]
itinerary = route['routeLegs'][0]['itineraryItems']
# Extract route text information
route_text = []
for item in itinerary:
if 'instruction' in item:
route_text.append(item['instruction']['text'])
return dict(route=route_text)
@tool_api(explode_return=True)
async def get_coordinates(self, location: str) -> dict:
"""Get the coordinates of a location.
Args:
location (:class:`str`): the location need to get coordinates.
Returns:
:class:`dict`: coordinates information
* latitude (float): the latitude of the location.
* longitude (float): the longitude of the location.
"""
url = self.base_url + 'Locations'
params = {'query': location, 'key': self.key}
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as resp:
data = await resp.json()
coordinates = data['resourceSets'][0]['resources'][0]['point'][
'coordinates']
return dict(latitude=coordinates[0], longitude=coordinates[1])
@tool_api(explode_return=True)
async def search_nearby(self,
search_term: str,
places: str = 'unknown',
latitude: float = 0.0,
longitude: float = 0.0,
radius: int = 5000) -> dict:
"""Search for places nearby a location, within a given radius, and return the results into a list. You can use either the places name or the latitude and longitude.
Args:
search_term (:class:`str`): the place name.
places (:class:`str`): the name of the location. Defaults to ``'unknown'``.
latitude (:class:`float`): the latitude of the location. Defaults to ``0.0``.
longitude (:class:`float`): the longitude of the location. Defaults to ``0.0``.
radius (:class:`int`): radius in meters. Defaults to ``5000``.
Returns:
:class:`dict`: places information
* places (list): the list of places, each place is a dict with name and address, at most 5 places.
"""
url = self.base_url + 'LocalSearch'
if places != 'unknown':
pos = self.get_coordinates(**{'location': places})
latitude, longitude = pos[1]['latitude'], pos[1]['longitude']
# Build the request query string
params = {
'query': search_term,
'userLocation': f'{latitude},{longitude}',
'radius': radius,
'key': self.key
}
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as resp:
data = await resp.json()
results = data['resourceSets'][0]['resources']
addresses = []
for result in results:
name = result['name']
address = result['Address']['formattedAddress']
addresses.append(dict(name=name, address=address))
if len(addresses) == 5:
break
return dict(place=addresses)
|