# Background NDVI trend jobs: Theil-Sen + Mann-Kendall, poll status, download GeoTIFF results
JOBS: dict = {}
# Job request schema (needs at least 10 years)
class TrendRequest(BaseModel):
district: str
start_year: int = Field(2001, ge=2001, le=2024)
end_year: int = Field(2024, ge=2001, le=2024)
@model_validator(mode="after")
def at_least_ten_years(self):
if self.end_year - self.start_year < 9:
raise ValueError("a trend needs at least 10 years (end_year - start_year >= 9)")
return self
# Worker: annual-max Theil-Sen slope + Mann-Kendall p, write GeoTIFF
def run_trend(job_id: str, geom, req: TrendRequest):
job = JOBS[job_id]
job.update(status="running", started=datetime.now(timezone.utc).isoformat(timespec="seconds"))
try:
t0 = time.perf_counter()
inside = polygon_pixels(geom)
rows, cols = np.nonzero(inside)
r0, r1, c0, c1 = rows.min(), rows.max() + 1, cols.min(), cols.max() + 1
years = np.arange(req.start_year, req.end_year + 1)
cube = store.ndvi[:, r0:r1, c0:c1].astype("float32") / 1e4
cube[cube == 0] = np.nan
annual = np.stack([np.nanmax(cube[store.dates.year == y], axis=0) for y in years]) # (years, rows, cols)
n = len(years)
i, j = np.triu_indices(n, 1)
diffs = annual[j] - annual[i]
slopes = diffs / (years[j] - years[i])[:, None, None]
sen = np.nanmedian(slopes, axis=0) * 10 # NDVI per decade
s = np.nansum(np.sign(diffs), axis=0)
z = (s - np.sign(s)) / np.sqrt(n * (n - 1) * (2 * n + 5) / 18)
p = 2 * norm.sf(np.abs(z))
mask = inside[r0:r1, c0:c1] & np.isfinite(sen)
sen[~mask], p[~mask] = np.nan, np.nan
path = OUT / f"trend_{job_id}.tif"
profile = dict(driver="GTiff", width=c1 - c0, height=r1 - r0, count=2, dtype="float32", crs=store.ndvi_crs, nodata=np.nan,
transform=store.ndvi_transform * rasterio.Affine.translation(c0, r0), compress="deflate")
with rasterio.open(path, "w", **profile) as dst:
dst.write(np.stack([sen, p]).astype("float32"))
dst.set_band_description(1, "Theil-Sen slope of annual max NDVI per decade")
dst.set_band_description(2, "Mann-Kendall p-value")
valid = sen[mask]
job.update(status="done", seconds=round(time.perf_counter() - t0, 2), result=f"/jobs/{job_id}/result",
summary={"pixels": int(mask.sum()), "median_slope_per_decade": round(float(np.median(valid)), 4),
"share_significant_decline": round(float(((valid < 0) & (p[mask] < 0.05)).mean()), 3),
"share_significant_increase": round(float(((valid > 0) & (p[mask] < 0.05)).mean()), 3)})
except Exception as exc: # a failed job must say why
job.update(status="failed", error=f"{type(exc).__name__}: {exc}")
# Submit / poll / download endpoints
@app.post("/jobs/ndvi-trend", status_code=202, tags=["jobs"], dependencies=[Depends(require_key), Depends(limiter)])
def submit_trend(req: TrendRequest, background: BackgroundTasks):
"Start an NDVI trend analysis for a district; poll the returned URL."
row = store.districts.iloc[find_district(req.district)]
job_id = uuid.uuid4().hex[:12]
JOBS[job_id] = {"id": job_id, "status": "queued", "request": req.model_dump(),
"submitted": datetime.now(timezone.utc).isoformat(timespec="seconds")}
background.add_task(run_trend, job_id, row.geometry, req)
return JSONResponse({"id": job_id, "status": "queued", "href": f"/jobs/{job_id}"}, status_code=202,
headers={"Location": f"/jobs/{job_id}"})
@app.get("/jobs/{job_id}", tags=["jobs"])
def job_status(job_id: str):
if job_id not in JOBS:
raise HTTPException(404, f"No job {job_id}")
return JOBS[job_id]
@app.get("/jobs/{job_id}/result", tags=["jobs"])
def job_result(job_id: str):
job = job_status(job_id)
if job["status"] != "done":
raise HTTPException(409, f"Job is {job['status']}")
return FileResponse(OUT / f"trend_{job_id}.tif", media_type="image/tiff", filename=f"ndvi_trend_{job['request']['district']}.tif")
# Real HTTP server so BackgroundTasks run; submit jobs and poll until done
server = web.start_server(app)
api = httpx.Client(base_url=server.url, headers=headers, timeout=120)
print(server)
results = {}
for district in ["Dhaka", "Gazipur", "Rangamati", "Bogra"]:
r = api.post("/jobs/ndvi-trend", json={"district": district})
job = r.json()
print(r.status_code, "Location:", r.headers["location"], "|", job["status"])
polled = []
while job["status"] in ("queued", "running"):
time.sleep(0.2)
job = api.get(f"/jobs/{job['id']}").json()
polled.append(job["status"])
print(f" polled {len(polled)} times -> {job['status']} in {job.get('seconds')} s: {job.get('summary')}")
tif = api.get(job["result"])
path = OUT / f"downloaded_trend_{district}.tif"
path.write_bytes(tif.content)
results[district] = (path, job)
time.sleep(0.6)
bad = api.post("/jobs/ndvi-trend", json={"district": "Dhaka", "start_year": 2016})
print(bad.status_code, bad.json()["detail"][0]["msg"])