-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_app.py
More file actions
893 lines (731 loc) · 30.1 KB
/
Copy pathweb_app.py
File metadata and controls
893 lines (731 loc) · 30.1 KB
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
#!/usr/bin/env python3
"""
Humanitarian Geocoder - Flask web application backed by PostGIS.
"""
import base64
import hashlib
import io
import json
import os
import tempfile
from functools import wraps
from threading import Lock
import pandas as pd
import psycopg2
import psycopg2.extras
from dotenv import load_dotenv
from flask import (
Flask,
jsonify,
redirect,
request,
send_from_directory,
session,
)
from flask_compress import Compress
from flask_cors import CORS
from werkzeug.utils import secure_filename
from geocode import (
geocode_address,
geocode_dataframe,
get_db_conn,
resolve_pcodes,
resolve_secondary_boundaries,
)
import xlsforms
load_dotenv()
app = Flask(__name__)
CORS(app)
Compress(app)
# ---------------------------------------------------------------------------
# In-memory response caches (invalidated on ingest, not on restart)
# ---------------------------------------------------------------------------
_countries_cache: dict = {} # {"data": [...], "json": "...", "etag": "..."}
_boundaries_cache: dict = {} # {(iso2, level): {"json": "...", "etag": "..."}}
_secondary_cache: dict = {} # {(iso2, type): {"json": "...", "etag": "..."}}
_cache_lock = Lock()
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024 # 16 MB
app.config["UPLOAD_FOLDER"] = tempfile.gettempdir()
app.config["SECRET_KEY"] = os.getenv(
"SECRET_KEY", "dev-secret-key-change-in-production"
)
USERNAME = os.getenv("LOGIN_USERNAME", "admin")
PASSWORD = os.getenv("LOGIN_PASSWORD", "admin")
# ---------------------------------------------------------------------------
# Auth helpers
# ---------------------------------------------------------------------------
def login_required(f):
@wraps(f)
def decorated(*args, **kwargs):
if not session.get("logged_in"):
return jsonify({"error": "Authentication required"}), 401
return f(*args, **kwargs)
return decorated
# ---------------------------------------------------------------------------
# Startup check
# ---------------------------------------------------------------------------
def check_db():
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute("SELECT COUNT(*) FROM cod_adm LIMIT 1")
print("Database connection OK")
except Exception as e:
print(f"WARNING: Database not reachable at startup: {e}")
# ---------------------------------------------------------------------------
# Auth routes
# ---------------------------------------------------------------------------
@app.route("/login", methods=["POST"])
def login():
username = request.form.get("username")
password = request.form.get("password")
if username == USERNAME and password == PASSWORD:
session["logged_in"] = True
return redirect("/")
return "Invalid username or password", 401
@app.route("/logout")
def logout():
session.pop("logged_in", None)
return redirect("/")
# ---------------------------------------------------------------------------
# Country list (DB-driven)
# ---------------------------------------------------------------------------
@app.route("/countries")
def countries():
"""All ingested countries with computed centroid for map centering."""
global _countries_cache
with _cache_lock:
cached = _countries_cache.get("json")
etag = _countries_cache.get("etag")
if cached:
if request.headers.get("If-None-Match") == etag:
return "", 304
from flask import Response
resp = Response(cached, mimetype="application/json")
resp.headers["ETag"] = etag
resp.headers["Cache-Control"] = "public, max-age=300"
return resp
try:
with get_db_conn() as conn:
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
cur.execute("""
SELECT iso2, iso3, country_name,
max_adm_level, center_lon, center_lat
FROM mv_countries
ORDER BY country_name
""")
rows = cur.fetchall()
result = []
for row in rows:
result.append({
"code": row["iso2"],
"iso3": row["iso3"],
"name": row["country_name"],
"key": row["iso2"].lower(),
"max_adm_level": row["max_adm_level"],
"map_center": {
"lat": round(row["center_lat"], 4) if row["center_lat"] else 0,
"lon": round(row["center_lon"], 4) if row["center_lon"] else 0,
"zoom": 6,
},
})
body = json.dumps(result)
etag = hashlib.md5(body.encode()).hexdigest()
with _cache_lock:
_countries_cache["json"] = body
_countries_cache["etag"] = etag
if request.headers.get("If-None-Match") == etag:
return "", 304
from flask import Response
resp = Response(body, mimetype="application/json")
resp.headers["ETag"] = etag
resp.headers["Cache-Control"] = "public, max-age=300"
return resp
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------------------------------------------------------------------
# Available admin levels for a country
# ---------------------------------------------------------------------------
@app.route("/api/available_levels")
def available_levels():
"""Return the distinct admin levels present in the DB for a country."""
iso2 = request.args.get("country", "").upper()
if not iso2:
return jsonify({"error": "country parameter required"}), 400
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
# Only include a level if the level's own pcode column is
# actually populated — filters out sparse/empty higher levels
# written by the ingest even though the country lacks that data.
cur.execute(
"""
SELECT DISTINCT adm_level FROM cod_adm
WHERE iso2 = %s
AND CASE adm_level
WHEN 1 THEN adm1_pcode
WHEN 2 THEN adm2_pcode
WHEN 3 THEN adm3_pcode
WHEN 4 THEN adm4_pcode
END IS NOT NULL
ORDER BY adm_level
""",
[iso2],
)
levels = [r[0] for r in cur.fetchall()]
return jsonify({"iso2": iso2, "levels": levels})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------------------------------------------------------------------
# Admin-level name list (province filter)
# ---------------------------------------------------------------------------
@app.route("/api/admin_levels")
def get_admin_levels():
"""Distinct names at a given admin level for one country."""
try:
iso2 = request.args.get("country", "").upper()
if not iso2:
return jsonify({"error": "country parameter required"}), 400
try:
level = int(request.args.get("level", 1))
except ValueError:
return jsonify({"error": "level must be an integer"}), 400
if level not in range(5):
return jsonify({"error": "level must be 0-4"}), 400
name_col = f"adm{level}_name"
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute(
f"""
SELECT DISTINCT {name_col}
FROM cod_adm
WHERE iso2 = %s AND adm_level >= %s AND {name_col} IS NOT NULL
ORDER BY {name_col}
""",
[iso2, level],
)
names = [r[0] for r in cur.fetchall()]
return jsonify({
"iso2": iso2,
"level": level,
"label": f"ADM{level}",
"values": names,
})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------------------------------------------------------------------
# GET /boundaries.geojson -- boundary polygons for a country/level (public)
# ---------------------------------------------------------------------------
@app.route("/boundaries.geojson")
def boundaries_geojson():
"""
Boundary polygons for a given country and admin level as GeoJSON.
Results are cached in memory after the first request per (country, level).
Query params:
country ISO2 code (required)
level admin level integer, default 1
"""
iso2 = request.args.get("country", "").upper()
if not iso2:
return jsonify({"error": "country parameter required"}), 400
try:
level = int(request.args.get("level", 1))
except ValueError:
return jsonify({"error": "level must be an integer"}), 400
if level not in range(5):
return jsonify({"error": "level must be 0-4"}), 400
cache_key = (iso2, level)
with _cache_lock:
cached = _boundaries_cache.get(cache_key)
if cached:
etag = cached["etag"]
if request.headers.get("If-None-Match") == etag:
return "", 304
from flask import Response
resp = Response(cached["json"], mimetype="application/json")
resp.headers["ETag"] = etag
resp.headers["Cache-Control"] = "public, max-age=3600"
return resp
name_col = f"adm{level}_name"
pcode_col = f"adm{level}_pcode"
# Include all parent level columns so the frontend can show the full hierarchy
parent_cols = "".join(
f"adm{n}_name, adm{n}_pcode, " for n in range(level)
)
try:
with get_db_conn() as conn:
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
cur.execute(
f"""
SELECT
{pcode_col} AS pcode,
{name_col} AS name,
{parent_cols}
ST_AsGeoJSON(ST_SimplifyPreserveTopology(geom, 0.001))::json AS geometry
FROM cod_adm
WHERE iso2 = %s AND adm_level = %s
""",
[iso2, level],
)
rows = cur.fetchall()
except Exception as e:
return jsonify({"error": str(e)}), 500
features = []
for row in rows:
geom = row.pop("geometry")
features.append({
"type": "Feature",
"geometry": geom,
"properties": dict(row),
})
fc = json.dumps({"type": "FeatureCollection", "features": features})
etag = hashlib.md5(fc.encode()).hexdigest()
with _cache_lock:
_boundaries_cache[cache_key] = {"json": fc, "etag": etag}
if request.headers.get("If-None-Match") == etag:
return "", 304
from flask import Response
resp = Response(fc, mimetype="application/json")
resp.headers["ETag"] = etag
resp.headers["Cache-Control"] = "public, max-age=3600"
return resp
# ---------------------------------------------------------------------------
# Secondary (non-administrative) boundary layers, e.g. health zones
# ---------------------------------------------------------------------------
@app.route("/api/secondary_types")
def secondary_types():
"""
Return the distinct secondary boundary types available for a country,
so the frontend can offer matching overlay toggles. Empty list when none.
Query params:
country ISO2 code (required)
"""
iso2 = request.args.get("country", "").upper()
if not iso2:
return jsonify({"error": "country parameter required"}), 400
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT DISTINCT boundary_type FROM secondary_boundaries "
"WHERE iso2 = %s ORDER BY boundary_type",
[iso2],
)
types = [r[0] for r in cur.fetchall()]
except Exception:
# Table may not exist yet (no secondary data loaded) — treat as none.
types = []
return jsonify({"iso2": iso2, "types": types})
@app.route("/secondary_boundaries.geojson")
def secondary_boundaries_geojson():
"""
Secondary boundary polygons (e.g. health zones) for a country as GeoJSON.
Cached in memory per (country, type), mirroring /boundaries.geojson.
Query params:
country ISO2 code (required)
type boundary type, e.g. 'health' (default: 'health')
"""
iso2 = request.args.get("country", "").upper()
if not iso2:
return jsonify({"error": "country parameter required"}), 400
btype = request.args.get("type", "health").lower()
cache_key = (iso2, btype)
with _cache_lock:
cached = _secondary_cache.get(cache_key)
if cached:
etag = cached["etag"]
if request.headers.get("If-None-Match") == etag:
return "", 304
from flask import Response
resp = Response(cached["json"], mimetype="application/json")
resp.headers["ETag"] = etag
resp.headers["Cache-Control"] = "public, max-age=3600"
return resp
try:
with get_db_conn() as conn:
with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
cur.execute(
"""
SELECT
name,
ref_dhis2,
source_id,
ST_AsGeoJSON(ST_SimplifyPreserveTopology(geom, 0.001))::json
AS geometry
FROM secondary_boundaries
WHERE iso2 = %s AND boundary_type = %s
""",
[iso2, btype],
)
rows = cur.fetchall()
except Exception as e:
return jsonify({"error": str(e)}), 500
features = []
for row in rows:
geom = row.pop("geometry")
features.append({
"type": "Feature",
"geometry": geom,
"properties": dict(row),
})
fc = json.dumps({"type": "FeatureCollection", "features": features})
etag = hashlib.md5(fc.encode()).hexdigest()
with _cache_lock:
_secondary_cache[cache_key] = {"json": fc, "etag": etag}
if request.headers.get("If-None-Match") == etag:
return "", 304
from flask import Response
resp = Response(fc, mimetype="application/json")
resp.headers["ETag"] = etag
resp.headers["Cache-Control"] = "public, max-age=3600"
return resp
# ---------------------------------------------------------------------------
# GET /xlsform -- download a cascading-select XLSForm for a country (public)
# ---------------------------------------------------------------------------
@app.route("/xlsform")
def download_xlsform():
"""
Stream a pre-generated KoboCollect XLSForm with cascading admin-boundary
select_one questions for a country. Served from disk
({XLSFORM_DIR}/{ISO2}.xlsx); generated on the fly and cached to disk if the
file is missing (e.g. a newly ingested country).
Query params:
country ISO2 code (required)
"""
from flask import Response
iso2 = request.args.get("country", "").upper()
if not iso2:
return jsonify({"error": "country parameter required"}), 400
path = os.path.join(xlsforms.XLSFORM_DIR, f"{iso2}.xlsx")
country_name = iso2
try:
if os.path.exists(path):
with open(path, "rb") as f:
data = f.read()
# Recover a friendlier filename without rebuilding the workbook.
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT country_name FROM mv_countries WHERE iso2 = %s LIMIT 1",
[iso2],
)
row = cur.fetchone()
if row and row[0]:
country_name = row[0]
except Exception:
pass
else:
data, country_name = xlsforms.build_xlsform(iso2)
try:
os.makedirs(xlsforms.XLSFORM_DIR, exist_ok=True)
with open(path, "wb") as f:
f.write(data)
except OSError:
pass # Read-only dir: still serve the in-memory bytes.
except ValueError as e:
return jsonify({"error": str(e)}), 404
except Exception as e:
return jsonify({"error": str(e)}), 500
etag = hashlib.md5(data).hexdigest()
if request.headers.get("If-None-Match") == etag:
return "", 304
out_name = f"{iso2} ({country_name}).xlsx"
resp = Response(
data,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
resp.headers["Content-Disposition"] = f'attachment; filename="{out_name}"'
resp.headers["ETag"] = etag
resp.headers["Cache-Control"] = "public, max-age=3600"
return resp
# ---------------------------------------------------------------------------
# GET /geocode -- coordinate or address lookup (public)
# ---------------------------------------------------------------------------
@app.route("/geocode", methods=["GET"])
def geocode_get():
"""
Resolve P-codes from coordinates or a free-text address.
Query parameters:
lat / latitude -- decimal latitude
lon / longitude -- decimal longitude
address -- free-text address (geocoded via Google Places)
country -- ISO2 code to scope the lookup (optional)
"""
try:
lat_raw = request.args.get("lat") or request.args.get("latitude")
lon_raw = request.args.get("lon") or request.args.get("longitude")
address_input = request.args.get("address", "").strip()
iso2 = request.args.get("country", "").upper() or None
confidence = None
if lat_raw is not None and lon_raw is not None:
try:
lat = float(lat_raw)
lon = float(lon_raw)
except ValueError:
return jsonify({"error": "Invalid latitude or longitude"}), 400
elif address_input:
result = geocode_address(address_input)
if not result:
return jsonify({"success": False, "error": "Could not geocode address"}), 404
lat, lon, confidence = result
else:
return jsonify({"error": "Provide lat/lon or address parameters"}), 400
pcodes = resolve_pcodes(lat, lon, iso2=iso2)
if not pcodes:
return jsonify({"success": False, "error": "Point outside known boundaries"}), 404
response = {"success": True, "latitude": lat, "longitude": lon}
if confidence:
response["confidence"] = confidence
response.update(pcodes)
response.update(resolve_secondary_boundaries(lat, lon, iso2=iso2))
return jsonify(response)
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------------------------------------------------------------------
# POST /geocode -- CSV/XLSX batch upload (requires login)
# ---------------------------------------------------------------------------
@app.route("/geocode", methods=["POST"])
@login_required
def geocode_post():
try:
iso2 = request.form.get("country", "").upper() or None
output_filename = request.form.get("output_filename", "").strip()
# Look up country name to use as geocoding hint
country_hint = None
if iso2:
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT DISTINCT country_name FROM cod_adm WHERE iso2 = %s LIMIT 1",
[iso2],
)
row = cur.fetchone()
if row:
country_hint = row[0]
except Exception:
pass
if "file" not in request.files:
return jsonify({"error": "No file uploaded"}), 400
file = request.files["file"]
if not file.filename:
return jsonify({"error": "No file selected"}), 400
limit = request.form.get("limit", type=int)
try:
filename = secure_filename(file.filename)
if filename.endswith((".xlsx", ".xls")):
df = pd.read_excel(file, engine="openpyxl")
else:
df = pd.read_csv(file, encoding="utf-8-sig", sep=";")
if "date" in df.columns:
def convert_date(date_str):
if pd.isna(date_str):
return date_str
try:
parts = str(date_str).strip().split("/")
if len(parts) == 2:
month, day = parts
return f"2025-{int(month):02d}-{int(day):02d}"
return date_str
except Exception:
return date_str
df["date"] = df["date"].apply(convert_date)
if limit and limit > 0:
df = df.head(limit)
if "address" not in df.columns:
return jsonify({"error": 'File must have an "address" column'}), 400
except Exception as e:
return jsonify({"error": f"Failed to read file: {e}"}), 400
# Geocode addresses to (lat, lon) points
points_gdf, stats = geocode_dataframe(
df, address_column="address", delay=0.05, country_hint=country_hint
)
# Resolve P-codes per row via PostGIS
pcode_rows = []
for _, row in points_gdf.iterrows():
if row.geometry is None:
pcode_rows.append({})
continue
lat, lon = row.geometry.y, row.geometry.x
pcodes = resolve_pcodes(lat, lon, iso2=iso2) or {}
pcodes.update(resolve_secondary_boundaries(lat, lon, iso2=iso2))
pcode_rows.append(pcodes)
pcode_df = pd.DataFrame(pcode_rows)
result_df = pd.concat(
[
pd.DataFrame(points_gdf.drop(columns="geometry")).reset_index(drop=True),
pcode_df.reset_index(drop=True),
],
axis=1,
)
output = io.BytesIO()
output_format = request.form.get("format", "csv")
base_filename = (
output_filename.rsplit(".", 1)[0] if output_filename else "geocoded_addresses"
)
if output_format == "xlsx":
result_df.to_excel(output, index=False, engine="openpyxl")
mimetype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
out_filename = f"{base_filename}.xlsx"
else:
result_df.to_csv(output, index=False)
mimetype = "text/csv"
out_filename = f"{base_filename}.csv"
output.seek(0)
file_data = base64.b64encode(output.read()).decode("utf-8")
return jsonify({
"success": True,
"stats": stats,
"file_data": file_data,
"filename": out_filename,
"mimetype": mimetype,
})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------------------------------------------------------------------
# POST /geocode_single -- single address lookup (public)
# ---------------------------------------------------------------------------
@app.route("/geocode_single", methods=["POST"])
def geocode_single():
"""Geocode a single address or coordinate string."""
try:
data = request.get_json() if request.is_json else request.form
address_input = data.get("address", "").strip()
iso2 = data.get("country", "").upper() or None
if not address_input:
return jsonify({"error": "address is required"}), 400
# Look up country name to use as a geocoding hint (improves disambiguation).
country_hint = None
if iso2:
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT country_name FROM mv_countries WHERE iso2 = %s LIMIT 1",
(iso2,),
)
row = cur.fetchone()
if row:
country_hint = row[0]
except Exception:
pass
result = geocode_address(address_input, country_hint=country_hint)
if not result:
return jsonify({"success": False, "error": "Could not geocode the address"})
lat, lon, confidence = result
# Resolve pcodes from actual coordinates without country filter — the
# geocoded location already determines the country.
pcodes = resolve_pcodes(lat, lon) or {}
secondary = resolve_secondary_boundaries(lat, lon)
return jsonify({
"success": True,
"address": address_input,
"latitude": lat,
"longitude": lon,
"confidence": confidence,
**pcodes,
**secondary,
})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------------------------------------------------------------------
# POST /reverse_geocode -- lat/lon to P-codes (public, used by map clicks)
# ---------------------------------------------------------------------------
@app.route("/reverse_geocode", methods=["POST"])
def reverse_geocode():
"""Resolve P-codes from a latitude/longitude coordinate."""
try:
data = request.get_json() if request.is_json else request.form
lat_raw = data.get("latitude") or data.get("lat")
lon_raw = data.get("longitude") or data.get("lon")
iso2 = data.get("country", "").upper() or None
if lat_raw is None or lon_raw is None:
return jsonify({"error": "latitude and longitude are required"}), 400
try:
lat = float(lat_raw)
lon = float(lon_raw)
except ValueError:
return jsonify({"error": "Invalid latitude or longitude"}), 400
pcodes = resolve_pcodes(lat, lon, iso2=iso2)
if not pcodes:
return jsonify({"success": False, "error": "Point outside known boundaries"})
secondary = resolve_secondary_boundaries(lat, lon, iso2=iso2)
return jsonify(
{"success": True, "latitude": lat, "longitude": lon, **pcodes, **secondary}
)
except Exception as e:
return jsonify({"error": str(e)}), 500
# ---------------------------------------------------------------------------
# Health check
# ---------------------------------------------------------------------------
@app.route("/health")
def health():
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute("SELECT COUNT(DISTINCT iso2) FROM cod_adm")
country_count = cur.fetchone()[0]
return jsonify({"status": "ok", "countries_in_db": country_count})
except Exception as e:
return jsonify({"status": "degraded", "error": str(e)}), 500
# ---------------------------------------------------------------------------
# Auth state (used by SPA to check session)
# ---------------------------------------------------------------------------
@app.route("/api/auth")
def auth_state():
return jsonify({"logged_in": bool(session.get("logged_in"))})
# ---------------------------------------------------------------------------
# Cache invalidation (called after ingest)
# ---------------------------------------------------------------------------
@app.route("/api/cache/clear", methods=["POST"])
@login_required
def clear_cache():
"""Invalidate the in-memory countries and boundaries caches after a data reload."""
with _cache_lock:
_countries_cache.clear()
_boundaries_cache.clear()
_secondary_cache.clear()
# Rebuild the materialized view so the next cold-cache hit is instant.
try:
with get_db_conn() as conn:
with conn.cursor() as cur:
cur.execute("REFRESH MATERIALIZED VIEW CONCURRENTLY mv_countries")
conn.commit()
except Exception as e:
return jsonify({"status": "error", "message": f"Cache cleared but view refresh failed: {e}"}), 500
# Regenerate XLSForms so they track the updated boundary layers. Best-effort:
# a generation failure must not fail the cache-clear. Regenerate just the
# ingested country if named, otherwise all of them.
data = request.get_json(silent=True) if request.is_json else request.form
country = (data.get("country", "").upper() if data else "") or None
try:
if country:
xlsforms.generate_one(country)
else:
xlsforms.generate_all()
except Exception as e:
return jsonify({
"status": "ok",
"message": f"Cache cleared; XLSForm regeneration failed: {e}",
})
return jsonify({"status": "ok", "message": "Cache cleared"})
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# SPA catch-all — serve the React build for any non-API route
# ---------------------------------------------------------------------------
_STATIC_FOLDER = os.path.join(os.path.dirname(__file__), "static")
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def serve_spa(path: str):
"""Serve the compiled React SPA for any route not matched by the API."""
target = os.path.join(_STATIC_FOLDER, path)
if path and os.path.exists(target):
return send_from_directory(_STATIC_FOLDER, path)
return send_from_directory(_STATIC_FOLDER, "index.html")
if __name__ == "__main__":
check_db()
port = int(os.getenv("PORT", 5001))
app.run(debug=True, host="0.0.0.0", port=port)