Files
remote-sensing/prediction_interface.html
T
2026-01-06 12:25:42 +07:00

2273 lines
105 KiB
HTML

<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prediction Interface - Land Classification</title>
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css" />
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
min-height: 100vh;
}
.container {
max-width: 1400px;
margin: 0 auto;
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 2.5em;
margin-bottom: 10px;
}
.header p {
opacity: 0.9;
font-size: 1.1em;
}
.content {
padding: 30px;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 30px;
}
#predictMap {
height: 500px;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
.map-container {
grid-column: 1 / -1;
}
.map-instructions {
background: #e3f2fd;
padding: 15px;
border-radius: 10px;
margin-bottom: 15px;
border-left: 4px solid #2196f3;
}
.map-instructions h3 {
color: #1976d2;
margin-bottom: 8px;
}
.map-instructions p {
color: #555;
margin: 5px 0;
}
.section {
margin-bottom: 30px;
padding: 20px;
background: #f8f9fa;
border-radius: 10px;
}
.section h2 {
color: #667eea;
margin-bottom: 15px;
font-size: 1.5em;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
color: #333;
font-weight: 600;
}
.form-group input, .form-group select {
width: 100%;
padding: 10px;
border: 2px solid #e0e0e0;
border-radius: 5px;
font-size: 1em;
transition: border-color 0.3s;
}
.form-group input:focus, .form-group select:focus {
outline: none;
border-color: #667eea;
}
.form-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
}
.btn {
padding: 12px 30px;
border: none;
border-radius: 5px;
font-size: 1em;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
margin-right: 10px;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
.btn-success {
background: #28a745;
color: white;
}
.btn-success:hover {
background: #218838;
}
.btn-secondary {
background: #6c757d;
color: white;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.status-box {
padding: 20px;
background: white;
border-radius: 10px;
border-left: 5px solid #667eea;
margin-bottom: 20px;
}
.status-box.success {
border-left-color: #28a745;
background: #d4edda;
}
.status-box.error {
border-left-color: #dc3545;
background: #f8d7da;
}
.status-box.predicting {
border-left-color: #ffc107;
background: #fff3cd;
}
.progress {
height: 30px;
background: #e0e0e0;
border-radius: 15px;
overflow: hidden;
margin: 10px 0;
}
.progress-bar {
height: 100%;
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
width: 0%;
transition: width 0.3s;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 600;
}
.metric-card {
background: white;
padding: 15px;
border-radius: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
text-align: center;
}
.metric-card h4 {
color: #667eea;
margin-bottom: 10px;
}
.metric-card .value {
font-size: 2em;
font-weight: bold;
color: #333;
}
.alert {
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
.alert-info {
background: #d1ecf1;
border-left: 4px solid #0c5460;
color: #0c5460;
}
.alert-success {
background: #d4edda;
border-left: 4px solid #155724;
color: #155724;
}
.alert-danger {
background: #f8d7da;
border-left: 4px solid #721c24;
color: #721c24;
}
.predictions-list {
max-height: 400px;
overflow-y: auto;
}
.prediction-item {
background: white;
padding: 15px;
border-radius: 8px;
margin-bottom: 10px;
border-left: 4px solid #667eea;
display: flex;
justify-content: space-between;
align-items: center;
}
.prediction-item:hover {
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
@media (max-width: 768px) {
.content {
grid-template-columns: 1fr;
}
.form-row {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🗺️ Prediction Interface</h1>
<p>Phân loại đất cho khu vực mới sử dụng model đã train</p>
</div>
<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>
<a href="/reports" style="padding: 10px 20px; background: #ff6b6b; color: white; border-radius: 8px; text-decoration: none; font-weight: 600;">📝 Reports</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">
<!-- Province Selection Section -->
<div class="section" style="grid-column: 1 / -1;">
<h2>🗺️ Chọn Khu Vực Prediction</h2>
<div class="form-group" style="margin-bottom: 20px;">
<label>
<strong>🗺️ Chọn theo Tỉnh Thành:</strong>
<span style="color: #999; font-size: 13px; font-weight: normal;">(Hoặc vẽ bbox thủ công bên dưới)</span>
</label>
<!-- Toggle between 63 and 32 provinces -->
<div style="margin-bottom: 10px; display: flex; gap: 10px; align-items: center;">
<button type="button" id="btnPred63Provinces" onclick="switchPredProvinceList('63')" style="padding: 8px 16px; background: #667eea; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">63 Tỉnh (Cũ)</button>
<button type="button" id="btnPred32Provinces" onclick="switchPredProvinceList('32')" style="padding: 8px 16px; background: #f0f0f0; color: #333; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">32 Tỉnh (Sau sáp nhập)</button>
<span id="predProvinceListMode" style="color: #667eea; font-weight: bold;">Danh sách: 63 tỉnh</span>
</div>
<select id="predProvinceSelect" style="padding: 12px; width: 100%; border: 2px solid #ddd; border-radius: 8px; font-size: 14px; cursor: pointer;">
<option value="">-- Chọn tỉnh thành để tải bbox tự động --</option>
</select>
</div>
<!-- Region Filter -->
<div class="form-group" style="margin-bottom: 20px;">
<label><strong>🌍 Lọc theo Vùng:</strong></label>
<div id="predRegionFilterContainer" style="display: flex; gap: 10px; flex-wrap: wrap;">
<button type="button" class="pred-region-filter-btn" data-region="all" style="padding: 8px 16px; background: #667eea; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">Tất cả</button>
<!-- Dynamic region buttons will be added here -->
</div>
</div>
</div>
<!-- Map Section -->
<div class="map-container">
<div class="map-instructions">
<h3>💡 Hướng dẫn:</h3>
<p>📍 Chọn tỉnh thành ở trên để tự động điền bbox, hoặc sử dụng công cụ vẽ hình chữ nhật trên bản đồ</p>
<p>🔄 Có thể chỉnh sửa sau khi vẽ</p>
</div>
<div id="predictMap"></div>
<!-- Prediction Cache Section -->
<div class="section" style="margin-top: 20px;">
<h3>💾 Cache Predictions (Tự động lưu)</h3>
<p style="color: #666; font-size: 0.9em; margin-bottom: 10px;">Cache được tự động tạo sau mỗi lần predict thành công</p>
<div style="display: flex; gap: 10px; margin-bottom: 15px;">
<select id="predCacheSelect" style="flex: 1; padding: 10px; border: 2px solid #e0e0e0; border-radius: 5px;">
<option value="">-- Chọn cache để phục hồi cấu hình --</option>
</select>
<button onclick="loadPredictionCache()" class="btn btn-success">📂 Phục hồi</button>
<button onclick="refreshPredCache()" class="btn btn-secondary" title="Làm mới danh sách">🔄</button>
</div>
<div id="predCacheList" style="max-height: 200px; overflow-y: auto; background: white; border-radius: 5px; padding: 10px;"></div>
</div>
</div>
<!-- Model Selection -->
<div class="section">
<h2>🤖 Chọn Model</h2>
<div class="form-group">
<label for="modelSelect">Model đã train:</label>
<select id="modelSelect">
<option value="">Đang tải...</option>
</select>
</div>
<!-- Cache selection dropdown -->
<div class="form-group" style="margin-top:15px;">
<label for="cacheSelect">Chọn cache dữ liệu đầu vào:</label>
<select id="cacheSelect">
<option value="">-- Không dùng cache --</option>
</select>
</div>
<div id="modelInfo" style="display: none; background: #e8f5e9; padding: 15px; border-radius: 8px; margin-top: 15px;">
<h4 style="color: #2e7d32; margin-bottom: 10px;">📊 Thông tin Model</h4>
<p><strong>Type:</strong> <span id="modelType">-</span></p>
<p><strong>Accuracy:</strong> <span id="modelAccuracy">-</span></p>
<p><strong>Training Date:</strong> <span id="modelDate">-</span></p>
</div>
</div>
<!-- Time & Data Configuration -->
<div class="section">
<h2>⏰ Thời gian & Dữ liệu</h2>
<div class="form-row">
<div class="form-group">
<label for="predStartDate">Từ ngày:</label>
<input type="date" id="predStartDate" value="2023-03-01">
</div>
<div class="form-group">
<label for="predEndDate">Đến ngày:</label>
<input type="date" id="predEndDate" value="2023-05-31">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="predMaxScenes">Max Scenes:</label>
<input type="number" id="predMaxScenes" value="12" min="1" max="100">
</div>
<div class="form-group">
<label for="predCloudCover">Cloud Cover (%):</label>
<input type="number" id="predCloudCover" value="30" min="0" max="100">
</div>
</div>
<div class="form-group">
<label for="predResolution">Resolution:</label>
<select id="predResolution">
<option value="10">10m (Chi tiết cao - Chậm)</option>
<option value="20" selected>20m (Cân bằng)</option>
</select>
</div>
<div class="form-group" style="margin-top: 15px; padding: 15px; background: #fff3e0; border-radius: 8px; border-left: 4px solid #ff9800;">
<label style="display: flex; align-items: center; cursor: pointer; margin: 0;">
<input type="checkbox" id="useGpuPred" checked style="width: 18px; height: 18px; margin-right: 10px;">
<span style="font-weight: 600; color: #e65100;">🚀 Sử dụng GPU (Deep Learning Models)</span>
</label>
<div style="font-size: 12px; color: #e65100; margin-top: 8px; margin-left: 28px;">
⚡ Tăng tốc prediction cho CNN/Swin-UNet models (yêu cầu GPU khả dụng)
</div>
</div>
<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>
<!-- Status Section -->
<div class="section" style="grid-column: 1 / -1;">
<h2>📊 Trạng thái Prediction</h2>
<div id="predictionStatus" class="status-box" style="display: none;">
<h3>⏳ Đang xử lý...</h3>
<p id="predictionProgress">Đang khởi tạo...</p>
<div class="progress">
<div class="progress-bar" id="predictionProgressBar">0%</div>
</div>
</div>
<div id="predictionResult" style="display: none;">
<div class="alert alert-success">
<h3>✅ Prediction hoàn thành!</h3>
<p><strong>Output file:</strong> <span id="resultFile"></span></p>
<p><strong>Shape:</strong> <span id="resultShape"></span></p>
<p><strong>Unique classes:</strong> <span id="resultClasses"></span></p>
<!-- PNG Preview -->
<div id="pngPreviewContainer" style="display: none; margin: 20px 0;">
<h4 style="margin-bottom: 10px;">🖼️ Preview:</h4>
<img id="pngPreview" style="max-width: 100%; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.2);" />
</div>
<div style="margin-top: 15px;">
<button class="btn btn-success" onclick="downloadPrediction()">
💾 Download GeoTIFF
</button>
<button class="btn btn-secondary" onclick="viewReport()">
📄 View Report
</button>
</div>
</div>
</div>
<div id="predictionError" class="alert alert-danger" style="display: none;">
<h3>❌ Lỗi</h3>
<p id="errorMessage"></p>
</div>
</div>
<!-- Previous Predictions -->
<div class="section" style="grid-column: 1 / -1;">
<h2>📋 Predictions đã tạo</h2>
<div id="predictionsList" class="predictions-list">
<p style="text-align: center; color: #666;">Đang tải...</p>
</div>
</div>
</div>
<!-- NDVI Analysis Content -->
<div id="ndviContent" class="content" style="display: none;">
<!-- Province Selection for NDVI -->
<div class="section" style="grid-column: 1 / -1;">
<h2>🗺️ Chọn Khu Vực NDVI Analysis</h2>
<div class="form-group" style="margin-bottom: 20px;">
<label>
<strong>🗺️ Chọn theo Tỉnh Thành:</strong>
<span style="color: #999; font-size: 13px; font-weight: normal;">(Hoặc vẽ bbox thủ công bên dưới)</span>
</label>
<!-- Toggle between 63 and 32 provinces -->
<div style="margin-bottom: 10px; display: flex; gap: 10px; align-items: center;">
<button type="button" id="btnNDVI63Provinces" onclick="switchNDVIProvinceList('63')" style="padding: 8px 16px; background: #2ecc71; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">63 Tỉnh (Cũ)</button>
<button type="button" id="btnNDVI32Provinces" onclick="switchNDVIProvinceList('32')" style="padding: 8px 16px; background: #f0f0f0; color: #333; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">32 Tỉnh (Sau sáp nhập)</button>
<span id="ndviProvinceListMode" style="color: #2ecc71; font-weight: bold;">Danh sách: 63 tỉnh</span>
</div>
<select id="ndviProvinceSelect" style="padding: 12px; width: 100%; border: 2px solid #ddd; border-radius: 8px; font-size: 14px; cursor: pointer;">
<option value="">-- Chọn tỉnh thành để tải bbox tự động --</option>
</select>
</div>
<!-- Region Filter for NDVI -->
<div class="form-group" style="margin-bottom: 20px;">
<label><strong>🌍 Lọc theo Vùng:</strong></label>
<div id="ndviRegionFilterContainer" style="display: flex; gap: 10px; flex-wrap: wrap;">
<button type="button" class="ndvi-region-filter-btn" data-region="all" style="padding: 8px 16px; background: #2ecc71; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">Tất cả</button>
<!-- Dynamic region buttons will be added here -->
</div>
</div>
</div>
<!-- Model Selection for NDVI -->
<div class="section">
<h2>🤖 Chọn Model để Predict</h2>
<div class="form-group">
<label for="ndviModelSelect">Model đã train:</label>
<select id="ndviModelSelect" style="padding: 10px; width: 100%; border: 2px solid #ddd; border-radius: 8px; font-size: 14px; cursor: pointer;">
<option value="">Đang tải...</option>
</select>
</div>
<div id="ndviModelInfo" style="display: none; background: #e8f5e9; padding: 15px; border-radius: 8px; margin-top: 15px;">
<h4 style="color: #2e7d32; margin-bottom: 10px;">📊 Thông tin Model</h4>
<p><strong>Type:</strong> <span id="ndviModelType">-</span></p>
<p><strong>Accuracy:</strong> <span id="ndviModelAccuracy">-</span></p>
<p><strong>Training Date:</strong> <span id="ndviModelDate">-</span></p>
</div>
<div class="form-group" style="margin-top: 15px; padding: 15px; background: #fff3e0; border-radius: 8px; border-left: 4px solid #ff9800;">
<label style="display: flex; align-items: center; cursor: pointer; margin: 0;">
<input type="checkbox" id="useGpuNDVI" checked style="width: 18px; height: 18px; margin-right: 10px;">
<span style="font-weight: 600; color: #e65100;">🚀 Sử dụng GPU (Deep Learning Models)</span>
</label>
<div style="font-size: 12px; color: #e65100; margin-top: 8px; margin-left: 28px;">
⚡ Tăng tốc prediction cho CNN/Swin-UNet models (yêu cầu GPU khả dụng)
</div>
</div>
</div>
<!-- NDVI Configuration -->
<div class="section">
<h2>⚙️ Cấu hình NDVI để so sánh thay đổi</h2>
<!-- Quick Presets -->
<div class="form-group" style="margin-bottom: 20px; padding: 15px; background: #e8f5e9; border-radius: 8px; border-left: 4px solid #4caf50;">
<label style="color: #2e7d32; font-weight: 700; margin-bottom: 10px;">🎯 Quick Presets (Khu vực có dữ liệu tốt)</label>
<select id="ndviQuickPreset" onchange="applyNDVIPreset()" style="padding: 10px; width: 100%; border: 2px solid #4caf50; border-radius: 6px; font-size: 14px; cursor: pointer;">
<option value="">-- Chọn preset để áp dụng tự động --</option>
<option value="mekong_dry">🌾 Đồng bằng Cửu Long - Mùa khô (Jan-Apr 2024)</option>
<option value="hanoi_dry">🏙️ Hà Nội - Mùa khô (Feb-Apr 2024)</option>
<option value="danang_dry">🏖️ Đà Nẵng - Mùa khô (Jan-Mar 2024)</option>
<option value="mekong_2023">🌾 Đồng bằng Cửu Long - Full năm 2023</option>
<option value="small_test">⚡ Test nhanh - Khu vực nhỏ (500 points)</option>
</select>
<div style="font-size: 12px; color: #2e7d32; margin-top: 8px;">💡 Các preset này đã được kiểm tra và có dữ liệu tốt, ít mây</div>
</div>
<!-- NDVI Map for selecting bbox -->
<div class="form-group">
<label>Chọn bbox trên bản đồ hoặc nhập tọa độ:</label>
<div id="ndviMap" style="height: 300px; border-radius: 10px; margin-bottom: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.08);"></div>
<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 style="font-size: 12px; color: #1976d2; margin-top: 8px;">✏️ Vẽ hình chữ nhật trên bản đồ để chọn bbox NDVI, các ô tọa độ sẽ tự động cập nhật.</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>
<div class="form-group">
<label for="ndviMaxScenes">Số scenes tối đa:</label>
<input type="number" id="ndviMaxScenes" value="12" min="1" max="100">
<div style="font-size: 12px; color: #666; margin-top: 5px;">Giới hạn số lượng ảnh vệ tinh xử lý. Ít scenes = nhanh hơn nhưng ít dữ liệu.</div>
</div>
<div class="form-group">
<label for="ndviResolution">Resolution:</label>
<select id="ndviResolution">
<option value="10">10m (Chi tiết cao - Chậm)</option>
<option value="20" selected>20m (Cân bằng)</option>
</select>
</div>
<div class="form-group">
<label for="ndviSamplePoints">Số điểm dự đoán (sample):</label>
<input type="number" id="ndviSamplePoints" value="1000" min="100" max="10000" step="100">
<div style="font-size: 12px; color: #666; margin-top: 5px;">Số điểm ngẫu nhiên để predict và tính NDVI time series. Nhiều điểm = chính xác hơn nhưng chậm hơn.</div>
</div>
<button class="btn btn-primary" onclick="calculateNDVIPrediction()" id="ndviCalculateBtn">
📊 Predict & 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
let map, drawnItems, drawControl;
let ndviMap, ndviDrawnItems, ndviDrawControl;
let selectedBbox = null;
let currentPredictionFile = null;
let currentReportFile = null;
let statusCheckInterval = null;
let ndviData = null;
let ndviChart = null;
// Province data
let allPredProvinces = {};
let allPredProvincesMerged = {};
let currentPredProvinceMode = '63'; // '63' or '32'
let currentPredProvinceName = '';
// Initialize map
function initMap() {
map = L.map('predictMap').setView([9.5, 105.9], 9);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
drawControl = new L.Control.Draw({
draw: {
rectangle: true,
polygon: false,
circle: false,
marker: false,
polyline: false,
circlemarker: false
},
edit: {
featureGroup: drawnItems,
remove: true
}
});
map.addControl(drawControl);
map.on(L.Draw.Event.CREATED, function(event) {
drawnItems.clearLayers();
const layer = event.layer;
drawnItems.addLayer(layer);
const bounds = layer.getBounds();
let bbox = {
min_lon: bounds.getWest(),
min_lat: bounds.getSouth(),
max_lon: bounds.getEast(),
max_lat: bounds.getNorth()
};
if (bbox.min_lon < -180 || bbox.max_lon > 180 || bbox.min_lat < -90 || bbox.max_lat > 90) {
alert('❌ Bbox không hợp lệ! Vui lòng vẽ trong phạm vi bản đồ hợp lệ.\nKinh độ: -180 đến 180, Vĩ độ: -90 đến 90');
drawnItems.clearLayers();
return;
}
selectedBbox = bbox;
localStorage.setItem('prediction_bbox', JSON.stringify(selectedBbox));
console.log('Selected bbox:', selectedBbox);
});
// Restore bbox from cache if exists
const cachedBbox = localStorage.getItem('prediction_bbox');
if (cachedBbox) {
try {
const bbox = JSON.parse(cachedBbox);
if (bbox.min_lon < -180 || bbox.max_lon > 180 || bbox.min_lat < -90 || bbox.max_lat > 90) {
console.warn('Cache bbox không hợp lệ, đã xóa:', bbox);
localStorage.removeItem('prediction_bbox');
} else {
const bounds = [
[bbox.min_lat, bbox.min_lon],
[bbox.max_lat, bbox.max_lon]
];
const rectangle = L.rectangle(bounds, {
color: '#667eea',
weight: 3,
fillOpacity: 0.2
});
drawnItems.addLayer(rectangle);
map.fitBounds(bounds);
selectedBbox = bbox;
}
} catch (e) {
console.warn('Không thể khôi phục bbox từ cache:', e);
localStorage.removeItem('prediction_bbox');
}
}
// NDVI Map setup
ndviMap = L.map('ndviMap').setView([9.5, 105.9], 9);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(ndviMap);
ndviDrawnItems = new L.FeatureGroup();
ndviMap.addLayer(ndviDrawnItems);
ndviDrawControl = new L.Control.Draw({
draw: {
rectangle: true,
polygon: false,
circle: false,
marker: false,
polyline: false,
circlemarker: false
},
edit: {
featureGroup: ndviDrawnItems,
remove: true
}
});
ndviMap.addControl(ndviDrawControl);
ndviMap.on(L.Draw.Event.CREATED, function(event) {
ndviDrawnItems.clearLayers();
const layer = event.layer;
ndviDrawnItems.addLayer(layer);
const bounds = layer.getBounds();
// Update NDVI bbox inputs
document.getElementById('ndviMinLon').value = bounds.getWest().toFixed(4);
document.getElementById('ndviMinLat').value = bounds.getSouth().toFixed(4);
document.getElementById('ndviMaxLon').value = bounds.getEast().toFixed(4);
document.getElementById('ndviMaxLat').value = bounds.getNorth().toFixed(4);
});
// Sync NDVI bbox inputs to map
['ndviMinLon','ndviMinLat','ndviMaxLon','ndviMaxLat'].forEach(id => {
document.getElementById(id).addEventListener('change', function() {
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);
if (!isNaN(minLon) && !isNaN(minLat) && !isNaN(maxLon) && !isNaN(maxLat)) {
ndviDrawnItems.clearLayers();
const bounds = [
[minLat, minLon],
[maxLat, maxLon]
];
const rectangle = L.rectangle(bounds, {
color: '#2ecc71',
weight: 3,
fillOpacity: 0.2
});
ndviDrawnItems.addLayer(rectangle);
ndviMap.fitBounds(bounds);
}
});
});
}
// Load models list
async function loadModels() {
try {
const response = await fetch('/api/models/list');
const data = await response.json();
const select = document.getElementById('modelSelect');
select.innerHTML = '<option value="">Chọn model...</option>';
// Chỉ lấy các file model thực sự (.joblib), loại bỏ các file có chứa '_info.joblib'
data.models
.filter(m => m.filename.endsWith('.joblib') && !m.filename.includes('_info.joblib'))
.forEach(model => {
const option = document.createElement('option');
option.value = model.filename;
option.textContent = `${model.filename} - ${model.created}`;
option.dataset.info = JSON.stringify(model.info);
select.appendChild(option);
});
// Auto-select first model đúng
const firstJoblib = data.models.find(m => m.filename.endsWith('.joblib') && !m.filename.includes('_info.joblib'));
if (firstJoblib) {
select.value = firstJoblib.filename;
updateModelInfo();
}
} catch (error) {
console.error('Error loading models:', error);
}
}
// Update model info display
function updateModelInfo() {
const select = document.getElementById('modelSelect');
const option = select.options[select.selectedIndex];
if (option && option.dataset && option.dataset.info) {
try {
const info = JSON.parse(option.dataset.info);
const infoDiv = document.getElementById('modelInfo');
document.getElementById('modelType').textContent = info.model_type || 'N/A';
document.getElementById('modelAccuracy').textContent = info.metrics?.accuracy
? (info.metrics.accuracy * 100).toFixed(2) + '%'
: 'N/A';
document.getElementById('modelDate').textContent = info.training_date || 'N/A';
infoDiv.style.display = 'block';
} catch (e) {
console.warn('Error parsing model info:', e);
document.getElementById('modelInfo').style.display = 'none';
}
} else {
document.getElementById('modelInfo').style.display = 'none';
}
}
// Start prediction
async function startPrediction() {
if (!selectedBbox) {
alert('❌ Vui lòng vẽ bbox trên bản đồ trước!');
return;
}
// Validate bbox before sending
if (selectedBbox.min_lon < -180 || selectedBbox.max_lon > 180 ||
selectedBbox.min_lat < -90 || selectedBbox.max_lat > 90) {
alert('❌ Bbox không hợp lệ! Vui lòng vẽ lại trong phạm vi bản đồ hợp lệ.');
drawnItems.clearLayers();
selectedBbox = null;
localStorage.removeItem('prediction_bbox');
return;
}
const modelFilename = document.getElementById('modelSelect').value;
if (!modelFilename) {
alert('❌ Vui lòng chọn model!');
return;
}
// Check if export NDVI is enabled
const exportNDVI = document.getElementById('exportNDVI').checked;
const useGpu = document.getElementById('useGpuPred').checked;
const config = {
model_filename: modelFilename,
min_lon: selectedBbox.min_lon,
min_lat: selectedBbox.min_lat,
max_lon: selectedBbox.max_lon,
max_lat: selectedBbox.max_lat,
start_date: document.getElementById('predStartDate').value,
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),
use_gpu: useGpu,
export_ndvi: exportNDVI,
export_classification: true
};
try {
document.getElementById('predictBtn').disabled = true;
document.getElementById('predictionStatus').style.display = 'block';
document.getElementById('predictionResult').style.display = 'none';
document.getElementById('predictionError').style.display = 'none';
// 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)
});
const result = await response.json();
if (response.ok) {
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');
}
} catch (error) {
console.error('Error starting prediction:', error);
document.getElementById('predictionError').style.display = 'block';
document.getElementById('errorMessage').textContent = error.message;
document.getElementById('predictBtn').disabled = false;
}
}
// Check prediction status
async function checkStatus() {
try {
const response = await fetch('/api/prediction/status');
const status = await response.json();
document.getElementById('predictionProgress').textContent = status.progress;
// Update progress bar (estimate based on message)
let progress = 0;
if (status.progress.includes('khởi')) progress = 10;
else if (status.progress.includes('Sentinel-2')) progress = 30;
else if (status.progress.includes('NDVI')) progress = 50;
else if (status.progress.includes('Sentinel-1')) progress = 60;
else if (status.progress.includes('features')) progress = 70;
else if (status.progress.includes('dự đoán')) progress = 80;
else if (status.progress.includes('lưu')) progress = 90;
else if (status.progress.includes('Hoàn thành')) progress = 100;
document.getElementById('predictionProgressBar').style.width = progress + '%';
document.getElementById('predictionProgressBar').textContent = progress + '%';
if (!status.is_predicting) {
stopStatusCheck();
document.getElementById('predictBtn').disabled = false;
if (status.error) {
document.getElementById('predictionStatus').style.display = 'none';
document.getElementById('predictionError').style.display = 'block';
document.getElementById('errorMessage').textContent = status.error;
} else if (status.result) {
document.getElementById('predictionStatus').style.display = 'none';
document.getElementById('predictionResult').style.display = 'block';
currentPredictionFile = status.result.output_file;
currentReportFile = status.result.report_filename;
document.getElementById('resultFile').textContent = status.result.output_file;
document.getElementById('resultShape').textContent = status.result.shape.join(' x ');
document.getElementById('resultClasses').textContent = status.result.unique_classes.join(', ');
// Show PNG preview if available
if (status.result.png_file) {
const pngFilename = status.result.png_file.split('/').pop();
const previewImg = document.getElementById('pngPreview');
const previewContainer = document.getElementById('pngPreviewContainer');
previewImg.src = `/api/predictions/preview/${pngFilename}`;
previewContainer.style.display = 'block';
}
// Reload predictions list
loadPredictionsList();
}
}
} catch (error) {
console.error('Error checking status:', error);
}
}
// Start/stop status monitoring
function startStatusCheck() {
if (statusCheckInterval) clearInterval(statusCheckInterval);
statusCheckInterval = setInterval(checkStatus, 2000);
}
function stopStatusCheck() {
if (statusCheckInterval) {
clearInterval(statusCheckInterval);
statusCheckInterval = null;
}
}
// Download prediction
function downloadPrediction() {
if (currentPredictionFile) {
const filename = currentPredictionFile.split('/').pop();
window.location.href = `/api/predictions/download/${filename}`;
}
}
// View report
function viewReport() {
if (currentReportFile) {
window.open(`/api/reports/view/${currentReportFile}`, '_blank');
}
}
// Load predictions list
async function loadPredictionsList() {
try {
const response = await fetch('/api/predictions/list');
const data = await response.json();
const listDiv = document.getElementById('predictionsList');
if (data.predictions.length === 0) {
listDiv.innerHTML = '<p style="text-align: center; color: #666;">Chưa có prediction nào</p>';
return;
}
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>
`;
}).join('');
} catch (error) {
console.error('Error loading predictions:', error);
}
}
// Load cache list
async function loadCacheList() {
try {
const response = await fetch('/api/cache/info');
const data = await response.json();
const select = document.getElementById('cacheSelect');
select.innerHTML = '<option value="">-- Không dùng cache --</option>';
// Store cache data globally for later use
window.cacheFiles = data.files || [];
if (data.files && data.files.length > 0) {
data.files.forEach((file, idx) => {
if (file.filename.startsWith('prediction_input_')) {
let label = `#${idx+1} | ${file.filename}`;
if (file.metadata && file.metadata.bbox) {
label += ` | BBox: [${file.metadata.bbox.join(', ')}]`;
}
if (file.metadata && file.metadata.time_range) {
label += ` | Time: ${file.metadata.time_range}`;
}
select.innerHTML += `<option value="${file.filename}">${label}</option>`;
}
});
}
} catch (e) {
console.warn('Không thể tải danh sách cache:', e);
}
}
// ============ PREDICTION CACHE FUNCTIONS (Auto-save) ============
// Load prediction cache list
async function loadPredCacheList() {
try {
const response = await fetch('/api/prediction/cache/list');
const data = await response.json();
const select = document.getElementById('predCacheSelect');
const listDiv = document.getElementById('predCacheList');
select.innerHTML = '<option value="">-- Chọn cache để phục hồi cấu hình --</option>';
listDiv.innerHTML = '';
if (data.caches && data.caches.length > 0) {
data.caches.forEach(cache => {
// Add to select dropdown
const option = document.createElement('option');
option.value = cache.filename;
option.textContent = cache.display_name;
option.dataset.config = JSON.stringify(cache.config);
select.appendChild(option);
// Add to list
const item = document.createElement('div');
item.style.cssText = 'background: #f8f9fa; padding: 10px; border-radius: 5px; margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center; border-left: 3px solid #4facfe;';
const cfg = cache.config;
item.innerHTML = `
<div style="flex: 1;">
<strong style="color: #667eea;">📍 [${cfg.bbox[0].toFixed(2)}, ${cfg.bbox[1].toFixed(2)}${cfg.bbox[2].toFixed(2)}, ${cfg.bbox[3].toFixed(2)}]</strong><br>
<small style="color: #666;">📅 ${cfg.start_date}${cfg.end_date}</small><br>
<small style="color: #999;">🔧 Resolution: ${cfg.resolution}m | Scenes: ${cfg.max_scenes} | Cloud: ${cfg.cloud_cover}%</small><br>
<small style="color: #999;">⏰ ${cache.created || 'N/A'}</small>
</div>
<div style="display: flex; gap: 5px;">
<button onclick="applyPredCache('${cache.filename}')" class="btn btn-success" style="padding: 5px 10px; font-size: 0.9em;">📂</button>
<button onclick="deletePredCache('${cache.filename}')" class="btn btn-secondary" style="padding: 5px 10px; font-size: 0.9em;">🗑️</button>
</div>
`;
listDiv.appendChild(item);
});
} else {
listDiv.innerHTML = '<p style="color: #999; text-align: center; padding: 20px;">Chưa có cache nào. Cache sẽ tự động được tạo sau khi predict thành công.</p>';
}
} catch (error) {
console.error('Error loading prediction cache:', error);
}
}
// Refresh prediction cache list
function refreshPredCache() {
loadPredCacheList();
}
// Apply prediction cache from filename
function applyPredCache(filename) {
const select = document.getElementById('predCacheSelect');
// Find option by filename
for (let i = 0; i < select.options.length; i++) {
if (select.options[i].value === filename) {
select.selectedIndex = i;
loadPredictionCache();
return;
}
}
}
// Load prediction cache and restore all parameters
function loadPredictionCache() {
const select = document.getElementById('predCacheSelect');
const selectedOption = select.options[select.selectedIndex];
if (!selectedOption || !selectedOption.value || !selectedOption.dataset.config) {
alert('⚠️ Vui lòng chọn cache từ danh sách!');
return;
}
const config = JSON.parse(selectedOption.dataset.config);
// Update selectedBbox
selectedBbox = {
min_lon: config.min_lon,
min_lat: config.min_lat,
max_lon: config.max_lon,
max_lat: config.max_lat
};
// Save to localStorage
localStorage.setItem('prediction_bbox', JSON.stringify(selectedBbox));
// Update ALL form fields
if (config.start_date) document.getElementById('predStartDate').value = config.start_date;
if (config.end_date) document.getElementById('predEndDate').value = config.end_date;
if (config.max_scenes) document.getElementById('predMaxScenes').value = config.max_scenes;
if (config.cloud_cover) document.getElementById('predCloudCover').value = config.cloud_cover;
if (config.resolution) document.getElementById('predResolution').value = config.resolution;
// Select model if available
if (config.model_filename) {
const modelSelect = document.getElementById('modelSelect');
for (let i = 0; i < modelSelect.options.length; i++) {
if (modelSelect.options[i].value === config.model_filename) {
modelSelect.selectedIndex = i;
updateModelInfo();
break;
}
}
}
// Draw rectangle on map
const bbox = config.bbox;
const bounds = [[bbox[1], bbox[0]], [bbox[3], bbox[2]]];
// Remove previous rectangle
drawnItems.clearLayers();
// Add new rectangle
const rectangle = L.rectangle(bounds, {
color: '#4facfe',
weight: 3,
fillOpacity: 0.2
});
drawnItems.addLayer(rectangle);
// Fit map to bounds
map.fitBounds(bounds, { padding: [50, 50] });
alert(`✅ Đã phục hồi cấu hình từ cache!\n\n📍 Bbox: [${bbox.map(n => n.toFixed(4)).join(', ')}]\n📅 Time: ${config.start_date}${config.end_date}\n🔧 Resolution: ${config.resolution}m, Scenes: ${config.max_scenes}, Cloud: ${config.cloud_cover}%`);
}
// Delete prediction cache
async function deletePredCache(filename) {
if (!confirm(`Bạn có chắc muốn xóa cache này?\n\nFile: ${filename}`)) {
return;
}
try {
const response = await fetch(`/api/prediction/cache/delete/${filename}`, {
method: 'DELETE'
});
const result = await response.json();
if (result.success) {
alert(`✅ ${result.message}`);
loadPredCacheList(); // Reload list
} else {
alert(`❌ Lỗi: ${result.detail || 'Unknown error'}`);
}
} catch (error) {
console.error('Error deleting cache:', error);
alert(`❌ Lỗi khi xóa cache: ${error.message}`);
}
}
// Apply cache preset - auto fill bbox and other params
function applyCachePreset() {
const selectValue = document.getElementById('cacheSelect').value;
if (!selectValue || !window.cacheFiles) return;
// Find selected cache file
const cacheFile = window.cacheFiles.find(f => f.filename === selectValue);
if (!cacheFile || !cacheFile.metadata) {
console.warn('No metadata found for selected cache');
return;
}
const meta = cacheFile.metadata;
// Auto-fill bbox from cache
if (meta.bbox && meta.bbox.length === 4) {
const [min_lon, min_lat, max_lon, max_lat] = meta.bbox;
// Set selectedBbox directly without drawing on map
selectedBbox = {
min_lon: min_lon,
min_lat: min_lat,
max_lon: max_lon,
max_lat: max_lat
};
// Save to localStorage
localStorage.setItem('prediction_bbox', JSON.stringify(selectedBbox));
// Draw rectangle on map to visualize
if (currentRectangle) {
drawnItems.removeLayer(currentRectangle);
}
const bounds = L.latLngBounds(
[min_lat, min_lon],
[max_lat, max_lon]
);
currentRectangle = L.rectangle(bounds, {
color: '#4facfe',
weight: 3,
fillOpacity: 0.2
});
drawnItems.addLayer(currentRectangle);
map.fitBounds(bounds);
console.log(`✅ Auto-applied bbox from cache: [${min_lon}, ${min_lat}, ${max_lon}, ${max_lat}]`);
}
// Auto-fill time range if available
if (meta.start_date) {
document.getElementById('predStartDate').value = meta.start_date;
}
if (meta.end_date) {
document.getElementById('predEndDate').value = meta.end_date;
}
// Auto-fill other params
if (meta.resolution) {
document.getElementById('predResolution').value = meta.resolution;
}
if (meta.max_scenes) {
document.getElementById('predMaxScenes').value = meta.max_scenes;
}
if (meta.cloud_cover) {
document.getElementById('predCloudCover').value = meta.cloud_cover;
}
// Show notification
alert(`✅ Đã áp dụng cache preset!\n\nBBox: [${meta.bbox?.join(', ') || 'N/A'}]\nTime: ${meta.start_date || '?'}${meta.end_date || '?'}\n\nBạn có thể predict ngay mà không cần vẽ bbox!`);
}
// === PROVINCE SELECTION FUNCTIONS FOR PREDICTION ===
// Load provinces list (both 63 and 32)
async function loadPredProvinces() {
try {
// Load 63 provinces
const response63 = await fetch('/api/provinces/by-region');
allPredProvinces = await response63.json();
// Load 32 merged provinces
const response32 = await fetch('/api/provinces-32/by-region');
allPredProvincesMerged = await response32.json();
// Default to 63 provinces
populatePredRegionButtons();
populatePredProvinceSelect();
} catch (error) {
console.error('Error loading provinces:', error);
document.getElementById('predProvinceSelect').innerHTML = '<option value="">Lỗi tải danh sách tỉnh</option>';
}
}
// Switch between 63 and 32 province lists
function switchPredProvinceList(mode) {
currentPredProvinceMode = mode;
// Update button styles
const btn63 = document.getElementById('btnPred63Provinces');
const btn32 = document.getElementById('btnPred32Provinces');
const modeLabel = document.getElementById('predProvinceListMode');
if (mode === '63') {
btn63.style.background = '#667eea';
btn63.style.color = 'white';
btn32.style.background = '#f0f0f0';
btn32.style.color = '#333';
modeLabel.textContent = 'Danh sách: 63 tỉnh';
} else {
btn63.style.background = '#f0f0f0';
btn63.style.color = '#333';
btn32.style.background = '#667eea';
btn32.style.color = 'white';
modeLabel.textContent = 'Danh sách: 32 tỉnh (sau sáp nhập)';
}
// Update region filter buttons
populatePredRegionButtons();
// Reload province list
populatePredProvinceSelect();
}
// Populate region filter buttons
function populatePredRegionButtons() {
const container = document.getElementById('predRegionFilterContainer');
// Keep the "Tất cả" button
const allButton = container.querySelector('[data-region="all"]');
container.innerHTML = '';
container.appendChild(allButton);
// Get regions from current data
const provinceData = currentPredProvinceMode === '63' ? allPredProvinces : allPredProvincesMerged;
const regions = Object.keys(provinceData);
// Add button for each region
regions.forEach(region => {
const button = document.createElement('button');
button.type = 'button';
button.className = 'pred-region-filter-btn';
button.dataset.region = region;
button.textContent = region;
button.style.cssText = 'padding: 8px 16px; background: #f0f0f0; color: #333; border: none; border-radius: 6px; cursor: pointer;';
container.appendChild(button);
});
// Re-setup event listeners
setupPredRegionFilters();
}
// Populate province select dropdown
function populatePredProvinceSelect(filterRegion = 'all') {
const select = document.getElementById('predProvinceSelect');
select.innerHTML = '<option value="">-- Chọn tỉnh thành để tải bbox tự động --</option>';
// Choose which province list to use
const provinceData = currentPredProvinceMode === '63' ? allPredProvinces : allPredProvincesMerged;
// Get all regions dynamically from data
const regions = Object.keys(provinceData);
regions.forEach(region => {
if (filterRegion !== 'all' && filterRegion !== region) {
return;
}
const provinces = provinceData[region];
if (!provinces || provinces.length === 0) return;
const optgroup = document.createElement('optgroup');
optgroup.label = `${region} (${provinces.length} tỉnh)`;
provinces.forEach(province => {
const option = document.createElement('option');
option.value = province.name;
// For merged provinces, show additional info
if (currentPredProvinceMode === '32' && province.merged_from) {
option.textContent = `${province.name} (${province.merged_from.join(', ')})`;
} else {
option.textContent = `${province.name} - ${province.name_en || ''}`;
}
option.dataset.bbox = JSON.stringify(province.bbox);
optgroup.appendChild(option);
});
select.appendChild(optgroup);
});
}
// Handle province selection for prediction
function onPredProvinceSelect(event) {
const select = event.target;
const selectedOption = select.options[select.selectedIndex];
if (!selectedOption.value) {
currentPredProvinceName = '';
return;
}
const provinceName = selectedOption.value;
const bbox = JSON.parse(selectedOption.dataset.bbox);
currentPredProvinceName = provinceName;
// Update selectedBbox
selectedBbox = {
min_lon: bbox[0],
min_lat: bbox[1],
max_lon: bbox[2],
max_lat: bbox[3]
};
// Save to localStorage
localStorage.setItem('prediction_bbox', JSON.stringify(selectedBbox));
// Draw rectangle on map
const bounds = [[bbox[1], bbox[0]], [bbox[3], bbox[2]]];
// Remove previous rectangle
drawnItems.clearLayers();
// Add new rectangle
const rectangle = L.rectangle(bounds, {
color: '#667eea',
weight: 3,
fillOpacity: 0.2
});
drawnItems.addLayer(rectangle);
// Fit map to bounds
map.fitBounds(bounds, { padding: [50, 50] });
// Show notification
console.log(`✅ Đã chọn tỉnh: ${provinceName}`);
alert(`✅ Đã chọn tỉnh: ${provinceName}\n\nBbox: [${bbox.join(', ')}]`);
}
// Handle region filter for prediction
function setupPredRegionFilters() {
const filterButtons = document.querySelectorAll('.pred-region-filter-btn');
filterButtons.forEach(btn => {
btn.addEventListener('click', function() {
// Update active button style
filterButtons.forEach(b => {
b.style.background = '#f0f0f0';
b.style.color = '#333';
b.style.fontWeight = 'normal';
});
this.style.background = '#667eea';
this.style.color = 'white';
this.style.fontWeight = '600';
// Filter provinces
const region = this.dataset.region;
populatePredProvinceSelect(region);
});
});
}
// === NDVI PROVINCE SELECTION FUNCTIONS ===
let allNDVIProvinces = {};
let allNDVIProvincesMerged = {};
let currentNDVIProvinceMode = '63'; // '63' or '32'
// Switch between 63 and 32 province lists for NDVI
function switchNDVIProvinceList(mode) {
currentNDVIProvinceMode = mode;
// Update button styles
const btn63 = document.getElementById('btnNDVI63Provinces');
const btn32 = document.getElementById('btnNDVI32Provinces');
const modeLabel = document.getElementById('ndviProvinceListMode');
if (mode === '63') {
btn63.style.background = '#2ecc71';
btn63.style.color = 'white';
btn32.style.background = '#f0f0f0';
btn32.style.color = '#333';
modeLabel.textContent = 'Danh sách: 63 tỉnh';
} else {
btn63.style.background = '#f0f0f0';
btn63.style.color = '#333';
btn32.style.background = '#2ecc71';
btn32.style.color = 'white';
modeLabel.textContent = 'Danh sách: 32 tỉnh (sau sáp nhập)';
}
// Update region filter buttons
populateNDVIRegionButtons();
// Reload province list
populateNDVIProvinceSelect();
}
// Populate region filter buttons for NDVI
function populateNDVIRegionButtons() {
const container = document.getElementById('ndviRegionFilterContainer');
// Keep the "Tất cả" button
const allButton = container.querySelector('[data-region="all"]');
container.innerHTML = '';
container.appendChild(allButton);
// Get regions from current data
const provinceData = currentNDVIProvinceMode === '63' ? allNDVIProvinces : allNDVIProvincesMerged;
const regions = Object.keys(provinceData);
// Add button for each region
regions.forEach(region => {
const button = document.createElement('button');
button.type = 'button';
button.className = 'ndvi-region-filter-btn';
button.dataset.region = region;
button.textContent = region;
button.style.cssText = 'padding: 8px 16px; background: #f0f0f0; color: #333; border: none; border-radius: 6px; cursor: pointer;';
container.appendChild(button);
});
// Re-setup event listeners
setupNDVIRegionFilters();
}
// Populate province select dropdown for NDVI
function populateNDVIProvinceSelect(filterRegion = 'all') {
const select = document.getElementById('ndviProvinceSelect');
select.innerHTML = '<option value="">-- Chọn tỉnh thành để tải bbox tự động --</option>';
// Choose which province list to use
const provinceData = currentNDVIProvinceMode === '63' ? allNDVIProvinces : allNDVIProvincesMerged;
// Get all regions dynamically from data
const regions = Object.keys(provinceData);
regions.forEach(region => {
if (filterRegion !== 'all' && filterRegion !== region) {
return;
}
const provinces = provinceData[region];
if (!provinces || provinces.length === 0) return;
const optgroup = document.createElement('optgroup');
optgroup.label = `${region} (${provinces.length} tỉnh)`;
provinces.forEach(province => {
const option = document.createElement('option');
option.value = province.name;
// For merged provinces, show additional info
if (currentNDVIProvinceMode === '32' && province.merged_from) {
option.textContent = `${province.name} (${province.merged_from.join(', ')})`;
} else {
option.textContent = `${province.name} - ${province.name_en || ''}`;
}
option.dataset.bbox = JSON.stringify(province.bbox);
optgroup.appendChild(option);
});
select.appendChild(optgroup);
});
}
// Handle province selection for NDVI
function onNDVIProvinceSelect(event) {
const select = event.target;
const selectedOption = select.options[select.selectedIndex];
if (!selectedOption.value) {
return;
}
const provinceName = selectedOption.value;
const bbox = JSON.parse(selectedOption.dataset.bbox);
// Update NDVI bbox inputs
document.getElementById('ndviMinLon').value = bbox[0].toFixed(4);
document.getElementById('ndviMinLat').value = bbox[1].toFixed(4);
document.getElementById('ndviMaxLon').value = bbox[2].toFixed(4);
document.getElementById('ndviMaxLat').value = bbox[3].toFixed(4);
// Draw rectangle on NDVI map
const bounds = [[bbox[1], bbox[0]], [bbox[3], bbox[2]]];
// Remove previous rectangle
ndviDrawnItems.clearLayers();
// Add new rectangle
const rectangle = L.rectangle(bounds, {
color: '#2ecc71',
weight: 3,
fillOpacity: 0.2
});
ndviDrawnItems.addLayer(rectangle);
// Fit map to bounds
ndviMap.fitBounds(bounds, { padding: [50, 50] });
// Show notification
console.log(`✅ NDVI - Đã chọn tỉnh: ${provinceName}`);
alert(`✅ Đã chọn tỉnh cho NDVI Analysis: ${provinceName}\n\nBbox: [${bbox.join(', ')}]`);
}
// Handle region filter for NDVI
function setupNDVIRegionFilters() {
const filterButtons = document.querySelectorAll('.ndvi-region-filter-btn');
filterButtons.forEach(btn => {
btn.addEventListener('click', function() {
// Update active button style
filterButtons.forEach(b => {
b.style.background = '#f0f0f0';
b.style.color = '#333';
b.style.fontWeight = 'normal';
});
this.style.background = '#2ecc71';
this.style.color = 'white';
this.style.fontWeight = '600';
// Filter provinces
const region = this.dataset.region;
populateNDVIProvinceSelect(region);
});
});
}
// Load NDVI provinces data
async function loadNDVIProvinces() {
try {
// Reuse data from prediction if already loaded
if (Object.keys(allPredProvinces).length > 0) {
allNDVIProvinces = allPredProvinces;
allNDVIProvincesMerged = allPredProvincesMerged;
} else {
// Load fresh
const response63 = await fetch('/api/provinces/by-region');
allNDVIProvinces = await response63.json();
const response32 = await fetch('/api/provinces-32/by-region');
allNDVIProvincesMerged = await response32.json();
}
// Populate NDVI province UI
populateNDVIRegionButtons();
populateNDVIProvinceSelect();
} catch (error) {
console.error('Error loading NDVI provinces:', error);
document.getElementById('ndviProvinceSelect').innerHTML = '<option value="">Lỗi tải danh sách tỉnh</option>';
}
}
// Load models for NDVI
async function loadNDVIModels() {
try {
const response = await fetch('/api/models/list');
const data = await response.json();
const select = document.getElementById('ndviModelSelect');
select.innerHTML = '<option value="">Chọn model...</option>';
// Chỉ lấy các file model thực sự (.joblib), loại bỏ các file có chứa '_info.joblib'
data.models
.filter(m => m.filename.endsWith('.joblib') && !m.filename.includes('_info.joblib'))
.forEach(model => {
const option = document.createElement('option');
option.value = model.filename;
option.textContent = model.filename;
if (model.info) {
option.dataset.info = JSON.stringify(model.info);
}
select.appendChild(option);
});
// Auto-select first model
const firstJoblib = data.models.find(m => m.filename.endsWith('.joblib') && !m.filename.includes('_info.joblib'));
if (firstJoblib) {
select.value = firstJoblib.filename;
updateNDVIModelInfo();
}
} catch (error) {
console.error('Error loading NDVI models:', error);
}
}
// Update NDVI model info display
function updateNDVIModelInfo() {
const select = document.getElementById('ndviModelSelect');
const option = select.options[select.selectedIndex];
if (option && option.dataset && option.dataset.info) {
try {
const info = JSON.parse(option.dataset.info);
const infoDiv = document.getElementById('ndviModelInfo');
document.getElementById('ndviModelType').textContent = info.model_type || 'N/A';
document.getElementById('ndviModelAccuracy').textContent = info.metrics?.accuracy
? (info.metrics.accuracy * 100).toFixed(2) + '%'
: 'N/A';
document.getElementById('ndviModelDate').textContent = info.training_date || 'N/A';
infoDiv.style.display = 'block';
} catch (e) {
console.warn('Error parsing NDVI model info:', e);
document.getElementById('ndviModelInfo').style.display = 'none';
}
} else {
document.getElementById('ndviModelInfo').style.display = 'none';
}
}
// Initialize on page load
window.onload = function() {
initMap();
loadModels();
loadPredictionsList();
loadCacheList();
loadPredCacheList(); // Load prediction cache list
loadPredProvinces(); // Load provinces list
loadNDVIProvinces(); // Load NDVI provinces list
loadNDVIModels(); // Load models for NDVI
// Add event listener for model selection
document.getElementById('modelSelect').addEventListener('change', updateModelInfo);
document.getElementById('ndviModelSelect').addEventListener('change', updateNDVIModelInfo);
// Add event listener for cache selection
document.getElementById('cacheSelect').addEventListener('change', applyCachePreset);
// Add event listener for province selection
document.getElementById('predProvinceSelect').addEventListener('change', onPredProvinceSelect);
document.getElementById('ndviProvinceSelect').addEventListener('change', onNDVIProvinceSelect);
setupPredRegionFilters();
setupNDVIRegionFilters();
};
// Cleanup on page unload
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';
// Invalidate map size when switching back to prediction tab
setTimeout(() => {
if (map) map.invalidateSize();
}, 100);
} 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';
// Fix NDVI map rendering issue when tab is shown
setTimeout(() => {
if (ndviMap) ndviMap.invalidateSize();
}, 100);
}
}
// 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.min_lon.toFixed(4);
document.getElementById('ndviMinLat').value = selectedBbox.min_lat.toFixed(4);
document.getElementById('ndviMaxLon').value = selectedBbox.max_lon.toFixed(4);
document.getElementById('ndviMaxLat').value = selectedBbox.max_lat.toFixed(4);
alert('✅ Đã copy bbox từ Prediction!');
}
// Calculate NDVI time series with prediction
async function calculateNDVIPrediction() {
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);
const maxScenes = parseInt(document.getElementById('ndviMaxScenes').value);
const modelFilename = document.getElementById('ndviModelSelect').value;
const useGpu = document.getElementById('useGpuNDVI').checked;
const resolution = parseInt(document.getElementById('ndviResolution').value);
const samplePoints = parseInt(document.getElementById('ndviSamplePoints').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;
}
if (!modelFilename) {
showNDVIError('Vui lòng chọn model để predict!');
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 = {
model_filename: modelFilename,
bbox: [minLon, minLat, maxLon, maxLat],
start_date: startDate,
end_date: endDate,
max_cloud_cover: maxCloudCover,
max_scenes: maxScenes,
resolution: resolution,
sample_points: samplePoints,
use_gpu: useGpu
};
try {
const response = await fetch('/api/ndvi/predict-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 predict NDVI');
}
} catch (error) {
console.error('Error calculating NDVI with prediction:', error);
showNDVIError(error.message);
} finally {
document.getElementById('ndviLoading').style.display = 'none';
document.getElementById('ndviCalculateBtn').disabled = false;
}
}
// Calculate NDVI time series (legacy - without prediction)
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.mean_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,Mean_NDVI,Min_NDVI,Max_NDVI,Std_NDVI,Valid_Points\\n';
ndviData.timeseries.forEach(item => {
csv += `${item.date},${item.mean_ndvi},${item.min_ndvi},${item.max_ndvi},${item.std_ndvi},${item.n_valid_points}\\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;
}
// Apply NDVI preset
function applyNDVIPreset() {
const preset = document.getElementById('ndviQuickPreset').value;
if (!preset) return;
const presets = {
'mekong_dry': {
name: 'Đồng bằng Cửu Long - Mùa khô',
bbox: [105.6, 9.3, 106.2, 9.8],
start_date: '2024-01-01',
end_date: '2024-04-30',
cloud_cover: 30,
max_scenes: 15,
sample_points: 1000
},
'hanoi_dry': {
name: 'Hà Nội - Mùa khô',
bbox: [105.7, 20.9, 105.9, 21.1],
start_date: '2024-02-01',
end_date: '2024-04-30',
cloud_cover: 40,
max_scenes: 12,
sample_points: 800
},
'danang_dry': {
name: 'Đà Nẵng - Mùa khô',
bbox: [107.9, 15.9, 108.3, 16.2],
start_date: '2024-01-01',
end_date: '2024-03-31',
cloud_cover: 35,
max_scenes: 12,
sample_points: 800
},
'mekong_2023': {
name: 'Đồng bằng Cửu Long - Full 2023',
bbox: [105.6, 9.3, 106.2, 9.8],
start_date: '2023-01-01',
end_date: '2023-12-31',
cloud_cover: 40,
max_scenes: 20,
sample_points: 1000
},
'small_test': {
name: 'Test nhanh - Khu vực nhỏ',
bbox: [105.8, 9.5, 105.9, 9.6],
start_date: '2024-01-01',
end_date: '2024-03-31',
cloud_cover: 50,
max_scenes: 10,
sample_points: 500
}
};
const config = presets[preset];
if (!config) return;
// Apply bbox
document.getElementById('ndviMinLon').value = config.bbox[0];
document.getElementById('ndviMinLat').value = config.bbox[1];
document.getElementById('ndviMaxLon').value = config.bbox[2];
document.getElementById('ndviMaxLat').value = config.bbox[3];
// Apply dates
document.getElementById('ndviStartDate').value = config.start_date;
document.getElementById('ndviEndDate').value = config.end_date;
// Apply other params
document.getElementById('ndviCloudCover').value = config.cloud_cover;
document.getElementById('ndviMaxScenes').value = config.max_scenes;
document.getElementById('ndviSamplePoints').value = config.sample_points;
// Draw bbox on map
ndviDrawnItems.clearLayers();
const bounds = [[config.bbox[1], config.bbox[0]], [config.bbox[3], config.bbox[2]]];
const rectangle = L.rectangle(bounds, {
color: '#2ecc71',
weight: 3,
fillOpacity: 0.2
});
ndviDrawnItems.addLayer(rectangle);
ndviMap.fitBounds(bounds, { padding: [50, 50] });
alert(`✅ Đã áp dụng preset: ${config.name}\n\nBbox: [${config.bbox.join(', ')}]\nThời gian: ${config.start_date}${config.end_date}\nSample points: ${config.sample_points}`);
}
</script>
</body>
</html>