Spaces:
Runtime error
Runtime error
4 channel support
Browse files1 unmodified line234567811 unmodified lines2021222324254 unmodified lines303132333435361 unmodified line38394041424344454611 unmodified lines5859606162636416 unmodified lines818283848586874 unmodified lines92939495969798991001011021037 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321332 unmodified lines1361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062071 unmodified lineimport 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 io11 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom rasterio.plot import show# detectree2 / detectron2from detectree2.preprocessing.tiling import tile_data4 unmodified lines# ---------------------------------------------------------------------# 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",1 unmodified line"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",]11 unmodified linesp = 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:16 unmodified linesplt.close(fig)def _summarize_raster(path):import rasteriowith rasterio.open(path) as src:return {"bands": src.count,4 unmodified lines"height": src.height,}def run_inference(geom_file, environment, confidence, progress=gr.Progress(track_tqdm=True)):import glob, os, io, time, shutil, zipfile, tempfilet_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)7 unmodified lineselse:raise RuntimeError(f"Unsupported upload type: {type(geom_file)}")# Basic raster sanity checkmeta = _summarize_raster(src_path)if not meta["crs"]:raise RuntimeError("Input has no CRS. Reproject to a metric CRS (e.g., UTM) and try again.")if "UTM" not in (meta["crs"] or "").upper() and "EPSG:32" not in (meta["crs"] or "") and "EPSG:33" not in (meta["crs"] or ""):# Heuristic: most UTM EPSG codes start with 32xxx or 33xxxraise RuntimeError(f"Input CRS looks non-metric ({meta['crs']}). Reproject to local UTM before running.")bands = meta["bands"]img_mode = "rgb" if bands <= 3 else "ms"if bands == 1:raise RuntimeError("Input has 1 band. The bundled model expects RGB (3-band) or multispectral (4+).")progress(0.05, desc=f"Tiling image ({img_mode})…")buffer, tile_w, tile_h = 30, 40, 40 # meters# dtype_bool=True per docs to avoid blank PNG bugtile_data(src_path, tiles_path, buffer, tile_w, tile_h, dtype_bool=True, mode=img_mode)# Verify tiles existpngs = glob.glob(os.path.join(tiles_path, "*.png"))2 unmodified linesif n_tiles == 0:raise RuntimeError("Tiling produced 0 tiles. Check CRS (must be metric/UTM) and tile/buffer sizes.")# 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)# Verify predictions existpreds_dir = os.path.join(tiles_path, "predictions")if not os.path.isdir(preds_dir) or not os.listdir(preds_dir):raise RuntimeError("No predictions were written. Try a smaller confidence, check band count/CRS, or use RGB data.")progress(0.65, desc="Projecting + stitching crowns…")project_to_geojson(tiles_path, preds_dir, 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…")with 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)with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf:zf.write(out_gpkg, arcname="crowns_out.gpkg")took = time.time() - t_allsummary = (f"Raster: {os.path.basename(src_path)} | bands={bands} | crs={meta['crs']} | res={meta['res']}\n"f"Tiles: {n_tiles} | Detected crowns: {total} | Took {took:.1f}s")return out_png, out_zip, summaryexcept Exception as e:return None, None, f"Error during inference: {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")1 unmodified line234567811 unmodified lines202122232425264 unmodified lines313233343536371 unmodified line3940414243444511 unmodified lines57585960616216 unmodified lines7980818283844 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491507 unmodified lines1581591601611621631641651661671681691701711721731741751761771781791801812 unmodified lines1841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572581 unmodified lineimport 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 io11 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom rasterio.plot import showfrom PIL import Image # used to strip alpha from any png tiles# detectree2 / detectron2from detectree2.preprocessing.tiling import tile_data4 unmodified lines# ---------------------------------------------------------------------# Weights: local path + auto-download from Zenodo if missing.# The detectree2 model garden points to '230103_randresize_full.pth'.# ---------------------------------------------------------------------WEIGHTS = {"Forest": "weights/230103_randresize_full.pth",1 unmodified line"Flexible": "weights/230103_randresize_full.pth",}ZENODO_CANDIDATES = ["https://zenodo.org/records/10522461/files/230103_randresize_full.pth?download=1","https://zenodo.org/records/15014353/files/230103_randresize_full.pth?download=1",]11 unmodified linesp = Path(WEIGHTS.get(chosen, WEIGHTS["Flexible"]))if p.exists():return pif progress: progress(0.20, desc="Downloading model weights…")last_err = Nonefor url in ZENODO_CANDIDATES:16 unmodified linesplt.close(fig)def _summarize_raster(path):with rasterio.open(path) as src:return {"bands": src.count,4 unmodified lines"height": src.height,}# --- NEW: force any 4+ band input down to 3-band RGB (keep 1-3 bands sane) ---def ensure_three_band_rgb(in_path: str) -> (str, int):"""Returns path to a 3-band RGB GeoTIFF and the original band count.- If input already has 3 bands: returns the original path.- If input has >=4 bands (e.g., RGBA or MS): writes a copy with bands 1,2,3.- If input has 2 bands: duplicates band 2 to make 3.- If input has 1 band: repeats band 1 to make 3."""with rasterio.open(in_path) as src:orig_bands = src.countif orig_bands == 3:return in_path, orig_bandsprofile = src.profile.copy()profile.update(count=3)rgb_path = os.path.join(os.path.dirname(in_path), "rgb_input.tif")if orig_bands >= 3:data = src.read([1, 2, 3])elif orig_bands == 2:b1, b2 = src.read([1, 2])data = np.stack([b1, b2, b2], axis=0)elif orig_bands == 1:b1 = src.read(1)data = np.stack([b1, b1, b1], axis=0)else:raise RuntimeError(f"Unexpected band count: {orig_bands}")with rasterio.open(rgb_path, "w", **profile) as dst:dst.write(data)return rgb_path, orig_bandsdef strip_alpha_pngs(tiles_dir: str) -> int:"""Ensure all PNG tiles are RGB (no alpha). Returns number of files patched."""import globpatched = 0for p in glob.glob(os.path.join(tiles_dir, "*.png")):try:with Image.open(p) as im:if im.mode != "RGB":im.convert("RGB").save(p)patched += 1except Exception:passreturn patcheddef run_inference(geom_file, environment, confidence, progress=gr.Progress(track_tqdm=True)):import globt_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_geojson = os.path.join(tmpdir, "crowns_out.geojson")out_zip = os.path.join(tmpdir, "crowns_out.zip")tiles_path = os.path.join(tmpdir, "tiles_pred")os.makedirs(tiles_path, exist_ok=True)7 unmodified lineselse:raise RuntimeError(f"Unsupported upload type: {type(geom_file)}")# Validate georeferencing (need a projected CRS in metres)meta = _summarize_raster(src_path)if not meta["crs"]:raise RuntimeError("Input has no CRS. Reproject to a metric CRS (e.g., UTM) and try again.")crs_str = (meta["crs"] or "").upper()if "UTM" not in crs_str and "EPSG:32" not in crs_str and "EPSG:33" not in crs_str:raise RuntimeError(f"Input CRS looks non-metric ({meta['crs']}). Reproject to local UTM before running.")# 🔴 Force 3-band RGB no matter what was uploaded (handles 4-band/alpha etc.)src_path_rgb, orig_bands = ensure_three_band_rgb(src_path)if progress: progress(0.05, desc=f"Tiling image (forced 3-band RGB)…")buffer, tile_w, tile_h = 30, 40, 40 # meters# RGB mode → PNG tilestile_data(src_path_rgb, tiles_path, buffer, tile_w, tile_h, dtype_bool=True, mode="rgb")# Ensure any PNGs are RGB (strip alpha if present)patched = strip_alpha_pngs(tiles_path)# Verify tiles existpngs = glob.glob(os.path.join(tiles_path, "*.png"))2 unmodified linesif n_tiles == 0:raise RuntimeError("Tiling produced 0 tiles. Check CRS (must be metric/UTM) and tile/buffer sizes.")# Load weightsweights = WEIGHTS.get(environment, WEIGHTS["Flexible"])if not os.path.exists(weights):# Attempt download if missingensure_weights(environment, progress=progress)if progress: progress(0.25, desc="Loading model…")cfg = setup_cfg(update_model=weights)predictor = DefaultPredictor(cfg)if progress: progress(0.35, desc="Predicting on tiles…")predict_on_data(tiles_path, predictor=predictor)# Verify predictions existpreds_dir = os.path.join(tiles_path, "predictions")if not os.path.isdir(preds_dir) or not os.listdir(preds_dir):raise RuntimeError("No predictions were written. Check that imagery is RGB-like and contains trees.")if progress: progress(0.65, desc="Projecting + stitching crowns…")preds_geo_dir = os.path.join(tiles_path, "predictions_geo")project_to_geojson(tiles_path, preds_dir, preds_geo_dir)crowns = stitch_crowns(preds_geo_dir, 1)if progress: progress(0.80, desc="Cleaning crowns…")clean = clean_crowns(crowns, 0.6, confidence=0)clean = clean[clean["Confidence_score"] > float(confidence)]try:clean = clean.set_geometry(clean.geometry.simplify(0.3, preserve_topology=True))except Exception:pass# Save vector output (prefer GPKG; fallback to GeoJSON)saved = Nonetry:clean.to_file(out_gpkg, driver="GPKG")saved = out_gpkgexcept Exception:clean.to_file(out_geojson, driver="GeoJSON")saved = out_geojsonif progress: progress(0.90, desc="Rendering overlay…")render_overlay(src_path_rgb, clean, out_png)with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf:zf.write(saved, arcname=os.path.basename(saved))took = time.time() - t_allsummary = (f"Original bands: {orig_bands} → processed as 3-band RGB"f"{' (patched PNG alpha)' if patched else ''}\n"f"CRS: {meta['crs']} | res={meta['res']} | tiles={n_tiles} | crowns={len(clean)} | {took:.1f}s")return out_png, out_zip, summaryexcept Exception as e:return None, None, f"Error during inference: {e}"# ----------------------------- UI -----------------------------with gr.Blocks(title="Detectree2 Inference") as demo:gr.Markdown("# 🌳 Detectree2 Demo\n""Upload an orthomosaic (GeoTIFF), pick an environment, and get a crown overlay + vector output.\n\n""This app forces inputs to 3-band RGB (drops alpha/extra bands) for compatibility with the bundled model.")with gr.Row():inp = gr.File(label="Upload GeoTIFF / Image",file_types=[".tif", ".tiff", ".png", ".jpg", ".jpeg"],type="filepath" # 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")
app.py+99-48