location / app.py
kimappl's picture
Update app.py
464579e verified
import streamlit as st
from streamlit_javascript import st_javascript
import requests
import os
import pandas as pd
import json
# Google API Key (Stored as a secret in Hugging Face Spaces)
API_KEY = os.getenv("GOOGLE_PLACES_API_KEY")
st.title("πŸ“ AI-Powered Restaurant & Museum Finder")
# Run JavaScript to get geolocation
js_code = """
navigator.geolocation.getCurrentPosition(
(position) => {
const coords = JSON.stringify({ latitude: position.coords.latitude, longitude: position.coords.longitude });
localStorage.setItem('user_coords', coords);
},
(error) => {
localStorage.setItem('user_coords', JSON.stringify({ error: error.message }));
}
);
localStorage.getItem('user_coords');
"""
location = st_javascript(js_code)
# Debugging: Display raw location response
st.write("πŸ“Œ Raw Location Data:", location)
# Check if location was successfully fetched
if location:
try:
loc_data = json.loads(location)
if "latitude" in loc_data:
lat, lon = loc_data["latitude"], loc_data["longitude"]
st.success(f"βœ… Detected Location: {lat}, {lon}")
else:
st.warning(f"⚠ Error: {loc_data.get('error', 'Unknown issue')}")
lat = st.number_input("Enter Latitude", value=40.7128) # Default: NYC
lon = st.number_input("Enter Longitude", value=-74.0060) # Default: NYC
except json.JSONDecodeError:
st.error("❌ Error processing location data. Try refreshing the page.")
lat = st.number_input("Enter Latitude", value=40.7128)
lon = st.number_input("Enter Longitude", value=-74.0060)
else:
st.warning("⚠ Unable to detect location. Please enable location services or enter manually.")
lat = st.number_input("Enter Latitude", value=40.7128) # Default: NYC
lon = st.number_input("Enter Longitude", value=-74.0060) # Default: NYC
# Fetch places from Google Places API
def fetch_places(lat, lon, place_type="restaurant"):
radius = 3000 # 3km range
url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{lon}&radius={radius}&type={place_type}&key={API_KEY}"
response = requests.get(url)
return response.json().get("results", [])
# Choose category (restaurant or museum)
place_type = st.selectbox("Choose a Category", ["restaurant", "museum"])
places = fetch_places(lat, lon, place_type)
if places:
df = pd.DataFrame([
{"Name": p["name"], "Rating": p.get("rating", "N/A"), "Address": p.get("vicinity", "Unknown")}
for p in places[:10]
])
st.table(df)
else:
st.warning(f"⚠ No {place_type}s found nearby. Try increasing the radius or entering a different location.")