-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdescartes_webapp.py
95 lines (73 loc) · 3.31 KB
/
descartes_webapp.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
'''
@author: Stephen Gadd, Docuracy Ltd, UK
'''
import logging
from logging.handlers import RotatingFileHandler
import sys
from flask import Flask, request, jsonify
import os
import shutil
import datetime
from tiles_to_tiff import create_geotiff
from extract_modern_roads import extract_modern_roads
from desCartes import desCartes
DATADIR = './data/'
app = Flask(__name__)
# create the logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# create the formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# create the file handler
file_handler = RotatingFileHandler('desCartes.log', maxBytes=100000, backupCount=10)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# create the stream handler
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.DEBUG)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
# redirect print statements to the logger
class PrintToLogger:
def __init__(self, logger, level):
self.logger = logger
self.level = level
def write(self, message):
if message.strip():
self.logger.log(self.level, message.strip())
sys.stdout = PrintToLogger(logger, logging.INFO)
sys.stderr = PrintToLogger(logger, logging.ERROR)
@app.route("/", methods=['POST'])
def get_desCartes():
try:
print("Starting get_desCartes function")
args = {k: v for k, v in request.form.items() if k not in ['viewID', 'bounds', 'url', 'zoom', 'modern_roads', 'default_values_dropdown']}
bounds = request.form.get('bounds')
if bounds:
EXTENT = bounds.split(",")
EXTENT = [float(x) for x in EXTENT]
RASTER_TILE_URL = request.form.get('url')
RASTER_TILE_ZOOM = int(request.form.get('zoom'))
MODERN_ROADFILE = request.form.get('modern_roads')
VIEW_ID = request.form.get('viewID')
OUTPUTDIR = './output/' + VIEW_ID + '/'
GEOTIFF_NAME = 'geo.tiff'
if not os.path.exists(OUTPUTDIR + GEOTIFF_NAME):
create_geotiff(RASTER_TILE_URL, OUTPUTDIR, GEOTIFF_NAME, EXTENT, RASTER_TILE_ZOOM)
extract_modern_roads(DATADIR, OUTPUTDIR, MODERN_ROADFILE, VIEW_ID, EXTENT, shapefile=False)
_, _, result_images, message = desCartes(OUTPUTDIR, **args)
logger.debug(f"desCartes function completed with result_images: {result_images}")
# Clean up output directory
now = datetime.datetime.now()
cutoff = now - datetime.timedelta(hours=8)
for item in os.listdir('./output/'):
path = os.path.join('./output/', item)
if os.path.isdir(path) and datetime.datetime.fromtimestamp(os.path.getctime(path)) < cutoff:
shutil.rmtree(path)
return jsonify({"result_images": result_images, "GeoPackage": OUTPUTDIR + 'desCartes.gpkg', "message": message})
else:
return jsonify({"message": "No bounds found in the request."})
except Exception as e:
logger.error("Error: %s", e, exc_info=True)
return jsonify({"error": f"Error: {e}, line: {sys.exc_info()[2].tb_lineno}, function: {sys._getframe().f_code.co_name}"})