douglasribeiro's picture
Update app.py
9cb0f55 verified
Raw History Blame Contribute Delete
29.4 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) -> centróides por Malhas (por município) + cache
# - MST (kNN) + segmentos com fallbacks + KML/CSVs para download
# ============================================================
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 config
# -------------------------
ox.settings.log_console = False
ox.settings.use_cache = True
# -------------------------
# PARAMS
# -------------------------
SPAN_THRESHOLD_M = 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
CITY_KNN_K = 10
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"
]
# -------------------------
# Helpers: upload -> folder
# -------------------------
def stage_uploaded_files(files):
"""
Recebe lista de arquivos (gr.File) e copia para um diretório temporário.
Retorna (tmpdir, path do .shp principal).
"""
if not files:
raise ValueError("Envie o shapefile (pelo menos o .shp).")
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):
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.set_crs(4326, inplace=True)
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)
return gdf
# -------------------------
# IBGE: municípios do UF (Localidades) + centróides via Malhas (por município) + CACHE (HF CPU basic)
# -------------------------
CACHE_DIR = os.path.join(os.path.dirname(__file__), "cache")
os.makedirs(CACHE_DIR, exist_ok=True)
def cache_path_for_uf(uf_sigla, qualidade):
return os.path.join(CACHE_DIR, f"ibge_centroides_{uf_sigla.upper()}_q{int(qualidade)}.json")
def load_json(path):
if os.path.exists(path):
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
return {}
def save_json_atomic(obj, path):
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(obj, f, ensure_ascii=False, indent=2)
os.replace(tmp, path)
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"])
def ibge_get_municipios_por_uf(uf_id, timeout=60):
url = f"https://servicodados.ibge.gov.br/api/v1/localidades/estados/{int(uf_id)}/municipios"
return requests.get(url, timeout=timeout).json()
def ibge_malha_centroid_por_mun_id(mun_id, qualidade=2, timeout=120, retries=3):
url = (
f"https://servicodados.ibge.gov.br/api/v2/malhas/{int(mun_id)}"
f"?formato=application/vnd.geo+json&qualidade={int(qualidade)}"
)
last = None
for r in range(retries):
try:
gj = requests.get(url, timeout=timeout).json()
feats = gj.get("features", [])
if not feats:
return None
g = shape(feats[0]["geometry"])
c = g.centroid
return float(c.y), float(c.x) # lat, lon
except Exception as e:
last = e
time.sleep(0.4 * (r + 1))
return None
# ✅ CORREÇÃO A: progress_cb aqui
def ibge_municipios_centroides_por_uf(
uf_sigla,
qualidade=2,
timeout=120,
progress_cb=None
):
"""
Retorna: (uf_id, cities_gdf, cities_status_df, cache_path)
"""
uf_sigla = uf_sigla.upper().strip()
uf_id = ibge_get_uf_id_from_sigla(uf_sigla, timeout=60)
municipios = ibge_get_municipios_por_uf(uf_id, timeout=60)
cpath = cache_path_for_uf(uf_sigla, qualidade)
cache = load_json(cpath) # { "mun_id": {"name":..., "lat":..., "lon":...} | null }
rows = []
names_all = []
total = len(municipios)
for idx, m in enumerate(municipios, 1):
mun_id = int(m.get("id"))
name = (m.get("nome") or "").strip()
names_all.append(name)
key = str(mun_id)
if key in cache:
v = cache[key]
if v and "lat" in v and "lon" in v:
rows.append({
"name": v["name"],
"lat": v["lat"],
"lon": v["lon"],
"geometry": Point(v["lon"], v["lat"])
})
else:
latlon = ibge_malha_centroid_por_mun_id(mun_id, qualidade=qualidade, timeout=timeout, retries=3)
if latlon is None:
cache[key] = None
else:
lat, lon = latlon
cache[key] = {"name": name, "lat": lat, "lon": lon}
rows.append({"name": name, "lat": lat, "lon": lon, "geometry": Point(lon, lat)})
# salva a cada 10 (não perder progresso no CPU basic)
if idx % 10 == 0:
save_json_atomic(cache, cpath)
# dá uma folga pro serviço
if idx % 25 == 0:
time.sleep(0.25)
# ✅ progress callback
if progress_cb and (idx % 25 == 0 or idx == total):
progress_cb(idx, total)
save_json_atomic(cache, cpath)
cities_gdf = gpd.GeoDataFrame(rows, crs=4326)\
.dropna(subset=["lat","lon"])\
.drop_duplicates(subset=["name"])\
.reset_index(drop=True)
status = pd.DataFrame({"name": names_all})
status["geocoded"] = status["name"].isin(set(cities_gdf["name"]))
return uf_id, cities_gdf, status, cpath
# -------------------------
# MST eficiente: kNN graph + MST
# -------------------------
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_graph(cities_gdf, k=CITY_KNN_K):
coords = np.vstack([cities_gdf[["lat","lon"]].values])
nn = NearestNeighbors(n_neighbors=min(k+1, len(coords))).fit(coords)
_, idxs = nn.kneighbors(coords)
G = nx.Graph()
for i in range(len(cities_gdf)):
G.add_node(i, name=cities_gdf.iloc[i]["name"])
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)
if not G.has_edge(i, j):
G.add_edge(i, j, weight=w)
return G
def build_city_mst(cities_gdf, k=CITY_KNN_K):
G_knn = build_city_knn_graph(cities_gdf, k=k)
if not nx.is_connected(G_knn):
for kk in [12, 16, 20, 24]:
G_knn = build_city_knn_graph(cities_gdf, k=min(kk, len(cities_gdf)-1))
if nx.is_connected(G_knn):
break
if not nx.is_connected(G_knn):
comps = list(nx.connected_components(G_knn))
for a in range(len(comps)-1):
A = list(comps[a]); B = list(comps[a+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)
_, i, j = best
G_knn.add_edge(i, j, weight=w)
return nx.minimum_spanning_tree(G_knn, weight="weight")
# -------------------------
# 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():
kml = simplekml.Kml()
f_main = kml.newfolder(name="Backbone (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):
ls = folder_main.newlinestring(name=name)
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
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 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):
try:
logs = []
t0 = time.time()
# 0) Upload staging
tmpdir, shp_path = stage_uploaded_files(files)
logs.append(f"📁 Upload staging: {tmpdir}")
logs.append(f"🧷 SHP: {os.path.basename(shp_path)}")
# 1) Postes
logs.append("1) Lendo postes...")
poles = load_poles_shapefile(shp_path)
logs.append(f"✅ Postes carregados: {len(poles):,}")
# 2) IBGE cidades (com cache + progress)
logs.append(f"2) IBGE: municípios de UF={uf} + centróides (cache local)...")
def _pcb(done, total):
logs.append(f" Centröides (IBGE): {done}/{total}")
uf_id, cities_gdf, cities_status, cpath = ibge_municipios_centroides_por_uf(
uf, qualidade=int(qualidade), timeout=120, progress_cb=_pcb
)
logs.append(f"✅ UF id (IBGE): {uf_id}")
logs.append(f"✅ Municípios com centróide: {len(cities_gdf)}")
logs.append(f"🗂️ Cache: {cpath}")
if len(cities_gdf) < 3:
raise RuntimeError("Poucas cidades retornadas pelo IBGE para montar MST.")
# 3) MST
logs.append("3) Construindo MST (kNN)...")
global CITY_KNN_K
CITY_KNN_K = int(k_city_knn)
T = build_city_mst(cities_gdf, k=CITY_KNN_K)
logs.append(f"✅ MST arestas: {T.number_of_edges()}")
# 4) KML + edges
logs.append("4) Gerando KML + CSVs...")
kml, f_main, f_gaps, f_fbk, f_pts = build_kml_structure()
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 = []
for u, v in T.edges():
cu = cities_gdf.iloc[u]
cv = cities_gdf.iloc[v]
edge_name = f"{cu['name']} ↔ {cv['name']}"
logs.append(f"→ {edge_name}")
try:
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, edge_name, coords, segs, resumo)
edges_rows.append({
"city_u": cu["name"], "city_v": cv["name"],
"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": edge_name,
"final_method": resumo["method"],
"error_chain": " | ".join(errs)
})
except Exception as e:
exc_rows.append({
"edge": edge_name,
"final_method": "FAILED",
"error_chain": repr(e)
})
logs.append(f" ⚠️ Falhou: {repr(e)}")
# 5) extras de conectividade
logs.append("5) Garantindo 100% conectividade (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]
edge_name = f"[EXTRA] {cu['name']} ↔ {cv['name']}"
logs.append(f"+ {edge_name} | {resumo['method']}")
add_edge_to_kml(f_main, f_gaps, f_fbk, edge_name, coords, segs, resumo)
edges_rows.append({
"city_u": cu["name"], "city_v": cv["name"],
"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": edge_name,
"final_method": resumo["method"],
"error_chain": " | ".join(errs)
})
df_edges = pd.DataFrame(edges_rows)
df_exc = pd.DataFrame(exc_rows)
# 6) salvar outputs
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 = os.path.join(outdir, "vgo6_cities_status.csv")
cities_status.to_csv(out_cities, 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
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}")
return "\n".join(logs), df_edges, out_kml, out_edges, out_exc, out_cities
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
# -------------------------
import gradio as gr
with gr.Blocks(title="VGO6 — Backbone Fibra 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 o UF\n"
"- O app busca os municípios do UF pelo IBGE e gera o backbone (KML + CSVs)\n"
)
with gr.Row():
files = gr.File(label="Upload shapefile (pode selecionar múltiplos arquivos)", file_count="multiple")
uf = gr.Dropdown(UF_OPTIONS, value="GO", label="UF do shapefile (para buscar cidades 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=200, step=10, label="Vão máximo entre postes (m)")
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")
run_btn.click(
fn=run_vgo6,
inputs=[files, uf, qualidade, k_city_knn, span_threshold_m],
outputs=[logs, df_preview, out_kml, out_edges, out_exc, out_cities],
)
# Gradio 5+ (HF): limite global de concorrência aqui
demo.queue().launch(server_name="0.0.0.0", server_port=7860)