Pharmacy_Finder / app.py
reddmann007's picture
Update app.py
75b6f87 verified
Raw
History Blame Contribute Delete
3.41 kB
import streamlit as st
import googlemaps
import math
import os
from streamlit_js_eval import get_geolocation
# --- CONFIGURATION ---
# Pulling the key securely from Hugging Face Secrets
MAPS_API_KEY = os.environ.get("MAPS_API_KEY")
if not MAPS_API_KEY:
st.error("⚠️ MAPS_API_KEY not found. Please add it to your Hugging Face Secrets.")
st.stop()
gmaps = googlemaps.Client(key=MAPS_API_KEY)
def calculate_haversine(lat1, lon1, lat2, lon2):
"""Calculates the straight-line distance in km."""
R = 6371.0
dlat, dlon = math.radians(lat2 - lat1), math.radians(lon2 - lon1)
a = math.sin(dlat / 2)**2 + math.cos(math.radians(lat1)) * \
math.cos(math.radians(lat2)) * math.sin(dlon / 2)**2
return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
# --- APP UI ---
st.set_page_config(page_title="Pharmacy Finder", page_icon="πŸ₯")
st.title("πŸ₯ Real-Time Pharmacy Locator")
# 1. Get User Location Automatically via Browser
loc = get_geolocation()
if loc:
user_lat = loc['coords']['latitude']
user_lng = loc['coords']['longitude']
st.success(f"πŸ“ Location detected: {user_lat}, {user_lng}")
query = st.text_input("Which pharmacy are you looking for?", placeholder="e.g. Apollo Pharmacy")
if query:
try:
# 2. Live Search via Google Places API
# We search specifically 'nearby' the user's coordinates
places_result = gmaps.places(query=query, location=(user_lat, user_lng))['results']
if places_result:
# 3. Process and Rank Top 5
found_pharmacies = []
for place in places_result[:5]:
p_lat = place['geometry']['location']['lat']
p_lng = place['geometry']['location']['lng']
# Using our math tool to get the distance
dist = calculate_haversine(user_lat, user_lng, p_lat, p_lng)
found_pharmacies.append({
"name": place['name'],
"address": place.get('formatted_address', 'No address provided'),
"distance": round(dist, 2),
"lat": p_lat,
"lng": p_lng
})
# Sort results: closest first
found_pharmacies.sort(key=lambda x: x['distance'])
# 4. Display as Expandable Cards
st.subheader(f"Top {len(found_pharmacies)} Results:")
for p in found_pharmacies:
with st.expander(f"πŸ₯ {p['name']} β€” {p['distance']} km away"):
st.write(f"**Address:** {p['address']}")
st.write(f"**Coordinates:** {p['lat']}, {p['lng']}")
# Universal Navigation Link (Works on iOS, Android, and Desktop)
nav_url = f"https://www.google.com/maps/dir/?api=1&destination={p['lat']},{p['lng']}"
st.link_button("πŸš€ Open in Navigation", nav_url)
else:
st.warning("No pharmacies found for that name nearby.")
except Exception as e:
st.error(f"An error occurred: {e}")
else:
st.info("Please allow location access in your browser to find pharmacies near you.")