Spaces:
Sleeping

chipas / app.py
douglasribeiro's picture
Create app.py
ed6372a verified
Raw History Blame Contribute Delete
25 kB
from __future__ import annotations
import io
import json
import math
import os
import tempfile
import zipfile
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import geopandas as gpd
import gradio as gr
import networkx as nx
import numpy as np
import pandas as pd
import pyogrio
import simplekml
from pyproj import CRS
from scipy.spatial import cKDTree
from shapely.geometry import LineString, MultiLineString, Point
from shapely.ops import linemerge
# ============================================================
# Utilidades gerais
# ============================================================
ROAD_CLASSES = {
"motorway",
"motorway_link",
"trunk",
"trunk_link",
"primary",
"primary_link",
"secondary",
"secondary_link",
"tertiary",
"tertiary_link",
"unclassified",
"residential",
"living_street",
"service",
}
PUBLIC_PRIORITY_RULES = [
("amenity", {"townhall"}, 100),
("office", {"government"}, 95),
("government", None, 92),
("amenity", {"courthouse"}, 90),
("amenity", {"police"}, 88),
("building", {"public", "civic"}, 85),
("amenity", {"fire_station"}, 75),
("amenity", {"post_office"}, 72),
("amenity", {"public_building"}, 70),
]
MUNICIPALITY_NAME_COLS = ["name", "name:es", "official_name", "alt_name"]
@dataclass
class BuildResult:
zip_path: str
log_text: str
class Logger:
def __init__(self) -> None:
self.lines: List[str] = []
def add(self, text: str) -> None:
self.lines.append(text)
def dump(self) -> str:
return "\n".join(self.lines)
def safe_str(x) -> str:
if pd.isna(x):
return ""
return str(x)
def choose_metric_crs(gdf: gpd.GeoDataFrame) -> CRS:
centroid = gdf.to_crs(4326).unary_union.centroid
lon, lat = float(centroid.x), float(centroid.y)
zone = int((lon + 180) // 6) + 1
epsg = 32600 + zone if lat >= 0 else 32700 + zone
return CRS.from_epsg(epsg)
def detect_name_column(gdf: gpd.GeoDataFrame) -> str:
for col in MUNICIPALITY_NAME_COLS:
if col in gdf.columns:
return col
raise ValueError("Não encontrei uma coluna de nome para os municípios no PBF.")
def explode_lines(geom):
if geom is None or geom.is_empty:
return []
if isinstance(geom, LineString):
return [geom]
if isinstance(geom, MultiLineString):
return [g for g in geom.geoms if isinstance(g, LineString)]
try:
merged = linemerge(geom)
if isinstance(merged, LineString):
return [merged]
if isinstance(merged, MultiLineString):
return [g for g in merged.geoms if isinstance(g, LineString)]
except Exception:
pass
return []
def geometry_to_point(geom):
if geom is None or geom.is_empty:
return None
if geom.geom_type == "Point":
return geom
return geom.representative_point()
def normalize_text_columns(gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
for col in gdf.columns:
if col != "geometry":
try:
gdf[col] = gdf[col].astype(str).replace("nan", "")
except Exception:
pass
return gdf
# ============================================================
# Leitura do PBF via GDAL/pyogrio
# ============================================================
def read_layer(pbf_path: str, layer: str, columns: Optional[List[str]] = None) -> gpd.GeoDataFrame:
return pyogrio.read_dataframe(pbf_path, layer=layer, columns=columns)
def list_pbf_layers(pbf_path: str) -> List[str]:
layers = pyogrio.list_layers(pbf_path)
return [row[0] for row in layers]
def load_roads(pbf_path: str, logger: Logger) -> gpd.GeoDataFrame:
lines = read_layer(pbf_path, "lines")
if "highway" not in lines.columns:
raise ValueError("A camada 'lines' do PBF não possui a coluna 'highway'.")
roads = lines[lines["highway"].isin(ROAD_CLASSES)].copy()
roads = roads[roads.geometry.notna()].copy()
roads = roads[~roads.geometry.is_empty].copy()
logger.add(f"Trechos viários válidos: {len(roads):,}".replace(",", "."))
return roads
def load_municipalities(pbf_path: str, logger: Logger) -> gpd.GeoDataFrame:
polys = read_layer(pbf_path, "multipolygons")
required = {"boundary", "admin_level"}
missing = required - set(polys.columns)
if missing:
raise ValueError(
f"A camada 'multipolygons' não possui as colunas necessárias para limites administrativos: {missing}"
)
mun = polys[
(polys["boundary"].astype(str) == "administrative")
& (polys["admin_level"].astype(str) == "8")
].copy()
name_col = detect_name_column(mun)
mun = mun[mun[name_col].notna()].copy()
mun["municipio"] = mun[name_col].astype(str).str.strip()
mun = mun[["municipio", "geometry"]].copy()
mun = mun.dissolve(by="municipio", as_index=False)
mun = mun[mun.geometry.notna()].copy()
mun = mun[~mun.geometry.is_empty].copy()
logger.add(f"Municípios detectados: {len(mun)}")
return mun
def compute_public_priority(row: pd.Series) -> int:
best = 0
for field, allowed, score in PUBLIC_PRIORITY_RULES:
if field in row.index:
val = safe_str(row.get(field, "")).strip().lower()
if not val:
continue
if allowed is None:
best = max(best, score)
elif val in allowed:
best = max(best, score)
name_blob = " ".join(
safe_str(row.get(col, "")).lower()
for col in ["name", "official_name", "brand", "operator", "description"]
if col in row.index
)
if "palacio municipal" in name_blob:
best = max(best, 98)
if "ayuntamiento" in name_blob:
best = max(best, 97)
if "presidencia municipal" in name_blob:
best = max(best, 97)
return best
def load_public_buildings_and_pois(pbf_path: str, logger: Logger) -> gpd.GeoDataFrame:
points = read_layer(pbf_path, "points")
polys = read_layer(pbf_path, "multipolygons")
candidate_points = points.copy()
candidate_points["geometry"] = candidate_points.geometry.apply(geometry_to_point)
candidate_points = candidate_points[candidate_points.geometry.notna()].copy()
candidate_polys = polys.copy()
candidate_polys["geometry"] = candidate_polys.geometry.apply(geometry_to_point)
candidate_polys = candidate_polys[candidate_polys.geometry.notna()].copy()
common_cols = sorted(set(candidate_points.columns) | set(candidate_polys.columns))
candidate_points = candidate_points.reindex(columns=common_cols)
candidate_polys = candidate_polys.reindex(columns=common_cols)
candidates = pd.concat([candidate_points, candidate_polys], ignore_index=True)
candidates = gpd.GeoDataFrame(candidates, geometry="geometry", crs=points.crs or polys.crs)
candidates = normalize_text_columns(candidates)
candidates["priority"] = candidates.apply(compute_public_priority, axis=1)
candidates = candidates[candidates["priority"] > 0].copy()
candidates = candidates[candidates.geometry.notna()].copy()
candidates = candidates[~candidates.geometry.is_empty].copy()
logger.add(f"Candidatos a prédio público/governo: {len(candidates):,}".replace(",", "."))
return candidates
# ============================================================
# Seleção de 1 nó por município
# ============================================================
def choose_backbone_nodes(
municipalities: gpd.GeoDataFrame,
candidates: gpd.GeoDataFrame,
logger: Logger,
) -> gpd.GeoDataFrame:
municipalities = municipalities.copy()
municipalities["rep_pt"] = municipalities.geometry.representative_point()
join = gpd.sjoin(
candidates[[c for c in candidates.columns if c != "geometry"] + ["geometry"]],
municipalities[["municipio", "rep_pt", "geometry"]],
how="inner",
predicate="within",
)
if len(join) == 0:
raise ValueError(
"Nenhum prédio público/governamental caiu dentro dos municípios detectados."
)
join = join.rename(columns={"geometry": "cand_geom"})
join = gpd.GeoDataFrame(join, geometry="cand_geom", crs=municipalities.crs)
join["dist_rep"] = join.apply(lambda r: r.cand_geom.distance(r.rep_pt), axis=1)
join = join.sort_values(["municipio", "priority", "dist_rep"], ascending=[True, False, True])
chosen = join.groupby("municipio", as_index=False).first()
result = municipalities.merge(
chosen[["municipio", "cand_geom", "priority", "name", "amenity", "office", "building", "government"]],
on="municipio",
how="left",
)
# fallback: caso algum município não tenha candidato, usa representative_point e sinaliza.
result["fallback"] = result["cand_geom"].isna()
result["node_geom"] = result["cand_geom"]
result.loc[result["fallback"], "node_geom"] = result.loc[result["fallback"], "rep_pt"]
result["node_source"] = np.where(result["fallback"], "fallback_centroid", "public_building")
missing = int(result["fallback"].sum())
logger.add(f"Municípios com prédio público encontrado: {len(result) - missing}")
logger.add(f"Municípios em fallback (sem prédio público etiquetado no OSM): {missing}")
result = gpd.GeoDataFrame(result, geometry="node_geom", crs=municipalities.crs)
return result
# ============================================================
# Grafo viário
# ============================================================
def build_road_graph(roads_metric: gpd.GeoDataFrame, logger: Logger) -> Tuple[nx.Graph, Dict[int, Tuple[float, float]]]:
G = nx.Graph()
node_xy_to_id: Dict[Tuple[float, float], int] = {}
node_id_to_xy: Dict[int, Tuple[float, float]] = {}
next_id = 0
def get_node_id(x: float, y: float) -> int:
nonlocal next_id
key = (round(float(x), 3), round(float(y), 3))
if key not in node_xy_to_id:
node_xy_to_id[key] = next_id
node_id_to_xy[next_id] = key
G.add_node(next_id, x=key[0], y=key[1])
next_id += 1
return node_xy_to_id[key]
edge_count = 0
for geom in roads_metric.geometry:
for line in explode_lines(geom):
coords = list(line.coords)
if len(coords) < 2:
continue
for a, b in zip(coords[:-1], coords[1:]):
u = get_node_id(*a)
v = get_node_id(*b)
dist = math.hypot(b[0] - a[0], b[1] - a[1])
if dist <= 0:
continue
if G.has_edge(u, v):
if dist < G[u][v]["weight"]:
G[u][v]["weight"] = dist
else:
G.add_edge(u, v, weight=dist)
edge_count += 1
logger.add(f"Nós viários no grafo: {G.number_of_nodes():,}".replace(",", "."))
logger.add(f"Arestas viárias no grafo: {edge_count:,}".replace(",", "."))
return G, node_id_to_xy
def build_kdtree_from_graph_nodes(node_id_to_xy: Dict[int, Tuple[float, float]]):
ids = np.array(list(node_id_to_xy.keys()))
xy = np.array([node_id_to_xy[i] for i in ids], dtype=float)
tree = cKDTree(xy)
return ids, xy, tree
def snap_points_to_graph(points_metric: gpd.GeoDataFrame, node_ids, node_xy, tree, logger: Logger) -> pd.DataFrame:
xy = np.array([(geom.x, geom.y) for geom in points_metric.geometry], dtype=float)
dist, idx = tree.query(xy, k=1)
snapped_ids = node_ids[idx]
out = points_metric.copy()
out["snap_node"] = snapped_ids
out["snap_dist_m"] = dist
logger.add(
f"Distância média de snap dos nós municipais para a malha viária: {float(np.mean(dist)):.1f} m"
)
return pd.DataFrame(out.drop(columns="geometry"))
# ============================================================
# Construção do backbone por MST sobre distâncias de menor caminho
# ============================================================
def build_candidate_pairs(nodes_metric: gpd.GeoDataFrame, k: int) -> List[Tuple[int, int]]:
xy = np.array([(g.x, g.y) for g in nodes_metric.geometry], dtype=float)
tree = cKDTree(xy)
dists, idxs = tree.query(xy, k=min(k + 1, len(nodes_metric)))
pairs = set()
for i in range(len(nodes_metric)):
neighs = np.atleast_1d(idxs[i])[1:]
for j in neighs:
a, b = sorted((i, int(j)))
if a != b:
pairs.add((a, b))
return sorted(pairs)
def compute_sparse_intercity_graph(
road_graph: nx.Graph,
nodes_metric: gpd.GeoDataFrame,
logger: Logger,
k_values: List[int] = [4, 6, 8, 10, 12],
) -> Tuple[nx.Graph, Dict[Tuple[int, int], List[int]], int]:
routes: Dict[Tuple[int, int], List[int]] = {}
chosen_k = k_values[-1]
for k in k_values:
H = nx.Graph()
for idx, row in nodes_metric.iterrows():
H.add_node(idx, municipio=row["municipio"], snap_node=int(row["snap_node"]))
pairs = build_candidate_pairs(nodes_metric, k=k)
logger.add(f"Tentando grafo intermunicipal com k={k} vizinhos... pares: {len(pairs)}")
for i, j in pairs:
source = int(nodes_metric.loc[i, "snap_node"])
target = int(nodes_metric.loc[j, "snap_node"])
if source == target:
H.add_edge(i, j, weight=1.0)
routes[(i, j)] = [source]
continue
try:
path = nx.shortest_path(road_graph, source, target, weight="weight")
length = nx.path_weight(road_graph, path, weight="weight")
H.add_edge(i, j, weight=length)
routes[(i, j)] = path
except nx.NetworkXNoPath:
continue
if H.number_of_edges() == 0:
continue
if nx.is_connected(H):
logger.add(f"Grafo intermunicipal conectado com k={k}.")
chosen_k = k
return H, routes, chosen_k
comps = list(nx.connected_components(H))
logger.add(f"Ainda desconectado com k={k}. Componentes: {len(comps)}")
# tentativa final: conectar componentes pela menor distância euclidiana entre municípios, usando o menor caminho real na via
logger.add("Executando etapa final para conectar componentes remanescentes...")
H = nx.Graph()
for idx, row in nodes_metric.iterrows():
H.add_node(idx, municipio=row["municipio"], snap_node=int(row["snap_node"]))
# reaproveita maior k
pairs = build_candidate_pairs(nodes_metric, k=chosen_k)
for i, j in pairs:
source = int(nodes_metric.loc[i, "snap_node"])
target = int(nodes_metric.loc[j, "snap_node"])
try:
path = nx.shortest_path(road_graph, source, target, weight="weight")
length = nx.path_weight(road_graph, path, weight="weight")
H.add_edge(i, j, weight=length)
routes[(i, j)] = path
except nx.NetworkXNoPath:
pass
xy = np.array([(g.x, g.y) for g in nodes_metric.geometry], dtype=float)
while H.number_of_nodes() > 0 and not nx.is_connected(H):
comps = [sorted(list(c)) for c in nx.connected_components(H)]
best = None
for a_idx in range(len(comps)):
for b_idx in range(a_idx + 1, len(comps)):
for i in comps[a_idx]:
for j in comps[b_idx]:
d = float(np.linalg.norm(xy[i] - xy[j]))
if best is None or d < best[0]:
best = (d, i, j)
if best is None:
break
_, i, j = best
source = int(nodes_metric.loc[i, "snap_node"])
target = int(nodes_metric.loc[j, "snap_node"])
try:
path = nx.shortest_path(road_graph, source, target, weight="weight")
length = nx.path_weight(road_graph, path, weight="weight")
H.add_edge(i, j, weight=length)
routes[(min(i, j), max(i, j))] = path
except nx.NetworkXNoPath:
# evita loop infinito
H.add_edge(i, j, weight=best[0] * 1000)
routes[(min(i, j), max(i, j))] = [source, target]
if not nx.is_connected(H):
raise ValueError("Não foi possível conectar todos os nós municipais pela malha viária do PBF.")
return H, routes, chosen_k
def extract_mst_routes(
H: nx.Graph,
routes: Dict[Tuple[int, int], List[int]],
nodes_metric: gpd.GeoDataFrame,
node_id_to_xy: Dict[int, Tuple[float, float]],
) -> gpd.GeoDataFrame:
mst = nx.minimum_spanning_tree(H, weight="weight")
rows = []
for u, v, data in mst.edges(data=True):
key = (min(u, v), max(u, v))
path_nodes = routes[key]
coords = [node_id_to_xy[n] for n in path_nodes if n in node_id_to_xy]
if len(coords) < 2:
continue
rows.append(
{
"origem": nodes_metric.loc[u, "municipio"],
"destino": nodes_metric.loc[v, "municipio"],
"length_m": float(data["weight"]),
"geometry": LineString(coords),
}
)
return gpd.GeoDataFrame(rows, geometry="geometry", crs=nodes_metric.crs)
# ============================================================
# Saída KML + CSV + LOG
# ============================================================
def export_outputs(
out_dir: str,
backbone_lines_wgs84: gpd.GeoDataFrame,
nodes_wgs84: gpd.GeoDataFrame,
logger: Logger,
) -> str:
out_dir = str(out_dir)
kml = simplekml.Kml(name="Backbone Chiapas")
folder_lines = kml.newfolder(name="Backbone_Linhas")
folder_nodes = kml.newfolder(name="Nos_Backbone_Nucleo")
for _, row in backbone_lines_wgs84.iterrows():
ls = folder_lines.newlinestring(
name=f"{row['origem']} x {row['destino']}",
coords=list(row.geometry.coords),
)
ls.style.linestyle.width = 4
ls.style.linestyle.color = simplekml.Color.blue
ls.description = f"Comprimento aproximado: {row['length_m']:.0f} m"
for _, row in nodes_wgs84.iterrows():
pt = folder_nodes.newpoint(name=row["municipio"], coords=[(row.geometry.x, row.geometry.y)])
pt.style.iconstyle.color = simplekml.Color.red
pt.style.iconstyle.scale = 1.1
pt.description = (
f"Municipio: {row['municipio']}\n"
f"Origem do nó: {row['node_source']}\n"
f"Nome OSM: {safe_str(row.get('name', ''))}\n"
f"Amenity: {safe_str(row.get('amenity', ''))}\n"
f"Office: {safe_str(row.get('office', ''))}\n"
f"Building: {safe_str(row.get('building', ''))}\n"
f"Government: {safe_str(row.get('government', ''))}"
)
kml_path = os.path.join(out_dir, "chiapas_backbone.kml")
kml.save(kml_path)
nodes_csv = os.path.join(out_dir, "chiapas_backbone_nos.csv")
nodes_export = nodes_wgs84.copy()
nodes_export["lon"] = nodes_export.geometry.x
nodes_export["lat"] = nodes_export.geometry.y
nodes_export.drop(columns="geometry").to_csv(nodes_csv, index=False, encoding="utf-8-sig")
lines_csv = os.path.join(out_dir, "chiapas_backbone_trechos.csv")
backbone_lines_wgs84.drop(columns="geometry").to_csv(lines_csv, index=False, encoding="utf-8-sig")
log_path = os.path.join(out_dir, "processamento_log.txt")
with open(log_path, "w", encoding="utf-8") as f:
f.write(logger.dump())
zip_path = os.path.join(out_dir, "chiapas_backbone_saida.zip")
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
zf.write(kml_path, arcname=os.path.basename(kml_path))
zf.write(nodes_csv, arcname=os.path.basename(nodes_csv))
zf.write(lines_csv, arcname=os.path.basename(lines_csv))
zf.write(log_path, arcname=os.path.basename(log_path))
return zip_path
# ============================================================
# Pipeline principal
# ============================================================
def build_backbone_from_pbf(pbf_file: str) -> BuildResult:
logger = Logger()
logger.add("Iniciando leitura do PBF...")
layers = list_pbf_layers(pbf_file)
logger.add(f"Camadas encontradas no PBF: {', '.join(layers)}")
needed = {"lines", "points", "multipolygons"}
missing = needed - set(layers)
if missing:
raise ValueError(
f"O PBF precisa conter as camadas {sorted(needed)}. Ausentes: {sorted(missing)}"
)
roads = load_roads(pbf_file, logger)
municipalities = load_municipalities(pbf_file, logger)
public_candidates = load_public_buildings_and_pois(pbf_file, logger)
if len(municipalities) != 124:
logger.add(
f"ATENÇÃO: foram detectados {len(municipalities)} municípios, não exatamente 124. O processamento continuará."
)
metric_crs = choose_metric_crs(municipalities)
logger.add(f"CRS métrico escolhido: {metric_crs.to_string()}")
roads_metric = roads.to_crs(metric_crs)
municipalities_metric = municipalities.to_crs(metric_crs)
public_metric = public_candidates.to_crs(metric_crs)
nodes_metric = choose_backbone_nodes(municipalities_metric, public_metric, logger)
road_graph, node_id_to_xy = build_road_graph(roads_metric, logger)
graph_node_ids, graph_xy, graph_tree = build_kdtree_from_graph_nodes(node_id_to_xy)
snap_df = snap_points_to_graph(nodes_metric[["municipio", "node_source", "geometry"]].copy(), graph_node_ids, graph_xy, graph_tree, logger)
nodes_metric = nodes_metric.reset_index(drop=True)
nodes_metric["snap_node"] = snap_df["snap_node"].values
nodes_metric["snap_dist_m"] = snap_df["snap_dist_m"].values
H, routes, chosen_k = compute_sparse_intercity_graph(road_graph, nodes_metric, logger)
logger.add(f"Valor final de k utilizado na conexão intermunicipal: {chosen_k}")
backbone_lines_metric = extract_mst_routes(H, routes, nodes_metric, node_id_to_xy)
logger.add(f"Trechos finais do backbone (MST): {len(backbone_lines_metric)}")
logger.add(
f"Comprimento total aproximado do backbone: {backbone_lines_metric['length_m'].sum()/1000:.1f} km"
)
backbone_lines_wgs84 = backbone_lines_metric.to_crs(4326)
nodes_wgs84 = nodes_metric.to_crs(4326)
out_dir = tempfile.mkdtemp(prefix="chiapas_backbone_")
zip_path = export_outputs(out_dir, backbone_lines_wgs84, nodes_wgs84, logger)
return BuildResult(zip_path=zip_path, log_text=logger.dump())
# ============================================================
# Interface Gradio
# ============================================================
def run_app(pbf_file):
if pbf_file is None:
raise gr.Error("Envie um arquivo .pbf do estado de Chiapas.")
pbf_path = pbf_file.name if hasattr(pbf_file, "name") else str(pbf_file)
if not pbf_path.lower().endswith(".pbf"):
raise gr.Error("O arquivo enviado precisa estar no formato .pbf.")
try:
result = build_backbone_from_pbf(pbf_path)
return result.zip_path, result.log_text
except Exception as e:
raise gr.Error(f"Falha no processamento: {e}")
DESCRIPTION = """
# Backbone de Fibra Óptica – Chiapas (PBF → KML)
Este app lê **um único arquivo `.pbf` do OpenStreetMap** do estado de Chiapas e gera:
- **KML** do backbone viário entre os municípios detectados;
- **pontos dos nós de backbone de núcleo** por município;
- CSVs auxiliares e log de processamento.
## Regras implementadas
1. Usa os **124 municípios** de Chiapas quando eles estiverem presentes no PBF como `boundary=administrative` e `admin_level=8`.
2. Tenta escolher, dentro de cada município, **um prédio público/governamental** com prioridade para:
- `amenity=townhall`
- `office=government`
- `government=*`
- `amenity=police`
- `amenity=courthouse`
- `building=public/civic`
3. Conecta os municípios pela **malha de vias do próprio PBF**.
4. O backbone final é uma **árvore geradora mínima (MST)** sobre as distâncias de menor caminho na rede viária.
## Observação importante
Se o PBF não trouxer corretamente os **limites municipais** ou não tiver **prédios públicos etiquetados** em alguns municípios, o app faz fallback para o ponto representativo do município e registra isso no log.
"""
with gr.Blocks() as demo:
gr.Markdown(DESCRIPTION)
with gr.Row():
pbf_input = gr.File(label="Arquivo PBF de Chiapas", file_types=[".pbf"])
run_btn = gr.Button("Gerar backbone")
zip_output = gr.File(label="Saída ZIP (KML + CSV + LOG)")
log_output = gr.Textbox(label="Log de processamento", lines=22)
run_btn.click(fn=run_app, inputs=pbf_input, outputs=[zip_output, log_output])
if __name__ == "__main__":
demo.launch()