Spaces:
Sleeping
Sleeping
Update app.py
#2
by
roundb
- opened
app.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
-
# app.py
|
| 2 |
import os
|
| 3 |
import re
|
| 4 |
import zipfile
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
from geopy.geocoders import Nominatim
|
| 7 |
import osmnx as ox
|
|
@@ -14,9 +15,18 @@ import geopandas as gpd
|
|
| 14 |
geolocator = Nominatim(user_agent="gradio_osm_app")
|
| 15 |
ox.settings.log_console = False
|
| 16 |
|
| 17 |
-
|
|
|
|
|
|
|
| 18 |
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
def slugify(name: str) -> str:
|
| 21 |
return re.sub(r"[^0-9A-Za-z]+", "_", name).strip("_")
|
| 22 |
|
|
@@ -138,6 +148,7 @@ def ensure_saved(gdf: gpd.GeoDataFrame, slug: str, layer: str):
|
|
| 138 |
|
| 139 |
try:
|
| 140 |
try_to_file(gdf_clean, path, driver="GPKG")
|
|
|
|
| 141 |
except Exception:
|
| 142 |
# Drop common problematic OSM fields as a second attempt
|
| 143 |
drop_candidates = [c for c in gdf_clean.columns if c.lower() in {"fixme", "note", "source_ref"}]
|
|
@@ -151,6 +162,7 @@ def ensure_saved(gdf: gpd.GeoDataFrame, slug: str, layer: str):
|
|
| 151 |
if c != gdf_last.geometry.name:
|
| 152 |
gdf_last[c] = gdf_last[c].astype(str)
|
| 153 |
try_to_file(gdf_last, path, driver="GPKG")
|
|
|
|
| 154 |
|
| 155 |
# --------- UI / main logic ----------
|
| 156 |
def make_legend(selected_layers):
|
|
@@ -210,13 +222,19 @@ def map_with_layers(place_name, cb_highways, cb_buildings, cb_school,
|
|
| 210 |
return
|
| 211 |
|
| 212 |
layers = {}
|
|
|
|
|
|
|
| 213 |
if cb_highways:
|
| 214 |
yield None, "🔄 Downloading Highways..."
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
tag_map = {
|
| 222 |
'Buildings': {'building': True},
|
|
@@ -233,12 +251,17 @@ def map_with_layers(place_name, cb_highways, cb_buildings, cb_school,
|
|
| 233 |
for (name, tags), flag in zip(tag_map.items(), flags):
|
| 234 |
if flag:
|
| 235 |
yield None, f"🔄 Downloading {name}..."
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
yield None, "🔄 Rendering map..."
|
| 244 |
m = folium.Map([lat, lon], zoom_start=13, tiles='CartoDB Dark_Matter')
|
|
@@ -271,16 +294,29 @@ def download_data(place_name, cb_highways, cb_buildings, cb_school,
|
|
| 271 |
return zip_path
|
| 272 |
|
| 273 |
files = []
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
if flag:
|
| 281 |
path = os.path.join(DOWNLOAD_DIR, f"{slug}_{layer}.gpkg")
|
| 282 |
if os.path.exists(path):
|
|
|
|
| 283 |
files.append(path)
|
|
|
|
|
|
|
|
|
|
| 284 |
html_path = os.path.join(DOWNLOAD_DIR, f"{slug}_map.html")
|
| 285 |
if os.path.exists(html_path):
|
| 286 |
files.append(html_path)
|
|
@@ -297,7 +333,6 @@ def download_data(place_name, cb_highways, cb_buildings, cb_school,
|
|
| 297 |
|
| 298 |
print("ZIP gerado com sucesso:", zip_path)
|
| 299 |
return zip_path
|
| 300 |
-
|
| 301 |
except Exception as e:
|
| 302 |
print("Erro ao gerar o ZIP:", str(e))
|
| 303 |
raise gr.Error(f"❌ Download failed: {e}")
|
|
@@ -318,7 +353,7 @@ with gr.Blocks(title="Geoeasy View") as demo:
|
|
| 318 |
<h1 id="app-title">OSM View</h1>
|
| 319 |
</div>
|
| 320 |
""")
|
| 321 |
-
inp = gr.Textbox(label='Place', placeholder='e.g.:
|
| 322 |
with gr.Row():
|
| 323 |
cb_highways = gr.Checkbox(label='Highways', value=True)
|
| 324 |
cb_buildings = gr.Checkbox(label='Buildings', value=True)
|
|
@@ -343,7 +378,6 @@ with gr.Blocks(title="Geoeasy View") as demo:
|
|
| 343 |
with gr.TabItem('Taginfo'):
|
| 344 |
gr.Markdown('''
|
| 345 |
**Most used keys (Taginfo)**
|
| 346 |
-
|
| 347 |
| Position | Key | Approximate usage¹ |
|
| 348 |
|----------|------------|----------------------------|
|
| 349 |
| 1 | `highway` | ~58 million geometries |
|
|
@@ -356,9 +390,9 @@ with gr.Blocks(title="Geoeasy View") as demo:
|
|
| 356 |
| 8 | `amenity` | ~16 million geometries |
|
| 357 |
| 9 | `place` | ~12 million geometries |
|
| 358 |
| 10 | `power` | ~14 million geometries |
|
| 359 |
-
|
| 360 |
¹ Approximate values from daily Taginfo reports.
|
| 361 |
''')
|
| 362 |
|
| 363 |
if __name__ == '__main__':
|
| 364 |
-
|
|
|
|
|
|
| 1 |
+
# app.py - VERSÃO FINAL CORRIGIDA
|
| 2 |
import os
|
| 3 |
import re
|
| 4 |
import zipfile
|
| 5 |
+
import tempfile
|
| 6 |
import gradio as gr
|
| 7 |
from geopy.geocoders import Nominatim
|
| 8 |
import osmnx as ox
|
|
|
|
| 15 |
geolocator = Nominatim(user_agent="gradio_osm_app")
|
| 16 |
ox.settings.log_console = False
|
| 17 |
|
| 18 |
+
# CORRIGIDO: Usar diretório de trabalho atual ou temp do sistema
|
| 19 |
+
# Opção 1: Usar diretório "downloads" no diretório de trabalho atual
|
| 20 |
+
DOWNLOAD_DIR = os.path.join(os.getcwd(), "downloads")
|
| 21 |
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
| 22 |
|
| 23 |
+
# Se o diretório de trabalho não for acessível, usar temp do sistema
|
| 24 |
+
if not os.access(DOWNLOAD_DIR, os.W_OK):
|
| 25 |
+
DOWNLOAD_DIR = tempfile.gettempdir()
|
| 26 |
+
print(f"⚠️ Usando diretório temporário do sistema: {DOWNLOAD_DIR}")
|
| 27 |
+
else:
|
| 28 |
+
print(f"✅ Usando diretório de downloads: {DOWNLOAD_DIR}")
|
| 29 |
+
|
| 30 |
def slugify(name: str) -> str:
|
| 31 |
return re.sub(r"[^0-9A-Za-z]+", "_", name).strip("_")
|
| 32 |
|
|
|
|
| 148 |
|
| 149 |
try:
|
| 150 |
try_to_file(gdf_clean, path, driver="GPKG")
|
| 151 |
+
print(f"✅ Arquivo salvo com sucesso: {path}")
|
| 152 |
except Exception:
|
| 153 |
# Drop common problematic OSM fields as a second attempt
|
| 154 |
drop_candidates = [c for c in gdf_clean.columns if c.lower() in {"fixme", "note", "source_ref"}]
|
|
|
|
| 162 |
if c != gdf_last.geometry.name:
|
| 163 |
gdf_last[c] = gdf_last[c].astype(str)
|
| 164 |
try_to_file(gdf_last, path, driver="GPKG")
|
| 165 |
+
print(f"✅ Arquivo salvo com sucesso (com tratamento): {path}")
|
| 166 |
|
| 167 |
# --------- UI / main logic ----------
|
| 168 |
def make_legend(selected_layers):
|
|
|
|
| 222 |
return
|
| 223 |
|
| 224 |
layers = {}
|
| 225 |
+
|
| 226 |
+
# Salvar highways com o nome correto
|
| 227 |
if cb_highways:
|
| 228 |
yield None, "🔄 Downloading Highways..."
|
| 229 |
+
try:
|
| 230 |
+
G = ox.graph_from_polygon(poly, network_type="all", simplify=True)
|
| 231 |
+
gdf = ox.graph_to_gdfs(G, nodes=False, edges=True)
|
| 232 |
+
if not gdf.empty:
|
| 233 |
+
layers['Highways'] = gdf
|
| 234 |
+
ensure_saved(gdf, slug, 'highways')
|
| 235 |
+
yield None, f"✅ Highways downloaded: {len(gdf)} features"
|
| 236 |
+
except Exception as e:
|
| 237 |
+
yield None, f"⚠️ Highways error: {e}"
|
| 238 |
|
| 239 |
tag_map = {
|
| 240 |
'Buildings': {'building': True},
|
|
|
|
| 251 |
for (name, tags), flag in zip(tag_map.items(), flags):
|
| 252 |
if flag:
|
| 253 |
yield None, f"🔄 Downloading {name}..."
|
| 254 |
+
try:
|
| 255 |
+
gdf2 = ox.features_from_polygon(poly, tags)
|
| 256 |
+
# Only polygons for these layers
|
| 257 |
+
gdf2 = gdf2[gdf2.geometry.type.isin(['Polygon', 'MultiPolygon'])]
|
| 258 |
+
if not gdf2.empty:
|
| 259 |
+
layers[name] = gdf2
|
| 260 |
+
layer_name = name.replace(' ', '').lower()
|
| 261 |
+
ensure_saved(gdf2, slug, layer_name)
|
| 262 |
+
yield None, f"✅ {name} downloaded: {len(gdf2)} features"
|
| 263 |
+
except Exception as e:
|
| 264 |
+
yield None, f"⚠️ {name} error: {e}"
|
| 265 |
|
| 266 |
yield None, "🔄 Rendering map..."
|
| 267 |
m = folium.Map([lat, lon], zoom_start=13, tiles='CartoDB Dark_Matter')
|
|
|
|
| 294 |
return zip_path
|
| 295 |
|
| 296 |
files = []
|
| 297 |
+
|
| 298 |
+
# Mapeamento consistente de nomes de camadas
|
| 299 |
+
layer_mapping = {
|
| 300 |
+
'highways': cb_highways,
|
| 301 |
+
'buildings': cb_buildings,
|
| 302 |
+
'school': cb_school,
|
| 303 |
+
'fire_station': cb_fire,
|
| 304 |
+
'hospital': cb_hospital,
|
| 305 |
+
'police_station': cb_police,
|
| 306 |
+
'restaurants': cb_rest,
|
| 307 |
+
'hotels': cb_hotels,
|
| 308 |
+
'monuments': cb_monuments
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
for layer, flag in layer_mapping.items():
|
| 312 |
if flag:
|
| 313 |
path = os.path.join(DOWNLOAD_DIR, f"{slug}_{layer}.gpkg")
|
| 314 |
if os.path.exists(path):
|
| 315 |
+
print(f"✅ Arquivo encontrado: {path}")
|
| 316 |
files.append(path)
|
| 317 |
+
else:
|
| 318 |
+
print(f"⚠️ Arquivo não encontrado: {path}")
|
| 319 |
+
|
| 320 |
html_path = os.path.join(DOWNLOAD_DIR, f"{slug}_map.html")
|
| 321 |
if os.path.exists(html_path):
|
| 322 |
files.append(html_path)
|
|
|
|
| 333 |
|
| 334 |
print("ZIP gerado com sucesso:", zip_path)
|
| 335 |
return zip_path
|
|
|
|
| 336 |
except Exception as e:
|
| 337 |
print("Erro ao gerar o ZIP:", str(e))
|
| 338 |
raise gr.Error(f"❌ Download failed: {e}")
|
|
|
|
| 353 |
<h1 id="app-title">OSM View</h1>
|
| 354 |
</div>
|
| 355 |
""")
|
| 356 |
+
inp = gr.Textbox(label='Place', placeholder='e.g.: Ellwangen, Germany')
|
| 357 |
with gr.Row():
|
| 358 |
cb_highways = gr.Checkbox(label='Highways', value=True)
|
| 359 |
cb_buildings = gr.Checkbox(label='Buildings', value=True)
|
|
|
|
| 378 |
with gr.TabItem('Taginfo'):
|
| 379 |
gr.Markdown('''
|
| 380 |
**Most used keys (Taginfo)**
|
|
|
|
| 381 |
| Position | Key | Approximate usage¹ |
|
| 382 |
|----------|------------|----------------------------|
|
| 383 |
| 1 | `highway` | ~58 million geometries |
|
|
|
|
| 390 |
| 8 | `amenity` | ~16 million geometries |
|
| 391 |
| 9 | `place` | ~12 million geometries |
|
| 392 |
| 10 | `power` | ~14 million geometries |
|
|
|
|
| 393 |
¹ Approximate values from daily Taginfo reports.
|
| 394 |
''')
|
| 395 |
|
| 396 |
if __name__ == '__main__':
|
| 397 |
+
# CORRIGIDO: Adicionar allowed_paths para permitir downloads do diretório de downloads
|
| 398 |
+
demo.launch(allowed_paths=[DOWNLOAD_DIR])
|