Spaces:
Runtime error
Runtime error
app
Browse files79 unmodified lines808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521679 unmodified linesplt.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)):import jsonfrom pathlib import Pathimport shutil, tempfile, time, zipfileimport rasteriofrom rasterio.transform import Affinet0 = time.time()tmpdir = Path(tempfile.mkdtemp(prefix="dt2_"))out_png = tmpdir / "overlay.png"out_vec = 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):shutil.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):shutil.copy(geom_file.name, src_path)upload_name = os.path.basename(geom_file.name)elif isinstance(geom_file, (bytes, bytearray)):with 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)}"# -------- Validate the raster (fail fast with helpful messages) --------with rasterio.open(src_path) as src:crs = src.crstransform = src.transformband_count = src.count# Must be georeferenced to project predictions back (docs workflow)if crs is None or not isinstance(transform, Affine) or transform == Affine.identity():return None, None, ("Your file has no valid georeferencing. ""Please upload a GeoTIFF with a projected CRS (e.g., UTM, metres) ""so predictions can be projected to GeoJSON/GPKG.")if getattr(crs, "is_geographic", False):return None, None, (f"Your file CRS appears geographic ({crs.to_string()}). ""Detectree2 expects a projected CRS in metres (e.g., UTM). ""Reproject to UTM and try again.")imgmode = "ms" if band_count >= 4 else "rgb"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, mode=imgmode)# If no tiles were created (small image or odd metadata), retry with conservative sizestile_imgs = list(tiles_path.glob("*.png")) + list(tiles_path.glob("*.tif"))if len(tile_imgs) == 0:if progress: progress(0.12, desc="No tiles found; retrying with smaller tiles…")buffer, tile_w, tile_h = 5, 10, 10tile_data(str(src_path), str(tiles_path), buffer, tile_w, tile_h, dtype_bool=True, mode=imgmode)tile_imgs = list(tiles_path.glob("*.png")) + list(tiles_path.glob("*.tif"))if len(tile_imgs) == 0:return None, None, ("Tiling produced zero tiles. The raster might be too small or metadata is unusual. ""Try a larger image, or reduce buffer/tile sizes.")# Weights (uses your existing ensure_weights/environment)if progress: progress(0.20, desc="Preparing model…")weights_path = ensure_weights(environment, progress=progress)cfg = setup_cfg(update_model=str(weights_path))predictor = DefaultPredictor(cfg)if progress: progress(0.35, desc="Running predictions on tiles…")predict_on_data(str(tiles_path), predictor=predictor)# Verify predictions exist before projectingpreds_dir = tiles_path / "predictions"pred_jsons = list(preds_dir.glob("*.json"))if len(pred_jsons) == 0:# Common causes: wrong img mode (ms vs rgb), incompatible weights, or blank imagehints = []hints.append(f"Detected {band_count} band(s) → using mode='{imgmode}'.")hints.append("If your image is multispectral (≥4 bands) and not RGB, make sure mode='ms' is used.")hints.append("Check that the uploaded imagery actually contains trees and is not blank.")return None, None, ("Prediction stage produced no outputs.\n- " + "\n- ".join(hints))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))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_vec, driver="GPKG")saved = out_vecexcept Exception:clean.to_file(out_geojson, driver="GeoJSON")saved = out_geojsonif progress: progress(0.90, desc="Rendering overlay…")render_overlay(str(src_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() - t0return str(out_png), str(out_zip), f"Detected crowns: {len(clean)} | Min conf: {thr:.2f} | Took {took:.1f}s"except Exception as e:# Return the real message instead of a bare 'list index out of range'return None, None, f"Error during inference: {e}"# ----------------------------- UI -----------------------------with gr.Blocks(title="Detectree2 Inference") as demo:gr.Markdown(79 unmodified lines808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419579 unmodified linesplt.savefig(out_png, dpi=250, bbox_inches="tight", pad_inches=0)plt.close(fig)def _summarize_raster(path):import rasteriowith 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,}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)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)}")# 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"))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.")# 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(
app.py+93-114