-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
164 lines (133 loc) · 4.96 KB
/
main.py
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import logging
import os
import zipfile
import shutil
from typing import Union
from uuid import uuid4
import geopandas as gpd
import pygltflib
from fastapi import FastAPI, HTTPException, UploadFile
from .gltf import gltf_transform
from pyproj.exceptions import CRSError
from starlette.background import BackgroundTask
from starlette.responses import FileResponse
from pyproj import CRS, Transformer
app = FastAPI()
logger = logging.getLogger("uvicorn.error")
def convert_gdf(gdf, crsTarget, crsSource, filename):
if not crsTarget:
logger("No target crs provided, using EPSG:4326 as fallback")
crsTarget = "EPSG:4326"
source_filename = filename.split(".")[0]
converted_filename = (
f"{source_filename}_{crsTarget.replace(':', '').lower()}_{uuid4()}"
)
if gdf.crs is None:
logger.info("No CRS found in the input file, using crsSource if provided")
if not crsSource:
raise HTTPException(
status_code=400,
detail="No CRS found in the input file and no crsSource provided",
)
try:
gdf.crs = crsSource
except CRSError as e:
logger.error(e)
raise HTTPException(
status_code=400, detail=f"Invalid source CRS: {crsSource}"
)
else:
logger.info(f"Input file has CRS: {gdf.crs}")
try:
gdf_converted = gdf.to_crs(crsTarget)
except CRSError as e:
logger.error(e)
raise HTTPException(status_code=400, detail=f"Invalid target CRS: {crsTarget}")
return gdf_converted, converted_filename
@app.post("/convert_geojson")
async def convert_geojson(
file: UploadFile, crsTarget: str, crsSource: Union[str, None] = None
):
print(file.filename)
gdf_converted, converted_filename = convert_gdf(
gpd.read_file(file.file), crsTarget, crsSource, file.filename
)
converted_geojson = f"{converted_filename}.geojson"
gdf_converted.to_file(converted_geojson, driver="GeoJSON")
def cleanup():
logger.info("Cleaning up")
os.remove(converted_geojson)
outname = (
f'{file.filename.split(".")[0]}_{crsTarget.replace(":", "").lower()}.geojson'
)
return FileResponse(
converted_geojson,
media_type="application/octet-stream",
filename=outname,
background=BackgroundTask(cleanup),
)
@app.post("/convert_shapefile")
async def convert_shapefile(
file: UploadFile, crsTarget: str, crsSource: Union[str, None] = None
):
gdf_converted, converted_filename = convert_gdf(
gpd.read_file(file.file), crsTarget, crsSource, file.filename
)
logger.info(f"Saving converted shapefile to {converted_filename}")
gdf_converted.to_file(converted_filename)
with zipfile.ZipFile(f"{converted_filename}.zip", 'w', zipfile.ZIP_STORED) as zipf:
for root, dirs, files in os.walk(converted_filename):
for f in files:
zipf.write(os.path.join(root, f), os.path.relpath(os.path.join(root, f), converted_filename))
# shutil.make_archive(converted_filename, "zip", converted_filename)
converted_shapefile_archive = f"{converted_filename}.zip"
def cleanup():
logger.info("Cleaning up")
shutil.rmtree(converted_filename)
os.remove(converted_shapefile_archive)
outname = f'{file.filename.split(".")[0]}_{crsTarget.replace(":", "").lower()}.zip'
return FileResponse(
converted_shapefile_archive,
media_type="application/octet-stream",
filename=outname,
background=BackgroundTask(cleanup),
)
@app.post("/convert_gltf")
async def convert_gltf(file: UploadFile, crsTarget: str, crsSource: str):
logger.info(f"Converting {file.filename} from {crsSource} to {crsTarget}")
name, suffix = file.filename.split(".")
input_name = f"{name}_{uuid4()}.gltf"
try:
transformer = Transformer.from_crs(
CRS.from_string(crsSource), CRS.from_string(crsTarget)
)
except CRSError as e:
logger.error(e)
raise HTTPException(
status_code=400,
detail=f"Invalid CRS transformation: {crsSource} to {crsTarget}",
)
if suffix != "glb":
with open(input_name, "w") as input_file:
input_file.write(file.file.read().decode("utf-8"))
else:
with open(input_name, "wb") as input_file:
input_file.write(file.file.read())
gltf = (
pygltflib.GLTF2().load(input_name)
if suffix != "glb"
else pygltflib.GLTF2().load_binary(input_name)
)
gltf_output = gltf_transform(gltf, transformer)
output_name = f"out_{input_name}"
gltf_output.save(output_name)
def cleanup():
logger.info("Cleaning up")
os.remove(input_name)
os.remove(output_name)
return FileResponse(
output_name,
media_type="application/octet-stream",
filename=f'{name}_{crsTarget.replace(":", "").lower()}.gltf',
background=BackgroundTask(cleanup),
)