Chatgptgmaps / app.py
jasfriends11's picture
Update app.py
e1c9d44 verified
import os
import googlemaps
import gradio as gr
from openai import OpenAI
# Load API keys
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
gmaps = googlemaps.Client(key=GOOGLE_API_KEY)
client = OpenAI(api_key=OPENAI_API_KEY)
# Generate Google Static Map URL
def generate_map_url(origin, destination):
directions = gmaps.directions(origin, destination)
polyline = directions[0]['overview_polyline']['points']
return (
f"https://maps.googleapis.com/maps/api/staticmap?"
f"size=600x400&path=enc:{polyline}&"
f"markers=color:green|{origin}&markers=color:red|{destination}&"
f"key={GOOGLE_API_KEY}"
)
# Chatbot logic
def chatbot(user_message, history):
try:
# Ask GPT to extract origin and destination
prompt = f"""
Extract origin and destination from this user query for a driving route:
Query: {user_message}
Return in format: Origin: <origin>, Destination: <destination>
"""
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful travel assistant."},
{"role": "user", "content": prompt}
]
)
parsed_text = response.choices[0].message.content
parts = parsed_text.split(',')
origin = parts[0].split(':')[1].strip()
destination = parts[1].split(':')[1].strip()
# Get distance & time
result = gmaps.distance_matrix(origin, destination, mode="driving")
distance_text = result['rows'][0]['elements'][0]['distance']['text']
duration_text = result['rows'][0]['elements'][0]['duration']['text']
# Generate map URL
map_url = generate_map_url(origin, destination)
# βœ… Display map inline using HTML <img>
reply_html = f"""
βœ… Distance from {origin} to {destination}: {distance_text}<br>
βœ… Estimated Time: {duration_text}<br><br>
<img src="{map_url}" alt="Map" style="max-width:100%; border-radius:8px;">
"""
return reply_html
except Exception as e:
return f"❌ Error: {str(e)}"
# Gradio Interface
with gr.Blocks() as demo:
gr.Markdown("# πŸ—Ί ChatGPT + Google Maps Assistant")
chatbot_ui = gr.ChatInterface(fn=chatbot, type="messages")
demo.launch()