gauthamnairy commited on
Commit
b7aeeca
·
verified ·
1 Parent(s): 4650839

Update backend/main.py

Browse files
Files changed (1) hide show
  1. backend/main.py +123 -121
backend/main.py CHANGED
@@ -1,121 +1,123 @@
1
- from fastapi import FastAPI, HTTPException
2
- from fastapi.middleware.cors import CORSMiddleware
3
- from pydantic import BaseModel
4
- import httpx
5
- import pyproj
6
- from typing import List, Dict, Optional, Any
7
-
8
- app = FastAPI(title="Ground Elevation API")
9
-
10
- # Configure CORS
11
- app.add_middleware(
12
- CORSMiddleware,
13
- allow_origins=["*"], # Allows all origins
14
- allow_credentials=True,
15
- allow_methods=["*"], # Allows all methods
16
- allow_headers=["*"], # Allows all headers
17
- )
18
-
19
- # Define request and response models
20
- class CoordinateRequest(BaseModel):
21
- latitude: float
22
- longitude: float
23
- crs: str = "EPSG:4326" # Default to WGS84
24
-
25
- class ElevationResponse(BaseModel):
26
- latitude: float
27
- longitude: float
28
- elevation: float
29
- wgs84_latitude: float # Add WGS84 coordinates
30
- wgs84_longitude: float
31
- original_crs: str
32
-
33
- class CRSInfo(BaseModel):
34
- code: str
35
- name: str
36
-
37
- # Route for fetching elevation data
38
- @app.post("/api/elevation", response_model=ElevationResponse)
39
- async def get_elevation(request: CoordinateRequest):
40
- """Get elevation for a given coordinate pair"""
41
- try:
42
- # Convert from source CRS to WGS84 (EPSG:4326) if necessary
43
- wgs84_coords = convert_to_wgs84(request.longitude, request.latitude, request.crs)
44
-
45
- # Query Open-Meteo for elevation data
46
- elevation = await query_open_meteo(wgs84_coords[1], wgs84_coords[0])
47
-
48
- return ElevationResponse(
49
- latitude=request.latitude,
50
- longitude=request.longitude,
51
- elevation=elevation,
52
- wgs84_latitude=wgs84_coords[1],
53
- wgs84_longitude=wgs84_coords[0],
54
- original_crs=request.crs
55
- )
56
- except Exception as e:
57
- raise HTTPException(status_code=500, detail=str(e))
58
-
59
- # Route for fetching CRS list
60
- @app.get("/api/crs-list", response_model=List[CRSInfo])
61
- async def get_crs_list():
62
- """Get a list of supported coordinate reference systems"""
63
- # List of common CRS systems
64
- crs_list = [
65
- {"code": "EPSG:4326", "name": "WGS 84"},
66
- {"code": "EPSG:3857", "name": "Web Mercator"},
67
- {"code": "EPSG:2154", "name": "RGF93 / Lambert-93"},
68
- {"code": "EPSG:27700", "name": "OSGB 1936 / British National Grid"},
69
- {"code": "EPSG:3785", "name": "Popular Visualisation CRS / Mercator"},
70
- {"code": "EPSG:4269", "name": "NAD83"},
71
- {"code": "EPSG:4267", "name": "NAD27"},
72
- {"code": "EPSG:32633", "name": "WGS 84 / UTM zone 33N"},
73
- ]
74
- return crs_list
75
-
76
- # Convert coordinates from source CRS to WGS84
77
- def convert_to_wgs84(x, y, source_crs):
78
- """Convert coordinates from source CRS to WGS84"""
79
- # If already WGS84, return as is
80
- if source_crs == "EPSG:4326":
81
- return (x, y)
82
-
83
- try:
84
- # Create transformation
85
- transformer = pyproj.Transformer.from_crs(source_crs, "EPSG:4326", always_xy=True)
86
- # Transform coordinates
87
- lon, lat = transformer.transform(x, y)
88
- return (lon, lat)
89
- except Exception as e:
90
- raise Exception(f"Coordinate transformation error: {str(e)}")
91
-
92
- # Query elevation from Open-Meteo API
93
- async def query_open_meteo(lat, lon):
94
- """Query Open-Meteo for elevation data"""
95
- url = f"https://api.open-meteo.com/v1/elevation?latitude={lat}&longitude={lon}"
96
-
97
- async with httpx.AsyncClient() as client:
98
- try:
99
- response = await client.get(url)
100
- response.raise_for_status()
101
- data = response.json()
102
-
103
- # Extract elevation from response
104
- if "elevation" in data and isinstance(data["elevation"], list) and len(data["elevation"]) > 0:
105
- return float(data["elevation"][0])
106
- else:
107
- raise Exception("No elevation data found in API response")
108
- except httpx.HTTPStatusError as e:
109
- raise Exception(f"Elevation API error: {str(e)}")
110
- except Exception as e:
111
- raise Exception(f"Error querying elevation: {str(e)}")
112
-
113
- # Add additional health check endpoint
114
- @app.get("/api/health")
115
- async def health_check():
116
- """Health check endpoint"""
117
- return {"status": "ok"}
118
-
119
- if __name__ == "__main__":
120
- import uvicorn
121
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ import httpx
5
+ import pyproj
6
+ from typing import List, Dict, Optional, Any
7
+
8
+ app = FastAPI(title="Ground Elevation API")
9
+
10
+ # Configure CORS
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"], # Allows all origins
14
+ allow_credentials=True,
15
+ allow_methods=["*"], # Allows all methods
16
+ allow_headers=["*"], # Allows all headers
17
+ )
18
+
19
+ # Define request and response models
20
+ class CoordinateRequest(BaseModel):
21
+ latitude: float
22
+ longitude: float
23
+ crs: str = "EPSG:4326" # Default to WGS84
24
+
25
+ class ElevationResponse(BaseModel):
26
+ latitude: float
27
+ longitude: float
28
+ elevation: float
29
+ wgs84_latitude: float # Add WGS84 coordinates
30
+ wgs84_longitude: float
31
+ original_crs: str
32
+
33
+ class CRSInfo(BaseModel):
34
+ code: str
35
+ name: str
36
+
37
+ # Route for fetching elevation data
38
+ @app.post("/api/elevation", response_model=ElevationResponse)
39
+ async def get_elevation(request: CoordinateRequest):
40
+ """Get elevation for a given coordinate pair"""
41
+ try:
42
+ # Convert from source CRS to WGS84 (EPSG:4326) if necessary
43
+ wgs84_coords = convert_to_wgs84(request.longitude, request.latitude, request.crs)
44
+
45
+ # Query Open-Meteo for elevation data
46
+ elevation = await query_open_meteo(wgs84_coords[1], wgs84_coords[0])
47
+
48
+ return ElevationResponse(
49
+ latitude=request.latitude,
50
+ longitude=request.longitude,
51
+ elevation=elevation,
52
+ wgs84_latitude=wgs84_coords[1],
53
+ wgs84_longitude=wgs84_coords[0],
54
+ original_crs=request.crs
55
+ )
56
+ except Exception as e:
57
+ raise HTTPException(status_code=500, detail=str(e))
58
+
59
+ # Route for fetching CRS list
60
+ @app.get("/api/crs-list", response_model=List[CRSInfo])
61
+ async def get_crs_list():
62
+ """Get a list of supported coordinate reference systems"""
63
+ # List of common CRS systems
64
+ crs_list = [
65
+ {"code": "EPSG:4326", "name": "WGS 84"},
66
+ {"code": "EPSG:3857", "name": "Web Mercator"},
67
+ {"code": "EPSG:2154", "name": "RGF93 / Lambert-93"},
68
+ {"code": "EPSG:27700", "name": "OSGB 1936 / British National Grid"},
69
+ {"code": "EPSG:3785", "name": "Popular Visualisation CRS / Mercator"},
70
+ {"code": "EPSG:4269", "name": "NAD83"},
71
+ {"code": "EPSG:4267", "name": "NAD27"},
72
+ {"code": "EPSG:32633", "name": "WGS 84 / UTM zone 33N"},
73
+ ]
74
+ return crs_list
75
+
76
+ # Convert coordinates from source CRS to WGS84
77
+ def convert_to_wgs84(x, y, source_crs):
78
+ """Convert coordinates from source CRS to WGS84"""
79
+ # If already WGS84, return as is
80
+ if source_crs == "EPSG:4326":
81
+ return (x, y)
82
+
83
+ try:
84
+ # Create transformation
85
+ transformer = pyproj.Transformer.from_crs(source_crs, "EPSG:4326", always_xy=True)
86
+ # Transform coordinates
87
+ lon, lat = transformer.transform(x, y)
88
+ return (lon, lat)
89
+ except Exception as e:
90
+ raise Exception(f"Coordinate transformation error: {str(e)}")
91
+
92
+ # Query elevation from Open-Meteo API
93
+ async def query_open_meteo(lat, lon):
94
+ """Query Open-Meteo for elevation data"""
95
+ url = f"https://api.open-meteo.com/v1/elevation?latitude={lat}&longitude={lon}"
96
+
97
+ async with httpx.AsyncClient() as client:
98
+ try:
99
+ response = await client.get(url)
100
+ response.raise_for_status()
101
+ data = response.json()
102
+
103
+ # Extract elevation from response
104
+ if "elevation" in data and isinstance(data["elevation"], list) and len(data["elevation"]) > 0:
105
+ return float(data["elevation"][0])
106
+ else:
107
+ raise Exception("No elevation data found in API response")
108
+ except httpx.HTTPStatusError as e:
109
+ raise Exception(f"Elevation API error: {str(e)}")
110
+ except Exception as e:
111
+ raise Exception(f"Error querying elevation: {str(e)}")
112
+
113
+ # Add additional health check endpoint
114
+ @app.get("/api/health")
115
+ async def health_check():
116
+ """Health check endpoint"""
117
+ return {"status": "ok"}
118
+
119
+ if __name__ == "__main__":
120
+ import uvicorn
121
+ import os
122
+ port = int(os.environ.get("PORT", 7860))
123
+ uvicorn.run(app, host="0.0.0.0", port=port)