"""Gola reference labelling: serves the labelling page and records each label.""" from __future__ import annotations import json import os import re from pathlib import Path from fastapi import FastAPI, HTTPException from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel import store STATIC = Path(__file__).parent / "static" CODE = os.environ.get("ACCESS_CODE", "") POINTS = {p["id"] for p in json.loads((STATIC / "points.json").read_text())} app = FastAPI(docs_url=None, redoc_url=None) class Label(BaseModel): labeller: str code: str = "" point_id: str forest_2017: str forest_2023: str change_type: str confidence: str source_2017: str = "esri" source_2023: str = "esri" note: str = "" def _check(labeller: str, code: str): if CODE and code != CODE: raise HTTPException(403, "Wrong access code.") if not store.slug(labeller): raise HTTPException(400, "Enter your name.") @app.on_event("startup") def _start(): store.start() @app.get("/api/labels") def labels(labeller: str, code: str = ""): _check(labeller, code) return store.load(labeller) @app.post("/api/labels") def save(lb: Label): _check(lb.labeller, lb.code) if lb.point_id not in POINTS: raise HTTPException(400, "Unknown point.") ok = {"forest_2017": {"yes", "no", "unsure"}, "forest_2023": {"yes", "no", "unsure"}, "change_type": {"none", "clearing", "degradation", "regrowth", "plantation", "other"}, "confidence": {"high", "medium", "low"}} for k, allowed in ok.items(): if getattr(lb, k) not in allowed: raise HTTPException(400, f"Missing {k.replace('_', ' ')}.") return store.save(lb.labeller, lb.point_id, lb.model_dump()) @app.get("/") def index(): return FileResponse(STATIC / "index.html") app.mount("/", StaticFiles(directory=STATIC), name="static")