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

+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")