app/: the Labeling page becomes Data, back to a restyled Plotly, one plot to start and more to add (D-139)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2f0947fe03
commit
ebb60e7e3c
14 files changed
+323
-288
No files matched your search
+5
-5
@@ -7,8 +7,8 @@ import { IconChartLine, IconMessages, IconMoon, IconPhoto, IconSun } from "@tabl
|
||||
import Support, { AGENTS, Etat, NOMS } from "./pages/Support.jsx";
|
||||
import Images from "./pages/Images.jsx";
|
||||
|
||||
const Etiquetage = lazy(() => import("./pages/Etiquetage.jsx")); // ECharts, chargé seulement ici
|
||||
const PAGES = [["support", "Support", IconMessages], ["images", "Images", IconPhoto], ["etiquetage", "Étiquetage", IconChartLine]];
|
||||
const Data = lazy(() => import("./pages/Data.jsx")); // Plotly, chargé seulement ici
|
||||
const PAGES = [["support", "Support", IconMessages], ["images", "Images", IconPhoto], ["data", "Data", IconChartLine]];
|
||||
|
||||
// L'adresse : #/<page>?station=…&du=…&au=… ; recharger garde la page et la sélection, Retour marche
|
||||
function lireAdresse() {
|
||||
@@ -77,7 +77,7 @@ export default function App() {
|
||||
const [evenements, setEvenements] = useState([]);
|
||||
const [mobile, { toggle: basculerMobile, close: fermerMobile }] = useDisclosure(false);
|
||||
const [bureau, { toggle: basculerBureau }] = useDisclosure(true);
|
||||
// La dernière station et plage vues, pour revenir à Images ou Étiquetage depuis Support
|
||||
// La dernière station et plage vues, pour revenir à Images ou Data depuis Support
|
||||
const [derniere, setDerniere] = useState(selection);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -108,8 +108,8 @@ export default function App() {
|
||||
<AppShell.Main bg="var(--mantine-color-default-hover)">
|
||||
{page === "support" && <Support etat={etat} evenements={evenements} />}
|
||||
{page === "images" && <Images selection={selection} choisir={choisir} />}
|
||||
{page === "etiquetage" && (
|
||||
<Suspense fallback={<Loader m="xl" />}><Etiquetage selection={selection} choisir={choisir} /></Suspense>
|
||||
{page === "data" && (
|
||||
<Suspense fallback={<Loader m="xl" />}><Data selection={selection} choisir={choisir} /></Suspense>
|
||||
)}
|
||||
</AppShell.Main>
|
||||
</AppShell>
|
||||
|
||||
@@ -33,7 +33,7 @@ export function Carte({ surtitre, titre, action, children, ...reste }) {
|
||||
);
|
||||
}
|
||||
|
||||
// La station et la plage (UTC, Au exclue ; vides : toute la période), partagées par Images et Étiquetage via l'adresse
|
||||
// La station et la plage (UTC, Au exclue ; vides : toute la période), partagées par Images et Data 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)); }, []);
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
ActionIcon, Button, Card, Group, Loader, NativeSelect, Stack, Text, Textarea, TextInput, Title, Tooltip, useComputedColorScheme,
|
||||
} from "@mantine/core";
|
||||
import { IconPlus, IconX } from "@tabler/icons-react";
|
||||
import { appel, Selecteur } from "../commun.jsx";
|
||||
|
||||
// Data, le visualiseur de courbes (et l'étiquetage de labeling/labeling.py) : un plot au départ, d'autres à ajouter ou enlever,
|
||||
// tous alignés sur le temps ; sous eux la barre des étiquettes : y glisser sélectionne une plage, un clic ouvre une étiquette.
|
||||
// Les étiquettes sont dans labeling/<auto|manual>/<STATION>.jsonl, relues à chaque chargement.
|
||||
const FAMILLES = { "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) }))];
|
||||
const GRIS = "#b0b0aa", BLEU = "#2a78d6", VOIE = 26; // VOIE : px par rangée d'étiquettes
|
||||
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.12 },
|
||||
sombre: { texte: "#c9c9c9", faible: "#828282", grille: "#2e2e2e", axe: "#424242", fond: "#3b3b3b", bulle: "#242424", zone: 0.18 } };
|
||||
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,
|
||||
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
|
||||
|
||||
export default function Data({ selection, choisir }) {
|
||||
const [donnees, setDonnees] = useState(null), [charge, setCharge] = useState(false);
|
||||
const { station, du, au } = selection;
|
||||
useEffect(() => {
|
||||
setDonnees(null);
|
||||
if (!station) return;
|
||||
setCharge(true);
|
||||
appel(`/api/courbes?${new URLSearchParams({ station, du, au })}`).then(d => { setDonnees(d); setCharge(false); });
|
||||
}, [station, du, au]);
|
||||
return (
|
||||
<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 : glisser sur leur barre sélectionne une plage,
|
||||
un clic sur une étiquette l'ouvre.</Text>
|
||||
</div>
|
||||
<Selecteur selection={selection} choisir={choisir} />
|
||||
{charge && <Loader />}
|
||||
{donnees && <Courbes key={`${station}${du}${au}`} station={station} d={donnees} />}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function Courbes({ station, d }) {
|
||||
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 [source, setSource] = useState("auto"), [labels, setLabels] = useState([]), [choix, setChoix] = useState(null);
|
||||
const [ajout, setAjout] = useState({ categorie: "", texte: "" });
|
||||
const [ouverte, setOuverte] = useState(null), [edit, setEdit] = useState(null), [note, setNote] = useState("");
|
||||
const [toutes, setToutes] = useState([]), sombre = useComputedColorScheme("light") === "dark";
|
||||
// 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({});
|
||||
courant.current = { vues, labels, choix, ouvrir, c: COULEURS[sombre ? "sombre" : "clair"] }; // ce que lisent les événements Plotly
|
||||
|
||||
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);
|
||||
|
||||
function zones() {
|
||||
const { labels, choix, c } = courant.current;
|
||||
const z = (a, b, c, o) => ({ type: "rect", xref: "x", yref: "paper", x0: lisible(a), x1: lisible(b), y0: 0, y1: 1,
|
||||
fillcolor: c, opacity: o, line: { width: 0 }, layer: "below" });
|
||||
return labels.map(l => z(l.debut, l.fin, couleur(l), c.zone)).concat(choix ? [z(choix[0], choix[1], BLEU, 0.25)] : []);
|
||||
}
|
||||
|
||||
// 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;
|
||||
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));
|
||||
return Promise.all([...gs, b].map(g => {
|
||||
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(() => { // le texte des étiquettes suit le zoom et la largeur
|
||||
const v = `${rg}|${b._fullLayout._size.w}`;
|
||||
if (v !== vue.current) { vue.current = v; return Plotly.restyle(b, { text: [textes(tries.current, b._fullLayout)] }); }
|
||||
});
|
||||
}
|
||||
|
||||
// Le texte de chaque étiquette, tronqué à la largeur visible de sa barre (~6 px par caractère en 11 px)
|
||||
function textes(t, L) {
|
||||
const [r0, r1] = L.xaxis.range.map(date), w = L._size.w;
|
||||
return t.map(l => {
|
||||
const px = (Math.min(date(l.fin), r1) - Math.max(date(l.debut), r0)) / (r1 - r0) * w, n = Math.floor((px - 10) / 6);
|
||||
return n < 3 ? "" : l.description.length <= n ? l.description : l.description.slice(0, n - 1) + "…";
|
||||
});
|
||||
}
|
||||
|
||||
function dessineFig(g, m) {
|
||||
const p = PLOTS[m], { c } = courant.current, b = barre.current?._fullLayout;
|
||||
// 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.
|
||||
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,
|
||||
hovertemplate: `${t.name} : %{y}<br>%{x|%Y-%m-%d %H:%M} UTC<extra></extra>` })),
|
||||
{ ...habillage(c), height: 400, hovermode: "closest", margin: { ...marge(), t: 34 }, uirevision: 1, shapes: zones(), // t : la barre d'outils
|
||||
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)); }
|
||||
return aligne(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); }));
|
||||
}
|
||||
|
||||
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;
|
||||
return i;
|
||||
});
|
||||
const n = Math.max(1, voies.length), gs = liste(), f = gs[0]._fullLayout, { c } = courant.current;
|
||||
vue.current = "";
|
||||
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: { color: c.fond, width: 1 } },
|
||||
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 : la famille et tout le texte, que la barre tronque
|
||||
customdata: t.map(l => (l.categorie ? `<b>${NOM_FAMILLE(l.categorie)}</b><br>` : "") + coupe(l.description)),
|
||||
hovertemplate: "%{customdata}<extra></extra>" }],
|
||||
{ ...habillage(c), height: 40 + VOIE * n, dragmode: "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 },
|
||||
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 } },
|
||||
{ responsive: true, displayModeBar: false, doubleClick: false });
|
||||
}
|
||||
|
||||
// Le premier dessin, puis les événements de la barre, une fois
|
||||
useEffect(() => {
|
||||
if (!Plotly) return;
|
||||
dessinePlots().then(dessineBarre).then(() => aligne()).then(() => {
|
||||
barre.current.on("plotly_selected", ev => {
|
||||
const r = ev?.range?.x;
|
||||
if (r) setChoix(r.map(v => String(v).slice(0, 16).replace(" ", "T") + "Z"));
|
||||
});
|
||||
barre.current.on("plotly_deselect", () => setChoix(null));
|
||||
barre.current.on("plotly_click", ev => courant.current.ouvrir(tries.current[ev.points[0].pointIndex]));
|
||||
setPret(true);
|
||||
});
|
||||
return () => [...Object.values(figs.current), barre.current].forEach(g => g && Plotly.purge(g));
|
||||
}, [Plotly]);
|
||||
|
||||
useEffect(() => { if (pret) dessinePlots().then(() => aligne(barre.current)); }, [vues]);
|
||||
useEffect(() => { if (pret) dessineBarre(); }, [pret, labels]);
|
||||
useEffect(() => { if (pret) dessinePlots(true).then(dessineBarre); }, [sombre]);
|
||||
useEffect(() => { if (pret) liste().forEach(g => Plotly.relayout(g, { shapes: zones() })); }, [pret, labels, choix]);
|
||||
|
||||
// Lues à chaque chargement et à chaque changement de dossier : la page montre toujours le fichier
|
||||
useEffect(() => {
|
||||
appel(`/api/etiquettes?${new URLSearchParams({ station, dossier: source })}`)
|
||||
.then(l => { setToutes(l || []); setLabels(l ? l.filter(x => x.debut < B && x.fin > A) : []); });
|
||||
}, [source]);
|
||||
|
||||
// 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 }]);
|
||||
}
|
||||
|
||||
function enleverPlot(id) {
|
||||
Plotly.purge(figs.current[id]);
|
||||
delete figs.current[id]; delete dessines.current[id];
|
||||
setVues(vues.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);
|
||||
|
||||
// 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("");
|
||||
setEdit(l && { debut: l.debut.slice(0, 16), fin: l.fin.slice(0, 16), categorie: l.categorie || "", texte: l.description });
|
||||
return true;
|
||||
}
|
||||
|
||||
async function ajouter() {
|
||||
const l = await appel("/api/etiquettes", "POST", { station, dossier: source, debut: choix[0], fin: choix[1],
|
||||
categorie: ajout.categorie, description: ajout.texte.trim() });
|
||||
if (!l) return; // rien n'est perdu : le texte et la plage restent dans la page
|
||||
setLabels(ls => [...ls, l]);
|
||||
setAjout({ categorie: "", texte: "" });
|
||||
await Plotly.relayout(barre.current, { selections: [] });
|
||||
setChoix(null);
|
||||
}
|
||||
|
||||
async function enregistrer() {
|
||||
const l = await appel("/api/etiquettes", "PUT", { station, dossier: source, 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
|
||||
setLabels(ls => ls.map(x => (x === ouverte ? l : x)));
|
||||
setOuverte(l); setNote("Enregistrée");
|
||||
}
|
||||
|
||||
async function supprimer() {
|
||||
if (!confirm("Supprimer cette étiquette ?")) return;
|
||||
if (await appel("/api/etiquettes", "DELETE", { station, dossier: source, avant: ouverte }) === null) return;
|
||||
setLabels(ls => ls.filter(x => x !== ouverte));
|
||||
setOuverte(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;
|
||||
return (
|
||||
<Card shadow="sm" withBorder>
|
||||
<Stack gap="sm">
|
||||
<Group gap="md" align="flex-end">
|
||||
<NativeSelect label="Étiquettes" data={[{ value: "auto", label: "auto (l'étiqueteur)" }, { value: "manual", label: "manual (les tiennes)" }]}
|
||||
value={source} onChange={e => { const v = e.currentTarget.value; if (ouvrir(null)) setSource(v); }} />
|
||||
<Button variant="light" leftSection={<IconPlus size={16} />} onClick={ajouterPlot} disabled={!pret}>Ajouter un plot</Button>
|
||||
{!pret && <Loader size="sm" />}
|
||||
</Group>
|
||||
{vues.map(v => (
|
||||
<div key={v.id}>
|
||||
<Group gap="xs" align="flex-end" wrap="nowrap">
|
||||
<NativeSelect label="Plot" data={options} value={String(v.m)} maw={420} style={{ flex: 1 }}
|
||||
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" size="lg" aria-label="Enlever ce plot" onClick={() => enleverPlot(v.id)}>
|
||||
<IconX size={18} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Group>
|
||||
<div ref={el => { if (el) figs.current[v.id] = el; }} />
|
||||
</div>
|
||||
))}
|
||||
<div ref={barre} />
|
||||
{pret && !labels.length && ( // sinon une barre vide ne dit pas pourquoi
|
||||
<Text size="sm" c="orange">{toutes.length
|
||||
? `Aucune étiquette ${source} sur cette plage : celles de ${station} vont du ${lisible(toutes.reduce((m, l) => (l.debut < m ? l.debut : m), toutes[0].debut))} au ${lisible(toutes.reduce((m, l) => (l.fin > m ? l.fin : m), toutes[0].fin))} UTC.`
|
||||
: `${station} n'a aucune étiquette dans labeling/${source}/.`}</Text>
|
||||
)}
|
||||
{ouverte && 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 })} />
|
||||
</Group>
|
||||
<Textarea autosize minRows={3} value={edit.texte} onChange={e => setEdit({ ...edit, texte: e.currentTarget.value })} />
|
||||
<Group gap="sm">
|
||||
<Button onClick={enregistrer} disabled={!peutEnregistrer}>Enregistrer</Button>
|
||||
<Button variant="default" onClick={() => ouvrir(null)}>Fermer</Button>
|
||||
<Text size="sm" c="teal">{note}</Text>
|
||||
<Button color="red" variant="light" ml="auto" onClick={supprimer}>Supprimer</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Card>
|
||||
)}
|
||||
<Text size="sm">{choix ? `${lisible(choix[0])} → ${lisible(choix[1])} UTC` : "Glisser sur la barre des étiquettes pour sélectionner une plage."}</Text>
|
||||
<NativeSelect label="Famille" data={CHOIX_FAMILLE} value={ajout.categorie} onChange={e => setAjout({ ...ajout, categorie: e.currentTarget.value })} maw={300} />
|
||||
<Textarea autosize minRows={3} placeholder="Que voit-on sur cette plage ?" value={ajout.texte}
|
||||
onChange={e => setAjout({ ...ajout, texte: e.currentTarget.value })} />
|
||||
<Group><Button onClick={ajouter} disabled={!(choix && choix[0] < choix[1] && ajout.texte.trim())}>Ajouter</Button></Group>
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Button, Card, Group, Loader, NativeSelect, Stack, Text, Textarea, TextInput, Title, useComputedColorScheme } from "@mantine/core";
|
||||
import * as echarts from "echarts";
|
||||
import { appel, Selecteur } from "../commun.jsx";
|
||||
|
||||
// L'étiquetage (labeling/labeling.py) : deux plots alignés, la barre des étiquettes ; y glisser sélectionne une plage,
|
||||
// un clic ouvre une étiquette. Les étiquettes sont dans labeling/<auto|manual>/<STATION>.jsonl, relues à chaque chargement.
|
||||
const FAMILLES = { "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) }))];
|
||||
const GRIS = "#b0b0aa", BLEU = "#2a78d6", VOIE = 22; // VOIE : px par rangée d'étiquettes
|
||||
const couleur = l => FAMILLES[l.categorie] || GRIS;
|
||||
const lisible = s => s.slice(0, 16).replace("T", " ");
|
||||
const ms = s => Date.parse(s[10] === " " ? s.replace(" ", "T") + "Z" : s); // "AAAA-MM-JJ HH:MM" des courbes : UTC
|
||||
const iso = v => new Date(v).toISOString().slice(0, 16) + "Z";
|
||||
// Le graphique, de haut en bas : plot 1, plot 2, barre des étiquettes (VOIE px par rangée), réglette du zoom
|
||||
const G = { l: 70, r: 120, h: 300, haut1: 10, haut2: 350, barre: 690 };
|
||||
const reglette = n => G.barre + VOIE * n + 34;
|
||||
|
||||
export default function Etiquetage({ selection, choisir }) {
|
||||
const [donnees, setDonnees] = useState(null), [charge, setCharge] = useState(false);
|
||||
const { station, du, au } = selection;
|
||||
useEffect(() => {
|
||||
setDonnees(null);
|
||||
if (!station) return;
|
||||
setCharge(true);
|
||||
appel(`/api/courbes?${new URLSearchParams({ station, du, au })}`).then(d => { setDonnees(d); setCharge(false); });
|
||||
}, [station, du, au]);
|
||||
return (
|
||||
<Stack gap="lg">
|
||||
<div>
|
||||
<Title order={2}>Étiquetage</Title>
|
||||
<Text c="dimmed">Molette : zoom ; glisser sur un plot : déplacer ; double-clic : tout voir. Glisser sur la barre des étiquettes
|
||||
sélectionne une plage ; un clic sur une étiquette l'ouvre.</Text>
|
||||
</div>
|
||||
<Selecteur selection={selection} choisir={choisir} />
|
||||
{charge && <Loader />}
|
||||
{donnees && <Etiqueteur key={`${station}${du}${au}`} station={station} d={donnees} />}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function Etiqueteur({ station, d }) {
|
||||
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 [source, setSource] = useState("auto"), [labels, setLabels] = useState([]), [choix, setChoix] = useState(null);
|
||||
const [m1, setM1] = useState(indice("Relative Corrected Horizontal Shift", 0));
|
||||
const [m2, setM2] = useState(indice("Relative Corrected Vertical Shift", PLOTS.length > 1 ? 1 : 0));
|
||||
const [ajout, setAjout] = useState({ categorie: "", texte: "" });
|
||||
const [ouverte, setOuverte] = useState(null), [edit, setEdit] = useState(null), [note, setNote] = useState("");
|
||||
const sombre = useComputedColorScheme("light") === "dark";
|
||||
const boite = useRef(), graphe = useRef(), courant = useRef({});
|
||||
|
||||
const temps = useMemo(() => Object.fromEntries(Object.entries(T).map(([k, v]) => [k, v.map(ms)])), [T]);
|
||||
// Les étiquettes par début, chacune dans la première rangée libre, sinon une nouvelle
|
||||
const { tries, voie, n } = useMemo(() => {
|
||||
const tries = [...labels].sort((a, b) => (a.debut < b.debut ? -1 : 1)), voies = [];
|
||||
const voie = tries.map(l => { const r = voies.findIndex(f => f <= l.debut), i = r < 0 ? voies.length : r; voies[i] = l.fin; return i; });
|
||||
return { tries, voie, n: Math.max(1, voies.length) };
|
||||
}, [labels]);
|
||||
courant.current = { tries, ouvrir, n }; // ce que lisent les événements du graphique, installés une fois
|
||||
|
||||
// Les zones des étiquettes (et la plage choisie) sur les plots, puis les barres des étiquettes
|
||||
function decor() {
|
||||
const zone = (a, b, c, o) => [{ xAxis: ms(a), itemStyle: { color: c, opacity: o } }, { xAxis: ms(b) }];
|
||||
const zones = labels.map(l => zone(l.debut, l.fin, couleur(l), 0.12)).concat(choix ? [zone(choix[0], choix[1], BLEU, 0.25)] : []);
|
||||
return [0, 1].map(g => ({ id: `zones${g}`, type: "line", xAxisIndex: g, yAxisIndex: g, data: [], markArea: { silent: true, data: zones } }))
|
||||
.concat({ id: "barre", type: "custom", xAxisIndex: 2, yAxisIndex: 2, encode: { x: [0, 1], y: 2 }, cursor: "pointer",
|
||||
data: tries.map((l, i) => [ms(l.debut), ms(l.fin), voie[i], i]),
|
||||
renderItem: (p, api) => {
|
||||
const a = api.coord([api.value(0), api.value(2)]), b = api.coord([api.value(1), api.value(2)]), h = api.size([0, 1])[1] * 0.85;
|
||||
const r = echarts.graphic.clipRectByRect({ x: a[0], y: a[1] - h / 2, width: Math.max(b[0] - a[0] - 1, 2), height: h }, p.coordSys);
|
||||
const l = courant.current.tries[api.value(3)];
|
||||
return r && { type: "rect", shape: r, style: { fill: couleur(l) },
|
||||
textContent: { style: { text: r.width > 30 ? l.description : "", // la couleur dit la famille
|
||||
fill: "#1a1b1e", fontSize: 11, width: r.width - 8, overflow: "truncate" } },
|
||||
textConfig: { position: "insideLeft" } };
|
||||
},
|
||||
markArea: { silent: true, data: choix ? [[{ xAxis: ms(choix[0]), itemStyle: { color: BLEU, opacity: 0.25 } }, { xAxis: ms(choix[1]) }]] : [] } });
|
||||
}
|
||||
|
||||
// Le cadre, refait à chaque thème (setTheme d'ECharts efface les séries) : trois grilles sur le même temps ; la molette et le glisser zooment les plots, la réglette les trois
|
||||
useEffect(() => {
|
||||
const c = echarts.init(boite.current, sombre ? "dark" : null);
|
||||
graphe.current = c;
|
||||
const axe = i => ({ gridIndex: i, type: "time", min: ms(A), max: ms(B), axisLabel: { hideOverlap: true } });
|
||||
c.setOption({
|
||||
backgroundColor: "transparent", animation: false, useUTC: true, textStyle: { fontFamily: "Roboto, sans-serif" },
|
||||
grid: [{ left: G.l, right: G.r, top: G.haut1, height: G.h }, { left: G.l, right: G.r, top: G.haut2, height: G.h },
|
||||
{ left: G.l, right: G.r, top: G.barre, height: VOIE, show: true, borderWidth: 0, backgroundColor: "rgba(128,128,128,0.1)" }],
|
||||
xAxis: [axe(0), axe(1), { ...axe(2), axisLine: { show: false }, splitLine: { show: false } }],
|
||||
yAxis: [0, 1].map(g => ({ gridIndex: g, scale: true, nameLocation: "middle", nameGap: 50, nameTextStyle: { fontSize: 11 } }))
|
||||
.concat({ gridIndex: 2, min: -0.5, max: 0.5, inverse: true, show: false }),
|
||||
dataZoom: [{ type: "inside", xAxisIndex: [0, 1] },
|
||||
{ type: "slider", xAxisIndex: [0, 1, 2], filterMode: "weakFilter", left: G.l, right: G.r, height: 20, top: reglette(1),
|
||||
labelFormatter: v => lisible(iso(v)) }],
|
||||
legend: { type: "scroll", orient: "vertical", icon: "roundRect", itemWidth: 14, itemHeight: 4, right: 0, top: G.haut1, height: G.haut2 + G.h - G.haut1, textStyle: { fontSize: 11 } },
|
||||
tooltip: { trigger: "axis", confine: true, textStyle: { fontSize: 11 }, formatter: ps => {
|
||||
const v = ps.filter(p => p.seriesType === "line" && p.value?.[1] != null);
|
||||
if (!v.length) return "";
|
||||
return `<b>${lisible(iso(v[0].value[0]))} UTC</b><div style="display:grid;grid-template-columns:repeat(${v.length > 12 ? 3 : 1},auto);gap:0 14px">`
|
||||
+ v.map(p => `<span>${p.marker}${p.seriesName} ${+p.value[1].toPrecision(5)}</span>`).join("") + "</div>";
|
||||
} },
|
||||
});
|
||||
c.on("click", { seriesId: "barre" }, p => courant.current.ouvrir(courant.current.tries[p.value[3]]));
|
||||
|
||||
// Glisser sur la barre : la plage choisie, dessinée à même le canvas pendant le geste (les courbes ne sont pas redessinées)
|
||||
const zr = c.getZr(), dans = e => c.containPixel({ gridIndex: 2 }, [e.offsetX, e.offsetY]);
|
||||
const valeur = x => c.convertFromPixel({ gridIndex: 2 }, [x, G.barre])[0];
|
||||
let depart = null, rect = null;
|
||||
zr.on("mousedown", e => { if (dans(e)) depart = e.offsetX; });
|
||||
zr.on("mousemove", e => {
|
||||
if (dans(e)) zr.setCursorStyle(e.target ? "pointer" : "crosshair");
|
||||
if (depart === null || Math.abs(e.offsetX - depart) < 3) return;
|
||||
if (!rect) zr.add(rect = new echarts.graphic.Rect({ silent: true, z: 100, style: { fill: BLEU, opacity: 0.25 } }));
|
||||
rect.setShape({ x: Math.min(depart, e.offsetX), y: G.barre, width: Math.abs(e.offsetX - depart), height: VOIE * courant.current.n });
|
||||
});
|
||||
zr.on("mouseup", e => {
|
||||
if (depart === null) return;
|
||||
const [a, b] = [valeur(depart), valeur(e.offsetX)].sort((x, y) => x - y), glisse = Math.abs(e.offsetX - depart) >= 3;
|
||||
if (rect) { zr.remove(rect); rect = null; }
|
||||
depart = null;
|
||||
if (glisse) setChoix([iso(a), iso(b)]);
|
||||
else if (!e.target) setChoix(null); // un clic hors des étiquettes efface la plage
|
||||
});
|
||||
zr.on("dblclick", () => c.dispatchAction({ type: "dataZoom", start: 0, end: 100 }));
|
||||
const suivre = new ResizeObserver(() => c.resize());
|
||||
suivre.observe(boite.current);
|
||||
return () => { suivre.disconnect(); c.dispose(); };
|
||||
}, [sombre]);
|
||||
|
||||
// Les courbes, sans échantillonnage (LTTB relie les points par-dessus les trous) : changer de plot remplace les séries ; le zoom et les capteurs cachés dans la légende restent
|
||||
useEffect(() => {
|
||||
const lignes = (g, m) => PLOTS[m].traces.map(t => ({
|
||||
type: "line", name: t.name, xAxisIndex: g, yAxisIndex: g, symbolSize: 4, showSymbol: t.mode === "lines+markers",
|
||||
lineStyle: { width: t.line?.width, color: t.line?.color, type: t.line?.dash === "dot" ? "dotted" : "solid" }, itemStyle: { color: t.line?.color },
|
||||
data: temps[t.t].map((x, i) => [x, t.y[i]]) }));
|
||||
graphe.current.setOption({
|
||||
legend: { data: [...new Set([...PLOTS[m1].traces, ...PLOTS[m2].traces].map(t => t.name))] },
|
||||
yAxis: [{ name: PLOTS[m1].titre }, { name: PLOTS[m2].titre }],
|
||||
series: [...lignes(0, m1), ...lignes(1, m2), ...decor()],
|
||||
}, { replaceMerge: ["series"] });
|
||||
}, [m1, m2, sombre]);
|
||||
|
||||
// Les étiquettes et la plage choisie ; la barre prend une rangée par chevauchement
|
||||
useEffect(() => {
|
||||
const c = graphe.current;
|
||||
c.setOption({ grid: [{}, {}, { height: VOIE * n }], yAxis: [{}, {}, { max: n - 0.5 }], dataZoom: [{}, { top: reglette(n) }], series: decor() });
|
||||
c.resize();
|
||||
}, [labels, choix, sombre]);
|
||||
|
||||
// Lues à chaque chargement et à chaque changement de dossier : la page montre toujours le fichier
|
||||
useEffect(() => {
|
||||
appel(`/api/etiquettes?${new URLSearchParams({ station, dossier: source })}`)
|
||||
.then(l => setLabels(l ? l.filter(x => x.debut < B && x.fin > A) : []));
|
||||
}, [source]);
|
||||
|
||||
const modifiee = () => ouverte && edit && (edit.texte.trim() !== ouverte.description || edit.categorie !== (ouverte.categorie || "")
|
||||
|| edit.debut + "Z" !== ouverte.debut || edit.fin + "Z" !== ouverte.fin);
|
||||
|
||||
// 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("");
|
||||
setEdit(l && { debut: l.debut.slice(0, 16), fin: l.fin.slice(0, 16), categorie: l.categorie || "", texte: l.description });
|
||||
return true;
|
||||
}
|
||||
|
||||
async function ajouter() {
|
||||
const l = await appel("/api/etiquettes", "POST", { station, dossier: source, debut: choix[0], fin: choix[1],
|
||||
categorie: ajout.categorie, description: ajout.texte.trim() });
|
||||
if (!l) return; // rien n'est perdu : le texte et la plage restent dans la page
|
||||
setLabels(ls => [...ls, l]);
|
||||
setAjout({ categorie: "", texte: "" });
|
||||
setChoix(null);
|
||||
}
|
||||
|
||||
async function enregistrer() {
|
||||
const l = await appel("/api/etiquettes", "PUT", { station, dossier: source, 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
|
||||
setLabels(ls => ls.map(x => (x === ouverte ? l : x)));
|
||||
setOuverte(l); setNote("Enregistrée");
|
||||
}
|
||||
|
||||
async function supprimer() {
|
||||
if (!confirm("Supprimer cette étiquette ?")) return;
|
||||
if (await appel("/api/etiquettes", "DELETE", { station, dossier: source, avant: ouverte }) === null) return;
|
||||
setLabels(ls => ls.filter(x => x !== ouverte));
|
||||
setOuverte(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;
|
||||
return (
|
||||
<Card shadow="sm" withBorder>
|
||||
<Stack gap="sm">
|
||||
<Group gap="md" align="flex-end">
|
||||
<NativeSelect label="Étiquettes" data={[{ value: "auto", label: "auto (l'étiqueteur)" }, { value: "manual", label: "manual (les tiennes)" }]}
|
||||
value={source} onChange={e => { const v = e.currentTarget.value; if (ouvrir(null)) setSource(v); }} />
|
||||
<NativeSelect label="Plot du haut" data={options} value={String(m1)} onChange={e => setM1(+e.currentTarget.value)} w={320} maw="100%" />
|
||||
<NativeSelect label="Plot du bas" data={options} value={String(m2)} onChange={e => setM2(+e.currentTarget.value)} w={320} maw="100%" />
|
||||
</Group>
|
||||
<div ref={boite} style={{ height: reglette(n) + 40 }} />
|
||||
{ouverte && 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 })} />
|
||||
</Group>
|
||||
<Textarea autosize minRows={3} value={edit.texte} onChange={e => setEdit({ ...edit, texte: e.currentTarget.value })} />
|
||||
<Group gap="sm">
|
||||
<Button onClick={enregistrer} disabled={!peutEnregistrer}>Enregistrer</Button>
|
||||
<Button variant="default" onClick={() => ouvrir(null)}>Fermer</Button>
|
||||
<Text size="sm" c="teal">{note}</Text>
|
||||
<Button color="red" variant="light" ml="auto" onClick={supprimer}>Supprimer</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Card>
|
||||
)}
|
||||
<Text size="sm">{choix ? `${lisible(choix[0])} → ${lisible(choix[1])} UTC` : "Glisser sur la barre des étiquettes pour sélectionner une plage."}</Text>
|
||||
<NativeSelect label="Famille" data={CHOIX_FAMILLE} value={ajout.categorie} onChange={e => setAjout({ ...ajout, categorie: e.currentTarget.value })} maw={300} />
|
||||
<Textarea autosize minRows={3} placeholder="Que voit-on sur cette plage ?" value={ajout.texte}
|
||||
onChange={e => setAjout({ ...ajout, texte: e.currentTarget.value })} />
|
||||
<Group><Button onClick={ajouter} disabled={!(choix && choix[0] < choix[1] && ajout.texte.trim())}>Ajouter</Button></Group>
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -126,7 +126,7 @@ export default function Support({ etat, evenements }) {
|
||||
{etat.station && (
|
||||
<Group gap="xs">
|
||||
<Button component="a" href={lien("images", etat.station)} variant="light" leftSection={<IconPhoto size={16} />}>Images de {etat.station}</Button>
|
||||
<Button component="a" href={lien("etiquetage", etat.station)} variant="light" leftSection={<IconChartLine size={16} />}>Étiquetage</Button>
|
||||
<Button component="a" href={lien("data", etat.station)} variant="light" leftSection={<IconChartLine size={16} />}>Data de {etat.station}</Button>
|
||||
</Group>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
Reference in new issue
Block a user