Spaces:
Runtime error
Runtime error
app
Browse files1234567812 unmodified lines21222324252627282930313233343536373844 unmodified lines838485868788899091929394959697987 unmodified lines1061071081091101111121131141151161171181191201212 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461471481491 unmodified line15115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221320 unmodified lines23423523623723823924024124224324 unmodified lines2682692702712722732742752762772782792802812822832842852 unmodified lines2882892902912922932942952962972982993003013 unmodified lines30530630730830931031131231331410 unmodified lines3253263273283293303312 unmodified lines3343353363373383393402 unmodified lines3433443453463473483493 unmodified lines3533543553563573583593603613627 unmodified lines370371372373374375376# 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 time12 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_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.# ---------------------------------------------------------------------WEIGHTS = {"Forest": "weights/230103_randresize_full.pth","Urban": "weights/230103_randresize_full.pth",44 unmodified lines}def _robust_uint8(band_arr: np.ndarray) -> np.ndarray:"""Convert a single band to uint8 using robust 2–98 percentile scaling."""if band_arr.dtype == np.uint8:return band_arrarr = band_arr# subsample for speed on huge rastersif arr.size > 50_000_000:arr = arr[::10, ::10]# safe percentilesfinite = np.isfinite(arr)if not finite.any():return np.zeros_like(band_arr, dtype=np.uint8)7 unmodified linesdef _pick_rgb_bands(src) -> list:"""Choose which 3 bands to use as RGB.Preference: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 (best-effort)."""count = src.countci = list(src.colorinterp) if src.colorinterp else []# (1) true RGB if presentif ci:try:r = ci.index(ColorInterp.red) + 12 unmodified linesreturn [r, g, b]except ValueError:pass# (2) drop alpha, take first 3 non-alphanon_alpha = [i + 1 for i, c in enumerate(ci) if c != ColorInterp.alpha]if len(non_alpha) >= 3:return non_alpha[:3]# (3) fallback to first 3 valid bandsreturn [i for i in range(1, min(3, count) + 1)]def _safe_read_bands(src, bands: list) -> np.ndarray:"""Read the requested 1-based band indices robustly (one-by-one).If a band read fails or is out of range, it is skipped.Returns array of shape (n_read, H, W)."""arrays = []for b in bands:try:if 1 <= b <= src.count:arrays.append(src.read(b))except (RasterioIOError, IndexError):# skip bad bandcontinueif len(arrays) == 0:raise RuntimeError(f"Could not read any of the requested bands {bands} (count={src.count}).")1 unmodified linedef ensure_three_band_rgb_uint8(in_path: str, work_dir: Path, debug: dict) -> str:"""Accepts 3- or 4-band GeoTIFF. Returns path to a 3-band RGB **uint8** GeoTIFF.- Prefers true RGB via ColorInterp- Otherwise drops alpha / picks first 3 readable bands- Reads bands individually to avoid 'list index out of range' crashes"""out_path = str(work_dir / "rgb_uint8_input.tif")with rasterio.open(in_path) as src:count = src.countif count < 3:raise RuntimeError(f"Input has {count} band(s). Need at least 3.")# candidate bands (length >=1, prefer 3)cand = _pick_rgb_bands(src)debug["cand_bands_initial"] = cand# read candidates safelydata = _safe_read_bands(src, cand)# if we got <3 bands, fill up from the remaining valid bandsif data.shape[0] < 3:remaining = [b for b in range(1, count + 1) if b not in cand]extra = _safe_read_bands(src, remaining) if remaining else Noneif extra is not None and extra.shape[0] > 0:need = 3 - data.shape[0]take = min(need, extra.shape[0])data = np.concatenate([data, extra[:take]], axis=0)# still less than 3? pad with zerosif data.shape[0] < 3:H, W = data.shape[-2], data.shape[-1]pad = np.zeros((3 - data.shape[0], H, W), dtype=data.dtype)data = np.concatenate([data, pad], axis=0)# ensure exactly 3data = data[:3, :, :]debug["bands_used"] = data.shape[0]# 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)try: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:20 unmodified linesdebug = {}stage = "ingest"try:# --------------------- Stage 0: ingest upload ---------------------if 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)24 unmodified linesif meta0["bands"] < 3:return None, None, f"Input has {meta0['bands']} band(s). Need at least 3."# --------------------- Stage 1: RGB uint8 conversion ---------------------stage = "rgb-conversion"if progress: progress(0.08, desc="Converting to 3-band RGB (uint8)…")rgb_path = ensure_three_band_rgb_uint8(str(upload_src), tmpdir, debug)# --------------------- Stage 2: tiling ---------------------stage = "tiling"if progress: progress(0.18, 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)2 unmodified linesstrip_alpha_pngs(tiles_path)# --------------------- Stage 3: predictor ---------------------stage = "model"weights_path = ensure_weights(environment, progress=progress)if progress: progress(0.30, desc="Loading model…")cfg = setup_cfg(update_model=str(weights_path))predictor = DefaultPredictor(cfg)# --------------------- Stage 4: prediction ---------------------stage = "prediction"if progress: progress(0.40, desc="Predicting on tiles…")predict_on_data(str(tiles_path), predictor=predictor)3 unmodified linesif 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"10 unmodified linesexcept 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# --------------------- Stage 6: overlay + zip ---------------------stage = "render"if progress: progress(0.90, desc="Rendering overlay…")render_overlay(rgb_path, clean, str(out_png))2 unmodified linestook = time.time() - t0summary = (f"Raster: {Path(upload_src).name} | bands_in={meta0['bands']} ({meta0['dtype']}) → using RGB uint8 | "f"crs={meta0['crs']} | res={meta0['res']}\n"f"colorinterp: {debug.get('meta_ingest',{}).get('colorinterp')} | "f"cand_bands_initial: {debug.get('cand_bands_initial')} | "3 unmodified linesreturn str(out_png), str(out_zip), summaryexcept Exception as e:# Bubble up a detailed error with contextmore = ""if debug:more = f"\nDebug: {debug}"return None, None, f"Error during inference ({stage}): {e}{more}"# ----------------------------- UI -----------------------------7 unmodified linesinp = 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")123456712 unmodified lines202122232425262728293031323344 unmodified lines78798081828384858687887 unmodified lines969798991001011021031041051062 unmodified lines1091101111121131141151161171181191201211221231241251261 unmodified line12812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418520 unmodified lines20620720820921021121221321424 unmodified lines2392402412422432442452462472482492502512522532542552 unmodified lines2582592602612622632642652662672682692702713 unmodified lines27527627727827928028128228328410 unmodified lines2952962972982993002 unmodified lines3033043053063073083092 unmodified lines3123133143153163173183 unmodified lines3223233243253263273287 unmodified lines336337338339340341342# app.pyimport osos.environ.setdefault("OMP_NUM_THREADS", "1")os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib")os.makedirs(os.environ["MPLCONFIGDIR"], exist_ok=True)import time12 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 DefaultPredictorWEIGHTS = {"Forest": "weights/230103_randresize_full.pth","Urban": "weights/230103_randresize_full.pth",44 unmodified lines}def _robust_uint8(band_arr: np.ndarray) -> np.ndarray:if band_arr.dtype == np.uint8:return band_arrarr = band_arrif arr.size > 50_000_000:arr = arr[::10, ::10]finite = np.isfinite(arr)if not finite.any():return np.zeros_like(band_arr, dtype=np.uint8)7 unmodified linesdef _pick_rgb_bands(src) -> list:"""Returns 1-based indices for R,G,B.Prefers explicit RGB colorinterp; else drops alpha; else [1,2,3]."""count = src.countci = list(src.colorinterp) if src.colorinterp else []if ci:try:r = ci.index(ColorInterp.red) + 12 unmodified linesreturn [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 [i for i in range(1, min(3, count) + 1)]def _safe_read_bands(src, bands: list) -> np.ndarray:arrays = []for b in bands:try:if 1 <= b <= src.count:arrays.append(src.read(b))except (RasterioIOError, IndexError):continueif len(arrays) == 0:raise RuntimeError(f"Could not read any of the requested bands {bands} (count={src.count}).")1 unmodified linedef ensure_three_band_rgb_uint8(in_path: str, work_dir: Path, debug: dict) -> str:"""Build a clean 3×uint8 RGB GeoTIFF from a 3- or 4-band input.IMPORTANT: we write with a MINIMAL profile (no photometric/colorinterp tweaks)to avoid GDAL's 'list index out of range' edge-cases."""out_path = str(work_dir / "rgb_uint8_input.tif")with rasterio.open(in_path) as src:if src.count < 3:raise RuntimeError(f"Input has {src.count} band(s). Need at least 3.")cand = _pick_rgb_bands(src)debug["cand_bands_initial"] = canddata = _safe_read_bands(src, cand)if data.shape[0] < 3:remaining = [b for b in range(1, src.count + 1) if b not in cand]if remaining:extra = _safe_read_bands(src, remaining)need = 3 - data.shape[0]take = min(need, extra.shape[0])data = np.concatenate([data, extra[:take]], axis=0)if data.shape[0] < 3:H, W = data.shape[-2], data.shape[-1]pad = np.zeros((3 - data.shape[0], H, W), dtype=data.dtype)data = np.concatenate([data, pad], axis=0)data = data[:3, :, :]debug["bands_used"] = data.shape[0]if data.dtype != np.uint8:data = np.stack([_robust_uint8(data[i]) for i in range(3)], axis=0)# Minimal, clean profile (avoid copying quirky keys)profile = {"driver": "GTiff","height": src.height,"width": src.width,"count": 3,"dtype": "uint8","crs": src.crs,"transform": src.transform,"tiled": False, # keep simple"interleave": "pixel", # common default# no 'photometric', no 'nodata', no colorinterp writes}with rasterio.open(out_path, "w", **profile) as dst:dst.write(data)return out_pathdef strip_alpha_pngs(tiles_dir: Path):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:passdef render_overlay(base_tif: str, crowns_gdf: gpd.GeoDataFrame, out_png: str) -> None:with rasterio.open(base_tif) as src:20 unmodified linesdebug = {}stage = "ingest"try:# ingestif 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)24 unmodified linesif meta0["bands"] < 3:return None, None, f"Input has {meta0['bands']} band(s). Need at least 3."# rgb-conversionstage = "rgb-conversion"if progress: progress(0.08, desc="Converting to 3-band RGB (uint8)…")rgb_path = ensure_three_band_rgb_uint8(str(upload_src), tmpdir, debug)# tilingstage = "tiling"if progress: progress(0.18, desc="Tiling image (RGB)…")buffer, tile_w, tile_h = 30, 40, 40tile_data(rgb_path, str(tiles_path), buffer, tile_w, tile_h, dtype_bool=True, mode="rgb")pngs = list(tiles_path.glob("*.png"))tifs = list(tiles_path.glob("*.tif"))n_tiles = len(pngs) + len(tifs)2 unmodified linesstrip_alpha_pngs(tiles_path)# modelstage = "model"weights_path = ensure_weights(environment, progress=progress)if progress: progress(0.30, desc="Loading model…")cfg = setup_cfg(update_model=str(weights_path))predictor = DefaultPredictor(cfg)# predictionstage = "prediction"if progress: progress(0.40, desc="Predicting on tiles…")predict_on_data(str(tiles_path), predictor=predictor)3 unmodified linesif len(pred_jsons) == 0:return None, None, ("No predictions were written after inference. ""Ensure the image truly contains trees and RGB content is valid.")# postprocessstage = "postprocess"if progress: progress(0.65, desc="Projecting + stitching crowns…")preds_geo_dir = tiles_path / "predictions_geo"10 unmodified linesexcept Exception:passsaved = Nonetry:clean.to_file(out_gpkg, driver="GPKG")2 unmodified linesclean.to_file(out_geojson, driver="GeoJSON")saved = out_geojson# renderstage = "render"if progress: progress(0.90, desc="Rendering overlay…")render_overlay(rgb_path, clean, str(out_png))2 unmodified linestook = time.time() - t0summary = (f"Raster: {Path(upload_src).name} | bands_in={meta0['bands']} ({meta0['dtype']}) → RGB uint8 | "f"crs={meta0['crs']} | res={meta0['res']}\n"f"colorinterp: {debug.get('meta_ingest',{}).get('colorinterp')} | "f"cand_bands_initial: {debug.get('cand_bands_initial')} | "3 unmodified linesreturn str(out_png), str(out_zip), summaryexcept Exception as e:more = f"\nDebug: {debug}" if debug else ""return None, None, f"Error during inference ({stage}): {e}{more}"# ----------------------------- UI -----------------------------7 unmodified linesinp = gr.File(label="Upload GeoTIFF (RGB or 4-band)",file_types=[".tif", ".tiff"],type="filepath")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+39-73