Spaces:
Runtime error
Runtime error
app
Browse files28 unmodified lines293031323334353627 unmodified lines6465666566676768697071727373747576777879808182767783848586878889909184929394878895969798991001011021031041051061071081091101111121131141151161171181191201219495122123124125971261271281291021031041051061071081091101111121301311321331341351361371381391401 unmodified line14214314414514614714828 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as plt
import globfrom affine import Affineimport rasteriofrom rasterio.plot import showimport geopandas as gpd27 unmodified lines workdir = tempfile.mkdtemp(prefix="dtr2_") tiles_dir = os.path.join(workdir, "tilespred") os.makedirs(tiles_dir, exist_ok=True)
# 👇 Add this so any relative writes (like "./train_outputs") land in /tmp os.chdir(workdir) os.chdir(workdir) # keep all relative writes in a writable tmp
try: infile = os.path.join(workdir, os.path.basename(geotiff_path)) shutil.copy2(geotiff_path, infile)
# ... # ▶ sanity: must be georeferenced or projection will make nothing with 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)
# make absolutely sure outputs stay in our temp workspace cfg.MODEL.DEVICE = DEVICE # ▶ lower test threshold so we actually emit predictions cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = float(os.getenv("DTR2_SCORE_THRESH", "0.25")) # ▶ keep detectron outputs contained cfg.OUTPUT_DIR = os.path.join(workdir, "train_outputs") os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)
predictor = DefaultPredictor(cfg)
# 3) Predict on all tiles # run predictions on tiles predict_on_data(tiles_dir, predictor=predictor)
# 4) Project + stitch + clean preds_dir = os.path.join(tiles_dir, "predictions") # ▶ robustly locate where predict_on_data wrote JSONs cand_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, ( f"Error: no prediction JSONs in {preds_dir}. " f"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 stitching 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}."
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)) cleaned = cleaned[cleaned["Confidence_score"] > float(conf_threshold)].set_geometry( cleaned.simplify(0.4) )
# 5) Save outputs 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") # Make sure GDAL uses a writable cache os.environ.setdefault("GDAL_CACHEMAX", "64") with rasterio.Env(): 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) 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, ""1 unmodified line except 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)app.py+49-23