Spaces:
Running on Zero
Running on Zero
Download app.py from bunker-core/visioncar: direct link, hf CLI and curl.
- Browser
- Download file 8.52 kB
-
https://huggingface.co/spaces/bunker-core/visioncar/resolve/main/app.py
- Command line
-
hf download hf://spaces/bunker-core/visioncar/app.py
-
curl -L -o app.py https://huggingface.co/spaces/bunker-core/visioncar/resolve/main/app.py
8.52 kB
| import warnings | |
| warnings.filterwarnings("ignore") | |
| import csv | |
| import json | |
| import tempfile | |
| import xml.etree.ElementTree as ET | |
| import numpy as np | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import gradio as gr | |
| import spaces | |
| import pystac_client | |
| import planetary_computer | |
| import rasterio | |
| from rasterio.mask import mask | |
| from shapely.geometry import Polygon, MultiPoint, shape | |
| from shapely.ops import transform | |
| import pyproj | |
| POLIGONO_EXEMPLO = Polygon([ | |
| (-52.9895, -17.2225), | |
| (-52.9715, -17.2205), | |
| (-52.9685, -17.2345), | |
| (-52.9765, -17.2415), | |
| (-52.9915, -17.2365), | |
| (-52.9895, -17.2225) | |
| ]) | |
| def ler_poligono_arquivo(arquivo): | |
| if arquivo is None: | |
| return POLIGONO_EXEMPLO, "Polígono de Exemplo" | |
| caminho = arquivo.name | |
| if caminho.lower().endswith((".geojson", ".json")): | |
| with open(caminho, "r", encoding="utf-8") as f: | |
| data = json.load(f) | |
| if data.get("type") == "FeatureCollection": | |
| geom = shape(data["features"][0]["geometry"]) | |
| elif data.get("type") == "Feature": | |
| geom = shape(data["geometry"]) | |
| else: | |
| geom = shape(data) | |
| return geom, f"GeoJSON ({caminho.split('/')[-1]})" | |
| elif caminho.lower().endswith(".kml"): | |
| tree = ET.parse(caminho) | |
| root = tree.getroot() | |
| pontos_soltos = [] | |
| for elem in root.iter(): | |
| if elem.tag.endswith("coordinates") and elem.text: | |
| coords = [] | |
| for pt in elem.text.strip().split(): | |
| partes = pt.split(",") | |
| if len(partes) >= 2: | |
| coords.append((float(partes[0]), float(partes[1]))) | |
| if len(coords) >= 3: | |
| return Polygon(coords), f"KML ({caminho.split('/')[-1]})" | |
| pontos_soltos.extend(coords) | |
| if len(pontos_soltos) >= 3: | |
| return MultiPoint(pontos_soltos).convex_hull, f"KML via Pontos ({caminho.split('/')[-1]})" | |
| raise ValueError("O KML precisa de um polígono fechado ou pelo menos 3 pontos.") | |
| raise ValueError("Formato não suportado. Envie um arquivo .geojson ou .kml.") | |
| def auditar_imovel(arquivo, ano, max_nuvens): | |
| try: | |
| poligono_wgs84, origem = ler_poligono_arquivo(arquivo) | |
| bbox = list(poligono_wgs84.bounds) | |
| catalog = pystac_client.Client.open( | |
| "https://planetarycomputer.microsoft.com/api/stac/v1", | |
| modifier=planetary_computer.sign_inplace, | |
| ) | |
| def obter_ndvi(periodo, limite_nuvens): | |
| search = catalog.search( | |
| collections=["sentinel-2-l2a"], | |
| bbox=bbox, | |
| datetime=periodo, | |
| query={"eo:cloud_cover": {"lt": limite_nuvens}}, | |
| ) | |
| items = list(search.items()) | |
| if not items: | |
| raise ValueError(f"Nenhuma imagem limpa em {periodo}. Aumente o limite de nuvens.") | |
| item = min(items, key=lambda x: x.properties["eo:cloud_cover"]) | |
| data_str = item.datetime.strftime("%d/%m/%Y") | |
| def ler_banda(asset_key): | |
| with rasterio.open(item.assets[asset_key].href) as src: | |
| project = pyproj.Transformer.from_crs("EPSG:4326", src.crs, always_xy=True).transform | |
| geom_proj = transform(project, poligono_wgs84) | |
| out_img, _ = mask(src, [geom_proj], crop=True, filled=True, nodata=0) | |
| banda = out_img[0].astype(float) | |
| banda[banda == 0] = np.nan | |
| return np.clip(banda - 1000.0, 0, None) | |
| red = ler_banda("B04") | |
| nir = ler_banda("B08") | |
| ndvi = (nir - red) / (nir + red + 1e-5) | |
| return data_str, ndvi | |
| data_chuva, ndvi_chuva = obter_ndvi(f"{ano}-01-01/{ano}-04-30", max(max_nuvens, 25)) | |
| data_seca, ndvi_seca = obter_ndvi(f"{ano}-07-01/{ano}-09-30", max_nuvens) | |
| h = min(ndvi_chuva.shape[0], ndvi_seca.shape[0]) | |
| w = min(ndvi_chuva.shape[1], ndvi_seca.shape[1]) | |
| ndvi_chuva = ndvi_chuva[:h, :w] | |
| ndvi_seca = ndvi_seca[:h, :w] | |
| dentro_imovel = (~np.isnan(ndvi_chuva)) & (~np.isnan(ndvi_seca)) | |
| mata_nativa = dentro_imovel & (ndvi_seca > 0.55) & (ndvi_chuva > 0.65) | |
| lavoura_pasto = dentro_imovel & (~mata_nativa) & ((ndvi_chuva > 0.45) | (ndvi_seca > 0.30)) | |
| solo_exposto = dentro_imovel & (~mata_nativa) & (~lavoura_pasto) | |
| ha_pixel = 0.01 | |
| area_total = np.sum(dentro_imovel) * ha_pixel | |
| ha_mata = np.sum(mata_nativa) * ha_pixel | |
| ha_lavoura = np.sum(lavoura_pasto) * ha_pixel | |
| ha_solo = np.sum(solo_exposto) * ha_pixel | |
| pct_mata = (ha_mata / area_total) * 100 | |
| pct_lavoura = (ha_lavoura / area_total) * 100 | |
| pct_solo = (ha_solo / area_total) * 100 | |
| # Gera CSV para download | |
| tmp_csv = tempfile.NamedTemporaryFile(delete=False, suffix=".csv", prefix="visioncar_") | |
| with open(tmp_csv.name, "w", newline="", encoding="utf-8") as f: | |
| writer = csv.writer(f) | |
| writer.writerow(["Origem", "Cena_Aguas", "Cena_Seca", "Classe", "Area_ha", "Percentual"]) | |
| writer.writerow([origem, data_chuva, data_seca, "Mata Nativa / Permanente", f"{ha_mata:.2f}", f"{pct_mata:.1f}%"]) | |
| writer.writerow([origem, data_chuva, data_seca, "Lavoura / Pastagem Sazonal", f"{ha_lavoura:.2f}", f"{pct_lavoura:.1f}%"]) | |
| writer.writerow([origem, data_chuva, data_seca, "Solo Exposto / Estradas", f"{ha_solo:.2f}", f"{pct_solo:.1f}%"]) | |
| writer.writerow([origem, data_chuva, data_seca, "TOTAL", f"{area_total:.2f}", "100.0%"]) | |
| mapa_class = np.ones((h, w, 3)) | |
| mapa_class[mata_nativa] = [0.0, 0.40, 0.0] | |
| mapa_class[lavoura_pasto] = [0.65, 0.85, 0.20] | |
| mapa_class[solo_exposto] = [0.65, 0.45, 0.25] | |
| fig, axes = plt.subplots(1, 3, figsize=(16, 5)) | |
| axes[0].imshow(ndvi_chuva, cmap="RdYlGn", vmin=0.0, vmax=0.9) | |
| axes[0].set_title(f"NDVI Águas ({data_chuva})") | |
| axes[0].axis("off") | |
| axes[1].imshow(ndvi_seca, cmap="RdYlGn", vmin=0.0, vmax=0.9) | |
| axes[1].set_title(f"NDVI Seca ({data_seca})") | |
| axes[1].axis("off") | |
| axes[2].imshow(mapa_class) | |
| axes[2].set_title(f"Classificação CAR ({area_total:.1f} ha)") | |
| axes[2].axis("off") | |
| plt.tight_layout() | |
| relatorio = f"""### 📋 Relatório de Auditoria Multi-temporal CAR | |
| **Origem:** {origem} | |
| **Cenas Sentinel-2:** Águas (`{data_chuva}`) × Seca (`{data_seca}`) | |
| **Área Total Auditada:** `{area_total:.1f} ha` | |
| | Classe de Uso do Solo | Área (ha) | Percentual (%) | | |
| | :--- | :---: | :---: | | |
| | 🌲 **Mata Nativa / Vegetação Permanente** | {ha_mata:.1f} ha | **{pct_mata:.1f}%** | | |
| | 🌱 **Lavoura / Pastagem Sazonal** | {ha_lavoura:.1f} ha | **{pct_lavoura:.1f}%** | | |
| | 🟫 **Solo Exposto / Estradas / Infraestrutura** | {ha_solo:.1f} ha | **{pct_solo:.1f}%** | | |
| """ | |
| return fig, relatorio, tmp_csv.name | |
| except Exception as e: | |
| return None, f"❌ **Erro na auditoria:** {str(e)}", None | |
| with gr.Blocks(theme=gr.themes.Soft(), title="VisionCAR - InovaCAR Desafio 2") as demo: | |
| gr.Markdown( | |
| "# 🛰️ VisionCAR — Auditoria Multi-temporal de Uso do Solo\n" | |
| "Protótipo Open-Source para o **Desafio 2 do InovaCAR** (Sentinel-2 + Cruzamento Sazonal)." | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| input_arquivo = gr.File( | |
| label="Polígono do Imóvel (.geojson ou .kml) — deixe vazio para usar o exemplo", | |
| file_types=[".geojson", ".json", ".kml"] | |
| ) | |
| input_ano = gr.Dropdown(choices=[2026, 2025, 2024], value=2026, label="Ano da Auditoria") | |
| input_nuvens = gr.Slider(minimum=5, maximum=40, value=15, step=5, label="Limite máximo de nuvens na Seca (%)") | |
| btn_rodar = gr.Button("🚀 Auditar Imóvel", variant="primary") | |
| output_csv = gr.File(label="📥 Baixar Relatório (CSV)") | |
| with gr.Column(scale=2): | |
| output_relatorio = gr.Markdown("Clique em **Auditar Imóvel** para iniciar o processamento via satélite.") | |
| output_mapa = gr.Plot(label="Mapas de Análise") | |
| btn_rodar.click( | |
| fn=auditar_imovel, | |
| inputs=[input_arquivo, input_ano, input_nuvens], | |
| outputs=[output_mapa, output_relatorio, output_csv] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |