Update google_places.py
Browse files- google_places.py +154 -154
google_places.py
CHANGED
|
@@ -1,154 +1,154 @@
|
|
| 1 |
-
from dotenv import load_dotenv
|
| 2 |
-
import os
|
| 3 |
-
import googlemaps
|
| 4 |
-
import re
|
| 5 |
-
import gradio as gr
|
| 6 |
-
from datetime import datetime
|
| 7 |
-
|
| 8 |
-
# Load environment variables and initialize Google Maps client
|
| 9 |
-
dotenv_path = os.getenv('DOTENV_PATH', None)
|
| 10 |
-
if dotenv_path:
|
| 11 |
-
load_dotenv(dotenv_path)
|
| 12 |
-
else:
|
| 13 |
-
load_dotenv()
|
| 14 |
-
|
| 15 |
-
api_key = os.getenv("GOOGLE_API_KEY")
|
| 16 |
-
if not api_key:
|
| 17 |
-
raise EnvironmentError("GOOGLE_API_KEY not found in environment variables.")
|
| 18 |
-
|
| 19 |
-
gmaps = googlemaps.Client(key=api_key)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def get_places(trip_type: str, location: str) -> list[str]:
|
| 23 |
-
"""
|
| 24 |
-
Fetches up to 5 popular tourist attractions matching the trip_type in the given location.
|
| 25 |
-
"""
|
| 26 |
-
query = f"{trip_type} places in {location}"
|
| 27 |
-
results = gmaps.places(query=query, type="tourist_attraction")
|
| 28 |
-
places = results.get("results", [])[:5]
|
| 29 |
-
return [place.get("name") for place in places]
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
def get_restaurants(location: str, prefs: str) -> list[str]:
|
| 33 |
-
"""
|
| 34 |
-
Fetches up to 3 restaurants near the given location matching the user preferences.
|
| 35 |
-
"""
|
| 36 |
-
query = f"{prefs} restaurants near {location}"
|
| 37 |
-
results = gmaps.places(query=query, type="restaurant")
|
| 38 |
-
restaurants = results.get("results", [])[:3]
|
| 39 |
-
return [r.get("name") for r in restaurants]
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
def get_directions(
|
| 43 |
-
source: str,
|
| 44 |
-
destination: str,
|
| 45 |
-
mode: str,
|
| 46 |
-
departure_time: str,
|
| 47 |
-
waypoints: str = ""
|
| 48 |
-
) -> str:
|
| 49 |
-
"""
|
| 50 |
-
Returns a Markdown-formatted string with step-by-step directions and a static map URL.
|
| 51 |
-
|
| 52 |
-
Args:
|
| 53 |
-
source: Starting address or place name.
|
| 54 |
-
destination: Ending address or place name.
|
| 55 |
-
mode: Transport mode: driving, walking, bicycling, or transit.
|
| 56 |
-
departure_time: Trip start time in "YYYY-MM-DD HH:MM" format.
|
| 57 |
-
waypoints: Optional comma-separated list of waypoints.
|
| 58 |
-
|
| 59 |
-
Returns:
|
| 60 |
-
A single Markdown string summarizing the route or an error message.
|
| 61 |
-
"""
|
| 62 |
-
# Parse departure time
|
| 63 |
-
try:
|
| 64 |
-
dt = datetime.strptime(departure_time.strip(), "%Y-%m-%d %H:%M")
|
| 65 |
-
except ValueError:
|
| 66 |
-
return (
|
| 67 |
-
"**⚠️ Invalid time format.** Please enter departure time as YYYY-MM-DD HH:MM."
|
| 68 |
-
)
|
| 69 |
-
|
| 70 |
-
# Build waypoints list
|
| 71 |
-
wp_list = [w.strip() for w in waypoints.split(",")] if waypoints else None
|
| 72 |
-
|
| 73 |
-
# Call Directions API
|
| 74 |
-
directions = gmaps.directions(
|
| 75 |
-
origin=source,
|
| 76 |
-
destination=destination,
|
| 77 |
-
mode=mode.lower(),
|
| 78 |
-
departure_time=dt,
|
| 79 |
-
waypoints=wp_list,
|
| 80 |
-
optimize_waypoints=False,
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
if not directions:
|
| 84 |
-
return "**No route found.**"
|
| 85 |
-
|
| 86 |
-
# Use first route & leg
|
| 87 |
-
route = directions[0]
|
| 88 |
-
leg = route["legs"][0]
|
| 89 |
-
|
| 90 |
-
# Build summary
|
| 91 |
-
summary = f"**Trip from '{leg['start_address']}' to '{leg['end_address']}'**\n"
|
| 92 |
-
summary += f"- Total distance: {leg['distance']['text']}\n"
|
| 93 |
-
summary += f"- Estimated duration: {leg['duration']['text']}\n\n"
|
| 94 |
-
summary += "### Step-by-Step Directions:\n"
|
| 95 |
-
|
| 96 |
-
for i, step in enumerate(leg["steps"], start=1):
|
| 97 |
-
travel_mode = step.get("travel_mode", "").upper()
|
| 98 |
-
if travel_mode == "TRANSIT":
|
| 99 |
-
details = step.get("transit_details", {})
|
| 100 |
-
line = details.get("line", {})
|
| 101 |
-
vehicle = line.get("vehicle", {}).get("type", "Transit")
|
| 102 |
-
line_name = line.get("short_name") or line.get("name", "")
|
| 103 |
-
dep = details.get("departure_stop", {}).get("name", "")
|
| 104 |
-
arr = details.get("arrival_stop", {}).get("name", "")
|
| 105 |
-
stops = details.get("num_stops", "")
|
| 106 |
-
instr = f"Take {vehicle} {line_name} from {dep} to {arr} ({stops} stops)"
|
| 107 |
-
dist = step.get("distance", {}).get("text", "")
|
| 108 |
-
else:
|
| 109 |
-
raw = step.get("html_instructions", "")
|
| 110 |
-
instr = re.sub(r"<[^>]+>", "", raw)
|
| 111 |
-
dist = step.get("distance", {}).get("text", "")
|
| 112 |
-
|
| 113 |
-
summary += f"{i}. {instr} ({dist})\n"
|
| 114 |
-
|
| 115 |
-
# Static map snapshot
|
| 116 |
-
poly = route.get("overview_polyline", {}).get("points")
|
| 117 |
-
if poly:
|
| 118 |
-
static_map_url = (
|
| 119 |
-
"https://maps.googleapis.com/maps/api/staticmap"
|
| 120 |
-
f"?size=600x400&path=enc:{poly}&key={api_key}"
|
| 121 |
-
)
|
| 122 |
-
summary += "\n---\n"
|
| 123 |
-
summary += ("Here’s a **static map snapshot** of this route:\n" + static_map_url)
|
| 124 |
-
|
| 125 |
-
return summary
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
# Gradio UI
|
| 129 |
-
demo = gr.Interface(
|
| 130 |
-
fn=get_directions,
|
| 131 |
-
inputs=[
|
| 132 |
-
gr.Textbox(label="Source Location", placeholder="e.g. New York City"),
|
| 133 |
-
gr.Textbox(label="Destination Location", placeholder="e.g. Los Angeles"),
|
| 134 |
-
gr.Radio(
|
| 135 |
-
["driving", "walking", "bicycling", "transit"],
|
| 136 |
-
label="Travel Mode",
|
| 137 |
-
value="driving"
|
| 138 |
-
),
|
| 139 |
-
gr.Textbox(
|
| 140 |
-
label="Departure Time (YYYY-MM-DD HH:MM)",
|
| 141 |
-
placeholder="e.g. 2025-06-08 14:30"
|
| 142 |
-
),
|
| 143 |
-
gr.Textbox(
|
| 144 |
-
label="Waypoints (optional, comma-separated)",
|
| 145 |
-
placeholder="e.g. museum, coffee shop"
|
| 146 |
-
),
|
| 147 |
-
],
|
| 148 |
-
outputs=gr.Markdown(label="Directions Summary"),
|
| 149 |
-
title="Google Maps Directions",
|
| 150 |
-
description="Get step-by-step directions between two locations using the Google Maps API."
|
| 151 |
-
)
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
| 1 |
+
from dotenv import load_dotenv
|
| 2 |
+
import os
|
| 3 |
+
import googlemaps
|
| 4 |
+
import re
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
# Load environment variables and initialize Google Maps client
|
| 9 |
+
dotenv_path = os.getenv('DOTENV_PATH', None)
|
| 10 |
+
if dotenv_path:
|
| 11 |
+
load_dotenv(dotenv_path)
|
| 12 |
+
else:
|
| 13 |
+
load_dotenv()
|
| 14 |
+
|
| 15 |
+
api_key = os.getenv("GOOGLE_API_KEY")
|
| 16 |
+
if not api_key:
|
| 17 |
+
raise EnvironmentError("GOOGLE_API_KEY not found in environment variables.")
|
| 18 |
+
|
| 19 |
+
gmaps = googlemaps.Client(key=api_key)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_places(trip_type: str, location: str) -> list[str]:
|
| 23 |
+
"""
|
| 24 |
+
Fetches up to 5 popular tourist attractions matching the trip_type in the given location.
|
| 25 |
+
"""
|
| 26 |
+
query = f"{trip_type} places in {location}"
|
| 27 |
+
results = gmaps.places(query=query, type="tourist_attraction")
|
| 28 |
+
places = results.get("results", [])[:5]
|
| 29 |
+
return [place.get("name") for place in places]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_restaurants(location: str, prefs: str) -> list[str]:
|
| 33 |
+
"""
|
| 34 |
+
Fetches up to 3 restaurants near the given location matching the user preferences.
|
| 35 |
+
"""
|
| 36 |
+
query = f"{prefs} restaurants near {location}"
|
| 37 |
+
results = gmaps.places(query=query, type="restaurant")
|
| 38 |
+
restaurants = results.get("results", [])[:3]
|
| 39 |
+
return [r.get("name") for r in restaurants]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_directions(
|
| 43 |
+
source: str,
|
| 44 |
+
destination: str,
|
| 45 |
+
mode: str,
|
| 46 |
+
departure_time: str,
|
| 47 |
+
waypoints: str = ""
|
| 48 |
+
) -> str:
|
| 49 |
+
"""
|
| 50 |
+
Returns a Markdown-formatted string with step-by-step directions and a static map URL.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
source: Starting address or place name.
|
| 54 |
+
destination: Ending address or place name.
|
| 55 |
+
mode: Transport mode: driving, walking, bicycling, or transit.
|
| 56 |
+
departure_time: Trip start time in "YYYY-MM-DD HH:MM" format.
|
| 57 |
+
waypoints: Optional comma-separated list of waypoints.
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
A single Markdown string summarizing the route or an error message.
|
| 61 |
+
"""
|
| 62 |
+
# Parse departure time
|
| 63 |
+
try:
|
| 64 |
+
dt = datetime.strptime(departure_time.strip(), "%Y-%m-%d %H:%M")
|
| 65 |
+
except ValueError:
|
| 66 |
+
return (
|
| 67 |
+
"**⚠️ Invalid time format.** Please enter departure time as YYYY-MM-DD HH:MM."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# Build waypoints list
|
| 71 |
+
wp_list = [w.strip() for w in waypoints.split(",")] if waypoints else None
|
| 72 |
+
|
| 73 |
+
# Call Directions API
|
| 74 |
+
directions = gmaps.directions(
|
| 75 |
+
origin=source,
|
| 76 |
+
destination=destination,
|
| 77 |
+
mode=mode.lower(),
|
| 78 |
+
departure_time=dt,
|
| 79 |
+
waypoints=wp_list,
|
| 80 |
+
optimize_waypoints=False,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
if not directions:
|
| 84 |
+
return "**No route found.**"
|
| 85 |
+
|
| 86 |
+
# Use first route & leg
|
| 87 |
+
route = directions[0]
|
| 88 |
+
leg = route["legs"][0]
|
| 89 |
+
|
| 90 |
+
# Build summary
|
| 91 |
+
summary = f"**Trip from '{leg['start_address']}' to '{leg['end_address']}'**\n"
|
| 92 |
+
summary += f"- Total distance: {leg['distance']['text']}\n"
|
| 93 |
+
summary += f"- Estimated duration: {leg['duration']['text']}\n\n"
|
| 94 |
+
summary += "### Step-by-Step Directions:\n"
|
| 95 |
+
|
| 96 |
+
for i, step in enumerate(leg["steps"], start=1):
|
| 97 |
+
travel_mode = step.get("travel_mode", "").upper()
|
| 98 |
+
if travel_mode == "TRANSIT":
|
| 99 |
+
details = step.get("transit_details", {})
|
| 100 |
+
line = details.get("line", {})
|
| 101 |
+
vehicle = line.get("vehicle", {}).get("type", "Transit")
|
| 102 |
+
line_name = line.get("short_name") or line.get("name", "")
|
| 103 |
+
dep = details.get("departure_stop", {}).get("name", "")
|
| 104 |
+
arr = details.get("arrival_stop", {}).get("name", "")
|
| 105 |
+
stops = details.get("num_stops", "")
|
| 106 |
+
instr = f"Take {vehicle} {line_name} from {dep} to {arr} ({stops} stops)"
|
| 107 |
+
dist = step.get("distance", {}).get("text", "")
|
| 108 |
+
else:
|
| 109 |
+
raw = step.get("html_instructions", "")
|
| 110 |
+
instr = re.sub(r"<[^>]+>", "", raw)
|
| 111 |
+
dist = step.get("distance", {}).get("text", "")
|
| 112 |
+
|
| 113 |
+
summary += f"{i}. {instr} ({dist})\n"
|
| 114 |
+
|
| 115 |
+
# Static map snapshot
|
| 116 |
+
poly = route.get("overview_polyline", {}).get("points")
|
| 117 |
+
if poly:
|
| 118 |
+
static_map_url = (
|
| 119 |
+
"https://maps.googleapis.com/maps/api/staticmap"
|
| 120 |
+
f"?size=600x400&path=enc:{poly}&key={api_key}"
|
| 121 |
+
)
|
| 122 |
+
summary += "\n---\n"
|
| 123 |
+
summary += ("Here’s a **static map snapshot** of this route:\n" + static_map_url)
|
| 124 |
+
|
| 125 |
+
return summary
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# Gradio UI
|
| 129 |
+
demo = gr.Interface(
|
| 130 |
+
fn=get_directions,
|
| 131 |
+
inputs=[
|
| 132 |
+
gr.Textbox(label="Source Location", placeholder="e.g. New York City"),
|
| 133 |
+
gr.Textbox(label="Destination Location", placeholder="e.g. Los Angeles"),
|
| 134 |
+
gr.Radio(
|
| 135 |
+
["driving", "walking", "bicycling", "transit"],
|
| 136 |
+
label="Travel Mode",
|
| 137 |
+
value="driving"
|
| 138 |
+
),
|
| 139 |
+
gr.Textbox(
|
| 140 |
+
label="Departure Time (YYYY-MM-DD HH:MM)",
|
| 141 |
+
placeholder="e.g. 2025-06-08 14:30"
|
| 142 |
+
),
|
| 143 |
+
gr.Textbox(
|
| 144 |
+
label="Waypoints (optional, comma-separated)",
|
| 145 |
+
placeholder="e.g. museum, coffee shop"
|
| 146 |
+
),
|
| 147 |
+
],
|
| 148 |
+
outputs=gr.Markdown(label="Directions Summary"),
|
| 149 |
+
title="Google Maps Directions",
|
| 150 |
+
description="Get step-by-step directions between two locations using the Google Maps API."
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
demo.launch(mcp_server=True, share=True)
|