Spaces:
Runtime error
Runtime error
app
Browse files4 unmodified lines5678910118 unmodified lines202122232425264 unmodified lines3132333435363730 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212 unmodified lines2242252262272282292302312322332342352362372382392402412422 unmodified lines2452462472482492502512522532542552562572584 unmodified linesos.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib") # writable cacheos.makedirs(os.environ["MPLCONFIGDIR"], exist_ok=True)import ioimport timeimport shutilimport zipfile8 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",30 unmodified linescontinueraise 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 _summarize_raster(path):with rasterio.open(path) as src:return {"bands": src.count,"crs": str(src.crs) if src.crs else None,"res": src.res,"dtype": src.dtypes[0] if src.count else None,"width": src.width,"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)try:# Normalize Gradio file to a real pathif isinstance(geom_file, (str, bytes, os.PathLike)):src_path = str(geom_file)elif hasattr(geom_file, "name"):src_path = geom_file.nameelse: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"))tifs = glob.glob(os.path.join(tiles_path, "*.tif"))n_tiles = len(pngs) + len(tifs)if 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")2 unmodified linesclean.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}"2 unmodified lineswith 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")4 unmodified lines56789108 unmodified lines192021222324254 unmodified lines30313233343530 unmodified lines666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532 unmodified lines2562572582592602612622632642652662672682692702712722732742752762 unmodified lines2792802812822832842852862872882892902912924 unmodified linesos.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib") # writable cacheos.makedirs(os.environ["MPLCONFIGDIR"], exist_ok=True)import timeimport shutilimport zipfile8 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom rasterio.plot import showfrom PIL import Image # used to ensure PNG tiles are RGB (strip alpha if any)# detectree2 / detectron2from detectree2.preprocessing.tiling import tile_data4 unmodified lines# ---------------------------------------------------------------------# Weights: local path + auto-download from Zenodo if missing.# ---------------------------------------------------------------------WEIGHTS = {"Forest": "weights/230103_randresize_full.pth",30 unmodified linescontinueraise RuntimeError(f"Could not obtain weights at {p} — last error: {last_err}")# -------------------- helpers --------------------def _summarize_raster(path):with rasterio.open(path) as src:return {"bands": src.count,"crs": src.crs,"res": src.res,"dtype": src.dtypes[0] if src.count else None,"width": src.width,"height": src.height,"colorinterp": list(src.colorinterp) if src.colorinterp else [],}def pick_rgb_bands(src):"""Choose 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: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)# -------------------- 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"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:# Normalize upload to a real file inside our tmpdirif not geom_file:return None, None, "Error: no file provided."upload_src = tmpdir / (Path(geom_file).name if isinstance(geom_file, str) else "input_upload.tif")if isinstance(geom_file, str) and os.path.isfile(geom_file):shutil.copy(geom_file, upload_src)elif hasattr(geom_file, "name") and isinstance(geom_file.name, str) and os.path.isfile(geom_file.name):shutil.copy(geom_file.name, upload_src)elif isinstance(geom_file, (bytes, bytearray)):with open(upload_src, "wb") as f:f.write(geom_file)else: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:is_geographic = Falseif 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")# Ensure tiles existpngs = list(tiles_path.glob("*.png"))tifs = list(tiles_path.glob("*.tif"))n_tiles = len(pngs) + len(tifs)if 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))crowns = stitch_crowns(str(preds_geo_dir), 1)if progress: progress(0.80, desc="Cleaning crowns…")clean = clean_crowns(crowns, 0.6, confidence=0)thr = float(confidence)if "Confidence_score" in clean.columns:clean = clean[clean["Confidence_score"] > thr]try:clean = clean.set_geometry(clean.geometry.simplify(0.3, preserve_topology=True))except Exception:pass# Save vector output (GPKG → fallback GeoJSON)saved = Nonetry:clean.to_file(out_gpkg, driver="GPKG")2 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}"2 unmodified lineswith 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(label="Upload GeoTIFF (RGB or 4-band)",file_types=[".tif", ".tiff"],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")
app.py+143-109