Spaces:
Sleeping
Sleeping
Download app.py from douglasribeiro/vaos: direct link, hf CLI and curl.
- Browser
- Download file 5.27 kB
-
https://huggingface.co/spaces/douglasribeiro/vaos/resolve/main/app.py
- Command line
-
hf download hf://spaces/douglasribeiro/vaos/app.py
-
curl -L -o app.py https://huggingface.co/spaces/douglasribeiro/vaos/resolve/main/app.py
5.27 kB
| import gradio as gr | |
| from lxml import etree | |
| from shapely.geometry import LineString, Point | |
| from shapely.ops import substring | |
| from pyproj import Transformer | |
| from pathlib import Path | |
| import tempfile | |
| import math | |
| # --------------------------------------------------------- | |
| # Leitura do KML | |
| # --------------------------------------------------------- | |
| def ler_tracado_e_pontos(kml_file): | |
| tree = etree.parse(kml_file) | |
| ns = {"kml": "http://www.opengis.net/kml/2.2"} | |
| # LineString (traçado) | |
| coords_text = tree.find(".//kml:LineString/kml:coordinates", ns) | |
| if coords_text is None: | |
| raise ValueError("KML não contém LineString.") | |
| coords = [] | |
| for c in coords_text.text.strip().split(): | |
| lon, lat, *_ = map(float, c.split(",")) | |
| coords.append((lon, lat)) | |
| linha = LineString(coords) | |
| # Points (se existirem) | |
| pontos = [] | |
| for pm in tree.findall(".//kml:Placemark", ns): | |
| coord = pm.find(".//kml:Point/kml:coordinates", ns) | |
| if coord is not None: | |
| lon, lat, *_ = map(float, coord.text.strip().split(",")) | |
| pontos.append(Point(lon, lat)) | |
| return linha, pontos | |
| # --------------------------------------------------------- | |
| # Processamento principal | |
| # --------------------------------------------------------- | |
| def processar(cidade_origem, cidade_destino, kml_file, limite): | |
| try: | |
| linha, pontos = ler_tracado_e_pontos(kml_file) | |
| except Exception as e: | |
| return f"❌ Erro ao ler KML: {e}", None | |
| # CRS | |
| transformer = Transformer.from_crs("EPSG:4326", "EPSG:32722", always_xy=True) | |
| inv = Transformer.from_crs("EPSG:32722", "EPSG:4326", always_xy=True) | |
| linha_m = LineString([transformer.transform(x, y) for x, y in linha.coords]) | |
| referencias = [] | |
| # Se houver pontos no KML, usa-os | |
| if pontos: | |
| for p in pontos: | |
| p_m = Point(transformer.transform(p.x, p.y)) | |
| referencias.append(linha_m.project(p_m)) | |
| else: | |
| # fallback: usa vértices do traçado | |
| dist = 0.0 | |
| referencias.append(0.0) | |
| for i in range(1, len(linha_m.coords)): | |
| p1 = Point(linha_m.coords[i - 1]) | |
| p2 = Point(linha_m.coords[i]) | |
| dist += p1.distance(p2) | |
| referencias.append(dist) | |
| referencias = sorted(set(referencias)) | |
| trechos = [] | |
| for i in range(len(referencias) - 1): | |
| s1 = referencias[i] | |
| s2 = referencias[i + 1] | |
| dist = abs(s2 - s1) | |
| if dist <= limite or dist < 1: | |
| continue | |
| trecho = substring(linha_m, min(s1, s2), max(s1, s2)) | |
| if trecho.is_empty or trecho.length < 1: | |
| continue | |
| trechos.append((trecho, dist)) | |
| if not trechos: | |
| return "✅ Nenhum vão acima do limite foi encontrado.", None | |
| # --------------------------------------------------------- | |
| # Gerar KML | |
| # --------------------------------------------------------- | |
| kml = etree.Element("kml", xmlns="http://www.opengis.net/kml/2.2") | |
| doc = etree.SubElement(kml, "Document") | |
| style = etree.SubElement(doc, "Style", id="vaoStyle") | |
| line_style = etree.SubElement(style, "LineStyle") | |
| etree.SubElement(line_style, "color").text = "ff0000ff" | |
| etree.SubElement(line_style, "width").text = "4" | |
| resultados = [] | |
| for idx, (trecho, dist) in enumerate(trechos, start=1): | |
| dist_int = math.ceil(dist) | |
| pm = etree.SubElement(doc, "Placemark") | |
| etree.SubElement(pm, "styleUrl").text = "#vaoStyle" | |
| # Nome estético pedido | |
| name = etree.SubElement(pm, "name") | |
| name.text = f"Vão {idx}: {dist_int}" | |
| # Atributos | |
| ext = etree.SubElement(pm, "ExtendedData") | |
| def add_data(nome, valor): | |
| d = etree.SubElement(ext, "Data", name=nome) | |
| etree.SubElement(d, "value").text = str(valor) | |
| add_data("nome_vao", f"{cidade_origem} X {cidade_destino}") | |
| add_data("distancia_m", dist_int) | |
| ls = etree.SubElement(pm, "LineString") | |
| coords = etree.SubElement(ls, "coordinates") | |
| coords.text = " ".join( | |
| f"{inv.transform(x, y)[0]},{inv.transform(x, y)[1]},0" | |
| for x, y in trecho.coords | |
| ) | |
| resultados.append(f"Vão {idx}: {dist_int} m") | |
| tmp = Path(tempfile.mkstemp(suffix=".kml")[1]) | |
| tmp.write_bytes( | |
| etree.tostring(kml, pretty_print=True, xml_declaration=True, encoding="UTF-8") | |
| ) | |
| return "\n".join(resultados), str(tmp) | |
| # --------------------------------------------------------- | |
| # Interface Gradio | |
| # --------------------------------------------------------- | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## 📏 Vãos > Limite seguindo o traçado do KML (V1.1.2)") | |
| cidade_origem = gr.Textbox(label="Cidade origem") | |
| cidade_destino = gr.Textbox(label="Cidade destino") | |
| kml_file = gr.File(label="KML do traçado (LineString)") | |
| limite = gr.Number(value=200, label="Limite do vão (m)") | |
| out_text = gr.Textbox(lines=8, label="Resultado") | |
| out_file = gr.File(label="KML gerado") | |
| gr.Button("Processar").click( | |
| processar, | |
| inputs=[cidade_origem, cidade_destino, kml_file, limite], | |
| outputs=[out_text, out_file] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |