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 = ('🗺️ Bekijken') 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 = """ Perceelkaart & Street View
Perceel
BAG-gebouwen
📍 Google Maps / Street View
""" 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'
📍 {addr}{pc_part}
' return ( addr_line + 'Perceel ' + str(row.get('sectie', '')) + '-' + str(row.get('perceelnummer', '')) + '
' + 'Kadaster-ID: ' + str(row[ID_COL]) + '
' + 'Gemeente: ' + str(row.get('kadastraleGemeenteWaarde', '')) + '
' + 'Perceel: ' + str(round(float(row.get('total_parcel_area', 0.0)), 1)) + ' m\u00b2
' + 'Bebouwing: ' + str(round(float(row.get('total_building_footprint', 0.0)), 1)) + ' m\u00b2 (' + str(int(row.get('n_buildings', 0))) + ' panden)
' + 'Tuin: ' + str(round(float(row.get('calculated_garden_area', 0.0)), 1)) + ' m\u00b2' ) def build_map(pid): sel = PARCELS[PARCELS[ID_COL] == pid] if sel.empty: return '

Perceel niet gevonden in de momentopname.

', '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('&', '&').replace('"', '"') 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 '

Perceel niet gevonden in de momentopname.

' 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('') # 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('') 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='/')