Spaces:
Runtime error
Runtime error
changes to app
Browse files12342 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import os, io, time, shutil, zipfile, tempfileimport gradio as grimport numpy as npimport rasterio2 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom rasterio.plot import showfrom PIL import Imagefrom detectree2.preprocessing.tiling import tile_datafrom detectree2.models.outputs import project_to_geojson, stitch_crowns, clean_crownsfrom detectree2.models.predict import predict_on_datafrom detectree2.models.train import setup_cfgfrom detectron2.engine import DefaultPredictor# --- Weights: you have 3 options ---# (A) Put .pth files in the repo (LFS, best reliability)# (B) Download at startup from Zenodo/HF Hub# (C) Provide a dropdown that chooses among local weightsWEIGHTS = {"Forest": "weights/230103_randresize_full.pth", # put this file in repo (LFS)"Urban": "weights/230103_randresize_full.pth","Flexible": "weights/230103_randresize_full.pth"}os.makedirs("weights", exist_ok=True)def run_inference(geom_file, environment, confidence, progress=gr.Progress(track_tqdm=True)):t_all = time.time()tmpdir = tempfile.mkdtemp(prefix="dt2_")out_png = os.path.join(tmpdir, "overlay.png")out_gpkg = os.path.join(tmpdir, "crowns_out.gpkg")out_zip = os.path.join(tmpdir, "crowns_out.zip")tiles_path = os.path.join(tmpdir, "tiles_pred")os.makedirs(tiles_path, exist_ok=True)try:# Save upload to temp pathsrc_path = os.path.join(tmpdir, geom_file.name.split("/")[-1])with open(src_path, "wb") as f:f.write(geom_file.read())progress(0.05, desc="Tiling image…")# Small, safe defaults. You can expose these as UI controls if you want.buffer, tile_w, tile_h = 30, 40, 40tile_data(src_path, tiles_path, buffer, tile_w, tile_h, dtype_bool=True)# Choose weightsweights = WEIGHTS.get(environment, WEIGHTS["Flexible"])if not os.path.exists(weights):raise RuntimeError(f"Model weights not found: {weights}")progress(0.25, desc="Loading model…")cfg = setup_cfg(update_model=weights)predictor = DefaultPredictor(cfg)progress(0.35, desc="Predicting on tiles…")predict_on_data(tiles_path, predictor=predictor)progress(0.65, desc="Projecting + stitching crowns…")project_to_geojson(tiles_path, os.path.join(tiles_path, "predictions/"),os.path.join(tiles_path, "predictions_geo/"))crowns = stitch_crowns(os.path.join(tiles_path, "predictions_geo/"), 1)progress(0.8, desc="Cleaning crowns…")clean = clean_crowns(crowns, 0.6, confidence=0)clean = clean[clean["Confidence_score"] > float(confidence)]clean = clean.set_geometry(clean.simplify(0.3))clean.to_file(out_gpkg, driver="GPKG")total = len(clean)progress(0.9, desc="Rendering overlay…")# Render overlay on the base imagewith rasterio.open(src_path) as src:fig, ax = plt.subplots(figsize=(10, 10))show(src, ax=ax)clean.plot(ax=ax, facecolor="none", edgecolor="red", linewidth=1.2)ax = plt.gca()ax.set_xticks([]); ax.set_yticks([]); ax.set_frame_on(False)plt.tight_layout(pad=0)plt.savefig(out_png, dpi=250, bbox_inches="tight", pad_inches=0)plt.close(fig)# Zip the gpkg for downloadwith zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf:zf.write(out_gpkg, arcname="crowns_out.gpkg")took = time.time() - t_allsummary = f"Detected crowns: {total} | Took {took:.1f}s"return out_png, out_zip, summaryexcept Exception as e:return None, None, f"Error: {e}"finally:# Keep tmpdir so user can download; Spaces cleans between runs automatically.passwith gr.Blocks(title="Detectree2 Inference") as demo:gr.Markdown("# 🌳 Detectree2 Demo\n""Upload an orthomosaic (GeoTIFF preferred), pick an environment, and get a crown overlay and GPKG.")with gr.Row():inp = gr.File(label="Upload GeoTIFF / Image", file_types=[".tif", ".tiff", ".png", ".jpg", ".jpeg"])env = gr.Dropdown(choices=["Forest", "Urban", "Flexible"], value="Forest", label="Environment preset")conf = gr.Slider(0.0, 1.0, value=0.5, step=0.05, label="Min confidence")run = gr.Button("Run inference", variant="primary")with gr.Row():overlay = gr.Image(label="Overlay preview", type="filepath")gpkg_zip = gr.File(label="Download crowns_out.gpkg (zip)")notes = gr.Markdown()run.click(fn=run_inference, inputs=[inp, env, conf], outputs=[overlay, gpkg_zip, notes])demo.launch()12345678910111213141516172 unmodified lines2021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202# app.pyimport os# Be defensive about Spaces' env quirks before any heavy importsos.environ.setdefault("OMP_NUM_THREADS", "1") # avoid libgomp crashos.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib") # writable cacheos.makedirs(os.environ["MPLCONFIGDIR"], exist_ok=True)import ioimport timeimport shutilimport zipfileimport tempfilefrom pathlib import Pathimport gradio as grimport numpy as npimport rasterio2 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom rasterio.plot import show# detectree2 / detectron2from detectree2.preprocessing.tiling import tile_datafrom detectree2.models.outputs import project_to_geojson, stitch_crowns, clean_crownsfrom detectree2.models.predict import predict_on_datafrom detectree2.models.train import setup_cfgfrom detectron2.engine import DefaultPredictor# ---------------------------------------------------------------------# Weights: local path + auto-download from Zenodo if missing.# The detectree2 docs & model garden point to '230103_randresize_full.pth'.# ---------------------------------------------------------------------WEIGHTS = {"Forest": "weights/230103_randresize_full.pth","Urban": "weights/230103_randresize_full.pth","Flexible": "weights/230103_randresize_full.pth",}ZENODO_CANDIDATES = [# 2024 record"https://zenodo.org/records/10522461/files/230103_randresize_full.pth?download=1",# 2025 record (duplicate hosting)"https://zenodo.org/records/15014353/files/230103_randresize_full.pth?download=1",]def _download_file(url: str, dest_path: Path, chunk: int = 1 << 20) -> None:import requestsdest_path.parent.mkdir(parents=True, exist_ok=True)with requests.get(url, stream=True, timeout=120) as r:r.raise_for_status()with open(dest_path, "wb") as f:for part in r.iter_content(chunk_size=chunk):if part:f.write(part)def ensure_weights(chosen: str, progress=None) -> Path:p = Path(WEIGHTS.get(chosen, WEIGHTS["Flexible"]))if p.exists():return p# try to downloadif progress: progress(0.20, desc="Downloading model weights…")last_err = Nonefor url in ZENODO_CANDIDATES:try:_download_file(url, p)return pexcept Exception as e:last_err = econtinueraise RuntimeError(f"Could not obtain weights at {p} — last error: {last_err}")def render_overlay(base_tif: str, crowns_gdf: gpd.GeoDataFrame, out_png: str) -> None:with rasterio.open(base_tif) as src:fig, ax = plt.subplots(figsize=(10, 10))show(src, ax=ax)crowns_gdf.plot(ax=ax, facecolor="none", edgecolor="red", linewidth=1.2)ax.set_xticks([]); ax.set_yticks([]); ax.set_frame_on(False)plt.tight_layout(pad=0)plt.savefig(out_png, dpi=250, bbox_inches="tight", pad_inches=0)plt.close(fig)def run_inference(geom_file, environment, confidence, progress=gr.Progress(track_tqdm=True)):t0 = time.time()tmpdir = Path(tempfile.mkdtemp(prefix="dt2_"))out_png = tmpdir / "overlay.png"out_gpkg = tmpdir / "crowns_out.gpkg"out_geojson = tmpdir / "crowns_out.geojson"out_zip = tmpdir / "crowns_out.zip"tiles_path = tmpdir / "tiles_pred"tiles_path.mkdir(parents=True, exist_ok=True)try:if not geom_file:return None, None, "Error: no file provided."# Normalize upload into a local path we controlsrc_path = tmpdir / "input_upload"if isinstance(geom_file, str) and os.path.isfile(geom_file):# gr.File with type="filepath" -> strshutil.copy(geom_file, src_path)upload_name = os.path.basename(geom_file)elif hasattr(geom_file, "name") and isinstance(geom_file.name, str) and os.path.isfile(geom_file.name):# Some gradio wrappers expose .name (path)shutil.copy(geom_file.name, src_path)upload_name = os.path.basename(geom_file.name)elif isinstance(geom_file, (bytes, bytearray)):# If you switch to type="binary", we handle it herewith open(src_path, "wb") as f:f.write(geom_file)upload_name = "upload.bin"else:return None, None, f"Unsupported upload type: {type(geom_file)}"# Tile image (prediction mode). dtype_bool=True avoids blank-tile bug noted in docs.if progress: progress(0.05, desc=f"Tiling {upload_name} …")buffer, tile_w, tile_h = 30, 40, 40tile_data(str(src_path), str(tiles_path), buffer, tile_w, tile_h, dtype_bool=True)# Ensure weights (download if missing)if progress: progress(0.20, desc="Preparing model…")weights_path = ensure_weights(environment, progress=progress)# Build predictor from detectree2 configcfg = setup_cfg(update_model=str(weights_path))predictor = DefaultPredictor(cfg)# Predict on tilesif progress: progress(0.35, desc="Running predictions on tiles…")predict_on_data(str(tiles_path), predictor=predictor)# Reproject + stitch crownsif progress: progress(0.65, desc="Projecting + stitching crowns…")preds_dir = tiles_path / "predictions"preds_geo_dir = tiles_path / "predictions_geo"project_to_geojson(str(tiles_path), str(preds_dir), str(preds_geo_dir))crowns = stitch_crowns(str(preds_geo_dir), 1)# Clean crowns + filter by confidence sliderif progress: progress(0.80, desc="Cleaning crowns…")clean = clean_crowns(crowns, 0.6, confidence=0)conf_thr = float(confidence)if "Confidence_score" in clean.columns:clean = clean[clean["Confidence_score"] > conf_thr]# Light simplify for UX; units follow CRS (meters if UTM)try:clean = clean.set_geometry(clean.geometry.simplify(0.3, preserve_topology=True))except Exception:pass# Try GPKG; fallback to GeoJSON if the driver isn't availablesaved = Nonetry:clean.to_file(out_gpkg, driver="GPKG")saved = out_gpkgexcept Exception:clean.to_file(out_geojson, driver="GeoJSON")saved = out_geojsontotal = int(len(clean))# Render overlayif progress: progress(0.90, desc="Rendering overlay…")render_overlay(str(src_path), clean, str(out_png))# Zip vector output for downloadwith zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf:zf.write(saved, arcname=saved.name)took = time.time() - t0summary = f"Detected crowns: {total} | Min confidence: {conf_thr:.2f} | Took {took:.1f}s"return str(out_png), str(out_zip), summaryexcept Exception as e:return None, None, f"Error: {e}"# ----------------------------- UI -----------------------------with gr.Blocks(title="Detectree2 Inference") as demo:gr.Markdown("# 🌳 Detectree2 Demo\n""Upload an orthomosaic (GeoTIFF preferred), pick an environment, and get a crown overlay and GPKG/GeoJSON.\n\n""Pipeline: tiling → prediction → project → stitch → clean (per detectree2 tutorial).")with gr.Row():inp = gr.File(label="Upload GeoTIFF / Image",file_types=[".tif", ".tiff", ".png", ".jpg", ".jpeg"],type="filepath" # IMPORTANT: gives a string path, not a file-like)env = gr.Dropdown(choices=["Forest", "Urban", "Flexible"], value="Forest", label="Environment preset")conf = gr.Slider(0.0, 1.0, value=0.5, step=0.05, label="Min confidence")run = gr.Button("Run inference", variant="primary")with gr.Row():overlay = gr.Image(label="Overlay preview", type="filepath")gpkg_zip = gr.File(label="Download crowns (zip)")notes = gr.Markdown()run.click(fn=run_inference, inputs=[inp, env, conf], outputs=[overlay, gpkg_zip, notes])if __name__ == "__main__":demo.launch()
app.py+153-69