Spaces:
Runtime error
Runtime error
tiling
Browse files19 unmodified lines20212223242556 unmodified lines828384858687888990915 unmodified lines9798991001011021031041051061071081091102 unmodified lines11311411511611711811912012118 unmodified lines1401411421431441451461 unmodified line1481491501511521531547 unmodified lines16216316416516616716816919 unmodified linesfrom rasterio.plot import showimport torchimport gradio as grimport mathimport numpy as np56 unmodified lines# 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:5 unmodified linesif src.crs is None or src.transform == Affine.identity():return None, None, None, "Error: input GeoTIFF has no CRS/transform."padded = pad_for_tiling(infile, BUFFER, TILE_W, TILE_H)tile_data(padded, 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)2 unmodified lineswith 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 = dbreak18 unmodified lines# 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))1 unmodified linegpkg_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))7 unmodified linesstats = {"total_trees": int(len(cleaned))}return overlay_path, gpkg_path, stats, ""except Exception as e:return None, None, None, f"Error: {e}"def infer(file_path, environment, confidence):return run_detectree2(file_path, environment, confidence)19 unmodified lines2021222324252656 unmodified lines83848586878889909192939495969798991001015 unmodified lines1071081091101111121131141151161171181191201211221231241251262 unmodified lines12913013113213313413513613713813918 unmodified lines1581591601611621631641 unmodified line1661671681691701711727 unmodified lines18018118218318418518618718818919 unmodified linesfrom rasterio.plot import showimport torchimport gradio as grimport tracebackimport mathimport numpy as np56 unmodified lines# Tiling defaultsBUFFER, TILE_W, TILE_H = 30, 40, 40def run_detectree2(geotiff_path: str, environment: str, conf_threshold):if environment not in WEIGHTS:return None, None, None, f"Error: unknown environment {environment!r}. Options: {list(WEIGHTS)}"try:conf_threshold = float(conf_threshold)except Exception:return None, None, None, f"Error: confidence is not numeric ({conf_threshold!r})"workdir = tempfile.mkdtemp(prefix="dtr2_")tiles_dir = os.path.join(workdir, "tilespred")os.makedirs(tiles_dir, exist_ok=True)cwd = os.getcwd()os.chdir(workdir)try:5 unmodified linesif src.crs is None or src.transform == Affine.identity():return None, None, None, "Error: input GeoTIFF has no CRS/transform."# pad before tiling to avoid dropped partial tiles at edgespadded = pad_for_tiling(infile, BUFFER, TILE_W, TILE_H)tile_data(padded, tiles_dir, BUFFER, TILE_W, TILE_H)weights = WEIGHTS.get(environment) or WEIGHTS[DEFAULT_ENV]if not os.path.exists(weights):return None, None, None, f"Error: weights not found at {weights}. Upload to {WEIGHT_DIR}"cfg = setup_cfg(update_model=weights)cfg.MODEL.DEVICE = DEVICEtry:cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = float(os.getenv("DTR2_SCORE_THRESH", "0.25"))except Exception:cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.25cfg.OUTPUT_DIR = os.path.join(workdir, "train_outputs")os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)2 unmodified lineswith 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 = dbreak18 unmodified lines# stitch + clean + filtercrowns = stitch_crowns(preds_geo_dir, 1)cleaned = clean_crowns(crowns, 0.6, confidence=0)cleaned = cleaned[cleaned["Confidence_score"] > conf_threshold].set_geometry(cleaned.simplify(0.4))1 unmodified linegpkg_path = os.path.join(workdir, "crowns_out.gpkg")cleaned.to_file(gpkg_path, driver="GPKG")# save overlay (draw on original, not padded)overlay_path = os.path.join(workdir, "crowns_out.png")with rasterio.open(infile) as src:fig, ax = plt.subplots(figsize=(10, 10))7 unmodified linesstats = {"total_trees": int(len(cleaned))}return overlay_path, gpkg_path, stats, ""except Exception:return None, None, None, "Error:\n" + traceback.format_exc()finally:os.chdir(cwd)def infer(file_path, environment, confidence):return run_detectree2(file_path, environment, confidence)
app.py+30-10