The app only calls the methods of aimsight-data: extraction/pumping.py, weather/meteoswiss.py (weather/ moved there)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-17 09:12:17 +01:00
1 parent b2923d8d49
commit d34828ab5e
7 files changed
+36 -279

No files matched your search

+29 -74
View File
@@ -2,26 +2,29 @@
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}/ and in the list of the tracked stations (extraction/stations.txt of ~/aimsight-data).
labeling/{auto,manual}/. 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
import functools
import csv
import fcntl
import glob
import json
import os
import re
import statistics
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"), str(ROOT / "weather")]
# ~/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"),
str(DATA_REPOSITORY / "extraction"), str(DATA_REPOSITORY / "weather")]
import data # noqa: E402
import meteoswiss # noqa: E402
import pumping # noqa: E402
from categories import events # noqa: E402
# data/ and labeling/ are links to ~/aimsight-data/data and ~/aimsight-labeling: no resolve(), the agents see data/ and labeling/
@@ -184,7 +187,7 @@ def curves(station, start, end):
if not out:
raise Refusal(f"no measurement of {station} in this range")
result = {"A": data.iso(a), "B": data.iso(b), "T": T, "plots": out}
if place := tracked().get(station): # the weather at the position of the station (stations.txt), if it has one
if place := pumping.tracked().get(station): # the weather at the position of the station (stations.txt), if it has one
try:
label, times, plots = weather(place, a, b)
T.update(times)
@@ -195,7 +198,7 @@ def curves(station, start, end):
return result
# --- the Data page, the weather at a place (weather/meteoswiss.py): plots "Weather: …" on the range of the curves
# --- the Data page, the weather at a place (weather/meteoswiss.py of ~/aimsight-data): plots "Weather: …" on the range of the curves
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"),
@@ -207,103 +210,55 @@ def weather(place, a, b):
"""-> (label, T, plots) as curves(): the hourly values of the MeteoSwiss station nearest to the place ("lat,lon" or
a Swiss place name), over [a, b); their times under T["system:weather"], so that the target filters ignore them."""
try:
lat, lon, name = meteoswiss.locate(place)
st = meteoswiss.nearest_station(lat, lon)
rows = meteoswiss.read_rows(meteoswiss.files_for(st["station_abbr"], a, b), a, b)
where, hours = meteoswiss.hourly(place, a, b)
except LookupError as e:
raise Refusal(str(e))
except OSError as e:
raise Refusal(f"MeteoSwiss unreachable: {e}")
param = {c: p for p, c in meteoswiss.PARAMETERS.items()}
times = sorted(rows)
value = lambda r, c: float(r[param[c]]) if r.get(param[c], "").replace(".", "", 1).lstrip("-").isdigit() else None # noqa: E731
times = list(hours)
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"}}
for i, (c, y) in enumerate((c, [value(rows[t], c) for t in times]) for c in columns) if any(v is not None for v in y)]
for i, (c, y) in enumerate((c, [hours[t][c] for t in times]) for c in columns) if any(v is not None for v in y)]
if traces:
plots.append({"title": "Weather: " + title, "traces": traces})
if not plots:
raise Refusal(f"no MeteoSwiss measurement at {st['station_name']} in this range")
return (f"{name} → MeteoSwiss {st['station_abbr']} {st['station_name']}, {st['distance_km']:.1f} km, "
f"{float(st['station_height_masl']):.0f} m",
raise Refusal(f"no MeteoSwiss measurement at {where['name']} in this range")
return (f"{where['place']} → MeteoSwiss {where['station']} {where['name']}, {where['distance_km']:.1f} km, "
f"{where['height_m']:.0f} m",
{"system:weather": [t.strftime("%Y-%m-%d %H:%M") for t in times]}, plots)
# --- the tracked stations and the pumping, in ~/aimsight-data (the repository of data/): extraction/stations.txt, one
# station per line, "SERIAL [position]" (position: "lat,lon" or a Swiss place, for the weather); extraction/pump.sh
# --- the tracked stations and the pumping: extraction/pumping.py of ~/aimsight-data
PUMPING = DATA.resolve().parent
SERIAL = re.compile(r"[A-Za-z0-9_-]+$") # it becomes an argument of pump.sh and a folder of data/
DAY = re.compile(r"\d{4}-\d{2}-\d{2}$")
pump_process = None
def tracked():
"""{serial: position ("" without)}, in the order of the file, without duplicates."""
f = PUMPING / "extraction" / "stations.txt"
lines = f.read_text().splitlines() if f.is_file() else []
out = {}
for line in lines:
serial, _, position = line.strip().partition(" ")
if serial:
out.setdefault(serial, position.strip())
return out
pump_process = None # the pumping launched by the app
def save_tracked(rows):
"""rows: [{serial, position}] -> the new stations.txt."""
out = {}
for r in rows:
serial, position = str(r.get("serial", "")).strip(), " ".join(str(r.get("position", "")).split())
if not SERIAL.match(serial):
raise Refusal(f"not a serial number: {serial!r}")
out.setdefault(serial, position)
(PUMPING / "extraction" / "stations.txt").write_text("".join(f"{s} {p}".rstrip() + "\n" for s, p in out.items()))
return [{"serial": s, "position": p} for s, p in out.items()]
try:
return [{"serial": s, "position": p} for s, p in pumping.save(rows).items()]
except ValueError as e:
raise Refusal(str(e))
def pumping():
"""{running, log}: a pumping running (the app's, the scheduler's or by hand: the lock of pump.sh), the end of
out/pump.log. The end of the app's pumping empties the cache of the detectors' events."""
def pump_state():
"""{running, log}; the end of the app's pumping empties the cache of the detectors' events."""
global pump_process
if pump_process and pump_process.poll() is not None:
pump_process = None
detectors.cache_clear()
try:
with open(PUMPING / "out" / "pump.lock") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
running = False
except FileNotFoundError:
running = False
except BlockingIOError:
running = True
try:
with open(PUMPING / "out" / "pump.log", "rb") as f:
f.seek(max(0, f.seek(0, os.SEEK_END) - 8000))
log = f.read().decode(errors="replace").splitlines()[-40:]
except FileNotFoundError:
log = []
return {"running": running or pump_process is not None, "log": log}
return {"running": pumping.running() or pump_process is not None, "log": pumping.log()}
def pump(body):
"""{stations, start, end, images}: pump.sh in the background, with --from start --to end, or without (the missing
days of each station up to now)."""
global pump_process
stations, start, end = body.get("stations") or [], body.get("start") or "", body.get("end") or ""
if not stations or not all(isinstance(s, str) and SERIAL.match(s) for s in stations):
raise Refusal("no station, or not a serial number")
if bool(start) != bool(end) or (start and not (DAY.match(start) and DAY.match(end) and start < end)):
raise Refusal("a range: From and To, YYYY-MM-DD, From before To")
if pumping()["running"]:
raise Refusal("a pumping is already running")
args = ["--from", start, "--to", end] * bool(start) + ["--images"] * bool(body.get("images")) + ["--delay", "300", *stations]
pump_process = subprocess.Popen([str(PUMPING / "extraction" / "pump.sh"), *args], cwd=PUMPING,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return pumping()
try:
pump_process = pumping.start(body.get("stations") or [], body.get("start") or "", body.get("end") or "", body.get("images"))
except ValueError as e:
raise Refusal(str(e))
return pump_state()
# --- the Data page, "Detectors" labels: the events of the journal, read-only