Skip to content

Commit 166b3d3

Browse files
authored
added the option to add new location when not in database (#72)
2 parents 2cbf9ae + 47e0555 commit 166b3d3

2 files changed

Lines changed: 61 additions & 9 deletions

File tree

API/fireguard_app/Fireguard_API.py

Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from .db_locations.crud import LocationOperations
88
import math
99
import numpy as np
10+
import requests
1011

1112
# Initialize the Fire Risk API
1213
frc = METFireRiskAPI()
@@ -24,12 +25,25 @@
2425
def get_fire_risk(loc: str, days_past: int = 7, weatherdata: bool = False):
2526
"""
2627
Fetches weather data and fire risk predictions for a given location.
28+
Adds the location to the database if it doesn't exist.
29+
:param loc: The location name (e.g., "Oslo")
2730
"""
2831
loc = loc.capitalize()
2932
# Define the location with their latitude and longitude
3033
location_db = operator_db.get_location_by_name(loc)
3134
if location_db is None:
32-
return {"error": "Location not found in the database."}
35+
try:
36+
coordinates = get_coordinates_from_StedsnavnAPI(loc)
37+
new_location = {
38+
"name": loc,
39+
"coordinates": coordinates,
40+
"fireRiskPrediction": None,
41+
"lastModified": None,
42+
}
43+
operator_db.create_location(new_location)
44+
except Exception as e:
45+
return {"error": f"Location {loc} not found in StedsnavnAPI. Error: {str(e)}"}
46+
location_db = operator_db.get_location_by_name(loc)
3347

3448
coordinates = location_db["coordinates"]
3549
location = Location(latitude=coordinates["latitude"], longitude=coordinates["longitude"])
@@ -45,11 +59,10 @@ def get_fire_risk(loc: str, days_past: int = 7, weatherdata: bool = False):
4559
}
4660

4761
try:
48-
fire_risk = frc.compute_now(location, obs_delta)
49-
50-
fire_risk_dict = serialize_fire_risk_prediction(fire_risk)
51-
operator_db.update_location_firerisk(loc, fire_risk_dict)
5262
if not beenModified:
63+
fire_risk = frc.compute_now(location, obs_delta)
64+
fire_risk_dict = serialize_fire_risk_prediction(fire_risk)
65+
operator_db.update_location_firerisk(loc, fire_risk_dict)
5366
data = {
5467
"location": {"name": loc, "latitude": location.latitude, "longitude": location.longitude},
5568
"fireRiskPrediction": fire_risk
@@ -126,3 +139,42 @@ def trenddetector(list_of_index, array_of_data, order=1):
126139
}
127140

128141
return trends
142+
143+
144+
def get_coordinates_from_StedsnavnAPI(location_name, kommunenavn=None):
145+
146+
url = "https://ws.geonorge.no/stedsnavn/v1/navn"
147+
params = {
148+
"sok": location_name,
149+
"treffPerSide": 10,
150+
}
151+
response = requests.get(url, params=params)
152+
if response.status_code == 200:
153+
data = response.json()
154+
places = data.get("navn", [])
155+
if kommunenavn:
156+
kommunenavn.capitalize()
157+
for place in places:
158+
# Check if any kommune in the place has the matching kommunenavn
159+
if any(kommune.get("kommunenavn") == kommunenavn for kommune in place.get("kommuner", [])):
160+
place = place
161+
break
162+
else:
163+
place = None
164+
else:
165+
place = places[0] if places else None
166+
167+
if place:
168+
representasjonspunkt = place.get("representasjonspunkt", {})
169+
if representasjonspunkt:
170+
latitude = representasjonspunkt.get("nord")
171+
longitude = representasjonspunkt.get("øst")
172+
if latitude is not None and longitude is not None:
173+
return {
174+
"latitude": latitude,
175+
"longitude": longitude,
176+
}
177+
else:
178+
return None
179+
else:
180+
return None

API/fireguard_app/db_locations/crud.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,30 +14,30 @@ def collection_exists(self, collection_name: str):
1414
collections = self.collection.database.list_collection_names()
1515
return collection_name in collections
1616
except Exception as e:
17-
print(f"An error occurred: {e}")
17+
print(f"An error occurred when checking if the collection exists: {e}")
1818
return False
1919

2020
def create_location(self, location_data: dict):
2121
try:
2222
result = self.collection.insert_one(location_data)
2323
except Exception as e:
24-
print(f"An error occurred: {e}")
24+
print(f"An error occurred when trying to create a location: {e}")
2525
return None
2626
return result.inserted_id
2727

2828
def get_location_by_name(self, location_name: str):
2929
try:
3030
location = self.collection.find_one({"name": location_name})
3131
except Exception as e:
32-
print(f"An error occurred: {e}")
32+
print(f"An error occurred when retriving a location by name: {e}")
3333
return None
3434
return location
3535

3636
def get_location(self, location_id: str):
3737
try:
3838
location = self.collection.find_one({"_id": ObjectId(location_id)})
3939
except Exception as e:
40-
print(f"An error occurred: {e}")
40+
print(f"An error occurred when retrieving a location by id: {e}")
4141
return None
4242
return location
4343

0 commit comments

Comments
 (0)