Spaces:
Runtime error
Runtime error
fix
Browse filesFiles changed (2)
- Dockerfile+19-9
- app.py+49-38
123456789101112131415161718192021222324252627282930313233341 unmodified line36373839404142434445FROM nvidia/cuda:11.1.1-cudnn8-runtime-ubuntu20.04ENV DEBIAN_FRONTEND=noninteractive \PIP_NO_CACHE_DIR=1 \FORCE_CUDA=1 \# make logs quiet + speed up matplotlibMPLCONFIGDIR=/tmp/matplotlib \# avoid libgomp complaintOMP_NUM_THREADS=1 MKL_NUM_THREADS=1 NUMEXPR_NUM_THREADS=1 \GRADIO_SERVER_NAME=0.0.0.0RUN 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/* && mkdir -p /tmp/matplotlib# Keep setuptools old enough for torch 1.x wheel toolingRUN python3 -m pip install --upgrade pip setuptools==59.5.0 wheel# --- Pin Pillow BEFORE detectron2 to avoid Pillow 10+ breakage ---RUN python3 -m pip install "pillow==9.5.0"# Core ML stack (Torch 1.x + cu111 + D2 0.6)RUN python3 -m pip install --extra-index-url https://download.pytorch.org/whl/cu111 \torch==1.10.0+cu111 torchvision==0.11.1+cu111RUN python3 -m pip install -f \https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/torch1.10/index.html \detectron2==0.6# Geospatial + UIRUN python3 -m pip install \gradio==4.* rasterio geopandas shapely matplotlib pillow==9.5.0 \"git+https://github.com/PatBall1/detectree2.git"1 unmodified lineWORKDIR /appCOPY app.py /app/app.py# Pretrained modelRUN mkdir -p /models && \wget -q -O /models/230103_randresize_full.pth \https://zenodo.org/records/10522461/files/230103_randresize_full.pthEXPOSE 7860CMD ["python3", "app.py"]1234567891011121314151617181920212223242526272829303132333435363738391 unmodified line414243444546474849505152535455# Torch 1.10 (cu111) + Detectron2 0.6 on CUDA 11.1, tuned for Hugging Face Spaces (Docker SDK)FROM nvidia/cuda:11.1.1-cudnn8-runtime-ubuntu20.04ENV DEBIAN_FRONTEND=noninteractive \PIP_NO_CACHE_DIR=1 \FORCE_CUDA=1 \# Writable matplotlib config/cache (avoid warnings & speed imports)MPLCONFIGDIR=/var/tmp/matplotlib \# Keep OpenMP/mkl threads sane in containerized envsOMP_NUM_THREADS=1 MKL_NUM_THREADS=1 NUMEXPR_NUM_THREADS=1 \# Gradio binding for HF SpacesGRADIO_SERVER_NAME=0.0.0.0# System deps (GDAL, OpenCV runtime, 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/* \&& mkdir -p /var/tmp/matplotlib && chmod -R 777 /var/tmp/matplotlib# Pip tooling (torch 1.x build expects older setuptools)RUN python3 -m pip install --upgrade pip setuptools==59.5.0 wheel# --- IMPORTANT: pin Pillow < 10 to avoid PIL.Image.LINEAR break in Detectron2 0.6 ---RUN python3 -m pip install "pillow==9.5.0"# Core ML stack: Torch 1.10 + cu111 + torchvision 0.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 0.6 prebuilt wheels for torch 1.10/cu111RUN python3 -m pip install -f \https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/torch1.10/index.html \detectron2==0.6# Geospatial + UI + detectree2RUN python3 -m pip install \gradio==4.* rasterio geopandas shapely matplotlib pillow==9.5.0 \"git+https://github.com/PatBall1/detectree2.git"1 unmodified lineWORKDIR /appCOPY app.py /app/app.py# Pretrained model(s). Default: ForestRUN mkdir -p /models && \wget -q -O /models/230103_randresize_full.pth \https://zenodo.org/records/10522461/files/230103_randresize_full.pth# To add more:# RUN wget -q -O /models/urban_trees_Cambridge_20230630.pth https://zenodo.org/records/10522461/files/urban_trees_Cambridge_20230630.pth# RUN wget -q -O /models/250312_flexi.pth https://zenodo.org/records/15014353/files/250312_flexi.pth# Spaces proxies 7860 unless overridden by README app_portEXPOSE 7860CMD ["python3", "app.py"]
1234567893 unmodified lines131415161718194 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071725 unmodified lines787980818283848586878889909192939495969798994 unmodified lines1041051061071081091101111124 unmodified lines1171181191201211221231241251261271281 unmodified line130131132133134135136137138139import os, tempfile, shutil, uuid, warningsos.environ.setdefault("OMP_NUM_THREADS", "1")os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib")os.makedirs(os.environ["MPLCONFIGDIR"], exist_ok=True)warnings.filterwarnings("ignore")import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as plt3 unmodified linesimport geopandas as gpdimport numpy as npfrom PIL import Imageimport torchimport gradio as gr4 unmodified linesfrom 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 tiles5 unmodified linesproject_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)4 unmodified linesexcept 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)4 unmodified lines"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")1 unmodified lineout_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)12345678910111213141516171819202122232425263 unmodified lines3031323334354 unmodified lines40414243444546474849505152535455565758596061626364656667686970717273747576777879805 unmodified lines86878889909192939495969798991001011021031041054 unmodified lines1101111121131141154 unmodified lines1201211221231241251261271281291 unmodified line131132133134135136137138139140141142143144145146147148149150# --- Harden environment EARLY (before heavy imports) ---import os# Some platforms inject invalid OMP values (e.g., "3500m"); libgomp requires intval = os.environ.get("OMP_NUM_THREADS", "")try:int(val)except Exception:os.environ["OMP_NUM_THREADS"] = "1"# Ensure matplotlib has a writable config/cache diros.environ.setdefault("MPLCONFIGDIR", "/var/tmp/matplotlib")try:os.makedirs(os.environ["MPLCONFIGDIR"], exist_ok=True)os.chmod(os.environ["MPLCONFIGDIR"], 0o777)except Exception:pass# --- Imports ---import warningswarnings.filterwarnings("ignore")import tempfile, shutilimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as plt3 unmodified linesimport geopandas as gpdimport numpy as npfrom PIL import Imageimport torchimport gradio as gr4 unmodified linesfrom detectree2.models.train import setup_cfg# --------- Config ---------WEIGHTS = {"Forest": "/models/230103_randresize_full.pth",# "Urban": "/models/urban_trees_Cambridge_20230630.pth", # uncomment if added in Dockerfile# "Flexi": "/models/250312_flexi.pth", # uncomment if added in Dockerfile}DEFAULT_ENV = "Forest"DEVICE = "cuda" if torch.cuda.is_available() else "cpu"# Tiling defaults (roughly match detectree2 tutorial)BUFFER = 30TILE_W = 40TILE_H = 40def run_detectree2(geotiff_path: str, environment: str, conf_threshold: float):"""1) Tile TIFF, 2) Predict with Detectron2 model, 3) Project & stitch crowns,4) Clean, 5) Save GPKG + render overlay PNG.Returns (overlay_png_path, crowns_gpkg_path, stats_dict, log_str_or_empty)"""workdir = tempfile.mkdtemp(prefix="dtr2_")tiles_dir = os.path.join(workdir, "tilespred")os.makedirs(tiles_dir, exist_ok=True)try:# Copy input to working dirinfile = os.path.join(workdir, 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) Config + predictorweights = WEIGHTS.get(environment) or WEIGHTS[DEFAULT_ENV]cfg = setup_cfg(update_model=weights)cfg.MODEL.DEVICE = DEVICEpredictor = DefaultPredictor(cfg)# 3) Predict on all tiles5 unmodified linesproject_to_geojson(tiles_dir, preds_dir, preds_geo_dir)crowns = stitch_crowns(preds_geo_dir, 1)cleaned = clean_crowns(crowns, 0.6, confidence=0)cleaned = cleaned[cleaned["Confidence_score"] > float(conf_threshold)]cleaned = cleaned.set_geometry(cleaned.simplify(0.4))# 5) Save outputsgpkg_path = os.path.join(workdir, "crowns_out.gpkg")cleaned.to_file(gpkg_path)overlay_path = os.path.join(workdir, "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)4 unmodified linesexcept Exception as e:return None, None, None, f"Error: {e}"# --------- Gradio UI ---------def infer(file_path, environment, confidence):return run_detectree2(file_path, environment, confidence)4 unmodified lines"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")1 unmodified lineout_stats = gr.JSON(label="Statistics")out_err = gr.Textbox(label="Logs / Errors", interactive=False)# New API: limit concurrency per-event (deprecated: concurrency_count on .queue)btn.click(infer,inputs=[inp_file, env_dd, conf],outputs=[out_img, out_gpkg, out_stats, out_err],concurrency_limit=1,)if __name__ == "__main__":port = int(os.getenv("PORT", "7860"))# No deprecated args; optionally cap worker threads globallydemo.queue().launch(server_name="0.0.0.0",server_port=port,max_threads=1,show_api=False,)
Dockerfile+19-9
app.py+49-38