douglasribeiro's picture
Update app.py
b1c2589 verified
Raw History Blame Contribute Delete
35.6 kB
# ============================================================
# VGO6 — HF Spaces + Gradio (CPU Basic-friendly)
# - Upload shapefile (um ou vários arquivos .shp/.dbf/.shx/.prj...)
# - Usuário escolhe UF
# - Cidades (municípios) vêm do IBGE (localidades + malhas por município -> centróides)
# - MST (kNN) com arestas obrigatórias (user picks) + segmentos com fallbacks + KML/CSVs
# ============================================================
import os, time, json, math, traceback, tempfile
import requests
import numpy as np
import pandas as pd
import geopandas as gpd
import networkx as nx
import osmnx as ox
import simplekml
from shapely.geometry import Point, LineString, Polygon, shape
from sklearn.neighbors import NearestNeighbors
# -------------------------
# OSMnx settings
# -------------------------
ox.settings.log_console = False
ox.settings.use_cache = True
# -------------------------
# PARAMS (defaults)
# -------------------------
SPAN_THRESHOLD_M_DEFAULT = 200.0
BASE_PARAMS = dict(
buffer_bbox_km=15,
buffer_road_km=8,
k_neighbors=10,
max_edge_m=3000.0,
alpha=10.0,
beta=0.3
)
FALLBACK_STAGES = [
dict(name="stage1_base", **BASE_PARAMS),
dict(name="stage2_wider_corridor",
buffer_bbox_km=20, buffer_road_km=15, k_neighbors=14, max_edge_m=3500.0, alpha=10.0, beta=0.25),
dict(name="stage3_very_wide_corridor",
buffer_bbox_km=30, buffer_road_km=25, k_neighbors=18, max_edge_m=4500.0, alpha=10.0, beta=0.15),
dict(name="stage4_free_alignment",
buffer_bbox_km=35, buffer_road_km=35, k_neighbors=22, max_edge_m=7000.0, alpha=12.0, beta=0.0),
]
SNAP_STEP_M = 150.0
SNAP_RADIUS_M = 120.0
UF_OPTIONS = [
"AC","AL","AP","AM","BA","CE","DF","ES","GO","MA","MT","MS","MG",
"PA","PB","PR","PE","PI","RJ","RN","RS","RO","RR","SC","SP","SE","TO"
]
# Cache persistente (HF Spaces costuma manter /data entre execuções)
DATA_DIR = os.getenv("HF_HOME", "/data")
CACHE_DIR = os.path.join(DATA_DIR, "vgo6_cache")
os.makedirs(CACHE_DIR, exist_ok=True)
# ============================================================
# Upload staging
# ============================================================
def stage_uploaded_files(files):
"""
Recebe lista de arquivos do gr.File (paths) e copia para um diretório temporário.
Retorna (tmpdir, shp_path).
"""
if not files:
raise ValueError("Envie o shapefile de postes (ideal: .shp + .dbf + .shx + .prj).")
tmpdir = tempfile.mkdtemp(prefix="vgo6_")
shp_path = None
for f in files:
src = f if isinstance(f, str) else getattr(f, "name", None) or getattr(f, "path", None)
if not src:
continue
base = os.path.basename(src)
dst = os.path.join(tmpdir, base)
with open(src, "rb") as r, open(dst, "wb") as w:
w.write(r.read())
if base.lower().endswith(".shp"):
shp_path = dst
if not shp_path:
raise ValueError("Não encontrei nenhum .shp no upload. Envie o arquivo .shp (e, se possível, .dbf/.shx).")
return tmpdir, shp_path
# ============================================================
# IO: Postes
# ============================================================
def load_poles_shapefile(shp_path):
# tenta recriar SHX se faltar
os.environ["SHAPE_RESTORE_SHX"] = "YES"
try:
gdf = gpd.read_file(shp_path, engine="pyogrio")
except Exception:
gdf = gpd.read_file(shp_path)
if gdf.crs is None:
gdf = gdf.set_crs(4326)
else:
gdf = gdf.to_crs(4326)
gdf = gdf[gdf.geometry.type.isin(["Point", "MultiPoint"])].copy()
gdf["geometry"] = gdf.geometry.apply(lambda g: g[0] if g.geom_type == "MultiPoint" else g)
gdf = gdf.dropna(subset=["geometry"]).reset_index(drop=True)
return gdf
# ============================================================
# IBGE: UF id + municipios list + centroides via malhas por municipio
# ============================================================
def ibge_get_uf_id_from_sigla(uf_sigla, timeout=60):
uf_sigla = uf_sigla.upper().strip()
estados = requests.get(
"https://servicodados.ibge.gov.br/api/v1/localidades/estados",
timeout=timeout
).json()
match = [e for e in estados if e.get("sigla") == uf_sigla]
if not match:
raise ValueError(f"UF inválida: {uf_sigla}")
return int(match[0]["id"]) # ex.: GO=52, MS=50
def ibge_list_municipios_por_uf(uf_id, timeout=90):
"""
Retorna lista de dicts: [{"id":..., "nome":...}, ...]
"""
url = f"https://servicodados.ibge.gov.br/api/v1/localidades/estados/{uf_id}/municipios"
data = requests.get(url, timeout=timeout).json()
out = []
for m in data:
mid = m.get("id")
nome = m.get("nome")
if mid and nome:
out.append({"id": int(mid), "name": str(nome).strip()})
return out
def _ibge_fetch_malha_geojson_any(mun_id, qualidade=2, timeout=120, session=None):
"""
Tenta múltiplos endpoints (v3 e v2) para obter GeoJSON do município.
Retorna dict GeoJSON (ou None).
"""
s = session or requests.Session()
# 1) tenta v3 (mais comum)
urls = [
f"https://servicodados.ibge.gov.br/api/v3/malhas/municipios/{mun_id}"
f"?formato=application/vnd.geo+json&resolucao=5&qualidade={int(qualidade)}",
# 2) fallback v2 (algumas instalações/rotas antigas)
f"https://servicodados.ibge.gov.br/api/v2/malhas/{mun_id}"
f"?formato=application/vnd.geo+json&resolucao=5&qualidade={int(qualidade)}",
]
last_err = None
for url in urls:
try:
resp = s.get(url, timeout=timeout)
if resp.status_code != 200:
last_err = f"{resp.status_code} @ {url}"
continue
gj = resp.json()
feats = gj.get("features", [])
if feats:
return gj
# às vezes vem como FeatureCollection vazia (ruim)
last_err = f"no features @ {url}"
except Exception as e:
last_err = repr(e)
return None
def ibge_municipios_centroides_por_uf(
uf_sigla: str,
qualidade: int = 2,
cache: bool = True,
throttle_s: float = 0.05
):
"""
- Busca municipios via localidades (id+nome)
- Para cada municipio, baixa malha (GeoJSON) e calcula centróide
- Cacheia por UF/qualidade em /data (HF)
Retorna: (uf_id, cities_gdf, cities_status_df)
"""
uf_sigla = uf_sigla.upper().strip()
uf_id = ibge_get_uf_id_from_sigla(uf_sigla)
cache_path = os.path.join(CACHE_DIR, f"ibge_centroids_{uf_sigla}_q{int(qualidade)}.csv")
if cache and os.path.exists(cache_path):
df = pd.read_csv(cache_path)
df = df.dropna(subset=["lat", "lon"])
gdf = gpd.GeoDataFrame(
df,
geometry=[Point(lon, lat) for lon, lat in zip(df["lon"], df["lat"])],
crs=4326
)
status = df[["id", "name", "ok"]].copy()
return uf_id, gdf.reset_index(drop=True), status.reset_index(drop=True)
municipios = ibge_list_municipios_por_uf(uf_id)
if not municipios:
raise RuntimeError(f"IBGE localidades não retornou municípios para UF={uf_sigla} (id={uf_id}).")
rows = []
status_rows = []
s = requests.Session()
for idx, m in enumerate(municipios, 1):
mid = int(m["id"])
name = m["name"]
gj = _ibge_fetch_malha_geojson_any(mid, qualidade=qualidade, session=s)
if not gj:
status_rows.append({"id": mid, "name": name, "ok": False, "reason": "malha_geojson_fail"})
continue
try:
geom = gj["features"][0].get("geometry")
if not geom:
status_rows.append({"id": mid, "name": name, "ok": False, "reason": "no_geometry"})
continue
g = shape(geom)
# centróide em WGS84 (shapely calcula em graus; ok para ponto “aprox”)
c = g.centroid
rows.append({"id": mid, "name": name, "lat": float(c.y), "lon": float(c.x)})
status_rows.append({"id": mid, "name": name, "ok": True, "reason": ""})
except Exception as e:
status_rows.append({"id": mid, "name": name, "ok": False, "reason": f"centroid_err:{repr(e)}"})
# micro-throttle (evita estourar IBGE)
if throttle_s:
time.sleep(throttle_s)
status_df = pd.DataFrame(status_rows)
df = pd.DataFrame(rows)
if cache:
# salva com status para diagnosticar
merged = status_df.merge(df, on=["id", "name"], how="left")
merged.to_csv(cache_path, index=False, encoding="utf-8-sig")
df = df.dropna(subset=["lat", "lon"]).drop_duplicates(subset=["name"]).reset_index(drop=True)
gdf = gpd.GeoDataFrame(df, geometry=[Point(lon, lat) for lon, lat in zip(df["lon"], df["lat"])], crs=4326)
return uf_id, gdf.reset_index(drop=True), status_df.reset_index(drop=True)
# ============================================================
# MST: kNN graph + MST
# + Arestas obrigatórias (user)
# ============================================================
def haversine_m(lat1, lon1, lat2, lon2):
R = 6371000.0
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dl = math.radians(lon2 - lon1)
a = math.sin(dphi/2)**2 + math.cos(phi1)*math.cos(phi2)*math.sin(dl/2)**2
return 2*R*math.atan2(math.sqrt(a), math.sqrt(1-a))
def build_city_knn_edges(cities_gdf, k=10):
coords = np.vstack([cities_gdf[["lat","lon"]].values])
nn = NearestNeighbors(n_neighbors=min(k+1, len(coords))).fit(coords)
_, idxs = nn.kneighbors(coords)
edges = []
for i in range(len(cities_gdf)):
for j in idxs[i][1:]:
j = int(j)
if j == i:
continue
lat1, lon1 = cities_gdf.iloc[i][["lat","lon"]]
lat2, lon2 = cities_gdf.iloc[j][["lat","lon"]]
w = haversine_m(lat1, lon1, lat2, lon2)
a, b = (i, j) if i < j else (j, i)
edges.append((a, b, float(w)))
# unique
edges = list({(a,b):w for a,b,w in edges}.items())
return [(a,b,w) for (a,b),w in edges]
class DSU:
def __init__(self, n):
self.p = list(range(n))
self.r = [0]*n
def find(self, x):
while self.p[x] != x:
self.p[x] = self.p[self.p[x]]
x = self.p[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.r[ra] < self.r[rb]:
ra, rb = rb, ra
self.p[rb] = ra
if self.r[ra] == self.r[rb]:
self.r[ra] += 1
return True
def parse_required_links(text, name_to_idx):
"""
Espera linhas no formato:
Cidade A | Cidade B
Cidade A ; Cidade B
Cidade A -> Cidade B
Retorna lista [(i,j),...]
"""
req = []
if not text or not text.strip():
return req
for raw in text.splitlines():
line = raw.strip()
if not line:
continue
for sep in ["|", ";", "->", "↔", ","]:
if sep in line:
a, b = [x.strip() for x in line.split(sep, 1)]
break
else:
# linha inválida, ignora
continue
if not a or not b:
continue
ia = name_to_idx.get(a.lower())
ib = name_to_idx.get(b.lower())
if ia is None or ib is None:
# tenta fuzzy mínimo: contém
ia = next((i for k,i in name_to_idx.items() if a.lower() in k), None)
ib = next((i for k,i in name_to_idx.items() if b.lower() in k), None)
if ia is None or ib is None or ia == ib:
continue
u, v = (ia, ib) if ia < ib else (ib, ia)
if (u, v) not in req:
req.append((u, v))
return req
def build_mst_with_required_edges(cities_gdf, k=10, required_pairs=None):
"""
MST via Kruskal em grafo kNN, mas:
- inclui primeiro as arestas obrigatórias (required_pairs)
- depois completa com arestas do kNN (ordenadas por peso)
"""
n = len(cities_gdf)
required_pairs = required_pairs or []
# edges kNN
knn_edges = build_city_knn_edges(cities_gdf, k=k)
# cria grafo resultado
T = nx.Graph()
for i in range(n):
T.add_node(i, name=cities_gdf.iloc[i]["name"])
dsu = DSU(n)
# 1) adiciona required
for (u, v) in required_pairs:
lat1, lon1 = cities_gdf.iloc[u][["lat","lon"]]
lat2, lon2 = cities_gdf.iloc[v][["lat","lon"]]
w = haversine_m(lat1, lon1, lat2, lon2)
# força inserir (mesmo que já una componente)
if not T.has_edge(u, v):
T.add_edge(u, v, weight=float(w), forced=True)
dsu.union(u, v)
# 2) completa kruskal usando kNN
knn_edges_sorted = sorted(knn_edges, key=lambda x: x[2])
for a, b, w in knn_edges_sorted:
if T.number_of_edges() >= n - 1:
break
if dsu.union(a, b):
T.add_edge(a, b, weight=float(w), forced=False)
# 3) se ainda não conectou (raro), conecta componentes por pares mais próximos (haversine completo)
if n > 1 and not nx.is_connected(T):
comps = sorted(list(nx.connected_components(T)), key=len, reverse=True)
while len(comps) > 1:
A = list(comps[0])
B = list(comps[1])
best = None
for i in A:
for j in B:
lat1, lon1 = cities_gdf.iloc[i][["lat","lon"]]
lat2, lon2 = cities_gdf.iloc[j][["lat","lon"]]
w = haversine_m(lat1, lon1, lat2, lon2)
if best is None or w < best[0]:
best = (w, i, j)
w, i, j = best
T.add_edge(i, j, weight=float(w), forced=False)
comps = sorted(list(nx.connected_components(T)), key=len, reverse=True)
return T
# ============================================================
# Rotas OSM + grafo de postes + fallbacks
# ============================================================
def estimate_bbox_between_points(p1, p2, buffer_km=15):
min_lat, max_lat = sorted([p1.y, p2.y])
min_lon, max_lon = sorted([p1.x, p2.x])
delta = buffer_km / 111.0
return (max_lat + delta, min_lat - delta, max_lon + delta, min_lon - delta)
def clip_poles_to_bbox(poles_gdf, north, south, east, west):
poly = Polygon([(west,south),(west,north),(east,north),(east,south),(west,south)])
return poles_gdf[poles_gdf.geometry.within(poly)].copy()
def download_road_network_for_pair(p1, p2, extra_buffer_km=5):
cities_m = gpd.GeoSeries([p1, p2], crs=4326).to_crs(3857)
dist_m = cities_m.iloc[0].distance(cities_m.iloc[1])
radius_m = dist_m/2 + extra_buffer_km*1000
mid_lon, mid_lat = (p1.x+p2.x)/2, (p1.y+p2.y)/2
G = ox.graph_from_point((mid_lat, mid_lon), dist=radius_m, network_type="drive", simplify=True)
return G
def road_route_line_for_pair(p1, p2):
G = download_road_network_for_pair(p1, p2)
nodes, _ = ox.graph_to_gdfs(G)
orig = ox.distance.nearest_nodes(G, X=p1.x, Y=p1.y)
dest = ox.distance.nearest_nodes(G, X=p2.x, Y=p2.y)
route_nodes = nx.shortest_path(G, orig, dest, weight="length")
coords = [(nodes.loc[n].x, nodes.loc[n].y) for n in route_nodes]
route_ll = LineString(coords)
return gpd.GeoSeries([route_ll], crs=4326).to_crs(3857).iloc[0]
def smooth_line(coords_4326, tolerance_m=20):
if len(coords_4326) < 2:
return coords_4326
line_ll = gpd.GeoSeries([LineString(coords_4326)], crs=4326).to_crs(3857)
simp_m = line_ll.geometry.iloc[0].simplify(tolerance_m)
simp_ll = gpd.GeoSeries([simp_m], crs=3857).to_crs(4326).iloc[0]
return list(simp_ll.coords)
def build_segments_from_path(poles_m, path_indices, gap_threshold=200):
poles_ll = poles_m.to_crs(4326)
coords = [(poles_ll.geometry.iloc[i].x, poles_ll.geometry.iloc[i].y) for i in path_indices]
segments = []
for i1, i2 in zip(path_indices[:-1], path_indices[1:]):
p1_m = poles_m.geometry.iloc[i1]
p2_m = poles_m.geometry.iloc[i2]
d = float(p1_m.distance(p2_m))
p1_ll = poles_ll.geometry.iloc[i1]
p2_ll = poles_ll.geometry.iloc[i2]
segments.append({
"start_coord": (p1_ll.x, p1_ll.y),
"end_coord": (p2_ll.x, p2_ll.y),
"length_m": d,
"is_gap": d > gap_threshold
})
return coords, segments
def build_pole_graph(poles_corr_m, road_line_m, span_threshold, k_neighbors, max_edge_m, alpha, beta):
N = len(poles_corr_m)
if N < 2:
raise RuntimeError("Poucos postes no recorte para montar grafo.")
dist_road = poles_corr_m.geometry.apply(lambda p: p.distance(road_line_m))
poles_corr_m = poles_corr_m.copy()
poles_corr_m["dist_road"] = dist_road.values
coords = np.array([[g.x, g.y] for g in poles_corr_m.geometry])
nn = NearestNeighbors(n_neighbors=min(k_neighbors+1, N)).fit(coords)
dists, neigh_idx = nn.kneighbors(coords)
G = nx.Graph()
for i in range(N):
G.add_node(i, dist_road=float(poles_corr_m["dist_road"].iloc[i]))
for i in range(N):
di = poles_corr_m["dist_road"].iloc[i]
for d, j in zip(dists[i][1:], neigh_idx[i][1:]):
j = int(j)
if j <= i:
continue
if d > max_edge_m:
continue
dj = poles_corr_m["dist_road"].iloc[j]
gap = max(0.0, float(d) - span_threshold)
road_penalty = float((di + dj) / 2.0)
cost = float(d) + alpha * gap + beta * road_penalty
G.add_edge(i, j, length_m=float(d), extra_gap=float(gap), cost=float(cost))
return G, poles_corr_m
def compute_segment_v16_style(poles_gdf, p_orig, p_dest, params, span_threshold=200.0):
north, south, east, west = estimate_bbox_between_points(p_orig, p_dest, buffer_km=params["buffer_bbox_km"])
poles_bbox = clip_poles_to_bbox(poles_gdf, north, south, east, west).to_crs(3857)
road_line_m = road_route_line_for_pair(p_orig, p_dest)
corridor_m = road_line_m.buffer(params["buffer_road_km"] * 1000.0)
poles_corr_m = poles_bbox[poles_bbox.geometry.within(corridor_m)].copy().reset_index(drop=True)
if len(poles_corr_m) < 30:
raise RuntimeError(f"Poucos postes no corredor: {len(poles_corr_m)}")
G_poles, poles_corr_m = build_pole_graph(
poles_corr_m, road_line_m,
span_threshold=span_threshold,
k_neighbors=params["k_neighbors"],
max_edge_m=params["max_edge_m"],
alpha=params["alpha"],
beta=params["beta"],
)
p_orig_m = gpd.GeoSeries([p_orig], crs=4326).to_crs(3857).iloc[0]
p_dest_m = gpd.GeoSeries([p_dest], crs=4326).to_crs(3857).iloc[0]
coords_corr = np.array([[g.x, g.y] for g in poles_corr_m.geometry])
nn_sd = NearestNeighbors(n_neighbors=1).fit(coords_corr)
_, idx_o = nn_sd.kneighbors([[p_orig_m.x, p_orig_m.y]])
_, idx_d = nn_sd.kneighbors([[p_dest_m.x, p_dest_m.y]])
start_idx = int(idx_o[0][0])
end_idx = int(idx_d[0][0])
path = nx.shortest_path(G_poles, start_idx, end_idx, weight="cost")
coords_4326, segments = build_segments_from_path(poles_corr_m, path, gap_threshold=span_threshold)
coords_smooth = smooth_line(coords_4326, tolerance_m=20.0)
total_len = sum(s["length_m"] for s in segments)
gaps = [s for s in segments if s["is_gap"]]
total_gap = sum(s["length_m"] for s in gaps)
new_poles = sum(max(0, int(math.ceil(s["length_m"]/span_threshold)-1)) for s in gaps)
resumo = dict(
method=params["name"],
dist_m=float(total_len),
n_gaps=int(len(gaps)),
total_gap_m=float(total_gap),
new_poles=int(new_poles),
poles_used=int(len(coords_4326))
)
return coords_smooth, segments, resumo
def fallback_snap_route_to_poles(poles_gdf, p_orig, p_dest, span_threshold=200.0):
road_line_m = road_route_line_for_pair(p_orig, p_dest)
poles_m = poles_gdf.to_crs(3857)
coords_poles = np.array([[g.x, g.y] for g in poles_m.geometry])
nn = NearestNeighbors(n_neighbors=1).fit(coords_poles)
L = road_line_m.length
nsteps = max(2, int(L // SNAP_STEP_M) + 1)
dists = np.linspace(0, L, nsteps)
pts = [road_line_m.interpolate(d) for d in dists]
coords_ll = []
used_flags = []
for pt in pts:
_, idx = nn.kneighbors([[pt.x, pt.y]])
idx = int(idx[0][0])
pole = poles_m.geometry.iloc[idx]
if pole.distance(pt) <= SNAP_RADIUS_M:
pole_ll = gpd.GeoSeries([pole], crs=3857).to_crs(4326).iloc[0]
coords_ll.append((pole_ll.x, pole_ll.y))
used_flags.append(True)
else:
pt_ll = gpd.GeoSeries([pt], crs=3857).to_crs(4326).iloc[0]
coords_ll.append((pt_ll.x, pt_ll.y))
used_flags.append(False)
segments = []
for (a, b, ua, ub) in zip(coords_ll[:-1], coords_ll[1:], used_flags[:-1], used_flags[1:]):
pa_m = gpd.GeoSeries([Point(a)], crs=4326).to_crs(3857).iloc[0]
pb_m = gpd.GeoSeries([Point(b)], crs=4326).to_crs(3857).iloc[0]
d = float(pa_m.distance(pb_m))
is_gap = (d > span_threshold) or (not ua) or (not ub)
segments.append({"start_coord": a, "end_coord": b, "length_m": d, "is_gap": is_gap})
coords_smooth = smooth_line(coords_ll, tolerance_m=25.0)
total_len = sum(s["length_m"] for s in segments)
gaps = [s for s in segments if s["is_gap"]]
total_gap = sum(s["length_m"] for s in gaps)
new_poles = sum(max(0, int(math.ceil(s["length_m"]/span_threshold)-1)) for s in gaps)
resumo = dict(
method="fallback_snap_route",
dist_m=float(total_len),
n_gaps=int(len(gaps)),
total_gap_m=float(total_gap),
new_poles=int(new_poles),
poles_used=int(sum(used_flags))
)
return coords_smooth, segments, resumo
def ultimate_fallback_straight(p_orig, p_dest, span_threshold=200.0):
a = (p_orig.x, p_orig.y)
b = (p_dest.x, p_dest.y)
pa_m = gpd.GeoSeries([Point(a)], crs=4326).to_crs(3857).iloc[0]
pb_m = gpd.GeoSeries([Point(b)], crs=4326).to_crs(3857).iloc[0]
d = float(pa_m.distance(pb_m))
segments = [{"start_coord": a, "end_coord": b, "length_m": d, "is_gap": True}]
new_poles = max(0, int(math.ceil(d/span_threshold)-1))
resumo = dict(method="fallback_straight", dist_m=d, n_gaps=1, total_gap_m=d, new_poles=int(new_poles), poles_used=0)
return [a, b], segments, resumo
def compute_segment_with_fallbacks(poles_gdf, p_orig, p_dest, span_threshold=200.0):
errors = []
for params in FALLBACK_STAGES:
try:
coords, segs, resumo = compute_segment_v16_style(poles_gdf, p_orig, p_dest, params, span_threshold=span_threshold)
return coords, segs, resumo, errors
except Exception as e:
errors.append(f"{params['name']}: {repr(e)}")
try:
coords, segs, resumo = fallback_snap_route_to_poles(poles_gdf, p_orig, p_dest, span_threshold=span_threshold)
return coords, segs, resumo, errors
except Exception as e:
errors.append(f"fallback_snap_route: {repr(e)}")
coords, segs, resumo = ultimate_fallback_straight(p_orig, p_dest, span_threshold=span_threshold)
return coords, segs, resumo, errors
# ============================================================
# KML helpers
# ============================================================
def build_kml_structure(uf):
kml = simplekml.Kml()
f_main = kml.newfolder(name=f"Backbone {uf} (VGO6)")
f_gaps = kml.newfolder(name="Gaps / Trechos críticos")
f_fbk = kml.newfolder(name="Fallbacks (snap/straight)")
f_pts = kml.newfolder(name="Cidades (pontos)")
return kml, f_main, f_gaps, f_fbk, f_pts
def add_edge_to_kml(folder_main, folder_gaps, folder_fbk, name, coords, segments, resumo, forced=False):
ls = folder_main.newlinestring(name=name + (" [FORÇADO]" if forced else ""))
ls.coords = coords
ls.style.linestyle.width = 2
if resumo["method"].startswith("stage"):
ls.style.linestyle.color = simplekml.Color.blue
elif resumo["method"] == "fallback_snap_route":
ls.style.linestyle.color = simplekml.Color.orange
else:
ls.style.linestyle.color = simplekml.Color.red
for seg in segments:
if seg["is_gap"]:
g = folder_gaps.newlinestring(name=f"GAP {name} ({seg['length_m']:.0f} m)")
g.coords = [seg["start_coord"], seg["end_coord"]]
g.style.linestyle.width = 3
g.style.linestyle.color = simplekml.Color.red
if resumo["method"].startswith("fallback"):
fb = folder_fbk.newlinestring(name=f"{name} [{resumo['method']}]")
fb.coords = coords
fb.style.linestyle.width = 3
fb.style.linestyle.color = simplekml.Color.orange
# ============================================================
# Garantia de conectividade final (extras)
# ============================================================
def ensure_connected_by_extra_links(cities_gdf, built_edges, poles_gdf, span_threshold=200.0):
G = nx.Graph()
for i in range(len(cities_gdf)):
G.add_node(i)
for u, v in built_edges:
G.add_edge(u, v)
if len(cities_gdf) <= 1 or nx.is_connected(G):
return []
extras = []
while not nx.is_connected(G):
comps = sorted(list(nx.connected_components(G)), key=len, reverse=True)
A = list(comps[0]); B = list(comps[1])
best = None
for i in A:
for j in B:
lat1, lon1 = cities_gdf.iloc[i][["lat","lon"]]
lat2, lon2 = cities_gdf.iloc[j][["lat","lon"]]
d = haversine_m(lat1, lon1, lat2, lon2)
if best is None or d < best[0]:
best = (d, i, j)
_, u, v = best
p_u = cities_gdf.geometry.iloc[u]
p_v = cities_gdf.geometry.iloc[v]
coords, segs, resumo, errs = compute_segment_with_fallbacks(poles_gdf, p_u, p_v, span_threshold=span_threshold)
extras.append((u, v, resumo, coords, segs, errs))
G.add_edge(u, v)
return extras
# ============================================================
# Pipeline principal (Gradio)
# ============================================================
def run_vgo6(files, uf, qualidade, k_city_knn, span_threshold_m, required_links_text):
try:
logs = []
t0 = time.time()
# 0) staging uploads
tmpdir, shp_path = stage_uploaded_files(files)
logs.append(f"📁 Upload staging: {tmpdir}")
logs.append(f"🧷 SHP: {shp_path}")
# 1) postes
logs.append("1) Lendo postes...")
poles = load_poles_shapefile(shp_path)
logs.append(f"✅ Postes carregados: {len(poles):,}")
if len(poles) < 10:
raise RuntimeError("Poucos postes no shapefile. Confirme se o arquivo está correto e em WGS84 (EPSG:4326) ou com CRS válido.")
# 2) IBGE: cidades por UF (centróides)
logs.append(f"2) Buscando municípios do UF={uf} via IBGE (localidades + malhas por município) ...")
uf_id, cities_gdf, cities_status = ibge_municipios_centroides_por_uf(uf, qualidade=int(qualidade), cache=True)
logs.append(f"✅ UF id: {uf_id} | Cidades com centróide OK: {len(cities_gdf)}")
fails = int((~cities_status["ok"]).sum()) if "ok" in cities_status.columns else 0
if fails:
logs.append(f"⚠️ Municípios sem centróide (falhas em malha/centroid): {fails}")
if len(cities_gdf) < 3:
# diagnóstico: mostra top reasons
if "reason" in cities_status.columns:
top = cities_status.loc[~cities_status["ok"], "reason"].value_counts().head(5).to_dict()
logs.append(f"Diagnóstico falhas IBGE: {top}")
raise RuntimeError("Poucas cidades retornadas pelo IBGE para montar a rede.")
# 3) required links parsing
name_to_idx = {str(cities_gdf.iloc[i]["name"]).strip().lower(): i for i in range(len(cities_gdf))}
required_pairs = parse_required_links(required_links_text or "", name_to_idx)
if required_pairs:
logs.append(f"3) Enlaces obrigatórios recebidos: {len(required_pairs)}")
else:
logs.append("3) Enlaces obrigatórios: nenhum")
# 4) MST (com required)
logs.append("4) Construindo MST (kNN) + arestas obrigatórias...")
k_city_knn = int(k_city_knn)
T = build_mst_with_required_edges(cities_gdf, k=k_city_knn, required_pairs=required_pairs)
logs.append(f"✅ Arestas no grafo final: {T.number_of_edges()} (esperado ~ {len(cities_gdf)-1})")
# 5) gerar KML/CSVs
logs.append("5) Gerando KML + CSVs...")
kml, f_main, f_gaps, f_fbk, f_pts = build_kml_structure(uf)
for _, row in cities_gdf.iterrows():
p = f_pts.newpoint(name=row["name"], coords=[(row["lon"], row["lat"])])
p.style.iconstyle.scale = 0.6
edges_rows = []
exc_rows = []
built_edges = []
# percorre arestas
for u, v, attrs in T.edges(data=True):
cu = cities_gdf.iloc[u]
cv = cities_gdf.iloc[v]
forced = bool(attrs.get("forced", False))
name = f"{cu['name']} ↔ {cv['name']}"
logs.append(("🔒 " if forced else "→ ") + name)
coords, segs, resumo, errs = compute_segment_with_fallbacks(
poles, cu.geometry, cv.geometry, span_threshold=float(span_threshold_m)
)
built_edges.append((u, v))
add_edge_to_kml(f_main, f_gaps, f_fbk, name, coords, segs, resumo, forced=forced)
edges_rows.append({
"city_u": cu["name"], "city_v": cv["name"],
"forced": forced,
"method": resumo["method"],
"dist_km": resumo["dist_m"]/1000.0,
"n_gaps": resumo["n_gaps"],
"gap_km": resumo["total_gap_m"]/1000.0,
"new_poles_est": resumo["new_poles"],
"poles_used": resumo.get("poles_used", None)
})
if errs:
exc_rows.append({
"edge": name,
"forced": forced,
"final_method": resumo["method"],
"error_chain": " | ".join(errs)
})
# 6) garante conectividade (extras)
logs.append("6) Garantindo conectividade total (extras se necessário)...")
extras = ensure_connected_by_extra_links(cities_gdf, built_edges, poles, span_threshold=float(span_threshold_m))
for (u, v, resumo, coords, segs, errs) in extras:
cu = cities_gdf.iloc[u]
cv = cities_gdf.iloc[v]
name = f"[EXTRA] {cu['name']} ↔ {cv['name']}"
logs.append(f"+ {name} | {resumo['method']}")
add_edge_to_kml(f_main, f_gaps, f_fbk, name, coords, segs, resumo, forced=False)
edges_rows.append({
"city_u": cu["name"], "city_v": cv["name"],
"forced": False,
"method": resumo["method"],
"dist_km": resumo["dist_m"]/1000.0,
"n_gaps": resumo["n_gaps"],
"gap_km": resumo["total_gap_m"]/1000.0,
"new_poles_est": resumo["new_poles"],
"poles_used": resumo.get("poles_used", None)
})
if errs:
exc_rows.append({
"edge": name,
"forced": False,
"final_method": resumo["method"],
"error_chain": " | ".join(errs)
})
df_edges = pd.DataFrame(edges_rows)
df_exc = pd.DataFrame(exc_rows)
outdir = tempfile.mkdtemp(prefix="vgo6_out_")
out_kml = os.path.join(outdir, f"backbone_{uf}_VGO6.kml")
out_edges = os.path.join(outdir, "vgo6_edges_summary.csv")
out_exc = os.path.join(outdir, "vgo6_exceptions.csv")
out_cities_status = os.path.join(outdir, "vgo6_cities_status.csv")
# status cidades (IBGE)
cities_status.to_csv(out_cities_status, index=False, encoding="utf-8-sig")
df_edges.to_csv(out_edges, index=False, encoding="utf-8-sig")
df_exc.to_csv(out_exc, index=False, encoding="utf-8-sig")
kml.save(out_kml)
total_km = df_edges["dist_km"].sum() if len(df_edges) else 0.0
total_new_poles = df_edges["new_poles_est"].sum() if len(df_edges) else 0
dt = time.time() - t0
logs.append("")
logs.append(f"✅ Concluído. Extensão total: {total_km:.1f} km | Postes novos est.: {int(total_new_poles)} | Arestas: {len(df_edges)}")
logs.append(f"⏱️ Tempo: {dt/60:.1f} min")
logs.append(f"📦 Saída: {outdir}")
# preview compacto
preview = df_edges.head(200)
return "\n".join(logs), preview, out_kml, out_edges, out_exc, out_cities_status
except Exception as e:
tb = traceback.format_exc()
return f"❌ ERRO:\n{repr(e)}\n\n{tb}", pd.DataFrame(), None, None, None, None
# ============================================================
# Gradio UI (Gradio 5.x)
# ============================================================
import gradio as gr
with gr.Blocks(title="VGO6 — Backbone por Postes (IBGE + OSM)") as demo:
gr.Markdown(
"## VGO6 — Backbone por postes (UF → cidades via IBGE)\n"
"- Envie o shapefile de postes (ideal: **.shp + .dbf + .shx**)\n"
"- Escolha a **UF** (para buscar municípios no IBGE)\n"
"- (Opcional) Defina **enlaces obrigatórios**: linhas `Cidade A | Cidade B`\n"
"- O app gera **KML** + **CSVs** para download.\n"
"\n"
"**Dica (CPU Basic):** GO e outros estados grandes podem demorar. Ajuste `kNN do MST` e a qualidade do IBGE se precisar.\n"
)
with gr.Row():
files = gr.File(label="Upload shapefile (selecione múltiplos arquivos: .shp/.dbf/.shx/.prj)", file_count="multiple")
uf = gr.Dropdown(UF_OPTIONS, value="GO", label="UF (para buscar municípios no IBGE)")
with gr.Row():
qualidade = gr.Slider(1, 4, value=2, step=1, label="IBGE qualidade (1=pior … 4=melhor)")
k_city_knn = gr.Slider(6, 24, value=10, step=1, label="kNN do MST (cidades)")
span_threshold_m = gr.Slider(100, 400, value=SPAN_THRESHOLD_M_DEFAULT, step=10, label="Vão máximo entre postes (m)")
required_links_text = gr.Textbox(
label="Enlaces obrigatórios (opcional) — 1 por linha: Cidade A | Cidade B",
lines=6,
placeholder="Ex:\nAnápolis | Alexânia\nGoiânia | Aparecida de Goiânia"
)
run_btn = gr.Button("🚀 Gerar Backbone (VGO6)", variant="primary")
logs = gr.Textbox(label="Logs", lines=18)
df_preview = gr.Dataframe(label="Resumo de arestas (preview)", interactive=False)
with gr.Row():
out_kml = gr.File(label="KML (backbone)")
out_edges = gr.File(label="CSV arestas")
out_exc = gr.File(label="CSV exceções")
out_cities = gr.File(label="CSV status cidades (IBGE)")
run_btn.click(
fn=run_vgo6,
inputs=[files, uf, qualidade, k_city_knn, span_threshold_m, required_links_text],
outputs=[logs, df_preview, out_kml, out_edges, out_exc, out_cities],
concurrency_limit=1
)
demo.queue().launch(server_name="0.0.0.0", server_port=7860)