Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251import osimport tempfileimport zipfileimport numpy as npimport gradio as grimport osmnx as oximport networkx as nximport geopandas as gpdfrom shapely.geometry import Polygon, LineString, Pointfrom shapely.ops import linemergefrom pyproj import CRS
# ------------------------------# PARÂMETROS DO MODELO# ------------------------------BUFFER_METROS = 1000PASSO_RODOVIA = 100RAIO_BUSCA_POSTE = 200MAX_DIST_POSTE = 200TOL_SMOOTH_METROS = 5OSM_MARGIN = 0.15
# ------------------------------# FUNÇÕES AUXILIARES# ------------------------------
def utm_sirgas_from_lon(lon): zona = int((lon + 180) // 6) + 1 epsg = 31960 + zona return f"EPSG:{epsg}"
def lado_da_linha(pt, ln): proj = ln.interpolate(ln.project(pt)) return (pt.x - proj.x) * (pt.y - proj.y)
# ------------------------------# FUNÇÃO PRINCIPAL (GERA KMZ)# ------------------------------
def processar(origem_nome, destino_nome, archivos):
# ------------------------------ # 1. Ler arquivos enviados # ------------------------------
tempdir = tempfile.mkdtemp()
for fname, fileobj in archivos.items(): with open(os.path.join(tempdir, fname), "wb") as f: f.write(fileobj.read())
shp_files = [f for f in os.listdir(tempdir) if f.lower().endswith(".shp")] if not shp_files: return "❌ Nenhum arquivo .shp encontrado."
postes_path = os.path.join(tempdir, shp_files[0])
# ------------------------------ # 2. Geocodificar # ------------------------------
try: o_lat, o_lon = ox.geocode(origem_nome) d_lat, d_lon = ox.geocode(destino_nome) except Exception as e: return f"❌ Erro na geocodificação: {e}"
ORIGEM = (o_lon, o_lat) DESTINO = (d_lon, d_lat)
utm_crs = utm_sirgas_from_lon((ORIGEM[0] + DESTINO[0]) / 2)
# ------------------------------ # 3. Ler postes # ------------------------------
os.environ["SHAPE_RESTORE_SHX"] = "YES" 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")
# ------------------------------ # 4. Baixar rede via 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) ])
try: G = ox.graph_from_polygon(bbox_polygon, network_type="drive", simplify=False) except Exception as e: return f"❌ Erro no download OSM: {e}"
# Garantir comprimento first_edge = next(iter(G.edges(data=True)))[-1] if "length" not in first_edge: G = ox.distance.add_edge_lengths(G)
# ------------------------------ # 5. Menor caminho na rodovia # ------------------------------
start_node = ox.nearest_nodes(G, X=o_lon, Y=o_lat) end_node = ox.nearest_nodes(G, X=d_lon, Y=d_lat)
if not nx.has_path(G, start_node, end_node): return "❌ Não há caminho viário entre origem e destino."
route_nodes = nx.shortest_path(G, start_node, end_node, weight="length")
# Construir geometria segmentos = [] for u, v in zip(route_nodes[:-1], route_nodes[1:]): d = G.get_edge_data(u, v) edge = min(d.values(), key=lambda d: d.get("length", 999999)) if "geometry" in edge: segmentos.append(edge["geometry"]) else: x1, y1 = G.nodes[u]["x"], G.nodes[u]["y"] x2, y2 = G.nodes[v]["x"], G.nodes[v]["y"] segmentos.append(LineString([(x1, y1), (x2, y2)]))
rota_line = linemerge(segmentos)
# ------------------------------ # 6. Postes no corredor da rodovia # ------------------------------
gdf_rota = gpd.GeoDataFrame(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] buffer_area = rota_utm.buffer(BUFFER_METROS)
gdf_postes_corredor = gdf_postes_utm[ gdf_postes_utm.geometry.within(buffer_area) ]
# ------------------------------ # 7. Lógica híbrida (modelo C) # ------------------------------
# Projetar postes na linha gdf_postes_corredor["proj"] = gdf_postes_corredor.geometry.apply( lambda p: rota_utm.project(p) ) gdf_postes_corredor["lado"] = gdf_postes_corredor.geometry.apply( lambda p: lado_da_linha(p, rota_utm) )
# Escolher lado dominante lado_med = gdf_postes_corredor.sort_values("proj").head(50)["lado"].mean() lado_final = 1 if lado_med >= 0 else -1
gdf_postes_lado = gdf_postes_corredor[ (gdf_postes_corredor["lado"] * lado_final) > 0 ]
# Amostragem da rodovia dist_total = rota_utm.length amostras = np.arange(0, dist_total, PASSO_RODOVIA)
pontos_enlace = [] for d in amostras: p = rota_utm.interpolate(d) subset = gdf_postes_lado[ gdf_postes_lado.geometry.distance(p) <= RAIO_BUSCA_POSTE ] if len(subset): melhor = subset.geometry.distance(p).idxmin() pontos_enlace.append(subset.loc[melhor].geometry) else: pontos_enlace.append(p)
# Filtrar saltos grandes filtrados = [] prev = None for p in pontos_enlace: if prev is None or p.distance(prev) <= MAX_DIST_POSTE: filtrados.append(p) prev = p else: filtrados.append(p) prev = p
# Converter para WGS84 gdf_temp = gpd.GeoDataFrame(geometry=filtrados, crs=utm_crs).to_crs("EPSG:4326") linha_bruta = LineString([(p.x, p.y) for p in gdf_temp.geometry])
# Suavização Douglas–Peucker tol_graus = TOL_SMOOTH_METROS / 111320 linha_final = linha_bruta.simplify(tol_graus)
# ------------------------------ # 8. Exportar KML final # ------------------------------
outfile = os.path.join(tempdir, "enlace_otimizado.kml") with open(outfile, "w") as f: f.write( "<kml><Document><Placemark>" "<Style><LineStyle><color>ff00ff00</color><width>4</width></LineStyle></Style>" "<LineString><coordinates>" ) for x, y in linha_final.coords: f.write(f"{x},{y},0 ")
f.write("</coordinates></LineString></Placemark></Document></kml>")
return outfile
# ------------------------------# INTERFACE GRADIO# ------------------------------
with gr.Blocks(title="Enlace Óptico Automatizado") as demo:
gr.Markdown("# 🔌 Enlace Óptico Automatizado (OSM + Shapefile)") gr.Markdown("Faça upload do shapefile de postes (.shp + .dbf + .shx + .prj)")
origem = gr.Textbox(label="Cidade de Origem", value="Anápolis, Goiás, Brasil") destino = gr.Textbox(label="Cidade de Destino", value="Alexânia, Goiás, Brasil")
arquivos = gr.File( label="Arquivos do Shapefile (envie vários ao mesmo tempo)", file_count="multiple" )
btn = gr.Button("Gerar Enlace")
saida = gr.File(label="Download do KML final")
btn.click(fn=processar, inputs=[origem, destino, arquivos], outputs=saida)
demo.launch()app.pyAdded+251