Dashboard web FastAPI + Chart.js

- 4 vues : spectre temps reel, historique detections, background, timeline CPS
- API REST : /api/status, /api/spectrum/current, /api/spectrum/difference,
  /api/background, /api/background/spectrum, /api/history, /api/cps/timeline
- Frontend vanilla JS + Chart.js (pas de Node.js, leger pour Pi 4)
- Moniteur modifie pour exporter son etat dans /data/monitor_state.json
  et le CPS dans /data/cps_log.jsonl chaque cycle
- Nouveau conteneur Docker 'web' sur port 8080
- Theme sombre, calibration energie (E = 0.33 + 2.97 * canal)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Jacquin Antoine
2026-05-19 13:33:07 +02:00
parent 27ef0727e8
commit 1e0c1a5ea5
22 changed files with 1031 additions and 2 deletions

181
web/static/css/style.css Normal file
View File

@ -0,0 +1,181 @@
:root {
--bg: #1a1a2e;
--bg-card: #16213e;
--text: #e0e0e0;
--text-dim: #888;
--accent: #0f3460;
--accent-bright: #4fc3f7;
--green: #4caf50;
--red: #f44336;
--yellow: #ff9800;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', system-ui, sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
}
header {
background: var(--bg-card);
padding: 12px 20px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #333;
}
header h1 {
font-size: 1.2em;
color: var(--accent-bright);
}
#status-bar {
display: flex;
align-items: center;
gap: 16px;
font-size: 0.9em;
}
.status-dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background: var(--red);
}
.status-dot.connected { background: var(--green); }
nav {
background: var(--accent);
display: flex;
}
nav a {
flex: 1;
text-align: center;
padding: 10px;
color: var(--text-dim);
text-decoration: none;
font-size: 0.95em;
transition: all 0.2s;
}
nav a:hover { background: rgba(255,255,255,0.1); }
nav a.active { color: var(--accent-bright); border-bottom: 2px solid var(--accent-bright); }
main { padding: 16px; }
.tab-content { display: none; }
.tab-content.active { display: block; }
.chart-container {
background: var(--bg-card);
border-radius: 8px;
padding: 12px;
margin-bottom: 12px;
}
.controls {
display: flex;
gap: 12px;
margin-bottom: 12px;
align-items: center;
}
.controls label {
display: flex;
align-items: center;
gap: 6px;
font-size: 0.9em;
color: var(--text-dim);
cursor: pointer;
}
.controls button {
background: var(--accent);
color: var(--text);
border: 1px solid #444;
padding: 6px 14px;
border-radius: 4px;
cursor: pointer;
font-size: 0.85em;
}
.controls button:hover { background: var(--accent-bright); color: #000; }
#isotopes-table, #peaks-table {
background: var(--bg-card);
border-radius: 8px;
padding: 12px;
}
.isotope-row {
display: flex;
justify-content: space-between;
padding: 6px 0;
border-bottom: 1px solid #333;
font-size: 0.9em;
}
.isotope-row:last-child { border-bottom: none; }
.isotope-name { color: var(--accent-bright); font-weight: bold; min-width: 80px; }
.isotope-prob { color: var(--green); min-width: 60px; }
.isotope-activity { color: var(--text-dim); }
.bg-stats {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
margin-bottom: 12px;
}
.bg-stat {
background: var(--bg-card);
border-radius: 8px;
padding: 12px;
text-align: center;
}
.bg-stat-value { font-size: 1.4em; color: var(--accent-bright); }
.bg-stat-label { font-size: 0.8em; color: var(--text-dim); }
.history-item {
background: var(--bg-card);
border-radius: 8px;
padding: 12px;
margin-bottom: 8px;
cursor: pointer;
transition: background 0.2s;
}
.history-item:hover { background: #1e2a4a; }
.history-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.history-date { font-weight: bold; color: var(--accent-bright); }
.history-cps { color: var(--text-dim); }
.history-isotopes { color: var(--green); font-size: 0.85em; }
.history-details { margin-top: 8px; padding-top: 8px; border-top: 1px solid #333; font-size: 0.9em; display: none; }
.history-details.open { display: block; }
.peak-row {
display: flex;
justify-content: space-between;
padding: 4px 0;
font-size: 0.85em;
}
@media (max-width: 600px) {
.bg-stats { grid-template-columns: repeat(2, 1fr); }
header { flex-direction: column; gap: 8px; }
nav a { font-size: 0.85em; padding: 8px; }
}

70
web/static/index.html Normal file
View File

@ -0,0 +1,70 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Radiacode 103 — Dashboard</title>
<link rel="stylesheet" href="/static/css/style.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
</head>
<body>
<header>
<h1>Radiacode 103</h1>
<div id="status-bar">
<span id="status-connected" class="status-dot"></span>
<span id="status-cps">-- CPS</span>
<span id="status-live-time">-- h</span>
</div>
</header>
<nav>
<a href="#spectrum" class="tab active" data-tab="spectrum">Spectre</a>
<a href="#history" class="tab" data-tab="history">Historique</a>
<a href="#background" class="tab" data-tab="background">Background</a>
<a href="#cps" class="tab" data-tab="cps">CPS</a>
</nav>
<main>
<section id="tab-spectrum" class="tab-content active">
<div class="chart-container">
<canvas id="spectrum-chart"></canvas>
</div>
<div class="controls">
<label><input type="checkbox" id="show-difference"> Background soustrait</label>
<label><input type="checkbox" id="log-scale"> Echelle log</label>
</div>
<div id="isotopes-table"></div>
</section>
<section id="tab-history" class="tab-content">
<div id="history-list"></div>
</section>
<section id="tab-background" class="tab-content">
<div class="bg-stats" id="bg-stats"></div>
<div class="chart-container">
<canvas id="background-chart"></canvas>
</div>
<div id="peaks-table"></div>
</section>
<section id="tab-cps" class="tab-content">
<div class="controls">
<button onclick="loadCps(1)">1h</button>
<button onclick="loadCps(6)">6h</button>
<button onclick="loadCps(24)">24h</button>
<button onclick="loadCps(168)">7j</button>
</div>
<div class="chart-container">
<canvas id="cps-chart"></canvas>
</div>
</section>
</main>
<script src="/static/js/app.js"></script>
<script src="/static/js/spectrum.js"></script>
<script src="/static/js/history.js"></script>
<script src="/static/js/background.js"></script>
<script src="/static/js/cps.js"></script>
</body>
</html>

51
web/static/js/app.js Normal file
View File

@ -0,0 +1,51 @@
const API_BASE = '';
let refreshInterval = null;
const REFRESH_MS = 30000; // 30 seconds
// Tab navigation
document.querySelectorAll('nav a').forEach(link => {
link.addEventListener('click', e => {
e.preventDefault();
const tab = link.dataset.tab;
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
link.classList.add('active');
document.getElementById(`tab-${tab}`).classList.add('active');
// Refresh the active tab
if (tab === 'spectrum') refreshSpectrum();
if (tab === 'background') refreshBackground();
if (tab === 'cps') loadCps(24);
});
});
// Status bar refresh
async function refreshStatus() {
try {
const resp = await fetch(`${API_BASE}/api/status`);
if (!resp.ok) {
document.getElementById('status-connected').className = 'status-dot';
return;
}
const data = await resp.json();
const dot = document.getElementById('status-connected');
dot.className = data.connected && !data.stale ? 'status-dot connected' : 'status-dot';
document.getElementById('status-cps').textContent = `${data.cps.toFixed(1)} CPS`;
document.getElementById('status-live-time').textContent = `${data.cumulated_live_time_h.toFixed(1)} h`;
} catch {
document.getElementById('status-connected').className = 'status-dot';
}
}
// Auto-refresh
function startRefresh() {
refreshStatus();
refreshSpectrum();
refreshInterval = setInterval(() => {
refreshStatus();
const activeTab = document.querySelector('.tab.active')?.dataset.tab;
if (activeTab === 'spectrum') refreshSpectrum();
}, REFRESH_MS);
}
// Initialize
startRefresh();

103
web/static/js/background.js Normal file
View File

@ -0,0 +1,103 @@
let bgChart = null;
async function refreshBackground() {
try {
const [infoResp, specResp] = await Promise.all([
fetch(`${API_BASE}/api/background`),
fetch(`${API_BASE}/api/background/spectrum`)
]);
if (!infoResp.ok || !specResp.ok) {
document.getElementById('bg-stats').innerHTML = '<p style="color:#888">Background non disponible</p>';
return;
}
const info = await infoResp.json();
const spec = await specResp.json();
// Stats
document.getElementById('bg-stats').innerHTML = `
<div class="bg-stat"><div class="bg-stat-value">${info.elapsed_hours.toFixed(1)}h</div><div class="bg-stat-label">Durée</div></div>
<div class="bg-stat"><div class="bg-stat-value">${info.live_time_s.toFixed(0)}s</div><div class="bg-stat-label">Live time</div></div>
<div class="bg-stat"><div class="bg-stat-value">${info.total_counts.toFixed(0)}</div><div class="bg-stat-label">Coups</div></div>
<div class="bg-stat"><div class="bg-stat-value">${info.cps.toFixed(2)}</div><div class="bg-stat-label">CPS</div></div>
`;
// Chart
updateBackgroundChart(spec);
// Peaks table
updatePeaksTable(info.top_peaks || []);
} catch {}
}
function updateBackgroundChart(spec) {
const ctx = document.getElementById('background-chart').getContext('2d');
const chartData = {
labels: spec.energy_kev,
datasets: [{
label: 'Background',
data: spec.counts,
borderColor: '#ff9800',
backgroundColor: 'rgba(255, 152, 0, 0.1)',
borderWidth: 1,
pointRadius: 0,
fill: true,
}]
};
const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { labels: { color: '#e0e0e0' } },
tooltip: {
callbacks: {
title: (items) => `${spec.energy_kev[items[0].dataIndex]} keV`,
label: (item) => `${item.raw.toFixed(1)} counts`
}
}
},
scales: {
x: {
type: 'linear',
title: { display: true, text: 'Énergie (keV)', color: '#888' },
ticks: { color: '#888', maxTicksLimit: 20 },
grid: { color: '#333' },
},
y: {
title: { display: true, text: 'Comptages', color: '#888' },
ticks: { color: '#888' },
grid: { color: '#333' },
}
}
};
if (bgChart) {
bgChart.data = chartData;
bgChart.options = options;
bgChart.update();
} else {
bgChart = new Chart(ctx, { type: 'line', data: chartData, options });
}
}
function updatePeaksTable(peaks) {
const container = document.getElementById('peaks-table');
if (!peaks || peaks.length === 0) {
container.innerHTML = '<p style="color:#888;text-align:center;padding:8px;">Pas assez de données pour identifier les pics</p>';
return;
}
let html = '<h3 style="margin-bottom:8px;color:#ff9800;">Pics détectés</h3>';
peaks.forEach(p => {
html += `<div class="peak-row">
<span style="color:#4fc3f7">${p.energy_kev.toFixed(1)} keV</span>
<span>${p.counts.toFixed(0)} cts</span>
</div>`;
});
container.innerHTML = html;
}
document.querySelector('[data-tab="background"]').addEventListener('click', refreshBackground);

83
web/static/js/cps.js Normal file
View File

@ -0,0 +1,83 @@
let cpsChart = null;
async function loadCps(hours = 24) {
// Highlight active button
document.querySelectorAll('.controls button').forEach(b => b.style.opacity = '0.6');
const activeBtn = [...document.querySelectorAll('.controls button')].find(
b => b.textContent.includes(hours <= 24 ? `${hours}h` : `${hours/24}j`) || (hours === 168 && b.textContent === '7j')
);
if (activeBtn) activeBtn.style.opacity = '1';
try {
const resp = await fetch(`${API_BASE}/api/cps/timeline?hours=${hours}`);
if (!resp.ok) return;
const data = await resp.json();
if (!data.data_points || data.data_points.length === 0) {
return;
}
const labels = data.data_points.map(d => d.ts);
const cpsValues = data.data_points.map(d => d.cps);
updateCpsChart(labels, cpsValues);
} catch {}
}
function updateCpsChart(labels, values) {
const ctx = document.getElementById('cps-chart').getContext('2d');
const chartData = {
labels: labels,
datasets: [{
label: 'CPS',
data: values,
borderColor: '#4caf50',
backgroundColor: 'rgba(76, 175, 80, 0.1)',
borderWidth: 1.5,
pointRadius: 0,
fill: true,
tension: 0.3,
}]
};
const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { labels: { color: '#e0e0e0' } },
},
scales: {
x: {
type: 'time',
time: {
tooltipFormat: 'dd/MM HH:mm',
displayFormats: { minute: 'HH:mm', hour: 'HH:mm', day: 'dd/MM' }
},
title: { display: true, text: 'Temps', color: '#888' },
ticks: { color: '#888', maxTicksLimit: 12 },
grid: { color: '#333' },
},
y: {
title: { display: true, text: 'CPS', color: '#888' },
ticks: { color: '#888' },
grid: { color: '#333' },
beginAtZero: true,
}
}
};
if (cpsChart) {
cpsChart.data = chartData;
cpsChart.options = options;
cpsChart.update();
} else {
// Chart.js needs the date adapter for time axis
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0/dist/chartjs-adapter-date-fns.bundle.min.js';
script.onload = () => {
cpsChart = new Chart(ctx, { type: 'line', data: chartData, options });
};
document.head.appendChild(script);
}
}

39
web/static/js/history.js Normal file
View File

@ -0,0 +1,39 @@
async function loadHistory() {
try {
const resp = await fetch(`${API_BASE}/api/history`);
if (!resp.ok) return;
const reports = await resp.json();
const container = document.getElementById('history-list');
if (reports.length === 0) {
container.innerHTML = '<p style="color:#888;text-align:center;padding:20px;">Aucun rapport disponible</p>';
return;
}
let html = '';
reports.forEach(r => {
const isoText = r.isotopes.length > 0 ? r.isotopes.join(', ') : 'background uniquement';
html += `<div class="history-item" onclick="toggleDetails(this)">
<div class="history-header">
<span class="history-date">${r.date.split('T')[0]}</span>
<span class="history-cps">${r.cps_mean.toFixed(1)} CPS</span>
<span class="history-isotopes">${r.isotope_count} isotope(s)</span>
</div>
<div class="history-details">
<p>Live time: ${r.live_time_hours.toFixed(1)}h | Total: ${r.total_counts} coups</p>
<p>Isotopes: ${isoText}</p>
<p>Background: ${r.background_subtracted ? 'soustrait' : 'non soustrait'}</p>
</div>
</div>`;
});
container.innerHTML = html;
} catch {}
}
function toggleDetails(el) {
const details = el.querySelector('.history-details');
details.classList.toggle('open');
}
// Load on tab switch
document.querySelector('[data-tab="history"]').addEventListener('click', loadHistory);

97
web/static/js/spectrum.js Normal file
View File

@ -0,0 +1,97 @@
let spectrumChart = null;
let currentSpectrumData = null;
async function refreshSpectrum() {
const showDiff = document.getElementById('show-difference').checked;
const endpoint = showDiff ? '/api/spectrum/difference' : '/api/spectrum/current';
try {
const resp = await fetch(`${API_BASE}${endpoint}`);
if (!resp.ok) return;
const data = await resp.json();
currentSpectrumData = data;
updateSpectrumChart(data);
updateIsotopesTable(data.isotopes_detected || []);
} catch {}
}
function updateSpectrumChart(data) {
const logScale = document.getElementById('log-scale').checked;
const ctx = document.getElementById('spectrum-chart').getContext('2d');
const chartData = {
labels: data.energy_kev,
datasets: [{
label: data.background_subtracted ? 'Spectre (background soustrait)' : 'Spectre cumulé',
data: data.counts,
borderColor: '#4fc3f7',
backgroundColor: 'rgba(79, 195, 247, 0.1)',
borderWidth: 1,
pointRadius: 0,
fill: true,
}]
};
const options = {
responsive: true,
maintainAspectRatio: false,
animation: { duration: 300 },
plugins: {
legend: { labels: { color: '#e0e0e0' } },
tooltip: {
callbacks: {
title: (items) => {
const idx = items[0].dataIndex;
return `${data.energy_kev[idx]} keV`;
},
label: (item) => `${item.raw.toFixed(1)} counts`
}
}
},
scales: {
x: {
type: 'linear',
title: { display: true, text: 'Énergie (keV)', color: '#888' },
ticks: { color: '#888', maxTicksLimit: 20 },
grid: { color: '#333' },
},
y: {
type: logScale ? 'logarithmic' : 'linear',
title: { display: true, text: 'Comptages', color: '#888' },
ticks: { color: '#888' },
grid: { color: '#333' },
}
}
};
if (spectrumChart) {
spectrumChart.data = chartData;
spectrumChart.options = options;
spectrumChart.update();
} else {
spectrumChart = new Chart(ctx, { type: 'line', data: chartData, options });
}
}
function updateIsotopesTable(isotopes) {
const container = document.getElementById('isotopes-table');
if (!isotopes || isotopes.length === 0) {
container.innerHTML = '<p style="color:#888;text-align:center;padding:8px;">Aucun isotope détecté (background uniquement)</p>';
return;
}
let html = '<h3 style="margin-bottom:8px;color:#4fc3f7;">Isotopes détectés</h3>';
isotopes.forEach(iso => {
const probColor = iso.probability > 0.9 ? '#4caf50' : iso.probability > 0.7 ? '#ff9800' : '#f44336';
html += `<div class="isotope-row">
<span class="isotope-name">${iso.isotope}</span>
<span class="isotope-prob" style="color:${probColor}">${(iso.probability * 100).toFixed(1)}%</span>
<span class="isotope-activity">${iso.activity_bq.toFixed(1)} Bq</span>
</div>`;
});
container.innerHTML = html;
}
// Event listeners
document.getElementById('show-difference').addEventListener('change', refreshSpectrum);
document.getElementById('log-scale').addEventListener('change', refreshSpectrum);