English: the app (server/, analysis.py, routes and JSON fields), instructions/analyst.md, docs; the table of shared renames

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-16 12:40:03 +01:00
1 parent 1d80a77cb1
commit a3e6ade845
24 files changed
+1959 -1835

No files matched your search

+3 -3
View File
@@ -1,14 +1,14 @@
<!doctype html>
<html lang="fr">
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Diagnostic AIMsight</title>
<title>AIMsight Diagnostic</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
</head>
<body>
<div id="racine"></div>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
+66 -66
View File
@@ -5,40 +5,40 @@ import {
import { useDisclosure } from "@mantine/hooks";
import { IconChartLine, IconFolder, IconMoon, IconSun } from "@tabler/icons-react";
const Data = lazy(() => import("./pages/Data.jsx")); // Plotly, chargé seulement ici
const Data = lazy(() => import("./pages/Data.jsx")); // Plotly, loaded only here
const PAGES = [["data", "Data", IconChartLine]];
// L'adresse : #/<page>?station=…&du=…&au=… ; recharger garde la page et la sélection, Retour marche ; sans dates, les 5 derniers
// jours UTC, aujourd'hui compris (au exclu : demain)
const jour = n => new Date(Date.now() + n * 864e5).toISOString().slice(0, 10);
function lireAdresse() {
// 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)
const day = n => new Date(Date.now() + n * 864e5).toISOString().slice(0, 10);
function readAddress() {
const [page, q = ""] = location.hash.replace(/^#\/?/, "").split("?");
const p = new URLSearchParams(q);
return { page: PAGES.some(([n]) => n === page) ? page : "data",
selection: { station: p.get("station") || "", du: p.get("du") || jour(-4), au: p.get("au") || jour(1) } };
selection: { station: p.get("station") || "", start: p.get("start") || day(-4), end: p.get("end") || day(1) } };
}
function adresse(page, s) {
function address(page, s) {
const q = new URLSearchParams(Object.entries(s).filter(([, v]) => v)).toString();
return `#/${page}${q ? "?" + q : ""}`;
}
function Entete({ mobile, bureau, basculer }) {
const { setColorScheme } = useMantineColorScheme(), schema = useComputedColorScheme("light");
function Header({ mobile, desktop, toggle }) {
const { setColorScheme } = useMantineColorScheme(), scheme = useComputedColorScheme("light");
return (
<AppShell.Header className="entete">
<AppShell.Header className="header">
<Group h="100%" px="md" justify="space-between" wrap="nowrap">
<Group gap="sm" wrap="nowrap">
<Burger opened={mobile} onClick={basculer.mobile} hiddenFrom="sm" size="sm" color="white" aria-label="Menu" />
<Burger opened={bureau} onClick={basculer.bureau} visibleFrom="sm" size="sm" color="white" aria-label="Barre latérale" />
<Burger opened={mobile} onClick={toggle.mobile} hiddenFrom="sm" size="sm" color="white" aria-label="Menu" />
<Burger opened={desktop} onClick={toggle.desktop} visibleFrom="sm" size="sm" color="white" aria-label="Sidebar" />
<Text fw={700} size="lg">AIMsight</Text>
<Text size="sm" opacity={0.6}>Diagnostic</Text>
</Group>
<Group gap="sm" wrap="nowrap">
<Tooltip label={schema === "dark" ? "Mode clair" : "Mode sombre"}>
<ActionIcon variant="subtle" color="white" size="lg" aria-label="Changer de thème"
onClick={() => setColorScheme(schema === "dark" ? "light" : "dark")}>
{schema === "dark" ? <IconSun size={20} /> : <IconMoon size={20} />}
<Tooltip label={scheme === "dark" ? "Light mode" : "Dark mode"}>
<ActionIcon variant="subtle" color="white" size="lg" aria-label="Change theme"
onClick={() => setColorScheme(scheme === "dark" ? "light" : "dark")}>
{scheme === "dark" ? <IconSun size={20} /> : <IconMoon size={20} />}
</ActionIcon>
</Tooltip>
</Group>
@@ -47,37 +47,37 @@ function Entete({ mobile, bureau, basculer }) {
);
}
// Les analyses de la page Data (labeling/auto/analyses/), relues toutes les 3 s : un dossier par station, ouvert d'office s'il en
// a une en cours, et dedans une analyse par plage ; un clic ouvre Data sur sa station et ses jours, et y montre son rapport
// La plage d'une analyse sur une ligne : « 01.11 · 10:30–11:40 » dans le jour, sinon « 04.11 21:12 – 07.11 14:12 » (UTC)
const jourMois = t => `${t.slice(8, 10)}.${t.slice(5, 7)}`, heure = t => t.slice(11, 16);
const plage = a => (a.debut.slice(0, 10) === a.fin.slice(0, 10)
? `${jourMois(a.debut)} · ${heure(a.debut)}–${heure(a.fin)}` : `${jourMois(a.debut)} ${heure(a.debut)} – ${jourMois(a.fin)} ${heure(a.fin)}`);
const COULEUR_ETAT = { fini: "teal", erreur: "red", interrompue: "gray" };
// L'état : une roue qui tourne en cours, sinon une pastille de couleur (son nom dans la bulle)
const Pastille = ({ etat }) => (etat === "en cours" ? <Loader size={10} color="orange" />
: <Tooltip label={etat}><ColorSwatch size={8} color={`var(--mantine-color-${COULEUR_ETAT[etat] || "gray"}-6)`} withShadow={false} /></Tooltip>);
function Analyses({ ouvrir }) {
const [liste, setListe] = useState([]);
// 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)
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 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([]);
useEffect(() => {
const lire = () => fetch("/api/analyses").then(r => r.ok && r.json()).then(l => l && setListe(l)).catch(() => {}); // en silence : toutes les 3 s
lire();
const minuterie = setInterval(lire, 3000);
return () => clearInterval(minuterie);
const read = () => fetch("/api/analyses").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);
}, []);
if (!liste.length) return null;
const stations = [...new Set(liste.map(a => a.station))].sort();
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>
{stations.map(st => {
const siennes = liste.filter(a => a.station === st), occupee = siennes.some(a => a.etat === "en cours");
// le chevron du dossier reste celui de Mantine : un rightSection prendrait sa place, et tournerait avec lui
const its = list.filter(a => a.station === st), busy = its.some(a => a.state === "running");
// the chevron of the folder stays Mantine's: a rightSection would take its place, and rotate with it
return (
<NavLink key={st} defaultOpened={occupee} childrenOffset={22} leftSection={<IconFolder size={16} />}
label={<Group gap={6} wrap="nowrap">{st}<Text span size="xs" c="dimmed">{siennes.length}</Text>{occupee && <Loader size={10} color="orange" />}</Group>}>
{siennes.map(a => (
<NavLink key={a.nom} py={4} onClick={() => ouvrir(a)} leftSection={<Pastille etat={a.etat} />}
label={<Text size="xs" ff="monospace" style={{ whiteSpace: "nowrap" }}>{plage(a)}</Text>} />
<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>}>
{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>} />
))}
</NavLink>
);
@@ -85,49 +85,49 @@ function Analyses({ ouvrir }) {
</>;
}
function Barre({ page, selection, fermer, ouvrir }) {
const titre = t => <Text size="xs" fw={700} tt="uppercase" c="dimmed" px="sm" pt="lg" pb="xs">{t}</Text>;
function Sidebar({ page, selection, close, open }) {
const title = t => <Text size="xs" fw={700} tt="uppercase" c="dimmed" px="sm" pt="lg" pb="xs">{t}</Text>;
return (
<AppShell.Navbar p="xs">
<ScrollArea type="scroll">
{titre("Pages")}
{PAGES.map(([n, nom, Icone]) => (
<NavLink key={n} label={nom} leftSection={<Icone size={18} />} active={page === n} onClick={fermer}
href={adresse(n, selection)} />
{title("Pages")}
{PAGES.map(([n, name, Icon]) => (
<NavLink key={n} label={name} leftSection={<Icon size={18} />} active={page === n} onClick={close}
href={address(n, selection)} />
))}
<Analyses ouvrir={a => { fermer(); ouvrir(a); }} />
<Analyses open={a => { close(); open(a); }} />
</ScrollArea>
</AppShell.Navbar>
);
}
export default function App() {
const [{ page, selection }, setLieu] = useState(lireAdresse);
const [mobile, { toggle: basculerMobile, close: fermerMobile }] = useDisclosure(false);
const [bureau, { toggle: basculerBureau }] = useDisclosure(true);
const [analyse, setAnalyse] = useState(null); // l'analyse dont Data montre le rapport
const [{ page, selection }, setPlace] = useState(readAddress);
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
useEffect(() => {
const suivre = () => setLieu(lireAdresse());
addEventListener("hashchange", suivre);
return () => removeEventListener("hashchange", suivre);
const follow = () => setPlace(readAddress());
addEventListener("hashchange", follow);
return () => removeEventListener("hashchange", follow);
}, []);
const choisir = s => { location.hash = adresse(page, s); };
// Une analyse de la barre : Data sur sa station, des jours qui couvrent sa plage (sauf si la plage affichée les couvre déjà)
function ouvrirAnalyse(a) {
const s = selection, couvre = s.station === a.station && s.du <= a.debut.slice(0, 10) && a.fin < s.au;
const au = new Date(Date.parse(a.fin.slice(0, 10)) + 864e5).toISOString().slice(0, 10);
setAnalyse(a.nom);
location.hash = adresse("data", couvre ? s : { station: a.station, du: a.debut.slice(0, 10), au });
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) {
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);
location.hash = address("data", covers ? s : { station: a.station, start: a.start.slice(0, 10), end });
}
return (
<AppShell header={{ height: 64 }} padding="lg"
navbar={{ width: 260, breakpoint: "sm", collapsed: { mobile: !mobile, desktop: !bureau } }}>
<Entete mobile={mobile} bureau={bureau} basculer={{ mobile: basculerMobile, bureau: basculerBureau }} />
<Barre page={page} selection={selection} fermer={fermerMobile} ouvrir={ouvrirAnalyse} />
navbar={{ width: 260, breakpoint: "sm", collapsed: { mobile: !mobile, desktop: !desktop } }}>
<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} choisir={choisir} analyse={analyse} setAnalyse={setAnalyse} /></Suspense>
<Suspense fallback={<Loader m="xl" />}><Data selection={selection} choose={choose} analysis={analysis} setAnalysis={setAnalysis} /></Suspense>
</AppShell.Main>
</AppShell>
);
+35
View File
@@ -0,0 +1,35 @@
import { useEffect, 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) });
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 });
} catch (e) {
notifications.show({ color: "red", title: "Server unreachable", message: e.message });
}
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);
useEffect(() => { call("/api/stations").then(l => l && setStations(l)); }, []);
useEffect(() => setS(selection), [selection.station, selection.start, selection.end]);
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 || "" })} />
<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>
</Group>
</Card>
);
}
-52
View File
@@ -1,52 +0,0 @@
import { useEffect, useState } from "react";
import { Button, Card, Group, Select, Text, TextInput } from "@mantine/core";
import { notifications } from "@mantine/notifications";
// Une requête à l'API ; un refus du serveur s'affiche en notification -> le JSON rendu, ou null
export async function appel(chemin, methode = "GET", corps) {
try {
const r = await fetch(chemin, corps === undefined ? { method: methode }
: { method: methode, headers: { "Content-Type": "application/json" }, body: JSON.stringify(corps) });
const json = await r.json().catch(() => ({ erreur: r.statusText }));
if (r.ok) return json;
notifications.show({ color: "red", title: "Refusé", message: json.erreur || r.statusText });
} catch (e) {
notifications.show({ color: "red", title: "Serveur injoignable", message: e.message });
}
return null;
}
export const poster = async (chemin, corps) => (await appel(chemin, "POST", corps)) !== null;
export function Carte({ surtitre, titre, action, children, ...reste }) {
return (
<Card shadow="sm" padding={0} withBorder {...reste}>
<Group px="lg" py="md" justify="space-between" wrap="nowrap" style={{ borderBottom: "1px solid var(--mantine-color-default-border)" }}>
<div>
<Text size="xs" fw={700} tt="uppercase" c="dimmed">{surtitre}</Text>
<Text fw={500}>{titre}</Text>
</div>
{action}
</Group>
{children}
</Card>
);
}
// La station et la plage (UTC, Au exclue ; vides : toute la période), partagées par les pages via l'adresse
export function Selecteur({ selection, choisir }) {
const [stations, setStations] = useState([]), [s, setS] = useState(selection);
useEffect(() => { appel("/api/stations").then(l => l && setStations(l)); }, []);
useEffect(() => setS(selection), [selection.station, selection.du, selection.au]);
return (
<Card shadow="sm" withBorder>
<Group align="flex-end" gap="md">
<Select label="Station" placeholder="Choisir" data={stations} value={s.station || null} searchable w={200}
onChange={v => setS({ ...s, station: v || "" })} />
<TextInput label="Du (UTC)" type="date" value={s.du} onChange={e => setS({ ...s, du: e.currentTarget.value })} />
<TextInput label="Au (exclu)" type="date" value={s.au} onChange={e => setS({ ...s, au: e.currentTarget.value })} />
<Button onClick={() => choisir(s)} disabled={!s.station}>Charger</Button>
</Group>
</Card>
);
}
+2 -2
View File
@@ -6,7 +6,7 @@ import "@mantine/notifications/styles.css";
import "./style.css";
import App from "./App.jsx";
// Bleu primaire #5383ff (shade 5), la palette retenue pour la page
// Primary blue #5383ff (shade 5), the palette chosen for the page
const theme = createTheme({
primaryColor: "aimsight",
primaryShade: 5,
@@ -16,7 +16,7 @@ const theme = createTheme({
defaultRadius: "md",
});
createRoot(document.getElementById("racine")).render(
createRoot(document.getElementById("root")).render(
<MantineProvider theme={theme} defaultColorScheme="auto">
<Notifications position="top-right" />
<App />
+353 -352
View File
@@ -4,80 +4,80 @@ import {
useComputedColorScheme,
} from "@mantine/core";
import { IconPlus, IconX } from "@tabler/icons-react";
import { appel, Selecteur } from "../commun.jsx";
import { ImagesDe } from "./Images.jsx";
import { call, Selector } from "../common.jsx";
import { StationImages } from "./Images.jsx";
// Data, le visualiseur de courbes et l'étiquetage : un plot au départ, d'autres à ajouter ou enlever,
// tous alignés sur le temps ; sous eux les étiquettes : Detectors (les événements du journal), LLM (labeling/auto/, en lecture)
// ou Analysis (les mêmes, à modifier, supprimer ; glisser sur la barre sélectionne une plage, que l'analyste diagnostique et
// étiquette ; ailleurs, glisser zoome) ; un clic ouvre une
// étiquette et la met en évidence. À droite, les images de la station, et sous elles les paramètres du diagnostic.
const FAMILLES = { "Visibility": "#8ec5e8", "Obstruction": "#f0b072", "Thermal displacement": "#f08a7e", "Displacement": "#b39ddb",
// 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
// 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",
"Target issue": "#e6d46a", "No data": "#c4c4be", "None": "#a8d5a2" };
const NOM_FAMILLE = f => (f === "None" ? "None (courbes intactes)" : f);
const CHOIX_FAMILLE = [{ value: "", label: "(sans famille)" }, ...Object.keys(FAMILLES).map(f => ({ value: f, label: NOM_FAMILLE(f) }))];
// LLM et Analysis : les mêmes étiquettes, labeling/auto/ ; LLM les lit, Analysis les modifie, supprime, et en fait faire par
// l'analyste sur une plage (app/serveur/analyse.py)
const SOURCES = [{ value: "detecteurs", label: "Detectors" }, { value: "auto", label: "LLM" }, { value: "analysis", label: "Analysis" }];
const GRIS = "#b0b0aa", BLEU = "#2a78d6", VOIE = 26, HAUT = 330; // VOIE : px par rangée d'étiquettes ; HAUT : d'un plot
const couleur = l => FAMILLES[l.categorie] || GRIS;
const lisible = s => s.slice(0, 16).replace("T", " ");
const marge = () => ({ l: 60, r: 20, t: 10, b: 30 });
// L'habillage, aux couleurs de Mantine (dark.0 à dark.7 en sombre, gray en clair)
const COULEURS = { clair: { texte: "#495057", faible: "#868e96", grille: "#eef0f2", axe: "#dee2e6", fond: "#f1f3f5", bulle: "#ffffff", zone: 0.05 },
sombre: { texte: "#c9c9c9", faible: "#828282", grille: "#2e2e2e", axe: "#424242", fond: "#3b3b3b", bulle: "#242424", zone: 0.07 } };
const POLICE = "Roboto, sans-serif";
const habillage = c => ({ paper_bgcolor: "rgba(0,0,0,0)", plot_bgcolor: "rgba(0,0,0,0)", font: { family: POLICE, size: 11, color: c.texte },
hoverlabel: { bgcolor: c.bulle, bordercolor: c.axe, align: "left", font: { family: POLICE, size: 12, color: c.texte } },
modebar: { bgcolor: "rgba(0,0,0,0)", color: c.faible, activecolor: "#5383ff" } });
const axe = c => ({ gridcolor: c.grille, linecolor: c.axe, showline: true, zeroline: false, ticks: "" });
const OUTILS = { responsive: true, doubleClick: "reset", displaylogo: false, showTips: false,
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) }))];
// 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" }];
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", " ");
const margin = () => ({ l: 60, r: 20, t: 10, b: 30 });
// The skin, in Mantine's colours (dark.0 to dark.7 in dark, gray in light)
const THEMES = { light: { text: "#495057", faint: "#868e96", grid: "#eef0f2", axis: "#dee2e6", bg: "#f1f3f5", tooltip: "#ffffff", zone: 0.05 },
dark: { text: "#c9c9c9", faint: "#828282", grid: "#2e2e2e", axis: "#424242", bg: "#3b3b3b", tooltip: "#242424", zone: 0.07 } };
const FONT = "Roboto, sans-serif";
const skin = c => ({ paper_bgcolor: "rgba(0,0,0,0)", plot_bgcolor: "rgba(0,0,0,0)", font: { family: FONT, size: 11, color: c.text },
hoverlabel: { bgcolor: c.tooltip, bordercolor: c.axis, align: "left", font: { family: FONT, size: 12, color: c.text } },
modebar: { bgcolor: "rgba(0,0,0,0)", color: c.faint, activecolor: "#5383ff" } });
const axis = c => ({ gridcolor: c.grid, linecolor: c.axis, showline: true, zeroline: false, ticks: "" });
const CONFIG = { responsive: true, doubleClick: "reset", displaylogo: false, showTips: false,
modeBarButtonsToRemove: ["lasso2d", "select2d", "autoScale2d", "zoomIn2d", "zoomOut2d", "hoverClosestCartesian", "hoverCompareCartesian", "toggleSpikelines"] };
const date = v => Date.parse(String(v).replace(" ", "T").replace(/Z?$/, "Z")); // une date Plotly ou d'étiquette -> ms UTC
const coupe = s => s.replace(/(.{1,80})(\s|$)/g, "$1<br>"); // la bulle : des lignes de 80 caractères au plus
const date = v => Date.parse(String(v).replace(" ", "T").replace(/Z?$/, "Z")); // a Plotly or label date -> ms UTC
const wrap = s => s.replace(/(.{1,80})(\s|$)/g, "$1<br>"); // the tooltip: lines of 80 characters at most
const DETECTEES = Object.keys(FAMILLES).filter(f => f !== "None"); // les familles des détecteurs (categories.py)
const DETECTED = Object.keys(FAMILIES).filter(f => f !== "None"); // the families of the detectors (categories.py)
export default function Data({ selection, choisir, analyse, setAnalyse }) {
const [donnees, setDonnees] = useState(null), [charge, setCharge] = useState(false), [large, setLarge] = useState(false);
const gauche = useRef(), [instant, setInstant] = useState(null); // instant : où caler les images (le début de l'événement cliqué)
// Les paramètres du diagnostic, sous l'image (Detectors et LLM) : familles montrées (filtre de la page) ; cibles gardées ("" :
// toutes ; sinon les détecteurs retournent sans les autres)
const [source, setSource] = useState("detecteurs"), [familles, setFamilles] = useState(DETECTEES), [cibles, setCibles] = useState("");
const [focus, setFocus] = useState(false); // un événement ouvert : les plots ne montrent que ses capteurs
const { station, du, au } = selection;
export default function Data({ selection, choose, analysis, setAnalysis }) {
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 { station, start, end } = selection;
useEffect(() => {
setDonnees(null); setCibles("");
setData(null); setTargets("");
if (!station) return;
setCharge(true);
appel(`/api/courbes?${new URLSearchParams({ station, du, au })}`).then(d => { setDonnees(d); setCharge(false); });
}, [station, du, au]);
// Les colonnes glissent (style.css) ; Plotly ne suit que la fenêtre : à la fin du glissement, les plots se recalent sur leur
// nouvelle largeur (les redessiner à chaque image du glissement serait trop lourd)
const finGlissement = e => { if (e.target === gauche.current && e.propertyName === "max-width") dispatchEvent(new Event("resize")); };
setLoading(true);
call(`/api/curves?${new URLSearchParams({ station, start, end })}`).then(d => { setData(d); setLoading(false); });
}, [station, start, end]);
// 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")); };
return (
<Grid gutter="lg" className="data-grille" onTransitionEnd={finGlissement}>
<Grid.Col span={{ base: 12, lg: large ? 5 : 8 }} ref={gauche}>
<Grid gutter="lg" className="data-grid" onTransitionEnd={slideEnd}>
<Grid.Col span={{ base: 12, lg: wide ? 5 : 8 }} ref={left}>
<Stack gap="lg">
<div>
<Title order={2}>Data</Title>
<Text c="dimmed">Les courbes d'une station, un plot ou plusieurs ; sous eux les étiquettes : un clic sur l'une la met en évidence et
l'ouvre.</Text>
<Text c="dimmed">The curves of a station, one plot or several; under them the labels: a click on one highlights it and
opens it.</Text>
</div>
<Selecteur selection={selection} choisir={choisir} />
{charge && <Loader />}
{donnees && <Courbes key={`${station}${du}${au}`} selection={selection} d={donnees} caler={(t, proche) => setInstant({ t, proche })}
source={source} setSource={setSource} familles={familles} cibles={cibles} focus={focus}
analyse={analyse} setAnalyse={setAnalyse} />}
<Selector selection={selection} choose={choose} />
{loading && <Loader />}
{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} />}
</Stack>
</Grid.Col>
<Grid.Col span={{ base: 12, lg: large ? 7 : 4 }}>
<div className="colle">
<Grid.Col span={{ base: 12, lg: wide ? 7 : 4 }}>
<div className="sticky">
<Stack gap="lg">
<ImagesDe selection={selection} compacte large={large} basculer={() => setLarge(!large)} instant={instant} />
{donnees && <Parametres key={`${station}${du}${au}`} d={donnees} familles={familles} setFamilles={setFamilles}
cibles={cibles} setCibles={setCibles} detect={source === "detecteurs"}
focus={focus} setFocus={setFocus} />}
<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} />}
</Stack>
</div>
</Grid.Col>
@@ -85,97 +85,97 @@ export default function Data({ selection, choisir, analyse, setAnalyse }) {
);
}
// Les familles s'appliquent tout de suite (filtre de la page, Detectors et LLM) ; les cibles, au bouton : chaque jeu de cibles
// relance les détecteurs (les étiquettes LLM ne disent pas leurs capteurs : elles ne les filtrent pas)
function Parametres({ d, familles, setFamilles, cibles, setCibles, detect, focus, setFocus }) {
const capteurs = Object.keys(d.T).filter(k => k && !k.startsWith("system:"));
// 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 }) {
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 [coches, setCoches] = useState(cibles ? cibles.split(",") : capteurs);
const voulu = coches.length === capteurs.length ? "" : capteurs.filter(c => coches.includes(c)).join(",");
const [checked, setChecked] = useState(targets ? targets.split(",") : sensors);
const wanted = checked.length === sensors.length ? "" : sensors.filter(c => checked.includes(c)).join(",");
return (
<Card shadow="sm" withBorder>
<Stack gap="sm">
<Title order={5}>Paramètres du diagnostic</Title>
<Switch label="Focus on event curves" description="Un événement ouvert : les plots ne montrent que ses capteurs"
<Title order={5}>Diagnostic settings</Title>
<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)} />
<Checkbox.Group label="Familles montrées" value={familles} onChange={setFamilles}>
<Checkbox.Group label="Families shown" value={families} onChange={setFamilies}>
<SimpleGrid cols={2} spacing={6} verticalSpacing={6} mt={6}>
{DETECTEES.map(f => <Checkbox key={f} size="xs" value={f} label={f} color={FAMILLES[f]} iconColor="#1a1b1e" />)}
{DETECTED.map(f => <Checkbox key={f} size="xs" value={f} label={f} color={FAMILIES[f]} iconColor="#1a1b1e" />)}
</SimpleGrid>
</Checkbox.Group>
<Checkbox.Group label="Cibles considérées (les autres sont écartées)" value={coches} onChange={setCoches}>
<Checkbox.Group label="Targets considered (the others are removed)" value={checked} onChange={setChecked}>
<SimpleGrid cols={3} spacing={6} verticalSpacing={6} mt={6}>
{capteurs.map(c => <Checkbox key={c} size="xs" value={c} label={c + (refs.has(c) ? " (ref.)" : "")} />)}
{sensors.map(c => <Checkbox key={c} size="xs" value={c} label={c + (refs.has(c) ? " (ref.)" : "")} />)}
</SimpleGrid>
</Checkbox.Group>
{!detect && <Text size="xs" c="dimmed">Les étiquettes ne disent pas leurs cibles : ce choix ne vaut que pour Detectors.</Text>}
{!detect && <Text size="xs" c="dimmed">Labels do not state their targets: this choice applies to Detectors only.</Text>}
<Group gap="sm">
<Button size="xs" onClick={() => setCibles(voulu)} disabled={!coches.length || voulu === cibles}>Relancer les détecteurs</Button>
<Button size="xs" variant="default" onClick={() => setCoches(coches.length ? [] : capteurs)}>{coches.length ? "Tout décocher" : "Tout cocher"}</Button>
<Button size="xs" onClick={() => setTargets(wanted)} disabled={!checked.length || wanted === targets}>Rerun the detectors</Button>
<Button size="xs" variant="default" onClick={() => setChecked(checked.length ? [] : sensors)}>{checked.length ? "Uncheck all" : "Check all"}</Button>
</Group>
</Stack>
</Card>
);
}
// Une ligne de la fiche d'un événement des détecteurs : son nom, puis sa valeur
const Champ = ({ nom, children }) => (
// A line of the card of a detectors' event: its name, then its value
const Field = ({ name, children }) => (
<Group gap="sm" align="flex-start" wrap="nowrap">
<Text size="sm" c="dimmed" w={80} style={{ flexShrink: 0 }}>{nom}</Text>
<Text size="sm" c="dimmed" w={80} style={{ flexShrink: 0 }}>{name}</Text>
<Text size="sm" component="div">{children}</Text>
</Group>
);
// Les capteurs d'un événement : ceux des détecteurs, sinon ceux que nomme le texte de l'étiquette (LLM, Analysis)
const nomme = (texte, s) => new RegExp(`(^|[^\\w])${s.replace(/[^\w]/g, "\\$&")}(?![\\w])`).test(texte);
const capteursDe = (l, noms) => l.capteurs ?? noms.filter(s => nomme(l.description, s));
// The sensors of an event: those of the detectors, otherwise those the text of the label names (LLM, Analysis)
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));
// analyse : le dossier de l'analyse montrée, tenu par App (la barre latérale en ouvre une)
function Courbes({ selection: { station, du, au }, d, caler, source, setSource, familles, cibles, focus, analyse, setAnalyse }) {
// 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 }) {
const { A, B, T, plots: PLOTS } = d;
const indice = (titre, sinon) => { const i = PLOTS.findIndex(p => p.titre === titre); return i < 0 ? sinon : i; };
const [Plotly, setPlotly] = useState(null), [pret, setPret] = useState(false);
const [vues, setVues] = useState([{ id: 1, m: indice("Relative Corrected Horizontal Shift", 0) }]); // les plots affichés
const [choix, setChoix] = useState(null);
const [indices, setIndices] = useState(""), [rev, setRev] = useState(0);
const [ouverte, setOuverte] = useState(null), [edit, setEdit] = useState(null), [note, setNote] = useState("");
const [toutes, setToutes] = useState([]), [lecture, setLecture] = useState(true), sombre = useComputedColorScheme("light") === "dark";
// toutes : le fichier (ou les détecteurs) ; labels : sur la plage, dans les familles cochées (sans famille ou None : toujours)
const labels = useMemo(() => toutes.filter(x => x.debut < B && x.fin > A
&& (!DETECTEES.includes(x.categorie) || familles.includes(x.categorie))), [toutes, familles]);
const detect = source === "detecteurs", lecteur = source !== "analysis"; // seul Analysis écrit
const dossier = source === "analysis" ? "auto" : source; // le dossier de labeling/ des étiquettes
// figs : id -> div du plot ; dessines : id -> plot qu'il montre ; vue : la plage et la largeur où le texte des étiquettes a été tronqué
const figs = useRef({}), dessines = useRef({}), prochain = useRef(2), barre = useRef(), tries = useRef([]), vue = useRef(""), courant = useRef({});
// le focus : les capteurs de l'événement ouvert (aucun : tous, comme pour No data) ; montres, leur clé
const noms = useMemo(() => Object.keys(T).filter(k => k && !k.startsWith("system:")), [T]);
const gardes = focus && ouverte ? capteursDe(ouverte, noms) : [], montres = gardes.join(",");
courant.current = { vues, labels, choix, ouverte, ouvrir, gardes: new Set(gardes), montres, c: COULEURS[sombre ? "sombre" : "clair"] }; // ce que lisent les événements Plotly
const plotIndex = (title, otherwise) => { const i = PLOTS.findIndex(p => p.title === title); return i < 0 ? otherwise : i; };
const [Plotly, setPlotly] = useState(null), [ready, setReady] = useState(false);
const [views, setViews] = useState([{ id: 1, m: plotIndex("Relative Corrected Horizontal Shift", 0) }]); // the plots shown
const [choice, setChoice] = useState(null);
const [hints, setHints] = useState(""), [rev, setRev] = useState(0);
const [opened, setOpened] = useState(null), [edit, setEdit] = useState(null), [note, setNote] = useState("");
const [allLabels, setAllLabels] = useState([]), [reading, setReading] = useState(true), dark = useComputedColorScheme("light") === "dark";
// allLabels: the file (or the detectors); labels: in the range, in the checked families (no family or None: always)
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
// 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
useEffect(() => { import("plotly.js-dist-min").then(m => setPlotly(() => m.default)); }, []);
const liste = () => courant.current.vues.map(v => figs.current[v.id]).filter(g => g?._fullLayout);
const plotDivs = () => current.current.views.map(v => figs.current[v.id]).filter(g => g?._fullLayout);
// Les zones des étiquettes, la plage choisie, et l'étiquette ouverte : plus marquée, entourée
// The zones of the labels, the chosen range, and the open label: more marked, outlined
function zones() {
const { labels, choix, ouverte, c } = courant.current;
const z = (a, b, f, o, ligne = { width: 0 }, couche = "below") => ({ type: "rect", xref: "x", yref: "paper", x0: lisible(a), x1: lisible(b),
y0: 0, y1: 1, fillcolor: f, opacity: o, line: ligne, layer: couche });
return labels.map(l => z(l.debut, l.fin, couleur(l), c.zone)).concat(choix ? [z(choix[0], choix[1], BLEU, 0.25)] : [])
.concat(ouverte ? [z(ouverte.debut, ouverte.fin, couleur(ouverte), 0.3),
z(ouverte.debut, ouverte.fin, "rgba(0,0,0,0)", 1, { color: c.texte, width: 1.5, dash: "dot" }, "above")] : []);
const { labels, choice, opened, c } = current.current;
const z = (a, b, f, o, line = { width: 0 }, layer = "below") => ({ type: "rect", xref: "x", yref: "paper", x0: readable(a), x1: readable(b),
y0: 0, y1: 1, fillcolor: f, opacity: o, line, layer });
return labels.map(l => z(l.start, l.end, color(l), c.zone)).concat(choice ? [z(choice[0], choice[1], BLUE, 0.25)] : [])
.concat(opened ? [z(opened.start, opened.end, color(opened), 0.3),
z(opened.start, opened.end, "rgba(0,0,0,0)", 1, { color: c.text, width: 1.5, dash: "dot" }, "above")] : []);
}
// Le contour des barres : épais pour l'étiquette ouverte
const contour = t => {
const { ouverte, c } = courant.current;
return { color: t.map(l => (l === ouverte ? c.texte : c.fond)), width: t.map(l => (l === ouverte ? 3 : 1)) };
// The outline of the bars: thick for the open label
const outline = t => {
const { opened, c } = current.current;
return { color: t.map(l => (l === opened ? c.text : c.bg)), width: t.map(l => (l === opened ? 3 : 1)) };
};
// Les plots et la barre partagent plage et marges : celui qui change impose les siens aux autres (rien si déjà alignés,
// sinon le relayout appelle aligne en boucle).
function aligne(src) {
const gs = liste(), b = barre.current;
// The plots and the bar share range and margins: the one that changes imposes its own on the others (nothing if already
// aligned, otherwise the relayout calls align in a loop).
function align(src) {
const gs = plotDivs(), b = bar.current;
if (!b?._fullLayout || !gs.length) return;
const rg = (src?._fullLayout ? src : gs[0])._fullLayout.xaxis.range.slice();
const l = Math.max(...gs.map(g => g._fullLayout._size.l)), r = Math.max(...gs.map(g => g._fullLayout._size.r));
@@ -183,379 +183,380 @@ function Courbes({ selection: { station, du, au }, d, caler, source, setSource,
const m = g._fullLayout.margin, x = g._fullLayout.xaxis.range;
if (m.l === l && m.r === r && date(x[0]) === date(rg[0]) && date(x[1]) === date(rg[1])) return;
return Plotly.relayout(g, { "xaxis.range": rg, "margin.l": l, "margin.r": r });
})).then(recaleTexte);
})).then(refitText);
}
// Le texte des étiquettes suit le zoom et la largeur de la barre (rien si les deux n'ont pas changé)
function recaleTexte() {
const b = barre.current, L = b?._fullLayout;
// The text of the labels follows the zoom and the width of the bar (nothing if neither changed)
function refitText() {
const b = bar.current, L = b?._fullLayout;
if (!L) return;
const v = `${L.xaxis.range}|${L._size.w}`;
if (v !== vue.current) { vue.current = v; return Plotly.restyle(b, { text: [textes(tries.current, L)] }); }
if (v !== viewKey.current) { viewKey.current = v; return Plotly.restyle(b, { text: [texts(sorted.current, L)] }); }
}
// Le texte de chaque étiquette, tronqué à la largeur visible de sa barre (~6 px par caractère en 11 px) ; pour un événement
// des détecteurs, sa famille seulement (ses capteurs dans la bulle, le reste au clic)
function textes(t, L) {
// The text of each label, truncated to the visible width of its bar (~6 px per character at 11 px); for a detectors'
// event, its family only (its sensors in the tooltip, the rest on click)
function texts(t, L) {
const [r0, r1] = L.xaxis.range.map(date), w = L._size.w;
return t.map(l => {
const x = l.message ? l.categorie : l.description;
const px = (Math.min(date(l.fin), r1) - Math.max(date(l.debut), r0)) / (r1 - r0) * w, n = Math.floor((px - 10) / 6);
const x = l.message ? l.family : l.description;
const px = (Math.min(date(l.end), r1) - Math.max(date(l.start), r0)) / (r1 - r0) * w, n = Math.floor((px - 10) / 6);
return n < 3 ? "" : x.length <= n ? x : x.slice(0, n - 1) + "…";
});
}
// Une trace de capteur sous le focus : visible si c'est l'un des siens, sinon dans la légende seulement ; uirevision de la
// trace : le focus qui change l'emporte sur les clics de légende, qui restent tant qu'il ne change pas
function focalise(t) {
const { gardes, montres } = courant.current;
if (!montres || !t.t || t.t.startsWith("system:")) return { uirevision: montres || 1 };
return { visible: gardes.has(t.t) ? true : "legendonly", uirevision: montres };
// A sensor trace under the focus: visible if it is one of its own, otherwise in the legend only; uirevision of the
// trace: the focus that changes wins over legend clicks, which stay as long as it does not change
function focusTrace(t) {
const { kept, shown } = current.current;
if (!shown || !t.t || t.t.startsWith("system:")) return { uirevision: shown || 1 };
return { visible: kept.has(t.t) ? true : "legendonly", uirevision: shown };
}
function dessineFig(g, m) {
const p = PLOTS[m], { c } = courant.current, b = barre.current?._fullLayout;
g.style.height = `${HAUT}px`; // responsive : Plotly reprend la hauteur du div à chaque restyle, il lui en faut une
// uirevision : le zoom et les capteurs cachés restent quand on change de plot ; l'ordonnée, propre à chaque plot, se recale.
// Un nouveau plot prend la plage déjà affichée. t : la place du menu du plot (à gauche) et de la barre d'outils (à droite).
function drawFig(g, m) {
const p = PLOTS[m], { c } = 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,
uid: t.name.replace(/\W/g, "_"), line: t.line, ...focalise(t),
hovertemplate: `${t.name} : %{y}<br>%{x|%Y-%m-%d %H:%M} UTC<extra></extra>` })),
{ ...habillage(c), height: HAUT, hovermode: "closest", margin: { ...marge(), t: 42, b: 36 }, uirevision: 1, shapes: zones(),
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(),
legend: { x: 1.01, y: 1, itemwidth: 30, font: { size: 11 } },
xaxis: { type: "date", range: b ? b.xaxis.range.slice() : [lisible(A), lisible(B)], ...axe(c) },
yaxis: { title: { text: p.titre, font: { size: 11, color: c.faible } }, uirevision: p.titre, ...axe(c) } },
OUTILS).then(() => {
if (!g.suivi) {
g.suivi = true;
g.on("plotly_relayout", () => aligne(g));
g.on("plotly_click", ev => caler(String(ev.points[0].x), true)); // un clic sur une courbe : l'image la plus proche
xaxis: { type: "date", range: b ? b.xaxis.range.slice() : [readable(A), readable(B)], ...axis(c) },
yaxis: { title: { text: p.title, font: { size: 11, color: c.faint } }, uirevision: p.title, ...axis(c) } },
CONFIG).then(() => {
if (!g.followed) {
g.followed = true;
g.on("plotly_relayout", () => align(g));
g.on("plotly_click", ev => setImage(String(ev.points[0].x), true)); // a click on a curve: the nearest image
}
return aligne(g);
return align(g);
});
}
// Les plots nouveaux ou changés (tous : au changement de thème)
function dessinePlots(tous) {
return Promise.all(courant.current.vues.filter(v => tous || dessines.current[v.id] !== v.m)
.map(v => { dessines.current[v.id] = v.m; return dessineFig(figs.current[v.id], v.m); }));
// The new or changed plots (all: when the theme changes)
function drawPlots(all) {
return Promise.all(current.current.views.filter(v => all || drawn.current[v.id] !== v.m)
.map(v => { drawn.current[v.id] = v.m; return drawFig(figs.current[v.id], v.m); }));
}
function dessineBarre() {
const t = [...courant.current.labels].sort((a, b) => (a.debut < b.debut ? -1 : 1));
tries.current = t;
const voies = [], voie = t.map(l => { // la première rangée libre, sinon une nouvelle
const r = voies.findIndex(f => f <= l.debut), i = r < 0 ? voies.length : r;
voies[i] = l.fin;
function drawBar() {
const t = [...current.current.labels].sort((a, b) => (a.start < b.start ? -1 : 1));
sorted.current = t;
const lanes = [], lane = t.map(l => { // the first free row, otherwise a new one
const r = lanes.findIndex(f => f <= l.start), i = r < 0 ? lanes.length : r;
lanes[i] = l.end;
return i;
});
const n = Math.max(1, voies.length), gs = liste(), f = gs[0]._fullLayout, { c } = courant.current;
vue.current = "";
barre.current.style.height = `${40 + VOIE * n}px`; // comme les plots
return Plotly.react(barre.current, [{ type: "bar", orientation: "h", y: voie, base: t.map(l => lisible(l.debut)),
x: t.map(l => Date.parse(l.fin) - Date.parse(l.debut)), width: 0.8,
marker: { color: t.map(couleur), cornerradius: 4, line: contour(t) },
text: textes(t, barre.current._fullLayout || f), textposition: "inside", insidetextanchor: "start", textangle: 0,
textfont: { family: POLICE, size: 11, color: "#1a1b1e" },
unselected: { marker: { opacity: 1 } }, // sinon une sélection les pâlit
// la bulle : pour un détecteur, ses cibles seulement ; sinon la famille et tout le texte, que la barre tronque
customdata: t.map(l => (l.message ? coupe(l.cibles.length ? l.cibles.join(", ") : l.references.length
? l.references.map(s => s + " (ref.)").join(", ") : "Tous les capteurs")
: (l.categorie ? `<b>${NOM_FAMILLE(l.categorie)}</b><br>` : "") + coupe(l.description))),
const n = Math.max(1, lanes.length), gs = plotDivs(), f = gs[0]._fullLayout, { c } = current.current;
viewKey.current = "";
bar.current.style.height = `${40 + LANE * n}px`; // as the plots
return Plotly.react(bar.current, [{ type: "bar", orientation: "h", y: lane, base: t.map(l => readable(l.start)),
x: t.map(l => Date.parse(l.end) - Date.parse(l.start)), width: 0.8,
marker: { color: t.map(color), cornerradius: 4, line: outline(t) },
text: texts(t, bar.current._fullLayout || f), textposition: "inside", insidetextanchor: "start", textangle: 0,
textfont: { family: FONT, size: 11, color: "#1a1b1e" },
unselected: { marker: { opacity: 1 } }, // otherwise a selection fades them
// the tooltip: for a detector, its targets only; otherwise the family and the whole text, which the bar truncates
customdata: t.map(l => (l.message ? wrap(l.targets.length ? l.targets.join(", ") : l.references.length
? 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>" }],
{ ...habillage(c), height: 40 + VOIE * n, dragmode: lecteur ? "zoom" : "select", selectdirection: "h", hovermode: "closest", plot_bgcolor: c.fond, showlegend: false,
margin: { ...marge(), 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.texte },
{ ...skin(c), height: 40 + LANE * n, dragmode: readOnly ? "zoom" : "select", 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 },
newselection: { line: { color: BLEU, width: 1 } }, activeselection: { fillcolor: BLEU, opacity: 0.25 } },
newselection: { line: { color: BLUE, width: 1 } }, activeselection: { fillcolor: BLUE, opacity: 0.25 } },
{ responsive: true, displayModeBar: false, doubleClick: false });
}
// Le premier dessin, puis les événements de la barre, une fois
// The first drawing, then the events of the bar, once
useEffect(() => {
if (!Plotly) return;
dessinePlots().then(dessineBarre).then(() => aligne()).then(() => {
barre.current.on("plotly_selected", ev => {
drawPlots().then(drawBar).then(() => align()).then(() => {
bar.current.on("plotly_selected", ev => {
const r = ev?.range?.x;
if (r) setChoix(r.map(v => String(v).slice(0, 16).replace(" ", "T") + "Z"));
if (r) setChoice(r.map(v => String(v).slice(0, 16).replace(" ", "T") + "Z"));
});
barre.current.on("plotly_deselect", () => setChoix(null));
barre.current.on("plotly_relayout", () => aligne(barre.current)); // zoomée (Detectors, LLM) ou redimensionnée seule (l'image agrandie)
// Un clic sur une étiquette l'ouvre ; un clic ailleurs sur la barre (pas un glisser) la referme
let surEtiquette = false, x0 = 0;
barre.current.on("plotly_click", ev => { surEtiquette = true; courant.current.ouvrir(tries.current[ev.points[0].pointIndex]); });
barre.current.addEventListener("mousedown", e => { x0 = e.clientX; }, true);
barre.current.addEventListener("click", e => {
if (!surEtiquette && Math.abs(e.clientX - x0) < 4) courant.current.ouvrir(null);
surEtiquette = false;
bar.current.on("plotly_deselect", () => setChoice(null));
bar.current.on("plotly_relayout", () => align(bar.current)); // zoomed (Detectors, LLM) or resized alone (the image enlarged)
// A click on a label opens it; a click elsewhere on the bar (not a drag) closes it
let onLabel = false, x0 = 0;
bar.current.on("plotly_click", ev => { onLabel = true; current.current.open(sorted.current[ev.points[0].pointIndex]); });
bar.current.addEventListener("mousedown", e => { x0 = e.clientX; }, true);
bar.current.addEventListener("click", e => {
if (!onLabel && Math.abs(e.clientX - x0) < 4) current.current.open(null);
onLabel = false;
});
setPret(true);
setReady(true);
});
return () => [...Object.values(figs.current), barre.current].forEach(g => g && Plotly.purge(g));
return () => [...Object.values(figs.current), bar.current].forEach(g => g && Plotly.purge(g));
}, [Plotly]);
useEffect(() => { if (pret) dessinePlots().then(() => aligne(barre.current)); }, [vues]);
useEffect(() => { if (pret) dessineBarre(); }, [pret, labels]);
// Glisser sur la barre : sélectionner une plage (Labelling), sinon zoomer dans le temps
useEffect(() => { if (pret) Plotly.relayout(barre.current, { dragmode: lecteur ? "zoom" : "select", selections: [] }); }, [pret, lecteur]);
useEffect(() => { if (pret) dessinePlots(true).then(dessineBarre); }, [sombre]);
useEffect(() => { if (pret) dessinePlots(true); }, [montres]);
useEffect(() => { if (pret) liste().forEach(g => Plotly.relayout(g, { shapes: zones() })); }, [pret, labels, choix, ouverte]);
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]);
useEffect(() => { if (ready) drawPlots(true).then(drawBar); }, [dark]);
useEffect(() => { if (ready) drawPlots(true); }, [shown]);
useEffect(() => { if (ready) plotDivs().forEach(g => Plotly.relayout(g, { shapes: zones() })); }, [ready, labels, choice, opened]);
useEffect(() => {
if (!pret || !barre.current._fullLayout) return;
const k = contour(tries.current);
Plotly.restyle(barre.current, { "marker.line.color": [k.color], "marker.line.width": [k.width] });
}, [ouverte]);
if (!ready || !bar.current._fullLayout) return;
const k = outline(sorted.current);
Plotly.restyle(bar.current, { "marker.line.color": [k.color], "marker.line.width": [k.width] });
}, [opened]);
// Lues à chaque chargement et à chaque changement de source : la page montre toujours le fichier ; les détecteurs tournent
// sur la plage la première fois (une minute ou plus), le serveur garde leur résultat
// Read at each load and at each change of source: the page always shows the file; the detectors run on the range the
// first time (a minute or more), the server keeps their result
useEffect(() => {
let vivant = true;
setLecture(true);
const url = source === "detecteurs" ? `/api/detecteurs?${new URLSearchParams({ station, du, au, cibles })}`
: `/api/etiquettes?${new URLSearchParams({ station, dossier })}`;
appel(url).then(l => {
if (!vivant) return; // une autre source a été choisie entre-temps
setLecture(false); setToutes(l || []);
let alive = true;
setReading(true);
const url = source === "detectors" ? `/api/detectors?${new URLSearchParams({ station, start, end, targets })}`
: `/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 () => { vivant = false; };
}, [source, cibles, rev]);
return () => { alive = false; };
}, [source, targets, rev]);
// Un plot de plus : le premier que la page ne montre pas encore, déplacement vertical d'abord
function ajouterPlot() {
const pris = vues.map(v => v.m), id = prochain.current++;
const m = [indice("Relative Corrected Vertical Shift", 0), ...PLOTS.keys()].find(i => !pris.includes(i)) ?? 0;
setVues([...vues, { id, m }]);
// One more plot: the first one the page does not show yet, vertical displacement first
function addPlot() {
const taken = views.map(v => v.m), id = nextId.current++;
const m = [plotIndex("Relative Corrected Vertical Shift", 0), ...PLOTS.keys()].find(i => !taken.includes(i)) ?? 0;
setViews([...views, { id, m }]);
}
function enleverPlot(id) {
function removePlot(id) {
Plotly.purge(figs.current[id]);
delete figs.current[id]; delete dessines.current[id];
setVues(vues.filter(v => v.id !== id));
delete figs.current[id]; delete drawn.current[id];
setViews(views.filter(v => v.id !== id));
}
const modifiee = () => ouverte && edit && (edit.texte.trim() !== ouverte.description || edit.categorie !== (ouverte.categorie || "")
|| edit.debut + "Z" !== ouverte.debut || edit.fin + "Z" !== ouverte.fin);
const modified = () => opened && edit && (edit.text.trim() !== opened.description || edit.family !== (opened.family || "")
|| edit.start + "Z" !== opened.start || edit.end + "Z" !== opened.end);
// l : l'étiquette à afficher, null pour fermer -> false si Marc garde ses changements non enregistrés
function ouvrir(l) {
if (modifiee() && !confirm("Abandonner les changements de cette étiquette ?")) return false;
setOuverte(l); setNote("");
if (l) caler(l.debut); // un nouvel objet à chaque clic : recliquer le même événement y ramène les images
setEdit(l && !lecteur ? { debut: l.debut.slice(0, 16), fin: l.fin.slice(0, 16), categorie: l.categorie || "", texte: l.description } : null);
// l: the label to show, null to close -> false if Marc keeps his unsaved changes
function open(l) {
if (modified() && !confirm("Discard the changes to this label?")) return false;
setOpened(l); setNote("");
if (l) setImage(l.start); // a new object at each click: clicking the same event again brings the images back to it
setEdit(l && !readOnly ? { start: l.start.slice(0, 16), end: l.end.slice(0, 16), family: l.family || "", text: l.description } : null);
return true;
}
async function analyser() {
const r = await appel("/api/analyses", "POST", { station, debut: choix[0], fin: choix[1], indices });
if (!r) return; // rien n'est perdu : les indices et la plage restent dans la page
setAnalyse(r.nom); setIndices("");
await Plotly.relayout(barre.current, { selections: [] });
setChoix(null);
async function runAnalysis() {
const r = await call("/api/analyses", "POST", { station, start: choice[0], end: choice[1], hints });
if (!r) return; // nothing is lost: the hints and the range stay in the page
setAnalysis(r.name); setHints("");
await Plotly.relayout(bar.current, { selections: [] });
setChoice(null);
}
async function enregistrer() {
const l = await appel("/api/etiquettes", "PUT", { station, dossier, avant: ouverte, debut: edit.debut + "Z", fin: edit.fin + "Z",
categorie: edit.categorie, description: edit.texte.trim() });
if (!l) return; // rien n'est perdu : le texte et les bornes restent dans la fenêtre
setToutes(ls => ls.map(x => (x === ouverte ? l : x)));
setOuverte(l); setNote("Enregistrée");
async function save() {
const l = await call("/api/labels", "PUT", { station, folder, before: opened, start: edit.start + "Z", end: edit.end + "Z",
family: edit.family, description: edit.text.trim() });
if (!l) return; // nothing is lost: the text and the bounds stay in the window
setAllLabels(ls => ls.map(x => (x === opened ? l : x)));
setOpened(l); setNote("Saved");
}
async function supprimer() {
if (!confirm("Supprimer cette étiquette ?")) return;
if (await appel("/api/etiquettes", "DELETE", { station, dossier, avant: ouverte }) === null) return;
setToutes(ls => ls.filter(x => x !== ouverte));
setOuverte(null); setEdit(null);
async function remove() {
if (!confirm("Delete this label?")) return;
if (await call("/api/labels", "DELETE", { station, folder, before: opened }) === null) return;
setAllLabels(ls => ls.filter(x => x !== opened));
setOpened(null); setEdit(null);
}
const options = PLOTS.map((p, i) => ({ value: String(i), label: p.titre }));
const peutEnregistrer = modifiee() && edit.texte.trim() && edit.debut && edit.fin && edit.debut < edit.fin;
const bornes = (champ, plus) => lisible(toutes.reduce((m, l) => (plus(l[champ], m) ? l[champ] : m), toutes[0][champ]));
const options = PLOTS.map((p, i) => ({ value: String(i), label: p.title }));
const canSave = modified() && edit.text.trim() && edit.start && edit.end && edit.start < edit.end;
const extent = (field, beyond) => readable(allLabels.reduce((m, l) => (beyond(l[field], m) ? l[field] : m), allLabels[0][field]));
return (
<Card shadow="sm" withBorder>
<Stack gap="sm">
<div>
{vues.map(v => (
{views.map(v => (
<div key={v.id} className="plot">
<div ref={el => { if (el) figs.current[v.id] = el; }} />
<Group gap={4} wrap="nowrap" className="plot-menu">
<NativeSelect size="xs" aria-label="Plot" data={options} value={String(v.m)} w={300}
onChange={e => { const m = +e.currentTarget.value; setVues(vues.map(x => (x.id === v.id ? { ...x, m } : x))); }} />
{vues.length > 1 && (
<Tooltip label="Enlever ce plot">
<ActionIcon variant="subtle" color="gray" aria-label="Enlever ce plot" onClick={() => enleverPlot(v.id)}><IconX size={16} /></ActionIcon>
onChange={e => { const m = +e.currentTarget.value; setViews(views.map(x => (x.id === v.id ? { ...x, m } : x))); }} />
{views.length > 1 && (
<Tooltip label="Remove this plot">
<ActionIcon variant="subtle" color="gray" aria-label="Remove this plot" onClick={() => removePlot(v.id)}><IconX size={16} /></ActionIcon>
</Tooltip>
)}
</Group>
</div>
))}
{!pret && <Loader size="sm" />}
{!ready && <Loader size="sm" />}
</div>
<Group justify="space-between" gap="sm">
<Group gap="sm">
<SegmentedControl size="xs" data={SOURCES} value={source} onChange={v => { if (ouvrir(null)) { setSource(v); setChoix(null); } }} />
{lecture && <Group gap={6}><Loader size="xs" /><Text size="xs" c="dimmed">{detect ? "Les détecteurs tournent sur la plage…" : "Lecture…"}</Text></Group>}
<SegmentedControl size="xs" data={SOURCES} value={source} onChange={v => { if (open(null)) { setSource(v); setChoice(null); } }} />
{reading && <Group gap={6}><Loader size="xs" /><Text size="xs" c="dimmed">{detect ? "The detectors are running on the range…" : "Reading…"}</Text></Group>}
</Group>
<Button size="xs" variant="light" leftSection={<IconPlus size={14} />} onClick={ajouterPlot} disabled={!pret}>Ajouter un plot</Button>
<Button size="xs" variant="light" leftSection={<IconPlus size={14} />} onClick={addPlot} disabled={!ready}>Add a plot</Button>
</Group>
<div ref={barre} />
{pret && !lecture && !labels.length && ( // sinon une barre vide ne dit pas pourquoi
<Text size="sm" c="orange">{detect ? `Les détecteurs ne trouvent aucun événement sur cette plage${toutes.length ? " dans les familles cochées" : ""}.`
: toutes.length ? `Aucune étiquette dans les familles cochées sur cette plage : celles de ${station} vont du ${bornes("debut", (a, b) => a < b)} au ${bornes("fin", (a, b) => a > b)} UTC.`
: `${station} n'a aucune étiquette dans labeling/${dossier}/.`}</Text>
<div ref={bar} />
{ready && !reading && !labels.length && ( // otherwise an empty bar does not say why
<Text size="sm" c="orange">{detect ? `The detectors find no event in this range${allLabels.length ? " in the checked families" : ""}.`
: allLabels.length ? `No label in the checked families in this range: those of ${station} go from ${extent("start", (a, b) => a < b)} to ${extent("end", (a, b) => a > b)} UTC.`
: `${station} has no label in labeling/${folder}/.`}</Text>
)}
<div>
{!ouverte && lecteur && <Text size="sm" c="dimmed">Cliquer sur un événement pour l'ouvrir.</Text>}
{ouverte && lecteur && (
{!opened && readOnly && <Text size="sm" c="dimmed">Click on an event to open it.</Text>}
{opened && readOnly && (
<Card withBorder bg="var(--mantine-color-default-hover)">
<Stack gap={6}>
<Group gap="xs">
<Badge color={couleur(ouverte)} c="#1a1b1e">{ouverte.categorie}</Badge>
<Text size="sm" fw={500}>{ouverte.sorte}</Text>
{ouverte.ignore && <Badge variant="outline" color="gray">grisé au journal</Badge>}
<Badge color={color(opened)} c="#1a1b1e">{opened.family}</Badge>
<Text size="sm" fw={500}>{opened.kind}</Text>
{opened.ignore && <Badge variant="outline" color="gray">greyed in the journal</Badge>}
</Group>
<Text size="sm" ff="monospace" fw={600}>{lisible(ouverte.debut)} → {lisible(ouverte.fin)} UTC</Text>
{ouverte.message ? <>
<Champ nom="Capteurs">{ouverte.capteurs.length ? <>
{ouverte.cibles.length > 0 && <div>Cibles ({ouverte.cibles.length}) : {ouverte.cibles.join(", ")}</div>}
{ouverte.references.length > 0 && <div>Références ({ouverte.references.length}) : {ouverte.references.join(", ")}</div>}
</> : "tous les capteurs"}</Champ>
<Champ nom="Message">{ouverte.message}</Champ>
<Champ nom="Action">{ouverte.action}</Champ>
</> : <Champ nom="Description">{ouverte.description}</Champ>}
<Text size="sm" ff="monospace" fw={600}>{readable(opened.start)} → {readable(opened.end)} UTC</Text>
{opened.message ? <>
<Field name="Sensors">{opened.sensors.length ? <>
{opened.targets.length > 0 && <div>Targets ({opened.targets.length}): {opened.targets.join(", ")}</div>}
{opened.references.length > 0 && <div>References ({opened.references.length}): {opened.references.join(", ")}</div>}
</> : "all sensors"}</Field>
<Field name="Message">{opened.message}</Field>
<Field name="Action">{opened.action}</Field>
</> : <Field name="Description">{opened.description}</Field>}
<Group>
<Button size="xs" variant="default" onClick={() => ouvrir(null)}>Fermer</Button>
{ouverte.analyse && <Button size="xs" variant="light" onClick={() => setAnalyse(ouverte.analyse)}>Voir le rapport</Button>}
<Button size="xs" variant="default" onClick={() => open(null)}>Close</Button>
{opened.analysis && <Button size="xs" variant="light" onClick={() => setAnalysis(opened.analysis)}>View the report</Button>}
</Group>
</Stack>
</Card>
)}
{ouverte && edit && (
{opened && edit && (
<Card withBorder bg="var(--mantine-color-default-hover)">
<Stack gap="xs">
<Group gap="sm" align="flex-end">
<TextInput label="Du (UTC)" type="datetime-local" step={60} value={edit.debut} onChange={e => setEdit({ ...edit, debut: e.currentTarget.value })} />
<TextInput label="Au (UTC)" type="datetime-local" step={60} value={edit.fin} onChange={e => setEdit({ ...edit, fin: e.currentTarget.value })} />
<NativeSelect label="Famille" data={CHOIX_FAMILLE} value={edit.categorie} onChange={e => setEdit({ ...edit, categorie: e.currentTarget.value })} />
<TextInput label="From (UTC)" type="datetime-local" step={60} value={edit.start} onChange={e => setEdit({ ...edit, start: e.currentTarget.value })} />
<TextInput label="To (UTC)" type="datetime-local" step={60} value={edit.end} onChange={e => setEdit({ ...edit, end: e.currentTarget.value })} />
<NativeSelect label="Family" data={FAMILY_CHOICES} value={edit.family} onChange={e => setEdit({ ...edit, family: e.currentTarget.value })} />
</Group>
<Textarea autosize minRows={3} value={edit.texte} onChange={e => setEdit({ ...edit, texte: e.currentTarget.value })} />
<Textarea autosize minRows={3} value={edit.text} onChange={e => setEdit({ ...edit, text: e.currentTarget.value })} />
<Group gap="sm">
<Button onClick={enregistrer} disabled={!peutEnregistrer}>Enregistrer</Button>
<Button variant="default" onClick={() => ouvrir(null)}>Fermer</Button>
{ouverte.analyse && <Button variant="light" onClick={() => setAnalyse(ouverte.analyse)}>Voir le rapport</Button>}
<Button onClick={save} disabled={!canSave}>Save</Button>
<Button variant="default" onClick={() => open(null)}>Close</Button>
{opened.analysis && <Button variant="light" onClick={() => setAnalysis(opened.analysis)}>View the report</Button>}
<Text size="sm" c="teal">{note}</Text>
<Button color="red" variant="light" ml="auto" onClick={supprimer}>Supprimer</Button>
<Button color="red" variant="light" ml="auto" onClick={remove}>Delete</Button>
</Group>
</Stack>
</Card>
)}
</div>
{!lecteur && <>
<Text size="sm">{choix ? `${lisible(choix[0])} → ${lisible(choix[1])} UTC` : "Glisser sur la barre des étiquettes pour sélectionner la plage à analyser."}</Text>
<Textarea autosize minRows={2} placeholder="Indices pour l'analyste (facultatif) : ce que tu as vu, ce qu'il faut regarder"
value={indices} onChange={e => setIndices(e.currentTarget.value)} />
<Group><Button onClick={analyser} disabled={!(choix && choix[0] < choix[1])}>Analyser la plage</Button></Group>
{!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>
</>}
{analyse && <Analyse key={analyse} nom={analyse} sombre={sombre} fini={() => setRev(r => r + 1)} fermer={() => setAnalyse(null)} />}
{analysis && <Analysis key={analysis} name={analysis} dark={dark} done={() => setRev(r => r + 1)} close={() => setAnalysis(null)} />}
</Stack>
</Card>
);
}
// Le fil d'un agent (analyste, optimisation) : les messages de l'utilisateur (« › ») en gras, le reste en petit, défilé jusqu'en bas
function Fil({ lignes }) {
const fil = useRef();
useEffect(() => { if (fil.current) fil.current.scrollTop = fil.current.scrollHeight; }, [lignes.length]);
if (!lignes.length) return null;
// The thread of an agent (analyst, optimization): the user's messages ("› ") in bold, the rest small, scrolled to the bottom
function Thread({ lines }) {
const thread = useRef();
useEffect(() => { if (thread.current) thread.current.scrollTop = thread.current.scrollHeight; }, [lines.length]);
if (!lines.length) return null;
return (
<div ref={fil} style={{ maxHeight: 260, overflowY: "auto" }}>
{lignes.map((l, i) => l.startsWith("› ")
<div ref={thread} style={{ maxHeight: 260, overflowY: "auto" }}>
{lines.map((l, i) => l.startsWith("› ")
? <Text key={i} size="sm" fw={500} mt={6}>{l}</Text>
: <Text key={i} size="xs" ff="monospace" c="dimmed" style={{ whiteSpace: "pre-wrap" }}>{l}</Text>)}
</div>
);
}
// Un markdown rendu par le serveur (rapport, bilan), à la hauteur de son contenu une fois ses images chargées
function Page({ titre, src }) {
const cadre = useRef();
const ajuste = () => { const b = cadre.current?.contentDocument?.body; if (b) cadre.current.style.height = `${b.scrollHeight + 20}px`; };
return <iframe ref={cadre} title={titre} sandbox="allow-same-origin" onLoad={ajuste} style={{ border: 0, width: "100%", height: 400 }} src={src} />;
// 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 COULEUR_ETAT = { "en cours": "blue", fini: "teal", erreur: "red", interrompue: "orange" };
const STATE_COLOR = { running: "blue", done: "teal", error: "red", interrupted: "orange" };
// Une analyse de l'onglet Analysis : son fil (relu toutes les 3 s tant qu'elle travaille), son rapport, et un message à
// l'analyste, qui reprend sa session ; à la fin de chaque tour, les étiquettes se relisent. Une analyse finie s'optimise
// (/improve d'Optimizer sur la plage de l'analyse, puis le tool-builder) : le fil de la séance, puis ses bilans sous le rapport
function Analyse({ nom, sombre, fini, fermer }) {
const [a, setA] = useState(null), [tour, setTour] = useState(0), [texte, setTexte] = useState("");
const boite = useRef(), charge = !!a;
useEffect(() => { if (charge) boite.current?.scrollIntoView({ behavior: "smooth", block: "start" }); }, [nom, charge]); // ouverte : on la voit
// 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 }) {
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 vivant = true, minuterie;
const lire = () => appel(`/api/analyses/${nom}`).then(r => {
if (!vivant || !r) return;
let alive = true, timer;
const read = () => call(`/api/analyses/${name}`).then(r => {
if (!alive || !r) return;
setA(r);
if (r.etat === "en cours" || r.optimisation?.etat === "en cours") minuterie = setTimeout(lire, 3000);
else if (r.versees !== null) fini();
if (r.state === "running" || r.optimization?.state === "running") timer = setTimeout(read, 3000);
else if (r.submitted !== null) done();
});
lire();
return () => { vivant = false; clearTimeout(minuterie); };
}, [nom, tour]);
async function envoyer() {
if (await appel(`/api/analyses/${nom}/message`, "POST", { texte }) == null) return; // le texte reste dans le champ
setTexte(""); setTour(t => t + 1);
read();
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
setText(""); setTurn(t => t + 1);
}
async function optimiser() {
if (await appel(`/api/analyses/${nom}/optimiser`, "POST") != null) setTour(t => t + 1);
async function optimize() {
if (await call(`/api/analyses/${name}/optimize`, "POST") != null) setTurn(t => t + 1);
}
if (!a) return <Loader size="sm" />;
const d = a.demande, o = a.optimisation, occupe = a.etat === "en cours", optimise = o?.etat === "en cours";
const au = new Date(Date.parse(d.fin.slice(0, 10)) + 864e5).toISOString().slice(0, 10);
const d = a.request, o = a.optimization, busy = a.state === "running", optimizing = o?.state === "running";
const end = new Date(Date.parse(d.end.slice(0, 10)) + 864e5).toISOString().slice(0, 10);
return (
<Card withBorder ref={boite}>
<Card withBorder ref={box}>
<Stack gap="xs">
<Group justify="space-between">
<Group gap="xs">
<Title order={5}>Analyse {lisible(d.debut)} → {lisible(d.fin)} UTC</Title>
<Badge color={COULEUR_ETAT[a.etat] || "gray"}>{a.etat}</Badge>
{occupe && <Loader size="xs" />}
<Title order={5}>Analysis {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.etat === "fini" && <Tooltip label="Améliorer les détecteurs (Optimizer), puis les outils de lecture (tool-builder), depuis cette analyse">
<Button size="xs" variant="light" onClick={optimiser} disabled={optimise}>Optimiser les détecteurs</Button></Tooltip>}
<ActionIcon variant="subtle" color="gray" aria-label="Fermer le rapport" onClick={fermer}><IconX size={16} /></ActionIcon>
{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.indices && <Text size="sm" c="dimmed">Indices : {d.indices}</Text>}
{a.etat === "interrompue" && <Text size="sm" c="orange">Arrêtée avec le serveur avant la fin.{a.dialogue
? " Sa session est gardée : écrire « continue » ci-dessous pour la reprendre là où elle en était." : ""}</Text>}
{a.versees !== null && a.etat === "fini" && <Text size="sm">{a.versees} étiquette(s) de cette analyse dans labeling/auto/{d.station}.jsonl, à relire.</Text>}
{a.rapport && <Page titre="Rapport" src={`/api/analyses/${nom}/rapport.html?sombre=${sombre}&v=${a.rapport}`} />}
<Fil lignes={a.lignes} />
{d.hints && <Text size="sm" c="dimmed">Hints: {d.hints}</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}`} />}
<Thread lines={a.lines} />
{a.dialogue && (
<Group align="flex-end" gap="sm" wrap="nowrap">
<Textarea autosize minRows={1} style={{ flex: 1 }} placeholder="Une question, une correction pour l'analyste"
value={texte} onChange={e => setTexte(e.currentTarget.value)} />
<Button onClick={envoyer} disabled={occupe || optimise || !texte.trim()}>Envoyer</Button>
<Textarea autosize minRows={1} style={{ flex: 1 }} placeholder="A question, a correction for the analyst"
value={text} onChange={e => setText(e.currentTarget.value)} />
<Button onClick={send} disabled={busy || optimizing || !text.trim()}>Send</Button>
</Group>
)}
{o && (
<Stack gap="xs" mt="sm">
<Group gap="xs">
<Title order={5}>Optimisation</Title>
<Badge color={COULEUR_ETAT[o.etat] || "gray"}>{o.etat}</Badge>
{optimise && <Loader size="xs" />}
<Title order={5}>Optimization</Title>
<Badge color={STATE_COLOR[o.state] || "gray"}>{o.state}</Badge>
{optimizing && <Loader size="xs" />}
</Group>
{o.etat === "interrompue" && <Text size="sm" c="orange">Arrêtée avec le serveur ; la relancer par le bouton.</Text>}
<Fil lignes={o.lignes} />
{o.bilan && <Page titre="Bilan" src={`/api/analyses/${nom}/bilan.html?sombre=${sombre}&v=${o.bilan}`} />}
{o.bilan && <Text size="xs" c="dimmed" ff="monospace">python3 detectors/bench/score.py data/{d.station} --labels labeling/auto/{d.station}.jsonl --from {d.debut.slice(0, 10)} --to {au}</Text>}
{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>}
</Stack>
)}
<Text size="xs" c="dimmed">labeling/auto/analyses/{nom}/</Text>
<Text size="xs" c="dimmed">labeling/auto/analyses/{name}/</Text>
</Stack>
</Card>
);
+141 -141
View File
@@ -1,240 +1,240 @@
import { useEffect, useRef, useState } from "react";
import { ActionIcon, Card, Group, Input, Loader, Stack, Text, Tooltip } from "@mantine/core";
import { IconArrowLeft, IconArrowRight, IconChevronLeft, IconChevronRight } from "@tabler/icons-react";
import { appel } from "../commun.jsx";
import { call } from "../common.jsx";
// Les images de la station et de la plage choisies ; compacte : à la largeur d'une colonne (page Data), au format de l'image ;
// basculer : la flèche qui agrandit l'image vers la gauche (large) ou la ramène ; instant {t} : montrer la première image à t ou après
// ({t, proche} : la plus proche de t, avant ou après)
export function ImagesDe({ selection, compacte, large, basculer, instant }) {
const [donnees, setDonnees] = useState(null), [charge, setCharge] = useState(false);
const { station, du, au } = selection;
// The images of the chosen station and range; compact: the width of a column (Data page), in the format of the image;
// toggle: the arrow that enlarges the image to the left (wide) or brings it back; moment {t}: show the first image at t or
// after ({t, nearest}: the nearest to t, before or after)
export function StationImages({ selection, compact, wide, toggle, moment }) {
const [data, setData] = useState(null), [loading, setLoading] = useState(false);
const { station, start, end } = selection;
useEffect(() => {
setDonnees(null);
setData(null);
if (!station) return;
setCharge(true);
appel(`/api/images?${new URLSearchParams({ station, du, au })}`).then(d => { setDonnees(d); setCharge(false); });
}, [station, du, au]);
if (charge) return <Loader />;
if (donnees && !donnees.images.length) return <Text size="sm" c="dimmed">Aucune image de {station} sur cette plage.</Text>;
return donnees && <Visionneuse key={`${station}${du}${au}`} station={station} d={donnees} compacte={compacte} large={large} basculer={basculer} instant={instant} />;
setLoading(true);
call(`/api/images?${new URLSearchParams({ station, start, end })}`).then(d => { setData(d); setLoading(false); });
}, [station, start, end]);
if (loading) return <Loader />;
if (data && !data.images.length) return <Text size="sm" c="dimmed">No image of {station} in this range.</Text>;
return data && <Viewer key={`${station}${start}${end}`} station={station} d={data} compact={compact} wide={wide} toggle={toggle} moment={moment} />;
}
function Visionneuse({ station, d, compacte, large, basculer, instant }) {
const r = { cadre: useRef(), couche: useRef(), img: useRef(), marques: useRef(), vecteurs: useRef(), glis: useRef(),
heure: useRef(), noms: useRef(), barre: useRef(), bande: useRef(), plage: useRef(), echelle: useRef(),
prec: useRef(), suiv: useRef(), montre: useRef() };
const XY = d.positions, refs = new Set(d.references), avecPositions = Object.keys(XY).length > 0;
function Viewer({ station, d, compact, wide, toggle, moment }) {
const r = { frame: useRef(), layer: useRef(), img: useRef(), marks: useRef(), vectors: useRef(), slider: useRef(),
time: useRef(), names: useRef(), bar: useRef(), band: useRef(), range: useRef(), scale: useRef(),
prev: useRef(), next: useRef(), show: useRef() };
const XY = d.positions, refs = new Set(d.references), withPositions = Object.keys(XY).length > 0;
useEffect(() => installer(r, station, d), [d]);
useEffect(() => { // « AAAA-MM-JJTHH:MMZ » face aux heures des images, « AAAA-MM-JJ HH:MM » (UTC)
if (!instant) return;
const t = instant.t.slice(0, 16).replace("T", " "), i = d.images.findIndex(im => im.t >= t);
const ms = s => Date.parse(s.slice(0, 16).replace(" ", "T") + "Z"), ecart = j => Math.abs(ms(d.images[j].t) - ms(t));
if (instant.proche && i !== 0) r.montre.current(i < 0 || ecart(i - 1) <= ecart(i) ? (i < 0 ? d.images.length : i) - 1 : i);
else r.montre.current(i < 0 ? d.images.length - 1 : i);
}, [instant, d]);
useEffect(() => install(r, station, d), [d]);
useEffect(() => { // "YYYY-MM-DDTHH:MMZ" against the times of the images, "YYYY-MM-DD HH:MM" (UTC)
if (!moment) return;
const t = moment.t.slice(0, 16).replace("T", " "), i = d.images.findIndex(im => im.t >= t);
const ms = s => Date.parse(s.slice(0, 16).replace(" ", "T") + "Z"), gap = j => Math.abs(ms(d.images[j].t) - ms(t));
if (moment.nearest && i !== 0) r.show.current(i < 0 || gap(i - 1) <= gap(i) ? (i < 0 ? d.images.length : i) - 1 : i);
else r.show.current(i < 0 ? d.images.length - 1 : i);
}, [moment, d]);
return (
<Card shadow="sm" withBorder padding={0} className="visionneuse">
{basculer && (
<Tooltip label={large ? "Réduire l'image" : "Agrandir l'image"}>
<ActionIcon className="agrandir" variant="filled" color="dark" aria-label={large ? "Réduire l'image" : "Agrandir l'image"} onClick={basculer}>
{large ? <IconArrowRight size={18} /> : <IconArrowLeft size={18} />}
<Card shadow="sm" withBorder padding={0} className="viewer">
{toggle && (
<Tooltip label={wide ? "Shrink the image" : "Enlarge the image"}>
<ActionIcon className="enlarge" variant="filled" color="dark" aria-label={wide ? "Shrink the image" : "Enlarge the image"} onClick={toggle}>
{wide ? <IconArrowRight size={18} /> : <IconArrowLeft size={18} />}
</ActionIcon>
</Tooltip>
)}
<div className={compacte ? "cadre compacte" : "cadre"} ref={r.cadre}>
<div className="couche" ref={r.couche}>
<div className={compact ? "frame compact" : "frame"} ref={r.frame}>
<div className="layer" ref={r.layer}>
<img ref={r.img} alt="" draggable="false" />
<svg className="marques" ref={r.marques} style={{ display: "none" }}>
<svg className="marks" ref={r.marks} style={{ display: "none" }}>
{Object.entries(XY).map(([s, [x, y]]) => (
<g key={s} className={refs.has(s) ? "ref" : "cible"}>
<g key={s} className={refs.has(s) ? "ref" : "target"}>
<circle cx={x} cy={y} r=".7em" /><text x={x} y={y} dy="-1em">{s}</text>
</g>
))}
</svg>
<svg className="vecteurs" ref={r.vecteurs} style={{ display: "none" }}>
<defs><marker id="pointe" viewBox="0 0 10 14" refX="9" refY="7" markerWidth="5" markerHeight="7" orient="auto">
<svg className="vectors" ref={r.vectors} style={{ display: "none" }}>
<defs><marker id="arrowhead" viewBox="0 0 10 14" refX="9" refY="7" markerWidth="5" markerHeight="7" orient="auto">
<path d="M0,0 L10,7 L0,14 z" fill="#2ecc40" /></marker></defs>
</svg>
</div>
</div>
<Stack gap={6} p="md">
<Group gap="sm" wrap="nowrap">
<ActionIcon ref={r.prec} variant="light" aria-label="Image précédente"><IconChevronLeft size={18} /></ActionIcon>
<input ref={r.glis} className="glisseur" type="range" min="0" max={d.images.length - 1} defaultValue="0" />
<ActionIcon ref={r.suiv} variant="light" aria-label="Image suivante"><IconChevronRight size={18} /></ActionIcon>
<ActionIcon ref={r.prev} variant="light" aria-label="Previous image"><IconChevronLeft size={18} /></ActionIcon>
<input ref={r.slider} className="slider" type="range" min="0" max={d.images.length - 1} defaultValue="0" />
<ActionIcon ref={r.next} variant="light" aria-label="Next image"><IconChevronRight size={18} /></ActionIcon>
</Group>
<div className="barre-plages" ref={r.barre}><div className="bande" ref={r.bande} style={{ display: "none" }} /></div>
<div className="range-bar" ref={r.bar}><div className="band" ref={r.band} style={{ display: "none" }} /></div>
<Group gap="lg" justify="space-between">
<Text ref={r.heure} ff="monospace" size="sm" />
<Text ref={r.time} ff="monospace" size="sm" />
<Group gap="md">
<label className="case"><input type="checkbox" ref={r.noms} disabled={!avecPositions} /> Noms</label>
{avecPositions
? <span className="legende"><span className="cible">○ Cible</span> <span className="ref">◌ Référence</span></span>
: <Text size="sm" c="dimmed">x, y ne sont pas des positions dans l'image sur cette station</Text>}
<label className="check"><input type="checkbox" ref={r.names} disabled={!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>}
</Group>
</Group>
<Group gap="lg" justify="space-between">
<Text ref={r.plage} size="sm" />
<Text ref={r.range} size="sm" />
<Group gap="xs" wrap="nowrap">
<Text size="sm">Flèches ×</Text>
<Input ref={r.echelle} type="number" min={1} defaultValue={100} w={90} size="xs" />
<Text size="sm">Arrows ×</Text>
<Input ref={r.scale} type="number" min={1} defaultValue={100} w={90} size="xs" />
</Group>
</Group>
<Text size="xs" c="dimmed">← → image · molette : zoom · glisser : se déplacer · double clic : image entière · flèche :
corr_x, corr_y à la fin moins au début (px), dans les axes de l'image</Text>
<Text size="xs" c="dimmed">← → image · wheel: zoom · drag: move · double click: whole image · arrow:
corr_x, corr_y at the end minus at the start (px), in the axes of the image</Text>
</Stack>
</Card>
);
}
// Le comportement de l'image (zoom, déplacement, flèches), sur les éléments de la page -> la fonction qui défait ce qu'il a installé
function installer(r, station, d) {
const IM = d.images.map(i => ({ t: i.t, src: `/api/image/${encodeURIComponent(station)}/${encodeURIComponent(i.nom)}` }));
// The behaviour of the image (zoom, move, arrows), on the elements of the page -> the function that undoes what it installed
function install(r, station, d) {
const IM = d.images.map(i => ({ t: i.t, src: `/api/image/${encodeURIComponent(station)}/${encodeURIComponent(i.name)}` }));
const C = d.corr, XY = d.positions;
const cadre = r.cadre.current, couche = r.couche.current, img = r.img.current, glis = r.glis.current, heure = r.heure.current;
const marques = r.marques.current, vecteurs = r.vecteurs.current, labels = r.noms.current;
const barre = r.barre.current, bande = r.bande.current, plage = r.plage.current, echelle = r.echelle.current;
const frame = r.frame.current, layer = r.layer.current, img = r.img.current, slider = r.slider.current, time = r.time.current;
const marks = r.marks.current, vectors = r.vectors.current, labels = r.names.current;
const bar = r.bar.current, band = r.band.current, range = r.range.current, scale = r.scale.current;
let V = 0, Z = { k: 1, x: 0, y: 0 }, P = null;
function zoom() {
Z.x = Math.min(0, Math.max(1 - Z.k, Z.x)); // l'image couvre toujours le cadre : on ne la perd pas en la glissant
Z.x = Math.min(0, Math.max(1 - Z.k, Z.x)); // the image always covers the frame: it is not lost by dragging it
Z.y = Math.min(0, Math.max(1 - Z.k, Z.y));
couche.style.transform = `translate(${Z.x * 100}%, ${Z.y * 100}%) scale(${Z.k})`;
// Les noms restent à 12 px à l'écran : les tailles des marques sont en em, et 1 px du svg vaut 1 px de l'image.
layer.style.transform = `translate(${Z.x * 100}%, ${Z.y * 100}%) scale(${Z.k})`;
// The names stay at 12 px on screen: the sizes of the marks are in em, and 1 px of the svg is 1 px of the image.
const W = img.naturalWidth, H = img.naturalHeight;
if (W) marques.style.fontSize = vecteurs.style.fontSize = `${12 / (Z.k * Math.min(cadre.clientWidth / W, cadre.clientHeight / H))}px`;
cale();
if (W) marks.style.fontSize = vectors.style.fontSize = `${12 / (Z.k * Math.min(frame.clientWidth / W, frame.clientHeight / H))}px`;
align();
}
const affiche = () => { marques.style.display = labels.checked && img.naturalWidth ? "" : "none"; };
labels.onchange = affiche;
r.montre.current = i => montre(i); // pour la page Data : l'image du début d'un événement
const display = () => { marks.style.display = labels.checked && img.naturalWidth ? "" : "none"; };
labels.onchange = display;
r.show.current = i => show(i); // for the Data page: the image of the start of an event
function montre(i) {
function show(i) {
V = Math.max(0, Math.min(IM.length - 1, i));
glis.value = V;
slider.value = V;
img.src = IM[V].src;
for (const n of [V - 1, V + 1]) if (IM[n]) new Image().src = IM[n].src; // les voisines, en cache
for (const n of [V - 1, V + 1]) if (IM[n]) new Image().src = IM[n].src; // the neighbours, in cache
}
// L'heure change avec l'image, pas avant : l'image d'avant reste affichée tant que la nouvelle se charge.
// The time changes with the image, not before: the previous image stays shown while the new one loads.
img.onload = () => {
heure.textContent = `${IM[V].t} UTC (${V + 1}/${IM.length})`;
marques.setAttribute("viewBox", `0 0 ${img.naturalWidth} ${img.naturalHeight}`); // cadré comme l'image, object-fit: contain
vecteurs.setAttribute("viewBox", marques.getAttribute("viewBox"));
fleches(); zoom(); affiche();
time.textContent = `${IM[V].t} UTC (${V + 1}/${IM.length})`;
marks.setAttribute("viewBox", `0 0 ${img.naturalWidth} ${img.naturalHeight}`); // framed as the image, object-fit: contain
vectors.setAttribute("viewBox", marks.getAttribute("viewBox"));
arrows(); zoom(); display();
};
img.onerror = () => {
img.removeAttribute("src");
heure.textContent = `${IM[V].t} UTC (${V + 1}/${IM.length}) : image illisible`;
affiche();
time.textContent = `${IM[V].t} UTC (${V + 1}/${IM.length}): unreadable image`;
display();
};
glis.oninput = () => montre(+glis.value);
r.prec.current.onclick = () => montre(V - 1);
r.suiv.current.onclick = () => montre(V + 1);
const clavier = e => {
if (!glis.offsetParent // la page Data cachée (une autre page affichée) : les flèches ne sont pas pour elle
slider.oninput = () => show(+slider.value);
r.prev.current.onclick = () => show(V - 1);
r.next.current.onclick = () => show(V + 1);
const keyboard = e => {
if (!slider.offsetParent // the Data page hidden (another page shown): the arrows are not for it
|| e.target.matches("textarea, select, input:not([type=range])") || !["ArrowLeft", "ArrowRight"].includes(e.key)) return;
e.preventDefault(); // sinon le glisseur, s'il a le focus, avance une seconde fois
montre(V + (e.key === "ArrowLeft" ? -1 : 1));
e.preventDefault(); // otherwise the slider, if it has the focus, moves a second time
show(V + (e.key === "ArrowLeft" ? -1 : 1));
};
document.addEventListener("keydown", clavier);
document.addEventListener("keydown", keyboard);
const molette = ev => { // zoom autour du pointeur
const wheel = ev => { // zoom around the pointer
ev.preventDefault();
const b = cadre.getBoundingClientRect(), u = (ev.clientX - b.left) / b.width, v = (ev.clientY - b.top) / b.height;
const b = frame.getBoundingClientRect(), u = (ev.clientX - b.left) / b.width, v = (ev.clientY - b.top) / b.height;
const k = Math.min(40, Math.max(1, Z.k * Math.exp(-ev.deltaY / 500)));
Z = { k, x: u - k * (u - Z.x) / Z.k, y: v - k * (v - Z.y) / Z.k };
zoom();
};
cadre.addEventListener("wheel", molette, { passive: false });
cadre.onpointerdown = ev => { // déplacement à la souris
cadre.setPointerCapture(ev.pointerId);
const b = cadre.getBoundingClientRect(), de = { ...Z, cx: ev.clientX, cy: ev.clientY };
cadre.onpointermove = e => { Z.x = de.x + (e.clientX - de.cx) / b.width; Z.y = de.y + (e.clientY - de.cy) / b.height; zoom(); };
cadre.onpointerup = () => { cadre.onpointermove = null; };
frame.addEventListener("wheel", wheel, { passive: false });
frame.onpointerdown = ev => { // move with the mouse
frame.setPointerCapture(ev.pointerId);
const b = frame.getBoundingClientRect(), from = { ...Z, cx: ev.clientX, cy: ev.clientY };
frame.onpointermove = e => { Z.x = from.x + (e.clientX - from.cx) / b.width; Z.y = from.y + (e.clientY - from.cy) / b.height; zoom(); };
frame.onpointerup = () => { frame.onpointermove = null; };
};
cadre.ondblclick = () => { Z = { k: 1, x: 0, y: 0 }; zoom(); };
frame.ondblclick = () => { Z = { k: 1, x: 0, y: 0 }; zoom(); };
// La plage : glisser sur la barre, alignée sur le glisseur ; les flèches vont de la position du capteur à position + k × déplacement.
function cale() {
const g = glis.getBoundingClientRect(), b = barre.getBoundingClientRect();
barre.style.marginLeft = `${(parseFloat(barre.style.marginLeft) || 0) + g.left - b.left}px`; barre.style.width = `${g.width}px`;
// The range: drag on the bar, aligned with the slider; the arrows go from the position of the sensor to position + k × displacement.
function align() {
const g = slider.getBoundingClientRect(), b = bar.getBoundingClientRect();
bar.style.marginLeft = `${(parseFloat(bar.style.marginLeft) || 0) + g.left - b.left}px`; bar.style.width = `${g.width}px`;
}
const indice = ev => { const b = barre.getBoundingClientRect(); return Math.round(Math.max(0, Math.min(1, (ev.clientX - b.left) / b.width)) * (IM.length - 1)); };
function bandeau() {
const index = ev => { const b = bar.getBoundingClientRect(); return Math.round(Math.max(0, Math.min(1, (ev.clientX - b.left) / b.width)) * (IM.length - 1)); };
function drawBand() {
const n = Math.max(1, IM.length - 1), [i, j] = P ? [Math.min(...P), Math.max(...P)] : [0, 0];
bande.style.left = `${i / n * 100}%`; bande.style.width = `${(j - i) / n * 100}%`; bande.style.display = P ? "" : "none";
band.style.left = `${i / n * 100}%`; band.style.width = `${(j - i) / n * 100}%`; band.style.display = P ? "" : "none";
}
function deplacements() {
function displacements() {
if (!P || P[0] === P[1]) return {};
const [i, j] = [Math.min(...P), Math.max(...P)], dep = {};
for (const [s, c] of Object.entries(C)) if (c[i] && c[j]) dep[s] = [c[j][0] - c[i][0], c[j][1] - c[i][1]];
return dep;
}
function fleches() {
const dep = deplacements(), W = img.naturalWidth, k = +echelle.value;
vecteurs.style.display = Object.keys(dep).length && W ? "" : "none";
vecteurs.querySelectorAll("line").forEach(l => l.remove());
function arrows() {
const dep = displacements(), W = img.naturalWidth, k = +scale.value;
vectors.style.display = Object.keys(dep).length && W ? "" : "none";
vectors.querySelectorAll("line").forEach(l => l.remove());
for (const [s, [dx, dy]] of Object.entries(dep)) {
const [x, y] = XY[s], l = document.createElementNS("http://www.w3.org/2000/svg", "line");
Object.entries({ x1: x, y1: y, x2: x + k * dx, y2: y + k * dy }).forEach(([a, v]) => l.setAttribute(a, v));
const titre = document.createElementNS("http://www.w3.org/2000/svg", "title");
titre.textContent = `${s} : corr_x ${dx.toFixed(3)} px, corr_y ${dy.toFixed(3)} px`;
l.appendChild(titre);
vecteurs.appendChild(l);
const title = document.createElementNS("http://www.w3.org/2000/svg", "title");
title.textContent = `${s}: corr_x ${dx.toFixed(3)} px, corr_y ${dy.toFixed(3)} px`;
l.appendChild(title);
vectors.appendChild(l);
}
if (P && P[0] !== P[1]) {
const [i, j] = [Math.min(...P), Math.max(...P)], manque = Object.keys(C).filter(s => !(s in dep));
plage.textContent = `${IM[i].t} → ${IM[j].t} UTC` + (manque.length ? ` · pas de mesure valide à une borne : ${manque.join(", ")}` : "");
} else plage.textContent = Object.keys(C).length ? "Glisser sur la barre pour choisir une plage" : "Pas de flèches : x, y ne sont pas des positions dans l'image";
const [i, j] = [Math.min(...P), Math.max(...P)], missing = Object.keys(C).filter(s => !(s in dep));
range.textContent = `${IM[i].t} → ${IM[j].t} UTC` + (missing.length ? ` · no valid measurement at a bound: ${missing.join(", ")}` : "");
} else range.textContent = Object.keys(C).length ? "Drag on the bar to choose a range" : "No arrows: x, y are not positions in the image";
}
// Ce que saisit le pointeur sur une plage placée : 0 son début, 1 sa fin (à 6 px près), 2 la bande entière, null rien.
function prise(ev) {
// What the pointer grabs on a placed range: 0 its start, 1 its end (within 6 px), 2 the whole band, null nothing.
function grab(ev) {
if (!P) return null;
const x = ev.clientX - barre.getBoundingClientRect().left, px = i => i / Math.max(1, IM.length - 1) * barre.clientWidth;
const x = ev.clientX - bar.getBoundingClientRect().left, px = i => i / Math.max(1, IM.length - 1) * bar.clientWidth;
return Math.abs(x - px(P[0])) < 6 ? 0 : Math.abs(x - px(P[1])) < 6 ? 1 : x > px(P[0]) && x < px(P[1]) ? 2 : null;
}
barre.onpointermove = e => {
if (!barre.hasPointerCapture(e.pointerId)) barre.style.cursor = ["ew-resize", "ew-resize", "grab"][prise(e)] || "crosshair";
bar.onpointermove = e => {
if (!bar.hasPointerCapture(e.pointerId)) bar.style.cursor = ["ew-resize", "ew-resize", "grab"][grab(e)] || "crosshair";
};
barre.onpointerdown = ev => {
barre.setPointerCapture(ev.pointerId);
const g = prise(ev), i0 = indice(ev), de = P && [...P];
bar.onpointerdown = ev => {
bar.setPointerCapture(ev.pointerId);
const g = grab(ev), i0 = index(ev), from = P && [...P];
if (g === null) P = [i0, i0];
bandeau(); montre(i0);
const survol = barre.onpointermove;
barre.onpointermove = e => {
const i = indice(e);
if (g === 2) { // la bande glisse sans sortir de la barre
const dd = Math.max(-de[0], Math.min(IM.length - 1 - de[1], i - i0));
P = [de[0] + dd, de[1] + dd];
drawBand(); show(i0);
const hover = bar.onpointermove;
bar.onpointermove = e => {
const i = index(e);
if (g === 2) { // the band slides without leaving the bar
const dd = Math.max(-from[0], Math.min(IM.length - 1 - from[1], i - i0));
P = [from[0] + dd, from[1] + dd];
} else P[g === null ? 1 : g] = i;
bandeau(); fleches(); montre(i);
drawBand(); arrows(); show(i);
};
barre.onpointerup = () => {
barre.onpointermove = survol;
bar.onpointerup = () => {
bar.onpointermove = hover;
P = [Math.min(...P), Math.max(...P)];
if (P[0] === P[1]) P = null;
else if (g === null) { // nouvelle plage, facteur proposé : la plus grande flèche fait 8 % de la largeur de l'image
const m = Math.max(...Object.values(deplacements()).map(([a, b]) => Math.hypot(a, b)), 0);
if (m && img.naturalWidth) echelle.value = Math.max(1, Math.round(0.08 * img.naturalWidth / m));
else if (g === null) { // new range, proposed factor: the largest arrow is 8 % of the width of the image
const m = Math.max(...Object.values(displacements()).map(([a, b]) => Math.hypot(a, b)), 0);
if (m && img.naturalWidth) scale.value = Math.max(1, Math.round(0.08 * img.naturalWidth / m));
}
bandeau(); fleches();
drawBand(); arrows();
};
};
echelle.oninput = fleches;
scale.oninput = arrows;
addEventListener("resize", zoom);
const observateur = new ResizeObserver(zoom); // la barre latérale qui se replie change la largeur sans resize
observateur.observe(cadre);
const observer = new ResizeObserver(zoom); // the sidebar that folds changes the width without resize
observer.observe(frame);
montre(0); cale(); fleches();
show(0); align(); arrows();
return () => {
document.removeEventListener("keydown", clavier);
document.removeEventListener("keydown", keyboard);
removeEventListener("resize", zoom);
cadre.removeEventListener("wheel", molette);
observateur.disconnect();
frame.removeEventListener("wheel", wheel);
observer.disconnect();
};
}
+29 -35
View File
@@ -1,39 +1,33 @@
/* Le reste du visuel vient de Mantine (thème dans main.jsx) */
.entete { background: #3d4977; color: #fff; border-bottom: 0; }
.message { white-space: pre-wrap; overflow-wrap: anywhere; }
.message.support, .message.relai { background: var(--mantine-color-aimsight-light); }
.message.analyste { background: var(--mantine-color-teal-light); }
.message.marc { background: var(--mantine-color-yellow-light); align-self: flex-end; max-width: 85%; }
.message.relai { border-left: 3px solid var(--mantine-color-aimsight-filled); }
.rapport { width: 100%; height: 78vh; border: 0; display: block; background: #fff; }
/* The rest of the visuals comes from Mantine (theme in main.jsx) */
.header { background: #3d4977; color: #fff; border-bottom: 0; }
/* Les images de la caméra (Images.jsx) */
.cadre { position: relative; height: calc(100vh - 420px); min-height: 300px; background: #000; overflow: hidden; cursor: grab;
/* The camera images (Images.jsx) */
.frame { position: relative; height: calc(100vh - 420px); min-height: 300px; background: #000; overflow: hidden; cursor: grab;
touch-action: none; border-radius: var(--mantine-radius-md) var(--mantine-radius-md) 0 0; }
.cadre:active { cursor: grabbing; }
.cadre.compacte { height: auto; min-height: 0; aspect-ratio: 3 / 2; } /* page Data : la colonne de droite */
.couche { position: absolute; inset: 0; transform-origin: 0 0; }
.couche > * { position: absolute; inset: 0; width: 100%; height: 100%; }
.couche img { object-fit: contain; user-select: none; }
.marques { overflow: visible; pointer-events: none; font-family: sans-serif; }
.marques circle { fill: none; stroke: currentColor; stroke-width: .12em; }
.marques .ref circle { stroke-dasharray: .3em .2em; }
.marques text { fill: currentColor; text-anchor: middle; paint-order: stroke; stroke: rgba(0, 0, 0, .85); stroke-width: .25em; stroke-linejoin: round; }
.cible { color: #ffd400; } .ref { color: #3cc8ff; }
.legende { background: #000; padding: 2px 8px; border-radius: 3px; white-space: nowrap; font-size: var(--mantine-font-size-sm); }
.vecteurs { overflow: visible; pointer-events: none; }
.vecteurs line { stroke: #2ecc40; stroke-width: .18em; marker-end: url(#pointe); }
.glisseur { flex: 1; min-width: 0; accent-color: var(--mantine-primary-color-filled); }
.barre-plages { position: relative; height: 22px; background: var(--mantine-color-default-hover); border: 1px solid var(--mantine-color-default-border);
border-radius: 3px; cursor: crosshair; touch-action: none; }
.bande { position: absolute; top: 0; bottom: 0; background: #e0730080; border-left: 2px solid #e07300; border-right: 2px solid #e07300; }
.case { display: flex; gap: 6px; align-items: center; font-size: var(--mantine-font-size-sm); }
/* page Data : le menu d'un plot dans sa marge du haut ; les images restent en vue quand on fait défiler les plots */
.frame:active { cursor: grabbing; }
.frame.compact { height: auto; min-height: 0; aspect-ratio: 3 / 2; } /* Data page: the right column */
.layer { position: absolute; inset: 0; transform-origin: 0 0; }
.layer > * { position: absolute; inset: 0; width: 100%; height: 100%; }
.layer img { object-fit: contain; user-select: none; }
.marks { overflow: visible; pointer-events: none; font-family: sans-serif; }
.marks circle { fill: none; stroke: currentColor; stroke-width: .12em; }
.marks .ref circle { stroke-dasharray: .3em .2em; }
.marks text { fill: currentColor; text-anchor: middle; paint-order: stroke; stroke: rgba(0, 0, 0, .85); stroke-width: .25em; stroke-linejoin: round; }
.target { color: #ffd400; } .ref { color: #3cc8ff; }
.legend { background: #000; padding: 2px 8px; border-radius: 3px; white-space: nowrap; font-size: var(--mantine-font-size-sm); }
.vectors { overflow: visible; pointer-events: none; }
.vectors line { stroke: #2ecc40; stroke-width: .18em; marker-end: url(#arrowhead); }
.slider { flex: 1; min-width: 0; accent-color: var(--mantine-primary-color-filled); }
.range-bar { position: relative; height: 22px; background: var(--mantine-color-default-hover); border: 1px solid var(--mantine-color-default-border);
border-radius: 3px; cursor: crosshair; touch-action: none; }
.band { position: absolute; top: 0; bottom: 0; background: #e0730080; border-left: 2px solid #e07300; border-right: 2px solid #e07300; }
.check { display: flex; gap: 6px; align-items: center; font-size: var(--mantine-font-size-sm); }
/* Data page: the menu of a plot in its top margin; the images stay in view when the plots scroll */
.plot { position: relative; }
.plot-menu { position: absolute; top: 2px; left: 56px; z-index: 2; }
.colle { position: sticky; top: calc(64px + var(--mantine-spacing-lg)); }
/* page Data : la flèche qui agrandit l'image, en haut à gauche de l'image (du côté des plots qu'elle pousse) */
.visionneuse { position: relative; }
.agrandir { position: absolute; top: 8px; left: 8px; z-index: 3; opacity: .75; }
.agrandir:hover { opacity: 1; }
.data-grille .mantine-Grid-col { transition: flex-basis .35s ease, max-width .35s ease; min-width: 0; } /* l'image qui grandit pousse les plots */
.sticky { position: sticky; top: calc(64px + var(--mantine-spacing-lg)); }
/* Data page: the arrow that enlarges the image, at the top left of the image (on the side of the plots it pushes) */
.viewer { position: relative; }
.enlarge { position: absolute; top: 8px; left: 8px; z-index: 3; opacity: .75; }
.enlarge:hover { opacity: 1; }
.data-grid .mantine-Grid-col { transition: flex-basis .35s ease, max-width .35s ease; min-width: 0; } /* the image that grows pushes the plots */
+1 -1
View File
@@ -1,7 +1,7 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// npm run dev : la page sur http://localhost:5173, l'API demandée au serveur Python (port 8770)
// npm run dev: the page on http://localhost:5173, the API asked of the Python server (port 8770)
export default defineConfig({
plugins: [react()],
server: { proxy: { "/api": "http://127.0.0.1:8770" } },