No domain logic in the app: labels checked by labeling (validate.check, ids.assign), client message and action by labeling/client.py, events by categories.window, references by data.is_reference; manual/ no longer written

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-17 09:32:20 +01:00
1 parent 7332306b79
commit a733575d65
7 files changed
+63 -109

No files matched your search

+2 -2
View File
@@ -6,9 +6,9 @@ The tool of the manual diagnostic: two pages, **Data** and **Stations**.
- **The plots**: one at the start (displacements, camera, image quality, system metrics), "Add a plot" to see several, aligned in time, the cross to remove one; a click on a curve sets the images to the image nearest to that moment. The zones of the labels are barely visible there (opacity 0.05, 0.07 in dark mode).
- **The labels**, under the plots, and their bar, according to the chosen source:
- **Detectors** (default): the detectors' events (`detectors/scripts/categories.py`, `events`), read-only. The bar carries only their family, the tooltip their targets; on click: their dates, their sensors (targets and references), the message (the first sentence of the text of the event, `categories.sentence`) and the action (the "For the client" column of `labeling/families.md`, refined per kind, `station.ACTION_KIND`);
- **Detectors** (default): the detectors' events (`detectors/scripts/categories.py`, `window`: the range with its 3 days of history), read-only. The bar carries only their family, the tooltip their targets; on click: their dates, their sensors (targets and references), the message and the action (`labeling/scripts/client.py`: the first sentence of the text of the event; the "For the client" columns of `labeling/families.md`, per family, refined per variety);
- **LLM**: `labeling/auto/<STATION>.jsonl`, read-only;
- **Analysis**: the same labels, to edit or delete; writes in `labeling/auto/<STATION>.jsonl`.
- **Analysis**: the same labels, to edit or delete; writes in `labeling/auto/<STATION>.jsonl`, each label checked by the rules of labeling (`labeling/scripts/validate.py`, `check`: one of the six families, no numeric value…) and given its id (`ids.py`, `assign`).
With Detectors and LLM, dragging on the bar zooms in time; with Analysis, it selects a range to analyze. A click highlights a label on the plots and the bar, sets the images to its start and opens it (with Analysis: bounds, family, text, Save, Delete); a click elsewhere on the bar closes it. The page does not show `labeling/manual/`.
- **The camera images**, on the right, on the same station and the same range: slider, ◀ ▶ and keyboard arrows; wheel to zoom, drag to move, double click for the whole image; Names box; a range on the bar under the slider draws the displacement arrow of each sensor. An arrow at the top left enlarges the image and pushes the plots to the left; the reverse arrow brings it back.
+5 -4
View File
@@ -55,7 +55,7 @@ def _optimizing():
def launch(body):
st, start, end = body.get("station"), body.get("start"), body.get("end")
station._validate({"description": "-"}, start, end)
station.checked_range(start, end)
station.folder(st)
if not (AGENTS / ".claude-plugin" / "plugin.json").exists():
raise station.Refusal("no agents in agents/ (the link: README.md)")
@@ -156,8 +156,9 @@ def submit(st, name, out):
for l in text.split("\n"):
if l.strip():
e = json.loads(l)
station._validate(e, e.get("start"), e.get("end"))
new.append({k: e[k] for k in ("start", "end", "family", "description") if k in e} | {"analysis": name})
label = {k: e[k] for k in ("start", "end", "family", "description") if k in e}
station.checked(label)
new.append(label | {"analysis": name})
if copy.exists() and copy.read_text(encoding="utf-8") == text:
return len(new)
# ponytail: removed then put back, the labels of the analysis lose the edits made in the page; keeping them would
@@ -166,7 +167,7 @@ def submit(st, name, out):
f = station.label_file(st, "auto") # the other lines stay as they are
kept = [l for l in (f.read_text(encoding="utf-8").split("\n") if f.exists() else [])
if l.strip() and json.loads(l).get("analysis") != name]
station.assign_ids(st, [json.loads(l) for l in kept] + new)
station.ids.assign(st, [json.loads(l) for l in kept] + new)
temp = f.with_name(f.name + ".tmp")
temp.write_text("".join(l + "\n" for l in kept + [json.dumps(e, ensure_ascii=False) for e in new]), encoding="utf-8")
os.replace(temp, f)
+8 -4
View File
@@ -75,8 +75,6 @@ def check_station():
ev = station.detectors("LENZSPITZE", "2026-10-26", "2026-10-27") # the detectors of the journal, ~10 s
assert ev and {"start", "end", "family", "description", "sensors"} <= set(ev[0]), ev[:1]
assert all(e["message"] and e["action"] and set(e["targets"] + e["references"]) == set(e["sensors"]) for e in ev), ev[:1]
assert station.message("A moved; nothing to do. The jump of 2 targets in this period has the same cause.") \
== "A moved. The jump of 2 targets in this period has the same cause."
assert all(e["end"] >= "2026-10-26T00:00Z" and e["start"] < "2026-10-27T00:00Z" for e in ev), [(e["start"], e["end"]) for e in ev]
refuses(station.pump, {"stations": ["A;rm"]}) # the pumping (extraction/pumping.py, checked there): a refusal
assert not any("SIM_CCID" in t or t.startswith("System: ip") for t in titles)
@@ -86,14 +84,20 @@ def check_station():
e = station.add({"station": "NIEDERHORN", "folder": "auto", "start": "2026-09-25T01:00Z",
"end": "2026-09-25T02:00Z", "family": "Visibility", "description": "fog"})
assert e["id"] == "NIEDERHORN-1" and next(iter(e)) == "id", e
refuses(station.update, {"station": "NIEDERHORN", "folder": "auto", "before": e, # labeling/scripts/validate.py
"start": e["start"], "end": e["end"], "family": "", "description": "rain"})
e2 = station.update({"station": "NIEDERHORN", "folder": "auto", "before": e,
"start": e["start"], "end": e["end"], "family": "", "description": "rain"})
assert e2 == {"id": "NIEDERHORN-1", "start": e["start"], "end": e["end"], "description": "rain"}, e2
"start": e["start"], "end": e["end"], "family": "Obstruction", "description": "rain"})
assert e2 == {"id": "NIEDERHORN-1", "start": e["start"], "end": e["end"], "family": "Obstruction", "description": "rain"}, e2
assert station.read("NIEDERHORN", "auto") == [e2]
assert "no longer in the file" in refuses(station.delete, {"station": "NIEDERHORN", "folder": "auto", "before": e})
station.delete({"station": "NIEDERHORN", "folder": "auto", "before": e2})
assert station.read("NIEDERHORN", "auto") == []
refuses(station.add, {"station": "NIEDERHORN", "folder": "../x", "start": "a", "end": "b", "description": "x"})
refuses(station.add, {"station": "NIEDERHORN", "folder": "manual", "start": "2026-09-25T01:00Z", # the expert's
"end": "2026-09-25T02:00Z", "family": "Visibility", "description": "fog"})
refuses(station.add, {"station": "NIEDERHORN", "start": "2026-09-25T01:00Z", "end": "2026-09-25T02:00Z",
"family": "Visibility", "description": "a shift of 3 px"})
refuses(station.add, {"station": "NIEDERHORN", "start": "2026-09-25T02:00Z", "end": "2026-09-25T01:00Z", "description": "x"})
finally:
shutil.rmtree(station.LABELS)
+1 -1
View File
@@ -98,7 +98,7 @@ def pump(body: dict):
@app.get("/api/labels")
def labels(station_: str = Query(alias="station"), folder: str = "manual"):
def labels(station_: str = Query(alias="station"), folder: str = "auto"):
try:
return station.read(station_, folder)
except json.JSONDecodeError as e: # a line damaged by hand: say so, without touching the file
+43 -96
View File
@@ -1,8 +1,9 @@
"""The data of the Data page: a station's images, its curves, its labels.
Data are read as the agents read them, tools/scripts/data.py (the tools repository, through the tools/ link); the detectors'
events are those of detectors/scripts/categories.py (events). Read-only on data/, filled only by pump.sh; writes only in
labeling/{auto,manual}/. What brings data in (the pumping, the list of the tracked stations, the weather) is in
events are those of detectors/scripts/categories.py (window); the rules of the labels and what the client is told, those of
labeling/scripts (validate, ids, client). Read-only on data/, filled only by pump.sh; writes only in
labeling/auto/. What brings data in (the pumping, the list of the tracked stations, the weather) is in
~/aimsight-data, called as it is (extraction/pumping.py, weather/meteoswiss.py).
"""
import bisect
@@ -19,12 +20,15 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
# ~/aimsight-data, the repository of data/: the methods that bring data in (the pumping, the weather), called as they are
DATA_REPOSITORY = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).resolve().parent
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"),
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"), str(ROOT / "labeling" / "scripts"),
str(DATA_REPOSITORY / "extraction"), str(DATA_REPOSITORY / "weather")]
import categories # noqa: E402
import client # noqa: E402 (labeling: what the client is told of an event)
import data # noqa: E402
import ids # noqa: E402 (labeling: the stable id of the labels)
import meteoswiss # noqa: E402
import pumping # noqa: E402
from categories import events # noqa: E402
import validate # noqa: E402 (labeling: the rules of a label)
# data/ and labeling/ are links to ~/aimsight-data/data and ~/aimsight-labeling: no resolve(), the agents see data/ and labeling/
DATA = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).absolute()
@@ -37,10 +41,8 @@ def links():
return [a for d in (DATA, LABELS, TOOLS) for a in ("--add-dir", str(d.resolve()))]
FOLDERS = ("auto", "manual") # those of the agents and of the page (D-105), those of the expert (D-102)
FAMILIES = ("Visibility", "Obstruction", "Thermal displacement", "Displacement", "Target issue", "No data", "None") # D-109
FOLDERS = ("auto",) # the labels of the agents and of the page (D-105); manual/ is the expert's alone (labeling/CLAUDE.md)
FORMAT = "%Y-%m-%dT%H:%MZ"
MARGIN_PX = 150 # Support-Agent detecteurs.MARGE_PX: x, y are positions in the image only far from the corner
COLORS = ["#2a78d6", "#eb6834", "#1baf7a", "#8a5cd6", "#d6a12a", "#d63b8a", "#3bb3d6", "#6b6b66"] # one per sensor
POSE = (("pan", "#1a1a19"), ("tilt", "#8a8a85"), ("rotation", "#b5651d"))
# The Advanced menu of Explore, in its order (Support-Agent labeling.PLOTS, QUALITE)
@@ -73,16 +75,15 @@ def bounds(start, end):
# --- the positions of the sensors in the image
def positions(measurements, a, b):
"""The median position of each sensor in the image over [a, b) ({} if x, y are not positions there)."""
homes = {s: (statistics.median(xs), statistics.median(ys)) for s, ms in measurements.items()
if (xs := [m["x"] for m in ms if a <= m["t"] < b and m["x"] is not None])
and (ys := [m["y"] for m in ms if a <= m["t"] < b and m["y"] is not None])}
return homes if any(abs(x) > MARGIN_PX or abs(y) > MARGIN_PX for x, y in homes.values()) else {}
"""Where to circle each sensor on the images: its median x, y over [a, b) (image px, tools/DATA.md)."""
return {s: (statistics.median(xs), statistics.median(ys)) for s, ms in measurements.items()
if (xs := [m["x"] for m in ms if a <= m["t"] < b and m["x"] is not None])
and (ys := [m["y"] for m in ms if a <= m["t"] < b and m["y"] is not None])}
def references(measurements, a, b):
"""Sensors of the compensation over the range: those with a reproj_err (references only)."""
return {s for s, ms in measurements.items() if any(m["reproj_err"] is not None for m in ms if a <= m["t"] < b)}
def references(measurements):
"""The references of the compensation (tools/scripts/data.py, is_reference)."""
return {s for s, ms in measurements.items() if data.is_reference(ms)}
# --- the images of the Data page
@@ -95,7 +96,7 @@ def images(station, start, end):
if not views:
raise Refusal(f"no image of {station} in this range")
measurements = data.load(d)
homes, refs = positions(measurements, a, b), references(measurements, a, b)
homes, refs = positions(measurements, a, b), references(measurements)
# ponytail: a single measurement at each bound, noisy; a median over a window if the arrows shake too much
margin, corr = timedelta(minutes=30), {}
for s in homes:
@@ -149,7 +150,7 @@ def curves(station, start, end):
hour = lambda t: t.strftime("%Y-%m-%d %H:%M") # noqa: E731 (UTC, without time zone: as Plotly shows it)
values = lambda s, c: [None if m[c] is None else round(m[c], 5) for m in s] # noqa: E731
inside = {s: [m for m in measurements[s] if a <= m["t"] < b] for s in sorted(measurements)}
refs, out = references(measurements, a, b), []
refs, out = references(measurements), []
def per_sensor(columns):
for col, title in columns:
@@ -252,9 +253,6 @@ def pump(body):
# --- the Data page, "Detectors" labels: the events of the journal, read-only
HISTORY = timedelta(days=3) # days before given to the detectors, as categories.py does (rule of 2026-10-24)
# ponytail: kept until the server restarts (a minute or more per range); restart it after an /optimize run outside the app
@functools.lru_cache(maxsize=32)
def detectors(station, start, end, targets=""):
@@ -269,49 +267,12 @@ def detectors(station, start, end, targets=""):
if not every:
raise Refusal(f"no \"advanced\" export for {station}" + " with these targets" * bool(targets))
a, b = span(every, start, end)
measurements = {s: k for s, ms in every.items() if (k := [m for m in ms if a - HISTORY <= m["t"] < b])}
evs = [v for v in events(measurements, b, str(d)) if v["end"] >= data.iso(a)] if measurements else []
refs = {s for s, ms in measurements.items() if ms[0]["pattern_type"] == "global_ref"}
return [{"id": f"D-{i + 1}", "start": v["start"], "end": v["end"], "family": v["category"], "kind": v["episodes"][0]["label"],
"description": f"{v['episodes'][0]['label']}. {v['text']}", "sensors": v["sensors"], "ignore": v["ignore"],
refs, advice = references(every), client.advice()
return [{"id": f"D-{i + 1}", "start": v["start"], "end": v["end"], "family": v["category"], "kind": (ep := v["episodes"][0])["label"],
"description": f"{ep['label']}. {v['text']}", "sensors": v["sensors"], "ignore": v["ignore"],
"targets": [s for s in v["sensors"] if s not in refs], "references": [s for s in v["sensors"] if s in refs],
"message": message(v["text"]), "action": action(v)}
for i, v in enumerate(evs)]
def message(text):
"""What happens: the first sentence of the journal (detectors/scripts/categories.py, sentence), up to its ";"; the rest
says what to do about it, except the sentence of the absorbed jumps, kept. ". " only: "1.5×" or "0.30 px" do not cut."""
same = re.search(r" (The jumps? of .* same cause\.)$", text)
return re.split(r"\. |; ", text, maxsplit=1)[0].rstrip(".") + "." + (" " + same.group(1) if same else "")
# What to do about it: the "For the client" column of labeling/families.md, per family; refined per kind (the label of the
# main episode, with its level) after the journal sentences validated on 2026-10-24 (detectors/scripts/categories.py, sentence)
ACTION_FAMILY = {
"Visibility": "Do not trust the curves in this period: this is not a movement.",
"Obstruction": "Ignore the curves of the hidden targets in this period.",
"Thermal displacement": "Normal, nothing to do.",
"Displacement": "To check: look at the images, then keep watching.",
"Target issue": "Act on the target (prism, mount); ignore its curve in the meantime.",
"No data": "The curves are missing in this period; its cause tells whether to act.",
}
ACTION_KIND = {
"Poor visibility reduced": "Use the data in this period with care: they are less precise.",
"Heat shimmer": "Nothing to do: the small fast wiggles are not movement.",
"Camera thermal movement": "Nothing to do: this is not a movement of the structure.",
"Brief obstruction": "Ignore this single point on the curves.",
"Sudden jump, back to normal": "Look at the images: the cause is not established.",
"Lasting shift": "Check whether the structure moved: look at the images.",
"Jump, not back yet": "Check whether the structure moved: look at the images.",
"Slow drift": "Keep watching it.",
}
def action(v):
ep = v["episodes"][0]
return ACTION_KIND.get(f"{ep['label']} {ep.get('level') or ''}".strip(), ACTION_KIND.get(ep["label"])) \
or ACTION_FAMILY.get(v["category"], "")
"message": client.message(v["text"]), "action": client.action(v["category"], ep["label"], ep.get("level"), advice)}
for i, v in enumerate(categories.window(every, a, b))]
# --- the labels
@@ -329,41 +290,29 @@ def read(station, source):
return [json.loads(l) for l in f.read_text(encoding="utf-8").split("\n") if l.strip()] if f.exists() else []
def assign_ids(station, labels):
"""As labeling/scripts/ids.py does (D-131): an id for the labels without one, the next of the station, as first field."""
n = max((int(e["id"].rsplit("-", 1)[1]) for e in labels if "id" in e), default=0)
for e in labels:
if "id" not in e:
n += 1
e["id"] = f"{station}-{n}"
if next(iter(e)) != "id":
rest = {k: v for k, v in e.items() if k != "id"}
ident = e["id"]
e.clear()
e.update({"id": ident}, **rest)
def checked(label):
"""A label written in auto/: the rules of labeling (labeling/scripts/validate.py, check), before its id."""
if errors := validate.check(label, proposed=True):
raise Refusal("; ".join(errors))
def _validate(body, start, end):
description = (body.get("description") or "").strip()
def checked_range(start, end):
"""A range asked by the page: YYYY-MM-DDTHH:MMZ, start before end."""
try:
empty = datetime.strptime(start, FORMAT) >= datetime.strptime(end, FORMAT)
if datetime.strptime(start, FORMAT) < datetime.strptime(end, FORMAT):
return
except (TypeError, ValueError):
raise Refusal("unreadable bounds (YYYY-MM-DDTHH:MMZ)") from None
if not description or empty:
raise Refusal("empty text or empty range")
family = body.get("family") or ""
if family and family not in FAMILIES:
raise Refusal("unknown family")
return description, family
pass
raise Refusal("unreadable or empty range (YYYY-MM-DDTHH:MMZ)")
def add(body):
station, source = body.get("station"), body.get("folder", "manual")
station, source = body.get("station"), body.get("folder", "auto")
f = label_file(station, source)
description, family = _validate(body, body.get("start"), body.get("end"))
label = {"start": body["start"], "end": body["end"]} | ({"family": family} if family else {}) | {"description": description}
if source == "auto": # an automatic label carries a stable id, the next of its station (D-131)
assign_ids(station, read(station, "auto") + [label])
label = {"start": body.get("start"), "end": body.get("end"), "family": body.get("family"),
"description": (body.get("description") or "").strip()}
checked(label)
ids.assign(station, read(station, source) + [label]) # a stable id, the next of its station (D-131)
f.parent.mkdir(parents=True, exist_ok=True)
before = f.read_bytes() if f.exists() else b"" # a line removed by hand may leave the file without a final newline
with open(f, "ab") as out:
@@ -374,19 +323,17 @@ def add(body):
def update(body):
before = body.get("before") or {}
start, end = body.get("start", before.get("start")), body.get("end", before.get("end"))
description, family = _validate(body, start, end)
label = dict.fromkeys(("id", "start", "end", "family")) | before | {"start": start, "end": end, "family": family,
"description": description}
label = dict.fromkeys(("id", "start", "end", "family")) | before | {"start": start, "end": end, "family": body.get("family"),
"description": (body.get("description") or "").strip()}
if label["id"] is None:
del label["id"]
if not family:
del label["family"]
label.pop("review", None) # changed: no longer reviewed
return replace(body.get("station"), body.get("folder", "manual"), before, label)
checked(label)
return replace(body.get("station"), body.get("folder", "auto"), before, label)
def delete(body):
replace(body.get("station"), body.get("folder", "manual"), body.get("before"), None)
replace(body.get("station"), body.get("folder", "auto"), body.get("before"), None)
return body.get("before")
+3 -1
View File
@@ -15,7 +15,9 @@ import { StationImages } from "./Images.jsx";
const FAMILIES = { "Visibility": "#8ec5e8", "Obstruction": "#f0b072", "Thermal displacement": "#f08a7e", "Displacement": "#b39ddb",
"Target issue": "#e6d46a", "No data": "#c4c4be", "None": "#a8d5a2" };
const FAMILY_NAME = f => (f === "None" ? "None (curves intact)" : f);
const FAMILY_CHOICES = [{ value: "", label: "(no family)" }, ...Object.keys(FAMILIES).map(f => ({ value: f, label: FAMILY_NAME(f) }))];
// A label of auto/ has one of the six families (labeling/scripts/validate.py); None is the expert's, in manual/
const FAMILY_CHOICES = [{ value: "", label: "(choose a family)" },
...Object.keys(FAMILIES).filter(f => f !== "None").map(f => ({ value: f, label: f }))];
// LLM and Analysis: the same labels, labeling/auto/; LLM reads them, Analysis edits, deletes them, and has the analyst make
// some on a range (app/server/analysis.py)
const SOURCES = [{ value: "detectors", label: "Detectors" }, { value: "auto", label: "LLM" }, { value: "analysis", label: "Analysis" }];