GitHub Actions commited on
Commit
8511cb6
·
0 Parent(s):

Deploy from GitHub Actions

Browse files
Files changed (7) hide show
  1. .streamlit/config.toml +10 -0
  2. .streamlit/secrets.toml +5 -0
  3. Dockerfile +33 -0
  4. README.md +11 -0
  5. app.py +474 -0
  6. requirements.txt +13 -0
  7. utils.py +230 -0
.streamlit/config.toml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ [theme]
2
+ primaryColor = "#1a9850"
3
+ backgroundColor = "#1e1e1e"
4
+ secondaryBackgroundColor = "#2d2d2d"
5
+ textColor = "#ffffff"
6
+
7
+ [server]
8
+ headless = true
9
+ enableCORS = false
10
+ enableXsrfProtection = false
.streamlit/secrets.toml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Add your secrets here
2
+ # HF_TOKEN = "hf_your_token_here"
3
+ # DATASET_ID = "Rahul-fix/cologne-green-data"
4
+ #
5
+ # NOTE: For HF Spaces, set these in Settings > Repository secrets instead
Dockerfile ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # Install system dependencies for GDAL/rasterio
4
+ RUN apt-get update && \
5
+ apt-get install -y --no-install-recommends \
6
+ build-essential \
7
+ libgdal-dev \
8
+ gdal-bin \
9
+ libgeos-dev \
10
+ libproj-dev \
11
+ curl \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
+ # Set GDAL environment
15
+ ENV GDAL_CONFIG=/usr/bin/gdal-config
16
+
17
+ WORKDIR /app
18
+
19
+ # Copy requirements first for caching
20
+ COPY requirements.txt .
21
+ RUN pip install --no-cache-dir -r requirements.txt
22
+
23
+ # Copy app files
24
+ COPY app.py utils.py ./
25
+
26
+ # Expose Streamlit port (HF Spaces uses 7860)
27
+ EXPOSE 7860
28
+
29
+ # Health check
30
+ HEALTHCHECK CMD curl --fail http://localhost:7860/_stcore/health || exit 1
31
+
32
+ # Run Streamlit
33
+ CMD ["streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0", "--server.enableCORS=false", "--server.enableXsrfProtection=false"]
README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Cologne Green Project
3
+ emoji: 🌳
4
+ colorFrom: green
5
+ colorTo: green
6
+ sdk: docker
7
+ pinned: false
8
+ short_description: 'Urban green analysis as a part of #Correlaid lc Cologne'
9
+ ---
10
+
11
+ For more information, Check out the project on GitHub: https://github.com/Rahul-fix/cologne-green-project
app.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ import matplotlib.pyplot as plt
5
+ import matplotlib.colors as mcolors
6
+ import folium
7
+ from streamlit_folium import st_folium
8
+ from shapely.geometry import Point, box
9
+ import geopandas as gpd
10
+ import duckdb
11
+ import rasterio
12
+ from huggingface_hub import HfFileSystem
13
+ import shapely.wkb
14
+ from dotenv import load_dotenv
15
+ import os
16
+ from pathlib import Path
17
+
18
+ # Import extracted utilities (shared with app_local.py)
19
+ from utils import (
20
+ FLAIR_COLORS, CLASS_LABELS, process_mosaic
21
+ )
22
+
23
+ # --- Cloud Configuration ---
24
+ load_dotenv()
25
+ env_path = Path(__file__).parent.parent / "DL_cologne_green" / ".env"
26
+ if env_path.exists():
27
+ load_dotenv(env_path)
28
+
29
+ HF_TOKEN = os.getenv("HF_TOKEN")
30
+ DATASET_ID = os.getenv("DATASET_ID", "Rahul-fix/cologne-green-data")
31
+ BASE_URL = f"hf://datasets/{DATASET_ID}"
32
+ STORAGE_OPTS = {"token": HF_TOKEN} if HF_TOKEN else None
33
+
34
+ # --- DuckDB Connection ---
35
+ @st.cache_resource
36
+ def get_db_connection():
37
+ con = duckdb.connect(database=":memory:")
38
+ con.execute("INSTALL spatial; LOAD spatial;")
39
+ con.execute("INSTALL httpfs; LOAD httpfs;")
40
+ if HF_TOKEN:
41
+ fs = HfFileSystem(token=HF_TOKEN)
42
+ con.register_filesystem(fs)
43
+ return con
44
+
45
+ con = get_db_connection()
46
+
47
+ # --- Cloud Data Loading Functions (mirror utils.py structure) ---
48
+ def safe_load_wkb(x):
49
+ try: return shapely.wkb.loads(bytes(x))
50
+ except: return None
51
+
52
+ @st.cache_data(ttl=3600)
53
+ def load_quarters_with_stats():
54
+ """Load Veedel boundaries with stats - Cloud version of utils.load_quarters_with_stats"""
55
+ try:
56
+ query = f"""
57
+ SELECT
58
+ v.name, ST_AsWKB(v.geometry) as geometry,
59
+ COALESCE(s.green_area_m2, 0) as green_area_m2,
60
+ COALESCE(s.ndvi_mean, 0) as ndvi_mean,
61
+ v.Shape_Area,
62
+ s.area_0, s.area_1, s.area_2, s.area_3, s.area_4, s.area_5, s.area_6, s.area_7,
63
+ s.area_8, s.area_9, s.area_10, s.area_11, s.area_12, s.area_13, s.area_14, s.area_15,
64
+ s.area_16, s.area_17, s.area_18
65
+ FROM '{BASE_URL}/data/boundaries/Stadtviertel.parquet' v
66
+ LEFT JOIN '{BASE_URL}/data/stats/extended_stats.parquet' s ON v.name = s.name
67
+ """
68
+ df = con.execute(query).fetchdf()
69
+ df['geometry'] = df['geometry'].apply(safe_load_wkb)
70
+ df = df.dropna(subset=['geometry'])
71
+
72
+ gdf = gpd.GeoDataFrame(df, geometry='geometry', crs="EPSG:4326")
73
+
74
+ # CRS Check (remote data may be in EPSG:25832)
75
+ if not gdf.empty and gdf.total_bounds[0] > 180:
76
+ gdf.crs = "EPSG:25832"
77
+ gdf = gdf.to_crs("EPSG:4326")
78
+
79
+ # Calculate green_pct
80
+ if 'green_area_m2' in gdf.columns and 'Shape_Area' in gdf.columns:
81
+ gdf['green_pct'] = (gdf['green_area_m2'] / gdf['Shape_Area']) * 100
82
+ else:
83
+ gdf['green_pct'] = 0.0
84
+
85
+ return gdf
86
+ except Exception as e:
87
+ st.error(f"Error loading quarters: {e}")
88
+ return gpd.GeoDataFrame()
89
+
90
+ @st.cache_data(ttl=3600)
91
+ def load_boroughs():
92
+ """Load borough boundaries - Cloud version of utils.load_boroughs"""
93
+ try:
94
+ query = f"SELECT STB_NAME as name, ST_AsWKB(geometry) as geometry FROM '{BASE_URL}/data/boundaries/Stadtbezirke.parquet'"
95
+ df = con.execute(query).fetchdf()
96
+ df['geometry'] = df['geometry'].apply(safe_load_wkb)
97
+ df = df.dropna(subset=['geometry'])
98
+
99
+ gdf = gpd.GeoDataFrame(df, geometry='geometry', crs="EPSG:4326")
100
+
101
+ if not gdf.empty and gdf.total_bounds[0] > 180:
102
+ gdf.crs = "EPSG:25832"
103
+ gdf = gdf.to_crs("EPSG:4326")
104
+
105
+ return gdf
106
+ except Exception as e:
107
+ st.error(f"Error loading boroughs: {e}")
108
+ return gpd.GeoDataFrame()
109
+
110
+ @st.cache_data(ttl=3600)
111
+ def get_tile_to_veedel_mapping():
112
+ """Get tile-to-Veedel mapping - Cloud version of utils.get_tile_to_veedel_mapping"""
113
+ try:
114
+ tiles_df = pd.read_csv(f"{BASE_URL}/data/metadata/cologne_tiles.csv", storage_options=STORAGE_OPTS)
115
+ geometries = [box(r['Koordinatenursprung_East'], r['Koordinatenursprung_North'],
116
+ r['Koordinatenursprung_East']+1000, r['Koordinatenursprung_North']+1000) for _, r in tiles_df.iterrows()]
117
+ tiles_gdf = gpd.GeoDataFrame(tiles_df, geometry=geometries, crs="EPSG:25832")
118
+
119
+ q_gdf = gpd.read_parquet(f"{BASE_URL}/data/boundaries/Stadtviertel.parquet", storage_options=STORAGE_OPTS)
120
+ if q_gdf.crs != "EPSG:25832": q_gdf = q_gdf.to_crs("EPSG:25832")
121
+
122
+ joined = gpd.sjoin(tiles_gdf, q_gdf, how="inner", predicate="intersects")
123
+ return joined.groupby('name')['Kachelname'].apply(list).to_dict()
124
+ except Exception as e:
125
+ return {}
126
+
127
+ @st.cache_data(ttl=3600)
128
+ def list_available_tiles():
129
+ """List available tiles from cloud (processed, web_optimized, or raw)"""
130
+ try:
131
+ fs = HfFileSystem(token=HF_TOKEN)
132
+ tiles = set()
133
+
134
+ # Check processed masks
135
+ processed_files = fs.glob(f"datasets/{DATASET_ID}/data/processed/*_mask.tif")
136
+ for f in processed_files:
137
+ tiles.add(Path(f).stem.replace("_mask", ""))
138
+
139
+ # Check web_optimized masks
140
+ web_opt_files = fs.glob(f"datasets/{DATASET_ID}/data/web_optimized/*_mask.tif")
141
+ for f in web_opt_files:
142
+ tiles.add(Path(f).stem.replace("_mask", ""))
143
+
144
+ # Also include raw tiles (for satellite view)
145
+ raw_files = fs.glob(f"datasets/{DATASET_ID}/data/raw/*.jp2")
146
+ for f in raw_files:
147
+ tiles.add(Path(f).stem)
148
+
149
+ return list(tiles)
150
+ except:
151
+ return []
152
+
153
+ def get_mosaic_data_remote(tile_names, layer_type):
154
+ """Load and mosaic tiles - Cloud version of utils.get_mosaic_data_local"""
155
+ fs = HfFileSystem(token=HF_TOKEN)
156
+ sources = []
157
+ memfiles = []
158
+
159
+ try:
160
+ for tile in tile_names:
161
+ suffix = "_mask" if "Land Cover" in layer_type else "_ndvi" if "NDVI" in layer_type else ""
162
+
163
+ paths = [
164
+ f"datasets/{DATASET_ID}/data/web_optimized/{tile}{suffix}.tif",
165
+ f"datasets/{DATASET_ID}/data/processed/{tile}{suffix}.tif",
166
+ ]
167
+ if layer_type == "Satellite":
168
+ paths.append(f"datasets/{DATASET_ID}/data/raw/{tile}.jp2")
169
+
170
+ found_bytes = None
171
+ for p in paths:
172
+ try:
173
+ with fs.open(p, "rb") as f:
174
+ found_bytes = f.read()
175
+ break
176
+ except: continue
177
+
178
+ if found_bytes:
179
+ m = rasterio.MemoryFile(found_bytes)
180
+ memfiles.append(m)
181
+ sources.append(m.open())
182
+
183
+ # Use shared processing logic
184
+ result = process_mosaic(sources, layer_type)
185
+
186
+ # Cleanup
187
+ for s in sources: s.close()
188
+ for m in memfiles: m.close()
189
+
190
+ return result
191
+ except Exception as e:
192
+ return None, None
193
+
194
+ # 1. Page Configuration
195
+ st.set_page_config(page_title="GreenCologne (Cloud)", layout="wide")
196
+ st.title("🌿 GreenCologne (Cloud Dashboard)")
197
+
198
+ # --- Sidebar: Dataset Info ---
199
+ with st.sidebar:
200
+ st.header("ℹ️ About This Dataset")
201
+
202
+ with st.expander("📡 Data Sources", expanded=False):
203
+ st.markdown("""
204
+ **Satellite Imagery**
205
+ [OpenNRW DOP10](https://www.bezreg-koeln.nrw.de/geobasis-nrw/produkte-und-dienste/luftbild-und-satellitenbildinformationen/aktuelle-luftbild-und-0) – 10cm resolution aerial photos (2022-2025)
206
+
207
+ **Administrative Boundaries**
208
+ [Offene Daten Köln](https://www.offenedaten-koeln.de/) – Stadtviertel & Stadtbezirke
209
+
210
+ **Coverage**
211
+ 840 tiles covering Cologne's 86 Veedels
212
+ """)
213
+
214
+ with st.expander("🤖 Model & Methodology", expanded=False):
215
+ st.markdown("""
216
+ **Land Cover Classification**
217
+ [FLAIR-Hub](https://huggingface.co/IGNF/FLAIR-HUB_LC-A_IR_swinbase-upernet) – Deep learning semantic segmentation trained on French aerial imagery, adapted for German urban landscapes.
218
+
219
+ **19 Land Cover Classes**
220
+ Buildings, deciduous trees, herbaceous vegetation, water, impervious surfaces, agricultural land, and more.
221
+
222
+ **NDVI Calculation**
223
+ Normalized Difference Vegetation Index computed from NIR and Red bands:
224
+ `NDVI = (NIR - Red) / (NIR + Red)`
225
+
226
+ **Green Area Detection**
227
+ Classes 4 (Deciduous), 5 (Coniferous), 17 (Herbaceous), and 18 (Agricultural) are classified as green areas.
228
+ """)
229
+
230
+ with st.expander("🙏 Acknowledgments", expanded=False):
231
+ st.markdown("""
232
+ - [CorrelAid](https://correlaid.org/) – Data-for-good community
233
+ - [OpenNRW](https://www.opengeodata.nrw.de/) – Open geospatial data
234
+ - [IGNF/FLAIR-Hub](https://huggingface.co/IGNF/FLAIR-HUB_LC-A_IR_swinbase-upernet) – Segmentation model
235
+ - [Stadt Köln](https://www.stadt-koeln.de/) – Open administrative data
236
+ """)
237
+
238
+ if not HF_TOKEN:
239
+ st.warning("⚠️ HF_TOKEN missing. Set in .env or Streamlit Secrets.")
240
+
241
+ # 2. Data Loading
242
+ gdf_quarters = load_quarters_with_stats()
243
+ gdf_boroughs = load_boroughs()
244
+ tile_mapping = get_tile_to_veedel_mapping()
245
+ available_tiles = list_available_tiles()
246
+
247
+ # 3. State Management
248
+ if 'selected_veedel' not in st.session_state: st.session_state['selected_veedel'] = "All"
249
+ if 'map_center' not in st.session_state: st.session_state['map_center'] = [50.9375, 6.9603] # Cologne
250
+ if 'map_zoom' not in st.session_state: st.session_state['map_zoom'] = 11
251
+ if 'map_click_counter' not in st.session_state: st.session_state['map_click_counter'] = 0
252
+
253
+ # --- Helper Functions ---
254
+ def update_zoom_for_veedel(veedel_name):
255
+ if veedel_name == "All":
256
+ st.session_state['map_center'] = [50.9375, 6.9603]
257
+ st.session_state['map_zoom'] = 10
258
+ elif gdf_quarters is not None and not gdf_quarters.empty:
259
+ match = gdf_quarters[gdf_quarters['name'] == veedel_name]
260
+ if not match.empty:
261
+ centroid = match.geometry.centroid.iloc[0]
262
+ st.session_state['map_center'] = [centroid.y, centroid.x]
263
+ st.session_state['map_zoom'] = 14
264
+
265
+ def on_veedel_change():
266
+ sel = st.session_state['selected_veedel_widget']
267
+ st.session_state['selected_veedel'] = sel
268
+ update_zoom_for_veedel(sel)
269
+
270
+ # --- Layout ---
271
+ col_map, col_details = st.columns([0.65, 0.35], gap="medium")
272
+
273
+ with col_details:
274
+ st.markdown("### GreenCologne Analysis")
275
+ tab_opts, tab_stats = st.tabs(["🛠️ Options", "📊 Statistics"])
276
+
277
+ veedel_list = ["All"] + sorted(gdf_quarters['name'].unique().tolist()) if gdf_quarters is not None and not gdf_quarters.empty else ["All"]
278
+
279
+ # --- Tab 1: Options ---
280
+ with tab_opts:
281
+ # Sync Widget
282
+ if 'selected_veedel_widget' in st.session_state and st.session_state['selected_veedel'] != st.session_state['selected_veedel_widget']:
283
+ st.session_state['selected_veedel_widget'] = st.session_state['selected_veedel']
284
+
285
+ selected_veedel = st.selectbox(
286
+ "Select Quarter (Veedel/Stadtviertel):",
287
+ veedel_list,
288
+ key='selected_veedel_widget',
289
+ on_change=on_veedel_change,
290
+ index=veedel_list.index(st.session_state['selected_veedel']) if st.session_state['selected_veedel'] in veedel_list else 0
291
+ )
292
+
293
+ # Tile Logic - Only load tiles when a specific veedel is selected
294
+ tiles_to_display = []
295
+ if selected_veedel != "All":
296
+ veedel_tiles = set(tile_mapping.get(selected_veedel, []))
297
+ filtered_tiles = [t for t in veedel_tiles if t in available_tiles]
298
+ tiles_to_display = sorted(filtered_tiles)
299
+
300
+ # Layer Selection
301
+ layer_selection = st.radio(
302
+ "Select Layer:",
303
+ ["Satellite", "Land Cover", "NDVI"],
304
+ index=2,
305
+ horizontal=True
306
+ )
307
+
308
+ # Legends
309
+ st.markdown("#### Legends")
310
+ st.markdown("**Veedel Health (Mean NDVI)**")
311
+ st.markdown("""
312
+ <div style="background: linear-gradient(to right, #d73027, #ffffbf, #1a9850); height: 10px; width: 100%; border-radius: 5px;"></div>
313
+ <div style="display: flex; justify-content: space-between; font-size: 10px; margin-top: 2px;"><span>0.0 (Low)</span><span>0.3</span><span>0.6+ (High)</span></div>
314
+ <div style="font-size: 11px; color: #666; margin-bottom: 15px;">*Average vegetation index per district.</div>
315
+ """, unsafe_allow_html=True)
316
+
317
+ if layer_selection == "Land Cover":
318
+ st.markdown("**Land Cover Classes**")
319
+ legend_html = "<div style='display: grid; grid-template-columns: 1fr 1fr; gap: 5px; font-size: 12px;'>"
320
+ for cls_id, label in CLASS_LABELS.items():
321
+ if cls_id == 13: continue
322
+ c = FLAIR_COLORS[cls_id]
323
+ legend_html += f"<div style='display: flex; align-items: center;'><div style='width: 12px; height: 12px; background: rgba({c[0]},{c[1]},{c[2]},{c[3]/255}); margin-right: 5px; border: 1px solid #ccc;'></div>{label}</div>"
324
+ st.markdown(legend_html + "</div>", unsafe_allow_html=True)
325
+
326
+ elif layer_selection == "NDVI":
327
+ st.markdown("**Pixel Vegetation Index (NDVI)**")
328
+ st.markdown("""
329
+ <div style="background: linear-gradient(to right, #d73027, #ffffbf, #1a9850); height: 10px; width: 100%; border-radius: 5px;"></div>
330
+ <div style="display: flex; justify-content: space-between; font-size: 10px; margin-top: 2px;"><span>-0.4 (Water)</span><span>0.3</span><span>1.0 (Dense)</span></div>
331
+ """, unsafe_allow_html=True)
332
+
333
+ # --- Tab 2: Statistics ---
334
+ with tab_stats:
335
+ if gdf_quarters is not None and not gdf_quarters.empty:
336
+ title = "Cologne (All Veedels) Stats"
337
+ area_m2 = 0
338
+ total_area_m2 = 1
339
+ class_data_source = None
340
+
341
+ if selected_veedel != "All":
342
+ row = gdf_quarters[gdf_quarters['name'] == selected_veedel]
343
+ if not row.empty:
344
+ title = f"{selected_veedel} Stats"
345
+ area_m2 = row['green_area_m2'].values[0] if 'green_area_m2' in row else 0
346
+ total_area_m2 = row['Shape_Area'].values[0] if 'Shape_Area' in row else 1
347
+ class_data_source = row
348
+ else:
349
+ st.warning(f"No stats for {selected_veedel}")
350
+ else:
351
+ area_m2 = gdf_quarters['green_area_m2'].sum() if 'green_area_m2' in gdf_quarters else 0
352
+ total_area_m2 = gdf_quarters['Shape_Area'].sum() if 'Shape_Area' in gdf_quarters else 1
353
+ class_cols = [c for c in gdf_quarters.columns if str(c).startswith('area_')]
354
+ if class_cols:
355
+ class_data_source = pd.DataFrame([{c: gdf_quarters[c].sum() for c in class_cols}])
356
+
357
+ st.markdown(f"#### {title}")
358
+ c1, c2 = st.columns(2)
359
+ c1.metric("Green Area", f"{(area_m2/10000):.2f} ha")
360
+ c2.metric("Green Coverage", f"{(area_m2/total_area_m2)*100:.1f}%")
361
+ st.divider()
362
+
363
+ if class_data_source is not None and not class_data_source.empty:
364
+ class_cols = [c for c in class_data_source.columns if str(c).startswith('area_')]
365
+ if class_cols:
366
+ class_data = class_data_source[class_cols].T.reset_index()
367
+ class_data.columns = ['class_col', 'area_m2']
368
+ class_data['class_id'] = pd.to_numeric(class_data['class_col'].str.replace('area_', '', regex=False), errors='coerce').fillna(0).astype(int)
369
+ class_data['class_name'] = class_data['class_id'].map(CLASS_LABELS)
370
+ class_data['color'] = class_data['class_id'].map(lambda x: f"rgba({FLAIR_COLORS[x][0]},{FLAIR_COLORS[x][1]},{FLAIR_COLORS[x][2]}, 1)")
371
+ class_data = class_data.sort_values(by='area_m2', ascending=False)
372
+
373
+ fig_pie = px.pie(
374
+ class_data,
375
+ names='class_name',
376
+ values='area_m2',
377
+ title="Land Cover Distribution",
378
+ color='class_name',
379
+ color_discrete_map={row['class_name']: row['color'] for _, row in class_data.iterrows()},
380
+ labels={'class_name': 'Land Cover', 'area_m2': 'Area'}
381
+ )
382
+ fig_pie.update_traces(
383
+ textposition='inside',
384
+ textinfo='percent',
385
+ hovertemplate='<b>%{label}</b><br>Area: %{value:,.0f} m² (%{percent})<extra></extra>'
386
+ )
387
+ st.plotly_chart(fig_pie, use_container_width=True)
388
+ else: st.info("No detailed land cover data.")
389
+
390
+ # --- Map View ---
391
+ with col_map:
392
+ # 1. Base Map
393
+ m = folium.Map(location=st.session_state['map_center'], zoom_start=st.session_state['map_zoom'], tiles="CartoDB positron", crs='EPSG3857')
394
+
395
+ # 2. Results: Districts
396
+ if gdf_boroughs is not None and not gdf_boroughs.empty:
397
+ folium.GeoJson(
398
+ gdf_boroughs, name="Districts",
399
+ style_function=lambda x: {'fillColor': 'none', 'color': '#333333', 'weight': 2, 'dashArray': '5, 5', 'fillOpacity': 0.0},
400
+ tooltip=folium.GeoJsonTooltip(fields=['name'], aliases=['Bezirk:'])
401
+ ).add_to(m)
402
+
403
+ # 3. Quarters (Veedel)
404
+ if gdf_quarters is not None and not gdf_quarters.empty:
405
+ min_ndvi = gdf_quarters['ndvi_mean'].min() if 'ndvi_mean' in gdf_quarters else 0
406
+ max_ndvi = gdf_quarters['ndvi_mean'].max() if 'ndvi_mean' in gdf_quarters else 0.6
407
+ if pd.isna(min_ndvi): min_ndvi = 0
408
+ if pd.isna(max_ndvi): max_ndvi = 0.6
409
+
410
+ def get_style(feature):
411
+ name = feature['properties']['name']
412
+ is_sel = (selected_veedel != "All" and name == selected_veedel)
413
+ val = feature['properties'].get('ndvi_mean')
414
+
415
+ fill_color = 'gray'
416
+ if is_sel: fill_color = '#ffff00'
417
+ elif val is not None and not pd.isna(val):
418
+ norm = max(0, min(1, (val - min_ndvi) / (max_ndvi - min_ndvi + 1e-9)))
419
+ fill_color = mcolors.to_hex(plt.get_cmap('RdYlGn')(norm))
420
+
421
+ return {
422
+ 'fillColor': fill_color,
423
+ 'color': 'black' if is_sel else '#666666',
424
+ 'weight': 3 if is_sel else 1,
425
+ 'fillOpacity': 0.0 if is_sel else 0.6
426
+ }
427
+
428
+ folium.GeoJson(
429
+ gdf_quarters, name="Veedel (NDVI)", style_function=get_style,
430
+ tooltip=folium.GeoJsonTooltip(
431
+ fields=['name', 'green_area_m2', 'green_pct', 'ndvi_mean'],
432
+ aliases=['Veedel:', 'Green Area (m²):', 'Green Coverage (%):', 'Mean NDVI:'],
433
+ localize=True, fmt='.2f'
434
+ )
435
+ ).add_to(m)
436
+
437
+ # 4. Tiles Grid (Mosaic)
438
+ if tiles_to_display:
439
+ with st.spinner(f"Loading {len(tiles_to_display)} tiles..."):
440
+ mosaic_img, mosaic_bounds = get_mosaic_data_remote(tiles_to_display, layer_selection)
441
+ if mosaic_img is not None and mosaic_bounds:
442
+ folium.raster_layers.ImageOverlay(
443
+ image=mosaic_img, bounds=mosaic_bounds,
444
+ opacity=0.8 if "Land Cover" in layer_selection else 1.0,
445
+ name=f"Mosaic - {layer_selection}", control=False
446
+ ).add_to(m)
447
+
448
+ folium.LayerControl().add_to(m)
449
+
450
+ # 5. Click Logic (Hybrid)
451
+ map_key = f"map_{st.session_state['selected_veedel']}_{st.session_state['map_zoom']}_{st.session_state['map_click_counter']}"
452
+ map_output = st_folium(m, width=None, height=700, key=map_key, use_container_width=True, returned_objects=["last_object_clicked", "last_clicked"])
453
+
454
+ clicked_name_final = None
455
+ if map_output:
456
+ # A: Check Object Property
457
+ if map_output.get('last_object_clicked'):
458
+ props = map_output['last_object_clicked'].get('properties', {})
459
+ if props and 'name' in props: clicked_name_final = props['name']
460
+
461
+ # B: Spatial Query Fallback
462
+ if not clicked_name_final and map_output.get('last_clicked'):
463
+ lat = map_output['last_clicked']['lat']
464
+ lng = map_output['last_clicked']['lng']
465
+ if lat and lng and gdf_quarters is not None:
466
+ p = Point(lng, lat)
467
+ matches = gdf_quarters[gdf_quarters.geometry.contains(p)]
468
+ if not matches.empty: clicked_name_final = matches['name'].iloc[0]
469
+
470
+ if clicked_name_final and clicked_name_final in veedel_list and clicked_name_final != st.session_state['selected_veedel']:
471
+ st.session_state['selected_veedel'] = clicked_name_final
472
+ update_zoom_for_veedel(clicked_name_final)
473
+ st.session_state['map_click_counter'] += 1
474
+ st.rerun()
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit>=1.28.0
2
+ streamlit-folium>=0.15.0
3
+ geopandas>=0.14.0
4
+ pandas>=2.0.0
5
+ duckdb>=0.9.0
6
+ rasterio>=1.3.0
7
+ huggingface_hub>=0.19.0
8
+ matplotlib>=3.7.0
9
+ plotly>=5.18.0
10
+ folium>=0.15.0
11
+ shapely>=2.0.0
12
+ python-dotenv>=1.0.0
13
+ pyarrow>=14.0.0
utils.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import duckdb
4
+ import rasterio
5
+ from rasterio.mask import mask
6
+ from rasterio.merge import merge
7
+ from rasterio.warp import calculate_default_transform, reproject, Resampling
8
+ from rasterio.crs import CRS
9
+ import numpy as np
10
+ import matplotlib.colors as mcolors
11
+ import matplotlib.pyplot as plt
12
+ from shapely.geometry import box
13
+ import geopandas as gpd
14
+ from pathlib import Path
15
+
16
+ # --- Constants ---
17
+ DATA_DIR = Path("data")
18
+ STATS_FILE = DATA_DIR / "stats" / "extended_stats.parquet"
19
+ QUARTERS_FILE = DATA_DIR / "boundaries" / "Stadtviertel.parquet"
20
+ BOROUGHS_FILE = DATA_DIR / "boundaries" / "Stadtbezirke.parquet"
21
+ PROCESSED_DIR = DATA_DIR / "processed"
22
+ TILES_METADATA_FILE = DATA_DIR / "metadata" / "cologne_tiles.csv"
23
+
24
+ FLAIR_COLORS = {
25
+ 0: [206, 112, 121, 255], # Building
26
+ 1: [185, 226, 212, 255], # Greenhouse
27
+ 2: [98, 208, 255, 255], # Swimming pool
28
+ 3: [166, 170, 183, 255], # Impervious surface
29
+ 4: [152, 119, 82, 255], # Pervious surface
30
+ 5: [187, 176, 150, 255], # Bare soil
31
+ 6: [51, 117, 161, 255], # Water
32
+ 7: [233, 239, 254, 255], # Snow
33
+ 8: [140, 215, 106, 255], # Herbaceous vegetation
34
+ 9: [222, 207, 85, 255], # Agricultural land
35
+ 10: [208, 163, 73, 255], # Plowed land
36
+ 11: [176, 130, 144, 255], # Vineyard
37
+ 12: [76, 145, 41, 255], # Deciduous
38
+ 13: [18, 100, 33, 255], # Coniferous
39
+ 14: [181, 195, 53, 255], # Brushwood
40
+ 15: [228, 142, 77, 255], # Clear cut
41
+ 16: [34, 34, 34, 255], # Ligneous
42
+ 17: [34, 34, 34, 255], # Mixed
43
+ 18: [34, 34, 34, 255], # Other
44
+ }
45
+
46
+ CLASS_LABELS = {
47
+ 0: 'Building', 1: 'Greenhouse', 2: 'Swimming pool',
48
+ 3: 'Impervious surface', 4: 'Pervious surface', 5: 'Bare soil',
49
+ 6: 'Water', 7: 'Snow', 8: 'Herbaceous vegetation',
50
+ 9: 'Agricultural land', 10: 'Plowed land', 11: 'Vineyard',
51
+ 12: 'Deciduous', 13: 'Coniferous', 14: 'Brushwood',
52
+ 15: 'Clear cut', 16: 'Ligneous', 17: 'Mixed', 18: 'Other'
53
+ }
54
+
55
+ # --- Data Loading ---
56
+ @st.cache_data
57
+ def load_quarters_with_stats():
58
+ # Load Boundaries
59
+ if not QUARTERS_FILE.exists(): return None
60
+ gdf = gpd.read_parquet(QUARTERS_FILE)
61
+ if gdf.crs != "EPSG:4326": gdf = gdf.to_crs("EPSG:4326")
62
+
63
+ # Load Stats
64
+ try:
65
+ con = duckdb.connect()
66
+ df_s = con.execute(f"SELECT * FROM '{STATS_FILE}'").df()
67
+ con.close()
68
+
69
+ # Merge
70
+ if 'name' in gdf.columns and 'name' in df_s.columns:
71
+ gdf = gdf.merge(df_s, on='name', how='left')
72
+ if 'green_area_m2' in gdf.columns:
73
+ gdf['green_area_m2'] = gdf['green_area_m2'].fillna(0)
74
+
75
+ # Calculate Percentage (Critical)
76
+ if 'green_area_m2' in gdf.columns and 'Shape_Area' in gdf.columns:
77
+ gdf['green_pct'] = (gdf['green_area_m2'] / gdf['Shape_Area']) * 100
78
+ else:
79
+ gdf['green_pct'] = 0.0
80
+
81
+ except Exception as e:
82
+ st.error(f"Error loading stats: {e}")
83
+
84
+ return gdf
85
+
86
+ @st.cache_data
87
+ def load_boroughs():
88
+ if not BOROUGHS_FILE.exists(): return None
89
+ gdf = gpd.read_parquet(BOROUGHS_FILE)
90
+ if gdf.crs != "EPSG:4326": gdf = gdf.to_crs("EPSG:4326")
91
+ if 'STB_NAME' in gdf.columns: gdf = gdf.rename(columns={'STB_NAME': 'name'})
92
+ return gdf
93
+
94
+ @st.cache_data
95
+ def get_tile_to_veedel_mapping():
96
+ if not TILES_METADATA_FILE.exists() or not QUARTERS_FILE.exists(): return {}
97
+ tiles_df = pd.read_csv(TILES_METADATA_FILE)
98
+ geometries = []
99
+ for _, row in tiles_df.iterrows():
100
+ e, n = row['Koordinatenursprung_East'], row['Koordinatenursprung_North']
101
+ geometries.append(box(e, n, e + 1000, n + 1000))
102
+ tiles_gdf = gpd.GeoDataFrame(tiles_df, geometry=geometries, crs="EPSG:25832")
103
+
104
+ quarters_gdf = gpd.read_parquet(QUARTERS_FILE)
105
+ if quarters_gdf.crs != "EPSG:25832": quarters_gdf = quarters_gdf.to_crs("EPSG:25832")
106
+
107
+ joined = gpd.sjoin(tiles_gdf, quarters_gdf, how="inner", predicate="intersects")
108
+ return joined.groupby('name')['Kachelname'].apply(list).to_dict()
109
+
110
+ # --- Mosaic Logic (Shared) ---
111
+ def process_mosaic(sources, layer_type):
112
+ """
113
+ Core Mosaic Logic: Merges, Reprojects, and Colorizes open rasterio sources.
114
+ Aguments:
115
+ sources: List of open rasterio DatasetReader objects (file or memory).
116
+ layer_type: String enum ["Satellite", "Land Cover", "NDVI"]
117
+ """
118
+ try:
119
+ if not sources: return None, None
120
+
121
+ # 1. Mosaic (Native CRS)
122
+ # We assume sources are compatible (same bands, dtype). Merge handles overlap.
123
+ mosaic, out_trans = merge(sources)
124
+
125
+ # 2. Reproject to WGS84
126
+ src_crs = CRS.from_epsg(25832) # Assuming all inputs are 25832
127
+ src_height, src_width = mosaic.shape[1], mosaic.shape[2]
128
+ dst_crs = CRS.from_epsg(4326)
129
+
130
+ dst_transform, dst_width, dst_height = calculate_default_transform(
131
+ src_crs, dst_crs, src_width, src_height,
132
+ *rasterio.transform.array_bounds(src_height, src_width, out_trans)
133
+ )
134
+
135
+ count = mosaic.shape[0]
136
+ if layer_type == "Satellite" and count < 3: count = 1
137
+
138
+ dst_array = np.zeros((count, dst_height, dst_width), dtype=mosaic.dtype)
139
+
140
+ reproject(
141
+ source=mosaic, destination=dst_array,
142
+ src_transform=out_trans, src_crs=src_crs,
143
+ dst_transform=dst_transform, dst_crs=dst_crs,
144
+ resampling=Resampling.nearest
145
+ )
146
+
147
+ # 3. Visualization Post-Processing
148
+ final_image = None
149
+
150
+ if layer_type == "Satellite":
151
+ if dst_array.shape[0] >= 3:
152
+ rgb = np.moveaxis(dst_array[:3], 0, -1)
153
+
154
+ # Handle uint16
155
+ if rgb.dtype == 'uint16':
156
+ p2, p98 = np.percentile(rgb[rgb > 0], (2, 98))
157
+ rgb = np.clip((rgb - p2) / (p98 - p2), 0, 1)
158
+ final_image = (rgb * 255).astype(np.uint8)
159
+ else:
160
+ final_image = rgb
161
+
162
+ # Alpha (Create transparency for 0 values)
163
+ alpha = np.any(final_image > 0, axis=2).astype(np.uint8) * 255
164
+ final_image = np.dstack((final_image, alpha))
165
+
166
+ elif layer_type == "Land Cover":
167
+ mask_data = dst_array[0]
168
+ rgba = np.zeros((mask_data.shape[0], mask_data.shape[1], 4), dtype=np.uint8)
169
+ for cls_id, color in FLAIR_COLORS.items():
170
+ rgba[mask_data == cls_id] = color
171
+ final_image = rgba
172
+
173
+ elif layer_type == "NDVI":
174
+ ndvi = dst_array[0].astype('float32')
175
+ norm = mcolors.Normalize(vmin=-0.4, vmax=1, clip=True)(ndvi)
176
+ cmap = plt.get_cmap('RdYlGn')
177
+ final_image_float = cmap(norm)
178
+ final_image = (final_image_float * 255).astype(np.uint8)
179
+
180
+ # Calculate Bounds for Leaflet
181
+ dst_bounds = rasterio.transform.array_bounds(dst_height, dst_width, dst_transform)
182
+ folium_bounds = [[dst_bounds[1], dst_bounds[0]], [dst_bounds[3], dst_bounds[2]]]
183
+
184
+ return final_image, folium_bounds
185
+
186
+ except Exception as e:
187
+ # st.error(f"Mosaic Process Error: {e}")
188
+ return None, None
189
+
190
+ def get_mosaic_data_local(tile_names, layer_type):
191
+ """
192
+ Local IO Wrapper for Mosaic Logic
193
+ """
194
+ sources = []
195
+ try:
196
+ for tile_name in tile_names:
197
+ # Determine Suffix
198
+ suffix = "_mask" if ("Land Cover" in layer_type) else "_ndvi"
199
+ if layer_type == "Satellite": suffix = ""
200
+
201
+ # Paths
202
+ opt_path = DATA_DIR / "web_optimized" / f"{tile_name}{suffix}.tif"
203
+ raw_path = DATA_DIR / "raw" / f"{tile_name}.jp2"
204
+ processed_mask = PROCESSED_DIR / f"{tile_name}_mask.tif"
205
+ processed_ndvi = PROCESSED_DIR / f"{tile_name}_ndvi.tif"
206
+
207
+ path_to_open = None
208
+ if layer_type == "Satellite":
209
+ if opt_path.exists(): path_to_open = opt_path
210
+ elif raw_path.exists(): path_to_open = raw_path
211
+ elif "Land Cover" in layer_type:
212
+ if opt_path.exists(): path_to_open = opt_path
213
+ elif processed_mask.exists(): path_to_open = processed_mask
214
+ elif layer_type == "NDVI":
215
+ if opt_path.exists(): path_to_open = opt_path
216
+ elif processed_ndvi.exists(): path_to_open = processed_ndvi
217
+
218
+ if path_to_open:
219
+ sources.append(rasterio.open(path_to_open))
220
+
221
+ result = process_mosaic(sources, layer_type)
222
+
223
+ # Cleanup
224
+ for s in sources: s.close()
225
+
226
+ return result
227
+
228
+ except Exception as e:
229
+ for s in sources: s.close()
230
+ return None, None