Spaces:
Runtime error
Runtime error
revert
Browse files19 unmodified lines20212223242526272829301 unmodified line323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899018 unmodified lines1091101111121131141151161171181191201211221231241251261275 unmodified lines1331341351361371381391401411421431441451461471481491501511522 unmodified lines15515615715815916016116216316416510 unmodified lines1761771781791801811821831841851861871881891901911921931941951961971981992002011 unmodified line2032042052062072082097 unmodified lines21721821922022122222322422522619 unmodified linesfrom rasterio.plot import showimport torchimport gradio as grimport tracebackimport reimport mathimport numpy as npfrom detectron2.engine import DefaultPredictorfrom detectree2.preprocessing.tiling import tile_data1 unmodified linefrom detectree2.models.predict import predict_on_datafrom detectree2.models.train import setup_cfgdef pad_for_tiling(src_path, buffer_m, tile_w_m, tile_h_m):# pads so its dimensions are multiples of tile sizewith rasterio.open(src_path) as src:res_x, res_y = src.res # meters/pixel (positive values)tw_px = max(1, int(round(tile_w_m / res_x)))th_px = max(1, int(round(tile_h_m / abs(res_y))))new_w = math.ceil(src.width / tw_px) * tw_pxnew_h = math.ceil(src.height / th_px) * th_pxif new_w == src.width and new_h == src.height:return src_path # already aligneddata = src.read() # (bands, H, W)pad_w = new_w - src.widthpad_h = new_h - src.heightdata_padded = np.pad(data, ((0,0), (0,pad_h), (0,pad_w)), mode="edge")prof = src.profileprof.update(width=new_w, height=new_h)padded_path = src_path + ".padded.tif"with rasterio.open(padded_path, "w", **prof) as dst:dst.write(data_padded)return padded_pathdef _sanitize_geojson_filenames(dirpath):changed = 0for p in glob.glob(os.path.join(dirpath, "*.geojson")):base = os.path.basename(p)nums = re.findall(r"-?\d+", base) # grab all integers anywhere# ensure we have exactly 5 integersif len(nums) < 5:nums = (["0"] * (5 - len(nums))) + numselse:nums = nums[-5:]target = "_".join(nums) + ".geojson"if target != base:dst = os.path.join(dirpath, target)# avoid collisionsif os.path.exists(dst):k = 1root = "_".join(nums)while os.path.exists(os.path.join(dirpath, f"{root}__{k}.geojson")):k += 1dst = os.path.join(dirpath, f"{root}__{k}.geojson")os.replace(p, dst)changed += 1return changed# configWEIGHT_DIR = os.getenv("DTR2_WEIGHT_DIR", "/data/weights")os.makedirs(WEIGHT_DIR, exist_ok=True)18 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 = dbreak10 unmodified linespreds_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)_sanitize_geojson_filenames(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}."bad = [os.path.basename(g)for g in geosif not re.fullmatch(r"-?\d+_-?\d+_-?\d+_-?\d+_-?\d+\.geojson", os.path.basename(g))]if bad:return None, None, None, "Error: Unexpected GeoJSON names (need 5 integers): " + ", ".join(bad)# 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)19 unmodified lines2021222324251 unmodified line27282930313218 unmodified lines515253545556575859605 unmodified lines6667686970717273747576772 unmodified lines80818283848586878810 unmodified lines991001011021031041051061071081091101111121131 unmodified line1151161171181191201217 unmodified lines12913013113213313413513619 unmodified linesfrom rasterio.plot import showimport torchimport gradio as grfrom detectron2.engine import DefaultPredictorfrom detectree2.preprocessing.tiling import tile_data1 unmodified linefrom detectree2.models.predict import predict_on_datafrom detectree2.models.train import setup_cfg# configWEIGHT_DIR = os.getenv("DTR2_WEIGHT_DIR", "/data/weights")os.makedirs(WEIGHT_DIR, exist_ok=True)18 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."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)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 = dbreak10 unmodified linespreds_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))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)
app.py+10-100