Points: a page to set each measurement of a range valid or not, saved in labeling/points/ (labeling/scripts/points.py), the ground truth of the benchmarks point by point
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1133a91078
commit
dcd255ab1f
6 files changed
+228
-5
No files matched your search
@@ -2,10 +2,10 @@
|
||||
|
||||
aimsight-app: the control station of the AIMsight diagnostic (`README.md`): the web app, and the launching of processes whose code lives elsewhere. A camera follows targets on a structure; the detectors read the displacement series of the stations and flag the moments when the curves must not be trusted (rain, fog, spider web, turbulence…) or a real movement. The architecture of the repositories: `docs/architecture.drawio`.
|
||||
|
||||
- **The processes**: the Analysis tab launches `agents:analyst` (plugin `agents/`) on a range, with `instructions/analyst.md` and `DETECTORS: no` (labels and report in `labeling/auto/analyses/<STATION>_<start>_<end>/`, submitted to `labeling/auto/<STATION>.jsonl`); "Optimize the detectors" launches `/optimize` in `optimizer/` on the analysis (its request in `app/server/analysis.py`, its summary in `optimizer/sessions/<analysis>_<time>/summary.md`), which commits the detectors in `detectors/` and the reading tools in `tools/`; the Support tab launches `agents:support` on a range with a question and `instructions/support.md` (its answer in `labeling/auto/support/<STATION>_<start>_<end>/answer.md`; it may launch the analyst itself; nothing submitted); the Conversations page launches `libredesk/conversations/pomper.sh` (read-only on LibreDesk, its key in `~/aimsight-libredesk/.env`), each conversation in `labeling/auto/conversations/<reference>/` (`transcript.md`, `messages.json`, `attachments/`).
|
||||
- **The processes**: the Analysis tab launches `agents:analyst` (plugin `agents/`) on a range, with `instructions/analyst.md` and `DETECTORS: no` (labels and report in `labeling/auto/analyses/<STATION>_<start>_<end>/`, submitted to `labeling/auto/<STATION>.jsonl`); "Optimize the detectors" launches `/optimize` in `optimizer/` on the analysis (its request in `app/server/analysis.py`, its summary in `optimizer/sessions/<analysis>_<time>/summary.md`), which commits the detectors in `detectors/` and the reading tools in `tools/`; the Support tab launches `agents:support` on a range with a question and `instructions/support.md` (its answer in `labeling/auto/support/<STATION>_<start>_<end>/answer.md`; it may launch the analyst itself; nothing submitted); the Conversations page launches `libredesk/conversations/pomper.sh` (read-only on LibreDesk, its key in `~/aimsight-libredesk/.env`), each conversation in `labeling/auto/conversations/<reference>/` (`transcript.md`, `messages.json`, `attachments/`). The Points page launches nothing: the user sets each measurement of a range valid or not, in `labeling/points/<STATION>_<start>_<end>.csv` (`app/server/validity.py`).
|
||||
- **The links** (ignored by git, one copy of each repository on the workstation): `data/`, `labeling/`, `detectors/`, `tools/`, `agents/`, `optimizer/`, `models/` (the pilot of learned detectors), `libredesk/` (the LibreDesk conversations); each thing is committed in its own repository, never here. This repository carries no agent, no reading tool, no workflow.
|
||||
- **The truth**: the labels of `labeling/auto/`; the labeling knowledge is in `labeling/`.
|
||||
- **The contracts**: the app calls the methods of the other repositories and holds no domain logic: with the detectors, `detectors/CLAUDE.md` (`categories.window`, `bench/score.py`); with the labels, `labeling/CLAUDE.md` (`scripts/validate.py` `check`, `scripts/ids.py` `assign`, `scripts/client.py`); with the data, `~/aimsight-data` (`extraction/pumping.py`; the weather is pumped into `data/<STATION>/weather/`; the runs of `data_diff/<SERIAL>/runs/<run>/` are stations `<SERIAL>@<run>` of the Data page, with the labels of `<SERIAL>`, not for the agents); with the agents, `agents/README.md` (the requests of the analyst and of the support); with Optimizer, `optimizer/README.md` (the request of `/optimize`); with LibreDesk, `libredesk/conversations/pompage.py` (`start`, `running`, `log`). A renaming over there requires the change here. One reader of the measurements, `tools/scripts/data.py`, for the Data page, the tools and the detectors (benchmark and Optimizer included): a reading fix there changes the benchmark.
|
||||
- **The contracts**: the app calls the methods of the other repositories and holds no domain logic: with the detectors, `detectors/CLAUDE.md` (`categories.window`, `bench/score.py`); with the labels, `labeling/CLAUDE.md` (`scripts/validate.py` `check`, `scripts/ids.py` `assign`, `scripts/client.py`, `scripts/points.py` for the point labels); with the data, `~/aimsight-data` (`extraction/pumping.py`; the weather is pumped into `data/<STATION>/weather/`; the runs of `data_diff/<SERIAL>/runs/<run>/` are stations `<SERIAL>@<run>` of the Data page, with the labels of `<SERIAL>`, not for the agents); with the agents, `agents/README.md` (the requests of the analyst and of the support); with Optimizer, `optimizer/README.md` (the request of `/optimize`); with LibreDesk, `libredesk/conversations/pompage.py` (`start`, `running`, `log`). A renaming over there requires the change here. One reader of the measurements, `tools/scripts/data.py`, for the Data page, the tools and the detectors (benchmark and Optimizer included): a reading fix there changes the benchmark.
|
||||
- **The benchmark**: `python3 detectors/bench/regression.py --labels labeling/auto --data data` (~1 min); the score of a range: `python3 detectors/bench/score.py data/<STATION> --labels labeling/auto/<STATION>.jsonl --from YYYY-MM-DD --to YYYY-MM-DD` (`--to` excluded).
|
||||
- **The pumping**: in `~/aimsight-data` (`extraction/pump.sh`, VS Code tasks **pump**, **pump a range**), read-only on the platform; user guide `~/aimsight-data/extraction/README.md`. Claude may launch it on small ranges; a long range or a history, outside busy hours.
|
||||
- **Check a change of the app**: `.venv/bin/python app/server/check.py`, then `cd app/web && npm run build` and launch the server. The labels: `python3 labeling/validate.py`.
|
||||
|
||||
+23
-1
@@ -47,6 +47,8 @@ def check_server():
|
||||
assert call("/api/stations") == 200
|
||||
assert call("/api/analyses") == 200
|
||||
assert call("/api/support") == 200
|
||||
assert call("/api/points") == 200
|
||||
assert call("/api/points/..%2Fx") in (400, 404)
|
||||
assert call("/api/support", {"station": "x"}) == 400
|
||||
assert call("/api/analyses/UNKNOWN/optimize", {}) == 400
|
||||
finally:
|
||||
@@ -427,7 +429,27 @@ def check_conversations():
|
||||
shutil.rmtree(root)
|
||||
|
||||
|
||||
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support, check_conversations]
|
||||
def check_points():
|
||||
# the Points page: a dataset of the real data in a temporary folder; its format and its rules, labeling/scripts/points.py --test
|
||||
import validity
|
||||
before, validity.points.FOLDER = validity.points.FOLDER, str(temp_folder())
|
||||
try:
|
||||
n = validity.create({"station": "NIEDERHORN", "start": "2026-09-25", "end": "2026-09-26"})
|
||||
assert n["points"] and not n["invalid"] and validity.listing("NIEDERHORN") == [n], n
|
||||
d = validity.dataset(n["name"])
|
||||
s, o = next(iter(d["sensors"].items()))
|
||||
assert validity.mark(n["name"], {"sensor": s, "times": o["t"][:2], "valid": False})["invalid"] == 2
|
||||
refuses(validity.create, {"station": "NIEDERHORN", "start": "2026-09-25", "end": "2026-09-26"}) # exists
|
||||
refuses(validity.create, {"station": "NIEDERHORN@run", "start": "2026-09-25", "end": "2026-09-26"})
|
||||
refuses(validity.dataset, "../x")
|
||||
refuses(validity.mark, n["name"], {"sensor": s, "times": ["2026-09-27 00:00:00"], "valid": False})
|
||||
finally:
|
||||
shutil.rmtree(validity.points.FOLDER)
|
||||
validity.points.FOLDER = before
|
||||
|
||||
|
||||
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support, check_conversations,
|
||||
check_points]
|
||||
|
||||
if __name__ == "__main__":
|
||||
name = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
|
||||
@@ -23,6 +23,7 @@ import analysis
|
||||
import conversations
|
||||
import station
|
||||
import support
|
||||
import validity
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
APP = Path(__file__).resolve().parents[1]
|
||||
@@ -202,6 +203,28 @@ def support_file(name: str, path: str):
|
||||
return FileResponse(analysis.file(name, path, support.FOLDER))
|
||||
|
||||
|
||||
# --- the Points page (validity.py): the point labels of labeling/points/, valid or not, set by the user
|
||||
|
||||
@app.get("/api/points")
|
||||
def points_list(station_: str = Query("", alias="station")):
|
||||
return validity.listing(station_)
|
||||
|
||||
|
||||
@app.post("/api/points")
|
||||
def points_create(body: dict):
|
||||
return validity.create(body)
|
||||
|
||||
|
||||
@app.get("/api/points/{name}")
|
||||
def points_dataset(name: str):
|
||||
return validity.dataset(name)
|
||||
|
||||
|
||||
@app.put("/api/points/{name}")
|
||||
def points_mark(name: str, body: dict):
|
||||
return validity.mark(name, body)
|
||||
|
||||
|
||||
# --- the Conversations page (conversations.py): the LibreDesk conversations, pumped read-only, and their transcripts
|
||||
|
||||
CSP = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'" # a client's mail: no script, no remote image
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""The Points page: the point labels of labeling/points/, one boolean per measurement (valid or not) on a range, set by
|
||||
the user. Their format, their files and their check are labeling/scripts/points.py; the measurements are read by
|
||||
tools/scripts/data.py, as everywhere. A station of data/ only (a run of data_diff/ refused).
|
||||
"""
|
||||
import threading
|
||||
|
||||
import station
|
||||
from station import Refusal, data
|
||||
|
||||
import points # noqa: E402 (labeling/scripts, on the path through station)
|
||||
|
||||
|
||||
def refused(f):
|
||||
def wrapped(*a):
|
||||
try:
|
||||
return f(*a)
|
||||
except (ValueError, FileNotFoundError) as e:
|
||||
raise Refusal(str(e)) from e
|
||||
return wrapped
|
||||
|
||||
|
||||
def summary(n):
|
||||
p = points.read(n)
|
||||
s, start, end = points.parts(n)
|
||||
return {"name": n, "station": s, "start": start, "end": end, "points": len(p), "invalid": sum(not v for v in p.values())}
|
||||
|
||||
|
||||
@refused
|
||||
def listing(st=""):
|
||||
return [summary(n) for n in points.datasets(st or None)]
|
||||
|
||||
|
||||
@refused
|
||||
def create(body):
|
||||
st, start, end = body.get("station", ""), body.get("start", ""), body.get("end", "")
|
||||
station.pumped(st)
|
||||
n = points.name(st, start, end)
|
||||
a, b = station.bounds(start, end)
|
||||
points.create(n, {s: [m["t"] for m in ms if a <= m["t"] < b and m["corr_x"] is not None and m["corr_y"] is not None]
|
||||
for s, ms in data.load(station.folder(st)).items()})
|
||||
return summary(n)
|
||||
|
||||
|
||||
@refused
|
||||
def dataset(n):
|
||||
"""-> {name, station, start, end, sensors: {sensor: {t, x, y, valid}}}: corr_x, corr_y (px, the curves labelled) of
|
||||
each point, None where the data no longer have it (a pumping again)."""
|
||||
p, st = points.read(n), points.parts(n)[0]
|
||||
now = {(s, points.time(m["t"])): m for s, ms in data.load(station.folder(st)).items() for m in ms}
|
||||
out = {}
|
||||
for (s, t), v in sorted(p.items()):
|
||||
m, o = now.get((s, t), {}), out.setdefault(s, {"t": [], "x": [], "y": [], "valid": []})
|
||||
o["t"].append(t[:19].replace("T", " ")) # as Plotly shows it, UTC
|
||||
o["x"].append(m.get("corr_x"))
|
||||
o["y"].append(m.get("corr_y"))
|
||||
o["valid"].append(v)
|
||||
return {**summary(n), "sensors": out}
|
||||
|
||||
|
||||
LOCK = threading.Lock() # the requests run in threads: two marks never read and write the file at the same time
|
||||
|
||||
|
||||
@refused
|
||||
def mark(n, body):
|
||||
"""{sensor, times (as the page shows them), valid} -> the summary."""
|
||||
times = [t.replace(" ", "T") + "Z" for t in body.get("times", [])]
|
||||
with LOCK:
|
||||
points.mark(n, body.get("sensor", ""), times, bool(body.get("valid")))
|
||||
return summary(n)
|
||||
+4
-2
@@ -3,12 +3,13 @@ import {
|
||||
ActionIcon, AppShell, Burger, ColorSwatch, Group, Loader, NavLink, ScrollArea, Text, Tooltip, useComputedColorScheme, useMantineColorScheme,
|
||||
} from "@mantine/core";
|
||||
import { useDisclosure } from "@mantine/hooks";
|
||||
import { IconChartLine, IconCircleCheck, IconCircleDashed, IconFolder, IconMessages, IconMoon, IconSatellite, IconSun } from "@tabler/icons-react";
|
||||
import { IconChartLine, IconCircleCheck, IconCircleDashed, IconFolder, IconMessages, IconMoon, IconPointFilled, IconSatellite, IconSun } from "@tabler/icons-react";
|
||||
|
||||
const Data = lazy(() => import("./pages/Data.jsx")); // Plotly, loaded only here
|
||||
const Stations = lazy(() => import("./pages/Stations.jsx"));
|
||||
const Conversations = lazy(() => import("./pages/Conversations.jsx"));
|
||||
const PAGES = [["data", "Data", IconChartLine], ["stations", "Stations", IconSatellite], ["conversations", "Conversations", IconMessages]];
|
||||
const Points = lazy(() => import("./pages/Points.jsx"));
|
||||
const PAGES = [["data", "Data", IconChartLine], ["points", "Points", IconPointFilled], ["stations", "Stations", IconSatellite], ["conversations", "Conversations", IconMessages]];
|
||||
|
||||
// The address: #/<page>?station=…&start=…&end=…; reloading keeps the page and the selection, Back works; without dates, the
|
||||
// last 5 UTC days, today included (end excluded: tomorrow)
|
||||
@@ -144,6 +145,7 @@ export default function App() {
|
||||
<Suspense fallback={<Loader m="xl" />}>
|
||||
{page === "stations" ? <Stations selection={selection} />
|
||||
: page === "conversations" ? <Conversations />
|
||||
: page === "points" ? <Points selection={selection} choose={choose} />
|
||||
: <Data selection={selection} choose={choose} analysis={analysis} setAnalysis={setAnalysis}
|
||||
support={support} setSupport={setSupport} />}
|
||||
</Suspense>
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Badge, Button, Card, Group, Loader, SegmentedControl, Select, Stack, Text, Title, useComputedColorScheme } from "@mantine/core";
|
||||
import { call, Selector } from "../common.jsx";
|
||||
|
||||
// Points: the point labels (labeling/points/, labeling/scripts/points.py), one boolean per measurement of a range, valid or
|
||||
// not, set by hand: the ground truth of the benchmarks. A dataset per station and range, created with every point valid;
|
||||
// one target at a time, corr_x above corr_y; a click on a point switches it, a box sets every point inside it (mode).
|
||||
// Each change is saved at once.
|
||||
const VALID = "#2a78d6", INVALID = "#e03131";
|
||||
const FONT = "Roboto, sans-serif";
|
||||
|
||||
export default function Points({ selection, choose }) {
|
||||
const { station, start, end } = selection, name = `${station}_${start}_${end}`;
|
||||
const [list, setList] = useState([]), [d, setD] = useState(null), [loading, setLoading] = useState(false);
|
||||
const [sensor, setSensor] = useState(null), [mode, setMode] = useState("invalid");
|
||||
const refresh = () => station ? call(`/api/points?${new URLSearchParams({ station })}`).then(l => l && setList(l)) : setList([]);
|
||||
const exists = list.some(x => x.name === name);
|
||||
useEffect(() => { refresh(); }, [station]);
|
||||
useEffect(() => {
|
||||
setD(null);
|
||||
if (!exists) return;
|
||||
setLoading(true);
|
||||
call(`/api/points/${name}`).then(r => { setLoading(false); if (r) { setD(r); setSensor(s => (s in r.sensors ? s : Object.keys(r.sensors)[0])); } });
|
||||
}, [name, exists]);
|
||||
const create = () => { setLoading(true); call("/api/points", "POST", { station, start, end }).then(r => { setLoading(false); r && refresh(); }); };
|
||||
// set the points (indices of the target's series) valid or not: at once on the page, then in the file; a refusal reloads
|
||||
function set(indices, valid) {
|
||||
const o = d.sensors[sensor], times = indices.filter(i => o.valid[i] !== valid).map(i => o.t[i]);
|
||||
if (!times.length) return;
|
||||
const v = o.valid.slice();
|
||||
indices.forEach(i => { v[i] = valid; });
|
||||
setD({ ...d, invalid: d.invalid + (valid ? -times.length : times.length), sensors: { ...d.sensors, [sensor]: { ...o, valid: v } } });
|
||||
call(`/api/points/${name}`, "PUT", { sensor, times, valid }).then(r => {
|
||||
if (r) setList(l => l.map(x => (x.name === name ? r : x)));
|
||||
else call(`/api/points/${name}`).then(r2 => r2 && setD(r2));
|
||||
});
|
||||
}
|
||||
const invalidOf = s => d.sensors[s].valid.filter(v => !v).length;
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<div>
|
||||
<Title order={2}>Points</Title>
|
||||
<Text c="dimmed">Each measurement of a range, valid or not, set by hand: the ground truth of the benchmarks
|
||||
(labeling/points/). A click on a point switches it; a box sets every point inside it.</Text>
|
||||
</div>
|
||||
<Selector selection={selection} choose={choose} />
|
||||
{list.length > 0 && <Group gap="xs">
|
||||
<Text size="sm" c="dimmed">Datasets of {station}:</Text>
|
||||
{list.map(x => <Button key={x.name} size="compact-sm" variant={x.name === name ? "filled" : "light"}
|
||||
onClick={() => choose({ station, start: x.start, end: x.end })}>
|
||||
{x.start} – {x.end} · {x.invalid}/{x.points} invalid</Button>)}
|
||||
</Group>}
|
||||
{loading && <Loader />}
|
||||
{station && !exists && !loading && <Card withBorder>
|
||||
<Group justify="space-between">
|
||||
<Text>No dataset for {station} from {start} to {end} (excluded).</Text>
|
||||
<Button onClick={create} disabled={!start || !end || station.includes("@")}>Create the dataset (every point valid)</Button>
|
||||
</Group>
|
||||
</Card>}
|
||||
{d && <Card withBorder>
|
||||
<Stack>
|
||||
<Group align="flex-end">
|
||||
<Select label="Target" w={260} searchable allowDeselect={false} value={sensor} onChange={setSensor}
|
||||
data={Object.keys(d.sensors).map(s => ({ value: s, label: `${s}${invalidOf(s) ? ` · ${invalidOf(s)} invalid` : ""}` }))} />
|
||||
<div>
|
||||
<Text size="sm" fw={500} mb={4}>A box sets the points</Text>
|
||||
<SegmentedControl value={mode} onChange={setMode} data={[{ value: "invalid", label: "Invalid" }, { value: "valid", label: "Valid" }]} />
|
||||
</div>
|
||||
<Badge size="lg" variant="light" color="red">{d.invalid} invalid of {d.points}</Badge>
|
||||
</Group>
|
||||
{sensor && <Plot o={d.sensors[sensor]} sensor={sensor} set={set} mode={mode} />}
|
||||
</Stack>
|
||||
</Card>}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
// corr_x above corr_y (px, the curves labelled), sharing the time; the points blue valid, red invalid
|
||||
function Plot({ o, sensor, set, mode }) {
|
||||
const g = useRef(), [Plotly, setPlotly] = useState(null), dark = useComputedColorScheme("light") === "dark";
|
||||
const latest = useRef();
|
||||
latest.current = { o, set, mode };
|
||||
useEffect(() => { import("plotly.js-dist-min").then(m => setPlotly(() => m.default)); }, []);
|
||||
useEffect(() => {
|
||||
if (!Plotly) return;
|
||||
const color = o.valid.map(v => (v ? VALID : INVALID)), text = dark ? "#c9c9c9" : "#495057", grid = dark ? "#2e2e2e" : "#eef0f2";
|
||||
const trace = (y, yaxis) => ({ type: "scattergl", mode: "lines+markers", x: o.t, y, yaxis, hovertemplate: "%{x}<br>%{y:.4f} px<extra></extra>",
|
||||
line: { width: 1, color: dark ? "#555" : "#ccc" }, marker: { size: 6, color }, unselected: { marker: { opacity: 1 } } });
|
||||
const axis = { gridcolor: grid, zeroline: false };
|
||||
Plotly.react(g.current, [trace(o.x, "y"), trace(o.y, "y2")], {
|
||||
height: 560, margin: { l: 60, r: 20, t: 10, b: 30 }, showlegend: false, dragmode: "select", selectdirection: "any",
|
||||
uirevision: sensor, paper_bgcolor: "rgba(0,0,0,0)", plot_bgcolor: "rgba(0,0,0,0)", font: { family: FONT, size: 11, color: text },
|
||||
grid: { rows: 2, columns: 1, shared_xaxes: true }, xaxis: { ...axis, anchor: "y2" },
|
||||
yaxis: { ...axis, domain: [0.53, 1], title: { text: "corr_x [px]" } }, yaxis2: { ...axis, domain: [0, 0.47], title: { text: "corr_y [px]" } },
|
||||
}, { responsive: true, displaylogo: false, doubleClick: "reset", modeBarButtonsToRemove: ["lasso2d", "autoScale2d", "toggleSpikelines"] });
|
||||
if (!g.current._bound) { // once per plot: the handlers read the latest state
|
||||
g.current._bound = true;
|
||||
g.current.on("plotly_click", ev => { const i = ev.points[0].pointIndex; latest.current.set([i], !latest.current.o.valid[i]); });
|
||||
g.current.on("plotly_selected", ev => {
|
||||
if (!ev?.points?.length) return;
|
||||
latest.current.set([...new Set(ev.points.map(p => p.pointIndex))], latest.current.mode === "valid");
|
||||
Plotly.relayout(g.current, { selections: [] });
|
||||
});
|
||||
}
|
||||
}, [Plotly, o, sensor, dark]);
|
||||
return <div ref={g} />;
|
||||
}
|
||||
Reference in new issue
Block a user