Spaces:
Runtime error
Runtime error
Commit
·
f07dae8
1
Parent(s):
fc5c224
Add geodistance func as api
Browse files
main.py
CHANGED
@@ -1,14 +1,22 @@
|
|
1 |
from fastapi import FastAPI
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
from fastapi.responses import JSONResponse, HTMLResponse
|
4 |
-
|
5 |
import requests
|
6 |
from geopy.geocoders import Nominatim
|
|
|
7 |
|
8 |
app = FastAPI()
|
9 |
|
10 |
loc = Nominatim(user_agent="GetLoc")
|
11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
app.add_middleware(
|
13 |
CORSMiddleware,
|
14 |
allow_origins=["*"], # Replace with your frontend domain in prod
|
@@ -69,3 +77,40 @@ def search_wiki(full_page: str):
|
|
69 |
content={"error": str(e), 'response': str(response)},
|
70 |
status_code=500
|
71 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from fastapi import FastAPI
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
from fastapi.responses import JSONResponse, HTMLResponse
|
4 |
+
from pydantic import BaseModel, Field
|
5 |
import requests
|
6 |
from geopy.geocoders import Nominatim
|
7 |
+
import geopy.distance
|
8 |
|
9 |
app = FastAPI()
|
10 |
|
11 |
loc = Nominatim(user_agent="GetLoc")
|
12 |
|
13 |
+
class Geodistance(BaseModel):
|
14 |
+
lat1: float = Field(..., ge=-90, le=90)
|
15 |
+
lon1: float = Field(..., ge=-180, le=180)
|
16 |
+
lat2: float = Field(..., ge=-90, le=90)
|
17 |
+
lon2: float = Field(..., ge=-180, le=180)
|
18 |
+
unit: str = "km"
|
19 |
+
|
20 |
app.add_middleware(
|
21 |
CORSMiddleware,
|
22 |
allow_origins=["*"], # Replace with your frontend domain in prod
|
|
|
77 |
content={"error": str(e), 'response': str(response)},
|
78 |
status_code=500
|
79 |
)
|
80 |
+
|
81 |
+
|
82 |
+
@app.post("/geodistance")
|
83 |
+
def get_geodistance(payload: Geodistance):
|
84 |
+
lat1, lon1 = payload.lat1, payload.lon1
|
85 |
+
lat2, lon2 = payload.lat2, payload.lon2
|
86 |
+
unit = payload.unit
|
87 |
+
|
88 |
+
try:
|
89 |
+
distance_km = geopy.distance.distance((lat1, lon1), (lat2, lon2)).km
|
90 |
+
if unit == "km":
|
91 |
+
distance = distance_km
|
92 |
+
elif unit == "mi":
|
93 |
+
distance = distance_km * 0.621371
|
94 |
+
else:
|
95 |
+
return JSONResponse(
|
96 |
+
content={"error": "Invalid unit"},
|
97 |
+
status_code=400
|
98 |
+
)
|
99 |
+
|
100 |
+
except Exception as e:
|
101 |
+
return JSONResponse(
|
102 |
+
content={"error": str(e)},
|
103 |
+
status_code=500
|
104 |
+
)
|
105 |
+
|
106 |
+
return JSONResponse(
|
107 |
+
content={
|
108 |
+
"distance": distance,
|
109 |
+
"unit": unit,
|
110 |
+
"lat1": lat1,
|
111 |
+
"lon1": lon1,
|
112 |
+
"lat2": lat2,
|
113 |
+
"lon2": lon2
|
114 |
+
},
|
115 |
+
status_code=200
|
116 |
+
)
|