Spaces:
Sleeping
Sleeping
Download app.py from douglasribeiro/redes: direct link, hf CLI and curl.
- Browser
- Download file 17.6 kB
-
https://huggingface.co/spaces/douglasribeiro/redes/resolve/main/app.py
- Command line
-
hf download hf://spaces/douglasribeiro/redes/app.py
-
curl -L -o app.py https://huggingface.co/spaces/douglasribeiro/redes/resolve/main/app.py
17.6 kB
| import os | |
| import shutil | |
| import tempfile | |
| import numpy as np | |
| import gradio as gr | |
| import osmnx as ox | |
| import networkx as nx | |
| import geopandas as gpd | |
| from shapely.geometry import Polygon, LineString, Point | |
| from shapely.ops import linemerge | |
| # ------------------------------ | |
| # PARÂMETROS DO MODELO | |
| # ------------------------------ | |
| BUFFER_METROS = 1000.0 # corredor para capturar postes (m) | |
| PASSO_RODOVIA = 100.0 # amostragem ao longo da rodovia (m) | |
| RAIO_BUSCA_POSTE = 200.0 # raio para buscar poste mais próximo (m) | |
| MAX_DIST_POSTE = 200.0 # limite de distância entre pontos consecutivos (m) | |
| TOL_SMOOTH_METROS = 5.0 # tolerância de suavização Douglas–Peucker (m) | |
| OSM_MARGIN = 0.15 # margem (em graus) para o bbox OSM | |
| # ------------------------------ | |
| # FUNÇÕES AUXILIARES | |
| # ------------------------------ | |
| def utm_sirgas_from_lon(lon: float) -> str: | |
| """Dada uma longitude em graus, retorna o EPSG SIRGAS 2000 UTM Zona Sul.""" | |
| zona = int((lon + 180) // 6) + 1 | |
| epsg = 31960 + zona # zona 22 → 31982, zona 21 → 31981 etc. | |
| return f"EPSG:{epsg}" | |
| def lado_da_linha(pt, ln): | |
| """Sinal do lado do ponto em relação à linha (rodovia).""" | |
| proj = ln.interpolate(ln.project(pt)) | |
| return (pt.x - proj.x) * (pt.y - proj.y) | |
| def validar_vaos_utm(lista_pts, limite, log): | |
| """ | |
| Valida se há vão maior que 'limite' metros entre pontos consecutivos. | |
| lista_pts: lista ordenada de shapely.Point em CRS métrico (UTM). | |
| """ | |
| log("") | |
| log("========== VALIDAÇÃO DOS VÃOS (UTM) ==========") | |
| if len(lista_pts) < 2: | |
| log("⚠️ Menos de 2 pontos. Nada a validar.") | |
| return True | |
| distancias = [] | |
| falhas = [] | |
| for i in range(len(lista_pts) - 1): | |
| d = lista_pts[i].distance(lista_pts[i + 1]) | |
| distancias.append(d) | |
| if d > limite: | |
| falhas.append((i, i + 1, d)) | |
| log(f"Total de vãos analisados: {len(distancias)}") | |
| log(f"Maior vão encontrado: {max(distancias):.2f} m") | |
| if falhas: | |
| log("") | |
| log("❌ ALERTA: Foram encontrados vãos maiores que o limite!") | |
| for i, j, d in falhas: | |
| log(f" - Ponto {i} → Ponto {j} = {d:.2f} m") | |
| log("") | |
| log("❌ Rede NÃO aprovada no critério de 200 m.") | |
| return False | |
| log("") | |
| log("✅ Todos os vãos estão dentro do limite de 200 m.") | |
| return True | |
| # ------------------------------ | |
| # FUNÇÃO PRINCIPAL DO GRADIO | |
| # ------------------------------ | |
| def processar(origem_nome, destino_nome, arquivos): | |
| logs = [] | |
| def log(msg): | |
| logs.append(str(msg)) | |
| print(msg) | |
| # --------------------------------- | |
| # Checagem básica de entradas | |
| # --------------------------------- | |
| if not origem_nome or not destino_nome: | |
| raise gr.Error("Informe os textos de origem e destino (ex.: 'Anápolis, Goiás, Brasil').") | |
| if not arquivos: | |
| raise gr.Error("Envie os arquivos do shapefile de postes (.shp, .dbf, .shx, .prj).") | |
| # --------------------------------- | |
| # Preparar pasta temporária e copiar arquivos | |
| # --------------------------------- | |
| tempdir = tempfile.mkdtemp() | |
| log(f"Pasta temporária: {tempdir}") | |
| # arquivos é uma lista de caminhos (type='filepath') | |
| for src in arquivos: | |
| if src is None: | |
| continue | |
| fname = os.path.basename(src) | |
| dst_path = os.path.join(tempdir, fname) | |
| shutil.copy(src, dst_path) | |
| log(f"Arquivo recebido: {fname}") | |
| shp_files = [f for f in os.listdir(tempdir) if f.lower().endswith(".shp")] | |
| if not shp_files: | |
| raise gr.Error("Nenhum arquivo .shp encontrado. Envie pelo menos o .shp do shapefile de postes.") | |
| postes_path = os.path.join(tempdir, shp_files[0]) | |
| log(f"Shapefile base: {postes_path}") | |
| # --------------------------------- | |
| # Geocodificar origem e destino | |
| # --------------------------------- | |
| log("Geocodificando origem e destino com OSM (Nominatim)...") | |
| try: | |
| orig_lat, orig_lon = ox.geocode(origem_nome) | |
| dest_lat, dest_lon = ox.geocode(destino_nome) | |
| except Exception as e: | |
| raise gr.Error(f"Erro ao geocodificar origem/destino: {e}") | |
| ORIGEM = (orig_lon, orig_lat) | |
| DESTINO = (dest_lon, dest_lat) | |
| log(f"Origem: {origem_nome} → {ORIGEM}") | |
| log(f"Destino: {destino_nome} → {DESTINO}") | |
| lon_med = (ORIGEM[0] + DESTINO[0]) / 2 | |
| UTM_CRS = utm_sirgas_from_lon(lon_med) | |
| log(f"CRS UTM SIRGAS escolhido: {UTM_CRS}") | |
| # --------------------------------- | |
| # Ler shapefile de postes | |
| # --------------------------------- | |
| os.environ["SHAPE_RESTORE_SHX"] = "YES" | |
| log("Lendo shapefile de postes (GeoPandas)...") | |
| gdf_postes = gpd.read_file(postes_path) | |
| if gdf_postes.crs is None: | |
| gdf_postes = gdf_postes.set_crs("EPSG:4326") | |
| else: | |
| gdf_postes = gdf_postes.to_crs("EPSG:4326") | |
| log(f"CRS postes: {gdf_postes.crs}") | |
| log(f"Total de geometrias de postes: {len(gdf_postes)}") | |
| # --------------------------------- | |
| # Baixar rede viária do OSM | |
| # --------------------------------- | |
| o_lon, o_lat = ORIGEM | |
| d_lon, d_lat = DESTINO | |
| north = max(o_lat, d_lat) + OSM_MARGIN | |
| south = min(o_lat, d_lat) - OSM_MARGIN | |
| east = max(o_lon, d_lon) + OSM_MARGIN | |
| west = min(o_lon, d_lon) - OSM_MARGIN | |
| bbox_polygon = Polygon([ | |
| (west, south), | |
| (east, south), | |
| (east, north), | |
| (west, north), | |
| (west, south) | |
| ]) | |
| log("Baixando rede viária OSM (network_type='drive', simplify=False)...") | |
| try: | |
| G = ox.graph_from_polygon( | |
| polygon=bbox_polygon, | |
| network_type="drive", | |
| simplify=False | |
| ) | |
| except Exception as e: | |
| raise gr.Error(f"Erro ao baixar rede OSM: {e}") | |
| if len(G.nodes()) == 0: | |
| raise gr.Error("Grafo OSM vazio na área especificada. Verifique os nomes das cidades ou aumente a margem.") | |
| log(f"Nós na rede viária: {len(G.nodes())}") | |
| log(f"Arestas na rede viária: {len(G.edges())}") | |
| # Garantir 'length' nas arestas | |
| log("Verificando/completando atributo 'length' nas arestas...") | |
| try: | |
| first_edge_data = next(iter(G.edges(data=True)))[-1] | |
| has_length = "length" in first_edge_data.keys() | |
| except StopIteration: | |
| raise gr.Error("Nenhuma aresta encontrada no grafo OSM.") | |
| if not has_length: | |
| log("→ 'length' não encontrado. Calculando comprimentos...") | |
| G = ox.distance.add_edge_lengths(G) | |
| else: | |
| log("→ 'length' já existe nas arestas.") | |
| # --------------------------------- | |
| # Menor caminho viário | |
| # --------------------------------- | |
| log("Encontrando nós mais próximos de origem e destino na rede viária...") | |
| try: | |
| start_node = ox.nearest_nodes(G, X=o_lon, Y=o_lat) | |
| end_node = ox.nearest_nodes(G, X=d_lon, Y=d_lat) | |
| except ImportError: | |
| raise gr.Error( | |
| "scikit-learn não está instalado. Inclua 'scikit-learn' no requirements.txt do Space." | |
| ) | |
| except Exception as e: | |
| raise gr.Error(f"Erro ao buscar nós mais próximos: {e}") | |
| log(f"Nó inicial (origem): {start_node}") | |
| log(f"Nó final (destino): {end_node}") | |
| if not nx.has_path(G, start_node, end_node): | |
| raise gr.Error("Não há caminho viário entre origem e destino na malha do OSM.") | |
| log("Calculando menor caminho viário (peso = 'length')...") | |
| route_nodes = nx.shortest_path(G, source=start_node, target=end_node, weight="length") | |
| log(f"Número de nós no caminho viário: {len(route_nodes)}") | |
| # --------------------------------- | |
| # Construir geometria robusta da rota | |
| # --------------------------------- | |
| log("Construindo geometria da rota a partir das arestas...") | |
| segmentos = [] | |
| for u, v in zip(route_nodes[:-1], route_nodes[1:]): | |
| edge_dict = G.get_edge_data(u, v) | |
| edge_data = min(edge_dict.values(), key=lambda d: d.get("length", 9e12)) | |
| if "geometry" in edge_data: | |
| geom = edge_data["geometry"] | |
| if not geom.is_empty and geom.length > 0: | |
| segmentos.append(geom) | |
| else: | |
| x1, y1 = G.nodes[u]["x"], G.nodes[u]["y"] | |
| x2, y2 = G.nodes[v]["x"], G.nodes[v]["y"] | |
| if (x1, y1) != (x2, y2): | |
| segmentos.append(LineString([(x1, y1), (x2, y2)])) | |
| if not segmentos: | |
| raise gr.Error("Não foi possível construir segmentos de rota válidos.") | |
| rota_line = linemerge(segmentos) | |
| if rota_line.is_empty: | |
| raise gr.Error("A geometria final da rota ficou vazia.") | |
| log(f"Geometria final da rota OK. Nº de vértices: {len(rota_line.coords)}") | |
| # --------------------------------- | |
| # Gerar KML da rota viária (referência) | |
| # --------------------------------- | |
| rota_kml_path = os.path.join(tempdir, "rota_viaria.kml") | |
| log(f"Gerando KML da rota viária: {rota_kml_path}") | |
| kml_lines_rota = [ | |
| '<?xml version="1.0" encoding="UTF-8"?>', | |
| '<kml xmlns="http://www.opengis.net/kml/2.2">', | |
| '<Document>', | |
| f' <name>Rota Viária {origem_nome} → {destino_nome}</name>', | |
| ' <Placemark>', | |
| ' <Style>', | |
| ' <LineStyle><color>ff0000ff</color><width>3</width></LineStyle>', | |
| ' </Style>', | |
| ' <LineString>', | |
| ' <tessellate>1</tessellate>', | |
| ' <coordinates>' | |
| ] | |
| for x, y in rota_line.coords: | |
| kml_lines_rota.append(f" {x:.8f},{y:.8f},0") | |
| kml_lines_rota += [ | |
| ' </coordinates>', | |
| ' </LineString>', | |
| ' </Placemark>', | |
| '</Document>', | |
| '</kml>' | |
| ] | |
| with open(rota_kml_path, "w", encoding="utf-8") as f: | |
| f.write("\n".join(kml_lines_rota)) | |
| # --------------------------------- | |
| # Projetar para UTM e criar corredor | |
| # --------------------------------- | |
| log(f"Projetando rota e postes para {UTM_CRS} e aplicando buffer de {BUFFER_METROS} m...") | |
| gdf_rota = gpd.GeoDataFrame({"id": [0]}, geometry=[rota_line], crs="EPSG:4326") | |
| gdf_rota_utm = gdf_rota.to_crs(UTM_CRS) | |
| gdf_postes_utm = gdf_postes.to_crs(UTM_CRS) | |
| rota_utm = gdf_rota_utm.geometry.iloc[0] | |
| rota_buffer = rota_utm.buffer(BUFFER_METROS) | |
| mask_corredor = gdf_postes_utm.geometry.within(rota_buffer) | |
| gdf_postes_corredor_utm = gdf_postes_utm[mask_corredor].copy() | |
| log(f"Postes dentro do corredor de {BUFFER_METROS} m: {len(gdf_postes_corredor_utm)}") | |
| if len(gdf_postes_corredor_utm) == 0: | |
| raise gr.Error("Nenhum poste encontrado dentro do corredor. Aumente BUFFER_METROS ou verifique o shapefile.") | |
| # --------------------------------- | |
| # KML dos postes no corredor | |
| # --------------------------------- | |
| postes_kml_path = os.path.join(tempdir, "postes_corredor.kml") | |
| log(f"Gerando KML dos postes no corredor: {postes_kml_path}") | |
| gdf_postes_corredor_ll = gdf_postes_corredor_utm.to_crs("EPSG:4326") | |
| kml_postes_points = [ | |
| '<?xml version="1.0" encoding="UTF-8"?>', | |
| '<kml xmlns="http://www.opengis.net/kml/2.2">', | |
| '<Document>', | |
| ' <name>Postes no Corredor do Enlace</name>', | |
| ] | |
| for idx, row in gdf_postes_corredor_ll.iterrows(): | |
| x = row.geometry.x | |
| y = row.geometry.y | |
| kml_postes_points += [ | |
| ' <Placemark>', | |
| f' <name>Poste {idx}</name>', | |
| ' <Point>', | |
| f' <coordinates>{x:.8f},{y:.8f},0</coordinates>', | |
| ' </Point>', | |
| ' </Placemark>' | |
| ] | |
| kml_postes_points += [ | |
| '</Document>', | |
| '</kml>' | |
| ] | |
| with open(postes_kml_path, "w", encoding="utf-8") as f: | |
| f.write("\n".join(kml_postes_points)) | |
| # --------------------------------- | |
| # MODELO HÍBRIDO: RODOVIA + POSTES (GARANTIA ≤ 200 m) | |
| # --------------------------------- | |
| log("Construindo enlace híbrido (rodovia + postes) com garantia de vãos ≤ 200 m...") | |
| gdf_postes_corredor_utm["proj"] = gdf_postes_corredor_utm.geometry.apply( | |
| lambda p: rota_utm.project(p) | |
| ) | |
| gdf_postes_corredor_utm["lado"] = gdf_postes_corredor_utm.geometry.apply( | |
| lambda p: lado_da_linha(p, rota_utm) | |
| ) | |
| lado_medio = gdf_postes_corredor_utm.sort_values("proj").head(50)["lado"].mean() | |
| lado_final = 1 if lado_medio >= 0 else -1 | |
| gdf_postes_lado = gdf_postes_corredor_utm[ | |
| (gdf_postes_corredor_utm["lado"] * lado_final) > 0 | |
| ].copy() | |
| log(f"Postes mantidos no lado escolhido da rodovia: {len(gdf_postes_lado)}") | |
| if len(gdf_postes_lado) < 2: | |
| raise gr.Error("Poucos postes no lado escolhido da rodovia. Ajuste o buffer ou verifique o shapefile.") | |
| dist_total = rota_utm.length | |
| amostras = np.arange(0, dist_total, PASSO_RODOVIA) | |
| pontos_enlace_utm = [] | |
| for d in amostras: | |
| pt_rodovia = rota_utm.interpolate(d) | |
| subset = gdf_postes_lado[ | |
| gdf_postes_lado.geometry.distance(pt_rodovia) <= RAIO_BUSCA_POSTE | |
| ] | |
| if len(subset): | |
| distancias = subset.geometry.distance(pt_rodovia) | |
| melhor_idx = distancias.idxmin() | |
| melhor_geom = subset.loc[melhor_idx].geometry | |
| pontos_enlace_utm.append(melhor_geom) | |
| else: | |
| # fallback: usa ponto na própria rodovia | |
| pontos_enlace_utm.append(pt_rodovia) | |
| if len(pontos_enlace_utm) < 2: | |
| raise gr.Error("Foram gerados poucos pontos para o enlace. Ajuste parâmetros.") | |
| # Densificação para garantir vãos ≤ MAX_DIST_POSTE | |
| log("Densificando o enlace para garantir vãos ≤ 200 m...") | |
| corrigidos_utm = [] | |
| prev = None | |
| for p in pontos_enlace_utm: | |
| if prev is None: | |
| corrigidos_utm.append(p) | |
| prev = p | |
| continue | |
| dist = prev.distance(p) | |
| if dist > MAX_DIST_POSTE: | |
| n = int(dist // MAX_DIST_POSTE) | |
| for i in range(1, n + 1): | |
| frac = i / (n + 1) | |
| inter = Point( | |
| prev.x + frac * (p.x - prev.x), | |
| prev.y + frac * (p.y - prev.y) | |
| ) | |
| corrigidos_utm.append(inter) | |
| corrigidos_utm.append(p) | |
| prev = p | |
| # Validação final dos vãos | |
| ok_vaos = validar_vaos_utm(corrigidos_utm, limite=MAX_DIST_POSTE, log=log) | |
| if not ok_vaos: | |
| log("⚠️ Mesmo assim, o enlace será exportado para inspeção visual no KML.") | |
| # --------------------------------- | |
| # Converter para WGS84, suavizar e gerar KML final | |
| # --------------------------------- | |
| log("Convertendo pontos do enlace para WGS84, suavizando e gerando KML final...") | |
| gdf_enlace_utm = gpd.GeoDataFrame(geometry=corrigidos_utm, crs=UTM_CRS) | |
| gdf_enlace_ll = gdf_enlace_utm.to_crs("EPSG:4326") | |
| linha_bruta = LineString([(p.x, p.y) for p in gdf_enlace_ll.geometry]) | |
| tol_graus = TOL_SMOOTH_METROS / 111320.0 | |
| linha_suave = linha_bruta.simplify(tol_graus, preserve_topology=False) | |
| enlace_kml_path = os.path.join(tempdir, "enlace_otimizado_v4.kml") | |
| log(f"Gerando KML do enlace final: {enlace_kml_path}") | |
| kml_suave = [ | |
| '<?xml version="1.0" encoding="UTF-8"?>', | |
| '<kml xmlns="http://www.opengis.net/kml/2.2">', | |
| '<Document><name>Enlace Fibra Otimizado (Híbrido v4)</name>', | |
| '<Placemark>', | |
| '<Style><LineStyle><color>ff00ff00</color><width>4</width></LineStyle></Style>', | |
| '<LineString><tessellate>1</tessellate><coordinates>' | |
| ] | |
| for x, y in linha_suave.coords: | |
| kml_suave.append(f"{x:.8f},{y:.8f},0") | |
| kml_suave += [ | |
| '</coordinates></LineString>', | |
| '</Placemark></Document></kml>' | |
| ] | |
| with open(enlace_kml_path, "w", encoding="utf-8") as f: | |
| f.write("\n".join(kml_suave)) | |
| log("") | |
| log("🎯 ARQUIVOS GERADOS:") | |
| log(f" 1) {rota_kml_path} (rota viária, vermelho)") | |
| log(f" 2) {postes_kml_path} (postes do corredor)") | |
| log(f" 3) {enlace_kml_path} (enlace de fibra final, verde)") | |
| # Retorna 3 arquivos + log | |
| return rota_kml_path, postes_kml_path, enlace_kml_path, "\n".join(logs) | |
| # ------------------------------ | |
| # INTERFACE GRADIO | |
| # ------------------------------ | |
| with gr.Blocks(title="Enlace Óptico – Híbrido OSM + Postes") as demo: | |
| gr.Markdown("# Enlace Óptico Automatizado (OSM + Shapefile de Postes)") | |
| gr.Markdown( | |
| "1. Informe **origem** e **destino** em texto livre (ex.: `Anápolis, Goiás, Brasil`). \n" | |
| "2. Envie TODOS os arquivos do shapefile de postes (`.shp`, `.dbf`, `.shx`, `.prj`). \n" | |
| "3. Clique em **Gerar Enlace** para baixar os KMLs." | |
| ) | |
| with gr.Row(): | |
| origem = gr.Textbox(label="Origem", value="Anápolis, Goiás, Brasil") | |
| destino = gr.Textbox(label="Destino", value="Alexânia, Goiás, Brasil") | |
| arquivos = gr.File( | |
| label="Arquivos do Shapefile de Postes (.shp + .dbf + .shx + .prj)", | |
| file_count="multiple", | |
| type="filepath", | |
| ) | |
| botao = gr.Button("Gerar Enlace") | |
| with gr.Row(): | |
| rota_out = gr.File(label="KML – Rota Viária (referência)") | |
| postes_out = gr.File(label="KML – Postes no Corredor") | |
| enlace_out = gr.File(label="KML – Enlace Final Otimizado") | |
| log_box = gr.Textbox( | |
| label="Logs do processamento", | |
| lines=20, | |
| interactive=False | |
| ) | |
| botao.click( | |
| fn=processar, | |
| inputs=[origem, destino, arquivos], | |
| outputs=[rota_out, postes_out, enlace_out, log_box], | |
| ) | |
| demo.launch() | |