vicoffee-coffee-mapper / vicoffee_predict_app.py
minhcreus's picture
Upload 5 files
5886412 verified
Raw History Blame Contribute Delete
12.7 kB
"""ViCoffee coffee-map web app (Gradio).
PC: python vicoffee_predict_app.py --weights <weights zip or session bundle> [--data <folder with the ViCoffee h5 files>] [--share]
molab: use vicoffee_predict_molab.py, which starts this app and prints a public link."""
import argparse, json, tempfile, time
from pathlib import Path
import numpy as np
import gradio as gr
from PIL import Image
import vicoffee_predict_core as C
YEARS = ["2023", "2024", "2025"]
def _summary(prob, dates_used, year, W, extra=""):
pred = prob >= 0.5
ha = pred.sum() * 0.01 # 10 m pixels
n_models = len(W["models"])
lines = [f"**{year}** · {len(dates_used)} dates ({dates_used[0]} to {dates_used[-1]}) · {prob.shape[0]}×{prob.shape[1]} px",
f"**Coffee: {pred.mean() * 100:.1f}% of the area, {ha:.1f} ha**",
f"Model: MAESTRO Tiny setup H, {W['kind']}, average of {n_models} fold model{'s' if n_models > 1 else ''}."]
if extra:
lines.append(extra)
return "\n\n".join(lines)
def _files(prob, rgb, profile, stem):
out = Path(tempfile.mkdtemp())
tif, png = out / f"{stem}_coffee.tif", out / f"{stem}_coffee.png"
C.write_geotiff(tif, prob, profile)
Image.fromarray(C.overlay(rgb, prob >= 0.5)).save(png)
return [str(tif), str(png)]
def run_series(W, d, year, tta, remove_offset, progress):
ys = C.split_years(d["dates"])
if not year:
year = max(ys, key=lambda y: len(ys[y]))
if year not in ys:
raise gr.Error(f"No dates in {year}. Years in the data: {', '.join(f'{y} ({len(i)})' for y, i in ys.items())}")
idx = ys[year]
X, clear = d["X"][idx], d["clear"][idx]
if remove_offset:
X = np.maximum(X - 1000, 0)
doy = np.array([C.doy_of(d["dates"][i]) for i in idx])
note = C.check_scale(X, clear)
warn = []
if note:
warn.append("⚠ " + note)
if len(idx) < 16:
warn.append(f"⚠ Only {len(idx)} dates in {year}; the model was trained on 70-84 dates a year (16 are used per prediction).")
if d.get("scl") is None and "clear" not in d.get("given", ()):
warn.append("⚠ No SCL band, so clouds are not masked.")
clear_frac = clear.mean()
t0 = time.time()
prob = C.predict(W, X, clear, doy, tta=tta, progress=lambda f: progress(f, desc="predicting"))
rgb = C.rgb_composite(X, clear, doy)
extra = f"{clear_frac * 100:.0f}% of pixels clear across dates · {time.time() - t0:.0f} s" + ("".join("\n\n" + w for w in warn))
return prob, rgb, [d["dates"][i] for i in idx], year, extra
def build(W, data=None, site_models=None):
Ws = dict(W, models=site_models or W["models"]) # site check needs the fold that held the site out
with gr.Blocks(title="ViCoffee coffee mapper") as demo:
gr.Markdown("# ViCoffee coffee mapper\nMAESTRO Tiny, pretrained on unlabelled Sentinel-2 over Kon Tum and fine-tuned on the ViCoffee sites. "
"Give it one year of Sentinel-2 L2A images and it maps coffee at 10 m.")
with gr.Tab("Upload images"):
gr.Markdown("A **.zip of GeoTIFFs, one per date** (date in the file name, bands B2 B3 B4 B5 B6 B7 B8 B8A B11 B12, optional 11th band SCL, "
"10 m, values ×10000 as in S2_SR_HARMONIZED), or one **.npz / .h5** with `X` (T,10,H,W), `dates` and `SCL`.")
with gr.Row():
with gr.Column(scale=1):
up = gr.File(label="Sentinel-2 series", file_count="multiple", file_types=[".zip", ".tif", ".tiff", ".npz", ".h5"])
up_year = gr.Textbox(label="Year (empty = the year with most dates)", max_lines=1)
up_off = gr.Checkbox(label="Remove the 1000 offset (baseline 04.00+ data that is not harmonized)")
up_tta = gr.Checkbox(label="Test-time augmentation (8 views x 4 date draws, slower, a bit better)")
up_btn = gr.Button("Map coffee", variant="primary")
with gr.Column(scale=2):
with gr.Row():
up_map = gr.Image(label="Coffee (amber) on the dry-season image", type="numpy")
up_prob = gr.Image(label="Coffee probability (blue 0 to amber 1)", type="numpy")
up_txt = gr.Markdown()
up_files = gr.File(label="Download: GeoTIFF (band 1 class, band 2 probability %) and PNG", file_count="multiple")
def do_upload(files, year, off, tta, progress=gr.Progress()):
if not files:
raise gr.Error("Add a file first.")
try:
d = C.read_upload([f if isinstance(f, str) else f.name for f in files])
except Exception as e:
raise gr.Error(str(e))
prob, rgb, used, year, extra = run_series(W, d, year.strip(), tta, off, progress)
return (C.upscale(C.overlay(rgb, prob >= 0.5)), C.upscale(C.prob_image(prob)),
_summary(prob, used, year, W, extra), _files(prob, rgb, d["profile"], f"upload_{year}"))
up_btn.click(do_upload, [up, up_year, up_off, up_tta], [up_map, up_prob, up_txt, up_files])
with gr.Tab("Fetch by location"):
gr.Markdown("Downloads the Sentinel-2 L2A series for one year around a point from Earth Search (AWS open data, no account). "
"About 1 minute per 10 dates for a 2 km square.")
with gr.Row():
with gr.Column(scale=1):
lat = gr.Number(label="Latitude", value=14.436)
lon = gr.Number(label="Longitude", value=107.908)
size = gr.Slider(0.5, 6, value=2, step=0.5, label="Square side (km)")
fy = gr.Dropdown(["2019", "2020", "2021", "2022", "2023", "2024", "2025"], value="2025", label="Year")
cloud = gr.Slider(10, 100, value=90, step=5, label="Skip scenes cloudier than (%)")
f_tta = gr.Checkbox(label="Test-time augmentation (slower)")
f_btn = gr.Button("Fetch and map coffee", variant="primary")
with gr.Column(scale=2):
with gr.Row():
f_map = gr.Image(label="Coffee (amber) on the dry-season image", type="numpy")
f_prob = gr.Image(label="Coffee probability", type="numpy")
f_txt = gr.Markdown()
f_files = gr.File(label="Download", file_count="multiple")
def do_fetch(la, lo, s, y, cc, tta, progress=gr.Progress()):
try:
d = C.fetch_s2(float(la), float(lo), float(s), int(y), max_cloud=cc,
progress=lambda f, msg: progress(f * 0.8, desc=msg))
except Exception as e:
raise gr.Error(f"Download failed: {e}")
d["given"] = ("clear",)
prob, rgb, used, year, extra = run_series(W, d, str(y), tta, False,
lambda f, desc="": progress(0.8 + 0.2 * f, desc=desc))
return (C.upscale(C.overlay(rgb, prob >= 0.5)), C.upscale(C.prob_image(prob)),
_summary(prob, used, year, W, extra), _files(prob, rgb, d["profile"], f"fetch_{la:.4f}_{lo:.4f}_{y}"))
f_btn.click(do_fetch, [lat, lon, size, fy, cloud, f_tta], [f_map, f_prob, f_txt, f_files])
if data is not None:
with gr.Tab("Check on a ViCoffee site"):
gr.Markdown("Proof against the real labels: each site is mapped by the fold model that **never trained on it** "
"(the site was a test site in that fold), then scored against the 2023-2025 coffee labels.")
with gr.Row():
with gr.Column(scale=1):
site = gr.Dropdown(data["sites"], value=data["sites"][0], label="Site")
yrs = data.get("years", YEARS)
sy = gr.Dropdown(yrs, value=yrs[-1], label="Year")
s_tta = gr.Checkbox(label="Test-time augmentation (as in the reported scores)", value=True)
s_btn = gr.Button("Map and score", variant="primary")
with gr.Column(scale=2):
with gr.Row():
s_lab = gr.Image(label="Label (amber coffee, grey ignored)", type="numpy")
s_pred = gr.Image(label="Prediction", type="numpy")
s_err = gr.Image(label="Errors (red: false coffee, purple: missed coffee)", type="numpy")
s_txt = gr.Markdown()
def do_site(p, y, tta, progress=gr.Progress()):
fold = next(f for f, t in C.FOLD_TEST.items() if p in t)
if fold not in Ws["models"]:
raise gr.Error(f"Fold {fold} weights are missing, so {p} can't be checked fairly.")
try:
X, clear, lab, doy = data["load"](p, y)
except KeyError:
raise gr.Error(f"No {y} data for {p}.")
prob = C.predict(Ws, X, clear, doy, tta=tta, folds=[fold], progress=lambda f: progress(f, desc="predicting"))
pred = (prob >= 0.5).astype(np.uint8)
rgb = C.rgb_composite(X, clear, doy)
m, (iou0, iou1) = C.miou(pred, lab)
labimg = C.overlay(rgb, lab == 1)
labimg[lab == 255] = (labimg[lab == 255] * 0.4 + 90).astype(np.uint8)
err = (rgb * 0.45).astype(np.uint8)
ok = lab != 255
err[ok & (pred == 1) & (lab == 0)] = (220, 50, 50)
err[ok & (pred == 0) & (lab == 1)] = (150, 80, 210)
txt = (f"**{p}, {y}: mIoU {m * 100:.1f}%** (coffee IoU {iou1 * 100:.1f}, non-coffee IoU {iou0 * 100:.1f}) · "
f"fold {fold} model ({W['kind']}), trained on other sites only. Accuracy on scored pixels: "
f"{(pred[ok] == lab[ok]).mean() * 100:.1f}%.")
return C.upscale(labimg), C.upscale(C.overlay(rgb, pred == 1)), C.upscale(err), txt
s_btn.click(do_site, [site, sy, s_tta], [s_lab, s_pred, s_err, s_txt])
gr.Markdown(f"<small>Weights: {W['kind']} · folds {sorted(W['models'])} · device {C.DEVICE}</small>")
return demo
def load_vicoffee(folder):
"""Site check data from the ViCoffee h5 files (s2_10m_2023_2025.h5, labels_10m.h5)."""
import h5py
folder = Path(folder)
s2 = next(iter(sorted(folder.rglob("s2_10m_2023_2025.h5"))), None)
lb = next(iter(sorted(folder.rglob("labels_10m.h5"))), None)
if s2 is None or lb is None:
return None
f, L = h5py.File(s2, "r"), h5py.File(lb, "r")
dates = [d.decode() if isinstance(d, bytes) else str(d) for d in f["dates"][:]]
tidx = {y: np.array([i for i, d in enumerate(dates) if d[:4] == y]) for y in YEARS}
doy = {y: np.array([C.doy_of(dates[i]) for i in t]) for y, t in tidx.items()}
def load(p, y):
t = tidx[y]
X = f[f"labeled/{p}/X"][:][t].astype("f4")
clear = np.isin(f[f"labeled/{p}/SCL"][:][t], C.CLEAR_SCL)
return X, clear, L[p]["label"][:][YEARS.index(y)], doy[y]
return dict(sites=sorted(L.keys()), load=load)
def load_samples(folder):
"""Site check data from sample files <site>_<year>.npz (X, SCL, dates) plus labels_10m.h5."""
import h5py, re
folder = Path(folder)
lb = next(iter(sorted(folder.rglob("labels_10m.h5"))), None)
files = {m.groups(): f for f in sorted(folder.rglob("p*_20*.npz")) if (m := re.fullmatch(r"(p\d\d)_(20\d\d)\.npz", f.name))}
if lb is None or not files:
return None
L = h5py.File(lb, "r")
def load(p, y):
d = C.read_upload([files[(p, y)]])
doy = np.array([C.doy_of(x) for x in d["dates"]])
return d["X"], d["clear"], L[p]["label"][:][YEARS.index(y)], doy
return dict(sites=sorted({p for p, _ in files}), years=sorted({y for _, y in files}), load=load)
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--weights", nargs="+", required=True, help="weights zip, session bundle zip, or folders")
ap.add_argument("--data", help="folder holding s2_10m_2023_2025.h5 and labels_10m.h5 (enables the site check)")
ap.add_argument("--share", action="store_true", help="public gradio.live link")
a = ap.parse_args()
W = C.load_models(a.weights)
build(W, load_vicoffee(a.data) if a.data else None).launch(share=a.share)