Spaces:
Runtime error
Runtime error
app
Browse files13 unmodified lines14151617181935 unmodified lines5556575859606123 unmodified lines8586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461478 unmodified lines1561571581591601611621634 unmodified lines1681691701711721731748 unmodified lines1831841851861871881891901911921931 unmodified line1951961971981992002012022032044 unmodified lines20921021121221321421521621721821922022122222322422522622722822923023123223323423523623718 unmodified lines25625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528613 unmodified linesimport gradio as grimport numpy as npimport rasterioimport geopandas as gpdimport matplotlibmatplotlib.use("Agg")35 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:try:23 unmodified linesChoose which 3 bands to use as RGB.Preference order:1) Explicit Red/Green/Blue color interpretations2) If there's an Alpha band, drop it and take first three non-alpha3) Fallback to [1,2,3]Returns 1-based band indices list of length 3."""ci = list(src.colorinterp) if src.colorinterp else []# Map color interps to indicesif ci:try:r = ci.index(rasterio.enums.ColorInterp.red) + 1g = ci.index(rasterio.enums.ColorInterp.green) + 1b = ci.index(rasterio.enums.ColorInterp.blue) + 1return [r, g, b]except ValueError:pass# Drop alpha if presentnon_alpha = [i+1 for i, c in enumerate(ci) if c != rasterio.enums.ColorInterp.alpha]if len(non_alpha) >= 3:return non_alpha[:3]# Fallbackreturn [1, 2, 3]def ensure_three_band_rgb(in_path: str, work_dir: Path) -> str:"""If the input has 4 bands, write a 3-band RGB copy and return its path.If it already has 3 bands, return original path.Only supports 3 or 4 band inputs per the request."""out_path = str(work_dir / "rgb_input.tif")with rasterio.open(in_path) as src:if src.count not in (3, 4):raise RuntimeError(f"Input has {src.count} band(s). This app currently supports 3 or 4 band GeoTIFFs.")if src.count == 3:return in_path# count == 4 → select RGB bands and writebands = pick_rgb_bands(src) # 1-baseddata = src.read(bands)profile = src.profile.copy()profile.update(count=3)# In case the source had nodata/alpha; we just write RGBprofile.pop("photometric", None)with rasterio.open(out_path, "w", **profile) as dst:dst.write(data)return out_pathdef strip_alpha_pngs(tiles_dir: Path):"""Ensure all PNG tiles (if any) are RGB (no alpha). Safe no-op if already RGB."""for p in tiles_dir.glob("*.png"):try:with Image.open(p) as im:if im.mode != "RGB":im.convert("RGB").save(p)except Exception:# best-effort; don't fail the whole pipelinepassdef render_overlay(base_tif: str, crowns_gdf: gpd.GeoDataFrame, out_png: str) -> None:with rasterio.open(base_tif) as src:8 unmodified lines# -------------------- main inference --------------------def run_inference(geom_file, environment, confidence, progress=gr.Progress(track_tqdm=True)):import globt0 = time.time()tmpdir = Path(tempfile.mkdtemp(prefix="dt2_"))out_png = tmpdir / "overlay.png"4 unmodified linestiles_path.mkdir(parents=True, exist_ok=True)try:# Normalize upload to a real file inside our tmpdirif not geom_file:return None, None, "Error: no file provided."8 unmodified lineselse:return None, None, f"Unsupported upload type: {type(geom_file)}"# Basic raster checksmeta = _summarize_raster(str(upload_src))if not meta["crs"]:return None, None, "Input has no CRS. Reproject to a metric CRS (e.g., UTM) and try again."# Reject geographic CRS (degrees). Prefer projected (metres) like UTM.try:is_geographic = bool(getattr(meta["crs"], "is_geographic", False))except Exception:1 unmodified lineif is_geographic:return None, None, f"Input CRS appears geographic ({meta['crs']}). Reproject to a projected CRS (e.g., UTM)."# Convert 4-band → 3-band RGB if needed (always end up 3-band)rgb_path = ensure_three_band_rgb(str(upload_src), tmpdir)if progress: progress(0.05, desc="Tiling image (RGB)…")buffer, tile_w, tile_h = 30, 40, 40 # metrestile_data(rgb_path, str(tiles_path), buffer, tile_w, tile_h, dtype_bool=True, mode="rgb")4 unmodified linesif n_tiles == 0:return None, None, "Tiling produced 0 tiles. Check CRS (must be projected/UTM) and tile/buffer sizes."# Make sure no PNG tile has an alpha channelstrip_alpha_pngs(tiles_path)# Prepare modelweights_path = ensure_weights(environment, progress=progress)if progress: progress(0.25, desc="Loading model…")cfg = setup_cfg(update_model=str(weights_path))predictor = DefaultPredictor(cfg)# Predictif progress: progress(0.35, desc="Predicting on tiles…")predict_on_data(str(tiles_path), predictor=predictor)# Verify predictions existpreds_dir = tiles_path / "predictions"pred_jsons = list(preds_dir.glob("*.json"))if len(pred_jsons) == 0:return None, None, ("No predictions were written. ""Ensure the image contains trees, and that RGB content is valid (not blank).")# Project → stitch → cleanif progress: progress(0.65, desc="Projecting + stitching crowns…")preds_geo_dir = tiles_path / "predictions_geo"project_to_geojson(str(tiles_path), str(preds_dir), str(preds_geo_dir))18 unmodified linesclean.to_file(out_geojson, driver="GeoJSON")saved = out_geojson# Overlay preview (use the 3-band RGB we tiled from)if progress: progress(0.90, desc="Rendering overlay…")render_overlay(rgb_path, clean, str(out_png))# Zip the vector outputwith zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf:zf.write(saved, arcname=saved.name)took = time.time() - t0summary = (f"Raster: {Path(upload_src).name} | bands_in={meta['bands']} → using RGB | "f"crs={meta['crs']} | res={meta['res']}\n"f"Tiles: {n_tiles} | Detected crowns: {len(clean)} | Took {took:.1f}s")return str(out_png), str(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 a GeoTIFF (3 or 4 bands). The app will convert to 3-band RGB and run Detectree2.\n\n""Pipeline: tiling → prediction → project → stitch → clean.")with gr.Row():inp = gr.File(13 unmodified lines1415161718192035 unmodified lines5657585960616223 unmodified lines86878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671688 unmodified lines1771781791801811824 unmodified lines1871881891901911921931948 unmodified lines2032042052062072082092102111 unmodified line2132142152162172182192202212222232242252264 unmodified lines23123223323423523623723823924024124224324424524624724824925025125225325425525625725825926018 unmodified lines27928028128228328428528628728828929029129229329429529629729829930030130230330430530630730813 unmodified linesimport gradio as grimport numpy as npimport rasteriofrom rasterio.enums import ColorInterpimport geopandas as gpdimport matplotlibmatplotlib.use("Agg")35 unmodified linesp = Path(WEIGHTS.get(chosen, WEIGHTS["Flexible"]))if p.exists():return pif progress: progress(0.18, desc="Downloading model weights…")last_err = Nonefor url in ZENODO_CANDIDATES:try:23 unmodified linesChoose which 3 bands to use as RGB.Preference order:1) Explicit Red/Green/Blue color interpretations2) Drop Alpha if present; take first three non-alpha3) Fallback to [1,2,3]Returns 1-based band indices list of length 3."""ci = list(src.colorinterp) if src.colorinterp else []if ci:try:r = ci.index(ColorInterp.red) + 1g = ci.index(ColorInterp.green) + 1b = ci.index(ColorInterp.blue) + 1return [r, g, b]except ValueError:passnon_alpha = [i + 1 for i, c in enumerate(ci) if c != ColorInterp.alpha]if len(non_alpha) >= 3:return non_alpha[:3]return [1, 2, 3]def _robust_uint8(band_arr: np.ndarray) -> np.ndarray:"""Convert a single band to uint8 using robust 2–98 percentile scaling.Handles 16-bit inputs safely; keeps uint8 as-is."""if band_arr.dtype == np.uint8:return band_arr# Subsample for speed if hugearr = band_arrif arr.size > 50_000_000: # ~50M pxarr = arr[::10, ::10]lo, hi = np.percentile(arr[np.isfinite(arr)], [2, 98])if hi <= lo:lo, hi = float(arr.min()), float(arr.max())if hi <= lo:return np.zeros_like(band_arr, dtype=np.uint8)scaled = (band_arr.astype(np.float32) - lo) * (255.0 / (hi - lo))return np.clip(scaled, 0, 255).astype(np.uint8)def ensure_three_band_rgb_uint8(in_path: str, work_dir: Path) -> str:"""Accepts 3- or 4-band GeoTIFF.- If 3 bands: ensure uint8 (robust scale if needed)- If 4 bands: pick RGB bands (drop alpha/NIR), ensure uint8Returns path to a 3-band uint8 GeoTIFF suitable for RGB tiling."""out_path = str(work_dir / "rgb_uint8_input.tif")with rasterio.open(in_path) as src:if src.count not in (3, 4):raise RuntimeError(f"Input has {src.count} band(s). This app supports 3 or 4 bands.")bands = [1, 2, 3] if src.count == 3 else pick_rgb_bands(src)data = src.read(bands) # shape: (3, H, W)# Make sure dtype is uint8if data.dtype != np.uint8:data = np.stack([_robust_uint8(data[i]) for i in range(3)], axis=0)profile = src.profile.copy()profile.update(count=3, dtype="uint8", photometric="RGB")profile.pop("nodata", None)with rasterio.open(out_path, "w", **profile) as dst:dst.write(data)# Set color interpretation to RGB explicitlytry:dst.colorinterp = (ColorInterp.red, ColorInterp.green, ColorInterp.blue)except Exception:passreturn out_pathdef strip_alpha_pngs(tiles_dir: Path):"""Ensure any PNG tiles are RGB (no alpha)."""for p in tiles_dir.glob("*.png"):try:with Image.open(p) as im:if im.mode != "RGB":im.convert("RGB").save(p)except Exception:pass # best-effort onlydef render_overlay(base_tif: str, crowns_gdf: gpd.GeoDataFrame, out_png: str) -> None:with rasterio.open(base_tif) as src:8 unmodified lines# -------------------- main inference --------------------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"4 unmodified linestiles_path.mkdir(parents=True, exist_ok=True)try:# --------------------- Stage 0: ingest upload ---------------------stage = "ingest"if not geom_file:return None, None, "Error: no file provided."8 unmodified lineselse:return None, None, f"Unsupported upload type: {type(geom_file)}"meta = _summarize_raster(str(upload_src))if not meta["crs"]:return None, None, "Input has no CRS. Reproject to a projected CRS (e.g., UTM, metres) and try again."try:is_geographic = bool(getattr(meta["crs"], "is_geographic", False))except Exception:1 unmodified lineif is_geographic:return None, None, f"Input CRS appears geographic ({meta['crs']}). Reproject to a projected CRS (e.g., UTM)."# --------------------- Stage 1: RGB uint8 conversion ---------------------stage = "rgb-conversion"if progress: progress(0.05, desc="Converting to 3-band RGB (uint8)…")rgb_path = ensure_three_band_rgb_uint8(str(upload_src), tmpdir)# --------------------- Stage 2: tiling ---------------------stage = "tiling"if progress: progress(0.15, desc="Tiling image (RGB)…")buffer, tile_w, tile_h = 30, 40, 40 # metrestile_data(rgb_path, str(tiles_path), buffer, tile_w, tile_h, dtype_bool=True, mode="rgb")4 unmodified linesif n_tiles == 0:return None, None, "Tiling produced 0 tiles. Check CRS (must be projected/UTM) and tile/buffer sizes."strip_alpha_pngs(tiles_path)# --------------------- Stage 3: predictor ---------------------stage = "model"weights_path = ensure_weights(environment, progress=progress)if progress: progress(0.28, desc="Loading model…")cfg = setup_cfg(update_model=str(weights_path))predictor = DefaultPredictor(cfg)# --------------------- Stage 4: prediction ---------------------stage = "prediction"if progress: progress(0.38, desc="Predicting on tiles…")predict_on_data(str(tiles_path), predictor=predictor)preds_dir = tiles_path / "predictions"pred_jsons = list(preds_dir.glob("*.json"))if len(pred_jsons) == 0:return None, None, ("No predictions were written after inference. ""Ensure the image truly contains trees and RGB content is valid (not blank/overexposed).")# --------------------- Stage 5: project + stitch + clean ---------------------stage = "postprocess"if progress: progress(0.65, desc="Projecting + stitching crowns…")preds_geo_dir = tiles_path / "predictions_geo"project_to_geojson(str(tiles_path), str(preds_dir), str(preds_geo_dir))18 unmodified linesclean.to_file(out_geojson, driver="GeoJSON")saved = out_geojson# --------------------- Stage 6: overlay + zip ---------------------stage = "render"if progress: progress(0.90, desc="Rendering overlay…")render_overlay(rgb_path, clean, str(out_png))with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf:zf.write(saved, arcname=saved.name)took = time.time() - t0summary = (f"Raster: {Path(upload_src).name} | bands_in={meta['bands']} ({meta['dtype']}) → using RGB uint8 | "f"crs={meta['crs']} | res={meta['res']}\n"f"Tiles: {n_tiles} | Detected crowns: {len(clean)} | Took {took:.1f}s")return str(out_png), str(out_zip), summaryexcept Exception as e:return None, None, f"Error during inference ({stage}): {e}"# ----------------------------- UI -----------------------------with gr.Blocks(title="Detectree2 Inference") as demo:gr.Markdown("# 🌳 Detectree2 Demo\n""Upload a GeoTIFF (3 or 4 bands). The app converts to 3-band RGB **uint8** and runs Detectree2.\n\n""Pipeline: RGB conversion → tiling → prediction → project → stitch → clean.")with gr.Row():inp = gr.File(
app.py+75-53