2026-11-16 12:40:03 +01:00
|
|
|
"""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'
|
2026-11-25 14:28:23 +01:00
|
|
|
events are those of detectors/detectors/categories.py (window); the rules of the labels and what the client is told, those of
|
2026-11-17 09:32:20 +01:00
|
|
|
labeling/scripts (validate, ids, client). Read-only on data/, filled only by pump.sh; writes only in
|
2026-11-18 07:17:51 +01:00
|
|
|
labeling/auto/. What brings data in (the pumping, the list of the tracked stations) is in ~/aimsight-data, called as it
|
|
|
|
|
is (extraction/pumping.py); the weather is pumped with the data, data/<STATION>/weather/ (data.load_weather).
|
2026-11-19 11:01:00 +01:00
|
|
|
The runs of the differential data (data_diff/<SERIAL>/runs/<run>/ of ~/aimsight-data) are stations too, <SERIAL>@<run>:
|
|
|
|
|
read by the same reader (data.shared: their images, metrics and weather in data_diff/<SERIAL>/); their labels are those of
|
|
|
|
|
<SERIAL>.
|
2026-11-16 12:40:03 +01:00
|
|
|
"""
|
|
|
|
|
import bisect
|
|
|
|
|
import functools
|
|
|
|
|
import glob
|
|
|
|
|
import json
|
|
|
|
|
import os
|
2026-11-18 17:25:30 +01:00
|
|
|
import pickle
|
2026-11-16 12:40:03 +01:00
|
|
|
import re
|
|
|
|
|
import statistics
|
2026-11-18 17:25:30 +01:00
|
|
|
import subprocess
|
2026-11-16 12:40:03 +01:00
|
|
|
import sys
|
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
2026-11-18 07:17:51 +01:00
|
|
|
# ~/aimsight-data, the repository of data/: the method that brings data in (the pumping, the weather with it), called as it is
|
2026-11-17 09:12:17 +01:00
|
|
|
DATA_REPOSITORY = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).resolve().parent
|
2026-11-25 14:28:23 +01:00
|
|
|
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "detectors"), str(ROOT / "labeling" / "scripts"),
|
2026-11-18 07:17:51 +01:00
|
|
|
str(DATA_REPOSITORY / "extraction")]
|
2026-11-17 09:32:20 +01:00
|
|
|
import categories # noqa: E402
|
|
|
|
|
import client # noqa: E402 (labeling: what the client is told of an event)
|
2026-11-16 12:40:03 +01:00
|
|
|
import data # noqa: E402
|
2026-11-17 09:32:20 +01:00
|
|
|
import ids # noqa: E402 (labeling: the stable id of the labels)
|
2026-11-17 09:12:17 +01:00
|
|
|
import pumping # noqa: E402
|
2026-11-17 09:32:20 +01:00
|
|
|
import validate # noqa: E402 (labeling: the rules of a label)
|
2026-11-16 12:40:03 +01:00
|
|
|
|
2026-11-16 14:56:41 +01:00
|
|
|
# data/ and labeling/ are links to ~/aimsight-data/data and ~/aimsight-labeling: no resolve(), the agents see data/ and labeling/
|
2026-11-16 12:40:03 +01:00
|
|
|
DATA = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).absolute()
|
|
|
|
|
LABELS = Path(os.environ.get("AIMSIGHT_LABELS", ROOT / "labeling")).absolute()
|
2026-11-19 11:01:00 +01:00
|
|
|
DATA_DIFF = DATA_REPOSITORY / "data_diff" # the runs, data_diff/<SERIAL>/runs/<run>/: out of git, filled by ~/aimsight-data
|
|
|
|
|
RUN = "@" # <SERIAL>@<run>: a run of data_diff/ in the list of the stations
|
2026-11-16 14:56:41 +01:00
|
|
|
TOOLS = ROOT / "tools" # the reading harness (~/aimsight-tools), read by the analyst and written by the upgrader (Optimizer)
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def links():
|
|
|
|
|
"""--add-dir for claude -p: the real target of the data/, labeling/ and tools/ links, outside the repository."""
|
|
|
|
|
return [a for d in (DATA, LABELS, TOOLS) for a in ("--add-dir", str(d.resolve()))]
|
|
|
|
|
|
|
|
|
|
|
2026-11-17 09:32:20 +01:00
|
|
|
FOLDERS = ("auto",) # the labels of the agents and of the page (D-105); manual/ is the expert's alone (labeling/CLAUDE.md)
|
2026-11-16 12:40:03 +01:00
|
|
|
FORMAT = "%Y-%m-%dT%H:%MZ"
|
|
|
|
|
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)
|
|
|
|
|
PLOTS = (("error_value", "Error value"), ("x", "X [px]"), ("y", "Y [px]"),
|
|
|
|
|
("relative_x", "Relative Horizontal Shift"), ("relative_y", "Relative Vertical Shift"),
|
|
|
|
|
("corr_x", "Relative Corrected Horizontal Shift"), ("corr_y", "Relative Corrected Vertical Shift"),
|
2026-11-18 07:17:51 +01:00
|
|
|
("corr_x_mm", "Relative Corrected Horizontal Shift [mm]"), ("corr_y_mm", "Relative Corrected Vertical Shift [mm]"),
|
2026-11-16 12:40:03 +01:00
|
|
|
("reproj_err", "References (reproj. error)"))
|
|
|
|
|
QUALITY = (("peak", "Quality: Peak"), ("flux", "Quality: Flux"), ("sharpness", "Quality: Sharpness"),
|
|
|
|
|
("fwhm", "Quality: FWHM [px]"), ("dominance", "Quality: Dominance"), ("snr", "Quality: SNR"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Refusal(ValueError):
|
|
|
|
|
"""A request to refuse (400), with its reason."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def stations():
|
2026-11-19 11:11:09 +01:00
|
|
|
runs = [f"{d.parent.parent.name}{RUN}{d.name}" for d in DATA_DIFF.glob("*/runs/*") if d.is_dir()]
|
|
|
|
|
return sorted([d.name for d in DATA.iterdir() if d.is_dir()] + runs) # a run right after its station
|
2026-11-19 11:01:00 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def serial(station):
|
|
|
|
|
"""The station of a run, <SERIAL>@<run> -> <SERIAL> (its labels); a station of data/ -> itself."""
|
|
|
|
|
return station.partition(RUN)[0]
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def folder(station):
|
2026-11-19 11:01:00 +01:00
|
|
|
if station not in stations(): # the name becomes a path: a folder of data/ or a run of data_diff/, nothing else
|
2026-11-16 12:40:03 +01:00
|
|
|
raise Refusal(f"unknown station: {station}")
|
2026-11-19 11:01:00 +01:00
|
|
|
s, _, run = station.partition(RUN)
|
|
|
|
|
return DATA_DIFF / s / "runs" / run if run else DATA / station
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def pumped(station):
|
|
|
|
|
"""A station of data/ (the agents read data/ only): a run of data_diff/ refused."""
|
|
|
|
|
folder(station)
|
|
|
|
|
if RUN in station:
|
|
|
|
|
raise Refusal(f"{station} is a run of data_diff/: the agents read the stations of data/ only")
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def bounds(start, end):
|
|
|
|
|
return data.parse_time(start or "0001-01-01"), data.parse_time(end or "9999-01-01")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- the positions of the sensors in the image
|
|
|
|
|
|
|
|
|
|
def positions(measurements, a, b):
|
2026-11-17 09:32:20 +01:00
|
|
|
"""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])}
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
2026-11-17 09:32:20 +01:00
|
|
|
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)}
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- the images of the Data page
|
|
|
|
|
|
|
|
|
|
def images(station, start, end):
|
|
|
|
|
"""The images of [start, end), the median positions of the sensors, the references, and for each circled sensor its
|
|
|
|
|
corr_x, corr_y at the time of each image: the nearest valid measurement, within 30 min, otherwise 0."""
|
|
|
|
|
d, (a, b) = folder(station), bounds(start, end)
|
2026-11-19 11:01:00 +01:00
|
|
|
views = [(t, im) for im in sorted(glob.glob(str(Path(data.shared(d)) / "images" / "*"))) if (t := data.image_time(im)) and a <= t < b]
|
2026-11-16 12:40:03 +01:00
|
|
|
if not views:
|
|
|
|
|
raise Refusal(f"no image of {station} in this range")
|
|
|
|
|
measurements = data.load(d)
|
2026-11-17 09:32:20 +01:00
|
|
|
homes, refs = positions(measurements, a, b), references(measurements)
|
2026-11-16 12:40:03 +01:00
|
|
|
# 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:
|
|
|
|
|
series = [(m["t"], m["corr_x"], m["corr_y"]) for m in measurements[s] if m["corr_x"] is not None and m["corr_y"] is not None]
|
|
|
|
|
times, corr[s] = [m[0] for m in series], []
|
|
|
|
|
for t, _ in views:
|
|
|
|
|
k = bisect.bisect_left(times, t)
|
|
|
|
|
k = min((n for n in (k - 1, k) if 0 <= n < len(series)), key=lambda n: abs(times[n] - t), default=None)
|
|
|
|
|
corr[s].append([round(series[k][1], 4), round(series[k][2], 4)] if k is not None and abs(times[k] - t) <= margin else 0)
|
|
|
|
|
return {"images": [{"t": data.iso(t).replace("T", " ").rstrip("Z"), "name": os.path.basename(im)} for t, im in views],
|
|
|
|
|
"positions": {s: [round(x, 1), round(y, 1)] for s, (x, y) in sorted(homes.items())},
|
|
|
|
|
"references": sorted(refs), "corr": corr}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def image(station, name):
|
2026-11-19 11:01:00 +01:00
|
|
|
images = Path(data.shared(folder(station))) / "images"
|
|
|
|
|
f = (images / name).resolve()
|
|
|
|
|
if f.parent != images.resolve() or not f.is_file():
|
2026-11-16 12:40:03 +01:00
|
|
|
raise Refusal("unknown image")
|
|
|
|
|
return f
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- the curves of the Data page
|
|
|
|
|
|
2026-11-17 09:20:17 +01:00
|
|
|
def holes(points, step=timedelta(hours=1)):
|
|
|
|
|
"""[(t, v)] sorted -> the same, with (t + step, None) after a point followed by nothing during more than a step."""
|
|
|
|
|
out = []
|
|
|
|
|
for t, v in points:
|
|
|
|
|
if out and t - out[-1][0] > step:
|
|
|
|
|
out.append((out[-1][0] + step, None))
|
|
|
|
|
out.append((t, v))
|
|
|
|
|
return out
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def span(measurements, start, end):
|
|
|
|
|
"""The range read: from start to end (excluded), otherwise from the first measurement to the last, plus one step."""
|
|
|
|
|
every = sorted({m["t"] for ms in measurements.values() for m in ms})
|
|
|
|
|
a = data.parse_time(start) if start else every[0]
|
|
|
|
|
b = data.parse_time(end) if end else every[-1] + (every[-1] - every[-2] if len(every) > 1 else timedelta(hours=1))
|
|
|
|
|
return a, b
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def curves(station, start, end):
|
|
|
|
|
"""-> {A, B, T, plots}: T, the times of each series, once (key: the sensor, "" for the camera, "system:" and its
|
|
|
|
|
name for a metric); plot: title and traces (name, t, y, line, mode), without empty plots or sensors."""
|
|
|
|
|
d = folder(station)
|
|
|
|
|
measurements = data.load(d)
|
|
|
|
|
if not measurements:
|
|
|
|
|
raise Refusal(f"no \"advanced\" export for {station}")
|
|
|
|
|
a, b = span(measurements, start, end)
|
|
|
|
|
poses = [p for p in data.load_camera(d) if a <= p["t"] < b]
|
|
|
|
|
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)}
|
2026-11-17 09:32:20 +01:00
|
|
|
refs, out = references(measurements), []
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
def per_sensor(columns):
|
|
|
|
|
for col, title in columns:
|
|
|
|
|
traces = [{"name": s + " (ref.)" * (s in refs), "t": s, "y": y,
|
|
|
|
|
"line": {"width": 1.2, "color": COLORS[i % len(COLORS)], "dash": "dot" if s in refs else "solid"}}
|
|
|
|
|
for i, (s, y) in enumerate((s, values(ms, col)) for s, ms in inside.items()) if any(v is not None for v in y)]
|
|
|
|
|
if traces:
|
|
|
|
|
out.append({"title": title, "traces": traces})
|
|
|
|
|
|
|
|
|
|
per_sensor(PLOTS)
|
|
|
|
|
if poses:
|
|
|
|
|
out.append({"title": "Camera movement (deg)", "traces": [{"name": c, "t": "", "y": values(poses, c),
|
|
|
|
|
"line": {"width": 1.2, "color": col}} for c, col in POSE]})
|
|
|
|
|
per_sensor(QUALITY)
|
|
|
|
|
T = {"": [hour(p["t"]) for p in poses], **{s: [hour(m["t"]) for m in ms] for s, ms in inside.items()}}
|
2026-11-17 09:20:17 +01:00
|
|
|
# the numeric system metrics (data.load_metrics: without the text metrics and the identifiers), over [a, b); an
|
|
|
|
|
# hour without value breaks the line (None), the hole shows
|
|
|
|
|
system = {n: holes(kept) for n, vs in data.load_metrics(d).items() if (kept := [(t, v) for t, v in vs if a <= t < b])}
|
2026-11-16 12:40:03 +01:00
|
|
|
for name in sorted(system, key=str.lower):
|
2026-11-17 09:20:17 +01:00
|
|
|
T["system:" + name] = [hour(t) for t, _ in system[name]]
|
2026-11-16 12:40:03 +01:00
|
|
|
out.append({"title": "System: " + name, "traces": [{"name": name, "t": "system:" + name, "mode": "lines+markers",
|
2026-11-17 09:20:17 +01:00
|
|
|
"y": [None if v is None else round(v, 5) for _, v in system[name]],
|
2026-11-16 12:40:03 +01:00
|
|
|
"line": {"width": 1.2, "color": COLORS[0]}}]})
|
|
|
|
|
if not out:
|
|
|
|
|
raise Refusal(f"no measurement of {station} in this range")
|
2026-11-17 08:51:48 +01:00
|
|
|
result = {"A": data.iso(a), "B": data.iso(b), "T": T, "plots": out}
|
2026-11-18 07:17:51 +01:00
|
|
|
if hours := [h for h in data.load_weather(d) if a <= h["t"] < b]: # the weather pumped with the data, if any
|
|
|
|
|
label, times, plots = weather(hours)
|
|
|
|
|
T.update(times)
|
|
|
|
|
out += plots
|
|
|
|
|
result["weather"] = label
|
2026-11-19 11:01:00 +01:00
|
|
|
elif pumping.tracked().get(serial(station)):
|
2026-11-18 07:17:51 +01:00
|
|
|
result["weather"] = "none pumped in this range (see the pumping log)"
|
2026-11-17 08:51:48 +01:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
2026-11-18 07:17:51 +01:00
|
|
|
# --- the Data page, the weather pumped in data/<STATION>/weather/ (extraction/weather.py of ~/aimsight-data): plots "Weather: …"
|
2026-11-17 08:51:48 +01:00
|
|
|
|
|
|
|
|
WEATHER = (("Precipitation (mm/h)", "precipitation_mm"), ("Temperature (°C)", "temperature_c"), ("Humidity (%)", "humidity_pct"),
|
|
|
|
|
("Wind (km/h)", "wind_speed_kmh", "wind_gust_kmh"), ("Wind direction (deg)", "wind_direction_deg"),
|
|
|
|
|
("Pressure (hPa)", "pressure_hpa"), ("Sunshine (min/h)", "sunshine_min"),
|
|
|
|
|
("Global radiation (W/m²)", "global_radiation_wm2"), ("Snow depth (cm)", "snow_depth_cm"))
|
|
|
|
|
|
|
|
|
|
|
2026-11-18 07:17:51 +01:00
|
|
|
def weather(hours):
|
|
|
|
|
"""[hour] of data.load_weather, not empty -> (label, T, plots) as curves(); their times under T["system:weather"], so
|
|
|
|
|
that the target filters ignore them; the label: where the last hour was measured."""
|
2026-11-17 08:51:48 +01:00
|
|
|
plots = []
|
|
|
|
|
for title, *columns in WEATHER:
|
|
|
|
|
traces = [{"name": c.rsplit("_", 1)[0].replace("_", " "), "t": "system:weather", "y": y,
|
|
|
|
|
"mode": "markers" if "direction" in c else "lines",
|
|
|
|
|
"line": {"width": 1.2, "color": COLORS[i], "shape": "hv" if c == "precipitation_mm" else "linear"}}
|
2026-11-18 07:17:51 +01:00
|
|
|
for i, (c, y) in enumerate((c, [h.get(c) for h in hours]) for c in columns) if any(v is not None for v in y)]
|
2026-11-17 08:51:48 +01:00
|
|
|
if traces:
|
|
|
|
|
plots.append({"title": "Weather: " + title, "traces": traces})
|
2026-11-18 07:17:51 +01:00
|
|
|
w = hours[-1]
|
|
|
|
|
return (f"{w['place']} → MeteoSwiss {w['station']} {w['station_name']}, {w['distance_km']} km, {w['height_m']} m"
|
|
|
|
|
+ " (no measurement in this range)" * (not plots),
|
|
|
|
|
{"system:weather": [h["t"].strftime("%Y-%m-%d %H:%M") for h in hours]}, plots)
|
2026-11-17 08:51:48 +01:00
|
|
|
|
|
|
|
|
|
2026-11-17 09:12:17 +01:00
|
|
|
# --- the tracked stations and the pumping: extraction/pumping.py of ~/aimsight-data
|
2026-11-17 08:51:48 +01:00
|
|
|
|
2026-11-19 11:13:38 +01:00
|
|
|
pump_process = {} # the pumpings launched by the app, by diff (pump_diff.sh, into data_diff/: beside pump.sh)
|
2026-11-17 08:51:48 +01:00
|
|
|
|
|
|
|
|
|
2026-11-17 09:12:17 +01:00
|
|
|
def save_tracked(rows):
|
|
|
|
|
try:
|
|
|
|
|
return [{"serial": s, "position": p} for s, p in pumping.save(rows).items()]
|
|
|
|
|
except ValueError as e:
|
|
|
|
|
raise Refusal(str(e))
|
2026-11-17 08:51:48 +01:00
|
|
|
|
|
|
|
|
|
2026-11-19 11:13:38 +01:00
|
|
|
def pump_state(diff=False):
|
2026-11-17 09:12:17 +01:00
|
|
|
"""{running, log}; the end of the app's pumping empties the cache of the detectors' events."""
|
2026-11-19 11:13:38 +01:00
|
|
|
if (p := pump_process.get(diff)) and p.poll() is not None:
|
|
|
|
|
del pump_process[diff]
|
2026-11-17 08:51:48 +01:00
|
|
|
detectors.cache_clear()
|
2026-11-19 11:13:38 +01:00
|
|
|
return {"running": pumping.running(diff) or diff in pump_process, "log": pumping.log(diff=diff)}
|
2026-11-17 08:51:48 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def pump(body):
|
2026-11-19 11:13:38 +01:00
|
|
|
diff = bool(body.get("diff"))
|
2026-11-17 09:12:17 +01:00
|
|
|
try:
|
2026-11-19 11:13:38 +01:00
|
|
|
pump_process[diff] = pumping.start(body.get("stations") or [], body.get("start") or "", body.get("end") or "",
|
|
|
|
|
body.get("images"), diff)
|
2026-11-17 09:12:17 +01:00
|
|
|
except ValueError as e:
|
|
|
|
|
raise Refusal(str(e))
|
2026-11-19 11:13:38 +01:00
|
|
|
return pump_state(diff)
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- the Data page, "Detectors" labels: the events of the journal, read-only
|
|
|
|
|
|
2026-11-25 14:28:23 +01:00
|
|
|
# The sets of detectors: detectors/detectors/ (classic, imported here), models/rules/manual/ (the same layout, hand-made: run in
|
2026-11-18 17:25:30 +01:00
|
|
|
# a process of its own, its modules bear the same names as the classic ones)
|
2026-11-25 14:28:23 +01:00
|
|
|
MANUAL = ROOT / "models" / "rules" / "manual"
|
2026-11-18 17:25:30 +01:00
|
|
|
CHILD = ("import pickle, sys; out, sys.stdout = sys.stdout.buffer, sys.stderr; sys.path.insert(0, sys.argv[1]); import categories; "
|
|
|
|
|
"pickle.dump(categories.window(*pickle.load(sys.stdin.buffer)), out)")
|
|
|
|
|
|
|
|
|
|
|
2026-11-25 11:45:39 +01:00
|
|
|
def window(set_, every, a, b, sensitivity=0):
|
|
|
|
|
"""categories.window of the chosen set; sensitivity (1 to 10, 0: the default of the code): the manual set only."""
|
2026-11-18 17:25:30 +01:00
|
|
|
if set_ != "manual":
|
|
|
|
|
return categories.window(every, a, b)
|
|
|
|
|
if not (MANUAL / "categories.py").is_file():
|
2026-11-25 14:28:23 +01:00
|
|
|
raise Refusal("no manual detectors: models/rules/manual/ has no categories.py")
|
2026-11-25 11:45:39 +01:00
|
|
|
run = subprocess.run([sys.executable, "-c", CHILD, str(MANUAL)], input=pickle.dumps((every, a, b, sensitivity or None)), capture_output=True, cwd=ROOT)
|
2026-11-18 17:25:30 +01:00
|
|
|
sys.stderr.write(run.stderr.decode(errors="replace"))
|
|
|
|
|
if run.returncode:
|
|
|
|
|
raise Refusal("the manual detectors failed: " + (run.stderr.decode(errors="replace").strip().splitlines() or ["?"])[-1])
|
|
|
|
|
return pickle.loads(run.stdout)
|
|
|
|
|
|
|
|
|
|
|
2026-11-25 11:45:39 +01:00
|
|
|
def detectors(station, start, end, targets="", set_="classic", sensitivity=0):
|
|
|
|
|
"""journal(), from the cache for the classic set; the manual set, being written, computed again at each call."""
|
|
|
|
|
return (journal.__wrapped__ if set_ == "manual" else journal)(station, start, end, targets, set_, sensitivity)
|
|
|
|
|
|
|
|
|
|
|
2026-11-16 14:15:55 +01:00
|
|
|
# ponytail: kept until the server restarts (a minute or more per range); restart it after an /optimize run outside the app
|
2026-11-16 12:40:03 +01:00
|
|
|
@functools.lru_cache(maxsize=32)
|
2026-11-25 11:45:39 +01:00
|
|
|
def journal(station, start, end, targets="", set_="classic", sensitivity=0):
|
2026-11-16 12:40:03 +01:00
|
|
|
"""-> the detectors' events over the range, in the label format (start, end, family, description); plus kind,
|
|
|
|
|
sensors, ignore (greyed area of the journal). targets: the sensors kept, comma-separated (empty: all); the others are
|
2026-11-25 14:28:23 +01:00
|
|
|
removed before the detectors, as if they did not exist. set_: classic (detectors/detectors/) or manual (models/rules/manual/);
|
2026-11-25 11:45:39 +01:00
|
|
|
sensitivity: of the manual set, 1 (tolerant) to 10 (severe), 0: the default of the code."""
|
2026-11-16 12:40:03 +01:00
|
|
|
d = folder(station)
|
|
|
|
|
every = data.load(d)
|
|
|
|
|
if targets:
|
|
|
|
|
keep = set(targets.split(","))
|
|
|
|
|
every = {s: ms for s, ms in every.items() if s in keep}
|
|
|
|
|
if not every:
|
|
|
|
|
raise Refusal(f"no \"advanced\" export for {station}" + " with these targets" * bool(targets))
|
|
|
|
|
a, b = span(every, start, end)
|
2026-11-17 09:32:20 +01:00
|
|
|
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"],
|
2026-11-16 12:40:03 +01:00
|
|
|
"targets": [s for s in v["sensors"] if s not in refs], "references": [s for s in v["sensors"] if s in refs],
|
2026-11-17 09:32:20 +01:00
|
|
|
"message": client.message(v["text"]), "action": client.action(v["category"], ep["label"], ep.get("level"), advice)}
|
2026-11-25 11:45:39 +01:00
|
|
|
for i, v in enumerate(window(set_, every, a, b, sensitivity))]
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# --- the labels
|
|
|
|
|
|
|
|
|
|
def label_file(station, source):
|
|
|
|
|
if source not in FOLDERS:
|
|
|
|
|
raise Refusal("unknown label folder")
|
|
|
|
|
folder(station)
|
2026-11-19 11:01:00 +01:00
|
|
|
return LABELS / source / f"{serial(station)}.jsonl"
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
2026-11-17 12:01:23 +01:00
|
|
|
CORE = ("start", "end", "family", "description") # what a label says; the rest (id, review, analysis) is about it
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def core(label):
|
|
|
|
|
return tuple(label.get(k) for k in CORE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def write(f, labels):
|
|
|
|
|
"""Writes the labels next to the file then replaces it: an interruption does not damage it."""
|
|
|
|
|
temp = f.with_name(f.name + ".tmp")
|
|
|
|
|
temp.write_text("".join(json.dumps(e, ensure_ascii=False) + "\n" for e in labels), encoding="utf-8")
|
|
|
|
|
os.replace(temp, f)
|
|
|
|
|
|
|
|
|
|
|
2026-11-16 12:40:03 +01:00
|
|
|
def read(station, source):
|
|
|
|
|
f = label_file(station, source)
|
|
|
|
|
# split and not splitlines: the latter would also cut on the Unicode separators the text may contain
|
|
|
|
|
return [json.loads(l) for l in f.read_text(encoding="utf-8").split("\n") if l.strip()] if f.exists() else []
|
|
|
|
|
|
|
|
|
|
|
2026-11-17 09:32:20 +01:00
|
|
|
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))
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
2026-11-17 09:32:20 +01:00
|
|
|
def checked_range(start, end):
|
|
|
|
|
"""A range asked by the page: YYYY-MM-DDTHH:MMZ, start before end."""
|
2026-11-16 12:40:03 +01:00
|
|
|
try:
|
2026-11-17 09:32:20 +01:00
|
|
|
if datetime.strptime(start, FORMAT) < datetime.strptime(end, FORMAT):
|
|
|
|
|
return
|
2026-11-16 12:40:03 +01:00
|
|
|
except (TypeError, ValueError):
|
2026-11-17 09:32:20 +01:00
|
|
|
pass
|
|
|
|
|
raise Refusal("unreadable or empty range (YYYY-MM-DDTHH:MMZ)")
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def add(body):
|
2026-11-17 09:32:20 +01:00
|
|
|
station, source = body.get("station"), body.get("folder", "auto")
|
2026-11-16 12:40:03 +01:00
|
|
|
f = label_file(station, source)
|
2026-11-17 09:32:20 +01:00
|
|
|
label = {"start": body.get("start"), "end": body.get("end"), "family": body.get("family"),
|
|
|
|
|
"description": (body.get("description") or "").strip()}
|
|
|
|
|
checked(label)
|
2026-11-19 11:01:00 +01:00
|
|
|
ids.assign(serial(station), read(station, source) + [label]) # a stable id, the next of its station (D-131)
|
2026-11-16 12:40:03 +01:00
|
|
|
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:
|
|
|
|
|
out.write(b"\n" * bool(before and not before.endswith(b"\n")) + json.dumps(label, ensure_ascii=False).encode() + b"\n")
|
|
|
|
|
return label
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def update(body):
|
|
|
|
|
before = body.get("before") or {}
|
|
|
|
|
start, end = body.get("start", before.get("start")), body.get("end", before.get("end"))
|
2026-11-17 09:32:20 +01:00
|
|
|
label = dict.fromkeys(("id", "start", "end", "family")) | before | {"start": start, "end": end, "family": body.get("family"),
|
|
|
|
|
"description": (body.get("description") or "").strip()}
|
2026-11-16 12:40:03 +01:00
|
|
|
if label["id"] is None:
|
|
|
|
|
del label["id"]
|
|
|
|
|
label.pop("review", None) # changed: no longer reviewed
|
2026-11-17 09:32:20 +01:00
|
|
|
checked(label)
|
|
|
|
|
return replace(body.get("station"), body.get("folder", "auto"), before, label)
|
2026-11-16 12:40:03 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def delete(body):
|
2026-11-17 09:32:20 +01:00
|
|
|
replace(body.get("station"), body.get("folder", "auto"), body.get("before"), None)
|
2026-11-16 12:40:03 +01:00
|
|
|
return body.get("before")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def replace(station, source, before, label):
|
|
|
|
|
"""Replaces the label before by label (None: removes it), found by its content, not by its rank: the file may have
|
|
|
|
|
changed since the page was loaded. Writes next to it then replaces: an interruption does not damage the file."""
|
|
|
|
|
f = label_file(station, source)
|
|
|
|
|
lines = f.read_text(encoding="utf-8").split("\n") if f.exists() else []
|
|
|
|
|
for i, line in enumerate(lines):
|
|
|
|
|
if line.strip() and json.loads(line) == before:
|
|
|
|
|
lines[i:i + 1] = [] if label is None else [json.dumps(label, ensure_ascii=False)]
|
|
|
|
|
temp = f.with_name(f.name + ".tmp")
|
|
|
|
|
temp.write_text("\n".join(lines), encoding="utf-8")
|
|
|
|
|
os.replace(temp, f)
|
2026-11-17 12:01:23 +01:00
|
|
|
if before.get("analysis"):
|
|
|
|
|
analysis_label(before, label)
|
2026-11-16 12:40:03 +01:00
|
|
|
return label
|
|
|
|
|
raise Refusal("this label is no longer in the file: reload the page")
|
2026-11-17 12:01:23 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def analysis_label(before, label):
|
|
|
|
|
"""A label of an analysis edited or removed in the page: the same in the labels.jsonl of the analysis, which says
|
|
|
|
|
whether it is validated (its review); a resubmission then keeps the edit."""
|
|
|
|
|
f = LABELS / "auto" / "analyses" / before["analysis"] / "labels.jsonl"
|
|
|
|
|
if not f.exists():
|
|
|
|
|
return
|
|
|
|
|
labels = [json.loads(l) for l in f.read_text(encoding="utf-8").split("\n") if l.strip()]
|
|
|
|
|
for i, e in enumerate(labels):
|
|
|
|
|
if core(e) == core(before):
|
|
|
|
|
labels[i:i + 1] = [] if label is None else [{k: label[k] for k in (*CORE, "review") if k in label}]
|
|
|
|
|
write(f, labels)
|
|
|
|
|
return
|