-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
146 lines (117 loc) · 5.32 KB
/
Copy pathapp.py
File metadata and controls
146 lines (117 loc) · 5.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
from flask import Flask, request, jsonify
import os
from weaviate_schema import setup_weaviate_client
from shelter_utils import geocode_address, find_nearest_shelters, find_shelters_by_query, format_shelter_response
app = Flask(__name__)
# Initialize Weaviate client
weaviate_url = os.environ.get("WEAVIATE_URL", "http://localhost:8080")
weaviate_api_key = os.environ.get("WEAVIATE_API_KEY", None)
weaviate_client = setup_weaviate_client(url=weaviate_url, api_key=weaviate_api_key)
@app.route('/api/stayhealthy', methods=['GET', 'POST'])
def stay_healthy():
print("Stay Healthy API was called")
return jsonify({"message": "Stay Healthy API endpoint"})
@app.route('/api/replacedocs', methods=['GET', 'POST'])
def replace_docs():
print("Replace Docs API was called")
return jsonify({"message": "Replace Docs API endpoint"})
@app.route('/api/debrisremove', methods=['GET', 'POST'])
def debris_remove():
print("Debris Remove API was called")
return jsonify({"message": "Debris Remove API endpoint"})
@app.route('/api/getshelter', methods=['POST'])
def get_shelter():
"""
Find the nearest shelter based on a natural language query and the user's address.
Expected JSON input:
{
"address": "123 Main St, Los Angeles, CA",
"query": "I need a shelter that accepts pets"
}
"""
print("Get Shelter API was called")
# Get the request data
data = request.get_json()
if not data:
return jsonify({"error": "No data provided. Please send a JSON request with 'address' field."}), 400
address = data.get('address', '')
query = data.get('query', '')
if not address:
return jsonify({"error": "No address provided. Please include your location."}), 400
print(f"Received query: {query}")
print(f"User address: {address}")
# Geocode the address - this now includes sanitization and context enrichment
coordinates = geocode_address(address)
if not coordinates:
return jsonify({
"error": "Could not geocode the provided address. Please check the address and try again."
}), 400
print(f"Geocoded to coordinates: {coordinates}")
# We'll first try a simplified approach to get some results
# Get all shelters and sort by distance
shelters = []
try:
# Query all shelters
result = weaviate_client.query.get(
"Shelter", [
"name",
"description",
"address",
"phoneNumber",
"website",
"currentCapacity",
"maximumCapacity",
"services",
"amenities",
"acceptsPets",
"operatingHours",
"shelterType",
"location"
]
).with_limit(100).do()
# Extract shelter data
all_shelters = result.get("data", {}).get("Get", {}).get("Shelter", [])
print(f"Retrieved {len(all_shelters)} total shelters from database")
# Filter to shelters with location data
shelters_with_location = []
for shelter in all_shelters:
if "location" in shelter and shelter["location"] is not None:
# Calculate distance
try:
shelter_lat = shelter["location"]["latitude"]
shelter_lon = shelter["location"]["longitude"]
# Calculate distance using haversine (from shelter_utils)
from shelter_utils import haversine_distance
distance = haversine_distance(
coordinates["latitude"],
coordinates["longitude"],
shelter_lat,
shelter_lon
)
# Add distance to shelter data
shelter["_additional"] = {"distance": distance}
shelters_with_location.append(shelter)
except Exception as e:
print(f"Error calculating distance for {shelter.get('name')}: {e}")
print(f"Found {len(shelters_with_location)} shelters with valid location data")
# Sort by distance
shelters_with_location.sort(key=lambda s: s.get("_additional", {}).get("distance", float('inf')))
# Get the 2 closest shelters
shelters = shelters_with_location[:2]
# Handle pet friendly filtering if needed
if query and "pet" in query.lower():
pet_friendly = [s for s in shelters_with_location if s.get("acceptsPets", False)]
if pet_friendly:
# Take the 2 closest pet-friendly shelters
shelters = pet_friendly[:2]
except Exception as e:
print(f"Error querying shelters: {e}")
# Format the response with the sanitized address
response = format_shelter_response(shelters, coordinates.get("address", address))
if not shelters:
response["message"] = "No shelters found matching your criteria. Please try a different location."
else:
response["message"] = f"Found {len(shelters)} nearby evacuation hotels/shelters."
return jsonify(response)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=6000)