Spaces:
Runtime error
Runtime error
File size: 13,200 Bytes
49e75a7 76c7b4d 3a08f1d b3b2242 49e75a7 1b6735c 673aea5 9021e76 0c8976a 9021e76 be207af 0c8976a 1b6735c ce8e246 1b6735c 38dfa48 3a08f1d 49e75a7 9021e76 101609b 2d58642 101609b 9021e76 3a08f1d 555c20e 101609b 9021e76 49e75a7 9021e76 f1c933e 25fc09d 3880959 9021e76 76c7b4d 9021e76 49e75a7 203d933 f1c933e 9021e76 f1c933e 76c7b4d 9021e76 49e75a7 673aea5 69b49c8 4298555 f1c933e 096a852 be207af f1c933e 9021e76 203d933 18df9a4 b3b2242 9021e76 f1c933e 49e75a7 9021e76 f1c933e 18df9a4 49e75a7 69b49c8 673aea5 69b49c8 381f62e 673aea5 f1c933e 49e75a7 9021e76 673aea5 9021e76 2c6124d 673aea5 69b49c8 673aea5 6db9c74 9021e76 76c7b4d 6db9c74 ce8e246 6db9c74 4298555 592792e b2f8dfd 49e75a7 b2f8dfd b3b2242 9021e76 f1c933e 18df9a4 b2f8dfd 673aea5 4298555 673aea5 4298555 673aea5 9021e76 69b49c8 3880959 b2f8dfd f1c933e 69b49c8 9021e76 18df9a4 3880959 b2f8dfd 69b49c8 9021e76 f1c933e f641304 69b49c8 f1c933e 9021e76 101609b 2d58642 101609b 2d58642 101609b 2d58642 101609b 3a08f1d aa745c6 381f62e 49e75a7 381f62e aa745c6 381f62e aa745c6 1c410e5 aa745c6 3a08f1d 381f62e 1c410e5 381f62e 3a08f1d aa745c6 ed125e8 aa745c6 78c210a aa745c6 69b49c8 aa745c6 3a08f1d 69b49c8 3a08f1d 824527d 381f62e eecfc8d 381f62e eecfc8d 381f62e eecfc8d 381f62e eecfc8d 381f62e 824527d 381f62e 824527d 3a08f1d 824527d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | # environment setup
import os
val = os.environ.get("OMP_NUM_THREADS", "")
try:
int(val)
except Exception:
os.environ["OMP_NUM_THREADS"] = "1"
os.environ.setdefault("MPLCONFIGDIR", "/var/tmp/matplotlib")
os.environ.setdefault("HF_HOME", "/data/.huggingface")
os.environ.setdefault("TORCH_HOME", "/data/.cache/torch")
import tempfile, shutil, glob
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from affine import Affine
import rasterio
from rasterio.plot import show
import torch
import gradio as gr
from detectron2.engine import DefaultPredictor
from detectree2.preprocessing.tiling import tile_data
from detectree2.models.outputs import project_to_geojson, stitch_crowns, clean_crowns, post_clean
from detectree2.models.predict import predict_on_data
from detectree2.models.train import setup_cfg
# config
WEIGHT_DIR = os.getenv("DTR2_WEIGHT_DIR", "/data/weights")
os.makedirs(WEIGHT_DIR, exist_ok=True)
# config
WEIGHTS = {
"Flexible": os.path.join(WEIGHT_DIR, "250312_flexi.pth"),
"Forest": os.path.join(WEIGHT_DIR, "250711_tropical_closed_canopy.pth"),
"Urban": os.path.join(WEIGHT_DIR, "urban_trees_Cambridge_20230630.pth"),
}
# Auto-download weights from Zenodo if missing
ZENODO_RECORD = "15863800"
ZENODO_URLS = {
"250312_flexi.pth": f"https://zenodo.org/records/{ZENODO_RECORD}/files/250312_flexi.pth?download=1",
"250711_tropical_closed_canopy.pth": f"https://zenodo.org/records/{ZENODO_RECORD}/files/250711_tropical_closed_canopy.pth?download=1",
"urban_trees_Cambridge_20230630.pth": f"https://zenodo.org/records/{ZENODO_RECORD}/files/urban_trees_Cambridge_20230630.pth?download=1",
}
for fname, url in ZENODO_URLS.items():
dest = os.path.join(WEIGHT_DIR, fname)
if not os.path.exists(dest):
print(f"Downloading {fname} from Zenodo...")
import urllib.request
urllib.request.urlretrieve(url, dest)
print(f" Saved to {dest} ({os.path.getsize(dest) / 1024**2:.0f} MB)")
DEFAULT_ENV = "Flexible"
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# Keep PyTorch from oversubscribing CPU
try:
torch.set_num_threads(1)
torch.set_num_interop_threads(1)
except Exception:
pass
# Tiling defaults
BUFFER, TILE_W, TILE_H = 30, 40, 40
def run_detectree2(geotiff_path: str, environment: str, conf_threshold: float, progress=None):
geotiff_path = os.path.abspath(geotiff_path)
original_cwd = os.getcwd()
workdir = tempfile.mkdtemp(prefix="dtr2_")
tiles_dir = os.path.join(workdir, "tilespred")
os.makedirs(tiles_dir, exist_ok=True)
os.chdir(workdir)
def update_progress(fraction, desc):
if progress is not None:
progress(fraction, desc=desc)
try:
update_progress(0.05, "Validating input...")
infile = os.path.join(workdir, os.path.basename(geotiff_path))
shutil.copy2(geotiff_path, infile)
# Must be georeferenced
with rasterio.open(infile) as src:
if src.crs is None or src.transform == Affine.identity():
return None, None, "", "Error: Input file is not a valid GeoTIFF. It must have a coordinate reference system (CRS) and geotransform."
update_progress(0.15, "Tiling raster...")
tile_data(infile, tiles_dir, BUFFER, TILE_W, TILE_H, full_coverage=True)
update_progress(0.25, "Loading model...")
weights = WEIGHTS.get(environment) or WEIGHTS[DEFAULT_ENV]
cfg = setup_cfg(update_model=weights)
cfg.MODEL.DEVICE = DEVICE
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = float(os.getenv("DTR2_SCORE_THRESH", "0.25"))
cfg.OUTPUT_DIR = os.path.join(workdir, "train_outputs")
os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)
predictor = DefaultPredictor(cfg)
update_progress(0.35, "Running predictions on tiles...")
with torch.inference_mode():
predict_on_data(tiles_dir, predictor=predictor)
update_progress(0.65, "Collecting predictions...")
for d in (os.path.join(tiles_dir, "predictions"),
os.path.join(cfg.OUTPUT_DIR, "predictions"),
os.path.join(workdir, "predictions")):
if os.path.isdir(d):
preds_dir = d
break
else:
return None, None, "", "Error: Prediction step did not produce any output. The image may be too small or in an unsupported format."
if not glob.glob(os.path.join(preds_dir, "*.json")):
return None, None, "", (
"No trees detected. Try lowering the confidence threshold, "
"or use a different model if your imagery doesn't match the current one."
)
update_progress(0.75, "Projecting to geographic coordinates...")
# project to geojson
preds_geo_dir = os.path.join(tiles_dir, "predictions_geo")
os.makedirs(preds_geo_dir, exist_ok=True)
project_to_geojson(tiles_dir, preds_dir, preds_geo_dir)
geos = glob.glob(os.path.join(preds_geo_dir, "*.geojson"))
if not geos:
return None, None, "", "Error: Could not project predictions to geographic coordinates. Check that the input CRS is valid."
update_progress(0.82, "Stitching and cleaning crowns...")
# stitch + clean + post_clean gap-fill + filter
crowns = stitch_crowns(preds_geo_dir, 1)
cleaned = clean_crowns(crowns, 0.6, confidence=0)
update_progress(0.88, "Filling gaps with post_clean...")
cleaned = post_clean(crowns, cleaned, iou_threshold=0.3, field="Confidence_score", verbose=True)
cleaned = cleaned[cleaned["Confidence_score"] > float(conf_threshold)].set_geometry(
cleaned.simplify(0.4)
)
# Save outputs to a Gradio-friendly temp dir (not cleaned up immediately)
out_dir = tempfile.mkdtemp(prefix="dtr2_out_")
# save vector
gpkg_path = os.path.join(out_dir, "crowns_out.gpkg")
cleaned.to_file(gpkg_path, driver="GPKG")
update_progress(0.92, "Generating overlay image...")
# save overlay
overlay_path = os.path.join(out_dir, "crowns_out.png")
with rasterio.open(infile) as src:
fig, ax = plt.subplots(figsize=(10, 10))
show(src, ax=ax)
if not cleaned.empty:
cleaned.plot(ax=ax, facecolor="none", edgecolor="cyan", linewidth=1.2)
ax.set_xticks([]); ax.set_yticks([]); ax.set_frame_on(False)
plt.savefig(overlay_path, dpi=220, bbox_inches="tight", pad_inches=0)
plt.close(fig)
# Compute raster area in hectares
raster_area_ha = (src.width * src.res[0] * src.height * src.res[1]) / 10000.0
# Compute stats
n_trees = int(len(cleaned))
if n_trees > 0 and not cleaned.empty:
areas = cleaned.geometry.area
mean_conf = cleaned["Confidence_score"].mean()
stats_md = (
"| Metric | Value |\n"
"| :--- | :--- |\n"
f"| Trees detected | **{n_trees}** |\n"
f"| Mean confidence | {mean_conf:.2f} |\n"
f"| Median crown area | {areas.median():.1f} m² |\n"
f"| Total crown area | {areas.sum():.0f} m² |\n"
f"| Input raster area | {raster_area_ha:.1f} ha |\n"
f"| Crown density | {n_trees / raster_area_ha:.1f} trees/ha |"
)
else:
stats_md = (
"| Metric | Value |\n"
"| :--- | :--- |\n"
f"| Trees detected | **0** |\n"
f"| Input raster area | {raster_area_ha:.1f} ha |"
)
# Restore CWD before cleaning up workdir
os.chdir(original_cwd)
shutil.rmtree(workdir, ignore_errors=True)
update_progress(1.0, "Done!")
return overlay_path, gpkg_path, stats_md, ""
except Exception as e:
os.chdir(original_cwd)
shutil.rmtree(workdir, ignore_errors=True)
return None, None, "", f"Error: {e}"
def infer(file_path, environment, confidence, progress=gr.Progress()):
if file_path is None:
return None, None, "", "Error: No file uploaded. Please upload a GeoTIFF (.tif) file first."
return run_detectree2(file_path, environment, confidence, progress=progress)
def save_to_persistent(path):
import traceback
try:
os.makedirs(WEIGHT_DIR, exist_ok=True)
fname = os.path.basename(path)
dest = os.path.join(WEIGHT_DIR, fname)
total, used, free = shutil.disk_usage("/data")
need = os.path.getsize(path)
if need > free:
return f"Not enough space: need {need/1024**2:.2f} MB, free {free/1024**2:.2f} MB."
shutil.copy2(path, dest)
return f"Saved {fname} to {WEIGHT_DIR}"
except Exception as e:
return "Upload failed:\n" + traceback.format_exc()
def list_persistent():
out = []
for root, dirs, files in os.walk("/data"):
for f in files:
p = os.path.join(root, f)
try:
sz = os.path.getsize(p) / (1024**2)
out.append(f"{p} — {sz:.2f} MB")
except Exception:
out.append(p)
return "\n".join(sorted(out)) or "(empty)"
# Model display names with descriptions for dropdown
MODEL_CHOICES = [
("Flexible (recommended)", "Flexible"),
("Forest – tropical closed canopy", "Forest"),
("Urban – city & suburban trees", "Urban"),
]
# Example file (bundled in the repo)
EXAMPLE_FILE = os.path.join(os.path.dirname(__file__) or ".", "example_danum_tile.tif")
# gradio ui
with gr.Blocks(title="Detectree2 – Tree Crown Detection") as demo:
gr.Markdown(
"# 🌳 Detectree2\n"
"Upload aerial RGB imagery as a GeoTIFF and get automatic tree crown delineations. "
"Supported by [forestmap.ai](https://forestmap.ai). "
"[GitHub](https://github.com/PatBall1/detectree2) · [Paper](https://doi.org/10.1002/rse2.332)\n\n"
"<sub>App created by Teddy Liang (University of Waterloo) and Dr James Ball (University of Cambridge).</sub>"
)
with gr.Tabs():
with gr.Tab("Predict"):
gr.Markdown(
"*Processing can take several minutes for large rasters. "
"Keep inputs under 2 GB in this demo. For larger rasters use the "
"[main Python package](https://github.com/PatBall1/detectree2).*"
)
with gr.Row():
inp_file = gr.File(
label="Input (.tif / .tiff) – must be a georeferenced GeoTIFF with RGB bands",
file_types=[".tif", ".tiff"],
type="filepath",
)
env_dd = gr.Dropdown(
label="Model",
choices=MODEL_CHOICES,
value=DEFAULT_ENV,
info="Flexible works well in closed and open canopy systems."
)
conf = gr.Slider(
0.0, 1.0, value=0.3, step=0.05,
label="Confidence threshold",
info="Lower values detect more trees but may include false positives."
)
run_btn = gr.Button("Run prediction", variant="primary")
out_img = gr.Image(label="Crown overlay", type="filepath")
out_gpkg = gr.File(label="⬇ Download crown vectors (GeoPackage)")
out_stats = gr.Markdown(label="Results")
out_err = gr.Textbox(label="Logs / Errors", interactive=False)
run_btn.click(
infer,
inputs=[inp_file, env_dd, conf],
outputs=[out_img, out_gpkg, out_stats, out_err],
concurrency_limit=1,
)
# Example section
if os.path.exists(EXAMPLE_FILE):
gr.Markdown("---\n**No GeoTIFF handy?** Click below to run detectree2 on an example tile from Danum Valley, Borneo.")
example_btn = gr.Button("▶ Run example", variant="secondary")
def run_example():
return run_detectree2(EXAMPLE_FILE, "Flexible", 0.3)
example_btn.click(
run_example,
inputs=[],
outputs=[out_img, out_gpkg, out_stats, out_err],
concurrency_limit=1,
)
# Manage Weights tab (hidden unless admin env var is set)
if os.getenv("DTR2_SHOW_ADMIN"):
with gr.Tab("Manage Weights"):
up = gr.File(label="Upload .pth", file_types=[".pth"])
up_out = gr.Textbox(label="Upload status")
up.upload(save_to_persistent, up, up_out)
list_btn = gr.Button("List /data contents")
list_out = gr.Textbox(label="Persistent files", lines=12)
list_btn.click(lambda: list_persistent(), None, list_out)
if __name__ == "__main__":
port = int(os.getenv("PORT", "7860"))
demo.queue().launch(server_name="0.0.0.0", server_port=port, max_threads=1, show_api=False)
|