Positions come from a new detecteurs.positions(), taken out of camera(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
155 lines
8.9 KiB
Python
155 lines
8.9 KiB
Python
"""Les images IRON d'une station (images/ du pompage). En haut, le data loader de la page Status : une autre station, d'autres
|
|
dates, et « Analyse » refait la page. Dessous, l'image, à parcourir au glisseur, par ◀ ▶ ou les flèches du clavier, et à zoomer
|
|
comme dans la maquette Explore : molette autour du pointeur, glisser pour se déplacer, double clic pour l'image entière ; le
|
|
zoom reste d'une image à l'autre. La case Labels écrit le nom de chaque capteur, à sa position médiane sur la plage : en jaune
|
|
les cibles, en bleu et cercle pointillé les références (reproj_err rempli, detecteurs.references) ; grisée si x, y ne sont pas
|
|
des positions dans l'image (LENZSPITZE, NADELHORN). Son serveur local (http://127.0.0.1:8768, lancé en tâche de fond) sert
|
|
out/ et data/, plus /analyse (ce script lancé à chaque fois, comme le data loader).
|
|
Usage : python3 view/view.py [<dossier de station> [--du AAAA-MM-JJ] [--au AAAA-MM-JJ]]
|
|
(sans dossier : le data loader seul ; --au exclu ; sans dates, toute la période du dossier ; page :
|
|
out/view_<STATION>_<première image>_<dernière image>.html, ouverte)
|
|
"""
|
|
import argparse
|
|
import glob
|
|
import html
|
|
import http.server
|
|
import json
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
ICI = Path(__file__).resolve().parent
|
|
sys.path[:0] = [str(ICI.parent / "detectors-view"), str(ICI.parent / "detectors-view" / "data-loader")]
|
|
import chargeur # noqa: E402 (son formulaire, son serveur ; bascule seule sur .venv si plotly manque)
|
|
import detecteurs # noqa: E402 (les positions des capteurs et les références de la page Status)
|
|
from detecteurs import donnees # noqa: E402
|
|
|
|
PORT = 8768 # ni celui de common.page (8765), ni celui du data loader (8766), ni celui de labeling (8767)
|
|
|
|
# Z : le zoom et le décalage, en fraction du cadre, comme la maquette Explore (explore_template.html).
|
|
PAGE_JS = """
|
|
const cadre = document.getElementById('cadre'), couche = document.getElementById('couche'), img = document.getElementById('img');
|
|
const glis = document.getElementById('glis'), heure = document.getElementById('heure');
|
|
const marques = document.getElementById('marques'), labels = document.getElementById('labels');
|
|
let V = 0, Z = {k: 1, x: 0, y: 0};
|
|
|
|
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.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.
|
|
const W = img.naturalWidth, H = img.naturalHeight;
|
|
if (W) marques.style.fontSize = `${12 / (Z.k * Math.min(cadre.clientWidth / W, cadre.clientHeight / H))}px`;
|
|
}
|
|
const affiche = () => marques.style.display = labels.checked && img.naturalWidth ? '' : 'none';
|
|
labels.onchange = affiche;
|
|
addEventListener('resize', zoom);
|
|
|
|
function montre(i) {
|
|
V = Math.max(0, Math.min(IM.length - 1, i));
|
|
glis.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
|
|
}
|
|
// L'heure change avec l'image, pas avant : l'image d'avant reste affichée tant que la nouvelle se charge.
|
|
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
|
|
zoom();
|
|
affiche();
|
|
};
|
|
img.onerror = () => {
|
|
img.removeAttribute('src');
|
|
heure.textContent = `${IM[V].t} UTC (${V + 1}/${IM.length}): image not readable`;
|
|
affiche();
|
|
};
|
|
|
|
glis.oninput = () => montre(+glis.value);
|
|
document.getElementById('prec').onclick = () => montre(V - 1);
|
|
document.getElementById('suiv').onclick = () => montre(V + 1);
|
|
document.addEventListener('keydown', e => {
|
|
if (e.target.closest('form') || !['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));
|
|
});
|
|
|
|
cadre.addEventListener('wheel', ev => { // zoom autour du pointeur
|
|
ev.preventDefault();
|
|
const r = cadre.getBoundingClientRect(), u = (ev.clientX - r.left) / r.width, v = (ev.clientY - r.top) / r.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();
|
|
}, {passive: false});
|
|
cadre.addEventListener('pointerdown', ev => { // déplacement à la souris
|
|
cadre.setPointerCapture(ev.pointerId);
|
|
const r = cadre.getBoundingClientRect(), de = {...Z, cx: ev.clientX, cy: ev.clientY};
|
|
cadre.onpointermove = e => { Z.x = de.x + (e.clientX - de.cx) / r.width; Z.y = de.y + (e.clientY - de.cy) / r.height; zoom(); };
|
|
cadre.onpointerup = () => cadre.onpointermove = null;
|
|
});
|
|
cadre.addEventListener('dblclick', () => { Z = {k: 1, x: 0, y: 0}; zoom(); });
|
|
|
|
montre(0);
|
|
"""
|
|
|
|
|
|
def page(dossier, du=None, au=None):
|
|
a, b = donnees.instant(du or "0001-01-01"), donnees.instant(au or "9999-01-01")
|
|
vues = [(t, im) for im in sorted(glob.glob(os.path.join(dossier, "images", "*")))
|
|
if (t := donnees.heure_image(im)) and a <= t < b]
|
|
if not vues:
|
|
raise SystemExit(f"Aucune image dans {dossier} du {du} au {au}.")
|
|
mesures = donnees.charger(dossier)
|
|
maisons, refs = detecteurs.positions(mesures, a, b), detecteurs.references(mesures, a, b)
|
|
marques = "".join(f"""<g class="{'ref' if s in refs else 'cible'}"><circle cx="{x:.1f}" cy="{y:.1f}" r=".7em"/>"""
|
|
f"""<text x="{x:.1f}" y="{y:.1f}" dy="-1em">{html.escape(s)}</text></g>""" for s, (x, y) in sorted(maisons.items()))
|
|
station = os.path.basename(os.path.normpath(dossier))
|
|
nom = f"{station}_{donnees.iso(vues[0][0])[:10]}_{donnees.iso(vues[-1][0])[:10]}"
|
|
chemin = chargeur.ROOT / "out" / f"view_{nom}.html"
|
|
chemin.parent.mkdir(exist_ok=True)
|
|
images = [{"t": donnees.iso(t).replace("T", " ").rstrip("Z"), "src": quote(Path(os.path.relpath(im, chemin.parent)).as_posix())}
|
|
for t, im in vues]
|
|
js = json.dumps(images, separators=(",", ":")).replace("</", "<\\/")
|
|
chemin.write_text(f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><title>View {html.escape(nom)}</title>
|
|
<style>body{{font-family:system-ui,sans-serif;margin:16px;background:#fff;color:#1a1a19}}
|
|
#cadre{{position:relative;height:calc(100vh - 190px);min-height:300px;background:#000;overflow:hidden;cursor:grab;touch-action:none}}
|
|
#cadre:active{{cursor:grabbing}}
|
|
#couche{{position:absolute;inset:0;transform-origin:0 0}} #couche>*{{position:absolute;inset:0;width:100%;height:100%}}
|
|
#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}}
|
|
#nav{{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:8px}} #glis{{flex:1;min-width:200px}}
|
|
#heure{{font-variant-numeric:tabular-nums}} #aide{{color:#6b6b66;font-size:13px;margin:4px 0 0}}</style></head><body>
|
|
<h2>View, {html.escape(station)}</h2>
|
|
{chargeur.formulaire(station, du or "", au or "")}
|
|
<div id="cadre"><div id="couche"><img id="img" alt="" draggable="false"><svg id="marques" style="display:none">{marques}</svg></div></div>
|
|
<div id="nav"><button id="prec">◀</button><input id="glis" type="range" min="0" max="{len(images) - 1}" value="0"><button id="suiv">▶</button>
|
|
<span id="heure"></span><label><input type="checkbox" id="labels"{" disabled" * (not maisons)}> Labels</label>
|
|
{'<span id="legende"><span class="cible">○ Target</span> <span class="ref">◌ Reference</span></span>' if maisons else '<span style="color:#6b6b66">x, y are not image positions at this station</span>'}</div>
|
|
<p id="aide">← → image · wheel: zoom · drag: pan · double-click: whole image</p>
|
|
<script>const IM = {js};
|
|
{PAGE_JS}</script>
|
|
</body></html>""", encoding="utf-8")
|
|
return chemin
|
|
|
|
|
|
class Serveur(chargeur.Chargeur):
|
|
SCRIPT = __file__
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if sys.argv[1:] == ["serve"]:
|
|
http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Serveur).serve_forever()
|
|
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
p.add_argument("dossier", nargs="?", help="sans dossier : le data loader seul")
|
|
p.add_argument("--du")
|
|
p.add_argument("--au")
|
|
p.add_argument("--sans-ouvrir", action="store_true", help="écrit la page sans l'ouvrir")
|
|
o = p.parse_args()
|
|
chemin = page(o.dossier, o.du, o.au) if o.dossier else chargeur.accueil("View", "view-loader")
|
|
print(chemin)
|
|
if not o.sans_ouvrir:
|
|
chargeur.open_served(chemin, PORT, __file__)
|