Spaces:
Runtime error
Runtime error
redo
Browse filesFiles changed (2)
- Dockerfile+29-33
- app.py+122-129
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152# CUDA 11.8 runtime is perfect for T4; cuDNN8; Ubuntu 22.04FROM nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu22.04ARG DEBIAN_FRONTEND=noninteractiveENV PYTHONUNBUFFERED=1 \PIP_NO_CACHE_DIR=1 \PIP_PREFER_BINARY=1 \GRADIO_SERVER_NAME=0.0.0.0# System depsRUN apt-get update && apt-get install -y --no-install-recommends \python3 python3-pip python3-dev build-essential git wget curl \ffmpeg libgl1 ca-certificates && \rm -rf /var/lib/apt/lists/*# Upgrade pipRUN python3 -m pip install --upgrade pip# ---- Deep learning stack (CUDA 11.8) ----# PyTorch 2.1.2 + cu118 and matching torchvisionRUN pip install --extra-index-url https://download.pytorch.org/whl/cu118 \torch==2.1.2+cu118 torchvision==0.16.2+cu118# Detectron2 0.6 prebuilt wheel for torch 2.1 / cu118RUN pip install -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu118/torch2.1/index.html \detectron2==0.6# ---- Geospatial & app deps ----# rasterio/fiona/geopandas wheels ship bundled GDAL on x86_64, so no system GDAL neededRUN pip install \rasterio==1.3.10 fiona geopandas shapely pyproj \opencv-python-headless pillow matplotlib \gradio==4.* \tqdm# Detectree2 (latest)RUN pip install git+https://github.com/PatBall1/detectree2.git# Model weightsRUN mkdir -p /models && \wget -q -O /models/230103_randresize_full.pth \https://zenodo.org/records/10522461/files/230103_randresize_full.pth# AppWORKDIR /appCOPY app.py /app/app.py# Spaces forwards $PORT; expose 7860 for local testingEXPOSE 7860# Run the Gradio appCMD ["python3", "app.py"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# GPU Space (Docker SDK). Torch 1.10 + cu111 + Detectron2 0.6# Base matches CUDA 11.1 + cuDNN 8 for T4 compatibilityFROM nvidia/cuda:11.1.1-cudnn8-runtime-ubuntu20.04ENV DEBIAN_FRONTEND=noninteractive \PIP_NO_CACHE_DIR=1 \FORCE_CUDA=1 \OMP_NUM_THREADS=1 \GRADIO_SERVER_NAME=0.0.0.0# System deps (keep lean; include GDAL tools, OpenCV runtime deps, etc.)RUN apt-get update && apt-get install -y --no-install-recommends \python3 python3-pip python3-dev build-essential git curl wget \libgl1 ffmpeg gdal-bin libspatialindex-dev ca-certificates \&& rm -rf /var/lib/apt/lists/*# Python basicsRUN python3 -m pip install --upgrade pip setuptools==59.5.0 wheel# ---- Core ML stack pinned to Torch 1.x (cu111) ----# Torch 1.10 and torchvision 0.11.1 wheels for CUDA 11.1RUN python3 -m pip install --extra-index-url https://download.pytorch.org/whl/cu111 \torch==1.10.0+cu111 torchvision==0.11.1+cu111# Detectron2 v0.6 prebuilt wheels for torch1.10 + cu111RUN python3 -m pip install -f \https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/torch1.10/index.html \detectron2==0.6# Geospatial + web UI libs. detectree2 comes from GitHub.RUN python3 -m pip install \gradio==4.* \rasterio geopandas shapely matplotlib pillow \"git+https://github.com/PatBall1/detectree2.git"# App codeWORKDIR /appCOPY app.py /app/app.py# Download a pretrained model (forest) at build timeRUN mkdir -p /models && \wget -q -O /models/230103_randresize_full.pth \https://zenodo.org/records/10522461/files/230103_randresize_full.pth# Gradio default port (Spaces will map $PORT for us)EXPOSE 7860CMD ["python3", "app.py"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143import os, io, tempfile, base64import numpy as npimport gradio as grimport rasteriofrom rasterio.plot import showimport geopandas as gpdimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltimport torchfrom detectron2.engine import DefaultPredictorfrom 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_cfgMODEL_FOREST = "/models/230103_randresize_full.pth"# Optional: add more models and download them in Dockerfile if you need:# MODEL_URBAN = "/models/urban_trees_Cambridge_20230630.pth"# MODEL_FLEXI = "/models/250312_flexi.pth"def make_plot_png(tif_path: str, crowns_gpkg: str) -> bytes:with rasterio.open(tif_path) as src:fig, ax = plt.subplots(figsize=(10, 10))show(src, ax=ax)gdf = gpd.read_file(crowns_gpkg)gdf.plot(ax=ax, facecolor="none", edgecolor="blue", linewidth=1.5)# Optional: label confidence at centroidsfor _, row in gdf.iterrows():c = row.geometry.centroidconf = float(row["Confidence_score"])ax.text(c.x, c.y, f"{conf:.2f}", fontsize=8, color="red",ha="center", va="center")ax.set_xticks([])ax.set_yticks([])ax.set_frame_on(False)buf = io.BytesIO()plt.savefig(buf, format="png", dpi=200, bbox_inches="tight", pad_inches=0)plt.close(fig)buf.seek(0)return buf.read()def run_detectree2(tif_file, environment, confidence, tile_w, tile_h, buffer_m, simplify_tol, progress=gr.Progress()):progress(0.02, desc="Preparing workspace")work = tempfile.mkdtemp(prefix="detectree2_")tiles_path = os.path.join(work, "tilespred")os.makedirs(tiles_path, exist_ok=True)# Save upload to disktif_path = os.path.join(work, os.path.basename(tif_file.name))with open(tif_path, "wb") as f:f.write(tif_file.read())# Choose weightsif environment == "Forest":trained_model = MODEL_FORESTelse:# default to forest model unless you add more weights in Dockerfiletrained_model = MODEL_FOREST# Configure model (GPU if available)progress(0.10, desc="Configuring model")cfg = setup_cfg(update_model=trained_model)cfg.MODEL.DEVICE = "cuda" if torch.cuda.is_available() else "cpu"# Tileprogress(0.25, desc="Tiling image")tile_data(tif_path, tiles_path, int(buffer_m), int(tile_w), int(tile_h), dtype_bool=True)# Predictprogress(0.55, desc="Running inference")predictor = DefaultPredictor(cfg)predict_on_data(tiles_path, predictor=predictor)# Geo post-processingprogress(0.75, desc="Vectorizing & stitching crowns")pred_dir = os.path.join(tiles_path, "predictions")geo_dir = os.path.join(tiles_path, "predictions_geo")project_to_geojson(tiles_path, pred_dir, geo_dir)crowns = stitch_crowns(geo_dir, 1)# Clean & filter by confidenceclean = clean_crowns(crowns, 0.6, confidence=0.0)if confidence is not None:clean = clean[clean["Confidence_score"] >= float(confidence)]# Simplify polygons for lighter downloadsif simplify_tol and simplify_tol > 0:clean = clean.set_geometry(clean.simplify(float(simplify_tol)))crowns_gpkg = os.path.join(work, "crowns_out.gpkg")clean.to_file(crowns_gpkg)# Overlay plotprogress(0.92, desc="Rendering overlay")png_bytes = make_plot_png(tif_path, crowns_gpkg)# Outputstotal_trees = int(len(clean))png_path = os.path.join(work, "crowns_out.png")with open(png_path, "wb") as f:f.write(png_bytes)# Return Gradio-friendly objectsreturn png_path, total_trees, crowns_gpkgwith gr.Blocks(title="Detectree2 – Tree Crown Delineation") as demo:gr.Markdown("# 🌳 Detectree2 – Tree Crown Delineation\nUpload a GeoTIFF orthomosaic and get crown polygons + overlay.")with gr.Row():with gr.Column(scale=2):tif_input = gr.File(label="Orthomosaic (GeoTIFF)", file_types=[".tif", ".tiff"], type="binary")environment = gr.Radio(["Forest"], value="Forest", label="Environment / Model")confidence = gr.Slider(0.0, 1.0, value=0.5, step=0.05, label="Confidence threshold")with gr.Accordion("Advanced tiling", open=False):tile_w = gr.Slider(20, 120, value=40, step=5, label="Tile width (m)")tile_h = gr.Slider(20, 120, value=40, step=5, label="Tile height (m)")buffer_m = gr.Slider(0, 60, value=30, step=5, label="Buffer (m)")simplify_tol = gr.Slider(0.0, 1.0, value=0.4, step=0.05, label="Simplify tolerance (map units)")run_btn = gr.Button("Run prediction", variant="primary")with gr.Column(scale=3):out_img = gr.Image(label="Overlay (PNG)", type="filepath")out_count = gr.Number(label="Total trees")out_gpkg = gr.File(label="Crowns (GPKG)")def _run_wrapper(tif_input, environment, confidence, tile_w, tile_h, buffer_m, simplify_tol, progress=gr.Progress()):if tif_input is None:raise gr.Error("Please upload a GeoTIFF first.")return run_detectree2(tif_input, environment, confidence, tile_w, tile_h, buffer_m, simplify_tol, progress)run_btn.click(_run_wrapper,[tif_input, environment, confidence, tile_w, tile_h, buffer_m, simplify_tol],[out_img, out_count, out_gpkg])if __name__ == "__main__":port = int(os.environ.get("PORT", "7860"))demo.queue(concurrency_count=1).launch(server_name="0.0.0.0", server_port=port)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import os, tempfile, shutil, uuid, warningswarnings.filterwarnings("ignore")import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltimport rasteriofrom rasterio.plot import showimport geopandas as gpdimport numpy as npfrom PIL import Imageimport torchimport gradio as grfrom detectron2.engine import DefaultPredictorfrom 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_cfg# --------- Config ---------# Pretrained weights on disk (add more if you have them)WEIGHTS = {"Forest": "/models/230103_randresize_full.pth",# "Urban": "/models/urban_trees_Cambridge_20230630.pth",# "Flexi": "/models/250312_flexi.pth",}DEFAULT_ENV = "Forest"DEVICE = "cuda" if torch.cuda.is_available() else "cpu"# Default tiling params (match tutorial)BUFFER = 30TILE_W = 40TILE_H = 40def run_detectree2(geotiff_path: str, environment: str, conf_threshold: float):"""Full inference pipeline on a single orthomosaic:- Tile image- Predict with Detectron2-based model- Project masks to GeoJSON, stitch & clean crowns- Save crowns to GPKG and render overlay PNGReturns (overlay_png_path, crowns_gpkg_path, stats_dict)"""# Working dir per-requestworkdir = tempfile.mkdtemp(prefix="dtr2_")site_dir = workdir # keep flattiles_dir = os.path.join(site_dir, "tilespred")os.makedirs(tiles_dir, exist_ok=True)try:# Copy input to working dir (keeps original safe)infile = os.path.join(site_dir, os.path.basename(geotiff_path))shutil.copy2(geotiff_path, infile)# 1) Tiletile_data(infile, tiles_dir, BUFFER, TILE_W, TILE_H, dtype_bool=True)# 2) Load weights (fallback to Forest if missing)weights = WEIGHTS.get(environment) or WEIGHTS[DEFAULT_ENV]cfg = setup_cfg(update_model=weights)cfg.MODEL.DEVICE = DEVICEpredictor = DefaultPredictor(cfg)# 3) Predict on all tilespredict_on_data(tiles_dir, predictor=predictor)# 4) Project + stitch + cleanpreds_dir = os.path.join(tiles_dir, "predictions")preds_geo_dir = os.path.join(tiles_dir, "predictions_geo")project_to_geojson(tiles_dir, preds_dir, preds_geo_dir)crowns = stitch_crowns(preds_geo_dir, 1)cleaned = clean_crowns(crowns, 0.6, confidence=0) # keep all, then filter belowcleaned = cleaned[cleaned["Confidence_score"] > float(conf_threshold)]cleaned = cleaned.set_geometry(cleaned.simplify(0.4))# 5) Save GPKGgpkg_path = os.path.join(site_dir, "crowns_out.gpkg")cleaned.to_file(gpkg_path)# 6) Render overlay PNGoverlay_path = os.path.join(site_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)stats = {"total_trees": int(len(cleaned))}return overlay_path, gpkg_path, stats, ""except Exception as e:return None, None, None, f"Error: {e}"# (No finally: keep temp dir so user can download results from returned paths)# --------- Gradio UI ---------def infer(file_path, environment, confidence):return run_detectree2(file_path, environment, confidence)with gr.Blocks(title="Detectree2 – Landscape Prediction") as demo:gr.Markdown("# 🌳 Detectree2 (GPU)\n""Upload a GeoTIFF orthomosaic and get predicted tree crowns as a PNG overlay + a GPKG.\n""Tip: start with a modest area to keep inference quick.")with gr.Row():inp_file = gr.File(label="Orthomosaic (.tif / .tiff)", file_types=[".tif", ".tiff"], type="filepath")env_dd = gr.Dropdown(label="Environment", choices=list(WEIGHTS.keys()), value=DEFAULT_ENV)conf = gr.Slider(0.0, 1.0, value=0.5, step=0.05, label="Confidence threshold")btn = gr.Button("Run prediction", variant="primary")out_img = gr.Image(label="Overlay (PNG)", type="filepath")out_gpkg = gr.File(label="Crowns (GPKG)")out_stats = gr.JSON(label="Statistics")out_err = gr.Textbox(label="Logs / Errors", interactive=False)btn.click(infer, inputs=[inp_file, env_dd, conf],outputs=[out_img, out_gpkg, out_stats, out_err])if __name__ == "__main__":# Spaces provides $PORT; default to 7860 locallyport = int(os.getenv("PORT", "7860"))demo.queue(concurrency_count=1).launch(server_name="0.0.0.0", server_port=port, show_api=False)
Dockerfile+29-33
app.py+122-129