update chức năng ndvi time seriese

This commit is contained in:
Victor Phan
2025-12-22 07:20:41 +07:00
parent 2f79565ca7
commit ec6dfa2587
12 changed files with 3558 additions and 66 deletions
+426 -23
View File
@@ -292,7 +292,26 @@
<p>Phân loại đất cho khu vực mới sử dụng model đã train</p>
</div>
<div class="content">
<div style="background: white; padding: 15px; display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; border-bottom: 2px solid #e0e0e0;">
<a href="/" style="padding: 10px 20px; background: #667eea; color: white; border-radius: 8px; text-decoration: none; font-weight: 600;">🏠 Trang Chủ</a>
<a href="/training" style="padding: 10px 20px; background: #f093fb; color: white; border-radius: 8px; text-decoration: none; font-weight: 600;">🎓 Training</a>
<a href="/prediction" style="padding: 10px 20px; background: #4facfe; color: white; border-radius: 8px; text-decoration: none; font-weight: 600;">🗺️ Prediction (Active)</a>
<a href="/batch" style="padding: 10px 20px; background: #764ba2; color: white; border-radius: 8px; text-decoration: none; font-weight: 600;">🚀 Batch Processing</a>
<a href="/ndvi" style="padding: 10px 20px; background: #2ecc71; color: white; border-radius: 8px; text-decoration: none; font-weight: 600;">🌿 NDVI Analysis</a>
</div>
<!-- Tab Navigation -->
<div style="background: white; padding: 15px; border-bottom: 2px solid #e0e0e0; display: flex; gap: 10px; justify-content: center;">
<button onclick="switchPredictTab('prediction')" id="tabPrediction" style="padding: 10px 20px; background: #4facfe; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;">
🗺️ Prediction
</button>
<button onclick="switchPredictTab('ndvi')" id="tabNDVI" style="padding: 10px 20px; background: #ccc; color: #666; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;">
🌿 NDVI Analysis
</button>
</div>
<!-- Prediction Content -->
<div id="predictionContent" class="content">
<!-- Map Section -->
<div class="map-container">
<div class="map-instructions">
@@ -362,8 +381,18 @@
</select>
</div>
<button class="btn btn-primary" onclick="startPrediction()" id="predictBtn">
🚀 Start Prediction
<div class="form-group" style="margin-top: 20px; padding: 15px; background: #e7f3ff; border-radius: 8px; border-left: 4px solid #2196F3;">
<label style="display: flex; align-items: center; cursor: pointer; margin: 0;">
<input type="checkbox" id="exportNDVI" checked style="width: 18px; height: 18px; margin-right: 10px;">
<span style="font-weight: 600; color: #1976d2;">🌿 Export NDVI Raster</span>
</label>
<div style="font-size: 12px; color: #1976d2; margin-top: 8px; margin-left: 28px;">
✅ Xuất ra file GeoTIFF chứa giá trị NDVI cho toàn bộ khu vực
</div>
</div>
<button class="btn btn-primary" onclick="startPrediction()" id="predictBtn" style="margin-top: 15px;">
🚀 Start Prediction (với NDVI)
</button>
</div>
@@ -417,11 +446,103 @@
</div>
</div>
</div>
<!-- NDVI Analysis Content -->
<div id="ndviContent" class="content" style="display: none;">
<!-- NDVI Configuration -->
<div class="section">
<h2>⚙️ Cấu hình NDVI</h2>
<div class="form-group">
<label>Bbox (dùng bbox từ prediction hoặc nhập mới):</label>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<input type="number" id="ndviMinLon" placeholder="Min Lon" step="0.0001">
<input type="number" id="ndviMinLat" placeholder="Min Lat" step="0.0001">
<input type="number" id="ndviMaxLon" placeholder="Max Lon" step="0.0001">
<input type="number" id="ndviMaxLat" placeholder="Max Lat" step="0.0001">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="ndviStartDate">Từ ngày:</label>
<input type="date" id="ndviStartDate" value="2023-01-01">
</div>
<div class="form-group">
<label for="ndviEndDate">Đến ngày:</label>
<input type="date" id="ndviEndDate" value="2023-12-31">
</div>
</div>
<div class="form-group">
<label for="ndviCloudCover">Cloud Cover tối đa (%):</label>
<input type="number" id="ndviCloudCover" value="30" min="0" max="100">
</div>
<button class="btn btn-primary" onclick="calculateNDVI()" id="ndviCalculateBtn">
📊 Tính NDVI Time Series
</button>
<button class="btn btn-secondary" onclick="usePredictionBbox()" style="margin-left: 10px;">
📍 Dùng Bbox từ Prediction
</button>
</div>
<!-- NDVI Results -->
<div class="section">
<h2>📈 Kết quả NDVI</h2>
<div id="ndviLoading" style="display: none; text-align: center; padding: 20px;">
<p>⏳ Đang tải dữ liệu và tính toán NDVI...</p>
<div style="margin-top: 10px; width: 100%; height: 20px; background: #e0e0e0; border-radius: 10px; overflow: hidden;">
<div id="ndviProgressBar" style="width: 0%; height: 100%; background: linear-gradient(90deg, #2ecc71, #27ae60); transition: width 0.3s;"></div>
</div>
</div>
<div id="ndviResults" style="display: none;">
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin-bottom: 20px;">
<div style="background: #e8f5e9; padding: 15px; border-radius: 8px; border-left: 4px solid #2ecc71;">
<h4 style="color: #666; font-size: 0.9em; margin-bottom: 5px;">Số ảnh</h4>
<p id="ndviStatImages" style="color: #2ecc71; font-size: 1.5em; font-weight: bold;">-</p>
</div>
<div style="background: #e8f5e9; padding: 15px; border-radius: 8px; border-left: 4px solid #2ecc71;">
<h4 style="color: #666; font-size: 0.9em; margin-bottom: 5px;">NDVI TB</h4>
<p id="ndviStatAvg" style="color: #2ecc71; font-size: 1.5em; font-weight: bold;">-</p>
</div>
<div style="background: #e8f5e9; padding: 15px; border-radius: 8px; border-left: 4px solid #2ecc71;">
<h4 style="color: #666; font-size: 0.9em; margin-bottom: 5px;">NDVI Min</h4>
<p id="ndviStatMin" style="color: #2ecc71; font-size: 1.5em; font-weight: bold;">-</p>
</div>
<div style="background: #e8f5e9; padding: 15px; border-radius: 8px; border-left: 4px solid #2ecc71;">
<h4 style="color: #666; font-size: 0.9em; margin-bottom: 5px;">NDVI Max</h4>
<p id="ndviStatMax" style="color: #2ecc71; font-size: 1.5em; font-weight: bold;">-</p>
</div>
</div>
<div style="margin-top: 15px;">
<button class="btn btn-success" onclick="downloadNDVIData()">💾 Download CSV</button>
<button class="btn btn-primary" onclick="downloadNDVIChart()" style="margin-left: 10px;">📸 Download Chart</button>
</div>
</div>
<div id="ndviError" class="alert alert-danger" style="display: none;">
<h3>⚠️ Lỗi</h3>
<p id="ndviErrorMessage"></p>
</div>
</div>
<!-- NDVI Chart -->
<div class="section" id="ndviChartSection" style="grid-column: 1 / -1; display: none;">
<h2 style="color: #2ecc71; margin-bottom: 20px;">📊 NDVI Time Series</h2>
<canvas id="ndviChart"></canvas>
</div>
</div>
</div>
<!-- Scripts -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
// Map setup
@@ -430,6 +551,8 @@
let currentPredictionFile = null;
let currentReportFile = null;
let statusCheckInterval = null;
let ndviData = null;
let ndviChart = null;
// Initialize map
function initMap() {
@@ -594,6 +717,9 @@
return;
}
// Check if export NDVI is enabled
const exportNDVI = document.getElementById('exportNDVI').checked;
const config = {
model_filename: modelFilename,
min_lon: selectedBbox.min_lon,
@@ -604,7 +730,9 @@
end_date: document.getElementById('predEndDate').value,
max_scenes: parseInt(document.getElementById('predMaxScenes').value),
cloud_cover: parseInt(document.getElementById('predCloudCover').value),
resolution: parseInt(document.getElementById('predResolution').value)
resolution: parseInt(document.getElementById('predResolution').value),
export_ndvi: exportNDVI,
export_classification: true
};
try {
@@ -613,7 +741,10 @@
document.getElementById('predictionResult').style.display = 'none';
document.getElementById('predictionError').style.display = 'none';
const response = await fetch('/api/prediction/start', {
// Choose API endpoint based on NDVI export option
const endpoint = exportNDVI ? '/api/predict/with-ndvi' : '/api/prediction/start';
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
@@ -622,8 +753,40 @@
const result = await response.json();
if (response.ok) {
// Start monitoring status
startStatusCheck();
if (exportNDVI) {
// Direct result for NDVI prediction
document.getElementById('predictionStatus').style.display = 'none';
document.getElementById('predictionResult').style.display = 'block';
// Display results
const outputFiles = result.output_files.map(f => f.path).join(', ');
document.getElementById('resultFile').textContent = outputFiles;
// Show NDVI stats
const statsHTML = `
<h4>🌿 NDVI Statistics:</h4>
<p>Mean: ${result.ndvi_stats.mean.toFixed(3)}</p>
<p>Min: ${result.ndvi_stats.min.toFixed(3)}</p>
<p>Max: ${result.ndvi_stats.max.toFixed(3)}</p>
<p>Std: ${result.ndvi_stats.std.toFixed(3)}</p>
<h4>📊 Class Distribution:</h4>
<p>${JSON.stringify(result.class_distribution, null, 2)}</p>
`;
document.getElementById('resultShape').innerHTML = statsHTML;
document.getElementById('resultClasses').textContent = `${result.n_scenes} scenes used`;
currentPredictionFile = result.output_files.find(f => f.type === 'classification')?.path || '';
currentReportFile = null;
document.getElementById('predictBtn').disabled = false;
// Reload predictions list
await loadPredictionsList();
} else {
// Start monitoring status for regular prediction
startStatusCheck();
}
} else {
throw new Error(result.detail || 'Lỗi khi bắt đầu prediction');
}
@@ -736,23 +899,52 @@
return;
}
listDiv.innerHTML = data.predictions.map(pred => `
<div class="prediction-item">
<div>
<strong>${pred.filename}</strong>
<br>
<small style="color: #666;">
${new Date(pred.created).toLocaleString('vi-VN')} - ${pred.size_mb} MB
</small>
listDiv.innerHTML = data.predictions.map(pred => {
const isBatchJob = pred.is_batch_job;
const batchInfo = pred.batch_metadata;
let batchLabel = '';
if (isBatchJob && batchInfo) {
const timestamp = batchInfo.batch_timestamp ?
new Date(batchInfo.batch_timestamp).toLocaleString('vi-VN') :
'N/A';
batchLabel = `
<div style="background: #fff3cd; padding: 5px 10px; border-radius: 5px; margin-top: 5px; border-left: 3px solid #ffc107;">
<small style="color: #856404;">
<strong>🚀 Batch Job:</strong> ${batchInfo.batch_name || 'N/A'}<br>
<strong>ID:</strong> ${batchInfo.batch_job_id || 'N/A'} |
<strong>Thời gian:</strong> ${timestamp}
</small>
</div>
`;
}
return `
<div class="prediction-item" style="border-left: ${isBatchJob ? '4px solid #ffc107' : '4px solid #667eea'};">
<div style="flex: 1;">
<strong>${pred.filename}</strong>
${isBatchJob ? '<span style="background: #ffc107; color: white; padding: 2px 8px; border-radius: 3px; font-size: 0.8em; margin-left: 8px;">BATCH</span>' : ''}
<br>
<small style="color: #666;">
${new Date(pred.created).toLocaleString('vi-VN')} - ${pred.size_mb} MB
</small>
${batchLabel}
</div>
<div style="display: flex; flex-direction: column; gap: 8px;">
<button class="btn btn-success" style="padding: 8px 16px; font-size: 0.9em;"
onclick="window.location.href='${pred.download_url}'">
💾 Download GeoTIFF
</button>
${pred.has_preview ? `
<button class="btn btn-primary" style="padding: 8px 16px; font-size: 0.9em;"
onclick="window.open('${pred.preview_url}', '_blank')">
🖼️ View PNG
</button>
` : ''}
</div>
</div>
<div>
<button class="btn btn-success" style="padding: 8px 16px; font-size: 0.9em;"
onclick="window.location.href='${pred.download_url}'">
💾 Download
</button>
</div>
</div>
`).join('');
`;
}).join('');
} catch (error) {
console.error('Error loading predictions:', error);
}
@@ -798,6 +990,217 @@
window.onbeforeunload = function() {
stopStatusCheck();
};
// ============ NDVI FUNCTIONS ============
// Switch between prediction and NDVI tabs
function switchPredictTab(tab) {
if (tab === 'prediction') {
document.getElementById('predictionContent').style.display = 'grid';
document.getElementById('ndviContent').style.display = 'none';
document.getElementById('tabPrediction').style.background = '#4facfe';
document.getElementById('tabPrediction').style.color = 'white';
document.getElementById('tabNDVI').style.background = '#ccc';
document.getElementById('tabNDVI').style.color = '#666';
} else {
document.getElementById('predictionContent').style.display = 'none';
document.getElementById('ndviContent').style.display = 'grid';
document.getElementById('tabPrediction').style.background = '#ccc';
document.getElementById('tabPrediction').style.color = '#666';
document.getElementById('tabNDVI').style.background = '#2ecc71';
document.getElementById('tabNDVI').style.color = 'white';
}
}
// Use bbox from prediction form
function usePredictionBbox() {
if (!selectedBbox) {
alert('⚠️ Chưa chọn bbox trong phần Prediction. Vui lòng vẽ bbox trên bản đồ trước!');
return;
}
document.getElementById('ndviMinLon').value = selectedBbox[0].toFixed(4);
document.getElementById('ndviMinLat').value = selectedBbox[1].toFixed(4);
document.getElementById('ndviMaxLon').value = selectedBbox[2].toFixed(4);
document.getElementById('ndviMaxLat').value = selectedBbox[3].toFixed(4);
alert('✅ Đã copy bbox từ Prediction!');
}
// Calculate NDVI time series
async function calculateNDVI() {
const minLon = parseFloat(document.getElementById('ndviMinLon').value);
const minLat = parseFloat(document.getElementById('ndviMinLat').value);
const maxLon = parseFloat(document.getElementById('ndviMaxLon').value);
const maxLat = parseFloat(document.getElementById('ndviMaxLat').value);
const startDate = document.getElementById('ndviStartDate').value;
const endDate = document.getElementById('ndviEndDate').value;
const maxCloudCover = parseInt(document.getElementById('ndviCloudCover').value);
// Validate
if (isNaN(minLon) || isNaN(minLat) || isNaN(maxLon) || isNaN(maxLat)) {
showNDVIError('Vui lòng nhập đầy đủ tọa độ bbox!');
return;
}
if (!startDate || !endDate) {
showNDVIError('Vui lòng chọn khoảng thời gian!');
return;
}
// Show loading
document.getElementById('ndviLoading').style.display = 'block';
document.getElementById('ndviResults').style.display = 'none';
document.getElementById('ndviChartSection').style.display = 'none';
document.getElementById('ndviError').style.display = 'none';
document.getElementById('ndviCalculateBtn').disabled = true;
const config = {
bbox: [minLon, minLat, maxLon, maxLat],
start_date: startDate,
end_date: endDate,
max_cloud_cover: maxCloudCover,
resolution: 20
};
try {
const response = await fetch('/api/ndvi/timeseries', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
});
const result = await response.json();
if (response.ok) {
ndviData = result;
displayNDVIResults(result);
} else {
throw new Error(result.detail || 'Lỗi khi tính NDVI');
}
} catch (error) {
console.error('Error calculating NDVI:', error);
showNDVIError(error.message);
} finally {
document.getElementById('ndviLoading').style.display = 'none';
document.getElementById('ndviCalculateBtn').disabled = false;
}
}
// Display NDVI results
function displayNDVIResults(data) {
document.getElementById('ndviResults').style.display = 'block';
document.getElementById('ndviChartSection').style.display = 'block';
// Update stats
document.getElementById('ndviStatImages').textContent = data.n_images;
document.getElementById('ndviStatAvg').textContent = data.mean_ndvi.toFixed(3);
document.getElementById('ndviStatMin').textContent = data.min_ndvi.toFixed(3);
document.getElementById('ndviStatMax').textContent = data.max_ndvi.toFixed(3);
// Create chart
createNDVIChart(data);
}
// Create NDVI chart
function createNDVIChart(data) {
const ctx = document.getElementById('ndviChart').getContext('2d');
// Destroy existing chart
if (ndviChart) {
ndviChart.destroy();
}
const dates = data.timeseries.map(item => new Date(item.date).toLocaleDateString('vi-VN'));
const ndviValues = data.timeseries.map(item => item.ndvi);
ndviChart = new Chart(ctx, {
type: 'line',
data: {
labels: dates,
datasets: [{
label: 'NDVI',
data: ndviValues,
borderColor: '#2ecc71',
backgroundColor: 'rgba(46, 204, 113, 0.1)',
borderWidth: 2,
fill: true,
tension: 0.4,
pointRadius: 4,
pointHoverRadius: 6,
pointBackgroundColor: '#2ecc71',
pointBorderColor: '#fff',
pointBorderWidth: 2
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
title: {
display: true,
text: 'NDVI Time Series - Biến động chỉ số thực vật theo thời gian',
font: { size: 16, weight: 'bold' }
},
legend: {
display: true,
position: 'top'
},
tooltip: {
callbacks: {
label: function(context) {
return `NDVI: ${context.parsed.y.toFixed(3)}`;
}
}
}
},
scales: {
y: {
beginAtZero: false,
title: { display: true, text: 'NDVI Value' },
grid: { color: 'rgba(0, 0, 0, 0.05)' }
},
x: {
title: { display: true, text: 'Ngày' },
grid: { display: false }
}
}
}
});
}
// Download NDVI data as CSV
function downloadNDVIData() {
if (!ndviData) return;
let csv = 'Date,NDVI\\n';
ndviData.timeseries.forEach(item => {
csv += `${item.date},${item.ndvi}\\n`;
});
const blob = new Blob([csv], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `ndvi_timeseries_${new Date().toISOString().split('T')[0]}.csv`;
a.click();
window.URL.revokeObjectURL(url);
}
// Download NDVI chart as PNG
function downloadNDVIChart() {
if (!ndviChart) return;
const url = ndviChart.toBase64Image();
const a = document.createElement('a');
a.href = url;
a.download = `ndvi_chart_${new Date().toISOString().split('T')[0]}.png`;
a.click();
}
// Show NDVI error
function showNDVIError(message) {
document.getElementById('ndviError').style.display = 'block';
document.getElementById('ndviErrorMessage').textContent = message;
}
</script>
</body>
</html>