Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d75a71522 | ||
|
|
cae07a2787 | ||
|
|
cccdeae67e | ||
|
|
f0470295fa | ||
|
|
54bcce1281 | ||
|
|
7ef808eee3 | ||
|
|
810e349b42 | ||
|
|
4a8b51f490 | ||
|
|
f8b27b13e6 | ||
|
|
2be232b91d | ||
|
|
f21fcebeae | ||
|
|
dcd255ab1f | ||
|
|
1133a91078 | ||
|
|
6b3f46434a | ||
|
|
cce6b850c6 | ||
|
|
d4d2e6b7b1 | ||
|
|
8e1aecc6cf | ||
|
|
51e939fa3c | ||
|
|
0db5775e97 | ||
|
|
0e6e671caa | ||
|
|
f58db178c7 | ||
|
|
adc5ae12bd | ||
|
|
45db86d1ff | ||
|
|
3544f29d85 | ||
|
|
ca2f66ce3d | ||
|
|
602ca02653 | ||
|
|
161fb0212f | ||
|
|
60d10a282c | ||
|
|
071057dff8 | ||
|
|
ce0200a97a | ||
|
|
effcf8fdcb | ||
|
|
2ed4a272b4 | ||
|
|
b31371a241 | ||
|
|
a733575d65 | ||
|
|
7332306b79 | ||
|
|
d34828ab5e | ||
|
|
b2923d8d49 | ||
|
|
07639748ee | ||
|
|
d72dccb14e | ||
|
|
c8c8c1587a | ||
|
|
eaa124f9f5 | ||
|
|
d8184fc18b | ||
|
|
9dcd31687c | ||
|
|
0a862758fb | ||
|
|
8fa555f43b |
No files matched your search
@@ -10,3 +10,5 @@ detectors
|
||||
tools
|
||||
agents
|
||||
optimizer
|
||||
models
|
||||
libredesk
|
||||
Vendored
+7
@@ -8,6 +8,13 @@
|
||||
"command": "{ [ -d .venv ] || { python3 -m venv .venv && .venv/bin/pip install -q -r app/requirements.txt; }; } && (cd app/web && { [ -d node_modules ] || npm install; } && npm run build) && .venv/bin/python app/server/server.py",
|
||||
"isBackground": true,
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "Reload the service",
|
||||
"detail": "After a change of the code: rebuilds the page and relaunches the systemd service aimsight-app on http://127.0.0.1:8770 (README.md, Run as a service)",
|
||||
"type": "shell",
|
||||
"command": "systemctl --user restart aimsight-app && systemctl --user is-active aimsight-app && echo http://127.0.0.1:8770 || { journalctl --user -u aimsight-app -n 30 --no-pager; exit 1; }",
|
||||
"problemMatcher": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
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 links** (ignored by git, one copy of each repository on the workstation): `data/`, `labeling/`, `detectors/`, `tools/`, `agents/`, `optimizer/`; each thing is committed in its own repository, never here. This repository carries no agent, no reading tool, no workflow.
|
||||
- **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 Conversations page launches `libredesk/conversations/pull.sh` (read-only on LibreDesk, its key in `~/aimsight-libredesk/.env`), each conversation in `labeling/auto/conversations/<reference>/` (`transcript.md`, `messages.json`, `attachments/`). The Points page launches nothing: the user sets each measurement of a range valid or not, mainly on the runs of the emulator (`<SERIAL>@<run>`), in `labeling/points/<STATION>_<start>_<end>.csv` (`app/server/validity.py`).
|
||||
- **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), `libredesk/` (the LibreDesk conversations); 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 contracts**: with the detectors, `detectors/CLAUDE.md` (`categories.events`, `bench/score.py`); 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. The Data page passes to the detectors the measurements read by `tools/scripts/data.py`, whereas the benchmark and Optimizer read through `detectors/scripts/data.py`: a reading fix in one is carried over to the other.
|
||||
- **The benchmark**: `python3 detectors/bench/regression.py --labels labeling/auto --data data` (~3 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 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`, `scripts/points.py` for the point labels); with the data, `~/aimsight-data` (`extraction/pumping.py`; the weather is pumped into `data/<STATION>/weather/`; the runs of `data_diff/<SERIAL>/runs/<run>/` are stations `<SERIAL>@<run>` of the Data page, with the labels of `<SERIAL>`, not for the agents); with the agents, `agents/README.md` (the requests of the analyst and of the support); with Optimizer, `optimizer/README.md` (the request of `/optimize`); with LibreDesk, `libredesk/conversations/pulling.py` (`start`, `running`, `log`). 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 models/rules/bench/regression.py --labels labeling/auto --data data` (~1 min); the score of a range: `python3 models/rules/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.
|
||||
- **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`.
|
||||
- **The server**: the systemd user service `aimsight-app` (`~/.config/systemd/user/aimsight-app.service`, `README.md` "Run as a service") serves http://127.0.0.1:8770, started with the workstation; it keeps the code it loaded: a change of the server or of the page is seen only after `systemctl --user restart aimsight-app` (it rebuilds the page itself), which interrupts nothing only when no analysis, optimization or support is running; its log, `journalctl --user -u aimsight-app`. A test server beside it: `AIMSIGHT_PORT=8771 .venv/bin/python app/server/server.py --no-browser`.
|
||||
|
||||
Rules:
|
||||
- Every time is in UTC.
|
||||
@@ -17,4 +18,5 @@ Rules:
|
||||
- Never read `.env` (the credentials of the platform).
|
||||
- The agents run on the Claude subscription, never on an API key.
|
||||
- Commits by path, never `git add -A`: another session may be working in this repository.
|
||||
- After every change of the app (server or page), restart the server, `systemctl --user restart aimsight-app`, and check it answers; if an analysis, an optimization or a support is running, wait for its end and restart then.
|
||||
- Language: the repository (documents, code, UI) in English; conversations with the user in French.
|
||||
@@ -1,19 +1,22 @@
|
||||
# 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;
|
||||
- **"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 **Conversations** page pumps the LibreDesk conversations (the thread, its images and attachments), read-only, through `~/aimsight-libredesk` (`conversations/`), into `labeling/auto/conversations/<reference>/`: for the support, and as training data. Nothing is ever written to LibreDesk.
|
||||
|
||||
The architecture of the repositories, one responsibility each: `docs/architecture.drawio`.
|
||||
|
||||
## The repository
|
||||
|
||||
- `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.
|
||||
|
||||
And six links, ignored by git, to the neighbouring repositories (a single copy of each on the workstation):
|
||||
And eight links, ignored by git, to the neighbouring repositories (a single copy of each on the workstation):
|
||||
|
||||
| Link | Repository | What the app does with it |
|
||||
|---|---|---|
|
||||
@@ -23,6 +26,8 @@ And six links, ignored by git, to the neighbouring repositories (a single copy o
|
||||
| `tools/` | `~/aimsight-tools` | reads the data through `tools/scripts/data.py`; the analyst uses it, the upgrader writes in it (Optimizer) |
|
||||
| `agents/` | `~/aimsight-agents` | the plugin of the agents (`--plugin-dir agents`, `--agent agents:analyst`) |
|
||||
| `optimizer/` | `~/aimsight-optimizer` | launches `/optimize` there; reads the summaries in `optimizer/sessions/` |
|
||||
| `libredesk/` | `~/aimsight-libredesk` | pumps the LibreDesk conversations (`conversations/pulling.py`, its key in its `.env`) into `labeling/auto/conversations/` |
|
||||
| `models/` | `~/aimsight-models` | nothing yet: the pilot of learned detectors (Visibility, Obstruction), measured with the benchmark |
|
||||
|
||||
Each thing is committed in its own repository: the labels in `~/aimsight-labeling`, the detectors in `~/aimsight-detectors` (the optimization session does it, without pushing), the tools in `~/aimsight-tools` (the same session, through the upgrader).
|
||||
|
||||
@@ -31,6 +36,7 @@ Each thing is committed in its own repository: the labels in `~/aimsight-labelin
|
||||
```bash
|
||||
ln -s ~/aimsight-data/data data && ln -s ~/aimsight-labeling labeling && ln -s ~/aimsight-detectors detectors
|
||||
ln -s ~/aimsight-tools tools && ln -s ~/aimsight-agents agents && ln -s ~/aimsight-optimizer optimizer
|
||||
ln -s ~/aimsight-libredesk libredesk
|
||||
```
|
||||
|
||||
The VS Code task **Run app** creates `.venv` and builds the front end if they are missing, then launches the server. By hand:
|
||||
@@ -43,6 +49,16 @@ cd app/web && npm install && npm run build && cd ../..
|
||||
|
||||
The page opens on `http://127.0.0.1:8770`. `claude` (Claude Code, logged in to the subscription) must be on the `PATH` for the Analysis tab.
|
||||
|
||||
### Run as a service
|
||||
|
||||
Without VS Code, the app runs as a systemd user service of WSL (`app/aimsight-app.service`, with `systemd=true` in `/etc/wsl.conf`), started with WSL; the page stays on `http://127.0.0.1:8770`. Once:
|
||||
|
||||
```bash
|
||||
systemctl --user enable --now ~/aimsight-app/app/aimsight-app.service
|
||||
```
|
||||
|
||||
After a change of the code, a restart rebuilds the page and relaunches the server: `systemctl --user restart aimsight-app`. The log: `journalctl --user -u aimsight-app -f`. Stop it before launching the VS Code task **Run app** (same port).
|
||||
|
||||
## Pump the data
|
||||
|
||||
The pumping is in the `~/aimsight-data` repository (`extraction/`, VS Code tasks **pump** and **pump a range**); user guide `~/aimsight-data/extraction/README.md`.
|
||||
@@ -51,4 +67,4 @@ The pumping is in the `~/aimsight-data` repository (`extraction/`, VS Code tasks
|
||||
|
||||
- the app: `.venv/bin/python app/server/check.py`;
|
||||
- the labels: `python3 labeling/scripts/validate.py` (the labels submitted by the app do not have `review` yet, which it requires: as many expected errors);
|
||||
- the detectors (benchmark, ~3 min): `python3 detectors/bench/regression.py --labels labeling/auto --data data`.
|
||||
- the detectors (benchmark, ~1 min): `python3 models/rules/bench/regression.py --labels labeling/auto --data data`.
|
||||
+27
-5
@@ -1,21 +1,28 @@
|
||||
# The AIMsight web app
|
||||
|
||||
The tool of the manual diagnostic: a single page, **Data**.
|
||||
The tool of the manual diagnostic: three pages, **Data**, **Stations** and **Conversations**.
|
||||
|
||||
## The Data page
|
||||
|
||||
- **The plots**: one at the start (displacements, camera, image quality, system metrics), "Add a plot" to see several, aligned in time, the cross to remove one; a click on a curve sets the images to the image nearest to that moment. The zones of the labels are barely visible there (opacity 0.05, 0.07 in dark mode).
|
||||
- **The labels**, under the plots, and their bar, according to the chosen source:
|
||||
- **Detectors** (default): the detectors' events (`detectors/scripts/categories.py`, `events`), read-only. The bar carries only their family, the tooltip their targets; on click: their dates, their sensors (targets and references), the message (the first sentence of the text of the event, `categories.sentence`) and the action (the "For the client" column of `labeling/families.md`, refined per kind, `station.ACTION_KIND`);
|
||||
- **Detectors** (default): the detectors' events (`detectors/detectors/categories.py`, `window`: the range with its 3 days of history), read-only. The bar carries only their family, the tooltip their targets; on click: their dates, their sensors (targets and references), the message and the action (`labeling/scripts/client.py`: the first sentence of the text of the event; the "For the client" columns of `labeling/families.md`, per family, refined per variety);
|
||||
- **LLM**: `labeling/auto/<STATION>.jsonl`, read-only;
|
||||
- **Analysis**: the same labels, to edit or delete; writes in `labeling/auto/<STATION>.jsonl`.
|
||||
- **Analysis**: the same labels, to edit or delete; writes in `labeling/auto/<STATION>.jsonl`, each label checked by the rules of labeling (`labeling/scripts/validate.py`, `check`: one of the seven 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 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, 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 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 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
|
||||
|
||||
- **Analyze the range**: a range selected, optional hints, then `server/analysis.py` launches the analyst of the agents repository by `claude -p` (non-interactive), with its instructions (`instructions/analyst.md`) and without the detectors (`DETECTORS: no`). It writes in `labeling/auto/analyses/<STATION>_<start>_<end>/` its labels and a diagnostic report (`report.md` and its figures; its work and claude's log in `work/`, outside git). The page follows its progress, then shows the report; the server submits its labels to `labeling/auto/<STATION>.jsonl` (field `analysis`). "View the report" on such a label opens it again.
|
||||
@@ -23,6 +30,11 @@ The address keeps the station and the range (UTC, `end` excluded): `#/data?stati
|
||||
- **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.
|
||||
|
||||
## 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
|
||||
|
||||
The VS Code task **Run app** (`.vscode/tasks.json`), or by hand (Node 22 for the front end):
|
||||
@@ -34,11 +46,21 @@ cd app/web && npm install && npm run build # once, and after each change of
|
||||
|
||||
The page opens on `http://127.0.0.1:8770`. Settings by variables: `AIMSIGHT_DATA` (data, default `data/`), `AIMSIGHT_LABELS` (labels, default `labeling/`), `AIMSIGHT_PORT` (8770). To work on the page: `npm run dev` in `app/web/` (http://localhost:5173), the Python server launched next to it.
|
||||
|
||||
## The Conversations page
|
||||
|
||||
The LibreDesk conversations (`helpdesk.sensima.ch`), every inbox and status, private notes included, pumped **read-only** by `~/aimsight-libredesk` (link `libredesk/`, `conversations/pull.sh` through `conversations/pulling.py`; the app only calls it, the read key stays in that repository's `.env`) into `labeling/auto/conversations/<reference>/`: `conversation.json`, `messages.json`, `attachments/`, and `transcript.md`, the readable thread.
|
||||
|
||||
- **Pump**: without dates, what changed since the last complete pumping (`pumped.json`; the first time, the whole history, at a quiet hour); with dates, the conversations updated in that range (To excluded). One at a time; the end of `out/conversations.log` of that repository read every 2 s. The commit of `auto/conversations/` in `~/aimsight-labeling` is the user's.
|
||||
- **The list**: the pumped conversations, the most recent message first, searched on subject, contact and reference; a click shows the transcript.
|
||||
- **What a client wrote is never run**: the transcript is escaped before Markdown, served with `Content-Security-Policy: default-src 'none'; img-src 'self'` (no script, no remote image or tracking pixel) in a sandboxed frame; a plain image (png, jpg, gif, webp) shows inline, any other attachment (an `.svg`, an `.html`) is downloaded.
|
||||
|
||||
## 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); the Conversations routes under `/api/conversations`.
|
||||
- `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/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/conversations.py`: the Conversations page; calls `libredesk/conversations/pulling.py`, lists `labeling/auto/conversations/`, renders a transcript safely.
|
||||
- `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.
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# The app as a systemd user service (WSL), without VS Code: README.md, "Run as a service".
|
||||
[Unit]
|
||||
Description=AIMsight diagnostic app (http://127.0.0.1:8770)
|
||||
|
||||
[Service]
|
||||
WorkingDirectory=%h/aimsight-app
|
||||
# claude (Claude Code, subscription) is in ~/.local/bin, which a service does not get from the shell
|
||||
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
# a restart rebuilds the page, so a change of the code needs only: systemctl --user restart aimsight-app
|
||||
# SUPABASE_CONVERSATIONS_URL / _KEY for the Suggestions page (aimsight-app/.env, outside git; optional)
|
||||
EnvironmentFile=-%h/aimsight-app/.env
|
||||
ExecStartPre=/bin/sh -c 'cd app/web && npm run build'
|
||||
ExecStart=%h/aimsight-app/.venv/bin/python app/server/server.py --no-browser
|
||||
Restart=on-failure
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
+74
-34
@@ -4,7 +4,9 @@ by `claude -p`, non-interactive, on a range chosen in the page, with the user's
|
||||
labeling/auto/analyses/<STATION>_<start>_<end>/ its labels (labels.jsonl) and a diagnostic report (report.md, its figures
|
||||
next to it); at the end, the server submits its labels to labeling/auto/<STATION>.jsonl, marked with their analysis (field
|
||||
`analysis`). Then the user can write to it: the same session resumes (`claude -p --resume`), and its labels, if they
|
||||
change, replace those it had submitted.
|
||||
change, replace those it had submitted. "Validate labels": the user agrees with all the labels of the analysis, each gets
|
||||
`review`, the date (labeling/README.md), in labels.jsonl, then submitted; the analysis is validated when all the labels of
|
||||
its labels.jsonl have it. A label changed afterwards, by the analyst or in the page, loses it.
|
||||
On a finished analysis, "Optimize" launches `/optimize` in Optimizer (optimizer/, the skill that, from the analysis, improves
|
||||
the detectors on its range, its labels as truth, then brings the analyst's scripts into the reading tools, tools/); one
|
||||
optimization at a time, no analysis or message meanwhile; the summary of the session
|
||||
@@ -55,8 +57,8 @@ def _optimizing():
|
||||
|
||||
def launch(body):
|
||||
st, start, end = body.get("station"), body.get("start"), body.get("end")
|
||||
station._validate({"description": "-"}, start, end)
|
||||
station.folder(st)
|
||||
station.checked_range(start, end)
|
||||
station.pumped(st)
|
||||
if not (AGENTS / ".claude-plugin" / "plugin.json").exists():
|
||||
raise station.Refusal("no agents in agents/ (the link: README.md)")
|
||||
name = f"{st}_{start[:16].replace(':', '')}_{end[:16].replace(':', '')}"
|
||||
@@ -79,23 +81,30 @@ def launch(body):
|
||||
return {"name": name}
|
||||
|
||||
|
||||
def run(a, out, prompt, resume, agent, tools, env=None):
|
||||
"""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
|
||||
session in work/session (resume: its id)."""
|
||||
p = subprocess.Popen(["claude", "-p", prompt, "--plugin-dir", str(AGENTS), "--agent", f"agents:{agent}", *ISOLATED,
|
||||
"--output-format", "stream-json", "--verbose",
|
||||
"--allowedTools", tools, "--permission-mode", "acceptEdits", *station.links()]
|
||||
+ (["--resume", resume] if resume else []),
|
||||
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:
|
||||
for line in p.stdout:
|
||||
log.write(line)
|
||||
a["lines"] += digest(line)
|
||||
if '"subtype":"init"' in line: # the session, for the next messages
|
||||
(out / "work" / "session").write_text(json.loads(line)["session_id"])
|
||||
if p.wait():
|
||||
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:
|
||||
p = subprocess.Popen(["claude", "-p", prompt, "--plugin-dir", str(AGENTS), "--agent", "agents:analyst", *ISOLATED,
|
||||
"--output-format", "stream-json", "--verbose",
|
||||
"--allowedTools", "Read,Write,Bash", "--permission-mode", "acceptEdits", *station.links()]
|
||||
+ (["--resume", resume] if resume else []),
|
||||
cwd=station.ROOT, env=_env(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
||||
with open(out / "work" / "log.jsonl", "a", encoding="utf-8") as log:
|
||||
for line in p.stdout:
|
||||
log.write(line)
|
||||
a["lines"] += digest(line)
|
||||
if '"subtype":"init"' in line: # the session, for the next messages
|
||||
(out / "work" / "session").write_text(json.loads(line)["session_id"])
|
||||
if p.wait():
|
||||
raise RuntimeError(f"claude ended with code {p.returncode}")
|
||||
run(a, out, prompt, resume, "analyst", "Read,Write,Bash")
|
||||
a["submitted"] = submit(a["station"], name, out)
|
||||
a["state"] = "done"
|
||||
except Exception as e: # noqa: BLE001 — the error shows in the page, the server goes on
|
||||
@@ -121,7 +130,8 @@ def message(name, body):
|
||||
log.write(line)
|
||||
a["lines"] += digest(line)
|
||||
prompt = (f"{text}\n\n(If you change your labels, rewrite {out.relative_to(station.ROOT)}/labels.jsonl in full, the "
|
||||
"server will submit them again; if the diagnosis changes, update report.md.)")
|
||||
"server will submit them again; a label you change loses its review field; if the diagnosis changes, update "
|
||||
"report.md.)")
|
||||
threading.Thread(target=work, args=(name, out, prompt, session.read_text()), daemon=True).start()
|
||||
return {}
|
||||
|
||||
@@ -147,26 +157,34 @@ def digest(line):
|
||||
return out
|
||||
|
||||
|
||||
def _labels(out):
|
||||
"""The labels of the analysis, its labels.jsonl."""
|
||||
f = out / "labels.jsonl"
|
||||
return [json.loads(l) for l in f.read_text(encoding="utf-8").split("\n") if l.strip()] if f.exists() else []
|
||||
|
||||
|
||||
def submit(st, name, out):
|
||||
"""The labels of the analysis into labeling/auto/<STATION>.jsonl, with their id and the name of the analysis; if the
|
||||
analyst changed them since the last submission, they replace those it had submitted -> their number."""
|
||||
"""The labels of the analysis into labeling/auto/<STATION>.jsonl, with their id, their review and the name of the
|
||||
analysis; if they changed since the last submission, they replace those it had submitted, an unchanged label keeping
|
||||
its id -> their number."""
|
||||
labels, copy = out / "labels.jsonl", out / "work" / "submitted.jsonl"
|
||||
text = labels.read_text(encoding="utf-8") if labels.exists() else ""
|
||||
new = []
|
||||
for l in text.split("\n"):
|
||||
if l.strip():
|
||||
e = json.loads(l)
|
||||
station._validate(e, e.get("start"), e.get("end"))
|
||||
new.append({k: e[k] for k in ("start", "end", "family", "description") if k in e} | {"analysis": name})
|
||||
for e in _labels(out):
|
||||
label = {k: e[k] for k in (*station.CORE, "review") if k in e}
|
||||
station.checked(label)
|
||||
new.append(label | {"analysis": name})
|
||||
if copy.exists() and copy.read_text(encoding="utf-8") == text:
|
||||
return len(new)
|
||||
# ponytail: removed then put back, the labels of the analysis lose the edits made in the page; keeping them would
|
||||
# require matching them one by one
|
||||
with lock:
|
||||
f = station.label_file(st, "auto") # the other lines stay as they are
|
||||
kept = [l for l in (f.read_text(encoding="utf-8").split("\n") if f.exists() else [])
|
||||
if l.strip() and json.loads(l).get("analysis") != name]
|
||||
station.assign_ids(st, [json.loads(l) for l in kept] + new)
|
||||
lines = [l for l in (f.read_text(encoding="utf-8").split("\n") if f.exists() else []) if l.strip()]
|
||||
kept = [l for l in lines if json.loads(l).get("analysis") != name]
|
||||
ids = {station.core(e): e["id"] for l in lines if (e := json.loads(l)).get("analysis") == name and "id" in e}
|
||||
for e in new:
|
||||
if station.core(e) in ids:
|
||||
e["id"] = ids.pop(station.core(e))
|
||||
station.ids.assign(st, [json.loads(l) for l in kept] + new, removed=ids.values())
|
||||
temp = f.with_name(f.name + ".tmp")
|
||||
temp.write_text("".join(l + "\n" for l in kept + [json.dumps(e, ensure_ascii=False) for e in new]), encoding="utf-8")
|
||||
os.replace(temp, f)
|
||||
@@ -186,10 +204,31 @@ def state(name):
|
||||
"submitted": None, "station": request["station"], "request": request}
|
||||
a, r = analyses[name], out / "report.md"
|
||||
return {"name": name, "state": a["state"], "lines": a["lines"], "submitted": a["submitted"],
|
||||
"validated": _validated(name),
|
||||
"report": int(r.stat().st_mtime) if r.exists() else None,
|
||||
"dialogue": (out / "work" / "session").exists(), "request": a["request"], "optimization": optimization(name)}
|
||||
|
||||
|
||||
def _validated(name):
|
||||
"""The date the user validated the labels of the analysis (the last), or None if one of its labels.jsonl is not."""
|
||||
its = _labels(FOLDER / name)
|
||||
return max(e["review"] for e in its) if its and all(e.get("review") for e in its) else None
|
||||
|
||||
|
||||
def validate(name):
|
||||
"""The "Validate labels" button: the user agrees with all the labels of the finished analysis -> their number."""
|
||||
a = state(name)
|
||||
if a["state"] != "done":
|
||||
raise station.Refusal("only a finished analysis can be validated")
|
||||
out, today = FOLDER / name, datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
||||
labels = _labels(out)
|
||||
if not labels:
|
||||
raise station.Refusal("no label in this analysis")
|
||||
station.write(out / "labels.jsonl", [e | {"review": e.get("review") or today} for e in labels])
|
||||
analyses[name]["submitted"] = submit(a["request"]["station"], name, out)
|
||||
return {"validated": len(labels)}
|
||||
|
||||
|
||||
def list_analyses():
|
||||
"""The history of the analyses (the sidebar), the most recent first: those of the server with their state, the others
|
||||
read on disk (done with a report, otherwise interrupted: an analysis stops with the server)."""
|
||||
@@ -198,14 +237,15 @@ def list_analyses():
|
||||
name = d.parent.name
|
||||
a = analyses.get(name) or {"state": "done" if (d.parent / "report.md").exists() else "interrupted",
|
||||
"request": json.loads(d.read_text(encoding="utf-8"))}
|
||||
out.append({"name": name, "state": a["state"]} | a["request"])
|
||||
out.append({"name": name, "state": a["state"], "validated": _validated(name)} | a["request"])
|
||||
return out
|
||||
|
||||
|
||||
def file(name, path):
|
||||
"""A file of the folder of the analysis (the report, its figures), never outside."""
|
||||
f = (FOLDER / name / path).resolve()
|
||||
if not f.is_file() or not f.is_relative_to(FOLDER.resolve()):
|
||||
def file(name, path, folder=None):
|
||||
"""A file of the folder of the analysis (the report, its figures; or of a support request), never outside."""
|
||||
folder = folder or FOLDER
|
||||
f = (folder / name / path).resolve()
|
||||
if not f.is_file() or not f.is_relative_to(folder.resolve()):
|
||||
raise station.Refusal("unknown file")
|
||||
return f
|
||||
|
||||
|
||||
+233
-5
@@ -46,6 +46,10 @@ def check_server():
|
||||
assert call("/api/labels", {"station": "x"}, {"Content-Type": "text/plain"}) == 403
|
||||
assert call("/api/stations") == 200
|
||||
assert call("/api/analyses") == 200
|
||||
assert call("/api/support") == 200
|
||||
assert call("/api/points") == 200
|
||||
assert call("/api/points/..%2Fx") in (400, 404)
|
||||
assert call("/api/support", {"station": "x"}) == 400
|
||||
assert call("/api/analyses/UNKNOWN/optimize", {}) == 400
|
||||
finally:
|
||||
srv.should_exit = True
|
||||
@@ -75,24 +79,36 @@ def check_station():
|
||||
ev = station.detectors("LENZSPITZE", "2026-10-26", "2026-10-27") # the detectors of the journal, ~10 s
|
||||
assert ev and {"start", "end", "family", "description", "sensors"} <= set(ev[0]), ev[:1]
|
||||
assert all(e["message"] and e["action"] and set(e["targets"] + e["references"]) == set(e["sensors"]) for e in ev), ev[:1]
|
||||
assert station.message("A moved; nothing to do. The jump of 2 targets in this period has the same cause.") \
|
||||
== "A moved. The jump of 2 targets in this period has the same cause."
|
||||
assert all(e["end"] >= "2026-10-26T00:00Z" and e["start"] < "2026-10-27T00:00Z" for e in ev), [(e["start"], e["end"]) for e in ev]
|
||||
refuses(station.pump, {"stations": ["A;rm"]}) # the pumping (extraction/pumping.py, checked there): a refusal
|
||||
refuses(station.pump, {"stations": ["A;rm"], "diff": True})
|
||||
assert set(station.pump_state(True)) == {"running", "log"}
|
||||
assert not any("SIM_CCID" in t or t.startswith("System: ip") for t in titles)
|
||||
assert all(len(c["T"][tr["t"]]) == len(tr["y"]) for p in c["plots"] for tr in p["traces"])
|
||||
if run := next((s for s in station.stations() if station.RUN in s), None): # a run of data_diff/, read as a station
|
||||
c = station.curves(run, "", "")
|
||||
assert c["plots"] and station.images(run, c["A"], c["B"])["images"], run
|
||||
assert station.label_file(run, "auto").name == station.serial(run) + ".jsonl"
|
||||
assert "data_diff" in refuses(station.pumped, run)
|
||||
before, station.LABELS = station.LABELS, temp_folder()
|
||||
try:
|
||||
e = station.add({"station": "NIEDERHORN", "folder": "auto", "start": "2026-09-25T01:00Z",
|
||||
"end": "2026-09-25T02:00Z", "family": "Visibility", "description": "fog"})
|
||||
assert e["id"] == "NIEDERHORN-1" and next(iter(e)) == "id", e
|
||||
refuses(station.update, {"station": "NIEDERHORN", "folder": "auto", "before": e, # labeling/scripts/validate.py
|
||||
"start": e["start"], "end": e["end"], "family": "", "description": "rain"})
|
||||
e2 = station.update({"station": "NIEDERHORN", "folder": "auto", "before": e,
|
||||
"start": e["start"], "end": e["end"], "family": "", "description": "rain"})
|
||||
assert e2 == {"id": "NIEDERHORN-1", "start": e["start"], "end": e["end"], "description": "rain"}, e2
|
||||
"start": e["start"], "end": e["end"], "family": "Obstruction", "description": "rain"})
|
||||
assert e2 == {"id": "NIEDERHORN-1", "start": e["start"], "end": e["end"], "family": "Obstruction", "description": "rain"}, e2
|
||||
assert station.read("NIEDERHORN", "auto") == [e2]
|
||||
assert "no longer in the file" in refuses(station.delete, {"station": "NIEDERHORN", "folder": "auto", "before": e})
|
||||
station.delete({"station": "NIEDERHORN", "folder": "auto", "before": e2})
|
||||
assert station.read("NIEDERHORN", "auto") == []
|
||||
refuses(station.add, {"station": "NIEDERHORN", "folder": "../x", "start": "a", "end": "b", "description": "x"})
|
||||
refuses(station.add, {"station": "NIEDERHORN", "folder": "manual", "start": "2026-09-25T01:00Z", # the expert's
|
||||
"end": "2026-09-25T02:00Z", "family": "Visibility", "description": "fog"})
|
||||
refuses(station.add, {"station": "NIEDERHORN", "start": "2026-09-25T01:00Z", "end": "2026-09-25T02:00Z",
|
||||
"family": "Visibility", "description": "a shift of 3 px"})
|
||||
refuses(station.add, {"station": "NIEDERHORN", "start": "2026-09-25T02:00Z", "end": "2026-09-25T01:00Z", "description": "x"})
|
||||
finally:
|
||||
shutil.rmtree(station.LABELS)
|
||||
@@ -255,7 +271,219 @@ def check_analysis():
|
||||
analysis.analyses.clear()
|
||||
|
||||
|
||||
CHECKS = [check_server, check_station, check_optimization, check_analysis]
|
||||
def check_validation():
|
||||
# "Validate labels" (analysis.validate): review on all the labels of the analysis, in its labels.jsonl (which says
|
||||
# whether it is validated) and submitted with their id; the others untouched; an edit in the page removes it from one
|
||||
# label, there too, and the analysis is no longer validated
|
||||
import analysis
|
||||
before = station.LABELS, analysis.FOLDER
|
||||
station.LABELS = temp_folder()
|
||||
analysis.FOLDER = station.LABELS / "auto" / "analyses"
|
||||
try:
|
||||
for name, report in (("NORDEND_a", True), ("NORDEND_b", False)):
|
||||
(analysis.FOLDER / name / "work").mkdir(parents=True)
|
||||
(analysis.FOLDER / name / "request.json").write_text(json.dumps({"station": "NORDEND"}))
|
||||
if report:
|
||||
(analysis.FOLDER / name / "report.md").write_text("# report")
|
||||
mine = [{"start": "2026-11-05T06:00Z", "end": "2026-11-05T07:00Z", "family": "Visibility",
|
||||
"description": f"fog {i}"} for i in (1, 2)]
|
||||
other = {"id": "NORDEND-3", "start": "2026-11-05T06:00Z", "end": "2026-11-05T07:00Z", "family": "Visibility",
|
||||
"description": "rain"}
|
||||
station.write(analysis.FOLDER / "NORDEND_a" / "labels.jsonl", mine)
|
||||
station.write(station.LABELS / "auto" / "NORDEND.jsonl",
|
||||
[{"id": f"NORDEND-{i}"} | e | {"analysis": "NORDEND_a"} for i, e in enumerate(mine, 1)] + [other])
|
||||
analysis.state("NORDEND_a")
|
||||
assert analysis.state("NORDEND_a")["validated"] is None
|
||||
assert "finished" in refuses(analysis.validate, "NORDEND_b") # interrupted, no report
|
||||
assert analysis.validate("NORDEND_a") == {"validated": 2}
|
||||
theirs = analysis._labels(analysis.FOLDER / "NORDEND_a")
|
||||
assert all(e.get("review") for e in theirs), theirs
|
||||
labels = station.read("NORDEND", "auto")
|
||||
assert {e["id"]: bool(e.get("review")) for e in labels} == \
|
||||
{"NORDEND-1": True, "NORDEND-2": True, "NORDEND-3": False}, labels # the ids kept
|
||||
assert analysis.state("NORDEND_a")["validated"] == theirs[0]["review"]
|
||||
assert {a["name"]: a["validated"] for a in analysis.list_analyses()} == \
|
||||
{"NORDEND_a": theirs[0]["review"], "NORDEND_b": None} # the sidebar
|
||||
edited = next(e for e in labels if e["id"] == "NORDEND-1")
|
||||
station.update({"station": "NORDEND", "before": edited, "family": "Visibility", "description": "fog again"})
|
||||
assert analysis.state("NORDEND_a")["validated"] is None
|
||||
assert [e["description"] for e in analysis._labels(analysis.FOLDER / "NORDEND_a")] == ["fog again", "fog 2"]
|
||||
assert analysis.validate("NORDEND_a") == {"validated": 2} # validated again, the edit and the ids kept
|
||||
assert sorted((e["id"], e["description"]) for e in station.read("NORDEND", "auto")) == \
|
||||
[("NORDEND-1", "fog again"), ("NORDEND-2", "fog 2"), ("NORDEND-3", "rain")]
|
||||
station.write(analysis.FOLDER / "NORDEND_a" / "labels.jsonl", [])
|
||||
assert "no label" in refuses(analysis.validate, "NORDEND_a")
|
||||
finally:
|
||||
shutil.rmtree(station.LABELS)
|
||||
station.LABELS, analysis.FOLDER = before
|
||||
analysis.analyses.clear()
|
||||
|
||||
|
||||
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")
|
||||
(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()
|
||||
|
||||
|
||||
def check_conversations():
|
||||
# the Conversations page (conversations.py): the list, the transcript rendered safely, the files, the pumping refused
|
||||
# on a bad range; without LibreDesk (the pumping is libredesk/conversations/, tested there)
|
||||
import conversations
|
||||
root, before = temp_folder(), conversations.FOLDER
|
||||
conversations.FOLDER = root
|
||||
try:
|
||||
c = root / "42"
|
||||
(c / "attachments").mkdir(parents=True)
|
||||
(c / "conversation.json").write_text(json.dumps({"reference_number": "42", "subject": "A jump", "status": "Open",
|
||||
"updated_at": "2026-11-18T09:00:00Z", "contact": {"first_name": "Jean", "last_name": "", "email": "j@x.ch"}}))
|
||||
(c / "messages.json").write_text(json.dumps([
|
||||
{"type": "incoming", "created_at": "2026-11-18T08:00:00Z", "attachments": [{"url": "attachments/p.png"}]},
|
||||
{"type": "activity", "created_at": "2026-11-18T08:05:00Z", "attachments": []},
|
||||
{"type": "outgoing", "created_at": "2026-11-18T08:10:00Z", "attachments": [{"url": "attachments/x.svg"}]}]))
|
||||
(c / "transcript.md").write_text("# A jump\n\n<script>alert(1)</script>\n\n\n")
|
||||
(c / "attachments" / "p.png").write_bytes(b"png")
|
||||
(c / "attachments" / "x.svg").write_text("<svg onload='alert(1)'/>")
|
||||
(root / "pumped.json").write_text("{}") # not a conversation
|
||||
assert conversations.list_conversations() == [{"reference": "42", "subject": "A jump", "contact": "Jean",
|
||||
"status": "Open", "last": "2026-11-18T08:10:00Z", "messages": 2, "attachments": 2}], conversations.list_conversations()
|
||||
page = conversations.transcript("42", False)
|
||||
assert "<script>" not in page and "<script>" in page and '<img alt="p" src="attachments/p.png"' in page, page
|
||||
assert server.conversation_file("42", "attachments/x.svg").headers["content-disposition"].startswith("attachment")
|
||||
png = server.conversation_file("42", "attachments/p.png").headers
|
||||
assert "content-disposition" not in png and png["x-content-type-options"] == "nosniff"
|
||||
assert "img-src 'self'" in server.conversation_transcript("42").headers["content-security-policy"]
|
||||
refuses(conversations.transcript, "../analyses", False)
|
||||
refuses(server.conversation_file, "42", "../../etc/passwd")
|
||||
if conversations.pulling: # ~/aimsight-libredesk may be on a branch without conversations/ yet
|
||||
assert "From and To" in refuses(conversations.pump, {"start": "2026-11-01"})
|
||||
assert set(conversations.pump_state()) == {"running", "log"}
|
||||
pulling, conversations.pulling = conversations.pulling, None # no libredesk/ link: the app still runs
|
||||
try:
|
||||
assert "libredesk/" in refuses(conversations.pump, {})
|
||||
assert conversations.pump_state()["running"] is False and "libredesk/" in conversations.pump_state()["log"][0]
|
||||
finally:
|
||||
conversations.pulling = pulling
|
||||
finally:
|
||||
conversations.FOLDER = before
|
||||
shutil.rmtree(root)
|
||||
|
||||
|
||||
def check_points():
|
||||
# the Points page: a dataset of the real data in a temporary folder; its format and its rules, labeling/scripts/points.py --test
|
||||
import validity
|
||||
before, validity.points.FOLDER = validity.points.FOLDER, str(temp_folder())
|
||||
try:
|
||||
n = validity.create({"station": "NIEDERHORN", "start": "2026-09-25", "end": "2026-09-26"})
|
||||
assert n["points"] and not n["invalid"] and validity.listing("NIEDERHORN") == [n], n
|
||||
d = validity.dataset(n["name"])
|
||||
s, o = next(iter(d["sensors"].items()))
|
||||
assert validity.mark(n["name"], {"sensor": s, "times": o["t"][:2], "valid": False})["invalid"] == 2
|
||||
refuses(validity.create, {"station": "NIEDERHORN", "start": "2026-09-25", "end": "2026-09-26"}) # exists
|
||||
refuses(validity.create, {"station": "NIEDERHORN@nope", "start": "2026-09-25", "end": "2026-09-26"}) # unknown run
|
||||
refuses(validity.dataset, "../x")
|
||||
refuses(validity.mark, n["name"], {"sensor": s, "times": ["2026-09-27 00:00:00"], "valid": False})
|
||||
finally:
|
||||
shutil.rmtree(validity.points.FOLDER)
|
||||
validity.points.FOLDER = before
|
||||
|
||||
|
||||
def check_suggestions():
|
||||
# the Suggestions page (suggestions.py): the support agent's rows read from Supabase Conversations, mocked here
|
||||
import suggestions
|
||||
saved = {k: os.environ.pop(k, None) for k in ("SUPABASE_CONVERSATIONS_URL", "SUPABASE_CONVERSATIONS_KEY")}
|
||||
real_get = suggestions._get
|
||||
try:
|
||||
assert "SUPABASE_CONVERSATIONS" in refuses(suggestions.list_suggestions)
|
||||
os.environ.update(SUPABASE_CONVERSATIONS_URL="https://x.supabase.co", SUPABASE_CONVERSATIONS_KEY="k")
|
||||
asked = []
|
||||
|
||||
def fake(path):
|
||||
asked.append(path)
|
||||
if path.startswith("/rest/v1/suggestions"):
|
||||
return json.dumps([{"id": 12, "conversation_uuid": "c1", "status": "ready", "reply": "Bonjour",
|
||||
"figures": [{"path": "12/1.png", "caption": "glare"}]}]).encode()
|
||||
if path.startswith("/rest/v1/conversations"):
|
||||
return json.dumps([{"uuid": "c1", "reference_number": "151", "subject": "Crissier"}]).encode()
|
||||
return b"png"
|
||||
suggestions._get = fake
|
||||
rows = suggestions.list_suggestions()
|
||||
assert rows[0]["reference"] == "151" and rows[0]["subject"] == "Crissier" and rows[0]["reply"] == "Bonjour", rows
|
||||
refuses(suggestions.figure, "../x")
|
||||
refuses(suggestions.figure, "1/a.png")
|
||||
assert suggestions.figure("12/1.png") == b"png" and asked[-1] == "/storage/v1/object/suggestions/12/1.png", asked
|
||||
r = server.suggestion_figure("12/1.png")
|
||||
assert r.media_type == "image/png" and r.headers["x-content-type-options"] == "nosniff"
|
||||
finally:
|
||||
suggestions._get = real_get
|
||||
for k, v in saved.items():
|
||||
os.environ.pop(k, None)
|
||||
if v is not None:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support, check_conversations,
|
||||
check_points, check_suggestions]
|
||||
|
||||
if __name__ == "__main__":
|
||||
name = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""The Conversations page: the LibreDesk conversations, pumped read-only by ~/aimsight-libredesk (link libredesk/,
|
||||
conversations/pulling.py, called as it is; its key stays in its .env) into labeling/auto/conversations/<reference>/
|
||||
(conversation.json, messages.json, attachments/, transcript.md). The app lists them and shows a transcript safely: the text
|
||||
escaped before Markdown (a client's <script> stays text), served with a strict CSP (no script, no remote image), the
|
||||
attachments other than plain images as downloads.
|
||||
"""
|
||||
import html
|
||||
import json
|
||||
import sys
|
||||
|
||||
import analysis
|
||||
import station
|
||||
|
||||
FOLDER = station.LABELS / "auto" / "conversations"
|
||||
LIBREDESK = station.ROOT / "libredesk"
|
||||
sys.path.append(str(LIBREDESK / "conversations"))
|
||||
try:
|
||||
import pulling # noqa: E402
|
||||
except ImportError: # the page is not core: without the link, the rest of the app runs
|
||||
pulling = None
|
||||
MISSING = "no libredesk/ link to ~/aimsight-libredesk with conversations/ (README)"
|
||||
|
||||
INLINE = {".png", ".jpg", ".jpeg", ".gif", ".webp"} # shown in the page; any other attachment is downloaded
|
||||
|
||||
|
||||
def pump_state():
|
||||
if not pulling:
|
||||
return {"running": False, "log": [MISSING]}
|
||||
return {"running": pulling.running(), "log": pulling.log()}
|
||||
|
||||
|
||||
def pump(body):
|
||||
if not pulling:
|
||||
raise station.Refusal(MISSING)
|
||||
try:
|
||||
pulling.start(body.get("start") or "", body.get("end") or "", str(FOLDER))
|
||||
except ValueError as e:
|
||||
raise station.Refusal(str(e)) from e
|
||||
return pump_state()
|
||||
|
||||
|
||||
def list_conversations():
|
||||
"""Each pumped conversation, the most recent message first."""
|
||||
out = []
|
||||
for f in FOLDER.glob("*/conversation.json"):
|
||||
c = json.loads(f.read_text(encoding="utf-8"))
|
||||
m = f.with_name("messages.json")
|
||||
messages = json.loads(m.read_text(encoding="utf-8")) if m.exists() else []
|
||||
contact = c.get("contact") or {}
|
||||
out.append({"reference": f.parent.name, "subject": c.get("subject") or "", "status": c.get("status") or "",
|
||||
"contact": " ".join(x for x in (contact.get("first_name"), contact.get("last_name")) if x)
|
||||
or contact.get("email") or "",
|
||||
"last": max((x["created_at"] for x in messages), default=c.get("updated_at") or ""),
|
||||
"messages": sum(x.get("type") != "activity" for x in messages),
|
||||
"attachments": sum(len(x.get("attachments") or []) for x in messages)})
|
||||
return sorted(out, key=lambda c: c["last"], reverse=True)
|
||||
|
||||
|
||||
def transcript(reference, dark):
|
||||
"""transcript.md in HTML, escaped first: what a client wrote is shown, never run."""
|
||||
text = analysis.file(reference, "transcript.md", FOLDER).read_text(encoding="utf-8")
|
||||
return analysis._page(html.escape(text, quote=False), reference, dark)
|
||||
+137
-5
@@ -2,7 +2,8 @@
|
||||
|
||||
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
|
||||
optimization of the detectors (analysis.py).
|
||||
optimization of the detectors (analysis.py); its Support tab, the support (support.py). The Conversations page, the
|
||||
LibreDesk conversations pumped by ~/aimsight-libredesk (conversations.py).
|
||||
Settings: AIMSIGHT_DATA (data), AIMSIGHT_LABELS (labels), AIMSIGHT_PORT (port, 8770).
|
||||
"""
|
||||
import json
|
||||
@@ -16,10 +17,14 @@ from pathlib import Path
|
||||
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, Query, Request
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
|
||||
|
||||
import analysis
|
||||
import conversations
|
||||
import suggestions
|
||||
import station
|
||||
import support
|
||||
import validity
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
APP = Path(__file__).resolve().parents[1]
|
||||
@@ -73,12 +78,33 @@ def curves(station_: str = Query(alias="station"), start: str = "", end: str = "
|
||||
|
||||
|
||||
@app.get("/api/detectors")
|
||||
def detectors(station_: str = Query(alias="station"), start: str = "", end: str = "", targets: str = ""):
|
||||
return station.detectors(station_, start, end, targets)
|
||||
def detectors(station_: str = Query(alias="station"), start: str = "", end: str = "", targets: str = "", set_: str = Query("classic", alias="set"),
|
||||
sensitivity: int = 0):
|
||||
return station.detectors(station_, start, end, targets, set_, sensitivity)
|
||||
|
||||
|
||||
@app.get("/api/tracked")
|
||||
def tracked():
|
||||
return [{"serial": s, "position": p} for s, p in station.pumping.tracked().items()]
|
||||
|
||||
|
||||
@app.put("/api/tracked")
|
||||
def save_tracked(body: dict):
|
||||
return station.save_tracked(body.get("stations") or [])
|
||||
|
||||
|
||||
@app.get("/api/pump")
|
||||
def pump_state(diff: bool = False):
|
||||
return station.pump_state(diff)
|
||||
|
||||
|
||||
@app.post("/api/pump")
|
||||
def pump(body: dict):
|
||||
return station.pump(body)
|
||||
|
||||
|
||||
@app.get("/api/labels")
|
||||
def labels(station_: str = Query(alias="station"), folder: str = "manual"):
|
||||
def labels(station_: str = Query(alias="station"), folder: str = "auto"):
|
||||
try:
|
||||
return station.read(station_, folder)
|
||||
except json.JSONDecodeError as e: # a line damaged by hand: say so, without touching the file
|
||||
@@ -127,6 +153,11 @@ def analysis_report(name: str, dark: bool = False):
|
||||
return HTMLResponse(analysis.report(name, dark))
|
||||
|
||||
|
||||
@app.post("/api/analyses/{name}/validate")
|
||||
def validate_analysis(name: str):
|
||||
return analysis.validate(name)
|
||||
|
||||
|
||||
@app.post("/api/analyses/{name}/optimize")
|
||||
def optimize_analysis(name: str):
|
||||
return analysis.optimize(name)
|
||||
@@ -142,6 +173,107 @@ def analysis_file(name: str, path: str):
|
||||
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))
|
||||
|
||||
|
||||
# --- the Points page (validity.py): the point labels of labeling/points/, valid or not, set by the user
|
||||
|
||||
@app.get("/api/points")
|
||||
def points_list(station_: str = Query("", alias="station")):
|
||||
return validity.listing(station_)
|
||||
|
||||
|
||||
@app.post("/api/points")
|
||||
def points_create(body: dict):
|
||||
return validity.create(body)
|
||||
|
||||
|
||||
@app.get("/api/points/{name}")
|
||||
def points_dataset(name: str):
|
||||
return validity.dataset(name)
|
||||
|
||||
|
||||
@app.put("/api/points/{name}")
|
||||
def points_mark(name: str, body: dict):
|
||||
return validity.mark(name, body)
|
||||
|
||||
|
||||
# --- the Conversations page (conversations.py): the LibreDesk conversations, pumped read-only, and their transcripts
|
||||
|
||||
CSP = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'" # a client's mail: no script, no remote image
|
||||
|
||||
|
||||
@app.get("/api/conversations/pump")
|
||||
def conversations_pump_state():
|
||||
return conversations.pump_state()
|
||||
|
||||
|
||||
@app.post("/api/conversations/pump")
|
||||
def conversations_pump(body: dict):
|
||||
return conversations.pump(body)
|
||||
|
||||
|
||||
@app.get("/api/conversations")
|
||||
def conversations_list():
|
||||
return conversations.list_conversations()
|
||||
|
||||
|
||||
@app.get("/api/conversations/{reference}/report.html")
|
||||
def conversation_transcript(reference: str, dark: bool = False):
|
||||
return HTMLResponse(conversations.transcript(reference, dark), headers={"Content-Security-Policy": CSP})
|
||||
|
||||
|
||||
@app.get("/api/conversations/{reference}/{path:path}")
|
||||
def conversation_file(reference: str, path: str):
|
||||
"""A plain image inline; any other attachment (an .html, an .svg) as a download: it never runs at the app's address."""
|
||||
f = analysis.file(reference, path, conversations.FOLDER)
|
||||
headers = {"X-Content-Type-Options": "nosniff", "Content-Security-Policy": CSP}
|
||||
return FileResponse(f, headers=headers) if f.suffix.lower() in conversations.INLINE \
|
||||
else FileResponse(f, filename=f.name, headers=headers)
|
||||
|
||||
|
||||
# --- the Suggestions page (suggestions.py): the support agent's draft replies, read-only from Supabase Conversations
|
||||
|
||||
@app.get("/api/suggestions")
|
||||
def suggestions_list():
|
||||
return suggestions.list_suggestions()
|
||||
|
||||
|
||||
@app.get("/api/suggestions/figure/{path:path}")
|
||||
def suggestion_figure(path: str):
|
||||
return Response(suggestions.figure(path), media_type="image/png",
|
||||
headers={"X-Content-Type-Options": "nosniff", "Content-Security-Policy": CSP})
|
||||
|
||||
|
||||
if PAGE.is_dir():
|
||||
app.mount("/", StaticFiles(directory=PAGE, html=True), name="page")
|
||||
else:
|
||||
|
||||
+211
-128
@@ -1,28 +1,44 @@
|
||||
"""The data of the Data page: a station's images, its curves, its labels.
|
||||
|
||||
Data are read as the agents read them, tools/scripts/data.py (the tools repository, through the tools/ link); the detectors'
|
||||
events are those of detectors/scripts/categories.py (events). Read-only on data/; writes only in labeling/{auto,manual}/.
|
||||
events are those of detectors/detectors/categories.py (window); the rules of the labels and what the client is told, those of
|
||||
labeling/scripts (validate, ids, client). Read-only on data/, filled only by pump.sh; writes only in
|
||||
labeling/auto/. What brings data in (the pumping, the list of the tracked stations) is in ~/aimsight-data, called as it
|
||||
is (extraction/pumping.py); the weather is pumped with the data, data/<STATION>/weather/ (data.load_weather).
|
||||
The runs of the differential data (data_diff/<SERIAL>/runs/<run>/ of ~/aimsight-data) are stations too, <SERIAL>@<run>:
|
||||
read by the same reader (data.shared: their images, metrics and weather in data_diff/<SERIAL>/); their labels are those of
|
||||
<SERIAL>.
|
||||
"""
|
||||
import bisect
|
||||
import functools
|
||||
import csv
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import pickle
|
||||
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")]
|
||||
# ~/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
|
||||
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "detectors"), str(ROOT / "labeling" / "scripts"),
|
||||
str(DATA_REPOSITORY / "extraction")]
|
||||
import categories # noqa: E402
|
||||
import client # noqa: E402 (labeling: what the client is told of an event)
|
||||
import data # noqa: E402
|
||||
from categories import events # noqa: E402
|
||||
import ids # noqa: E402 (labeling: the stable id of the labels)
|
||||
import pumping # noqa: E402
|
||||
import validate # noqa: E402 (labeling: the rules of a label)
|
||||
|
||||
# data/ and labeling/ are links to ~/aimsight-data/data and ~/aimsight-labeling: no resolve(), the agents see data/ and labeling/
|
||||
DATA = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).absolute()
|
||||
LABELS = Path(os.environ.get("AIMSIGHT_LABELS", ROOT / "labeling")).absolute()
|
||||
DATA_DIFF = DATA_REPOSITORY / "data_diff" # the runs, data_diff/<SERIAL>/runs/<run>/: out of git, filled by ~/aimsight-data
|
||||
RUN = "@" # <SERIAL>@<run>: a run of data_diff/ in the list of the stations
|
||||
TOOLS = ROOT / "tools" # the reading harness (~/aimsight-tools), read by the analyst and written by the upgrader (Optimizer)
|
||||
|
||||
|
||||
@@ -31,21 +47,18 @@ def links():
|
||||
return [a for d in (DATA, LABELS, TOOLS) for a in ("--add-dir", str(d.resolve()))]
|
||||
|
||||
|
||||
FOLDERS = ("auto", "manual") # those of the agents and of the page (D-105), those of the expert (D-102)
|
||||
FAMILIES = ("Visibility", "Obstruction", "Thermal displacement", "Displacement", "Target issue", "No data", "None") # D-109
|
||||
FOLDERS = ("auto",) # the labels of the agents and of the page (D-105); manual/ is the expert's alone (labeling/CLAUDE.md)
|
||||
FORMAT = "%Y-%m-%dT%H:%MZ"
|
||||
MARGIN_PX = 150 # Support-Agent detecteurs.MARGE_PX: x, y are positions in the image only far from the corner
|
||||
COLORS = ["#2a78d6", "#eb6834", "#1baf7a", "#8a5cd6", "#d6a12a", "#d63b8a", "#3bb3d6", "#6b6b66"] # one per sensor
|
||||
POSE = (("pan", "#1a1a19"), ("tilt", "#8a8a85"), ("rotation", "#b5651d"))
|
||||
# The Advanced menu of Explore, in its order (Support-Agent labeling.PLOTS, QUALITE)
|
||||
PLOTS = (("error_value", "Error value"), ("x", "X [px]"), ("y", "Y [px]"),
|
||||
("relative_x", "Relative Horizontal Shift"), ("relative_y", "Relative Vertical Shift"),
|
||||
("corr_x", "Relative Corrected Horizontal Shift"), ("corr_y", "Relative Corrected Vertical Shift"),
|
||||
("corr_x_mm", "Relative Corrected Horizontal Shift [mm]"), ("corr_y_mm", "Relative Corrected Vertical Shift [mm]"),
|
||||
("reproj_err", "References (reproj. error)"))
|
||||
QUALITY = (("peak", "Quality: Peak"), ("flux", "Quality: Flux"), ("sharpness", "Quality: Sharpness"),
|
||||
("fwhm", "Quality: FWHM [px]"), ("dominance", "Quality: Dominance"), ("snr", "Quality: SNR"))
|
||||
IDENTIFIER = re.compile(r"(SIM_CCID|ip(_.*)?)$") # never read (CLAUDE.md, "data/")
|
||||
METRIC = re.compile(r"^(.+?)_\d{4}_\d{2}_\d{2}_")
|
||||
|
||||
|
||||
class Refusal(ValueError):
|
||||
@@ -53,13 +66,27 @@ class Refusal(ValueError):
|
||||
|
||||
|
||||
def stations():
|
||||
return sorted(d.name for d in DATA.iterdir() if d.is_dir())
|
||||
runs = [f"{d.parent.parent.name}{RUN}{d.name}" for d in DATA_DIFF.glob("*/runs/*") if d.is_dir()]
|
||||
return sorted([d.name for d in DATA.iterdir() if d.is_dir()] + runs) # a run right after its station
|
||||
|
||||
|
||||
def serial(station):
|
||||
"""The station of a run, <SERIAL>@<run> -> <SERIAL> (its labels); a station of data/ -> itself."""
|
||||
return station.partition(RUN)[0]
|
||||
|
||||
|
||||
def folder(station):
|
||||
if station not in stations(): # the name becomes a path: a folder of data/, nothing else
|
||||
if station not in stations(): # the name becomes a path: a folder of data/ or a run of data_diff/, nothing else
|
||||
raise Refusal(f"unknown station: {station}")
|
||||
return DATA / station
|
||||
s, _, run = station.partition(RUN)
|
||||
return DATA_DIFF / s / "runs" / run if run else DATA / station
|
||||
|
||||
|
||||
def pumped(station):
|
||||
"""A station of data/ (the agents read data/ only): a run of data_diff/ refused."""
|
||||
folder(station)
|
||||
if RUN in station:
|
||||
raise Refusal(f"{station} is a run of data_diff/: the agents read the stations of data/ only")
|
||||
|
||||
|
||||
def bounds(start, end):
|
||||
@@ -69,16 +96,15 @@ def bounds(start, end):
|
||||
# --- the positions of the sensors in the image
|
||||
|
||||
def positions(measurements, a, b):
|
||||
"""The median position of each sensor in the image over [a, b) ({} if x, y are not positions there)."""
|
||||
homes = {s: (statistics.median(xs), statistics.median(ys)) for s, ms in measurements.items()
|
||||
if (xs := [m["x"] for m in ms if a <= m["t"] < b and m["x"] is not None])
|
||||
and (ys := [m["y"] for m in ms if a <= m["t"] < b and m["y"] is not None])}
|
||||
return homes if any(abs(x) > MARGIN_PX or abs(y) > MARGIN_PX for x, y in homes.values()) else {}
|
||||
"""Where to circle each sensor on the images: its median x, y over [a, b) (image px, tools/DATA.md)."""
|
||||
return {s: (statistics.median(xs), statistics.median(ys)) for s, ms in measurements.items()
|
||||
if (xs := [m["x"] for m in ms if a <= m["t"] < b and m["x"] is not None])
|
||||
and (ys := [m["y"] for m in ms if a <= m["t"] < b and m["y"] is not None])}
|
||||
|
||||
|
||||
def references(measurements, a, b):
|
||||
"""Sensors of the compensation over the range: those with a reproj_err (references only)."""
|
||||
return {s for s, ms in measurements.items() if any(m["reproj_err"] is not None for m in ms if a <= m["t"] < b)}
|
||||
def references(measurements):
|
||||
"""The references of the compensation (tools/scripts/data.py, is_reference)."""
|
||||
return {s for s, ms in measurements.items() if data.is_reference(ms)}
|
||||
|
||||
|
||||
# --- the images of the Data page
|
||||
@@ -87,11 +113,11 @@ def images(station, start, end):
|
||||
"""The images of [start, end), the median positions of the sensors, the references, and for each circled sensor its
|
||||
corr_x, corr_y at the time of each image: the nearest valid measurement, within 30 min, otherwise 0."""
|
||||
d, (a, b) = folder(station), bounds(start, end)
|
||||
views = [(t, im) for im in sorted(glob.glob(str(d / "images" / "*"))) if (t := data.image_time(im)) and a <= t < b]
|
||||
views = [(t, im) for im in sorted(glob.glob(str(Path(data.shared(d)) / "images" / "*"))) if (t := data.image_time(im)) and a <= t < b]
|
||||
if not views:
|
||||
raise Refusal(f"no image of {station} in this range")
|
||||
measurements = data.load(d)
|
||||
homes, refs = positions(measurements, a, b), references(measurements, a, b)
|
||||
homes, refs = positions(measurements, a, b), references(measurements)
|
||||
# ponytail: a single measurement at each bound, noisy; a median over a window if the arrows shake too much
|
||||
margin, corr = timedelta(minutes=30), {}
|
||||
for s in homes:
|
||||
@@ -107,32 +133,23 @@ def images(station, start, end):
|
||||
|
||||
|
||||
def image(station, name):
|
||||
f = (folder(station) / "images" / name).resolve()
|
||||
if f.parent != (DATA / station / "images").resolve() or not f.is_file():
|
||||
images = Path(data.shared(folder(station))) / "images"
|
||||
f = (images / name).resolve()
|
||||
if f.parent != images.resolve() or not f.is_file():
|
||||
raise Refusal("unknown image")
|
||||
return f
|
||||
|
||||
|
||||
# --- the curves of the Data page
|
||||
|
||||
def metrics(d, a, b):
|
||||
"""The numeric system metrics of metrics/ over [a, b) -> {name: {t: value or None}} (an empty value: None, the gap
|
||||
shows), without the text metrics, the identifiers, or those with no value at all."""
|
||||
station, series, text = d.name + "_", {}, set()
|
||||
for p in sorted(glob.glob(str(d / "metrics" / "*.csv"))):
|
||||
if not (m := METRIC.match(os.path.basename(p))) or IDENTIFIER.match(name := m.group(1).removeprefix(station)):
|
||||
continue
|
||||
with open(p, newline="") as f:
|
||||
for r in csv.DictReader(f):
|
||||
t, v = data.parse_time(r["time_utc"]), (r.get("metric") or "").strip("[]'\" ")
|
||||
if not a <= t < b:
|
||||
continue
|
||||
try:
|
||||
series.setdefault(name, {})[t] = float(v) if v else None
|
||||
except ValueError:
|
||||
text.add(name) # link, mode…: no curve
|
||||
return {n: dict(sorted(s.items())) for n, s in series.items()
|
||||
if n not in text and any(v is not None for v in s.values())}
|
||||
def holes(points, step=timedelta(hours=1)):
|
||||
"""[(t, v)] sorted -> the same, with (t + step, None) after a point followed by nothing during more than a step."""
|
||||
out = []
|
||||
for t, v in points:
|
||||
if out and t - out[-1][0] > step:
|
||||
out.append((out[-1][0] + step, None))
|
||||
out.append((t, v))
|
||||
return out
|
||||
|
||||
|
||||
def span(measurements, start, end):
|
||||
@@ -155,7 +172,7 @@ def curves(station, start, end):
|
||||
hour = lambda t: t.strftime("%Y-%m-%d %H:%M") # noqa: E731 (UTC, without time zone: as Plotly shows it)
|
||||
values = lambda s, c: [None if m[c] is None else round(m[c], 5) for m in s] # noqa: E731
|
||||
inside = {s: [m for m in measurements[s] if a <= m["t"] < b] for s in sorted(measurements)}
|
||||
refs, out = references(measurements, a, b), []
|
||||
refs, out = references(measurements), []
|
||||
|
||||
def per_sensor(columns):
|
||||
for col, title in columns:
|
||||
@@ -171,28 +188,116 @@ def curves(station, start, end):
|
||||
"line": {"width": 1.2, "color": col}} for c, col in POSE]})
|
||||
per_sensor(QUALITY)
|
||||
T = {"": [hour(p["t"]) for p in poses], **{s: [hour(m["t"]) for m in ms] for s, ms in inside.items()}}
|
||||
system = metrics(d, a, b)
|
||||
# the numeric system metrics (data.load_metrics: without the text metrics and the identifiers), over [a, b); an
|
||||
# hour without value breaks the line (None), the hole shows
|
||||
system = {n: holes(kept) for n, vs in data.load_metrics(d).items() if (kept := [(t, v) for t, v in vs if a <= t < b])}
|
||||
for name in sorted(system, key=str.lower):
|
||||
T["system:" + name] = [hour(t) for t in system[name]]
|
||||
T["system:" + name] = [hour(t) for t, _ in system[name]]
|
||||
out.append({"title": "System: " + name, "traces": [{"name": name, "t": "system:" + name, "mode": "lines+markers",
|
||||
"y": [None if v is None else round(v, 5) for v in system[name].values()],
|
||||
"y": [None if v is None else round(v, 5) for _, v in system[name]],
|
||||
"line": {"width": 1.2, "color": COLORS[0]}}]})
|
||||
if not out:
|
||||
raise Refusal(f"no measurement of {station} in this range")
|
||||
return {"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 hours := [h for h in data.load_weather(d) if a <= h["t"] < b]: # the weather pumped with the data, if any
|
||||
label, times, plots = weather(hours)
|
||||
T.update(times)
|
||||
out += plots
|
||||
result["weather"] = label
|
||||
elif pumping.tracked().get(serial(station)):
|
||||
result["weather"] = "none pumped in this range (see the pumping log)"
|
||||
return result
|
||||
|
||||
|
||||
# --- 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"),
|
||||
("Wind (km/h)", "wind_speed_kmh", "wind_gust_kmh"), ("Wind direction (deg)", "wind_direction_deg"),
|
||||
("Pressure (hPa)", "pressure_hpa"), ("Sunshine (min/h)", "sunshine_min"),
|
||||
("Global radiation (W/m²)", "global_radiation_wm2"), ("Snow depth (cm)", "snow_depth_cm"))
|
||||
|
||||
|
||||
def weather(hours):
|
||||
"""[hour] of data.load_weather, not empty -> (label, T, plots) as curves(); their times under T["system:weather"], so
|
||||
that the target filters ignore them; the label: where the last hour was measured."""
|
||||
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, [h.get(c) for h in hours]) for c in columns) if any(v is not None for v in y)]
|
||||
if traces:
|
||||
plots.append({"title": "Weather: " + title, "traces": traces})
|
||||
w = hours[-1]
|
||||
return (f"{w['place']} → MeteoSwiss {w['station']} {w['station_name']}, {w['distance_km']} km, {w['height_m']} m"
|
||||
+ " (no measurement in this range)" * (not plots),
|
||||
{"system:weather": [h["t"].strftime("%Y-%m-%d %H:%M") for h in hours]}, plots)
|
||||
|
||||
|
||||
# --- the tracked stations and the pumping: extraction/pumping.py of ~/aimsight-data
|
||||
|
||||
pump_process = {} # the pumpings launched by the app, by diff (pump_diff.sh, into data_diff/: beside pump.sh)
|
||||
|
||||
|
||||
def save_tracked(rows):
|
||||
try:
|
||||
return [{"serial": s, "position": p} for s, p in pumping.save(rows).items()]
|
||||
except ValueError as e:
|
||||
raise Refusal(str(e))
|
||||
|
||||
|
||||
def pump_state(diff=False):
|
||||
"""{running, log}; the end of the app's pumping empties the cache of the detectors' events."""
|
||||
if (p := pump_process.get(diff)) and p.poll() is not None:
|
||||
del pump_process[diff]
|
||||
detectors.cache_clear()
|
||||
return {"running": pumping.running(diff) or diff in pump_process, "log": pumping.log(diff=diff)}
|
||||
|
||||
|
||||
def pump(body):
|
||||
diff = bool(body.get("diff"))
|
||||
try:
|
||||
pump_process[diff] = pumping.start(body.get("stations") or [], body.get("start") or "", body.get("end") or "",
|
||||
body.get("images"), diff)
|
||||
except ValueError as e:
|
||||
raise Refusal(str(e))
|
||||
return pump_state(diff)
|
||||
|
||||
|
||||
# --- the Data page, "Detectors" labels: the events of the journal, read-only
|
||||
|
||||
HISTORY = timedelta(days=3) # days before given to the detectors, as categories.py does (rule of 2026-10-24)
|
||||
# The sets of detectors: detectors/detectors/ (classic, imported here), models/rules/manual/ (the same layout, hand-made: run in
|
||||
# a process of its own, its modules bear the same names as the classic ones)
|
||||
MANUAL = ROOT / "models" / "rules" / "manual"
|
||||
CHILD = ("import pickle, sys; out, sys.stdout = sys.stdout.buffer, sys.stderr; sys.path.insert(0, sys.argv[1]); import categories; "
|
||||
"pickle.dump(categories.window(*pickle.load(sys.stdin.buffer)), out)")
|
||||
|
||||
|
||||
def window(set_, every, a, b, sensitivity=0):
|
||||
"""categories.window of the chosen set; sensitivity (1 to 10, 0: the default of the code): the manual set only."""
|
||||
if set_ != "manual":
|
||||
return categories.window(every, a, b)
|
||||
if not (MANUAL / "categories.py").is_file():
|
||||
raise Refusal("no manual detectors: models/rules/manual/ has no categories.py")
|
||||
run = subprocess.run([sys.executable, "-c", CHILD, str(MANUAL)], input=pickle.dumps((every, a, b, sensitivity or None)), capture_output=True, cwd=ROOT)
|
||||
sys.stderr.write(run.stderr.decode(errors="replace"))
|
||||
if run.returncode:
|
||||
raise Refusal("the manual detectors failed: " + (run.stderr.decode(errors="replace").strip().splitlines() or ["?"])[-1])
|
||||
return pickle.loads(run.stdout)
|
||||
|
||||
|
||||
def detectors(station, start, end, targets="", set_="classic", sensitivity=0):
|
||||
"""journal(), from the cache for the classic set; the manual set, being written, computed again at each call."""
|
||||
return (journal.__wrapped__ if set_ == "manual" else journal)(station, start, end, targets, set_, sensitivity)
|
||||
|
||||
|
||||
# ponytail: kept until the server restarts (a minute or more per range); restart it after an /optimize run outside the app
|
||||
@functools.lru_cache(maxsize=32)
|
||||
def detectors(station, start, end, targets=""):
|
||||
def journal(station, start, end, targets="", set_="classic", sensitivity=0):
|
||||
"""-> the detectors' events over the range, in the label format (start, end, family, description); plus kind,
|
||||
sensors, ignore (greyed area of the journal). targets: the sensors kept, comma-separated (empty: all); the others are
|
||||
removed before the detectors, as if they did not exist."""
|
||||
removed before the detectors, as if they did not exist. set_: classic (detectors/detectors/) or manual (models/rules/manual/);
|
||||
sensitivity: of the manual set, 1 (tolerant) to 10 (severe), 0: the default of the code."""
|
||||
d = folder(station)
|
||||
every = data.load(d)
|
||||
if targets:
|
||||
@@ -201,50 +306,12 @@ def detectors(station, start, end, targets=""):
|
||||
if not every:
|
||||
raise Refusal(f"no \"advanced\" export for {station}" + " with these targets" * bool(targets))
|
||||
a, b = span(every, start, end)
|
||||
measurements = {s: k for s, ms in every.items() if (k := [m for m in ms if a - HISTORY <= m["t"] < b])}
|
||||
evs = [v for v in events(measurements, b, str(d)) if v["end"] >= data.iso(a)] if measurements else []
|
||||
refs = {s for s, ms in measurements.items() if ms[0]["pattern_type"] == "global_ref"}
|
||||
return [{"id": f"D-{i + 1}", "start": v["start"], "end": v["end"], "family": v["category"], "kind": v["episodes"][0]["label"],
|
||||
"description": f"{v['episodes'][0]['label']}. {v['text']}", "sensors": v["sensors"], "ignore": v["ignore"],
|
||||
refs, advice = references(every), client.advice()
|
||||
return [{"id": f"D-{i + 1}", "start": v["start"], "end": v["end"], "family": v["category"], "kind": (ep := v["episodes"][0])["label"],
|
||||
"description": f"{ep['label']}. {v['text']}", "sensors": v["sensors"], "ignore": v["ignore"],
|
||||
"targets": [s for s in v["sensors"] if s not in refs], "references": [s for s in v["sensors"] if s in refs],
|
||||
"message": message(v["text"]), "action": action(v)}
|
||||
for i, v in enumerate(evs)]
|
||||
|
||||
|
||||
def message(text):
|
||||
"""What happens: the first sentence of the journal (detectors/scripts/categories.py, sentence), up to its ";"; the rest
|
||||
says what to do about it, except the sentence of the absorbed jumps, kept. ". " only: "1.5×" or "0.30 px" do not cut."""
|
||||
same = re.search(r" (The jumps? of .* same cause\.)$", text)
|
||||
return re.split(r"\. |; ", text, maxsplit=1)[0].rstrip(".") + "." + (" " + same.group(1) if same else "")
|
||||
|
||||
|
||||
# What to do about it: the "For the client" column of labeling/families.md, per family; refined per kind (the label of the
|
||||
# main episode, with its level) after the journal sentences validated on 2026-10-24 (detectors/scripts/categories.py, sentence)
|
||||
ACTION_FAMILY = {
|
||||
"Visibility": "Do not trust the curves in this period: this is not a movement.",
|
||||
"Obstruction": "Ignore the curves of the hidden targets in this period.",
|
||||
"Thermal displacement": "Normal, nothing to do.",
|
||||
"Displacement": "To check: look at the images, then keep watching.",
|
||||
"Target issue": "Act on the target (prism, mount); ignore its curve in the meantime.",
|
||||
"No data": "The curves are missing in this period; its cause tells whether to act.",
|
||||
}
|
||||
ACTION_KIND = {
|
||||
"Poor visibility reduced": "Use the data in this period with care: they are less precise.",
|
||||
"Heat shimmer": "Nothing to do: the small fast wiggles are not movement.",
|
||||
"Camera thermal movement": "Nothing to do: this is not a movement of the structure.",
|
||||
"Brief obstruction": "Ignore this single point on the curves.",
|
||||
"Sudden jump, back to normal": "Look at the images: the cause is not established.",
|
||||
"Lasting shift": "Check whether the structure moved: look at the images.",
|
||||
"Jump, not back yet": "Check whether the structure moved: look at the images.",
|
||||
"Large shift": "Check whether the structure moved: look at the images.",
|
||||
"Slow drift": "Keep watching it.",
|
||||
}
|
||||
|
||||
|
||||
def action(v):
|
||||
ep = v["episodes"][0]
|
||||
return ACTION_KIND.get(f"{ep['label']} {ep.get('level') or ''}".strip(), ACTION_KIND.get(ep["label"])) \
|
||||
or ACTION_FAMILY.get(v["category"], "")
|
||||
"message": client.message(v["text"]), "action": client.action(v["category"], ep["label"], ep.get("level"), advice)}
|
||||
for i, v in enumerate(window(set_, every, a, b, sensitivity))]
|
||||
|
||||
|
||||
# --- the labels
|
||||
@@ -253,7 +320,21 @@ def label_file(station, source):
|
||||
if source not in FOLDERS:
|
||||
raise Refusal("unknown label folder")
|
||||
folder(station)
|
||||
return LABELS / source / f"{station}.jsonl"
|
||||
return LABELS / source / f"{serial(station)}.jsonl"
|
||||
|
||||
|
||||
CORE = ("start", "end", "family", "description") # what a label says; the rest (id, review, analysis) is about it
|
||||
|
||||
|
||||
def core(label):
|
||||
return tuple(label.get(k) for k in CORE)
|
||||
|
||||
|
||||
def write(f, labels):
|
||||
"""Writes the labels next to the file then replaces it: an interruption does not damage it."""
|
||||
temp = f.with_name(f.name + ".tmp")
|
||||
temp.write_text("".join(json.dumps(e, ensure_ascii=False) + "\n" for e in labels), encoding="utf-8")
|
||||
os.replace(temp, f)
|
||||
|
||||
|
||||
def read(station, source):
|
||||
@@ -262,41 +343,29 @@ def read(station, source):
|
||||
return [json.loads(l) for l in f.read_text(encoding="utf-8").split("\n") if l.strip()] if f.exists() else []
|
||||
|
||||
|
||||
def assign_ids(station, labels):
|
||||
"""As labeling/scripts/ids.py does (D-131): an id for the labels without one, the next of the station, as first field."""
|
||||
n = max((int(e["id"].rsplit("-", 1)[1]) for e in labels if "id" in e), default=0)
|
||||
for e in labels:
|
||||
if "id" not in e:
|
||||
n += 1
|
||||
e["id"] = f"{station}-{n}"
|
||||
if next(iter(e)) != "id":
|
||||
rest = {k: v for k, v in e.items() if k != "id"}
|
||||
ident = e["id"]
|
||||
e.clear()
|
||||
e.update({"id": ident}, **rest)
|
||||
def checked(label):
|
||||
"""A label written in auto/: the rules of labeling (labeling/scripts/validate.py, check), before its id."""
|
||||
if errors := validate.check(label, proposed=True):
|
||||
raise Refusal("; ".join(errors))
|
||||
|
||||
|
||||
def _validate(body, start, end):
|
||||
description = (body.get("description") or "").strip()
|
||||
def checked_range(start, end):
|
||||
"""A range asked by the page: YYYY-MM-DDTHH:MMZ, start before end."""
|
||||
try:
|
||||
empty = datetime.strptime(start, FORMAT) >= datetime.strptime(end, FORMAT)
|
||||
if datetime.strptime(start, FORMAT) < datetime.strptime(end, FORMAT):
|
||||
return
|
||||
except (TypeError, ValueError):
|
||||
raise Refusal("unreadable bounds (YYYY-MM-DDTHH:MMZ)") from None
|
||||
if not description or empty:
|
||||
raise Refusal("empty text or empty range")
|
||||
family = body.get("family") or ""
|
||||
if family and family not in FAMILIES:
|
||||
raise Refusal("unknown family")
|
||||
return description, family
|
||||
pass
|
||||
raise Refusal("unreadable or empty range (YYYY-MM-DDTHH:MMZ)")
|
||||
|
||||
|
||||
def add(body):
|
||||
station, source = body.get("station"), body.get("folder", "manual")
|
||||
station, source = body.get("station"), body.get("folder", "auto")
|
||||
f = label_file(station, source)
|
||||
description, family = _validate(body, body.get("start"), body.get("end"))
|
||||
label = {"start": body["start"], "end": body["end"]} | ({"family": family} if family else {}) | {"description": description}
|
||||
if source == "auto": # an automatic label carries a stable id, the next of its station (D-131)
|
||||
assign_ids(station, read(station, "auto") + [label])
|
||||
label = {"start": body.get("start"), "end": body.get("end"), "family": body.get("family"),
|
||||
"description": (body.get("description") or "").strip()}
|
||||
checked(label)
|
||||
ids.assign(serial(station), read(station, source) + [label]) # a stable id, the next of its station (D-131)
|
||||
f.parent.mkdir(parents=True, exist_ok=True)
|
||||
before = f.read_bytes() if f.exists() else b"" # a line removed by hand may leave the file without a final newline
|
||||
with open(f, "ab") as out:
|
||||
@@ -307,19 +376,17 @@ def add(body):
|
||||
def update(body):
|
||||
before = body.get("before") or {}
|
||||
start, end = body.get("start", before.get("start")), body.get("end", before.get("end"))
|
||||
description, family = _validate(body, start, end)
|
||||
label = dict.fromkeys(("id", "start", "end", "family")) | before | {"start": start, "end": end, "family": family,
|
||||
"description": description}
|
||||
label = dict.fromkeys(("id", "start", "end", "family")) | before | {"start": start, "end": end, "family": body.get("family"),
|
||||
"description": (body.get("description") or "").strip()}
|
||||
if label["id"] is None:
|
||||
del label["id"]
|
||||
if not family:
|
||||
del label["family"]
|
||||
label.pop("review", None) # changed: no longer reviewed
|
||||
return replace(body.get("station"), body.get("folder", "manual"), before, label)
|
||||
checked(label)
|
||||
return replace(body.get("station"), body.get("folder", "auto"), before, label)
|
||||
|
||||
|
||||
def delete(body):
|
||||
replace(body.get("station"), body.get("folder", "manual"), body.get("before"), None)
|
||||
replace(body.get("station"), body.get("folder", "auto"), body.get("before"), None)
|
||||
return body.get("before")
|
||||
|
||||
|
||||
@@ -334,5 +401,21 @@ def replace(station, source, before, label):
|
||||
temp = f.with_name(f.name + ".tmp")
|
||||
temp.write_text("\n".join(lines), encoding="utf-8")
|
||||
os.replace(temp, f)
|
||||
if before.get("analysis"):
|
||||
analysis_label(before, label)
|
||||
return label
|
||||
raise Refusal("this label is no longer in the file: reload the page")
|
||||
|
||||
|
||||
def analysis_label(before, label):
|
||||
"""A label of an analysis edited or removed in the page: the same in the labels.jsonl of the analysis, which says
|
||||
whether it is validated (its review); a resubmission then keeps the edit."""
|
||||
f = LABELS / "auto" / "analyses" / before["analysis"] / "labels.jsonl"
|
||||
if not f.exists():
|
||||
return
|
||||
labels = [json.loads(l) for l in f.read_text(encoding="utf-8").split("\n") if l.strip()]
|
||||
for i, e in enumerate(labels):
|
||||
if core(e) == core(before):
|
||||
labels[i:i + 1] = [] if label is None else [{k: label[k] for k in (*CORE, "review") if k in label}]
|
||||
write(f, labels)
|
||||
return
|
||||
@@ -0,0 +1,45 @@
|
||||
"""The Suggestions page: the support agent's suggestions (~/aimsight-support), read-only from the Supabase project
|
||||
Conversations (table suggestions, bucket suggestions): per customer message, its status, the reason it was left to a
|
||||
person, or the draft reply and its figures to paste into the mail. The person sends it from LibreDesk; nothing is sent
|
||||
from here. SUPABASE_CONVERSATIONS_URL and SUPABASE_CONVERSATIONS_KEY come from the app's environment (.env through the
|
||||
service's EnvironmentFile); standard library only.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
import station
|
||||
|
||||
FIGURE = re.compile(r"^\d+/\d+\.png$") # <suggestion id>/<n>.png, as the agent writes them
|
||||
MISSING = "no SUPABASE_CONVERSATIONS_URL / SUPABASE_CONVERSATIONS_KEY in the app's environment (README)"
|
||||
|
||||
|
||||
def _get(path: str) -> bytes:
|
||||
url, key = os.environ.get("SUPABASE_CONVERSATIONS_URL"), os.environ.get("SUPABASE_CONVERSATIONS_KEY")
|
||||
if not url or not key:
|
||||
raise station.Refusal(MISSING)
|
||||
r = urllib.request.Request(url.rstrip("/") + path, headers={"apikey": key})
|
||||
if key.startswith("eyJ"): # an old JWT key; a new sb_secret_ key goes only in apikey
|
||||
r.add_header("Authorization", f"Bearer {key}")
|
||||
with urllib.request.urlopen(r, timeout=30) as answer:
|
||||
return answer.read()
|
||||
|
||||
|
||||
def list_suggestions() -> list[dict]:
|
||||
"""The latest 200 suggestions, newest first, each with its conversation's reference and subject."""
|
||||
if not os.environ.get("SUPABASE_CONVERSATIONS_URL") or not os.environ.get("SUPABASE_CONVERSATIONS_KEY"):
|
||||
raise station.Refusal(MISSING)
|
||||
rows = json.loads(_get("/rest/v1/suggestions?select=*&order=created_at.desc&limit=200"))
|
||||
uuids = ",".join(sorted({r["conversation_uuid"] for r in rows}))
|
||||
convs = {c["uuid"]: c for c in json.loads(_get(
|
||||
f"/rest/v1/conversations?select=uuid,reference_number,subject&uuid=in.({urllib.parse.quote(uuids)})"))} if rows else {}
|
||||
return [r | {"reference": convs.get(r["conversation_uuid"], {}).get("reference_number", ""),
|
||||
"subject": convs.get(r["conversation_uuid"], {}).get("subject", "")} for r in rows]
|
||||
|
||||
|
||||
def figure(path: str) -> bytes:
|
||||
if not FIGURE.match(path):
|
||||
raise station.Refusal(f"not a suggestion figure: {path}")
|
||||
return _get(f"/storage/v1/object/suggestions/{path}")
|
||||
@@ -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.pumped(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)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""The Points page: the point labels of labeling/points/, one boolean per measurement (valid or not) on a range, set by
|
||||
the user. Their format, their files and their check are labeling/scripts/points.py; the measurements are read by
|
||||
tools/scripts/data.py, as everywhere. A station of data/ or a run of the emulator (<SERIAL>@<run>), each its own points.
|
||||
"""
|
||||
import threading
|
||||
|
||||
import station
|
||||
from station import Refusal, data
|
||||
|
||||
import points # noqa: E402 (labeling/scripts, on the path through station)
|
||||
|
||||
|
||||
def refused(f):
|
||||
def wrapped(*a):
|
||||
try:
|
||||
return f(*a)
|
||||
except (ValueError, FileNotFoundError) as e:
|
||||
raise Refusal(str(e)) from e
|
||||
return wrapped
|
||||
|
||||
|
||||
def summary(n):
|
||||
p = points.read(n)
|
||||
s, start, end = points.parts(n)
|
||||
return {"name": n, "station": s, "start": start, "end": end, "points": len(p), "invalid": sum(not v for v in p.values())}
|
||||
|
||||
|
||||
@refused
|
||||
def listing(st=""):
|
||||
return [summary(n) for n in points.datasets(st or None)]
|
||||
|
||||
|
||||
def measured(st, a, b):
|
||||
"""-> {sensor: [t]}: the points of [a, b), every measurement with a relative position, the rejected ones included
|
||||
(labeling/scripts/points.py)."""
|
||||
return {s: [m["t"] for m in ms if a <= m["t"] < b and m["relative_x"] is not None and m["relative_y"] is not None]
|
||||
for s, ms in data.load(station.folder(st)).items()}
|
||||
|
||||
|
||||
@refused
|
||||
def create(body):
|
||||
st, start, end = body.get("station", ""), body.get("start", ""), body.get("end", "")
|
||||
n = points.name(st, start, end)
|
||||
points.create(n, measured(st, *station.bounds(start, end)))
|
||||
return summary(n)
|
||||
|
||||
|
||||
# the plots of the page, in their order: rx, ry, the recognition error and its threshold, the image quality
|
||||
COLUMNS = ("relative_x", "relative_y", "error_value", "error_threshold", "peak", "flux", "sharpness", "fwhm", "dominance", "snr")
|
||||
|
||||
|
||||
@refused
|
||||
def dataset(n):
|
||||
"""-> {name, station, start, end, sensors: {sensor: {t, valid, columns: {column: [value]}}}}: the COLUMNS of each
|
||||
point, None where the data no longer have it (a pumping or a run again); a column empty for the sensor left out."""
|
||||
p, st = points.read(n), points.parts(n)[0]
|
||||
now = {(s, points.time(m["t"])): m for s, ms in data.load(station.folder(st)).items() for m in ms}
|
||||
out = {}
|
||||
for (s, t), v in sorted(p.items()):
|
||||
m, o = now.get((s, t), {}), out.setdefault(s, {"t": [], "valid": [], "columns": {c: [] for c in COLUMNS}})
|
||||
o["t"].append(t[:19].replace("T", " ")) # as Plotly shows it, UTC
|
||||
o["valid"].append(v)
|
||||
for c in COLUMNS:
|
||||
o["columns"][c].append(m.get(c))
|
||||
for o in out.values():
|
||||
o["columns"] = {c: vs for c, vs in o["columns"].items() if any(x is not None for x in vs)}
|
||||
return {**summary(n), "sensors": out}
|
||||
|
||||
|
||||
LOCK = threading.Lock() # the requests run in threads: two marks never read and write the file at the same time
|
||||
|
||||
|
||||
@refused
|
||||
def mark(n, body):
|
||||
"""{sensor, times (as the page shows them), valid} -> the summary."""
|
||||
times = [t.replace(" ", "T") + "Z" for t in body.get("times", [])]
|
||||
with LOCK:
|
||||
points.mark(n, body.get("sensor", ""), times, bool(body.get("valid")))
|
||||
return summary(n)
|
||||
+40
-17
@@ -3,10 +3,14 @@ import {
|
||||
ActionIcon, AppShell, Burger, ColorSwatch, Group, Loader, NavLink, ScrollArea, Text, Tooltip, useComputedColorScheme, useMantineColorScheme,
|
||||
} from "@mantine/core";
|
||||
import { useDisclosure } from "@mantine/hooks";
|
||||
import { IconChartLine, IconFolder, IconMoon, IconSun } from "@tabler/icons-react";
|
||||
import { IconChartLine, IconCircleCheck, IconCircleDashed, IconFolder, IconMessages, IconMailForward, IconMoon, IconPointFilled, IconSatellite, IconSun } from "@tabler/icons-react";
|
||||
|
||||
const Data = lazy(() => import("./pages/Data.jsx")); // Plotly, loaded only here
|
||||
const PAGES = [["data", "Data", IconChartLine]];
|
||||
const Stations = lazy(() => import("./pages/Stations.jsx"));
|
||||
const Conversations = lazy(() => import("./pages/Conversations.jsx"));
|
||||
const Points = lazy(() => import("./pages/Points.jsx"));
|
||||
const Suggestions = lazy(() => import("./pages/Suggestions.jsx"));
|
||||
const PAGES = [["data", "Data", IconChartLine], ["points", "Points", IconPointFilled], ["stations", "Stations", IconSatellite], ["conversations", "Conversations", IconMessages], ["suggestions", "Suggestions", IconMailForward]];
|
||||
|
||||
// The address: #/<page>?station=…&start=…&end=…; reloading keeps the page and the selection, Back works; without dates, the
|
||||
// last 5 UTC days, today included (end excluded: tomorrow)
|
||||
@@ -48,19 +52,22 @@ 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
|
||||
// it has one running, and inside one analysis per range; a click opens Data on its station and its days, and shows its report there
|
||||
// The range of an analysis on one line: "01.11 · 10:30–11:40" within the day, otherwise "04.11 21:12 – 07.11 14:12" (UTC)
|
||||
// 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. 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),
|
||||
// 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 range = a => (a.start.slice(0, 10) === a.end.slice(0, 10)
|
||||
? `${dayMonth(a.start)} · ${hour(a.start)}–${hour(a.end)}` : `${dayMonth(a.start)} ${hour(a.start)} – ${dayMonth(a.end)} ${hour(a.end)}`);
|
||||
const days = a => (a.start.slice(0, 10) === a.end.slice(0, 10) ? dayMonth(a.start) : `${dayMonth(a.start)} – ${dayMonth(a.end)}`);
|
||||
const hours = a => `${hour(a.start)} – ${hour(a.end)}`;
|
||||
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)
|
||||
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>);
|
||||
function Analyses({ open }) {
|
||||
const [list, setList] = useState([]);
|
||||
function Analyses({ kind = "analyses", open }) {
|
||||
const [list, setList] = useState([]), labels = kind === "analyses";
|
||||
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();
|
||||
const timer = setInterval(read, 3000);
|
||||
return () => clearInterval(timer);
|
||||
@@ -68,16 +75,21 @@ function Analyses({ open }) {
|
||||
if (!list.length) return null;
|
||||
const stations = [...new Set(list.map(a => a.station))].sort();
|
||||
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 => {
|
||||
const its = list.filter(a => a.station === st), busy = its.some(a => a.state === "running");
|
||||
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
|
||||
return (
|
||||
<NavLink key={st} defaultOpened={busy} childrenOffset={22} leftSection={<IconFolder size={16} />}
|
||||
label={<Group gap={6} wrap="nowrap">{st}<Text span size="xs" c="dimmed">{its.length}</Text>{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 => (
|
||||
<NavLink key={a.name} py={4} onClick={() => open(a)} leftSection={<Dot state={a.state} />}
|
||||
label={<Text size="xs" ff="monospace" style={{ whiteSpace: "nowrap" }}>{range(a)}</Text>} />
|
||||
rightSection={labels && (a.validated ? <Tooltip label={`labels validated ${a.validated}`}>
|
||||
<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>)}
|
||||
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>} />
|
||||
))}
|
||||
</NavLink>
|
||||
);
|
||||
@@ -96,6 +108,7 @@ function Sidebar({ page, selection, close, open }) {
|
||||
href={address(n, selection)} />
|
||||
))}
|
||||
<Analyses open={a => { close(); open(a); }} />
|
||||
<Analyses kind="support" open={a => { close(); open(a, "support"); }} />
|
||||
</ScrollArea>
|
||||
</AppShell.Navbar>
|
||||
);
|
||||
@@ -106,6 +119,7 @@ export default function App() {
|
||||
const [mobile, { toggle: toggleMobile, close: closeMobile }] = useDisclosure(false);
|
||||
const [desktop, { toggle: toggleDesktop }] = useDisclosure(true);
|
||||
const [analysis, setAnalysis] = useState(null); // the analysis whose report Data shows
|
||||
const [support, setSupport] = useState(null); // the support request whose answer Data shows
|
||||
|
||||
useEffect(() => {
|
||||
const follow = () => setPlace(readAddress());
|
||||
@@ -113,12 +127,14 @@ export default function App() {
|
||||
return () => removeEventListener("hashchange", follow);
|
||||
}, []);
|
||||
|
||||
const choose = s => { location.hash = address(page, s); };
|
||||
// An analysis of the sidebar: Data on its station, days that cover its range (unless the range shown already covers them)
|
||||
function openAnalysis(a) {
|
||||
// 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; };
|
||||
// An analysis (or a support request) of the sidebar: Data on its station, days that cover its range (unless the range
|
||||
// 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 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 });
|
||||
}
|
||||
return (
|
||||
@@ -127,7 +143,14 @@ export default function App() {
|
||||
<Header mobile={mobile} desktop={desktop} toggle={{ mobile: toggleMobile, desktop: toggleDesktop }} />
|
||||
<Sidebar page={page} selection={selection} close={closeMobile} open={openAnalysis} />
|
||||
<AppShell.Main bg="var(--mantine-color-default-hover)">
|
||||
<Suspense fallback={<Loader m="xl" />}><Data selection={selection} choose={choose} analysis={analysis} setAnalysis={setAnalysis} /></Suspense>
|
||||
<Suspense fallback={<Loader m="xl" />}>
|
||||
{page === "stations" ? <Stations selection={selection} />
|
||||
: page === "conversations" ? <Conversations />
|
||||
: page === "suggestions" ? <Suggestions />
|
||||
: page === "points" ? <Points selection={selection} choose={choose} />
|
||||
: <Data selection={selection} choose={choose} analysis={analysis} setAnalysis={setAnalysis}
|
||||
support={support} setSupport={setSupport} />}
|
||||
</Suspense>
|
||||
</AppShell.Main>
|
||||
</AppShell>
|
||||
);
|
||||
|
||||
+31
-9
@@ -1,12 +1,13 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Button, Card, Group, Select, TextInput } from "@mantine/core";
|
||||
import { notifications } from "@mantine/notifications";
|
||||
|
||||
// A request to the API; a refusal of the server shows as a notification -> the JSON returned, or null
|
||||
export async function call(path, method = "GET", body) {
|
||||
try {
|
||||
const r = await fetch(path, body === undefined ? { method }
|
||||
: { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
// every POST, PUT, DELETE declares JSON, even without a body: the server refuses it otherwise (its guard)
|
||||
const r = await fetch(path, method === "GET" ? { method }
|
||||
: { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body ?? {}) });
|
||||
const json = await r.json().catch(() => ({ error: r.statusText }));
|
||||
if (r.ok) return json;
|
||||
notifications.show({ color: "red", title: "Refused", message: json.error || r.statusText });
|
||||
@@ -16,16 +17,29 @@ export async function call(path, method = "GET", body) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// The station and the range (UTC, To excluded; empty: the whole period), shared by the pages through the address
|
||||
export function Selector({ selection, choose }) {
|
||||
const [stations, setStations] = useState([]), [s, setS] = useState(selection);
|
||||
// The station and the range (UTC, To excluded; empty: the whole period), shared by the pages through the address. Source:
|
||||
// Cloud, the stations of data/; Emulator, the runs of data_diff/, <SERIAL>@<run> for the server
|
||||
const SOURCES = [{ value: "cloud", label: "Cloud" }, { value: "emulator", label: "Emulator" }];
|
||||
// without a station, the page's own default (Points: the emulator, its main use)
|
||||
const sourceOf = (station, start = "cloud") => !station ? start : station.includes("@") ? "emulator" : "cloud";
|
||||
|
||||
export function Selector({ selection, choose, start = "cloud" }) {
|
||||
const [stations, setStations] = useState([]), [s, setS] = useState(selection), [source, setSource] = useState(sourceOf(selection.station, start));
|
||||
useEffect(() => { call("/api/stations").then(l => l && setStations(l)); }, []);
|
||||
useEffect(() => setS(selection), [selection.station, selection.start, selection.end]);
|
||||
useEffect(() => { setS(selection); if (selection.station) setSource(sourceOf(selection.station)); }, [selection]); // a new object at each change of the address
|
||||
const [serial, run] = (s.station || "").split("@");
|
||||
const runsOf = st => stations.filter(n => n.startsWith(st + "@")).map(n => n.split("@")[1]);
|
||||
const names = source === "cloud" ? stations.filter(n => !n.includes("@"))
|
||||
: [...new Set(stations.filter(n => n.includes("@")).map(n => n.split("@")[0]))];
|
||||
return (
|
||||
<Card shadow="sm" withBorder>
|
||||
<Group align="flex-end" gap="md">
|
||||
<Select label="Station" placeholder="Choose" data={stations} value={s.station || null} searchable w={200}
|
||||
onChange={v => setS({ ...s, station: v || "" })} />
|
||||
<Select label="Source" data={SOURCES} value={source} allowDeselect={false} w={130}
|
||||
onChange={v => { setSource(v); setS({ ...s, station: "" }); }} />
|
||||
<Select label="Station" placeholder="Choose" data={names} value={serial || null} searchable w={200}
|
||||
onChange={v => setS({ ...s, station: !v ? "" : source === "cloud" ? v : `${v}@${runsOf(v)[0]}` })} />
|
||||
{source === "emulator" && <Select label="Run" placeholder="Choose" data={serial ? runsOf(serial) : []} value={run || null}
|
||||
allowDeselect={false} w={140} onChange={v => setS({ ...s, station: `${serial}@${v}` })} />}
|
||||
<TextInput label="From (UTC)" type="date" value={s.start} onChange={e => setS({ ...s, start: e.currentTarget.value })} />
|
||||
<TextInput label="To (excluded)" type="date" value={s.end} onChange={e => setS({ ...s, end: e.currentTarget.value })} />
|
||||
<Button onClick={() => choose(s)} disabled={!s.station}>Load</Button>
|
||||
@@ -33,3 +47,11 @@ export function Selector({ selection, choose }) {
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// A markdown rendered by the server (report, summary, transcript), at the height of its content once its images are loaded;
|
||||
// sandboxed: no script runs in it (sandbox "allow-same-origin allow-downloads" where its links are attachments to save)
|
||||
export function Page({ title, src, sandbox = "allow-same-origin" }) {
|
||||
const frame = useRef();
|
||||
const fit = () => { const b = frame.current?.contentDocument?.body; if (b) frame.current.style.height = `${b.scrollHeight + 20}px`; };
|
||||
return <iframe ref={frame} title={title} sandbox={sandbox} onLoad={fit} style={{ border: 0, width: "100%", height: 400 }} src={src} />;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Button, Card, Code, Group, ScrollArea, Stack, Table, Text, TextInput, Title, useComputedColorScheme } from "@mantine/core";
|
||||
import { IconSearch } from "@tabler/icons-react";
|
||||
import { call, Page } from "../common.jsx";
|
||||
|
||||
const when = t => (t ? t.slice(0, 16).replace("T", " ") : "");
|
||||
|
||||
// The LibreDesk conversations, pumped read-only by ~/aimsight-libredesk into labeling/auto/conversations/: a pumping (a range
|
||||
// of updates, or without dates what changed since the last one), its log read every 2 s; the pumped conversations, searched
|
||||
// on subject, contact and reference; a click shows the transcript (images inline, the client's text never run)
|
||||
export default function Conversations() {
|
||||
const [range, setRange] = useState({ start: "", end: "" }), [state, setState] = useState(null);
|
||||
const [list, setList] = useState([]), [search, setSearch] = useState(""), [open, setOpen] = useState(null);
|
||||
const dark = useComputedColorScheme("light") === "dark", wasRunning = useRef(false);
|
||||
const read = () => call("/api/conversations").then(l => l && setList(l));
|
||||
useEffect(() => { read(); }, []);
|
||||
useEffect(() => {
|
||||
const poll = () => fetch("/api/conversations/pump").then(r => r.ok && r.json()).then(p => {
|
||||
if (!p) return;
|
||||
if (wasRunning.current && !p.running) read(); // a pumping ended: the list again
|
||||
wasRunning.current = p.running;
|
||||
setState(p);
|
||||
}).catch(() => {}); // silently: every 2 s
|
||||
poll();
|
||||
const timer = setInterval(poll, 2000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
const pump = () => call("/api/conversations/pump", "POST", range).then(p => { if (p) { wasRunning.current = p.running; setState(p); } });
|
||||
const q = search.trim().toLowerCase();
|
||||
const shown = list.filter(c => !q || [c.subject, c.contact, c.reference].some(x => x.toLowerCase().includes(q)));
|
||||
return (
|
||||
<Stack gap="lg" maw={1200}>
|
||||
<div>
|
||||
<Title order={2}>Conversations</Title>
|
||||
<Text c="dimmed">The LibreDesk conversations, pumped read-only into labeling/auto/conversations/: the thread, its images and
|
||||
attachments, for the support and as training data.</Text>
|
||||
</div>
|
||||
<Card shadow="sm" withBorder>
|
||||
<Stack gap="md">
|
||||
<Group align="flex-end" gap="md">
|
||||
<TextInput label="Updated from (UTC)" type="date" value={range.start} onChange={e => setRange({ ...range, start: e.currentTarget.value })} />
|
||||
<TextInput label="To (excluded)" type="date" value={range.end} onChange={e => setRange({ ...range, end: e.currentTarget.value })} />
|
||||
<Button onClick={pump} loading={!!state?.running}>Pump</Button>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">Without dates: what changed since the last pumping; the first time, the whole history (a quiet
|
||||
hour). The key stays in ~/aimsight-libredesk/.env; nothing is ever written to LibreDesk.</Text>
|
||||
{state?.log?.length > 0 && (
|
||||
<ScrollArea h={200} viewportRef={v => v && (v.scrollTop = v.scrollHeight)}>
|
||||
<Code block>{state.log.join("\n")}</Code>
|
||||
</ScrollArea>
|
||||
)}
|
||||
</Stack>
|
||||
</Card>
|
||||
<Card shadow="sm" withBorder>
|
||||
<Stack gap="md">
|
||||
<TextInput placeholder="Search: subject, contact, reference" leftSection={<IconSearch size={16} />} value={search}
|
||||
onChange={e => setSearch(e.currentTarget.value)} maw={400} />
|
||||
{list.length ? (
|
||||
<ScrollArea.Autosize mah={400}>
|
||||
<Table highlightOnHover verticalSpacing={4} stickyHeader>
|
||||
<Table.Thead><Table.Tr><Table.Th>Ref.</Table.Th><Table.Th>Subject</Table.Th><Table.Th>Contact</Table.Th>
|
||||
<Table.Th>Status</Table.Th><Table.Th>Last message (UTC)</Table.Th><Table.Th>Messages</Table.Th><Table.Th>Attachments</Table.Th></Table.Tr></Table.Thead>
|
||||
<Table.Tbody>
|
||||
{shown.map(c => (
|
||||
<Table.Tr key={c.reference} onClick={() => setOpen(c.reference)} style={{ cursor: "pointer" }}
|
||||
bg={open === c.reference ? "var(--mantine-primary-color-light)" : undefined}>
|
||||
<Table.Td ff="monospace">{c.reference}</Table.Td><Table.Td>{c.subject}</Table.Td><Table.Td>{c.contact}</Table.Td>
|
||||
<Table.Td>{c.status}</Table.Td><Table.Td ff="monospace">{when(c.last)}</Table.Td>
|
||||
<Table.Td>{c.messages}</Table.Td><Table.Td>{c.attachments}</Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</ScrollArea.Autosize>
|
||||
) : <Text c="dimmed" size="sm">No conversation pumped yet.</Text>}
|
||||
</Stack>
|
||||
</Card>
|
||||
{open && (
|
||||
<Card shadow="sm" withBorder>
|
||||
<Page key={`${open}-${dark}`} title="Transcript" sandbox="allow-same-origin allow-downloads" src={`/api/conversations/${encodeURIComponent(open)}/report.html?dark=${dark}`} />
|
||||
</Card>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
+119
-51
@@ -1,24 +1,29 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
ActionIcon, Badge, Button, Card, Checkbox, Grid, Group, Loader, NativeSelect, SegmentedControl, SimpleGrid, Stack, Switch, Text, Textarea, TextInput, Title, Tooltip,
|
||||
ActionIcon, Badge, Button, Card, Checkbox, Grid, Group, Loader, NativeSelect, SegmentedControl, SimpleGrid, Slider, Stack, Switch, Text, Textarea, TextInput, Title, Tooltip,
|
||||
useComputedColorScheme,
|
||||
} from "@mantine/core";
|
||||
import { IconPlus, IconX } from "@tabler/icons-react";
|
||||
import { call, Selector } from "../common.jsx";
|
||||
import { call, Page, Selector } from "../common.jsx";
|
||||
import { StationImages } from "./Images.jsx";
|
||||
|
||||
// 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)
|
||||
// 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.
|
||||
const FAMILIES = { "Visibility": "#8ec5e8", "Obstruction": "#f0b072", "Thermal displacement": "#f08a7e", "Displacement": "#b39ddb",
|
||||
const FAMILIES = { "Anomaly": "#e03131", "Visibility": "#8ec5e8", "Obstruction": "#f0b072", "Thermal displacement": "#f08a7e", "Displacement": "#b39ddb", "Perturbation": "#9fd8d0",
|
||||
"Target issue": "#e6d46a", "No data": "#c4c4be", "None": "#a8d5a2" };
|
||||
const FAMILY_NAME = f => (f === "None" ? "None (curves intact)" : f);
|
||||
const FAMILY_CHOICES = [{ value: "", label: "(no family)" }, ...Object.keys(FAMILIES).map(f => ({ value: f, label: FAMILY_NAME(f) }))];
|
||||
// A label of auto/ has one of the seven families (labeling/scripts/validate.py); None is the expert's, in manual/;
|
||||
// Anomaly, the detectors' alone (models/rules/manual/events.py: something happened, without saying what)
|
||||
const FAMILY_CHOICES = [{ value: "", label: "(choose a family)" },
|
||||
...Object.keys(FAMILIES).filter(f => f !== "None" && f !== "Anomaly").map(f => ({ value: f, label: f }))];
|
||||
// LLM and Analysis: the same labels, labeling/auto/; LLM reads them, Analysis edits, deletes them, and has the analyst make
|
||||
// some on a range (app/server/analysis.py)
|
||||
const SOURCES = [{ value: "detectors", label: "Detectors" }, { value: "auto", label: "LLM" }, { value: "analysis", label: "Analysis" }];
|
||||
// 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" },
|
||||
{ value: "support", label: "Support" }];
|
||||
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 readable = s => s.slice(0, 16).replace("T", " ");
|
||||
@@ -38,20 +43,24 @@ 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)
|
||||
|
||||
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 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 ("":
|
||||
// all; otherwise the detectors run again without the others)
|
||||
const [source, setSource] = useState("detectors"), [families, setFamilies] = useState(DETECTED), [targets, setTargets] = useState("");
|
||||
const [focus, setFocus] = useState(false); // with an event open, the plots show only its sensors
|
||||
const [hidden, setHidden] = useState([]); // the targets removed from the plots (the detectors still read them)
|
||||
const [set, setSet] = useState("classic"); // the detectors: classic (detectors/detectors/) or manual (models/rules/manual/)
|
||||
const [sensitivity, setSensitivity] = useState(5); // of the manual set: 1 (tolerant) to 10 (severe); 5, its limits as written
|
||||
const [cut, setCut] = useState(false); // the points under a label of the checked families removed, the curves joined
|
||||
const { station, start, end } = selection;
|
||||
useEffect(() => {
|
||||
setData(null); setTargets("");
|
||||
setData(null); setTargets(""); setHidden([]);
|
||||
if (!station) return;
|
||||
setLoading(true);
|
||||
call(`/api/curves?${new URLSearchParams({ station, start, end })}`).then(d => { setData(d); setLoading(false); });
|
||||
}, [station, start, end]);
|
||||
}, [selection]);
|
||||
// The columns slide (style.css); Plotly only follows the window: at the end of the slide, the plots refit to their
|
||||
// new width (redrawing them at every frame of the slide would be too heavy)
|
||||
const slideEnd = e => { if (e.target === left.current && e.propertyName === "max-width") dispatchEvent(new Event("resize")); };
|
||||
@@ -65,10 +74,12 @@ export default function Data({ selection, choose, analysis, setAnalysis }) {
|
||||
opens it.</Text>
|
||||
</div>
|
||||
<Selector selection={selection} choose={choose} />
|
||||
{data?.weather && <Text size="xs" c="dimmed" mt={-8}>Weather: {data.weather}.</Text>}
|
||||
{loading && <Loader />}
|
||||
{data && <TargetFilter d={data} hidden={hidden} setHidden={setHidden} />}
|
||||
{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}
|
||||
analysis={analysis} setAnalysis={setAnalysis} />}
|
||||
source={source} setSource={setSource} families={families} targets={targets} focus={focus} hidden={hidden} cut={cut} set={set} sensitivity={sensitivity}
|
||||
analysis={analysis} setAnalysis={setAnalysis} support={support} setSupport={setSupport} />}
|
||||
</Stack>
|
||||
</Grid.Col>
|
||||
<Grid.Col span={{ base: 12, lg: wide ? 7 : 4 }}>
|
||||
@@ -77,7 +88,8 @@ export default function Data({ selection, choose, analysis, setAnalysis }) {
|
||||
<StationImages selection={selection} compact wide={wide} toggle={() => setWide(!wide)} moment={moment} />
|
||||
{data && <Settings key={`${station}${start}${end}`} d={data} families={families} setFamilies={setFamilies}
|
||||
targets={targets} setTargets={setTargets} detect={source === "detectors"}
|
||||
focus={focus} setFocus={setFocus} />}
|
||||
focus={focus} setFocus={setFocus} cut={cut} setCut={setCut} set={set} setSet={setSet}
|
||||
sensitivity={sensitivity} setSensitivity={setSensitivity} />}
|
||||
</Stack>
|
||||
</div>
|
||||
</Grid.Col>
|
||||
@@ -85,9 +97,31 @@ export default function Data({ selection, choose, analysis, setAnalysis }) {
|
||||
);
|
||||
}
|
||||
|
||||
// The targets shown on the plots, at once; the others are removed from them, not from the detectors
|
||||
function TargetFilter({ d, hidden, setHidden }) {
|
||||
const sensors = Object.keys(d.T).filter(k => k && !k.startsWith("system:"));
|
||||
const refs = new Set(d.plots.flatMap(p => p.traces).filter(t => t.name.endsWith(" (ref.)")).map(t => t.t));
|
||||
return (
|
||||
<Card shadow="sm" withBorder>
|
||||
<Stack gap="sm">
|
||||
<Checkbox.Group label="Targets shown on the plots" value={sensors.filter(s => !hidden.includes(s))}
|
||||
onChange={v => setHidden(sensors.filter(s => !v.includes(s)))}>
|
||||
<Group gap="md" mt={6}>
|
||||
{sensors.map(c => <Checkbox key={c} size="xs" value={c} label={c + (refs.has(c) ? " (ref.)" : "")} />)}
|
||||
</Group>
|
||||
</Checkbox.Group>
|
||||
<Group gap="sm">
|
||||
<Button size="xs" variant="default" onClick={() => setHidden(hidden.length ? [] : sensors)}>
|
||||
{hidden.length ? "Show all" : "Hide all"}</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// The families apply at once (filter of the page, Detectors and LLM); the targets, with the button: each set of targets
|
||||
// runs the detectors again (the LLM labels do not state their sensors: they do not filter them)
|
||||
function Settings({ d, families, setFamilies, targets, setTargets, detect, focus, setFocus }) {
|
||||
function Settings({ d, families, setFamilies, targets, setTargets, detect, focus, setFocus, cut, setCut, set, setSet, sensitivity, setSensitivity }) {
|
||||
const sensors = Object.keys(d.T).filter(k => k && !k.startsWith("system:"));
|
||||
const refs = new Set(d.plots.flatMap(p => p.traces).filter(t => t.name.endsWith(" (ref.)")).map(t => t.t));
|
||||
const [checked, setChecked] = useState(targets ? targets.split(",") : sensors);
|
||||
@@ -96,8 +130,22 @@ function Settings({ d, families, setFamilies, targets, setTargets, detect, focus
|
||||
<Card shadow="sm" withBorder>
|
||||
<Stack gap="sm">
|
||||
<Title order={5}>Diagnostic settings</Title>
|
||||
<div>
|
||||
<Text size="sm" fw={500}>Detectors</Text>
|
||||
<SegmentedControl size="xs" mt={4} value={set} onChange={setSet}
|
||||
data={[{ value: "classic", label: "Classic" }, { value: "manual", label: "Manual (models/rules/manual/)" }]} />
|
||||
</div>
|
||||
{set === "manual" && <div>
|
||||
<Text size="sm" fw={500}>Sensitivity: {sensitivity}</Text>
|
||||
<Text size="xs" c="dimmed">1 tolerant, 10 severe: the limits of the manual detectors halved every 2 steps (5: as written)</Text>
|
||||
{/* key: the slider starts again from the value kept when the set is chosen again; onChangeEnd: the detectors run on release */}
|
||||
<Slider key={set} mt={6} mb={18} min={1} max={10} step={1} defaultValue={sensitivity} onChangeEnd={setSensitivity}
|
||||
marks={[1, 5, 10].map(v => ({ value: v, label: String(v) }))} />
|
||||
</div>}
|
||||
<Switch label="Focus on event curves" description="With an event open, the plots show only its sensors"
|
||||
checked={focus} onChange={e => setFocus(e.currentTarget.checked)} />
|
||||
<Switch label="Remove labeled points" description="The points under a label of the families shown leave the plots; the curves join over the holes"
|
||||
checked={cut} onChange={e => setCut(e.currentTarget.checked)} />
|
||||
<Checkbox.Group label="Families shown" value={families} onChange={setFamilies}>
|
||||
<SimpleGrid cols={2} spacing={6} verticalSpacing={6} mt={6}>
|
||||
{DETECTED.map(f => <Checkbox key={f} size="xs" value={f} label={f} color={FAMILIES[f]} iconColor="#1a1b1e" />)}
|
||||
@@ -130,8 +178,9 @@ const Field = ({ name, children }) => (
|
||||
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));
|
||||
|
||||
// analysis: the folder of the analysis shown, held by App (the sidebar opens one)
|
||||
function Curves({ selection: { station, start, end }, d, setImage, source, setSource, families, targets, focus, analysis, setAnalysis }) {
|
||||
// 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, cut, set, sensitivity, analysis, setAnalysis,
|
||||
support, setSupport }) {
|
||||
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 [Plotly, setPlotly] = useState(null), [ready, setReady] = useState(false);
|
||||
@@ -144,13 +193,14 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
|
||||
const labels = useMemo(() => allLabels.filter(x => x.start < B && x.end > A
|
||||
&& (!DETECTED.includes(x.family) || families.includes(x.family))), [allLabels, families]);
|
||||
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
|
||||
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
|
||||
const names = useMemo(() => Object.keys(T).filter(k => k && !k.startsWith("system:")), [T]);
|
||||
const kept = focus && opened ? sensorsOf(opened, names) : [], shown = kept.join(",");
|
||||
current.current = { views, labels, choice, opened, open, kept: new Set(kept), shown, c: THEMES[dark ? "dark" : "light"] }; // what the Plotly events read
|
||||
current.current = { views, labels, choice, opened, open, kept: new Set(kept), shown, hidden: new Set(hidden), cut, c: THEMES[dark ? "dark" : "light"] }; // what the Plotly events read
|
||||
|
||||
useEffect(() => { import("plotly.js-dist-min").then(m => setPlotly(() => m.default)); }, []);
|
||||
|
||||
@@ -213,12 +263,21 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
|
||||
return { visible: kept.has(t.t) ? true : "legendonly", uirevision: shown };
|
||||
}
|
||||
|
||||
// The points of a trace, without those under a label of the checked families when cut (no family or None: kept)
|
||||
function points(t) {
|
||||
const { cut, labels } = current.current, x = T[t.t];
|
||||
const under = cut ? labels.filter(l => DETECTED.includes(l.family)).map(l => [readable(l.start), readable(l.end)]) : [];
|
||||
if (!under.length) return { x, y: t.y };
|
||||
const keep = x.map(v => !under.some(([a, b]) => a <= v && v < b));
|
||||
return { x: x.filter((_, i) => keep[i]), y: t.y.filter((_, i) => keep[i]) };
|
||||
}
|
||||
|
||||
function drawFig(g, m) {
|
||||
const p = PLOTS[m], { c } = current.current, b = bar.current?._fullLayout;
|
||||
const p = PLOTS[m], { c, hidden } = current.current, b = bar.current?._fullLayout;
|
||||
g.style.height = `${HEIGHT}px`; // responsive: Plotly takes the height of the div again at each restyle, it needs one
|
||||
// uirevision: the zoom and the hidden sensors stay when the plot changes; the y axis, specific to each plot, refits.
|
||||
// A new plot takes the range already shown. t: the room for the plot menu (left) and the toolbar (right).
|
||||
return Plotly.react(g, p.traces.map(t => ({ type: "scatter", mode: t.mode || "lines", marker: { size: 4 }, x: T[t.t], y: t.y, name: t.name,
|
||||
return Plotly.react(g, p.traces.filter(t => !hidden.has(t.t)).map(t => ({ type: "scatter", mode: t.mode || "lines", marker: { size: 4 }, ...points(t), name: t.name,
|
||||
uid: t.name.replace(/\W/g, "_"), line: t.line, ...focusTrace(t),
|
||||
hovertemplate: `${t.name}: %{y}<br>%{x|%Y-%m-%d %H:%M} UTC<extra></extra>` })),
|
||||
{ ...skin(c), height: HEIGHT, hovermode: "closest", margin: { ...margin(), t: 42, b: 36 }, uirevision: 1, shapes: zones(),
|
||||
@@ -263,7 +322,7 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
|
||||
? l.references.map(s => s + " (ref.)").join(", ") : "All sensors")
|
||||
: (l.family ? `<b>${FAMILY_NAME(l.family)}</b><br>` : "") + wrap(l.description))),
|
||||
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)) },
|
||||
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 },
|
||||
@@ -296,10 +355,10 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
|
||||
|
||||
useEffect(() => { if (ready) drawPlots().then(() => align(bar.current)); }, [views]);
|
||||
useEffect(() => { if (ready) drawBar(); }, [ready, labels]);
|
||||
// Drag on the bar: select a range (Analysis), otherwise zoom in time
|
||||
useEffect(() => { if (ready) Plotly.relayout(bar.current, { dragmode: readOnly ? "zoom" : "select", selections: [] }); }, [ready, readOnly]);
|
||||
// Drag on the bar: select a range (Analysis, Support), otherwise zoom in time
|
||||
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); }, [shown]);
|
||||
useEffect(() => { if (ready) drawPlots(true); }, [shown, hidden, cut, cut && labels]);
|
||||
useEffect(() => { if (ready) plotDivs().forEach(g => Plotly.relayout(g, { shapes: zones() })); }, [ready, labels, choice, opened]);
|
||||
useEffect(() => {
|
||||
if (!ready || !bar.current._fullLayout) return;
|
||||
@@ -312,14 +371,14 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
setReading(true);
|
||||
const url = source === "detectors" ? `/api/detectors?${new URLSearchParams({ station, start, end, targets })}`
|
||||
const url = source === "detectors" ? `/api/detectors?${new URLSearchParams({ station, start, end, targets, set, ...(set === "manual" && { sensitivity }) })}`
|
||||
: `/api/labels?${new URLSearchParams({ station, folder })}`;
|
||||
call(url).then(l => {
|
||||
if (!alive) return; // another source was chosen in the meantime
|
||||
setReading(false); setAllLabels(l || []);
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [source, targets, rev]);
|
||||
}, [source, targets, set, sensitivity, rev]);
|
||||
|
||||
// One more plot: the first one the page does not show yet, vertical displacement first
|
||||
function addPlot() {
|
||||
@@ -346,10 +405,12 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
|
||||
return true;
|
||||
}
|
||||
|
||||
// The analyst on the range (Analysis, hints optional), or the support (Support, a question)
|
||||
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
|
||||
setAnalysis(r.name); setHints("");
|
||||
(asking ? setSupport : setAnalysis)(r.name); setHints("");
|
||||
await Plotly.relayout(bar.current, { selections: [] });
|
||||
setChoice(null);
|
||||
}
|
||||
@@ -451,13 +512,18 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
{!readOnly && <>
|
||||
<Text size="sm">{choice ? `${readable(choice[0])} → ${readable(choice[1])} UTC` : "Drag on the label bar to select the range to analyze."}</Text>
|
||||
<Textarea autosize minRows={2} placeholder="Hints for the analyst (optional): what you saw, what to look at"
|
||||
value={hints} onChange={e => setHints(e.currentTarget.value)} />
|
||||
<Group><Button onClick={runAnalysis} disabled={!(choice && choice[0] < choice[1])}>Analyze the range</Button></Group>
|
||||
{select && <>
|
||||
<Text size="sm">{choice ? `${readable(choice[0])} → ${readable(choice[1])} UTC`
|
||||
: `Drag on the label bar to select the range ${asking ? "of your question" : "to analyze"}.`}</Text>
|
||||
<Textarea autosize minRows={2} value={hints} onChange={e => setHints(e.currentTarget.value)}
|
||||
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)} />}
|
||||
{support && <Analysis kind="support" key={`support/${support}`} name={support} dark={dark} done={() => setRev(r => r + 1)}
|
||||
close={() => setSupport(null)} />}
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
@@ -477,26 +543,21 @@ function Thread({ lines }) {
|
||||
);
|
||||
}
|
||||
|
||||
// A markdown rendered by the server (report, summary), at the height of its content once its images are loaded
|
||||
function Page({ title, src }) {
|
||||
const frame = useRef();
|
||||
const fit = () => { const b = frame.current?.contentDocument?.body; if (b) frame.current.style.height = `${b.scrollHeight + 20}px`; };
|
||||
return <iframe ref={frame} title={title} sandbox="allow-same-origin" onLoad={fit} style={{ border: 0, width: "100%", height: 400 }} src={src} />;
|
||||
}
|
||||
|
||||
const STATE_COLOR = { running: "blue", done: "teal", error: "red", interrupted: "orange" };
|
||||
|
||||
// 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
|
||||
// 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
|
||||
function Analysis({ name, dark, done, close }) {
|
||||
// its summaries under the report. kind "support": a request of the Support tab, the same without labels: its question,
|
||||
// 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 box = useRef(), loaded = !!a;
|
||||
useEffect(() => { if (loaded) box.current?.scrollIntoView({ behavior: "smooth", block: "start" }); }, [name, loaded]); // opened: it is in view
|
||||
useEffect(() => {
|
||||
let alive = true, timer;
|
||||
const read = () => call(`/api/analyses/${name}`).then(r => {
|
||||
const read = () => call(`/api/${kind}/${name}`).then(r => {
|
||||
if (!alive || !r) return;
|
||||
setA(r);
|
||||
if (r.state === "running" || r.optimization?.state === "running") timer = setTimeout(read, 3000);
|
||||
@@ -506,39 +567,46 @@ function Analysis({ name, dark, done, close }) {
|
||||
return () => { alive = false; clearTimeout(timer); };
|
||||
}, [name, turn]);
|
||||
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);
|
||||
}
|
||||
async function optimize() {
|
||||
if (await call(`/api/analyses/${name}/optimize`, "POST") != null) setTurn(t => t + 1);
|
||||
}
|
||||
async function validate() {
|
||||
if (await call(`/api/analyses/${name}/validate`, "POST") != null) { setTurn(t => t + 1); done(); }
|
||||
}
|
||||
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);
|
||||
return (
|
||||
<Card withBorder ref={box}>
|
||||
<Stack gap="xs">
|
||||
<Group justify="space-between">
|
||||
<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>
|
||||
{busy && <Loader size="xs" />}
|
||||
</Group>
|
||||
<Group gap="xs">
|
||||
{a.state === "done" && <Tooltip label="Improve the detectors (Optimizer), then the reading tools (tool-builder), from this analysis">
|
||||
{!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">
|
||||
<Button size="xs" color="green" variant="light" onClick={validate} disabled={optimizing}>Validate labels</Button></Tooltip>}
|
||||
{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>}
|
||||
<ActionIcon variant="subtle" color="gray" aria-label="Close the report" onClick={close}><IconX size={16} /></ActionIcon>
|
||||
</Group>
|
||||
</Group>
|
||||
{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
|
||||
? " 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, to review.</Text>}
|
||||
{a.report && <Page title="Report" src={`/api/analyses/${name}/report.html?dark=${dark}&v=${a.report}`} />}
|
||||
{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/${kind}/${name}/report.html?dark=${dark}&v=${a.report}`} />}
|
||||
<Thread lines={a.lines} />
|
||||
{a.dialogue && (
|
||||
<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)} />
|
||||
<Button onClick={send} disabled={busy || optimizing || !text.trim()}>Send</Button>
|
||||
</Group>
|
||||
@@ -553,10 +621,10 @@ function Analysis({ name, dark, done, close }) {
|
||||
{o.state === "interrupted" && <Text size="sm" c="orange">Stopped with the server; rerun it with the button.</Text>}
|
||||
<Thread lines={o.lines} />
|
||||
{o.summary && <Page title="Summary" src={`/api/analyses/${name}/summary.html?dark=${dark}&v=${o.summary}`} />}
|
||||
{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 models/rules/bench/score.py data/{d.station} --labels labeling/auto/{d.station}.jsonl --from {d.start.slice(0, 10)} --to {end}</Text>}
|
||||
</Stack>
|
||||
)}
|
||||
<Text size="xs" c="dimmed">labeling/auto/analyses/{name}/</Text>
|
||||
<Text size="xs" c="dimmed">labeling/auto/{kind}/{name}/</Text>
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -70,7 +70,7 @@ function Viewer({ station, d, compact, wide, toggle, moment }) {
|
||||
<Group gap="lg" justify="space-between">
|
||||
<Text ref={r.time} ff="monospace" size="sm" />
|
||||
<Group gap="md">
|
||||
<label className="check"><input type="checkbox" ref={r.names} disabled={!withPositions} /> Names</label>
|
||||
<label className="check"><input type="checkbox" ref={r.names} disabled={!withPositions} defaultChecked={withPositions} /> Names</label>
|
||||
{withPositions
|
||||
? <span className="legend"><span className="target">○ Target</span> <span className="ref">◌ Reference</span></span>
|
||||
: <Text size="sm" c="dimmed">x, y are not positions in the image on this station</Text>}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Badge, Button, Card, Group, Loader, SegmentedControl, Select, Stack, Text, Title, useComputedColorScheme } from "@mantine/core";
|
||||
import { call, Selector } from "../common.jsx";
|
||||
|
||||
// Points: the point labels (labeling/points/, labeling/scripts/points.py), one boolean per measurement of a range, valid or
|
||||
// not, set by hand: the ground truth of the benchmarks. Mainly on the runs of the emulator: the page starts on that source. A dataset per station and range, created with every point valid;
|
||||
// one target at a time, its rx, ry, error value and image quality stacked on the same time; a click on a point of any plot
|
||||
// switches it, a box sets every point inside it (mode).
|
||||
// Each change is saved at once.
|
||||
const VALID = "#2f9e44", INVALID = "#e03131";
|
||||
const FONT = "Roboto, sans-serif";
|
||||
|
||||
export default function Points({ selection, choose }) {
|
||||
const { station, start, end } = selection, name = `${station}_${start}_${end}`;
|
||||
const [list, setList] = useState([]), [d, setD] = useState(null), [loading, setLoading] = useState(false);
|
||||
const [sensor, setSensor] = useState(null), [mode, setMode] = useState("invalid");
|
||||
const refresh = () => station ? call(`/api/points?${new URLSearchParams({ station })}`).then(l => l && setList(l)) : setList([]);
|
||||
const exists = list.some(x => x.name === name);
|
||||
useEffect(() => { refresh(); }, [station]);
|
||||
useEffect(() => {
|
||||
setD(null);
|
||||
if (!exists) return;
|
||||
setLoading(true);
|
||||
call(`/api/points/${name}`).then(r => { setLoading(false); if (r) { setD(r); setSensor(s => (s in r.sensors ? s : Object.keys(r.sensors)[0])); } });
|
||||
}, [name, exists]);
|
||||
const create = () => { setLoading(true); call("/api/points", "POST", { station, start, end }).then(r => { setLoading(false); r && refresh(); }); };
|
||||
// set the points (indices of the target's series) valid or not: at once on the page, then in the file; a refusal reloads
|
||||
function set(indices, valid) {
|
||||
const o = d.sensors[sensor], times = indices.filter(i => o.valid[i] !== valid).map(i => o.t[i]);
|
||||
if (!times.length) return;
|
||||
const v = o.valid.slice();
|
||||
indices.forEach(i => { v[i] = valid; });
|
||||
setD({ ...d, invalid: d.invalid + (valid ? -times.length : times.length), sensors: { ...d.sensors, [sensor]: { ...o, valid: v } } });
|
||||
call(`/api/points/${name}`, "PUT", { sensor, times, valid }).then(r => {
|
||||
if (r) setList(l => l.map(x => (x.name === name ? r : x)));
|
||||
else call(`/api/points/${name}`).then(r2 => r2 && setD(r2));
|
||||
});
|
||||
}
|
||||
const invalidOf = s => d.sensors[s].valid.filter(v => !v).length;
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<div>
|
||||
<Title order={2}>Points</Title>
|
||||
<Text c="dimmed">Each measurement of a range, valid or not, set by hand: the ground truth of the benchmarks
|
||||
(labeling/points/). A click on a point switches it; a box sets every point inside it.</Text>
|
||||
</div>
|
||||
<Selector selection={selection} choose={choose} start="emulator" />
|
||||
{list.length > 0 && <Group gap="xs">
|
||||
<Text size="sm" c="dimmed">Datasets of {station}:</Text>
|
||||
{list.map(x => <Button key={x.name} size="compact-sm" variant={x.name === name ? "filled" : "light"}
|
||||
onClick={() => choose({ station, start: x.start, end: x.end })}>
|
||||
{x.start} – {x.end} · {x.invalid}/{x.points} invalid</Button>)}
|
||||
</Group>}
|
||||
{loading && <Loader />}
|
||||
{station && !exists && !loading && <Card withBorder>
|
||||
<Group justify="space-between">
|
||||
<Text>No dataset for {station} from {start} to {end} (excluded).</Text>
|
||||
<Button onClick={create} disabled={!start || !end}>Create the dataset (every point valid)</Button>
|
||||
</Group>
|
||||
</Card>}
|
||||
{d && <Card withBorder>
|
||||
<Stack>
|
||||
<Group align="flex-end">
|
||||
<Select label="Target" w={260} searchable allowDeselect={false} value={sensor} onChange={setSensor}
|
||||
data={Object.keys(d.sensors).map(s => ({ value: s, label: `${s}${invalidOf(s) ? ` · ${invalidOf(s)} invalid` : ""}` }))} />
|
||||
<div>
|
||||
<Text size="sm" fw={500} mb={4}>A box sets the points</Text>
|
||||
<SegmentedControl value={mode} onChange={setMode} data={[{ value: "invalid", label: "Invalid" }, { value: "valid", label: "Valid" }]} />
|
||||
</div>
|
||||
<Badge size="lg" variant="light" color="red">{d.invalid} invalid of {d.points}</Badge>
|
||||
</Group>
|
||||
{sensor && <Plot o={d.sensors[sensor]} sensor={sensor} set={set} mode={mode} />}
|
||||
</Stack>
|
||||
</Card>}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
// The plots, top to bottom, those the sensor has (validity.COLUMNS): [column, title, unit of the tooltip]; the threshold
|
||||
// of the error drawn dashed on its plot
|
||||
const PANELS = [["relative_x", "rx [px]", " px"], ["relative_y", "ry [px]", " px"], ["error_value", "Error value", ""],
|
||||
["peak", "Peak", ""], ["flux", "Flux", ""], ["sharpness", "Sharpness", ""], ["fwhm", "FWHM [px]", " px"],
|
||||
["dominance", "Dominance", ""], ["snr", "SNR", ""]];
|
||||
const ROW = 340, GAP = 0.006; // px per plot; space between plots (fraction of the height)
|
||||
|
||||
// the points green valid, red invalid, the same point at the same index on every plot
|
||||
function Plot({ o, sensor, set, mode }) {
|
||||
const g = useRef(), [Plotly, setPlotly] = useState(null), dark = useComputedColorScheme("light") === "dark";
|
||||
const latest = useRef();
|
||||
latest.current = { o, set, mode };
|
||||
useEffect(() => { import("plotly.js-dist-min").then(m => setPlotly(() => m.default)); }, []);
|
||||
useEffect(() => {
|
||||
if (!Plotly) return;
|
||||
const color = o.valid.map(v => (v ? VALID : INVALID)), text = dark ? "#c9c9c9" : "#495057", grid = dark ? "#2e2e2e" : "#eef0f2";
|
||||
const panels = PANELS.filter(([c]) => o.columns[c]), n = panels.length, h = (1 - GAP * (n - 1)) / n;
|
||||
const axis = { gridcolor: grid, zeroline: false }, layout = {}, traces = [];
|
||||
panels.forEach(([c, title, unit], k) => {
|
||||
const y = k ? `y${k + 1}` : "y", top = 1 - k * (h + GAP);
|
||||
layout[k ? `yaxis${k + 1}` : "yaxis"] = { ...axis, domain: [Math.max(0, top - h), top], title: { text: title, font: { size: 11 } } };
|
||||
traces.push({ type: "scattergl", mode: "lines+markers", x: o.t, y: o.columns[c], yaxis: y, meta: "point",
|
||||
hovertemplate: `%{x}<br>${title}: %{y:.4f}${unit}<extra></extra>`, line: { width: 1, color: dark ? "#555" : "#ccc" },
|
||||
marker: { size: 5, color }, unselected: { marker: { opacity: 1 } } });
|
||||
if (c === "error_value" && o.columns.error_threshold)
|
||||
traces.push({ type: "scattergl", mode: "lines", x: o.t, y: o.columns.error_threshold, yaxis: y, meta: "threshold", hoverinfo: "skip",
|
||||
line: { width: 1, dash: "dash", color: INVALID } });
|
||||
});
|
||||
Plotly.react(g.current, traces, {
|
||||
...layout, height: ROW * n + 40, margin: { l: 70, r: 20, t: 10, b: 30 }, showlegend: false, dragmode: "select", selectdirection: "any",
|
||||
uirevision: sensor, paper_bgcolor: "rgba(0,0,0,0)", plot_bgcolor: "rgba(0,0,0,0)", font: { family: FONT, size: 11, color: text },
|
||||
xaxis: { ...axis, anchor: n > 1 ? `y${n}` : "y" },
|
||||
}, { responsive: true, displaylogo: false, doubleClick: "reset", modeBarButtonsToRemove: ["lasso2d", "autoScale2d", "toggleSpikelines"] });
|
||||
if (!g.current._bound) { // once per plot: the handlers read the latest state
|
||||
g.current._bound = true;
|
||||
const ofPoints = ps => ps.filter(p => p.data.meta === "point").map(p => p.pointIndex);
|
||||
g.current.on("plotly_click", ev => { const [i] = ofPoints(ev.points); if (i !== undefined) latest.current.set([i], !latest.current.o.valid[i]); });
|
||||
g.current.on("plotly_selected", ev => {
|
||||
const is = [...new Set(ofPoints(ev?.points || []))];
|
||||
if (!is.length) return;
|
||||
latest.current.set(is, latest.current.mode === "valid");
|
||||
Plotly.relayout(g.current, { selections: [] });
|
||||
});
|
||||
}
|
||||
}, [Plotly, o, sensor, dark]);
|
||||
return <div ref={g} />;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { ActionIcon, Button, Card, Checkbox, Code, Group, ScrollArea, SegmentedControl, Stack, Table, Text, TextInput, Title } from "@mantine/core";
|
||||
import { IconPlus, IconX } from "@tabler/icons-react";
|
||||
import { call } from "../common.jsx";
|
||||
|
||||
const shift = (d, n) => (d ? new Date(Date.parse(d) + n * 864e5).toISOString().slice(0, 10) : "");
|
||||
|
||||
// The tracked stations (extraction/stations.txt of ~/aimsight-data): serial and position (for the weather of the Data page);
|
||||
// the checked ones pumped (extraction/pump.sh) over a range, or without range their missing days up to now; or their
|
||||
// differential images into data_diff/ (extraction/pump_diff.sh, its own lock: beside pump.sh). The state of the chosen
|
||||
// pumping read every 2 s. By default, every station checked, and the range of the address (From 3 days before: the history of
|
||||
// the detectors)
|
||||
export default function Stations({ selection }) {
|
||||
const [rows, setRows] = useState([]), [checked, setChecked] = useState([]);
|
||||
const [range, setRange] = useState({ start: shift(selection.start, -3), end: selection.end });
|
||||
// the choice data/diff kept for the tab: back on the page, the pumping left is shown again (it never stops with the page)
|
||||
const [images, setImages] = useState(true), [diff, setDiffState] = useState(() => sessionStorage.getItem("pumpDiff") === "1");
|
||||
const setDiff = d => { sessionStorage.setItem("pumpDiff", d ? "1" : ""); setDiffState(d); };
|
||||
const [state, setState] = useState(null);
|
||||
useEffect(() => { call("/api/tracked").then(l => { if (l) { setRows(l); setChecked(l.map(r => r.serial)); } }); }, []);
|
||||
useEffect(() => {
|
||||
setState(null);
|
||||
const read = () => fetch(`/api/pump?diff=${diff}`).then(r => r.ok && r.json()).then(p => p && setState(p)).catch(() => {}); // silently
|
||||
read();
|
||||
const timer = setInterval(read, 2000);
|
||||
return () => clearInterval(timer);
|
||||
}, [diff]);
|
||||
const running = !!state?.running;
|
||||
const set = (i, k, v) => setRows(rows.map((r, n) => (n === i ? { ...r, [k]: v } : r)));
|
||||
const save = () => call("/api/tracked", "PUT", { stations: rows.filter(r => r.serial) }).then(l => l && setRows(l));
|
||||
const pump = () => call("/api/pump", "POST", { stations: checked, ...range, images, diff }).then(p => p && setState(p));
|
||||
return (
|
||||
<Stack gap="lg" maw={1000}>
|
||||
<div>
|
||||
<Title order={2}>Stations</Title>
|
||||
<Text c="dimmed">The tracked stations and their position (for the weather of the Data page); the checked ones pumped from
|
||||
the platform, read-only.</Text>
|
||||
</div>
|
||||
<Card shadow="sm" withBorder>
|
||||
<Stack gap="md">
|
||||
<Table withRowBorders={false} verticalSpacing={4}>
|
||||
<Table.Thead><Table.Tr><Table.Th w={50}>Pump</Table.Th><Table.Th>Serial</Table.Th>
|
||||
<Table.Th>Position (lat,lon or a Swiss place, for the weather; empty: an indoor site, no weather)</Table.Th><Table.Th w={40} /></Table.Tr></Table.Thead>
|
||||
<Table.Tbody>
|
||||
{rows.map((r, i) => (
|
||||
<Table.Tr key={i}>
|
||||
<Table.Td><Checkbox checked={checked.includes(r.serial)} disabled={!r.serial} aria-label={`Pump ${r.serial}`}
|
||||
onChange={e => setChecked(e.currentTarget.checked ? [...checked, r.serial] : checked.filter(c => c !== r.serial))} /></Table.Td>
|
||||
<Table.Td><TextInput size="xs" value={r.serial} onChange={e => set(i, "serial", e.currentTarget.value.trim())} /></Table.Td>
|
||||
<Table.Td><TextInput size="xs" value={r.position} placeholder="46.6895,7.7790"
|
||||
onChange={e => set(i, "position", e.currentTarget.value)} /></Table.Td>
|
||||
<Table.Td><ActionIcon variant="subtle" color="gray" aria-label="Remove" onClick={() => setRows(rows.filter((_, n) => n !== i))}>
|
||||
<IconX size={16} /></ActionIcon></Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
<Group gap="sm">
|
||||
<Button size="xs" variant="default" leftSection={<IconPlus size={14} />}
|
||||
onClick={() => setRows([...rows, { serial: "", position: "" }])}>Add a station</Button>
|
||||
<Button size="xs" onClick={save}>Save the list</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Card>
|
||||
<Card shadow="sm" withBorder>
|
||||
<Stack gap="md">
|
||||
<SegmentedControl value={diff ? "diff" : "data"} onChange={v => setDiff(v === "diff")} w="fit-content"
|
||||
data={[{ value: "data", label: "Data (data/)" }, { value: "diff", label: "Differential images (data_diff/)" }]} />
|
||||
<Group align="flex-end" gap="md">
|
||||
<TextInput label="From (UTC)" type="date" value={range.start} onChange={e => setRange({ ...range, start: e.currentTarget.value })} />
|
||||
<TextInput label="To (excluded)" type="date" value={range.end} onChange={e => setRange({ ...range, end: e.currentTarget.value })} />
|
||||
{!diff && <Checkbox label="Images" checked={images} onChange={e => setImages(e.currentTarget.checked)} mb={8} />}
|
||||
<Button onClick={pump} loading={running} disabled={!checked.length}>Pump {checked.length || ""}</Button>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">{diff
|
||||
? "The differential images, full size, with the metrics, the IRON images (one per hour) and the weather, into data_diff/<SERIAL>/; never data/ nor the runs. Without dates, from the last indexed day of each station up to now (a station never pumped is skipped: its history starts with a range). Heavy (~600 MB a day): a long range, outside busy hours."
|
||||
: "By default From is 3 days before the range of the Data page (the history of the detectors); without dates, the missing days of each station up to now. A long range, outside busy hours."}</Text>
|
||||
{state?.log?.length > 0 && (
|
||||
<ScrollArea h={320} viewportRef={v => v && (v.scrollTop = v.scrollHeight)}>
|
||||
<Code block>{state.log.join("\n")}</Code>
|
||||
</ScrollArea>
|
||||
)}
|
||||
</Stack>
|
||||
</Card>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Anchor, Badge, Button, Card, CopyButton, Group, Image, ScrollArea, SimpleGrid, Stack, Table, Text, Textarea, Title } from "@mantine/core";
|
||||
import { call } from "../common.jsx";
|
||||
|
||||
const when = t => (t ? t.slice(0, 16).replace("T", " ") : "");
|
||||
const COLORS = { ready: "green", needs_human: "orange", failed: "red", skipped: "gray" };
|
||||
|
||||
// The support agent's suggestions (~/aimsight-support), read-only from Supabase Conversations: one per customer message,
|
||||
// newest first; a click shows the draft reply (to copy into the mail in LibreDesk) and its figures (to download and paste)
|
||||
export default function Suggestions() {
|
||||
const [list, setList] = useState([]), [open, setOpen] = useState(null);
|
||||
const read = () => call("/api/suggestions").then(l => l && setList(l));
|
||||
useEffect(() => { read(); }, []);
|
||||
const s = list.find(r => r.id === open);
|
||||
return (
|
||||
<Stack gap="lg" maw={1200}>
|
||||
<div>
|
||||
<Title order={2}>Suggestions</Title>
|
||||
<Text c="dimmed">The support agent's draft replies to the customers' questions about their data. Nothing is sent from
|
||||
here: copy the reply and the figures into the mail in LibreDesk, adapt it, send it.</Text>
|
||||
</div>
|
||||
<Card shadow="sm" withBorder>
|
||||
<Stack gap="md">
|
||||
<Group><Button variant="default" onClick={read}>Refresh</Button></Group>
|
||||
{list.length ? (
|
||||
<ScrollArea.Autosize mah={400}>
|
||||
<Table highlightOnHover verticalSpacing={4} stickyHeader>
|
||||
<Table.Thead><Table.Tr><Table.Th>Ref.</Table.Th><Table.Th>Subject</Table.Th><Table.Th>Status</Table.Th>
|
||||
<Table.Th>Reason</Table.Th><Table.Th>Updated (UTC)</Table.Th></Table.Tr></Table.Thead>
|
||||
<Table.Tbody>
|
||||
{list.map(r => (
|
||||
<Table.Tr key={r.id} onClick={() => setOpen(r.id)} style={{ cursor: "pointer" }}
|
||||
bg={open === r.id ? "var(--mantine-primary-color-light)" : undefined}>
|
||||
<Table.Td ff="monospace">{r.reference}</Table.Td><Table.Td>{r.subject}</Table.Td>
|
||||
<Table.Td><Badge color={COLORS[r.status] || "blue"} variant="light">{r.status}</Badge></Table.Td>
|
||||
<Table.Td>{r.error || r.triage?.reason || ""}</Table.Td><Table.Td ff="monospace">{when(r.updated_at)}</Table.Td>
|
||||
</Table.Tr>
|
||||
))}
|
||||
</Table.Tbody>
|
||||
</Table>
|
||||
</ScrollArea.Autosize>
|
||||
) : <Text c="dimmed" size="sm">No suggestion yet.</Text>}
|
||||
</Stack>
|
||||
</Card>
|
||||
{s && (
|
||||
<Card shadow="sm" withBorder>
|
||||
<Stack gap="md">
|
||||
<Text size="sm" c="dimmed">#{s.reference} {s.subject} · station {s.triage?.station || "?"} · days {(s.triage?.range || []).join(" → ")}</Text>
|
||||
{s.reply ? (
|
||||
<>
|
||||
<Textarea value={s.reply} readOnly autosize minRows={6} />
|
||||
<Group><CopyButton value={s.reply}>{({ copied, copy }) => <Button onClick={copy}>{copied ? "Copied" : "Copy the reply"}</Button>}</CopyButton></Group>
|
||||
<SimpleGrid cols={{ base: 1, md: 2 }}>
|
||||
{s.figures.map(f => (
|
||||
<Stack key={f.path} gap={4}>
|
||||
<Image src={`/api/suggestions/figure/${f.path}`} alt={f.caption} />
|
||||
<Group justify="space-between"><Text size="xs">{f.caption}</Text>
|
||||
<Anchor size="xs" href={`/api/suggestions/figure/${f.path}`} download={f.path.replace("/", "_")}>Download</Anchor></Group>
|
||||
</Stack>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
</>
|
||||
) : <Text size="sm">{s.error || "In progress: " + s.status}</Text>}
|
||||
</Stack>
|
||||
</Card>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -113,6 +113,15 @@
|
||||
<mxPoint x="360" y="515" />
|
||||
</Array>
|
||||
</mxGeometry>
|
||||
</mxCell>
|
||||
<mxCell id="ld" value="<b style="font-size:14px">aimsight-libredesk</b><br><i>le support LibreDesk : brouillons de réponse, base de connaissances</i><br><font color="#2e7d32"><b>+</b></font> conversations/ : le pompage des conversations, en lecture seule (GET seulement)<br>• lit LibreDesk (helpdesk.sensima.ch) ; sa clé de lecture dans son .env" style="rounded=1;arcSize=4;whiteSpace=wrap;html=1;fillColor=#f8cecc;strokeColor=#b85450;fontSize=12;align=left;verticalAlign=top;spacingLeft=8;spacingRight=8;spacingTop=4;" vertex="1" parent="1">
|
||||
<mxGeometry x="1240" y="440" width="440" height="110" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dep-e13" value="lance le pompage des conversations" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;endFill=1;fontSize=11;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="app" target="ld">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
<mxCell id="dep-e14" value="écrit auto/conversations/" style="edgeStyle=orthogonalEdgeStyle;rounded=1;html=1;endArrow=block;endFill=1;fontSize=11;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="ld" target="lab">
|
||||
<mxGeometry relative="1" as="geometry" />
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
# Conversations Tab Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Pump every LibreDesk conversation, read-only, into `labeling/auto/conversations/<reference>/` (JSON, attachments, a readable transcript), launched and shown from a new **Conversations** page of the app.
|
||||
|
||||
**Architecture:** The pumping lives in `~/aimsight-libredesk/conversations/` (standard library, French, its own `.env` key, a guard test: `GET` only). The app reaches it through a new link `libredesk/` and calls `conversations/pompage.py` as `station.py` calls `extraction/pumping.py`; it lists the pumped folders and renders `transcript.md` safely (escaped, CSP, sandboxed frame, non-image attachments as downloads).
|
||||
|
||||
**Tech Stack:** Python 3 stdlib (`urllib`, `html.parser`, `unittest`) in aimsight-libredesk; FastAPI + `markdown` and React/Mantine in the app.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-18-conversations-tab-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- LibreDesk: only `GET`, only `/api/v1/conversations/all`, `/api/v1/conversations/{uuid}/messages`, and the `attachments[].url` the messages carry; never a URL found in a message's text.
|
||||
- `Authorization: token <key>:<secret>` only to the LibreDesk host (`add_unredirected_header`, host compared as in `snippets/envoyer.py`); attachments on another host (S3) downloaded without it.
|
||||
- Key: `LIBREDESK_API_KEY`, `LIBREDESK_API_SECRET` in `~/aimsight-libredesk/.env`; URL `LIBREDESK_URL`, default `https://helpdesk.sensima.ch`. Claude never reads a `.env`.
|
||||
- Every conversation: all inboxes, all statuses, private notes included, no filter.
|
||||
- `~/aimsight-libredesk`: standard library only, code/comments/commits in French. The app: English.
|
||||
- Every time in UTC. Commits by path, never `git add -A`; each message ends with a blank line then `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. Nothing pushed.
|
||||
- Nothing committed in `~/aimsight-labeling` by this plan: the user commits `auto/conversations/` after looking at the first range.
|
||||
|
||||
## Review Focus
|
||||
|
||||
- An attachment name with `/`, `..`, or an empty name → stays inside `attachments/` (sanitized, uuid fallback). Test in Task 2.
|
||||
- Two attachments with the same name in one conversation → both kept (second prefixed by its uuid). Test in Task 2.
|
||||
- A `reference_number` that is not `[A-Za-z0-9_-]+` → folder named by the conversation's `uuid`. Test in Task 2.
|
||||
- A pumping cut halfway (exception after some conversations) → `pumped.json` unchanged, the next run fetches the rest. Test in Task 2.
|
||||
- A client mail with `<script>`, an `<img src=https://…>` pixel, or an `.svg`/`.html` attachment → shown as text, not loaded, downloaded rather than rendered. Test in Task 4.
|
||||
|
||||
---
|
||||
|
||||
### Task 0: Branches
|
||||
|
||||
- [ ] **Step 1:** `cd ~/aimsight-libredesk && git switch -c feat/conversations` (from `main`; the user's uncommitted `docs/architecture.drawio` stays untouched and uncommitted).
|
||||
- [ ] **Step 2:** `cd ~/aimsight-app && git switch -c feat/conversations` (from `feat/weather-meteoswiss`, which carries the Support tab; the user's uncommitted `instructions/analyst.md` stays untouched).
|
||||
|
||||
### Task 1: The transcript (aimsight-libredesk)
|
||||
|
||||
**Files:**
|
||||
- Create: `~/aimsight-libredesk/conversations/__init__.py` (empty), `~/aimsight-libredesk/conversations/transcript.py`
|
||||
- Test: `~/aimsight-libredesk/tests/test_transcript.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `texte(contenu_html: str) -> str`; `transcript(conversation: dict, messages: list[dict]) -> str` (messages already in local form: `attachments[].url` = `attachments/<name>`, oldest first).
|
||||
|
||||
The format (exact):
|
||||
|
||||
```
|
||||
# <subject> (#<reference_number>)
|
||||
|
||||
Contact : <first_name> <last_name> <email> · Boîte : <inbox_name> · Statut : <status> · Créée : <YYYY-MM-DD HH:MM> UTC
|
||||
|
||||
## <YYYY-MM-DD HH:MM> UTC — <author first_name last_name, or "Client"/"Agent"> (client | agent | note privée)
|
||||
|
||||
<text>
|
||||
|
||||

|
||||
[<name>](attachments/<quoted name>)
|
||||
```
|
||||
|
||||
`activity` messages: one line `*<YYYY-MM-DD HH:MM> UTC — <text>*`. Role: `private` → `note privée`; else `sender_type == "contact"` → `client`; else `agent`. Image = `content_type` starting `image/` and not `image/svg+xml`. Link targets `urllib.parse.quote`d. Text: `text_content` if non-empty, else `texte(content)`.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
```python
|
||||
class TestTexte(unittest.TestCase):
|
||||
def test_paragraphes_et_entites(self):
|
||||
self.assertEqual(texte("<p>Bonjour & merci</p><p>L1<br>L2</p>"), "Bonjour\xa0& merci\n\nL1\nL2")
|
||||
def test_script_et_style_retires(self):
|
||||
self.assertEqual(texte("<style>p{}</style><script>x()</script><div>ok</div>"), "ok")
|
||||
def test_balise_echappee_reste_du_texte(self): # l'app échappe à l'affichage, pas ici
|
||||
self.assertEqual(texte("<script>"), "<script>")
|
||||
|
||||
class TestTranscript(unittest.TestCase):
|
||||
# CONV: subject "Saut", reference_number "42", contact Jean Dupont j@x.ch, inbox "Support", status "Open",
|
||||
# created_at "2026-11-18T08:00:00Z"; MESSAGES: incoming contact at 08:00 with attachments photo 1.jpg (image/jpeg)
|
||||
# and r.pdf, an activity at 08:05 "Assigned to Max", a private agent note at 08:10
|
||||
def test_entete(self):
|
||||
self.assertTrue(transcript(CONV, MESSAGES).startswith(
|
||||
"# Saut (#42)\n\nContact : Jean Dupont j@x.ch · Boîte : Support · Statut : Open · Créée : 2026-11-18 08:00 UTC\n"))
|
||||
def test_messages(self):
|
||||
t = transcript(CONV, MESSAGES)
|
||||
self.assertIn("## 2026-11-18 08:00 UTC — Jean Dupont (client)", t)
|
||||
self.assertIn("", t)
|
||||
self.assertIn("[r.pdf](attachments/r.pdf)", t)
|
||||
self.assertIn("*2026-11-18 08:05 UTC — Assigned to Max*", t)
|
||||
self.assertIn("(note privée)", t)
|
||||
def test_svg_en_lien(self): # an svg is a link, never an inline image
|
||||
self.assertNotIn("![", transcript(CONV, [msg_with_attachment("a.svg", "image/svg+xml")]))
|
||||
```
|
||||
|
||||
- [ ] **Step 2:** `cd ~/aimsight-libredesk && python3 -m unittest tests.test_transcript -v` → FAIL (`ModuleNotFoundError: conversations`).
|
||||
- [ ] **Step 3:** Implement `texte` with `html.parser.HTMLParser` (newline at `br`; blank line around `p`, `div`, `li`, `tr`, `h1`–`h6`, `blockquote`; skip `script`/`style` data; collapse 3+ newlines to 2; strip), and `transcript` per the format above. Times through `datetime.fromisoformat(...).astimezone(timezone.utc)`.
|
||||
- [ ] **Step 4:** Same command → PASS.
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add conversations/__init__.py conversations/transcript.py tests/test_transcript.py
|
||||
git commit -m "Conversations : le transcript lisible d'une conversation (texte seul, pièces jointes en lien)"
|
||||
```
|
||||
|
||||
### Task 2: The pumping (aimsight-libredesk)
|
||||
|
||||
**Files:**
|
||||
- Create: `~/aimsight-libredesk/conversations/pomper.py`
|
||||
- Modify: `~/aimsight-libredesk/tests/faux_libredesk.py` (only if a raw-bytes response needs another Content-Type; keep it backward compatible)
|
||||
- Test: `~/aimsight-libredesk/tests/test_pomper.py`, `~/aimsight-libredesk/tests/test_garde_fou_conversations.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `transcript(conversation, messages)` (Task 1).
|
||||
- Produces:
|
||||
- `class Lecteur(url: str, cle: str, secret: str)`: `conversations() -> Iterator[dict]` (pages of `/api/v1/conversations/all?page=N&page_size=100&order_by=updated_at&order=desc` until `page >= total_pages`), `messages(uuid: str) -> list[dict]` (every page of `/api/v1/conversations/{uuid}/messages?page=N&page_size=100`, then sorted by `created_at`), `telecharger(url: str, chemin: Path) -> None` (relative URL joined to `self.url`; header only if same scheme+host as `self.url`). HTTP errors raise (no `sys.exit` inside: the caller decides).
|
||||
- `pomper(lecteur: Lecteur, sortie: Path, depuis: str | None = None, jusqu_a: str | None = None, journal=print) -> int` (number of conversations written).
|
||||
- CLI: `python3 -m conversations.pomper --sortie <folder> [--depuis YYYY-MM-DD --jusqu-a YYYY-MM-DD]`, env `LIBREDESK_URL`, `LIBREDESK_API_KEY`, `LIBREDESK_API_SECRET`; exit 1 with a one-line message on a missing key or an HTTP error.
|
||||
|
||||
Rules of `pomper` (from the spec):
|
||||
- No range: mark = `sortie/pumped.json` `{"until": ISO}`; walk `conversations()`, stop at the first with `updated_at < until - 1 h`; at the end only, write `{"until": <UTC time at the start of the run>}`. No file: walk everything.
|
||||
- Range: skip `updated_at >= jusqu_a`, stop at `updated_at < depuis`; `pumped.json` untouched.
|
||||
- Per conversation: folder = `reference_number` if `re.fullmatch(r"[A-Za-z0-9_-]+", str(ref))`, else `uuid`. Write `conversation.json` (without `previous_conversations`), `messages.json` (each `attachments[].url` replaced by `attachments/<local name>`, and that URL replaced in `content` too), `transcript.md`; JSON with `ensure_ascii=False, indent=1`.
|
||||
- Attachment local name: `re.sub(r"[^\w.\- ]", "_", Path(name).name).strip(" .")`, empty → attachment `uuid`; already taken by another attachment of the conversation → `<uuid>_<name>`. Skip the download when the file exists with the same `size`.
|
||||
- `journal` gets one line per conversation (`#<ref> <subject> : <n> messages, <k> pièces jointes`) and a closing total.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests** (`setUp`: a `FauxLibreDesk` for LibreDesk, a second one as "S3"; helper `conv(ref, uuid, updated_at)`; `reponses[("GET", "/api/v1/conversations/all")]` = a callable paging on `?page=`)
|
||||
|
||||
```python
|
||||
def test_tout_au_premier_pompage(self): # 3 conversations over 2 pages → 3 folders, pumped.json written
|
||||
def test_incremental_s_arrete_sous_le_repere(self): # pumped.json until=10:00; convs at 12:00, 09:30, 08:00
|
||||
# → 12:00 and 09:30 (margin 1 h) fetched, 08:00 not; messages of 08:00 never requested
|
||||
def test_interrompu_le_repere_ne_bouge_pas(self): # messages of the 2nd conv answer 500 → raises, pumped.json unchanged
|
||||
def test_plage_ne_touche_pas_le_repere(self): # depuis/jusqu_a: only the convs in range, pumped.json absent after
|
||||
def test_pieces_jointes_locales(self):
|
||||
# messages.json url == "attachments/photo.jpg", content's URL replaced, the file's bytes on disk
|
||||
def test_nom_de_piece_jointe_assaini(self): # name "../../x.sh" → attachments/x.sh, inside the folder
|
||||
def test_noms_en_double(self): # two "a.png" → a.png and <uuid>_a.png
|
||||
def test_deja_telechargee_pas_de_requete(self): # second run, same size → no GET on /uploads/
|
||||
def test_reference_bizarre_dossier_par_uuid(self): # reference_number "../42" → folder <uuid>
|
||||
def test_cle_seulement_vers_libredesk(self):
|
||||
# attachment url on the "S3" fake: downloaded, and no "Authorization" in its entetes; LibreDesk's entetes have it
|
||||
def test_aucune_ecriture(self): # after a full run: self.faux.ecritures() == []
|
||||
```
|
||||
|
||||
`test_garde_fou_conversations.py`, as `test_garde_fou_snippets.py`: in every `conversations/*.py`, the `/api/v1/...` routes ⊆ `{"/api/v1/conversations/all", "/api/v1/conversations/{uuid}/messages"}`; none of `"POST"`, `"PUT"`, `"DELETE"`, `"PATCH"`, `method=` appears; and `pomper.py` exists.
|
||||
|
||||
- [ ] **Step 2:** `python3 -m unittest tests.test_pomper tests.test_garde_fou_conversations -v` → FAIL (no `pomper`).
|
||||
- [ ] **Step 3:** Implement `Lecteur`, `pomper` and the CLI in `conversations/pomper.py`; `urllib.request` with `timeout=60`.
|
||||
- [ ] **Step 4:** `python3 -m unittest discover -s tests -v` → all PASS (the old tests too).
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add conversations/pomper.py tests/test_pomper.py tests/test_garde_fou_conversations.py tests/faux_libredesk.py
|
||||
git commit -m "Conversations : le pompage en lecture seule (incrémental, pièces jointes, garde-fou GET)"
|
||||
```
|
||||
|
||||
### Task 3: Launching it (aimsight-libredesk)
|
||||
|
||||
**Files:**
|
||||
- Create: `~/aimsight-libredesk/conversations/pomper.sh` (executable), `~/aimsight-libredesk/conversations/pompage.py`
|
||||
- Modify: `~/aimsight-libredesk/README.md`, `~/aimsight-libredesk/.vscode/tasks.json`, `~/aimsight-libredesk/.gitignore` (`out/`)
|
||||
- Test: `~/aimsight-libredesk/tests/test_pompage.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces (imported by the app as a plain module, `sys.path` = `conversations/`; no package-relative import):
|
||||
- `start(depuis: str, jusqu_a: str, sortie: str) -> subprocess.Popen`: `ValueError("a range: From and To, YYYY-MM-DD, From before To")` (the words of `extraction/pumping.py`, shown in the app as they are) if only one date, a date not `YYYY-MM-DD`, `depuis >= jusqu_a`, or `running()`; runs `[pomper.sh, "--sortie", sortie, *(["--depuis", depuis, "--jusqu-a", jusqu_a] if depuis else [])]`, cwd the repository root, stdio to `DEVNULL`.
|
||||
- `running() -> bool`: `out/conversations.lock` held (`fcntl.flock` non-blocking, as `extraction/pumping.py`).
|
||||
- `log(lines: int = 40) -> list[str]`: the end of `out/conversations.log`.
|
||||
|
||||
`pomper.sh`, modelled on `~/aimsight-data/extraction/pump.sh`: `mkdir -p out`, `flock -n` on `out/conversations.lock`, `=== <UTC> pomper <args>` and `=== <UTC> fin` around `(set -a +u && . ./.env && set +a -u && python3 -m conversations.pomper "$@")`, all `2>&1 | tee -a out/conversations.log`.
|
||||
|
||||
- [ ] **Step 1: Write the failing tests:** `start("2026-11-01", "", "/tmp/x")`, `start("2026-11-02", "2026-11-01", …)`, `start("1.11.2026", "2026-11-02", …)` raise `ValueError`; `running()` is `False` without a lock file; `log()` returns the last lines of a temporary `out/conversations.log` (point `pompage.ROOT` at a temp folder).
|
||||
- [ ] **Step 2:** `python3 -m unittest tests.test_pompage -v` → FAIL.
|
||||
- [ ] **Step 3:** Implement `pompage.py` and `pomper.sh`; `chmod +x conversations/pomper.sh`.
|
||||
- [ ] **Step 4:** `python3 -m unittest discover -s tests -v` → PASS; `bash -n conversations/pomper.sh` → no output.
|
||||
- [ ] **Step 5:** README: a section « Pomper les conversations » (what, where it writes, read-only, the agent « Lecture conversations » with only `conversations:read_all` and `messages:read`, the two `.env` lines, the command, the app's page); the line « Aucun code de ce dépôt n'écrit dans une conversation » stays true, add the guard test next to `test_garde_fou_base.py`'s mention. Task « Conversations : pomper » in `tasks.json` (`bash conversations/pomper.sh --sortie ~/aimsight-labeling/auto/conversations`).
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add conversations/pomper.sh conversations/pompage.py tests/test_pompage.py README.md .vscode/tasks.json .gitignore
|
||||
git commit -m "Conversations : pomper.sh (.env, verrou, journal) et pompage.py, appelé par aimsight-app"
|
||||
```
|
||||
|
||||
### Task 4: The server side (aimsight-app)
|
||||
|
||||
**Files:**
|
||||
- Create: `app/server/conversations.py`
|
||||
- Modify: `app/server/server.py` (routes, docstring), `app/server/check.py` (`check_conversations`, in `CHECKS`)
|
||||
- Link: `ln -s ~/aimsight-libredesk libredesk` at the root (ignored: add `libredesk` to `.gitignore` next to the other links)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `pompage.start/running/log` (Task 3).
|
||||
- Produces (module `conversations`):
|
||||
- `FOLDER = station.LABELS / "auto" / "conversations"`; `LIBREDESK = station.ROOT / "libredesk"`; `sys.path.insert(0, str(LIBREDESK / "conversations"))` then `import pompage`.
|
||||
- `pump(body: dict) -> dict`: `pompage.start(body.get("start") or "", body.get("end") or "", str(FOLDER))`, `ValueError` → `station.Refusal`; returns `pump_state()`.
|
||||
- `pump_state() -> {"running": bool, "log": list[str]}`.
|
||||
- `list_conversations() -> list[dict]`: per folder with a `conversation.json`: `{"reference", "subject", "contact" (name, else email), "status", "last" (the last message's `created_at`, else `updated_at`), "messages" (count, `activity` excluded), "attachments" (count)}`, most recent `last` first.
|
||||
- `transcript(reference: str, dark: bool) -> str`: `analysis._page(html.escape(text, quote=False), reference, dark)` of `analysis.file(reference, "transcript.md", FOLDER)`.
|
||||
- `INLINE = {".png", ".jpg", ".jpeg", ".gif", ".webp"}`.
|
||||
- Routes in `server.py`, a new section `# --- the Conversations page (conversations.py)`:
|
||||
- `GET /api/conversations/pump` → `pump_state()`; `POST /api/conversations/pump` → `pump(body)`;
|
||||
- `GET /api/conversations` → `list_conversations()`;
|
||||
- `GET /api/conversations/{reference}/report.html` → `HTMLResponse(transcript(...), headers={"Content-Security-Policy": "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'"})`;
|
||||
- `GET /api/conversations/{reference}/{path:path}` → `f = analysis.file(reference, path, FOLDER)`; `FileResponse(f)` if `f.suffix.lower() in INLINE`, else `FileResponse(f, filename=f.name)` (attachment); both with `X-Content-Type-Options: nosniff`.
|
||||
|
||||
- [ ] **Step 1: Write `check_conversations`** (temp `FOLDER`, restored in `finally`): one folder `42/` with `conversation.json`, `messages.json` (2 messages, 1 activity), `attachments/p.png`, `attachments/x.svg`, and a `transcript.md` containing `<script>alert(1)</script>` and ``. Assert:
|
||||
|
||||
```python
|
||||
assert [c["reference"] for c in conversations.list_conversations()] == ["42"]
|
||||
assert conversations.list_conversations()[0]["messages"] == 2
|
||||
page = conversations.transcript("42", False)
|
||||
assert "<script>" not in page and "<script>" in page and '<img alt="p" src="attachments/p.png"' in page
|
||||
r = server.conversation_file("42", "attachments/x.svg")
|
||||
assert r.headers["content-disposition"].startswith("attachment")
|
||||
assert "content-disposition" not in server.conversation_file("42", "attachments/p.png").headers
|
||||
assert "img-src 'self'" in server.conversation_transcript("42").headers["content-security-policy"]
|
||||
refuses(conversations.transcript, "../analyses", False)
|
||||
assert "From and To" in refuses(conversations.pump, {"start": "2026-11-01"}) # message of pompage's ValueError
|
||||
```
|
||||
|
||||
(the last line launches nothing: `pompage.start` refuses before launching).
|
||||
- [ ] **Step 2:** `.venv/bin/python app/server/check.py check_conversations` → FAIL.
|
||||
- [ ] **Step 3:** Implement `conversations.py` and the routes (handler names `conversations_pump_state`, `conversations_pump`, `conversations_list`, `conversation_transcript(reference, dark=False)`, `conversation_file(reference, path)`).
|
||||
- [ ] **Step 4:** `.venv/bin/python app/server/check.py` → every check `ok`.
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add app/server/conversations.py app/server/server.py app/server/check.py .gitignore docs/superpowers/specs/2026-11-18-conversations-tab-design.md docs/superpowers/plans/2026-11-18-conversations-tab.md
|
||||
git commit -m "Conversations: pump LibreDesk through aimsight-libredesk, list and show the transcripts safely"
|
||||
```
|
||||
|
||||
### Task 5: The page and the docs (aimsight-app)
|
||||
|
||||
**Files:**
|
||||
- Create: `app/web/src/pages/Conversations.jsx`
|
||||
- Modify: `app/web/src/App.jsx` (`PAGES` entry `["conversations", "Conversations", IconMessages]`, lazy import, render branch), `app/web/src/common.jsx` (move `Page` here from `Data.jsx`, exported; `Data.jsx` imports it), `README.md`, `app/README.md`, `CLAUDE.md`, `docs/architecture.drawio`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: the routes of Task 4; `call` and `Page` from `common.jsx`.
|
||||
|
||||
The page, modelled on `Stations.jsx`: title "Conversations" and a dimmed line ("The LibreDesk conversations, pumped read-only into labeling/auto/conversations/"); a card "Pump" with From/To (`type="date"`, empty by default), the button `Pump` (`loading` while running), the hint "Without dates: what changed since the last pumping; the first time, the whole history.", the log read every 2 s (`GET /api/conversations/pump`) in a `ScrollArea` + `Code block`; a card with a `TextInput` "Search" (subject, contact, reference; case-insensitive) and a `Table` (Reference, Subject, Contact, Status, Last message `YYYY-MM-DD HH:MM`, Messages, Attachments), the list read again when a pumping ends; a click on a row shows `<Page title="Transcript" src={`/api/conversations/${ref}/report.html?dark=${dark}`} />` under the table.
|
||||
|
||||
- [ ] **Step 1:** Implement; `cd app/web && npm run build` → builds without error.
|
||||
- [ ] **Step 2:** Launch the server (`.venv/bin/python app/server/server.py`, or `systemctl --user restart aimsight-app` if the service runs) with the temp conversation of Task 4 copied into `labeling/auto/conversations/42/`; open `http://127.0.0.1:8770/#/conversations`: the row shows, the transcript shows its image and the `<script>` as text, `x.svg` downloads. Then remove `labeling/auto/conversations/42/`.
|
||||
- [ ] **Step 3:** Docs: `app/README.md` a section "The Conversations page" (what it pumps, where, read-only, the key in `~/aimsight-libredesk/.env`, the protections); `README.md` the link `libredesk/` in the table and the `ln -s` line, a bullet for the page; `CLAUDE.md` the link in **The links**, a line in **The processes** (the Conversations page launches `libredesk/conversations/pomper.sh`, its output in `labeling/auto/conversations/<reference>/`) and in **The contracts** (`~/aimsight-libredesk/conversations/pompage.py`); `docs/architecture.drawio` a box "aimsight-libredesk" in the style of its neighbours (French, like the diagram), an arrow app → aimsight-libredesk ("pompage des conversations") and aimsight-libredesk → aimsight-labeling ("auto/conversations/").
|
||||
- [ ] **Step 4:** `.venv/bin/python app/server/check.py` → all `ok`.
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add app/web/src/pages/Conversations.jsx app/web/src/App.jsx app/web/src/common.jsx app/web/src/pages/Data.jsx README.md app/README.md CLAUDE.md docs/architecture.drawio
|
||||
git commit -m "Conversations page: pump, search, read the transcript; docs and the libredesk link"
|
||||
```
|
||||
|
||||
### Task 6: The first real pumping (gated on the user)
|
||||
|
||||
- [ ] **Step 1:** The user creates in LibreDesk the agent « Lecture conversations », a role with only `conversations:read_all` and `messages:read`, its API key, and adds `export LIBREDESK_API_KEY=…` / `export LIBREDESK_API_SECRET=…` to `~/aimsight-libredesk/.env`. Wait for their word.
|
||||
- [ ] **Step 2:** From the page, a range of the last 3 days. Check the log ends with `=== … fin` and no error; open two transcripts.
|
||||
- [ ] **Step 3:** On one `messages.json`, confirm the attachment fields (`name`, `content_type`, `size`, `url`, `uuid`) and whether `updated_at` moved with the last message; if a field differs, fix `pomper.py` and the fake data of `test_pomper.py`, rerun the tests, commit in aimsight-libredesk.
|
||||
- [ ] **Step 4:** Hand over to the user: the folders to look at, and that the whole history (Pump without dates) is for a quiet hour, then their commit of `auto/conversations/` in `~/aimsight-labeling`.
|
||||
@@ -0,0 +1,63 @@
|
||||
# The Conversations tab: pumping the LibreDesk conversations
|
||||
|
||||
2026-11-18. Two repositories: `~/aimsight-libredesk` (the pumping) and `aimsight-app` (the tab).
|
||||
|
||||
## Intent
|
||||
|
||||
The client requests arrive by mail in LibreDesk (`helpdesk.sensima.ch`, v2.9.0). The user wants their conversations on the workstation, in full (the messages, the inline images, the attachments), for two uses: to help the support (a conversation read next to the station's data, the analyses and the support answers), and as training data. Nothing is ever written to LibreDesk.
|
||||
|
||||
## Goals, non-goals, anti-goals
|
||||
|
||||
- **Goals**: a **Conversations** page in the app that pumps the conversations on demand and shows them; each conversation stored in `labeling/auto/conversations/<reference>/`, committed in `~/aimsight-labeling` like the analyses and the support answers; the second pumping fetches only what changed.
|
||||
- **Non-goals (for now)**: linking a conversation to its stations (later: `acces/` of `~/aimsight-libredesk` maps a contact's e-mail to its serials); teaching the support agent to read `labeling/auto/conversations/` (`agents/agents/support.md`, a later change in `~/aimsight-agents`); turning the conversations into a training set (a later step; the raw material comes first); a scheduled pumping.
|
||||
- **Anti-goals**: any request to LibreDesk other than a `GET`; the API key passing through the app or read by Claude; the HTML of a client's mail rendered as HTML in the page (a mail can carry scripts or tracking pixels).
|
||||
|
||||
## Constraints
|
||||
|
||||
- Read-only on LibreDesk, enforced by a guard test in `~/aimsight-libredesk`, like `tests/test_garde_fou_snippets.py` for the snippets.
|
||||
- The key: a dedicated LibreDesk agent "Lecture conversations" whose role has only `conversations:read_all` and `messages:read`, created by the user; its key and secret in `~/aimsight-libredesk/.env` (`LIBREDESK_API_KEY`, `LIBREDESK_API_SECRET`), never read by Claude. The `Authorization: token <key>:<secret>` header goes only to the LibreDesk host (`add_unredirected_header`, as in `snippets/envoyer.py`).
|
||||
- Standard library only in `~/aimsight-libredesk` (its rule); its code and docs in French (its language); the app in English.
|
||||
- The app holds no domain logic: it calls the pumping of `~/aimsight-libredesk` as it calls `extraction/pumping.py` of `~/aimsight-data`.
|
||||
- Every conversation, by the user's decision: all the inboxes, all the statuses, no filter.
|
||||
- Committed in git, by the user's decision: the contacts' names and e-mails, and the attachments, go into the history of `~/aimsight-labeling`.
|
||||
- Every time in UTC.
|
||||
|
||||
## Approaches
|
||||
|
||||
- **A. The pumping in `~/aimsight-libredesk`, called by the app** (chosen): all the LibreDesk code in one repository, the key never in the app, the guard test next to the existing one. Costs: two repositories touched, one more link in the app.
|
||||
- **B. Everything in the app** (`app/server/conversations.py`): shorter, one repository; but the app would carry LibreDesk's logic and the API key, which the rule of the repository forbids.
|
||||
- Dropped: a `claude` agent that pumps: too heavy for a download.
|
||||
|
||||
## The design
|
||||
|
||||
### `~/aimsight-libredesk/conversations/` (French)
|
||||
|
||||
- `pomper.py`: the client restricted to three routes, all `GET`: `/api/v1/conversations/all` (`page`, `page_size` up to 500, `order_by=updated_at`, `order=desc`), `/api/v1/conversations/{uuid}/messages` (every page, private notes included), and the attachment URLs that the messages carry (`attachments[].url`, signed: `/uploads/{uuid}?…` on LibreDesk, or a bucket's host if production stores in S3), downloaded wherever they point, the `Authorization` header only to the LibreDesk host; never a URL found in a message's text. `python3 -m conversations.pomper [--depuis YYYY-MM-DD --jusqu-a YYYY-MM-DD] --sortie <folder>`.
|
||||
- **Incremental by default**: `<sortie>/pumped.json` (`{"until": <UTC time>}`, committed with the conversations) holds the start time of the last pumping that **completed**; a run walks the list from the most recently updated and stops below that mark (minus an hour of margin), and writes the new mark only at its end: a run cut short is caught up by the next one. No mark: the whole history. With `--depuis/--jusqu-a`, the conversations updated in that range (`--jusqu-a` excluded), stored ones fetched again; the mark untouched. *(Builder's call.)*
|
||||
- A conversation is fetched in full each time it changed: `conversation.json` and `messages.json` rewritten, attachments already present not downloaded again (same name and size).
|
||||
- `pomper.sh`: loads `.env` (`set -a`, as `extraction/pump.sh`), one pumping at a time (`flock` on `out/conversations.lock`), output appended to `out/conversations.log`.
|
||||
- `pompage.py`: what the app calls, the twin of `extraction/pumping.py`: `start(depuis, jusqu_a, sortie)` → the process, `running()`, `log(lines)`.
|
||||
- Tests (`tests/`, `unittest`, the fake server `tests/faux_libredesk.py` extended): only `GET`, the key never sent to another host, the incremental stop, the transcript (below), an attachment re-download skipped.
|
||||
|
||||
### One conversation: `labeling/auto/conversations/<reference_number>/`
|
||||
|
||||
- `conversation.json`: the conversation as the API gives it (subject, status, contact, inbox, dates, tags), `previous_conversations` removed.
|
||||
- `messages.json`: the messages as the API gives them, the oldest first, attachment URLs replaced by their local path (`attachments/<name>`; a signed URL expires).
|
||||
- `attachments/`: the files, under their name (a duplicate name prefixed by the attachment's uuid).
|
||||
- `transcript.md`: the readable thread, written from `messages.json`: per message, a heading `## <UTC time> — <author> (<client | agent | private note>)`, the text (`text_content`, or the HTML reduced to text: tags removed, entities decoded, paragraphs kept), the images as ``, the other attachments as links. The `activity` messages (assignments, status changes) on one line in italics. No raw HTML in it.
|
||||
|
||||
### The app: the **Conversations** page
|
||||
|
||||
- A link `libredesk/` → `~/aimsight-libredesk` (ignored by git, in the README's table and install line, and in `CLAUDE.md`'s links).
|
||||
- `app/server/conversations.py`: imports `pompage` (as `station.py` imports `pumping`); `pump(body)` (optional From/To), `pump_state()` (`running`, `log`), `list()` (each folder of `labeling/auto/conversations/`: reference, subject, contact name, status, last message time, message and attachment counts, read from `conversation.json`/`messages.json`), `transcript(reference, dark)` (`transcript.md` HTML-escaped **before** Markdown, so a client's `<script>` stays text; the page sent with `Content-Security-Policy: default-src 'none'; img-src 'self'; style-src 'unsafe-inline'`: no script, no remote image or tracking pixel), and the files of the folder through `analysis.file(…, FOLDER)`, images inline, any other attachment as a download (`Content-Disposition: attachment`: an `.html` or `.svg` attachment never runs at the app's address). The frame of the transcript sandboxed. *(Builder's call: the protection in the app, `transcript.md` stays plain readable text for the agents and the training.)*
|
||||
- `server.py`: `GET/POST /api/conversations/pump`, `GET /api/conversations`, `GET /api/conversations/{reference}/report.html`, `GET /api/conversations/{reference}/{path}`.
|
||||
- `web/src/pages/Conversations.jsx`, a page of the header next to Data and Stations: a card "Pump" (From/To optional, empty: what changed since the last pumping; the button; the end of the log read every 2 s), a table of the pumped conversations (the most recent first, a search field on subject and contact), a click shows its transcript in a frame, as the report of an analysis.
|
||||
- `check.py`: the list and the transcript on a temporary folder, without LibreDesk.
|
||||
- Docs: `app/README.md` (the page), `README.md` (the link, the tab), `docs/architecture.drawio` (the arrow app → aimsight-libredesk → labeling); `~/aimsight-libredesk/README.md` (the pumping, the key's role).
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- The exact fields of an attachment in v2.9.0 (`name`, `content_type`, `size`, `url`, `content_id` expected): confirm on the first real response; the fake server follows it.
|
||||
- Whether `updated_at` moves on a new message; if not, compare `last_message_at` as well.
|
||||
- The commit in `~/aimsight-labeling` after a pumping: by the user, by path (`auto/conversations/`), not by the app.
|
||||
- The order of the work: everything against the fake server first; then the user creates the read-only agent and puts its key in `.env`; then a first real pumping on a short range (Claude may launch it: the key stays in the subprocess), which settles the two points above; the whole history after, at a quiet hour. Nothing committed in `~/aimsight-labeling` before the user has looked at that first range.
|
||||
+49
-5
@@ -13,14 +13,58 @@ The user selected a range in the Data page and clicked "Analyze the range": they
|
||||
- Your labels go in `labels.jsonl`; the server is the one that submits them to `labeling/auto/<STATION>.jsonl`. **You never write in `labeling/auto/<STATION>.jsonl`.**
|
||||
- Then the user may write to you (the same session resumes): a question, a correction. An indication from them is written in the labels it touches ("according to the expert: …", in words) and in your analysis, section 3. If you change your labels, rewrite `labels.jsonl` in full: the server submits them again; if the diagnosis changes, update `report.md`.
|
||||
|
||||
## The weather
|
||||
|
||||
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.
|
||||
|
||||
## The targets in mm, their distance
|
||||
|
||||
`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
|
||||
|
||||
- **The labels** are read by an LLM, through retrieval (the precedents of the next analyses), and generalized into cases by the `cases` skill (`labeling/auto/cases/`): their descriptions are detailed, as `labeling/labeling-rules.md` asks.
|
||||
- **Your analysis** (`analysis.md`) is the full detail of your work: the commands, the values, the reasoning, the cases and the precedents that helped. Any other detailed note you find useful goes in the output folder too.
|
||||
- **The report** (`report.md`) is read by a human, in the page: simple and direct. It repeats neither the labels nor the analysis.
|
||||
|
||||
## The report
|
||||
|
||||
On top of your labels and your analysis: `report.md`, the diagnosis the user will read in the page, in English:
|
||||
`report.md`, in English, on exactly this outline:
|
||||
|
||||
- `# <STATION>: <the subject in a few words>`, then the question (their selection, their hints) in one or two sentences;
|
||||
- "What the data show": each event dated (UTC), the sensors affected and those that do not move, the cause and its level of evidence (confirmed / strongly supported / consistent with / possible / insufficient evidence / not observed), the command behind each fact;
|
||||
- the figures that prove, each inserted by `` and followed by a line that says what is seen in it: curves (`plot.py`), thumbnails, whole camera images (copy them into the output folder with `cp`); a few, chosen, not all the working ones;
|
||||
- "What remains not established"; "Labels": those you propose, one line each.
|
||||
```markdown
|
||||
# <STATION>: <the subject in a few words>
|
||||
|
||||
<their question: the selection and the hints, in one sentence>
|
||||
|
||||
## In short
|
||||
|
||||
<three lines at most: the answer to their question; whether the curves can be trusted, and where not; whether a real movement of the structure is seen>
|
||||
|
||||
## What happened
|
||||
|
||||
<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>
|
||||
|
||||
## What to do
|
||||
|
||||
<the actions it calls for (on site, the references, the configuration), or "Nothing.">
|
||||
|
||||
## Not established
|
||||
|
||||
<what stays open and what would settle it; the section is left out when nothing stays open>
|
||||
|
||||
## Labels
|
||||
|
||||
| Start (UTC) | End (UTC) | Family | Targets | In a few words |
|
||||
```
|
||||
|
||||
- Plain words: no commands, no tool names, no column names (`corr_x`: "the corrected curve in x"), no jargon (pose, similarity, residual) unless explained in the sentence. Short sentences.
|
||||
- It is read in two minutes: a phenomenon that repeats (a daily thermal cycle, the nightly rain) is one paragraph, not one per day.
|
||||
- Figures: inserted by ``, copied or drawn into the output folder (not `work/`): curves (`plot.py`), thumbnails, a whole camera image (`cp`).
|
||||
- **GIF**: when the cause is seen on the images over time (a passage, fog, rain, a spider web, an occultation, the sun), `.venv/bin/python tools/scripts/gif.py data/<STATION> --start T --end T --zone X,Y,W,H --out <output folder>` (`tools/GUIDE.md`, gif) shows it better than a still image. Read does not read a GIF: choose the zone and the times on `thumbnails.py` first. Keep it small: the zone of the targets concerned, a few dozen images.
|
||||
|
||||
## Your answer
|
||||
|
||||
|
||||
@@ -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: ``, 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.
|
||||
Reference in new issue
Block a user