File size: 1,954 Bytes
1408d02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""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")