DreamStream-1 commited on
Commit
4cfb561
·
verified ·
1 Parent(s): a9d7e8f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -73
app.py CHANGED
@@ -1,82 +1,103 @@
1
- import gradio as gr
2
- import pandas as pd
3
- import requests
 
 
 
 
4
 
5
- # Google Places API endpoint
6
- url = "https://maps.googleapis.com/maps/api/place/textsearch/json"
7
- places_details_url = "https://maps.googleapis.com/maps/api/place/details/json"
8
 
9
- # Your actual Google API Key (replace with your key)
10
- api_key = "GOOGLE_API_KEY"
11
-
12
- def get_places_data(query, location, radius, next_page_token=None):
13
- params = {
14
- "query": query,
15
- "location": location,
16
- "radius": radius,
17
- "key": api_key
18
- }
19
- if next_page_token:
20
- params["pagetoken"] = next_page_token
21
- response = requests.get(url, params=params)
22
- if response.status_code == 200:
23
- return response.json()
24
  else:
25
- return {"error": f"Error: {response.status_code} - {response.text}"}
26
 
27
- def get_place_details(place_id):
28
- params = {"place_id": place_id, "key": api_key}
29
- response = requests.get(places_details_url, params=params)
30
- if response.status_code == 200:
31
- details_data = response.json().get("result", {})
32
- return {
33
- "opening_hours": details_data.get("opening_hours", {}).get("weekday_text", "Not available"),
34
- "phone_number": details_data.get("formatted_phone_number", "Not available"),
35
- "website": details_data.get("website", "Not available")
36
- }
37
- else:
38
- return {"error": f"Error: {response.status_code} - {response.text}"}
39
 
40
- def get_all_places(query, location, radius):
41
- all_results = []
42
- next_page_token = None
43
- while True:
44
- data = get_places_data(query, location, radius, next_page_token)
45
- if "error" in data:
46
- return [data] # Return error message
47
- results = data.get('results', [])
48
- for place in results:
49
- place_id = place.get("place_id")
50
- details = get_place_details(place_id)
51
- if "error" in details:
52
- return [details] # Return error message
53
- all_results.append({**place, **details})
54
-
55
- next_page_token = data.get('next_page_token')
56
- if not next_page_token:
57
- break
58
- return all_results
59
 
60
- def display_data(query, location, radius):
61
- results = get_all_places(query, location, radius)
62
- if isinstance(results, list):
63
- if results and isinstance(results[0], dict):
64
- return pd.DataFrame(results)
65
- else:
66
- return pd.DataFrame() # Return an empty DataFrame if results is empty or not a list of dicts
 
 
 
 
 
 
 
 
 
 
 
 
67
  else:
68
- return pd.DataFrame() # Return an empty DataFrame if results is not a list
69
 
70
- iface = gr.Interface(
71
- fn=display_data,
72
- inputs=[
73
- gr.Textbox(lines=2, label="Search Query (e.g., 'therapist in Hawaii')"),
74
- gr.Textbox(label="Location (latitude,longitude)"),
75
- gr.Number(label="Radius (meters)")
76
- ],
77
- outputs=gr.Dataframe(headers=["Name", "Address", "Phone", "Website", "Opening Hours", "Rating", "Types", "Latitude", "Longitude"], type="pandas"),
78
- title="Hawaii Wellness Professionals Finder",
79
- description="Find wellness professionals in Hawaii using the Google Places API."
80
- )
81
 
82
- iface.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import folium
3
+ from folium.plugins import MarkerCluster
4
+ from streamlit_folium import folium_static
5
+ import googlemaps
6
+ from datetime import datetime
7
+ import os
8
 
9
+ # Initialize Google Maps API client securely
10
+ gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY')) # Fetch API key from Hugging Face secrets
 
11
 
12
+ # Function to fetch directions
13
+ def get_directions_and_coords(source, destination):
14
+ now = datetime.now()
15
+ directions_info = gmaps.directions(source, destination, mode='driving', departure_time=now)
16
+ if directions_info:
17
+ steps = directions_info[0]['legs'][0]['steps']
18
+ coords = [(step['start_location']['lat'], step['start_location']['lng']) for step in steps]
19
+ return steps, coords
 
 
 
 
 
 
 
20
  else:
21
+ return None, None
22
 
23
+ # Function to render map with directions
24
+ def render_folium_map(coords):
25
+ m = folium.Map(location=[coords[0][0], coords[0][1]], zoom_start=13)
26
+ folium.PolyLine(coords, color="blue", weight=2.5, opacity=1).add_to(m)
27
+ return m
 
 
 
 
 
 
 
28
 
29
+ # Function to add medical center paths and annotate distance
30
+ def add_medical_center_paths(m, source, med_centers):
31
+ for name, lat, lon, specialty, city in med_centers:
32
+ _, coords = get_directions_and_coords(source, (lat, lon))
33
+ if coords:
34
+ folium.PolyLine(coords, color="red", weight=2.5, opacity=1).add_to(m)
35
+ folium.Marker([lat, lon], popup=name).add_to(m)
36
+ distance_info = gmaps.distance_matrix(source, (lat, lon), mode='driving')
37
+ distance = distance_info['rows'][0]['elements'][0]['distance']['text']
38
+ folium.PolyLine(coords, color='red').add_to(m)
39
+ folium.map.Marker(
40
+ [coords[-1][0], coords[-1][1]],
41
+ icon=folium.DivIcon(
42
+ icon_size=(150, 36),
43
+ icon_anchor=(0, 0),
44
+ html=f'<div style="font-size: 10pt; color : red;">{distance}</div>',
45
+ )
46
+ ).add_to(m)
 
47
 
48
+ # Function to search nearby medical centers using Google Places API
49
+ def search_medical_centers(query, location, radius=10000):
50
+ # Search for places like hospitals or medical centers nearby
51
+ places_result = gmaps.places_nearby(location, radius=radius, type='hospital', keyword=query)
52
+ return places_result.get('results', [])
53
+
54
+ # Driving Directions Sidebar
55
+ st.sidebar.header('Directions 🚗')
56
+ source_location = st.sidebar.text_input("Source Location", "Honolulu, HI")
57
+ destination_location = st.sidebar.text_input("Destination Location", "Maui, HI")
58
+ if st.sidebar.button('Get Directions'):
59
+ steps, coords = get_directions_and_coords(source_location, destination_location)
60
+ if steps and coords:
61
+ st.subheader('Driving Directions:')
62
+ for i, step in enumerate(steps):
63
+ st.write(f"{i+1}. {step['html_instructions']}")
64
+ st.subheader('Route on Map:')
65
+ m1 = render_folium_map(coords)
66
+ folium_static(m1)
67
  else:
68
+ st.write("No available routes.")
69
 
70
+ # Medical Center Search Section
71
+ st.markdown("### 🏥 Search for Medical Centers in Hawaii 🗺️")
72
+ medical_center_query = st.text_input("Enter Medical Center Name or Specialty", "Hawaii Medical Center")
73
+ location_input = st.text_input("Enter your location (within Hawaii)", "Honolulu, HI")
 
 
 
 
 
 
 
74
 
75
+ if location_input and medical_center_query:
76
+ # Fetch the coordinates of the source location using Google Geocoding
77
+ geocode_result = gmaps.geocode(location_input)
78
+ if geocode_result:
79
+ location_coords = geocode_result[0]['geometry']['location']
80
+ lat, lon = location_coords['lat'], location_coords['lng']
81
+
82
+ # Fetch nearby medical centers in Hawaii
83
+ medical_centers = search_medical_centers(medical_center_query, (lat, lon))
84
+
85
+ if medical_centers:
86
+ st.subheader('Found Medical Centers:')
87
+ for center in medical_centers:
88
+ name = center['name']
89
+ vicinity = center.get('vicinity', 'N/A')
90
+ rating = center.get('rating', 'N/A')
91
+ st.write(f"**{name}** - {vicinity} - Rating: {rating}")
92
+
93
+ # Add marker for each medical center on map
94
+ folium.Marker([center['geometry']['location']['lat'], center['geometry']['location']['lng']],
95
+ popup=f"{name}\n{vicinity}\nRating: {rating}").add_to(m2)
96
+
97
+ # Render the map with medical centers
98
+ m2 = folium.Map(location=[lat, lon], zoom_start=13)
99
+ folium_static(m2)
100
+ else:
101
+ st.write("No medical centers found matching your query.")
102
+ else:
103
+ st.write("Could not retrieve location coordinates.")