cơ bản hoàn tát các chức năng chính

This commit is contained in:
Victor Phan
2025-12-21 17:31:51 +07:00
parent 82aa814777
commit 46da481029
15 changed files with 5470 additions and 523 deletions
+803
View File
@@ -0,0 +1,803 @@
<!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 class="content">
<!-- Map Section -->
<div class="map-container">
<div class="map-instructions">
<h3>📍 Chọn khu vực để predict</h3>
<p>✏️ Click vào nút hình vuông bên phải để vẽ bbox</p>
<p>🖱️ Kéo và thả để tạo vùng muốn phân loại</p>
<p>🔄 Có thể chỉnh sửa sau khi vẽ</p>
</div>
<div id="predictMap"></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>
<button class="btn btn-primary" onclick="startPrediction()" id="predictBtn">
🚀 Start Prediction
</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>
</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>
// Map setup
let map, drawnItems, drawControl;
let selectedBbox = null;
let currentPredictionFile = null;
let currentReportFile = null;
let statusCheckInterval = null;
// 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);
// Initialize drawing
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);
// Handle drawing
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()
};
// Validate bbox (must be within valid geographic coordinates)
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;
// Cache bbox to localStorage
localStorage.setItem('prediction_bbox', JSON.stringify(selectedBbox));
console.log('Selected bbox:', selectedBbox);
});
// On load, restore bbox from cache if exists
const cachedBbox = localStorage.getItem('prediction_bbox');
if (cachedBbox) {
try {
const bbox = JSON.parse(cachedBbox);
// Validate bbox before restoring
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 {
// Draw rectangle on map
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');
}
}
}
// 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.dataset.info) {
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';
} 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;
}
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)
};
try {
document.getElementById('predictBtn').disabled = true;
document.getElementById('predictionStatus').style.display = 'block';
document.getElementById('predictionResult').style.display = 'none';
document.getElementById('predictionError').style.display = 'none';
const response = await fetch('/api/prediction/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
});
const result = await response.json();
if (response.ok) {
// Start monitoring status
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 => `
<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>
</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('');
} 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>';
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);
}
}
// Initialize on page load
window.onload = function() {
initMap();
loadModels();
loadPredictionsList();
loadCacheList();
// Add event listener for model selection
document.getElementById('modelSelect').addEventListener('change', updateModelInfo);
};
// Cleanup on page unload
window.onbeforeunload = function() {
stopStatusCheck();
};
</script>
</body>
</html>