Spaces:
Runtime error
Runtime error
app cleanup
Browse files12345678910111213141516171819202122232425262728293031323334353637383940413 unmodified lines454647484950512 unmodified lines545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051 unmodified line10710810911011111211311411511611711811912012112212312412512612712812913010 unmodified lines1411421431441451461471481491501511521531541551561571581593 unmodified lines163164165166167168169# --- 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# Keep HF/torch caches writable and smallos.environ.setdefault("HF_HOME", "/tmp/hf")os.environ.setdefault("TORCH_HOME", "/tmp/torch")# --- Imports ---import warningswarnings.filterwarnings("ignore")import tempfile, shutilimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltimport globfrom affine import Affineimport rasteriofrom rasterio.plot import showimport geopandas as gpdimport numpy as npfrom PIL import Imageimport torchimport gradio as gr3 unmodified linesfrom detectree2.models.predict import predict_on_datafrom detectree2.models.train import setup_cfg# --------- Config ---------WEIGHTS = {"Forest": "/weights/230103_randresize_full.pth",# "Urban": "/weights/urban_trees_Cambridge_20230630.pth",2 unmodified linesDEFAULT_ENV = "Forest"DEVICE = "cuda" if torch.cuda.is_available() else "cpu"# Tiling defaults (roughly align with detectree2 tutorial)BUFFER = 30TILE_W = 40TILE_H = 40def run_detectree2(geotiff_path: str, environment: str, conf_threshold: float):workdir = tempfile.mkdtemp(prefix="dtr2_")tiles_dir = os.path.join(workdir, "tilespred")os.makedirs(tiles_dir, exist_ok=True)os.chdir(workdir) # keep all relative writes in a writable tmptry:infile = os.path.join(workdir, os.path.basename(geotiff_path))shutil.copy2(geotiff_path, infile)# ▶ sanity: must be georeferenced or projection will make nothingwith rasterio.open(infile) as src:if src.crs is None or src.transform == Affine.identity():return None, None, None, "Error: input GeoTIFF has no CRS/transform."# tile (use defaults; avoid dtype_bool=True for imagery tiles)tile_data(infile, tiles_dir, BUFFER, TILE_W, TILE_H)weights = WEIGHTS.get(environment) or WEIGHTS[DEFAULT_ENV]cfg = setup_cfg(update_model=weights)cfg.MODEL.DEVICE = DEVICE# ▶ lower test threshold so we actually emit predictionscfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = float(os.getenv("DTR2_SCORE_THRESH", "0.25"))# ▶ keep detectron outputs containedcfg.OUTPUT_DIR = os.path.join(workdir, "train_outputs")os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)predictor = DefaultPredictor(cfg)# run predictions on tilespredict_on_data(tiles_dir, predictor=predictor)# ▶ robustly locate where predict_on_data wrote JSONscand_pred_dirs = [os.path.join(tiles_dir, "predictions"),os.path.join(cfg.OUTPUT_DIR, "predictions"),os.path.join(workdir, "predictions"),]preds_dir = next((d for d in cand_pred_dirs if os.path.isdir(d)), None)if not preds_dir:return None, None, None, f"Error: no predictions folder found under {cand_pred_dirs}"if not glob.glob(os.path.join(preds_dir, "*.json")):return None, None, None, (1 unmodified linef"Try lowering SCORE_THRESH_TEST (now {cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST}).")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)# ▶ verify projections exist before stitchinggeos = glob.glob(os.path.join(preds_geo_dir, "*.geojson"))if not geos:return None, None, None, f"Error: No geojson files found in {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)].set_geometry(cleaned.simplify(0.4))gpkg_path = os.path.join(workdir, "crowns_out.gpkg")cleaned.to_file(gpkg_path, driver="GPKG")overlay_path = os.path.join(workdir, "crowns_out.png")with rasterio.open(infile) as src:fig, ax = plt.subplots(figsize=(10, 10))10 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)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")3 unmodified linesout_stats = gr.JSON(label="Statistics")out_err = gr.Textbox(label="Logs / Errors", interactive=False)# Use per-event concurrency limit to keep GPU happy on Spacesbtn.click(infer,inputs=[inp_file, env_dd, conf],12345678910111213141516171819202122233 unmodified lines272829303132332 unmodified lines36373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687881 unmodified line9091929394959697989910010110210310410510610710810911011111211311411511610 unmodified lines1271281291301311321331341351361371381391401411421433 unmodified lines147148149150151152# environment setupimport osval = 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", "/tmp/hf")os.environ.setdefault("TORCH_HOME", "/tmp/torch")import tempfile, shutil, globimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom affine import Affineimport rasteriofrom rasterio.plot import showimport torchimport gradio as gr3 unmodified linesfrom detectree2.models.predict import predict_on_datafrom detectree2.models.train import setup_cfg# configWEIGHTS = {"Forest": "/weights/230103_randresize_full.pth",# "Urban": "/weights/urban_trees_Cambridge_20230630.pth",2 unmodified linesDEFAULT_ENV = "Forest"DEVICE = "cuda" if torch.cuda.is_available() else "cpu"# Keep PyTorch from oversubscribing CPUtry:torch.set_num_threads(1)torch.set_num_interop_threads(1)except Exception:pass# Tiling defaultsBUFFER, TILE_W, TILE_H = 30, 40, 40def run_detectree2(geotiff_path: str, environment: str, conf_threshold: float):workdir = tempfile.mkdtemp(prefix="dtr2_")tiles_dir = os.path.join(workdir, "tilespred")os.makedirs(tiles_dir, exist_ok=True)os.chdir(workdir)try:infile = os.path.join(workdir, os.path.basename(geotiff_path))shutil.copy2(geotiff_path, infile)# Must be georeferencedwith rasterio.open(infile) as src:if src.crs is None or src.transform == Affine.identity():return None, None, None, "Error: input GeoTIFF has no CRS/transform."tile_data(infile, tiles_dir, BUFFER, TILE_W, TILE_H)weights = WEIGHTS.get(environment) or WEIGHTS[DEFAULT_ENV]cfg = setup_cfg(update_model=weights)cfg.MODEL.DEVICE = DEVICEcfg.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)with torch.inference_mode():predict_on_data(tiles_dir, predictor=predictor)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 = dbreakelse:return None, None, None, "Error: no predictions folder found."if not glob.glob(os.path.join(preds_dir, "*.json")):return None, None, None, (1 unmodified linef"Try lowering SCORE_THRESH_TEST (now {cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST}).")# project to geojsonpreds_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, None, f"Error: No geojson files found in {preds_geo_dir}."# stitch + clean + filtercrowns = stitch_crowns(preds_geo_dir, 1)cleaned = clean_crowns(crowns, 0.6, confidence=0)cleaned = cleaned[cleaned["Confidence_score"] > float(conf_threshold)].set_geometry(cleaned.simplify(0.4))# save vectorgpkg_path = os.path.join(workdir, "crowns_out.gpkg")cleaned.to_file(gpkg_path, driver="GPKG")# save overlayoverlay_path = os.path.join(workdir, "crowns_out.png")with rasterio.open(infile) as src:fig, ax = plt.subplots(figsize=(10, 10))10 unmodified linesexcept Exception as e:return None, None, None, f"Error: {e}"def infer(file_path, environment, confidence):return run_detectree2(file_path, environment, confidence)# gradio uiwith gr.Blocks(title="Detectree2 – Landscape Prediction") as demo:gr.Markdown("Detectree2\n""Upload a GeoTIFF and get predicted tree crowns as a PNG overlay + a GPKG.")with gr.Row():inp_file = gr.File(label="Input (.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")3 unmodified linesout_stats = gr.JSON(label="Statistics")out_err = gr.Textbox(label="Logs / Errors", interactive=False)btn.click(infer,inputs=[inp_file, env_dd, conf],
app.py+32-49