Spaces:
Runtime error
Runtime error
app
Browse files28 unmodified lines29303132333427 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151 unmodified line11711811912012112228 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltimport rasteriofrom rasterio.plot import showimport geopandas as gpd27 unmodified linesworkdir = 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 /tmpos.chdir(workdir)try:infile = os.path.join(workdir, os.path.basename(geotiff_path))shutil.copy2(geotiff_path, infile)# ...weights = WEIGHTS.get(environment) or WEIGHTS[DEFAULT_ENV]cfg = setup_cfg(update_model=weights)# make absolutely sure outputs stay in our temp workspacecfg.MODEL.DEVICE = DEVICEcfg.OUTPUT_DIR = os.path.join(workdir, "train_outputs")os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)predictor = 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)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, driver="GPKG")overlay_path = os.path.join(workdir, "crowns_out.png")# Make sure GDAL uses a writable cacheos.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)stats = {"total_trees": int(len(cleaned))}return overlay_path, gpkg_path, stats, ""1 unmodified lineexcept 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)28 unmodified lines293031323334353627 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401 unmodified line14214314414514614714828 unmodified linesmatplotlib.use("Agg")import matplotlib.pyplot as pltimport globfrom affine import Affineimport rasteriofrom rasterio.plot import showimport geopandas as gpd27 unmodified linesworkdir = 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, (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 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))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 lineexcept 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