Support tab (agents:support on a range with a question, instructions/support.md, its answer in labeling/auto/support/); the weather read from data/<STATION>/weather/ (pumped), no call to MeteoSwiss from the app; plots in mm (corr_x_mm, corr_y_mm); analyst instructions: the weather pumped, the targets in mm and their distance

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-18 07:17:51 +01:00
1 parent 60d10a282c
commit 161fb0212f
12 files changed
+405 -95

No files matched your search

+2 -2
View File
@@ -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`. 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 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 links** (ignored by git, one copy of each repository on the workstation): `data/`, `labeling/`, `detectors/`, `tools/`, `agents/`, `optimizer/`, `models/` (the pilot of learned detectors); each thing is committed in its own repository, never here. This repository carries no agent, no reading tool, no workflow. - **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); 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 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`, `weather/meteoswiss.py` `hourly`); with the agents, `agents/README.md` (the request of the analyst); with Optimizer, `optimizer/README.md` (the request of `/optimize`). 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`); with the data, `~/aimsight-data` (`extraction/pumping.py`; the weather is pumped into `data/<STATION>/weather/`); with the agents, `agents/README.md` (the requests of the analyst and of the support); with Optimizer, `optimizer/README.md` (the request of `/optimize`). 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 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. - **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`. - **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`.
+4 -3
View File
@@ -1,16 +1,17 @@
# aimsight-app # aimsight-app
The control station of the AIMsight diagnostic: see, analyze, launch. The Data page shows the curves, the camera images, the labels and the detectors' events; its Analysis tab launches, by `claude -p`, processes whose code lives in the other repositories: The control station of the AIMsight diagnostic: see, analyze, launch. The Data page shows the curves, the camera images, the labels and the detectors' events; its Analysis and Support tabs launch, by `claude -p`, processes whose code lives in the other repositories:
- **"Analyze the range"**: the `analyst` of the agents repository, on a chosen range, with the app's instructions (`instructions/analyst.md`) and without the detectors (`DETECTORS: no`): labels, submitted to `labeling/auto/`, and a diagnostic report; - **"Analyze the range"**: the `analyst` of the agents repository, on a chosen range, with the app's instructions (`instructions/analyst.md`) and without the detectors (`DETECTORS: no`): labels, submitted to `labeling/auto/`, and a diagnostic report;
- **"Optimize the detectors"**, on a finished analysis: `/optimize` in Optimizer, on the analysis: it improves the detectors on the range of the analysis, its labels as truth, without overfitting; then it brings the analyst's scripts into the reading harness (tools repository). - **"Optimize the detectors"**, on a finished analysis: `/optimize` in Optimizer, on the analysis: it improves the detectors on the range of the analysis, its labels as truth, without overfitting; then it brings the analyst's scripts into the reading harness (tools repository);
- **"Ask the support"** (Support tab): the `support` of the agents repository, on a chosen range, with a question and the app's instructions (`instructions/support.md`): it answers as it judges best, itself or through the analyst it launches; its answer and its work in `labeling/auto/support/`, its analyst's labels submitted nowhere.
The architecture of the repositories, one responsibility each: `docs/architecture.drawio`. The architecture of the repositories, one responsibility each: `docs/architecture.drawio`.
## The repository ## The repository
- `app/`: the web app (FastAPI server, React and Mantine page); its doc in `app/README.md`. - `app/`: the web app (FastAPI server, React and Mantine page); its doc in `app/README.md`.
- `instructions/analyst.md`: what the app asks of the analyst (output folder, report, dialogue). - `instructions/analyst.md`: what the app asks of the analyst (output folder, report, dialogue); `instructions/support.md`, of the support (how free it is, its answer, dialogue).
- `docs/`: the architecture of the repositories, the plans. - `docs/`: the architecture of the repositories, the plans.
And seven links, ignored by git, to the neighbouring repositories (a single copy of each on the workstation): And seven links, ignored by git, to the neighbouring repositories (a single copy of each on the workstation):
+12 -5
View File
@@ -8,19 +8,20 @@ The tool of the manual diagnostic: two pages, **Data** and **Stations**.
- **The labels**, under the plots, and their bar, according to the chosen source: - **The labels**, under the plots, and their bar, according to the chosen source:
- **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); - **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; - **LLM**: `labeling/auto/<STATION>.jsonl`, read-only;
- **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`). - **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`);
- **Support**: the same labels, read-only, to ask the support a question on a range.
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/`. With Detectors and LLM, dragging on the bar zooms in time; with Analysis and Support, it selects a range to analyze, or to ask about. 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. - **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.
- **The diagnostic settings**, under the image: "Focus on event curves" (with an event open, the plots show only its sensors: those of the detectors, or those the text of a label names), the families shown and, for Detectors only, the targets considered, the others removed before the detectors ("Rerun the detectors", parameter `targets` of `/api/detectors`). - **The diagnostic settings**, under the image: "Focus on event curves" (with an event open, the plots show only its sensors: those of the detectors, or those the text of a label names), the families shown and, for Detectors only, the targets considered, the others removed before the detectors ("Rerun the detectors", parameter `targets` of `/api/detectors`).
- **The weather**: a station with a position gets, at Load, the hourly measurements of the nearest MeteoSwiss station (`weather/meteoswiss.py` of `~/aimsight-data`, `hourly`) as plots "Weather: …", next to the "System: …" ones; the place found and the station chosen are written under the selector (check them: the search of a place always returns its best match). - **The weather**: a station with a position gets, at Load, the hourly measurements of the nearest MeteoSwiss station, pumped with its data (`data/<STATION>/weather/`, `data.load_weather`), as plots "Weather: …", next to the "System: …" ones; the place found and the station chosen are written under the selector. No call to MeteoSwiss from the app: a range not pumped has no weather.
The address keeps the station and the range (UTC, `end` excluded): `#/data?station=NIEDERHORN&start=2026-09-25&end=2026-10-08`; without dates, the last 5 UTC days, today included. The address keeps the station and the range (UTC, `end` excluded): `#/data?station=NIEDERHORN&start=2026-09-25&end=2026-10-08`; without dates, the last 5 UTC days, today included.
## The Stations page ## The Stations page
The tracked stations, `extraction/stations.txt` of `~/aimsight-data` (`SERIAL [position]`), to edit (serial, position: `lat,lon` or a Swiss place, for the weather of Data; empty for an indoor site: no weather), and the checked ones pumped (`extraction/pump.sh`, `--delay 300`; the list and the pumping through `extraction/pumping.py` of `~/aimsight-data`, the app only calls it) over a range (by default every station, over the range of the address, from 3 days before: the history of the detectors) or, without dates, their missing days up to now; the end of `out/pump.log` follows. The end of a pumping launched by the app empties the cache of the detectors' events. The tracked stations, `extraction/stations.txt` of `~/aimsight-data` (`SERIAL [position]`), to edit (serial, position: `lat,lon` or a Swiss place, for the weather pumped with the data; empty for an indoor site: no weather), and the checked ones pumped (`extraction/pump.sh`, `--delay 300`; the list and the pumping through `extraction/pumping.py` of `~/aimsight-data`, the app only calls it) over a range (by default every station, over the range of the address, from 3 days before: the history of the detectors) or, without dates, their missing days up to now; the end of `out/pump.log` follows. The end of a pumping launched by the app empties the cache of the detectors' events.
## The Analysis tab ## The Analysis tab
@@ -29,6 +30,11 @@ The tracked stations, `extraction/stations.txt` of `~/aimsight-data` (`SERIAL [p
- **The messages**: after the report, the user writes to the analyst, the same session resumes (`--resume`). An analysis stops with the server ("interrupted"); "continue" in the message field resumes it. - **The messages**: after the report, the user writes to the analyst, the same session resumes (`--resume`). An analysis stops with the server ("interrupted"); "continue" in the message field resumes it.
- **Optimize the detectors**, on a finished analysis: `/optimize` in Optimizer (`optimizer/`, with the plugin `agents/`) on the analysis: the detectors, then the reading tools; the detectors committed in `detectors/`, the reading tools in `tools/`, each on its current branch. The page follows the thread of the session (`work/optimization.jsonl`), then shows its summary under the report (`optimizer/sessions/<analysis>_<time>/summary.md`, and the `<analysis>/tools.md` of an older session). One optimization at a time; meanwhile, no analysis and no message to the analyst; an optimization cut by the server stopping is rerun with the button. The detectors' events are kept in memory until the end of an optimization: after an `/optimize` run outside the app, restart the server. - **Optimize the detectors**, on a finished analysis: `/optimize` in Optimizer (`optimizer/`, with the plugin `agents/`) on the analysis: the detectors, then the reading tools; the detectors committed in `detectors/`, the reading tools in `tools/`, each on its current branch. The page follows the thread of the session (`work/optimization.jsonl`), then shows its summary under the report (`optimizer/sessions/<analysis>_<time>/summary.md`, and the `<analysis>/tools.md` of an older session). One optimization at a time; meanwhile, no analysis and no message to the analyst; an optimization cut by the server stopping is rerun with the button. The detectors' events are kept in memory until the end of an optimization: after an `/optimize` run outside the app, restart the server.
## The Support tab
- **Ask the support**: a range selected, a question (required), then `server/support.py` launches the support of the agents repository by `claude -p`, with its instructions (`instructions/support.md`): free to answer as it judges best, itself (the labels, the analyses, a short reading of the data, the knowledge base) or through the analyst it launches on the range or a wider one (`DETECTORS: yes`, in the foreground: up to 3 h per command, `BASH_MAX_TIMEOUT_MS`). It writes in `labeling/auto/support/<STATION>_<start>_<end>/` its answer (`answer.md` and its figures), `request.md`, and its analyst's work in `analyst/`, whose labels are submitted nowhere. The page follows its progress, then shows the answer.
- **The sidebar**, **the messages**, the stop with the server: as for an analysis (`labeling/auto/support/`; only the requests of the app, which carry `request.json`). No support while an optimization runs.
## Launch ## Launch
The VS Code task **Run app** (`.vscode/tasks.json`), or by hand (Node 22 for the front end): The VS Code task **Run app** (`.vscode/tasks.json`), or by hand (Node 22 for the front end):
@@ -42,9 +48,10 @@ The page opens on `http://127.0.0.1:8770`. Settings by variables: `AIMSIGHT_DATA
## The folders ## The folders
- `server/server.py`: FastAPI; serves the built page and the API under `/api` (stations, images, curves, detectors, labels, analyses); answers only the pages of the workstation (local Host, declared JSON). - `server/server.py`: FastAPI; serves the built page and the API under `/api` (stations, images, curves, detectors, labels, analyses, support); answers only the pages of the workstation (local Host, declared JSON).
- `server/station.py`: the data of the Data page; read-only on `data/` (through `tools/scripts/data.py`), writes only in `labeling/{auto,manual}/`. - `server/station.py`: the data of the Data page; read-only on `data/` (through `tools/scripts/data.py`), writes only in `labeling/{auto,manual}/`.
- `server/analysis.py`: the Analysis tab; launches `claude` with the agent `agents:analyst` (Read, Write, Bash allowed without asking); and the optimization, `/optimize` in Optimizer (Read, Write, Edit, Bash, Agent). - `server/analysis.py`: the Analysis tab; launches `claude` with the agent `agents:analyst` (Read, Write, Bash allowed without asking); and the optimization, `/optimize` in Optimizer (Read, Write, Edit, Bash, Agent).
- `server/support.py`: the Support tab; launches `claude` with the agent `agents:support` (Read, Write, Edit, Bash, Glob, Grep allowed without asking), through `analysis.run`.
- `server/check.py`: checks, without calling claude: `.venv/bin/python app/server/check.py`. - `server/check.py`: checks, without calling claude: `.venv/bin/python app/server/check.py`.
- `web/`: React (Vite) and Mantine; `src/App.jsx` (header, sidebar, address), `src/pages/Data.jsx` (the page), `src/pages/Images.jsx` (the images, in Data), `src/common.jsx` (requests, selector), `src/main.jsx` (theme). Plotly, dressed in Mantine's colours, loads only with Data. `dist/` and `node_modules/` outside git. - `web/`: React (Vite) and Mantine; `src/App.jsx` (header, sidebar, address), `src/pages/Data.jsx` (the page), `src/pages/Images.jsx` (the images, in Data), `src/common.jsx` (requests, selector), `src/main.jsx` (theme). Plotly, dressed in Mantine's colours, loads only with Data. `dist/` and `node_modules/` outside git.
+19 -11
View File
@@ -81,15 +81,15 @@ def launch(body):
return {"name": name} return {"name": name}
def work(name, out, prompt, resume=None): def run(a, out, prompt, resume, agent, tools, env=None):
"""A turn of the analyst: the request, or a message of the user in the same session (resume: its id).""" """A turn of an agent of the plugin by claude -p, from the root: its stream in work/log.jsonl and in a["lines"], its
a = analyses[name] session in work/session (resume: its id)."""
try: p = subprocess.Popen(["claude", "-p", prompt, "--plugin-dir", str(AGENTS), "--agent", f"agents:{agent}", *ISOLATED,
p = subprocess.Popen(["claude", "-p", prompt, "--plugin-dir", str(AGENTS), "--agent", "agents:analyst", *ISOLATED,
"--output-format", "stream-json", "--verbose", "--output-format", "stream-json", "--verbose",
"--allowedTools", "Read,Write,Bash", "--permission-mode", "acceptEdits", *station.links()] "--allowedTools", tools, "--permission-mode", "acceptEdits", *station.links()]
+ (["--resume", resume] if resume else []), + (["--resume", resume] if resume else []),
cwd=station.ROOT, env=_env(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) cwd=station.ROOT, env=_env() | (env or {}), stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True)
with open(out / "work" / "log.jsonl", "a", encoding="utf-8") as log: with open(out / "work" / "log.jsonl", "a", encoding="utf-8") as log:
for line in p.stdout: for line in p.stdout:
log.write(line) log.write(line)
@@ -98,6 +98,13 @@ def work(name, out, prompt, resume=None):
(out / "work" / "session").write_text(json.loads(line)["session_id"]) (out / "work" / "session").write_text(json.loads(line)["session_id"])
if p.wait(): if p.wait():
raise RuntimeError(f"claude ended with code {p.returncode}") raise RuntimeError(f"claude ended with code {p.returncode}")
def work(name, out, prompt, resume=None):
"""A turn of the analyst: the request, or a message of the user in the same session (resume: its id)."""
a = analyses[name]
try:
run(a, out, prompt, resume, "analyst", "Read,Write,Bash")
a["submitted"] = submit(a["station"], name, out) a["submitted"] = submit(a["station"], name, out)
a["state"] = "done" a["state"] = "done"
except Exception as e: # noqa: BLE001 — the error shows in the page, the server goes on except Exception as e: # noqa: BLE001 — the error shows in the page, the server goes on
@@ -234,10 +241,11 @@ def list_analyses():
return out return out
def file(name, path): def file(name, path, folder=None):
"""A file of the folder of the analysis (the report, its figures), never outside.""" """A file of the folder of the analysis (the report, its figures; or of a support request), never outside."""
f = (FOLDER / name / path).resolve() folder = folder or FOLDER
if not f.is_file() or not f.is_relative_to(FOLDER.resolve()): f = (folder / name / path).resolve()
if not f.is_file() or not f.is_relative_to(folder.resolve()):
raise station.Refusal("unknown file") raise station.Refusal("unknown file")
return f return f
+70 -1
View File
@@ -46,6 +46,8 @@ def check_server():
assert call("/api/labels", {"station": "x"}, {"Content-Type": "text/plain"}) == 403 assert call("/api/labels", {"station": "x"}, {"Content-Type": "text/plain"}) == 403
assert call("/api/stations") == 200 assert call("/api/stations") == 200
assert call("/api/analyses") == 200 assert call("/api/analyses") == 200
assert call("/api/support") == 200
assert call("/api/support", {"station": "x"}) == 400
assert call("/api/analyses/UNKNOWN/optimize", {}) == 400 assert call("/api/analyses/UNKNOWN/optimize", {}) == 400
finally: finally:
srv.should_exit = True srv.should_exit = True
@@ -308,7 +310,74 @@ def check_validation():
analysis.analyses.clear() analysis.analyses.clear()
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation] def check_support():
# "Ask the support" then a message (support.launch, support.message), without claude: the support of the agents
# repository, its request (the question, its instructions, its absolute folder), the long commands it is given, the
# resumption of its session, its answer in the page; the state read again after a restart
import analysis
import support
launched = []
class FakeProcess:
returncode = 0
def __init__(self, args, *a, **k):
launched.append((args, k))
self.stdout = iter(['{"type":"system","subtype":"init","session_id":"s-1"}\n'])
def wait(self):
return 0
root = temp_folder()
before = support.FOLDER, analysis.subprocess.Popen, analysis.AGENTS
support.FOLDER, analysis.AGENTS, analysis.subprocess.Popen = root / "support", root / "agents", FakeProcess
key = os.environ.get("ANTHROPIC_API_KEY")
os.environ["ANTHROPIC_API_KEY"] = "test-key"
ask = {"station": "NORDEND", "start": "2026-11-05T06:00Z", "end": "2026-11-05T12:00Z", "question": "Why the jump?"}
try:
assert "agents/" in refuses(support.launch, ask)
(analysis.AGENTS / "agents").mkdir(parents=True)
(analysis.AGENTS / "agents" / "support.md").write_text("support")
assert "question" in refuses(support.launch, ask | {"question": " "})
name = support.launch(ask)["name"]
while support.supports[name]["state"] == "running":
time.sleep(0.05)
assert support.state(name)["state"] == "done" and support.state(name)["report"] is None, support.state(name)
args, k = launched[0]
assert args[args.index("--agent") + 1] == "agents:support" and "Edit" in args[args.index("--allowedTools") + 1], args
assert "ANTHROPIC_API_KEY" not in k["env"] and k["env"]["BASH_MAX_TIMEOUT_MS"] == "10800000", sorted(k["env"])
out = support.FOLDER / name
assert f"Output folder: {out}/." in args[2] and f"INSTRUCTIONS: {support.INSTRUCTIONS}." in args[2] \
and args[2].endswith("Question: Why the jump?") and support.INSTRUCTIONS.is_file(), args[2]
assert (out / "work" / "session").read_text() == "s-1"
assert support.launch(ask)["name"].startswith(name + "_") # another question on the same range, next to it
(out / "answer.md").write_text("# NORDEND: a jump\n\n![curves](fig.png)")
(out / "fig.png").write_bytes(b"png")
assert support.state(name)["report"] and "<h1>NORDEND: a jump</h1>" in support.answer(name, False)
assert analysis.file(name, "fig.png", support.FOLDER).is_file()
refuses(analysis.file, name, "../../agents/agents/support.md", support.FOLDER)
while any(s["state"] == "running" for s in support.supports.values()):
time.sleep(0.05)
support.message(name, {"text": "And the night before?"})
while support.supports[name]["state"] == "running":
time.sleep(0.05)
args = launched[-1][0]
assert args[args.index("--resume") + 1] == "s-1" and args[2].startswith("And the night before?"), args
support.supports.clear() # after a restart: the thread read again in the log, done with its answer
s = support.state(name)
assert s["state"] == "done" and s["lines"] == ["› And the night before?"], s
assert {x["name"]: x["state"] for x in support.list_supports()}[name] == "done" # the sidebar
refuses(support.state, "../analyses")
finally:
os.environ.pop("ANTHROPIC_API_KEY")
if key is not None:
os.environ["ANTHROPIC_API_KEY"] = key
shutil.rmtree(root)
support.FOLDER, analysis.subprocess.Popen, analysis.AGENTS = before
support.supports.clear()
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support]
if __name__ == "__main__": if __name__ == "__main__":
name = sys.argv[1] if len(sys.argv) > 1 else None name = sys.argv[1] if len(sys.argv) > 1 else None
+34 -1
View File
@@ -2,7 +2,7 @@
The FastAPI server serves the built React page (app/web/dist, `npm run build` in app/web) and the API under /api. The FastAPI server serves the built React page (app/web/dist, `npm run build` in app/web) and the API under /api.
The Data page reads data/ and the labels of labeling/ (station.py); its Analysis tab launches the analyst, and the The Data page reads data/ and the labels of labeling/ (station.py); its Analysis tab launches the analyst, and the
optimization of the detectors (analysis.py). optimization of the detectors (analysis.py); its Support tab, the support (support.py).
Settings: AIMSIGHT_DATA (data), AIMSIGHT_LABELS (labels), AIMSIGHT_PORT (port, 8770). Settings: AIMSIGHT_DATA (data), AIMSIGHT_LABELS (labels), AIMSIGHT_PORT (port, 8770).
""" """
import json import json
@@ -20,6 +20,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
import analysis import analysis
import station import station
import support
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
APP = Path(__file__).resolve().parents[1] APP = Path(__file__).resolve().parents[1]
@@ -167,6 +168,38 @@ def analysis_file(name: str, path: str):
return FileResponse(analysis.file(name, path)) return FileResponse(analysis.file(name, path))
# --- the Support tab of the Data page (support.py): the support launched by claude -p on a range, with a question
@app.post("/api/support")
def launch_support(body: dict):
return support.launch(body)
@app.get("/api/support")
def supports():
return support.list_supports()
@app.get("/api/support/{name}")
def support_state(name: str):
return support.state(name)
@app.post("/api/support/{name}/message")
def support_message(name: str, body: dict):
return support.message(name, body)
@app.get("/api/support/{name}/report.html")
def support_answer(name: str, dark: bool = False):
return HTMLResponse(support.answer(name, dark))
@app.get("/api/support/{name}/{path:path}")
def support_file(name: str, path: str):
return FileResponse(analysis.file(name, path, support.FOLDER))
if PAGE.is_dir(): if PAGE.is_dir():
app.mount("/", StaticFiles(directory=PAGE, html=True), name="page") app.mount("/", StaticFiles(directory=PAGE, html=True), name="page")
else: else:
+18 -27
View File
@@ -3,8 +3,8 @@
Data are read as the agents read them, tools/scripts/data.py (the tools repository, through the tools/ link); the detectors' 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 (window); the rules of the labels and what the client is told, those of 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/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 labeling/auto/. What brings data in (the pumping, the list of the tracked stations) is in ~/aimsight-data, called as it
~/aimsight-data, called as it is (extraction/pumping.py, weather/meteoswiss.py). is (extraction/pumping.py); the weather is pumped with the data, data/<STATION>/weather/ (data.load_weather).
""" """
import bisect import bisect
import functools import functools
@@ -18,15 +18,14 @@ from datetime import datetime, timedelta
from pathlib import Path from pathlib import Path
ROOT = Path(__file__).resolve().parents[2] 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 # ~/aimsight-data, the repository of data/: the method that brings data in (the pumping, the weather with it), called as it is
DATA_REPOSITORY = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).resolve().parent DATA_REPOSITORY = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).resolve().parent
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"), str(ROOT / "labeling" / "scripts"), sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"), str(ROOT / "labeling" / "scripts"),
str(DATA_REPOSITORY / "extraction"), str(DATA_REPOSITORY / "weather")] str(DATA_REPOSITORY / "extraction")]
import categories # noqa: E402 import categories # noqa: E402
import client # noqa: E402 (labeling: what the client is told of an event) import client # noqa: E402 (labeling: what the client is told of an event)
import data # noqa: E402 import data # noqa: E402
import ids # noqa: E402 (labeling: the stable id of the labels) import ids # noqa: E402 (labeling: the stable id of the labels)
import meteoswiss # noqa: E402
import pumping # noqa: E402 import pumping # noqa: E402
import validate # noqa: E402 (labeling: the rules of a label) import validate # noqa: E402 (labeling: the rules of a label)
@@ -49,6 +48,7 @@ POSE = (("pan", "#1a1a19"), ("tilt", "#8a8a85"), ("rotation", "#b5651d"))
PLOTS = (("error_value", "Error value"), ("x", "X [px]"), ("y", "Y [px]"), PLOTS = (("error_value", "Error value"), ("x", "X [px]"), ("y", "Y [px]"),
("relative_x", "Relative Horizontal Shift"), ("relative_y", "Relative Vertical Shift"), ("relative_x", "Relative Horizontal Shift"), ("relative_y", "Relative Vertical Shift"),
("corr_x", "Relative Corrected Horizontal Shift"), ("corr_y", "Relative Corrected Vertical Shift"), ("corr_x", "Relative Corrected Horizontal Shift"), ("corr_y", "Relative Corrected Vertical Shift"),
("corr_x_mm", "Relative Corrected Horizontal Shift [mm]"), ("corr_y_mm", "Relative Corrected Vertical Shift [mm]"),
("reproj_err", "References (reproj. error)")) ("reproj_err", "References (reproj. error)"))
QUALITY = (("peak", "Quality: Peak"), ("flux", "Quality: Flux"), ("sharpness", "Quality: Sharpness"), QUALITY = (("peak", "Quality: Peak"), ("flux", "Quality: Flux"), ("sharpness", "Quality: Sharpness"),
("fwhm", "Quality: FWHM [px]"), ("dominance", "Quality: Dominance"), ("snr", "Quality: SNR")) ("fwhm", "Quality: FWHM [px]"), ("dominance", "Quality: Dominance"), ("snr", "Quality: SNR"))
@@ -177,18 +177,17 @@ def curves(station, start, end):
if not out: if not out:
raise Refusal(f"no measurement of {station} in this range") raise Refusal(f"no measurement of {station} in this range")
result = {"A": data.iso(a), "B": data.iso(b), "T": T, "plots": out} result = {"A": data.iso(a), "B": data.iso(b), "T": T, "plots": out}
if place := pumping.tracked().get(station): # the weather at the position of the station (stations.txt), if it has one if hours := [h for h in data.load_weather(d) if a <= h["t"] < b]: # the weather pumped with the data, if any
try: label, times, plots = weather(hours)
label, times, plots = weather(place, a, b)
T.update(times) T.update(times)
out += plots out += plots
result["weather"] = label result["weather"] = label
except Refusal as e: elif pumping.tracked().get(station):
result["weather"] = f"unavailable ({e})" result["weather"] = "none pumped in this range (see the pumping log)"
return result return result
# --- the Data page, the weather at a place (weather/meteoswiss.py of ~/aimsight-data): plots "Weather: …" on the range of the curves # --- the Data page, the weather pumped in data/<STATION>/weather/ (extraction/weather.py of ~/aimsight-data): plots "Weather: …"
WEATHER = (("Precipitation (mm/h)", "precipitation_mm"), ("Temperature (°C)", "temperature_c"), ("Humidity (%)", "humidity_pct"), 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"), ("Wind (km/h)", "wind_speed_kmh", "wind_gust_kmh"), ("Wind direction (deg)", "wind_direction_deg"),
@@ -196,29 +195,21 @@ WEATHER = (("Precipitation (mm/h)", "precipitation_mm"), ("Temperature (°C)", "
("Global radiation (W/m²)", "global_radiation_wm2"), ("Snow depth (cm)", "snow_depth_cm")) ("Global radiation (W/m²)", "global_radiation_wm2"), ("Snow depth (cm)", "snow_depth_cm"))
def weather(place, a, b): def weather(hours):
"""-> (label, T, plots) as curves(): the hourly values of the MeteoSwiss station nearest to the place ("lat,lon" or """[hour] of data.load_weather, not empty -> (label, T, plots) as curves(); their times under T["system:weather"], so
a Swiss place name), over [a, b); their times under T["system:weather"], so that the target filters ignore them.""" that the target filters ignore them; the label: where the last hour was measured."""
try:
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}")
times = list(hours)
plots = [] plots = []
for title, *columns in WEATHER: for title, *columns in WEATHER:
traces = [{"name": c.rsplit("_", 1)[0].replace("_", " "), "t": "system:weather", "y": y, traces = [{"name": c.rsplit("_", 1)[0].replace("_", " "), "t": "system:weather", "y": y,
"mode": "markers" if "direction" in c else "lines", "mode": "markers" if "direction" in c else "lines",
"line": {"width": 1.2, "color": COLORS[i], "shape": "hv" if c == "precipitation_mm" else "linear"}} "line": {"width": 1.2, "color": COLORS[i], "shape": "hv" if c == "precipitation_mm" else "linear"}}
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)] 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)]
if traces: if traces:
plots.append({"title": "Weather: " + title, "traces": traces}) plots.append({"title": "Weather: " + title, "traces": traces})
if not plots: w = hours[-1]
raise Refusal(f"no MeteoSwiss measurement at {where['name']} in this range") return (f"{w['place']} → MeteoSwiss {w['station']} {w['station_name']}, {w['distance_km']} km, {w['height_m']} m"
return (f"{where['place']} → MeteoSwiss {where['station']} {where['name']}, {where['distance_km']:.1f} km, " + " (no measurement in this range)" * (not plots),
f"{where['height_m']:.0f} m", {"system:weather": [h["t"].strftime("%Y-%m-%d %H:%M") for h in hours]}, plots)
{"system:weather": [t.strftime("%Y-%m-%d %H:%M") for t in times]}, plots)
# --- the tracked stations and the pumping: extraction/pumping.py of ~/aimsight-data # --- the tracked stations and the pumping: extraction/pumping.py of ~/aimsight-data
+118
View File
@@ -0,0 +1,118 @@
"""The Support tab of the Data page: the support of the agents repository (agents/, --agent agents:support), launched by
`claude -p` on a range chosen in the page, with the user's question and its instructions (instructions/support.md). It
answers as it judges best: itself, or through the analyst it launches on the range or a wider one. It writes in
labeling/auto/support/<STATION>_<start>_<end>/ its answer (answer.md, its figures next to it); the labels of its analyst
stay there, submitted nowhere. Then the user can write to it: the same session resumes (`claude -p --resume`).
"""
import json
import threading
from datetime import datetime, timezone
import analysis
import station
FOLDER = station.LABELS / "auto" / "support"
INSTRUCTIONS = station.ROOT / "instructions" / "support.md"
REQUEST = """Station: data/{station}/. Range: {start} → {end} (UTC). Output folder: {out}/. INSTRUCTIONS: {instructions}.
Question: {question}"""
TOOLS = "Read,Write,Edit,Bash,Glob,Grep"
# the analyst it launches runs in the foreground, inside one of its commands: up to 3 h (claude -p ends with its turn)
ENV = {"BASH_DEFAULT_TIMEOUT_MS": "10800000", "BASH_MAX_TIMEOUT_MS": "10800000"}
# name -> {"state": "running" | "done" | "error", "lines": [...], "request": {...}}
supports = {}
def launch(body):
st, start, end = body.get("station"), body.get("start"), body.get("end")
question = (body.get("question") or "").strip()
station.checked_range(start, end)
station.folder(st)
if not question:
raise station.Refusal("no question for the support")
if not (analysis.AGENTS / "agents" / "support.md").exists():
raise station.Refusal("no support in agents/ (the link: README.md)")
name = f"{st}_{start[:16].replace(':', '')}_{end[:16].replace(':', '')}"
with analysis.lock:
if analysis._optimizing():
raise station.Refusal(analysis.BUSY)
out = FOLDER / name
if out.exists(): # another question on the same range: the earlier one stays, next to it
name += datetime.now(timezone.utc).strftime("_%H%M%S")
out = FOLDER / name
request = {"station": st, "start": start, "end": end, "question": question}
supports[name] = {"state": "running", "lines": [], "request": request}
(out / "work").mkdir(parents=True)
(out / "request.json").write_text(json.dumps(request, ensure_ascii=False, indent=1), encoding="utf-8")
prompt = REQUEST.format(station=st, start=start, end=end, out=out, instructions=INSTRUCTIONS, question=question)
threading.Thread(target=work, args=(name, out, prompt), daemon=True).start()
return {"name": name}
def work(name, out, prompt, resume=None):
"""A turn of the support: the request, or a message of the user in the same session (resume: its id)."""
s = supports[name]
try:
analysis.run(s, out, prompt, resume, "support", TOOLS, ENV)
s["state"] = "done"
except Exception as e: # noqa: BLE001 — the error shows in the page, the server goes on
s["lines"].append(f"Error: {e}")
s["state"] = "error"
def message(name, body):
"""A message of the user to the support: the same session resumes (claude -p --resume)."""
text, out = (body.get("text") or "").strip(), FOLDER / name
state(name) # the name checked, the state read again after a restart
s, session = supports[name], out / "work" / "session"
if not text or not session.exists():
raise station.Refusal("empty message, or the support has no session to resume")
with analysis.lock:
if analysis._optimizing():
raise station.Refusal(analysis.BUSY)
if s["state"] == "running":
raise station.Refusal("the support is still working")
s["state"] = "running"
line = json.dumps({"type": "page", "text": text}, ensure_ascii=False) + "\n"
with open(out / "work" / "log.jsonl", "a", encoding="utf-8") as log:
log.write(line)
s["lines"] += analysis.digest(line)
prompt = f"{text}\n\n(If your answer changes, rewrite {out}/answer.md in full: the page shows it again.)"
threading.Thread(target=work, args=(name, out, prompt, session.read_text()), daemon=True).start()
return {}
def _ended(out):
"""The state of a request the server does not hold (after a restart): done with an answer, otherwise interrupted."""
return "done" if (out / "answer.md").exists() else "interrupted"
def state(name):
out = FOLDER / name
if "/" in name or name.startswith(".") or not (out / "request.json").is_file():
raise station.Refusal("unknown support request")
if name not in supports: # after a restart of the server, only the folder is left: the thread is read again in the log
log = out / "work" / "log.jsonl"
supports[name] = {"state": _ended(out), "request": json.loads((out / "request.json").read_text(encoding="utf-8")),
"lines": [r for l in open(log, encoding="utf-8") for r in analysis.digest(l)] if log.exists() else []}
s, r = supports[name], out / "answer.md"
# report and submitted: the names of the Analysis panel, which the page reuses (no labels submitted here)
return {"name": name, "state": s["state"], "lines": s["lines"], "submitted": None, "request": s["request"],
"report": int(r.stat().st_mtime) if r.exists() else None, "dialogue": (out / "work" / "session").exists()}
def list_supports():
"""The history of the requests (the sidebar), the most recent first. Only those of the app: a folder of the support
launched elsewhere has no request.json."""
out = []
for f in sorted(FOLDER.glob("*/request.json"), key=lambda f: f.parent.stat().st_mtime, reverse=True):
name = f.parent.name
s = supports.get(name) or {"state": _ended(f.parent), "request": json.loads(f.read_text(encoding="utf-8"))}
out.append({"name": name, "state": s["state"]} | s["request"])
return out
def answer(name, dark):
"""answer.md in HTML, served in the folder of the request: its relative images are found there."""
return analysis._page(analysis.file(name, "answer.md", FOLDER).read_text(encoding="utf-8"), name, dark)
+17 -12
View File
@@ -50,7 +50,8 @@ function Header({ mobile, desktop, toggle }) {
// The analyses of the Data page (labeling/auto/analyses/), read again every 3 s: one folder per station, open by default if // The analyses of the Data page (labeling/auto/analyses/), read again every 3 s: one folder per station, open by default if
// it has one running, and inside one analysis per range (a green tick: its labels validated); a click opens Data on its // it has one running, and inside one analysis per range (a green tick: its labels validated); a click opens Data on its
// station and its days, and shows its report there // station and its days, and shows its report there. kind "support": the requests of the Support tab (labeling/auto/support/),
// the same without labels to validate
// The range of an analysis on two lines, too wide for the sidebar on one: the days "04.11 – 07.11" ("01.11" within the day), // The range of an analysis on two lines, too wide for the sidebar on one: the days "04.11 – 07.11" ("01.11" within the day),
// under them the hours "21:12 – 14:12" (UTC) // under them the hours "21:12 – 14:12" (UTC)
const dayMonth = t => `${t.slice(8, 10)}.${t.slice(5, 7)}`, hour = t => t.slice(11, 16); const dayMonth = t => `${t.slice(8, 10)}.${t.slice(5, 7)}`, hour = t => t.slice(11, 16);
@@ -60,10 +61,10 @@ const STATE_COLOR = { done: "teal", error: "red", interrupted: "gray" };
// The state: a spinning wheel while running, otherwise a coloured dot (its name in the tooltip) // The state: a spinning wheel while running, otherwise a coloured dot (its name in the tooltip)
const Dot = ({ state }) => (state === "running" ? <Loader size={10} color="orange" /> const Dot = ({ state }) => (state === "running" ? <Loader size={10} color="orange" />
: <Tooltip label={state}><ColorSwatch size={8} color={`var(--mantine-color-${STATE_COLOR[state] || "gray"}-6)`} withShadow={false} /></Tooltip>); : <Tooltip label={state}><ColorSwatch size={8} color={`var(--mantine-color-${STATE_COLOR[state] || "gray"}-6)`} withShadow={false} /></Tooltip>);
function Analyses({ open }) { function Analyses({ kind = "analyses", open }) {
const [list, setList] = useState([]); const [list, setList] = useState([]), labels = kind === "analyses";
useEffect(() => { useEffect(() => {
const read = () => fetch("/api/analyses").then(r => r.ok && r.json()).then(l => l && setList(l)).catch(() => {}); // silently: every 3 s const read = () => fetch(`/api/${kind}`).then(r => r.ok && r.json()).then(l => l && setList(l)).catch(() => {}); // silently: every 3 s
read(); read();
const timer = setInterval(read, 3000); const timer = setInterval(read, 3000);
return () => clearInterval(timer); return () => clearInterval(timer);
@@ -71,19 +72,19 @@ function Analyses({ open }) {
if (!list.length) return null; if (!list.length) return null;
const stations = [...new Set(list.map(a => a.station))].sort(); const stations = [...new Set(list.map(a => a.station))].sort();
return <> return <>
<Text size="xs" fw={700} tt="uppercase" c="dimmed" px="sm" pt="lg" pb="xs">Analyses (UTC)</Text> <Text size="xs" fw={700} tt="uppercase" c="dimmed" px="sm" pt="lg" pb="xs">{labels ? "Analyses" : "Support"} (UTC)</Text>
{stations.map(st => { {stations.map(st => {
const its = list.filter(a => a.station === st), busy = its.some(a => a.state === "running"); const its = list.filter(a => a.station === st), busy = its.some(a => a.state === "running");
const validated = its.filter(a => a.validated).length; const validated = its.filter(a => a.validated).length;
// the chevron of the folder stays Mantine's: a rightSection would take its place, and rotate with it // the chevron of the folder stays Mantine's: a rightSection would take its place, and rotate with it
return ( return (
<NavLink key={st} defaultOpened={busy} childrenOffset={22} leftSection={<IconFolder size={16} />} <NavLink key={st} defaultOpened={busy} childrenOffset={22} leftSection={<IconFolder size={16} />}
label={<Group gap={6} wrap="nowrap">{st}<Tooltip label={`${validated} of ${its.length} validated`}><Text span size="xs" c="dimmed">{validated}/{its.length}</Text></Tooltip>{busy && <Loader size={10} color="orange" />}</Group>}> label={<Group gap={6} wrap="nowrap">{st}{labels && <Tooltip label={`${validated} of ${its.length} validated`}><Text span size="xs" c="dimmed">{validated}/{its.length}</Text></Tooltip>}{busy && <Loader size={10} color="orange" />}</Group>}>
{its.map(a => ( {its.map(a => (
<NavLink key={a.name} py={4} onClick={() => open(a)} leftSection={<Dot state={a.state} />} <NavLink key={a.name} py={4} onClick={() => open(a)} leftSection={<Dot state={a.state} />}
rightSection={a.validated ? <Tooltip label={`labels validated ${a.validated}`}> rightSection={labels && (a.validated ? <Tooltip label={`labels validated ${a.validated}`}>
<IconCircleCheck size={14} color="var(--mantine-color-green-6)" /></Tooltip> <IconCircleCheck size={14} color="var(--mantine-color-green-6)" /></Tooltip>
: a.state === "done" && <Tooltip label="labels to validate"><IconCircleDashed size={14} color="var(--mantine-color-dimmed)" /></Tooltip>} : a.state === "done" && <Tooltip label="labels to validate"><IconCircleDashed size={14} color="var(--mantine-color-dimmed)" /></Tooltip>)}
label={<Text size="xs" ff="monospace" style={{ whiteSpace: "nowrap" }}>{days(a)}</Text>} label={<Text size="xs" ff="monospace" style={{ whiteSpace: "nowrap" }}>{days(a)}</Text>}
description={<Text span size="xs" ff="monospace" c="dimmed" style={{ whiteSpace: "nowrap" }}>{hours(a)}</Text>} /> description={<Text span size="xs" ff="monospace" c="dimmed" style={{ whiteSpace: "nowrap" }}>{hours(a)}</Text>} />
))} ))}
@@ -104,6 +105,7 @@ function Sidebar({ page, selection, close, open }) {
href={address(n, selection)} /> href={address(n, selection)} />
))} ))}
<Analyses open={a => { close(); open(a); }} /> <Analyses open={a => { close(); open(a); }} />
<Analyses kind="support" open={a => { close(); open(a, "support"); }} />
</ScrollArea> </ScrollArea>
</AppShell.Navbar> </AppShell.Navbar>
); );
@@ -114,6 +116,7 @@ export default function App() {
const [mobile, { toggle: toggleMobile, close: closeMobile }] = useDisclosure(false); const [mobile, { toggle: toggleMobile, close: closeMobile }] = useDisclosure(false);
const [desktop, { toggle: toggleDesktop }] = useDisclosure(true); const [desktop, { toggle: toggleDesktop }] = useDisclosure(true);
const [analysis, setAnalysis] = useState(null); // the analysis whose report Data shows const [analysis, setAnalysis] = useState(null); // the analysis whose report Data shows
const [support, setSupport] = useState(null); // the support request whose answer Data shows
useEffect(() => { useEffect(() => {
const follow = () => setPlace(readAddress()); const follow = () => setPlace(readAddress());
@@ -123,11 +126,12 @@ export default function App() {
// the same address again (Load): read again, a new selection loads the data again // the same address again (Load): read again, a new selection loads the data again
const choose = s => { const a = address(page, s); if (location.hash === a) setPlace(readAddress()); else location.hash = a; }; const choose = s => { const a = address(page, s); if (location.hash === a) setPlace(readAddress()); else location.hash = a; };
// An analysis of the sidebar: Data on its station, days that cover its range (unless the range shown already covers them) // An analysis (or a support request) of the sidebar: Data on its station, days that cover its range (unless the range
function openAnalysis(a) { // shown already covers them)
function openAnalysis(a, kind) {
const s = selection, covers = s.station === a.station && s.start <= a.start.slice(0, 10) && a.end < s.end; const s = selection, covers = s.station === a.station && s.start <= a.start.slice(0, 10) && a.end < s.end;
const end = new Date(Date.parse(a.end.slice(0, 10)) + 864e5).toISOString().slice(0, 10); const end = new Date(Date.parse(a.end.slice(0, 10)) + 864e5).toISOString().slice(0, 10);
setAnalysis(a.name); (kind === "support" ? setSupport : setAnalysis)(a.name);
location.hash = address("data", covers ? s : { station: a.station, start: a.start.slice(0, 10), end }); location.hash = address("data", covers ? s : { station: a.station, start: a.start.slice(0, 10), end });
} }
return ( return (
@@ -138,7 +142,8 @@ export default function App() {
<AppShell.Main bg="var(--mantine-color-default-hover)"> <AppShell.Main bg="var(--mantine-color-default-hover)">
<Suspense fallback={<Loader m="xl" />}> <Suspense fallback={<Loader m="xl" />}>
{page === "stations" ? <Stations selection={selection} /> {page === "stations" ? <Stations selection={selection} />
: <Data selection={selection} choose={choose} analysis={analysis} setAnalysis={setAnalysis} />} : <Data selection={selection} choose={choose} analysis={analysis} setAnalysis={setAnalysis}
support={support} setSupport={setSupport} />}
</Suspense> </Suspense>
</AppShell.Main> </AppShell.Main>
</AppShell> </AppShell>
+42 -29
View File
@@ -10,7 +10,8 @@ import { StationImages } from "./Images.jsx";
// Data, the curve viewer and the labelling: one plot at the start, others to add or remove, // Data, the curve viewer and the labelling: one plot at the start, others to add or remove,
// all aligned in time; under them the labels: Detectors (the events of the journal), LLM (labeling/auto/, read-only) // all aligned in time; under them the labels: Detectors (the events of the journal), LLM (labeling/auto/, read-only)
// or Analysis (the same, to edit, delete; dragging on the bar selects a range, which the analyst diagnoses and // or Analysis (the same, to edit, delete; dragging on the bar selects a range, which the analyst diagnoses and
// labels; elsewhere, dragging zooms); a click opens a // labels), or Support (LLM's labels; dragging selects a range, on which the support answers a question); elsewhere,
// dragging zooms; a click opens a
// label and highlights it. On the right, the images of the station, and under them the diagnostic settings. // label and highlights it. On the right, the images of the station, and under them the diagnostic settings.
const FAMILIES = { "Visibility": "#8ec5e8", "Obstruction": "#f0b072", "Thermal displacement": "#f08a7e", "Displacement": "#b39ddb", const FAMILIES = { "Visibility": "#8ec5e8", "Obstruction": "#f0b072", "Thermal displacement": "#f08a7e", "Displacement": "#b39ddb",
"Target issue": "#e6d46a", "No data": "#c4c4be", "None": "#a8d5a2" }; "Target issue": "#e6d46a", "No data": "#c4c4be", "None": "#a8d5a2" };
@@ -19,8 +20,9 @@ const FAMILY_NAME = f => (f === "None" ? "None (curves intact)" : f);
const FAMILY_CHOICES = [{ value: "", label: "(choose a family)" }, const FAMILY_CHOICES = [{ value: "", label: "(choose a family)" },
...Object.keys(FAMILIES).filter(f => f !== "None").map(f => ({ value: f, label: f }))]; ...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 // 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) // some on a range (app/server/analysis.py); Support reads them, and asks the support a question on a range (support.py)
const SOURCES = [{ value: "detectors", label: "Detectors" }, { value: "auto", label: "LLM" }, { value: "analysis", label: "Analysis" }]; const SOURCES = [{ value: "detectors", label: "Detectors" }, { value: "auto", label: "LLM" }, { value: "analysis", label: "Analysis" },
{ value: "support", label: "Support" }];
const GREY = "#b0b0aa", BLUE = "#2a78d6", LANE = 26, HEIGHT = 330; // LANE: px per row of labels; HEIGHT: of a plot const GREY = "#b0b0aa", BLUE = "#2a78d6", LANE = 26, HEIGHT = 330; // LANE: px per row of labels; HEIGHT: of a plot
const color = l => FAMILIES[l.family] || GREY; const color = l => FAMILIES[l.family] || GREY;
const readable = s => s.slice(0, 16).replace("T", " "); const readable = s => s.slice(0, 16).replace("T", " ");
@@ -40,7 +42,7 @@ const wrap = s => s.replace(/(.{1,80})(\s|$)/g, "$1<br>"); // the tooltip: line
const DETECTED = Object.keys(FAMILIES).filter(f => f !== "None"); // the families of the detectors (categories.py) const DETECTED = Object.keys(FAMILIES).filter(f => f !== "None"); // the families of the detectors (categories.py)
export default function Data({ selection, choose, analysis, setAnalysis }) { export default function Data({ selection, choose, analysis, setAnalysis, support, setSupport }) {
const [data, setData] = useState(null), [loading, setLoading] = useState(false), [wide, setWide] = useState(false); const [data, setData] = useState(null), [loading, setLoading] = useState(false), [wide, setWide] = useState(false);
const left = useRef(), [moment, setMoment] = useState(null); // moment: where to set the images (the start of the clicked event) const left = useRef(), [moment, setMoment] = useState(null); // moment: where to set the images (the start of the clicked event)
// The diagnostic settings, under the image (Detectors and LLM): families shown (filter of the page); targets kept ("": // The diagnostic settings, under the image (Detectors and LLM): families shown (filter of the page); targets kept ("":
@@ -73,7 +75,7 @@ export default function Data({ selection, choose, analysis, setAnalysis }) {
{data && <TargetFilter d={data} hidden={hidden} setHidden={setHidden} />} {data && <TargetFilter d={data} hidden={hidden} setHidden={setHidden} />}
{data && <Curves key={`${station}${start}${end}`} selection={selection} d={data} setImage={(t, nearest) => setMoment({ t, nearest })} {data && <Curves key={`${station}${start}${end}`} selection={selection} d={data} setImage={(t, nearest) => setMoment({ t, nearest })}
source={source} setSource={setSource} families={families} targets={targets} focus={focus} hidden={hidden} source={source} setSource={setSource} families={families} targets={targets} focus={focus} hidden={hidden}
analysis={analysis} setAnalysis={setAnalysis} />} analysis={analysis} setAnalysis={setAnalysis} support={support} setSupport={setSupport} />}
</Stack> </Stack>
</Grid.Col> </Grid.Col>
<Grid.Col span={{ base: 12, lg: wide ? 7 : 4 }}> <Grid.Col span={{ base: 12, lg: wide ? 7 : 4 }}>
@@ -157,8 +159,9 @@ const Field = ({ name, children }) => (
const mentions = (text, s) => new RegExp(`(^|[^\\w])${s.replace(/[^\w]/g, "\\$&")}(?![\\w])`).test(text); const mentions = (text, s) => new RegExp(`(^|[^\\w])${s.replace(/[^\w]/g, "\\$&")}(?![\\w])`).test(text);
const sensorsOf = (l, names) => l.sensors ?? names.filter(s => mentions(l.description, s)); const sensorsOf = (l, names) => l.sensors ?? names.filter(s => mentions(l.description, s));
// analysis: the folder of the analysis shown, held by App (the sidebar opens one) // analysis, support: the folder of the analysis, of the support request shown, held by App (the sidebar opens one)
function Curves({ selection: { station, start, end }, d, setImage, source, setSource, families, targets, focus, hidden, analysis, setAnalysis }) { function Curves({ selection: { station, start, end }, d, setImage, source, setSource, families, targets, focus, hidden, analysis, setAnalysis,
support, setSupport }) {
const { A, B, T, plots: PLOTS } = d; const { A, B, T, plots: PLOTS } = d;
const plotIndex = (title, otherwise) => { const i = PLOTS.findIndex(p => p.title === title); return i < 0 ? otherwise : i; }; const plotIndex = (title, otherwise) => { const i = PLOTS.findIndex(p => p.title === title); return i < 0 ? otherwise : i; };
const [Plotly, setPlotly] = useState(null), [ready, setReady] = useState(false); const [Plotly, setPlotly] = useState(null), [ready, setReady] = useState(false);
@@ -171,7 +174,8 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
const labels = useMemo(() => allLabels.filter(x => x.start < B && x.end > A const labels = useMemo(() => allLabels.filter(x => x.start < B && x.end > A
&& (!DETECTED.includes(x.family) || families.includes(x.family))), [allLabels, families]); && (!DETECTED.includes(x.family) || families.includes(x.family))), [allLabels, families]);
const detect = source === "detectors", readOnly = source !== "analysis"; // only Analysis writes const detect = source === "detectors", readOnly = source !== "analysis"; // only Analysis writes
const folder = source === "analysis" ? "auto" : source; // the labeling/ folder of the labels const asking = source === "support", select = asking || !readOnly; // select: dragging on the bar selects a range
const folder = "auto"; // the labeling/ folder of the labels
// figs: id -> div of the plot; drawn: id -> plot it shows; viewKey: the range and the width where the text of the labels was truncated // figs: id -> div of the plot; drawn: id -> plot it shows; viewKey: the range and the width where the text of the labels was truncated
const figs = useRef({}), drawn = useRef({}), nextId = useRef(2), bar = useRef(), sorted = useRef([]), viewKey = useRef(""), current = useRef({}); const figs = useRef({}), drawn = useRef({}), nextId = useRef(2), bar = useRef(), sorted = useRef([]), viewKey = useRef(""), current = useRef({});
// the focus: the sensors of the open event (none: all, as for No data); shown, their key // the focus: the sensors of the open event (none: all, as for No data); shown, their key
@@ -290,7 +294,7 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
? l.references.map(s => s + " (ref.)").join(", ") : "All sensors") ? l.references.map(s => s + " (ref.)").join(", ") : "All sensors")
: (l.family ? `<b>${FAMILY_NAME(l.family)}</b><br>` : "") + wrap(l.description))), : (l.family ? `<b>${FAMILY_NAME(l.family)}</b><br>` : "") + wrap(l.description))),
hovertemplate: "%{customdata}<extra></extra>" }], hovertemplate: "%{customdata}<extra></extra>" }],
{ ...skin(c), height: 40 + LANE * n, dragmode: readOnly ? "zoom" : "select", selectdirection: "h", hovermode: "closest", plot_bgcolor: c.bg, showlegend: false, { ...skin(c), height: 40 + LANE * n, dragmode: select ? "select" : "zoom", selectdirection: "h", hovermode: "closest", plot_bgcolor: c.bg, showlegend: false,
margin: { ...margin(), l: Math.max(...gs.map(g => g._fullLayout._size.l)), r: Math.max(...gs.map(g => g._fullLayout._size.r)) }, margin: { ...margin(), l: Math.max(...gs.map(g => g._fullLayout._size.l)), r: Math.max(...gs.map(g => g._fullLayout._size.r)) },
xaxis: { type: "date", range: f.xaxis.range.slice(), showgrid: false, ticks: "", color: c.text }, xaxis: { type: "date", range: f.xaxis.range.slice(), showgrid: false, ticks: "", color: c.text },
yaxis: { range: [n - 0.5, -0.5], fixedrange: true, showticklabels: false, showgrid: false, zeroline: false }, yaxis: { range: [n - 0.5, -0.5], fixedrange: true, showticklabels: false, showgrid: false, zeroline: false },
@@ -323,8 +327,8 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
useEffect(() => { if (ready) drawPlots().then(() => align(bar.current)); }, [views]); useEffect(() => { if (ready) drawPlots().then(() => align(bar.current)); }, [views]);
useEffect(() => { if (ready) drawBar(); }, [ready, labels]); useEffect(() => { if (ready) drawBar(); }, [ready, labels]);
// Drag on the bar: select a range (Analysis), otherwise zoom in time // Drag on the bar: select a range (Analysis, Support), otherwise zoom in time
useEffect(() => { if (ready) Plotly.relayout(bar.current, { dragmode: readOnly ? "zoom" : "select", selections: [] }); }, [ready, readOnly]); useEffect(() => { if (ready) Plotly.relayout(bar.current, { dragmode: select ? "select" : "zoom", selections: [] }); }, [ready, select]);
useEffect(() => { if (ready) drawPlots(true).then(drawBar); }, [dark]); useEffect(() => { if (ready) drawPlots(true).then(drawBar); }, [dark]);
useEffect(() => { if (ready) drawPlots(true); }, [shown, hidden]); useEffect(() => { if (ready) drawPlots(true); }, [shown, hidden]);
useEffect(() => { if (ready) plotDivs().forEach(g => Plotly.relayout(g, { shapes: zones() })); }, [ready, labels, choice, opened]); useEffect(() => { if (ready) plotDivs().forEach(g => Plotly.relayout(g, { shapes: zones() })); }, [ready, labels, choice, opened]);
@@ -373,10 +377,12 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
return true; return true;
} }
// The analyst on the range (Analysis, hints optional), or the support (Support, a question)
async function runAnalysis() { async function runAnalysis() {
const r = await call("/api/analyses", "POST", { station, start: choice[0], end: choice[1], hints }); const r = await call(asking ? "/api/support" : "/api/analyses", "POST",
{ station, start: choice[0], end: choice[1], ...(asking ? { question: hints } : { hints }) });
if (!r) return; // nothing is lost: the hints and the range stay in the page if (!r) return; // nothing is lost: the hints and the range stay in the page
setAnalysis(r.name); setHints(""); (asking ? setSupport : setAnalysis)(r.name); setHints("");
await Plotly.relayout(bar.current, { selections: [] }); await Plotly.relayout(bar.current, { selections: [] });
setChoice(null); setChoice(null);
} }
@@ -478,13 +484,18 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
</Card> </Card>
)} )}
</div> </div>
{!readOnly && <> {select && <>
<Text size="sm">{choice ? `${readable(choice[0])} → ${readable(choice[1])} UTC` : "Drag on the label bar to select the range to analyze."}</Text> <Text size="sm">{choice ? `${readable(choice[0])} → ${readable(choice[1])} UTC`
<Textarea autosize minRows={2} placeholder="Hints for the analyst (optional): what you saw, what to look at" : `Drag on the label bar to select the range ${asking ? "of your question" : "to analyze"}.`}</Text>
value={hints} onChange={e => setHints(e.currentTarget.value)} /> <Textarea autosize minRows={2} value={hints} onChange={e => setHints(e.currentTarget.value)}
<Group><Button onClick={runAnalysis} disabled={!(choice && choice[0] < choice[1])}>Analyze the range</Button></Group> placeholder={asking ? "Your question to the support: what you want to know about this range, or what to answer a client"
: "Hints for the analyst (optional): what you saw, what to look at"} />
<Group><Button onClick={runAnalysis} disabled={!(choice && choice[0] < choice[1]) || (asking && !hints.trim())}>
{asking ? "Ask the support" : "Analyze the range"}</Button></Group>
</>} </>}
{analysis && <Analysis key={analysis} name={analysis} dark={dark} done={() => setRev(r => r + 1)} close={() => setAnalysis(null)} />} {analysis && <Analysis key={analysis} name={analysis} dark={dark} done={() => setRev(r => r + 1)} close={() => setAnalysis(null)} />}
{support && <Analysis kind="support" key={`support/${support}`} name={support} dark={dark} done={() => setRev(r => r + 1)}
close={() => setSupport(null)} />}
</Stack> </Stack>
</Card> </Card>
); );
@@ -516,14 +527,15 @@ const STATE_COLOR = { running: "blue", done: "teal", error: "red", interrupted:
// An analysis of the Analysis tab: its thread (read again every 3 s while it works), its report, and a message to the // An analysis of the Analysis tab: its thread (read again every 3 s while it works), its report, and a message to the
// analyst, which resumes its session; at the end of each turn, the labels are read again. A finished analysis can be // analyst, which resumes its session; at the end of each turn, the labels are read again. A finished analysis can be
// optimized (/improve of Optimizer on the range of the analysis, then the tool-builder): the thread of the session, then // optimized (/improve of Optimizer on the range of the analysis, then the tool-builder): the thread of the session, then
// its summaries under the report // its summaries under the report. kind "support": a request of the Support tab, the same without labels: its question,
function Analysis({ name, dark, done, close }) { // its thread, its answer, the messages
function Analysis({ kind = "analyses", name, dark, done, close }) {
const [a, setA] = useState(null), [turn, setTurn] = useState(0), [text, setText] = useState(""); const [a, setA] = useState(null), [turn, setTurn] = useState(0), [text, setText] = useState("");
const box = useRef(), loaded = !!a; const box = useRef(), loaded = !!a;
useEffect(() => { if (loaded) box.current?.scrollIntoView({ behavior: "smooth", block: "start" }); }, [name, loaded]); // opened: it is in view useEffect(() => { if (loaded) box.current?.scrollIntoView({ behavior: "smooth", block: "start" }); }, [name, loaded]); // opened: it is in view
useEffect(() => { useEffect(() => {
let alive = true, timer; let alive = true, timer;
const read = () => call(`/api/analyses/${name}`).then(r => { const read = () => call(`/api/${kind}/${name}`).then(r => {
if (!alive || !r) return; if (!alive || !r) return;
setA(r); setA(r);
if (r.state === "running" || r.optimization?.state === "running") timer = setTimeout(read, 3000); if (r.state === "running" || r.optimization?.state === "running") timer = setTimeout(read, 3000);
@@ -533,7 +545,7 @@ function Analysis({ name, dark, done, close }) {
return () => { alive = false; clearTimeout(timer); }; return () => { alive = false; clearTimeout(timer); };
}, [name, turn]); }, [name, turn]);
async function send() { async function send() {
if (await call(`/api/analyses/${name}/message`, "POST", { text }) == null) return; // the text stays in the field if (await call(`/api/${kind}/${name}/message`, "POST", { text }) == null) return; // the text stays in the field
setText(""); setTurn(t => t + 1); setText(""); setTurn(t => t + 1);
} }
async function optimize() { async function optimize() {
@@ -543,35 +555,36 @@ function Analysis({ name, dark, done, close }) {
if (await call(`/api/analyses/${name}/validate`, "POST") != null) { setTurn(t => t + 1); done(); } if (await call(`/api/analyses/${name}/validate`, "POST") != null) { setTurn(t => t + 1); done(); }
} }
if (!a) return <Loader size="sm" />; if (!a) return <Loader size="sm" />;
const d = a.request, o = a.optimization, busy = a.state === "running", optimizing = o?.state === "running"; const d = a.request, o = a.optimization, busy = a.state === "running", optimizing = o?.state === "running", labels = kind === "analyses";
const end = new Date(Date.parse(d.end.slice(0, 10)) + 864e5).toISOString().slice(0, 10); const end = new Date(Date.parse(d.end.slice(0, 10)) + 864e5).toISOString().slice(0, 10);
return ( return (
<Card withBorder ref={box}> <Card withBorder ref={box}>
<Stack gap="xs"> <Stack gap="xs">
<Group justify="space-between"> <Group justify="space-between">
<Group gap="xs"> <Group gap="xs">
<Title order={5}>Analysis {readable(d.start)} → {readable(d.end)} UTC</Title> <Title order={5}>{labels ? "Analysis" : "Support"} {readable(d.start)} → {readable(d.end)} UTC</Title>
<Badge color={STATE_COLOR[a.state] || "gray"}>{a.state}</Badge> <Badge color={STATE_COLOR[a.state] || "gray"}>{a.state}</Badge>
{busy && <Loader size="xs" />} {busy && <Loader size="xs" />}
</Group> </Group>
<Group gap="xs"> <Group gap="xs">
{a.validated ? <Badge color="green" variant="light">labels validated {a.validated}</Badge> {!labels ? null : a.validated ? <Badge color="green" variant="light">labels validated {a.validated}</Badge>
: a.state === "done" && <Tooltip label="I agree with all the labels of this analysis: they become reference labels"> : a.state === "done" && <Tooltip label="I agree with all the labels of this analysis: they become reference labels">
<Button size="xs" color="green" variant="light" onClick={validate} disabled={optimizing}>Validate labels</Button></Tooltip>} <Button size="xs" color="green" variant="light" onClick={validate} disabled={optimizing}>Validate labels</Button></Tooltip>}
{a.state === "done" && <Tooltip label="Improve the detectors (Optimizer), then the reading tools (tool-builder), from this analysis"> {labels && a.state === "done" && <Tooltip label="Improve the detectors (Optimizer), then the reading tools (tool-builder), from this analysis">
<Button size="xs" variant="light" onClick={optimize} disabled={optimizing}>Optimize the detectors</Button></Tooltip>} <Button size="xs" variant="light" onClick={optimize} disabled={optimizing}>Optimize the detectors</Button></Tooltip>}
<ActionIcon variant="subtle" color="gray" aria-label="Close the report" onClick={close}><IconX size={16} /></ActionIcon> <ActionIcon variant="subtle" color="gray" aria-label="Close the report" onClick={close}><IconX size={16} /></ActionIcon>
</Group> </Group>
</Group> </Group>
{d.hints && <Text size="sm" c="dimmed">Hints: {d.hints}</Text>} {d.hints && <Text size="sm" c="dimmed">Hints: {d.hints}</Text>}
{d.question && <Text size="sm" c="dimmed" style={{ whiteSpace: "pre-wrap" }}>Question: {d.question}</Text>}
{a.state === "interrupted" && <Text size="sm" c="orange">Stopped with the server before the end.{a.dialogue {a.state === "interrupted" && <Text size="sm" c="orange">Stopped with the server before the end.{a.dialogue
? " Its session is kept: write “continue” below to resume it where it left off." : ""}</Text>} ? " Its session is kept: write “continue” below to resume it where it left off." : ""}</Text>}
{a.submitted !== null && a.state === "done" && <Text size="sm">{a.submitted} label(s) of this analysis in labeling/auto/{d.station}.jsonl{a.validated ? ", validated" : ", to validate"}.</Text>} {a.submitted !== null && a.state === "done" && <Text size="sm">{a.submitted} label(s) of this analysis in labeling/auto/{d.station}.jsonl{a.validated ? ", validated" : ", to validate"}.</Text>}
{a.report && <Page title="Report" src={`/api/analyses/${name}/report.html?dark=${dark}&v=${a.report}`} />} {a.report && <Page title="Report" src={`/api/${kind}/${name}/report.html?dark=${dark}&v=${a.report}`} />}
<Thread lines={a.lines} /> <Thread lines={a.lines} />
{a.dialogue && ( {a.dialogue && (
<Group align="flex-end" gap="sm" wrap="nowrap"> <Group align="flex-end" gap="sm" wrap="nowrap">
<Textarea autosize minRows={1} style={{ flex: 1 }} placeholder="A question, a correction for the analyst" <Textarea autosize minRows={1} style={{ flex: 1 }} placeholder={`A question, a correction for the ${labels ? "analyst" : "support"}`}
value={text} onChange={e => setText(e.currentTarget.value)} /> value={text} onChange={e => setText(e.currentTarget.value)} />
<Button onClick={send} disabled={busy || optimizing || !text.trim()}>Send</Button> <Button onClick={send} disabled={busy || optimizing || !text.trim()}>Send</Button>
</Group> </Group>
@@ -589,7 +602,7 @@ function Analysis({ name, dark, done, close }) {
{o.summary && <Text size="xs" c="dimmed" ff="monospace">python3 detectors/bench/score.py data/{d.station} --labels labeling/auto/{d.station}.jsonl --from {d.start.slice(0, 10)} --to {end}</Text>} {o.summary && <Text size="xs" c="dimmed" ff="monospace">python3 detectors/bench/score.py data/{d.station} --labels labeling/auto/{d.station}.jsonl --from {d.start.slice(0, 10)} --to {end}</Text>}
</Stack> </Stack>
)} )}
<Text size="xs" c="dimmed">labeling/auto/analyses/{name}/</Text> <Text size="xs" c="dimmed">labeling/auto/{kind}/{name}/</Text>
</Stack> </Stack>
</Card> </Card>
); );
+6 -4
View File
@@ -15,11 +15,13 @@ The user selected a range in the Data page and clicked "Analyze the range": they
## The weather ## The weather
The weather really measured near the station is not in `data/<STATION>/`: fetch it at the start, for every analysis, and read it with the other causes (rain, fog, wind, sun, frost, cold air). The place of the station is its line in `~/aimsight-data/extraction/stations.txt` (`<STATION> <place>`; no line, no weather: say so in your analysis). Then, from `~/aimsight-data`: The weather really measured near the station is in `data/<STATION>/weather/`, one CSV per day (`tools/DATA.md`, "The weather"): read it at the start, for every analysis, with the other causes (rain, fog, wind, sun, frost, cold air). Hourly, UTC; the MeteoSwiss station and its distance are in the columns `station_name`, `distance_km`: give them in your analysis. No folder, or no day of your range: no weather (station without a Swiss position): say so in your analysis. It is the weather a few km away, not at the camera: what the images show prevails.
`python3 weather/meteoswiss.py "<place>" <start> <end> --out <output folder>/work/weather.csv` ## The targets in mm, their distance
hourly, UTC, `end` excluded; the MeteoSwiss station chosen and its distance are written on stderr: give them in your analysis. It is the weather a few km away, not at the camera: what the images show prevails. `inventory.py` gives each target's distance from the camera, and `corr_x_mm`, `corr_y_mm` are `corr_x`, `corr_y` in mm (`tools/DATA.md`, "The targets"). The same curves: what is labelled is what stands out from the noise, in px or in mm, and a target's deviation in its own noises is the same in both units, so the threshold does not change. One event seen in px and in mm is one label.
The scale changes with the distance: a far target moves few px for many mm, a near one the reverse. So never compare targets with each other in px alone ("it moves more than the others", "they all move alike"): in mm, or in px with their distance. The distance also tells the camera from the structure: a camera that turns shifts every target by about the same px, so the mm grow with the distance; a movement of the structure of the same mm gives px that shrink with the distance; a parallax shows between targets at different distances. Use the mm if they help, px and distance otherwise; give the magnitudes in mm in the report. A target without a sure factor has no mm (`?` in `inventory.py`): say it in px.
## Three readers, three texts ## Three readers, three texts
@@ -42,7 +44,7 @@ hourly, UTC, `end` excluded; the MeteoSwiss station chosen and its distance are
## What happened ## What happened
<one short paragraph per phenomenon, not per label: when (UTC), which targets, how far the curves are wrong, the cause and how sure you are (confirmed / likely / possible / unknown)> <one short paragraph per phenomenon, not per label: when (UTC), which targets, how far the curves are wrong (in mm where the targets have them), the cause and how sure you are (confirmed / likely / possible / unknown)>
<one figure or GIF per phenomenon at most, the one that proves it, followed by one line saying what to look at> <one figure or GIF per phenomenon at most, the one that proves it, followed by one line saying what to look at>
+63
View File
@@ -0,0 +1,63 @@
# aimsight-app's instructions to the support
What the app asks of the support (agents repository, `agents:support`), on top of its trade. Launched by the Support tab of the Data page (`app/server/support.py`).
## Why this request
The user, the expert at the control station, selected a range of a station in the Data page and asked you a question about it (`Question` in the request). It can be about anything: what happened on the curves, whether a client can be told something, why the detectors fired or stayed silent, a fact about the station or the product, a draft reply to a client. The range is where they were looking: the context of the question, not its limit.
## How you go about it: your judgment
- **Yourself**, when it is simple: a fact to look up, what the labels and the analyses already say of the range (`labeling/auto/<STATION>.jsonl`, `labeling/auto/analyses/<STATION>_*/`, the earlier support folders), a short reading of the data, one figure. A label with `review` was validated by the expert: take it as established.
- **Through the analyst**, when the answer needs a reading of the range like the expert's: on the range given, or a wider one (the night before, the whole week to see whether it repeats) or a narrower one. You choose, and say which and why in your answer. One analyst per question: a follow-up resumes its session.
- Only what the answer needs: a question that the existing labels already answer needs no analyst.
## In this process
- You run under `claude -p`, launched by the server: nobody can answer you during your turn. A question that cannot be answered without a precision: ask it in your last message and stop; the user answers in the page, and the same session resumes.
- Launch the analyst **in the foreground**, not with `run_in_background`: under `claude -p`, a run left in the background can be cut when your turn ends. The server lets a command last up to 3 hours: no timeout to give.
- Your folder is the `Output folder` of the request: `labeling/auto/support/<STATION>_<start>_<end>/` (the same as `~/aimsight-labeling/auto/support/`). The server writes `request.json` there, and `log.jsonl` and `session` in `work/`: leave them. The rest as your trade says.
- Your analyst's labels stay in `analyst/`, submitted nowhere: made with the detectors' events as hints, they are not the truth the detectors are improved on. When they should become reference labels, say so in your answer: the user runs an Analysis of the range (the Analysis tab).
## The answer
`answer.md` is shown in the page, under the question: read by the expert, in two minutes. In English; a text meant for a client is in the client's language, in its own section, written as your trade says (an answer to a client).
```markdown
# <STATION>: <the subject in a few words>
<their question, in one sentence>
## In short
<three lines at most: the answer (yes, no, or it cannot be said) and why>
## How it was established
<the facts that found it, one short paragraph each: when (UTC), which targets, what the curves and the images show, how sure (confirmed / likely / possible / unknown); what you read for it (the labels, an analysis and its path, the knowledge base); whether you called the analyst, on which range and why>
<one figure or GIF per fact at most, the one that proves it, followed by one line saying what to look at>
## What to do
<the actions it calls for (on site, the references, the configuration, the labels); left out when there is none>
## Not established
<what stays open and what would settle it; left out when nothing stays open>
## For the client
<the text for the client, ready to copy; only when the question asks for one>
```
- Plain words, short sentences: no commands, no column names (`corr_x`: "the corrected curve in x"), no jargon unless explained in the sentence. The internal names (a detector, an event code, a tool) only when the question is about them, and never in the client's text.
- Figures: `![caption](path relative to your folder)`, in your folder, not in `work/`: the page serves your folder and nothing else (the analyst's figures in `analyst/` included). When the cause is seen on the images over time, a GIF (`tools/scripts/gif.py`, `tools/GUIDE.md`) shows it better than a still image; keep it small.
## The messages
Then the user may write to you (the same session resumes): a precision, a correction, another question on the same range. Rewrite `answer.md` in full: the page shows it again. An indication from them goes in it, in words ("according to the expert: …").
## Your answer
In 2 lines: the path of `answer.md`, and whether you called the analyst (on which range). The page shows `answer.md`: do not repeat it.