File size: 22,528 Bytes
633e544
 
 
 
 
 
 
 
413c3a0
 
633e544
4f74291
153e372
633e544
 
 
 
 
 
 
 
 
 
5c10f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633e544
 
 
 
 
 
5c10f64
633e544
 
5c10f64
633e544
 
 
 
5c10f64
 
633e544
 
5c10f64
 
 
 
 
 
 
 
633e544
5c10f64
 
633e544
 
5c10f64
 
633e544
5c10f64
633e544
413c3a0
5c10f64
633e544
 
 
 
 
 
 
 
 
 
5c10f64
 
8b7f106
 
633e544
5c10f64
 
 
 
 
8b7f106
5c10f64
8b7f106
 
5c10f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633e544
 
 
5c10f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633e544
 
 
 
 
5c10f64
8b7f106
5c10f64
 
633e544
 
 
 
 
5c10f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633e544
 
 
 
 
 
 
34fb759
633e544
 
 
e0562f0
 
 
 
 
 
 
 
e2d381e
 
 
 
 
 
 
 
 
 
 
 
5c10f64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633e544
 
 
5c10f64
633e544
 
 
 
 
 
 
 
 
 
 
5c10f64
633e544
 
 
 
 
 
 
 
 
 
 
 
 
34fb759
 
 
633e544
e0562f0
 
 
 
633e544
 
 
 
e0562f0
 
 
 
 
 
 
 
 
633e544
e0562f0
 
633e544
 
 
 
 
 
e2d381e
 
633e544
 
 
 
e0562f0
 
 
633e544
e0562f0
633e544
 
 
5c10f64
633e544
5c10f64
633e544
 
5c10f64
 
 
 
 
 
34fb759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633e544
34fb759
 
 
633e544
 
5c10f64
633e544
 
 
 
34fb759
 
633e544
5c10f64
 
2ec56ea
34fb759
5c10f64
 
34fb759
633e544
 
413c3a0
 
 
5c10f64
413c3a0
 
 
633e544
413c3a0
 
 
 
5c10f64
413c3a0
 
 
 
633e544
 
5c10f64
21392e0
5c10f64
633e544
5c10f64
 
 
 
633e544
 
 
 
 
e0562f0
5c10f64
 
e0562f0
5c10f64
 
e0562f0
5c10f64
 
e0562f0
5c10f64
 
633e544
5c10f64
 
e0562f0
 
 
 
 
 
 
633e544
5c10f64
 
 
 
 
34fb759
 
 
5c10f64
 
633e544
 
34fb759
 
 
633e544
5c10f64
34fb759
633e544
e0562f0
 
 
34fb759
 
 
 
413c3a0
4f74291
413c3a0
 
633e544
5c10f64
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
import os
import json
import tempfile

import gradio as ui
import geopandas as gpd
import pandas as pd
from huggingface_hub import hf_hub_download
from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

DATA_REPO = 'elikoy/mapviewer-data'
HF_TOKEN = os.environ.get('HF_TOKEN')

print('Loading Maastricht parcel snapshot ...')
PARCELS = gpd.read_parquet(
    hf_hub_download(DATA_REPO, 'parcels.parquet', repo_type='dataset', token=HF_TOKEN)
).to_crs(28992)
BUILDINGS = gpd.read_parquet(
    hf_hub_download(DATA_REPO, 'buildings.parquet', repo_type='dataset', token=HF_TOKEN)
).to_crs(28992)

# Merge enriched residential parcel attributes (Address, Postcode, GPS)
try:
    local_enriched = './data/parcels_residential_enriched.parquet'
    if os.path.exists(local_enriched):
        enr_df = pd.read_parquet(local_enriched)
    else:
        enr_df = pd.read_parquet(
            hf_hub_download(DATA_REPO, 'parcels_residential_enriched.parquet', repo_type='dataset', token=HF_TOKEN)
        )
    enr_cols = ['identificatieLokaalID', 'straat_en_huisnummer', 'postcode', 'gps_coordinates']
    PARCELS = PARCELS.merge(enr_df[enr_cols], on='identificatieLokaalID', how='left')
    print('Enriched parcel attributes merged successfully.')
except Exception as e:
    print('Warning: could not load enriched parcel attributes:', e)
    for col in ['straat_en_huisnummer', 'postcode', 'gps_coordinates']:
        if col not in PARCELS.columns:
            PARCELS[col] = None

print('parcels', PARCELS.shape, '| buildings', BUILDINGS.shape)

ID_COL = 'identificatieLokaalID'
DATA = pd.DataFrame(PARCELS.drop(columns='geometry'))

TABLE_COLS = [
    ID_COL, 'straat_en_huisnummer', 'postcode', 'kadastraleGemeenteWaarde', 'sectie', 'perceelnummer',
    'total_parcel_area', 'total_building_footprint', 'calculated_garden_area',
    'building_coverage_pct', 'n_buildings', 'bouwjaar_min', 'bouwjaar_max',
    'gebruiksdoel', 'has_woonfunctie', 'gps_coordinates',
]

RENAME = {
    ID_COL: 'Kadaster_ID',
    'straat_en_huisnummer': 'Adres',
    'postcode': 'Postcode',
    'kadastraleGemeenteWaarde': 'Gemeente',
    'sectie': 'Sectie',
    'perceelnummer': 'Perceelnummer',
    'total_parcel_area': 'Perceel_m2',
    'total_building_footprint': 'Bebouwing_m2',
    'calculated_garden_area': 'Tuin_m2',
    'building_coverage_pct': 'Bebouwing_pct',
    'n_buildings': 'Aantal_panden',
    'bouwjaar_min': 'Bouwjaar_min',
    'bouwjaar_max': 'Bouwjaar_max',
    'gebruiksdoel': 'Gebruiksdoel',
    'has_woonfunctie': 'Woonfunctie',
    'gps_coordinates': 'GPS',
}

DATATYPES = ['str', 'str', 'str', 'str', 'str', 'number', 'number', 'number', 'number',
             'number', 'number', 'number', 'number', 'str', 'bool', 'str', 'html']

NUM_ROUND = ['Perceel_m2', 'Bebouwing_m2', 'Tuin_m2', 'Bebouwing_pct']

VIEW_CELL = ('<a href="/map/{pid}" target="_blank" style="color:#2563eb;font-weight:600;'
             'text-decoration:underline;white-space:nowrap">&#128506;&#65039; Bekijken</a>')

GEMEENTEN = sorted(DATA['kadastraleGemeenteWaarde'].dropna().unique().tolist())
SECTIES = sorted(DATA['sectie'].dropna().unique().tolist())
DOELEN = sorted(DATA['gebruiksdoel'].dropna().unique().tolist())
PARCEL_MAX = float(int(DATA['total_parcel_area'].max()) + 1)

MAP_TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<meta name='viewport' content='width=device-width, initial-scale=1.0'/>
<title>Perceelkaart & Street View</title>
<link rel='stylesheet' href='https://unpkg.com/leaflet@1.9.4/dist/leaflet.css' crossorigin=''/>
<script src='https://unpkg.com/leaflet@1.9.4/dist/leaflet.js' crossorigin=''></script>
<style>
html, body { height: 100%; margin: 0; padding: 0; font-family: system-ui, -apple-system, sans-serif; overflow: hidden; background: #111827; }
.split-container { display: flex; width: 100vw; height: 100vh; }
.pane { flex: 1; position: relative; height: 100%; }
.pane-left { border-right: 2px solid #374151; }
.pane-right { display: flex; flex-direction: column; background: #1f2937; }
#map { position: absolute; top: 0; bottom: 0; left: 0; right: 0; }
#legend { position: absolute; bottom: 24px; left: 10px; z-index: 1000; background: rgba(255,255,255,.95); padding: 10px 12px; font: 13px/1.5 system-ui, sans-serif; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,.35); color: #1f2937; }
.sw { display: inline-block; width: 14px; height: 14px; margin-right: 8px; vertical-align: -3px; border-radius: 3px; }
.leaflet-control-zoom a { font-size: 20px !important; line-height: 28px !important; width: 32px !important; height: 32px !important; }

.right-header {
  height: 48px;
  background: #111827;
  border-bottom: 1px solid #374151;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-sizing: border-box;
  color: #f3f4f6;
  z-index: 10;
}
.right-header-title { font-weight: 600; font-size: 13px; color: #f3f4f6; display: flex; align-items: center; gap: 8px; white-space: nowrap; }
.right-header-actions { display: flex; gap: 6px; align-items: center; }
.btn-sm {
  padding: 5px 10px;
  font-size: 12px;
  font-weight: 500;
  border-radius: 6px;
  border: 1px solid #4b5563;
  background: #374151;
  color: #e5e7eb;
  text-decoration: none;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  transition: all 0.15s ease;
  white-space: nowrap;
}
.btn-sm:hover { background: #4b5563; color: #ffffff; }
.btn-sm.active { background: #2563eb; color: #ffffff; border-color: #2563eb; }

#right-iframe { flex: 1; width: 100%; height: calc(100% - 48px); border: 0; background: #111827; }

@media (max-width: 768px) {
  .split-container { flex-direction: column; }
  .pane-left { height: 50vh; border-right: none; border-bottom: 2px solid #374151; }
  .pane-right { height: 50vh; }
}
</style>
</head>
<body>
<div class='split-container'>
  <div class='pane pane-left'>
    <div id='map'></div>
    <div id='legend'>
      <div><span class='sw' style='background:#ff6a00'></span>Perceel</div>
      <div><span class='sw' style='background:#3b82f6'></span>BAG-gebouwen</div>
    </div>
  </div>
  <div class='pane pane-right'>
    <div class='right-header'>
      <div class='right-header-title'>
        <span>📍 Google Maps / Street View</span>
      </div>
      <div class='right-header-actions'>
        <button id='btn-sat' class='btn-sm active' onclick='setGoogleMode("satellite")'>Satelliet</button>
        <button id='btn-map' class='btn-sm' onclick='setGoogleMode("roadmap")'>Kaart</button>
        <a id='link-sv' class='btn-sm' target='_blank' href='#'>Street View ↗</a>
        <a id='link-gm' class='btn-sm' target='_blank' href='#'>Google Maps ↗</a>
      </div>
    </div>
    <iframe id='right-iframe' allowfullscreen loading='lazy' referrerpolicy='no-referrer-when-downgrade'></iframe>
  </div>
</div>
<script>
var parcel = __PARCEL__;
var buildings = __BUILDINGS__;
var popupHtml = __POPUP__;
var map = L.map('map', { zoomControl: false, maxZoom: 21 });
L.control.zoom({ position: 'topright' }).addTo(map);
var aerial = L.tileLayer('https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg', { maxZoom: 21, maxNativeZoom: 18, attribution: '&copy; PDOK / Beeldmateriaal' });
var osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 21, maxNativeZoom: 19, attribution: '&copy; OpenStreetMap' });
aerial.addTo(map);
var parcelLayer = L.geoJSON(parcel, { style: { color: '#ff6a00', weight: 3, fillColor: '#ff6a00', fillOpacity: 0.12 } }).addTo(map);
parcelLayer.bindPopup(popupHtml);
var bLayer = L.geoJSON(buildings, { style: { color: '#1d4ed8', weight: 1, fillColor: '#3b82f6', fillOpacity: 0.45 } });
bLayer.addTo(map);
L.control.layers({ 'Luchtfoto (PDOK)': aerial, 'Straatkaart (OSM)': osm }, { 'BAG-gebouwen': bLayer, 'Perceel': parcelLayer }, { collapsed: false, position: 'topright' }).addTo(map);
try { map.fitBounds(parcelLayer.getBounds().pad(0.25), { maxZoom: 19 }); } catch (e) { map.setView([50.8514, 5.6910], 16); }

var currentLat = 50.8514;
var currentLng = 5.6910;
try {
  var c = parcelLayer.getBounds().getCenter();
  currentLat = c.lat;
  currentLng = c.lng;
} catch (e) {}

var googleMode = 'satellite';

function updateGooglePane(lat, lng) {
  currentLat = lat;
  currentLng = lng;
  var latStr = lat.toFixed(6);
  var lngStr = lng.toFixed(6);
  var tParam = (googleMode === 'satellite') ? 'k' : 'm';
  var iframeUrl = 'https://maps.google.com/maps?q=' + latStr + ',' + lngStr + '&t=' + tParam + '&z=19&ie=UTF8&iwloc=&output=embed';
  var iframe = document.getElementById('right-iframe');
  if (iframe && iframe.src !== iframeUrl) {
    iframe.src = iframeUrl;
  }
  var svLink = document.getElementById('link-sv');
  if (svLink) {
    svLink.href = 'https://www.google.com/maps/@?api=1&map_action=pano&viewpoint=' + latStr + ',' + lngStr;
  }
  var gmLink = document.getElementById('link-gm');
  if (gmLink) {
    gmLink.href = 'https://www.google.com/maps/search/?api=1&query=' + latStr + ',' + lngStr;
  }
}

function setGoogleMode(mode) {
  googleMode = mode;
  document.getElementById('btn-sat').classList.toggle('active', mode === 'satellite');
  document.getElementById('btn-map').classList.toggle('active', mode === 'roadmap');
  updateGooglePane(currentLat, currentLng);
}

updateGooglePane(currentLat, currentLng);

map.on('click', function(e) {
  updateGooglePane(e.latlng.lat, e.latlng.lng);
});
</script>
</body>
</html>"""

CSS = """
#results-table { max-height: 620px; }
.modal-hint { font-size: 12px; color: #6b7280; }
#table-top-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; }
"""


def _fmt(v):
    try:
        fv = float(v)
        return str(int(fv)) if fv.is_integer() else str(round(fv, 1))
    except Exception:
        return str(v)


def _parse_int(v):
    if v is None:
        return None
    s = str(v).strip()
    if not s:
        return None
    try:
        return int(s)
    except ValueError:
        return None


def _popup_html(row):
    addr = str(row.get('straat_en_huisnummer') or '').strip()
    pc = str(row.get('postcode') or '').strip()
    addr_line = ''
    if addr and addr != 'None' and addr != 'nan':
        pc_part = f" ({pc})" if pc and pc != 'None' and pc != 'nan' else ""
        addr_line = f'<div style=\"font-size:14px;font-weight:700;color:#1d4ed8;margin-bottom:4px;\">📍 {addr}{pc_part}</div>'
    return (
        addr_line
        + '<b>Perceel ' + str(row.get('sectie', '')) + '-' + str(row.get('perceelnummer', '')) + '</b><br/>'
        + 'Kadaster-ID: ' + str(row[ID_COL]) + '<br/>'
        + 'Gemeente: ' + str(row.get('kadastraleGemeenteWaarde', '')) + '<br/>'
        + 'Perceel: ' + str(round(float(row.get('total_parcel_area', 0.0)), 1)) + ' m\u00b2<br/>'
        + 'Bebouwing: ' + str(round(float(row.get('total_building_footprint', 0.0)), 1))
        + ' m\u00b2 (' + str(int(row.get('n_buildings', 0))) + ' panden)<br/>'
        + 'Tuin: <b>' + str(round(float(row.get('calculated_garden_area', 0.0)), 1)) + ' m\u00b2</b>'
    )


def build_map(pid):
    sel = PARCELS[PARCELS[ID_COL] == pid]
    if sel.empty:
        return '<p>Perceel niet gevonden in de momentopname.</p>', 'Perceel niet gevonden'
    row = sel.iloc[0]
    geom = sel.geometry.iloc[0]
    parcel_geo = json.loads(sel.to_crs(4326).geometry.to_json())['features'][0]['geometry']
    try:
        near = BUILDINGS.iloc[list(BUILDINGS.sindex.query(geom, predicate='intersects'))]
    except Exception:
        near = BUILDINGS[BUILDINGS.intersects(geom)]
    if len(near):
        bjson = json.loads(near.to_crs(4326).geometry.to_json())
    else:
        bjson = {'type': 'FeatureCollection', 'features': []}
    popup = _popup_html(row)
    inner = (MAP_TEMPLATE
             .replace('__PARCEL__', json.dumps(parcel_geo))
             .replace('__BUILDINGS__', json.dumps(bjson))
             .replace('__POPUP__', json.dumps(popup)))
    srcdoc = inner.replace('&', '&amp;').replace('"', '&quot;')
    iframe = ('<iframe style="width:100%;height:540px;border:0;border-radius:10px" '
              'sandbox="allow-scripts allow-same-origin" srcdoc="' + srcdoc + '"></iframe>')
    title = ('Perceel ' + str(row.get('sectie', '')) + '-' + str(row.get('perceelnummer', ''))
             + ' \u00b7 ' + str(row.get('kadastraleGemeenteWaarde', ''))
             + ' \u00b7 ' + str(int(row.get('n_buildings', 0))) + ' pand(en)')
    return iframe, title


def get_filtered_df(garden_lo, garden_hi, parcel_lo, parcel_hi, cov_lo, cov_hi, nb_lo, nb_hi,
                    gemeenten, secties, perc_lo, perc_hi, year_lo, year_hi, excl_year,
                    doelen, residential, idq):
    df = DATA
    if garden_lo is None:
        garden_lo = 0.0
    if garden_hi is None:
        garden_hi = 1e12
    if parcel_lo is None:
        parcel_lo = 0.0
    if parcel_hi is None:
        parcel_hi = PARCEL_MAX
    if cov_lo is None:
        cov_lo = 0.0
    if cov_hi is None:
        cov_hi = 100.0
    if nb_lo is None:
        nb_lo = 0
    if nb_hi is None:
        nb_hi = 10 ** 9
    m = df['calculated_garden_area'].between(garden_lo, garden_hi)
    m = m & df['total_parcel_area'].between(parcel_lo, parcel_hi)
    m = m & df['building_coverage_pct'].between(cov_lo, cov_hi)
    m = m & df['n_buildings'].between(nb_lo, nb_hi)
    if gemeenten:
        m = m & df['kadastraleGemeenteWaarde'].isin(gemeenten)
    if secties:
        m = m & df['sectie'].isin(secties)
    if doelen:
        m = m & df['gebruiksdoel'].isin(doelen)
    perc_lo = _parse_int(perc_lo)
    perc_hi = _parse_int(perc_hi)
    if perc_lo is not None or perc_hi is not None:
        lo = -1 if perc_lo is None else perc_lo
        hi = 10 ** 9 if perc_hi is None else perc_hi
        m = m & df['perceelnummer'].between(lo, hi)
    if year_lo is not None or year_hi is not None:
        lo = 1200 if year_lo is None else year_lo
        hi = 2026 if year_hi is None else year_hi
        y = df['bouwjaar_median']
        ym = y.between(lo, hi)
        if not excl_year:
            ym = ym | y.isna()
        m = m & ym
    if residential == 'Ja':
        m = m & df['has_woonfunctie']
    elif residential == 'Nee':
        m = m & (~df['has_woonfunctie'])
    if idq:
        q = idq.strip()
        m = m & (
            df[ID_COL].astype(str).str.contains(q, case=False, na=False)
            | df['straat_en_huisnummer'].astype(str).str.contains(q, case=False, na=False)
            | df['postcode'].astype(str).str.contains(q, case=False, na=False)
        )
    return df[m]


def export_filtered_csv(garden_lo, garden_hi, parcel_lo, parcel_hi, cov_lo, cov_hi, nb_lo, nb_hi,
                        gemeenten, secties, perc_lo, perc_hi, year_lo, year_hi, excl_year,
                        doelen, residential, idq, limit):
    res = get_filtered_df(garden_lo, garden_hi, parcel_lo, parcel_hi, cov_lo, cov_hi, nb_lo, nb_hi,
                          gemeenten, secties, perc_lo, perc_hi, year_lo, year_hi, excl_year,
                          doelen, residential, idq)
    csv_path = os.path.join(tempfile.gettempdir(), 'maastricht_percelen_gefilterd.csv')
    if res.empty:
        empty_df = pd.DataFrame(columns=[RENAME.get(c, c) for c in TABLE_COLS])
        empty_df.to_csv(csv_path, index=False)
        return csv_path
    res = res.sort_values('calculated_garden_area', ascending=False)
    export = res[TABLE_COLS].rename(columns=RENAME)
    for c in NUM_ROUND:
        if c in export.columns:
            export[c] = export[c].round(1)
    export.to_csv(csv_path, index=False)
    return csv_path


def apply_filters(garden_lo, garden_hi, parcel_lo, parcel_hi, cov_lo, cov_hi, nb_lo, nb_hi,
                  gemeenten, secties, perc_lo, perc_hi, year_lo, year_hi, excl_year,
                  doelen, residential, idq, limit):
    res = get_filtered_df(garden_lo, garden_hi, parcel_lo, parcel_hi, cov_lo, cov_hi, nb_lo, nb_hi,
                          gemeenten, secties, perc_lo, perc_hi, year_lo, year_hi, excl_year,
                          doelen, residential, idq)
    csv_path = os.path.join(tempfile.gettempdir(), 'maastricht_percelen_gefilterd.csv')
    if res.empty:
        empty_df = pd.DataFrame(columns=[RENAME.get(c, c) for c in TABLE_COLS])
        empty_df.to_csv(csv_path, index=False)
        return 'Geen percelen gevonden met deze filters. Probeer de bereiken te verruimen.', None, csv_path, csv_path, csv_path
    res = res.sort_values('calculated_garden_area', ascending=False)
    shown = res[TABLE_COLS].head(int(limit)).copy()
    shown['Bekijken'] = [VIEW_CELL.replace('{pid}', str(v)) for v in shown[ID_COL]]
    shown = shown.rename(columns=RENAME)
    export = res[TABLE_COLS].rename(columns=RENAME)
    for frame in (shown, export):
        for c in NUM_ROUND:
            if c in frame.columns:
                frame[c] = frame[c].round(1)
    export.to_csv(csv_path, index=False)
    # NaN (percelen zonder gebouwen hebben geen bouwjaar) is niet JSON-compatibel:
    # naar None converteren zodat de Dataframe-payload serialiseert.
    shown = shown.astype(object).where(pd.notna(shown), None)
    status = ('**' + format(len(res), ',d') + '** percelen komen overeen (van ' + format(len(DATA), ',d')
              + ' in de momentopname). Tuin ' + _fmt(garden_lo) + '\u2013' + _fmt(garden_hi)
              + ' m\u00b2, gesorteerd op tuinoppervlak; top ' + str(len(shown)) + ' weergegeven.')
    return status, shown, csv_path, csv_path, csv_path


def build_map_page(pid):
    sel = PARCELS[PARCELS[ID_COL] == str(pid)]
    if sel.empty:
        return '<html><body><p>Perceel niet gevonden in de momentopname.</p></body></html>'
    row = sel.iloc[0]
    geom = sel.geometry.iloc[0]
    parcel_geo = json.loads(sel.to_crs(4326).geometry.to_json())['features'][0]['geometry']
    try:
        near = BUILDINGS.iloc[list(BUILDINGS.sindex.query(geom, predicate='intersects'))]
    except Exception:
        near = BUILDINGS[BUILDINGS.intersects(geom)]
    bjson = json.loads(near.to_crs(4326).geometry.to_json()) if len(near) else {'type': 'FeatureCollection', 'features': []}
    popup = _popup_html(row)
    return (MAP_TEMPLATE
            .replace('__PARCEL__', json.dumps(parcel_geo))
            .replace('__BUILDINGS__', json.dumps(bjson))
            .replace('__POPUP__', json.dumps(popup)))


with ui.Blocks(title='Maastricht Tuinzoeker') as demo:
    ui.HTML('<style>' + CSS + '</style>')  # inline CSS: compatible with Gradio 5 and 6
    ui.Markdown('# Maastricht Woning- & Tuinverkenner')
    ui.Markdown(
        'Kadastrale percelen (**Kadaster BRK**) gekoppeld aan gebouwvoetafdrukken (**BAG**) voor '
        'de hele gemeente Maastricht, vooraf geladen uit een eenmalige PDOK-momentopname.\n\n'
        '*Tuinoppervlak = perceeloppervlak \u2212 gebouwvoetafdruk (geknipt op de doorsnede). '
        'Elk veld is filterbaar; het tuinbereik staat standaard op 50\u2013500 m\u00b2.*'
    )

    with ui.Row():
        with ui.Column(scale=1):
            ui.Markdown('### Filters')
            with ui.Row():
                garden_lo = ui.Number(value=50, label='Tuin min (m\u00b2)')
                garden_hi = ui.Number(value=500, label='Tuin max (m\u00b2)')
            with ui.Row():
                parcel_lo = ui.Number(value=0, label='Perceel min (m\u00b2)')
                parcel_hi = ui.Number(value=PARCEL_MAX, label='Perceel max (m\u00b2)')
            with ui.Row():
                cov_lo = ui.Number(value=0, label='Bebouwing min (%)')
                cov_hi = ui.Number(value=100, label='Bebouwing max (%)')
            with ui.Row():
                nb_lo = ui.Number(value=0, label='Panden min')
                nb_hi = ui.Number(value=50, label='Panden max')
            with ui.Row():
                perc_lo = ui.Textbox(value='', label='Perceelnummer min')
                perc_hi = ui.Textbox(value='', label='Perceelnummer max')
            with ui.Row():
                year_lo = ui.Number(value=1200, label='Bouwjaar min')
                year_hi = ui.Number(value=2026, label='Bouwjaar max')
            gemeenten = ui.Dropdown(choices=GEMEENTEN, multiselect=True,
                                    label='Kadastrale gemeente')
            secties = ui.Dropdown(choices=SECTIES, multiselect=True, label='Sectie')
            doelen = ui.Dropdown(choices=DOELEN, multiselect=True, label='Gebruiksdoel')
            excl_year = ui.Checkbox(value=False,
                                    label='Percelen zonder bekend bouwjaar uitsluiten')
            residential = ui.Radio(choices=['Alle', 'Ja', 'Nee'], value='Alle',
                                   label='Woonfunctie')
            idq = ui.Textbox(label='Zoeken (Adres, Postcode, Kadaster-ID)', placeholder='bijv. Boschstraat, 6211, 3430000927')
            limit = ui.Slider(minimum=5, maximum=500, value=25, step=5, label='Weergegeven rijen')
            with ui.Row():
                btn = ui.Button('Filters toepassen', variant='primary', scale=2)
                export_btn = ui.DownloadButton('📥 Exporteer (.csv)', variant='secondary', scale=2)
            ui.Markdown('<div class="modal-hint">Klik op <b>Bekijken</b> in een rij om de '
                        'perceelkaart in een nieuw tabblad te openen.</div>')

        with ui.Column(scale=3):
            with ui.Row(elem_id='table-top-bar'):
                status = ui.Markdown()
                table_export_btn = ui.DownloadButton('📥 Exporteer naar .csv', variant='secondary', size='sm', scale=0)
            table = ui.Dataframe(datatype=DATATYPES, interactive=True, wrap=False,
                                 elem_id='results-table', label='Overeenkomende percelen')
            download = ui.File(label='📥 Gefilterde CSV downloaden')

    inputs = [garden_lo, garden_hi, parcel_lo, parcel_hi, cov_lo, cov_hi, nb_lo, nb_hi,
              gemeenten, secties, perc_lo, perc_hi, year_lo, year_hi, excl_year,
              doelen, residential, idq, limit]
    btn.click(fn=apply_filters, inputs=inputs, outputs=[status, table, export_btn, table_export_btn, download])
    demo.load(fn=apply_filters, inputs=inputs, outputs=[status, table, export_btn, table_export_btn, download])
    export_btn.click(fn=export_filtered_csv, inputs=inputs, outputs=export_btn)
    table_export_btn.click(fn=export_filtered_csv, inputs=inputs, outputs=table_export_btn)

@app.get('/map/{pid}')
def map_page(pid: str):
    return HTMLResponse(build_map_page(pid))

app = ui.mount_gradio_app(app, demo, path='/')