File size: 25,959 Bytes
8078d22 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 |
// Interactive Segmentation DOM elements
const inputCanvas = document.getElementById('inputCanvas');
const segmentedCanvas = document.getElementById('segmentedCanvas');
const imageUpload = document.getElementById('imageUpload');
const clearPointsButton = document.getElementById('clearPoints');
const voidsButton = document.getElementById('voidsButton');
const chipsButton = document.getElementById('chipsButton');
const retrainModelButton = document.getElementById('retrainModelButton');
const etaDisplay = document.getElementById('etaDisplay');
// Automatic Segmentation DOM elements
const automaticImageUpload = document.getElementById('automaticImageUpload');
const automaticProcessedImage = document.getElementById('automaticProcessedImage');
const resultsTableBody = document.getElementById('resultsTableBody');
const clearTableButton = document.getElementById('clearTableButton');
const exportTableButton = document.getElementById('exportTableButton');
// Constants for consistent canvas and SAM model dimensions
const CANVAS_SIZE = 512;
inputCanvas.width = CANVAS_SIZE;
inputCanvas.height = CANVAS_SIZE;
segmentedCanvas.width = CANVAS_SIZE;
segmentedCanvas.height = CANVAS_SIZE;
// Interactive segmentation variables
let points = { Voids: [], Chips: [] };
let labels = { Voids: [], Chips: [] };
let currentClass = 'Voids';
let imageUrl = '';
let originalImageWidth = 0;
let originalImageHeight = 0;
let trainingInProgress = false;
// Disable right-click menu on canvas
inputCanvas.addEventListener('contextmenu', (event) => event.preventDefault());
// Switch between classes
voidsButton.addEventListener('click', () => {
currentClass = 'Voids';
voidsButton.classList.add('active');
chipsButton.classList.remove('active');
clearAndRestorePoints();
});
chipsButton.addEventListener('click', () => {
currentClass = 'Chips';
chipsButton.classList.add('active');
voidsButton.classList.remove('active');
clearAndRestorePoints();
});
// Handle image upload for interactive tool
imageUpload.addEventListener('change', async (event) => {
const file = event.target.files[0];
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('/upload', { method: 'POST', body: formData });
const data = await response.json();
if (data.error) {
console.error('Error uploading image:', data.error);
return;
}
imageUrl = data.image_url;
console.log('Uploaded image URL:', imageUrl);
const img = new Image();
img.src = imageUrl;
img.onload = () => {
console.log('Image loaded:', img.width, img.height);
originalImageWidth = img.width;
originalImageHeight = img.height;
resizeAndDrawImage(inputCanvas, img);
resizeAndDrawImage(segmentedCanvas, img);
};
img.onerror = () => {
console.error('Failed to load image from URL:', imageUrl);
};
} catch (error) {
console.error('Failed to upload image:', error);
}
});
// Handle input canvas clicks
inputCanvas.addEventListener('mousedown', async (event) => {
const rect = inputCanvas.getBoundingClientRect();
const x = (event.clientX - rect.left) * (originalImageWidth / CANVAS_SIZE);
const y = (event.clientY - rect.top) * (originalImageHeight / CANVAS_SIZE);
if (event.button === 2) {
points[currentClass].push([x, y]);
labels[currentClass].push(0); // Exclude point (red)
} else if (event.button === 0) {
points[currentClass].push([x, y]);
labels[currentClass].push(1); // Include point (green)
}
drawPoints();
await updateSegmentation();
});
// Clear points for current class
clearPointsButton.addEventListener('click', () => {
points[currentClass] = [];
labels[currentClass] = [];
drawPoints();
resetSegmentation();
});
function resizeAndDrawImage(canvas, img) {
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
// Scale the image to fit within the canvas
const scale = Math.min(canvas.width / img.width, canvas.height / img.height);
const x = (canvas.width - img.width * scale) / 2;
const y = (canvas.height - img.height * scale) / 2;
ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
}
// Draw points on canvases
function drawPoints() {
[inputCanvas, segmentedCanvas].forEach((canvas) => {
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
const img = new Image();
img.src = imageUrl;
img.onload = () => {
resizeAndDrawImage(canvas, img);
points[currentClass].forEach(([x, y], i) => {
const scaledX = x * (CANVAS_SIZE / originalImageWidth);
const scaledY = y * (CANVAS_SIZE / originalImageHeight);
ctx.beginPath();
ctx.arc(scaledX, scaledY, 5, 0, 2 * Math.PI);
ctx.fillStyle = labels[currentClass][i] === 1 ? 'green' : 'red';
ctx.fill();
});
};
img.onerror = () => {
console.error('Error loading image for canvas:', img.src);
};
});
}
async function updateSegmentation() {
try {
const response = await fetch('/segment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ points: points[currentClass], labels: labels[currentClass], class: currentClass.toLowerCase() })
});
const data = await response.json();
if (data.error) {
console.error('Error during segmentation:', data.error);
alert(`Segmentation error: ${data.error}`);
return;
}
console.log('Segmentation result:', data);
const img = new Image();
img.src = `${data.segmented_url}?t=${new Date().getTime()}`; // Add timestamp to prevent caching
img.onload = () => {
console.log('Segmented image loaded successfully:', img.src);
resizeAndDrawImage(segmentedCanvas, img); // Render the segmented image
};
img.onerror = () => {
console.error('Failed to load segmented image:', img.src);
alert('Failed to load the segmented image.');
};
} catch (error) {
console.error('Error updating segmentation:', error);
alert('Failed to process segmentation.');
}
}
// Reset segmented canvas
function resetSegmentation() {
const ctx = segmentedCanvas.getContext('2d');
ctx.clearRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
const img = new Image();
img.src = imageUrl;
img.onload = () => resizeAndDrawImage(segmentedCanvas, img);
}
// Handle automatic segmentation
automaticImageUpload.addEventListener('change', async (event) => {
const file = event.target.files[0];
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('/automatic_segment', { method: 'POST', body: formData });
const data = await response.json();
if (data.error) return console.error('Error during automatic segmentation:', data.error);
// Display the processed image
const processedImage = document.getElementById('automaticProcessedImage');
processedImage.src = `${data.segmented_url}?t=${new Date().getTime()}`;
processedImage.style.display = 'block';
// Optionally append the table data
appendRowToTable(data.table_data);
} catch (error) {
console.error('Failed to process image automatically:', error);
}
});
function appendRowToTable(tableData) {
// Remove duplicates based on the image name and chip number
const existingRows = Array.from(resultsTableBody.querySelectorAll('tr'));
const existingIdentifiers = existingRows.map(row => {
const cells = row.querySelectorAll('td');
return `${cells[0]?.textContent}_${cells[1]?.textContent}`; // Combine Image Name and Chip #
});
tableData.chips.forEach((chip, index) => {
const uniqueId = `${tableData.image_name}_${chip.chip_number}`;
if (existingIdentifiers.includes(uniqueId)) return; // Skip if already present
const row = document.createElement('tr');
// Image Name (unchanged for each chip)
const imageNameCell = document.createElement('td');
imageNameCell.textContent = tableData.image_name;
row.appendChild(imageNameCell);
// Chip # (1, 2, etc.)
const chipNumberCell = document.createElement('td');
chipNumberCell.textContent = chip.chip_number;
row.appendChild(chipNumberCell);
// Chip Area
const chipAreaCell = document.createElement('td');
chipAreaCell.textContent = chip.chip_area.toFixed(2);
row.appendChild(chipAreaCell);
// Void % (Total void area / Chip area * 100)
const voidPercentageCell = document.createElement('td');
voidPercentageCell.textContent = chip.void_percentage.toFixed(2);
row.appendChild(voidPercentageCell);
// Max Void % (Largest void area / Chip area * 100)
const maxVoidPercentageCell = document.createElement('td');
maxVoidPercentageCell.textContent = chip.max_void_percentage.toFixed(2);
row.appendChild(maxVoidPercentageCell);
resultsTableBody.appendChild(row);
});
}
// Handle automatic segmentation
automaticImageUpload.addEventListener('change', async (event) => {
const file = event.target.files[0];
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('/automatic_segment', { method: 'POST', body: formData });
const data = await response.json();
if (data.error) return console.error('Error during automatic segmentation:', data.error);
automaticProcessedImage.src = `${data.segmented_url}?t=${new Date().getTime()}`;
automaticProcessedImage.style.display = 'block';
appendRowToTable(data.table_data); // Append new data to the table
} catch (error) {
console.error('Failed to process image automatically:', error);
}
});
// Clear table
clearTableButton.addEventListener('click', () => {
resultsTableBody.innerHTML = '';
});
// Export table to CSV
exportTableButton.addEventListener('click', () => {
const rows = Array.from(resultsTableBody.querySelectorAll('tr'));
const csvContent = [
['Image Name', 'Chip #', 'Chip Area', 'Void %', 'Max Void %'],
...rows.map(row =>
Array.from(row.children).map(cell => cell.textContent)
),
]
.map(row => row.join(','))
.join('\n');
const blob = new Blob([csvContent], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'segmentation_results.csv';
link.click();
URL.revokeObjectURL(url);
});
saveBothButton.addEventListener('click', async () => {
const imageName = imageUrl.split('/').pop(); // Extract the image name from the URL
if (!imageName) {
alert("No image to save.");
return;
}
const confirmSave = confirm("Are you sure you want to save both voids and chips segmentations?");
if (!confirmSave) return;
try {
const response = await fetch('/save_both', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ image_name: imageName })
});
const result = await response.json();
if (response.ok) {
alert(result.message);
} else {
alert("Failed to save segmentations.");
}
} catch (error) {
console.error("Error saving segmentations:", error);
alert("Failed to save segmentations.");
}
});
// Update the "historyButton" click listener to populate the list correctly
document.getElementById('historyButton').addEventListener('click', async () => {
try {
const response = await fetch('/get_history'); // Fetch the saved history
const result = await response.json();
if (response.ok) {
const historyList = document.getElementById('historyList');
historyList.innerHTML = ''; // Clear the list
if (result.images.length === 0) {
historyList.innerHTML = '<li class="list-group-item">No images found in history.</li>';
return;
}
result.images.forEach(image => {
const listItem = document.createElement('li');
listItem.className = 'list-group-item';
const imageName = document.createElement('span');
imageName.textContent = image;
const deleteButton = document.createElement('button');
deleteButton.className = 'btn btn-danger btn-sm';
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', async () => {
if (confirm(`Are you sure you want to delete ${image}?`)) {
await deleteHistoryItem(image, listItem);
}
});
listItem.appendChild(imageName);
listItem.appendChild(deleteButton);
historyList.appendChild(listItem);
});
new bootstrap.Modal(document.getElementById('historyModal')).show();
} else {
alert("Failed to fetch history.");
}
} catch (error) {
console.error("Error fetching history:", error);
alert("Failed to fetch history.");
}
});
// Function to delete history item
async function deleteHistoryItem(imageName, listItem) {
try {
const response = await fetch('/delete_history_item', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ image_name: imageName })
});
const result = await response.json();
if (response.ok) {
alert(result.message);
listItem.remove(); // Remove the item from the list
} else {
alert("Failed to delete image.");
}
} catch (error) {
console.error("Error deleting image:", error);
alert("Failed to delete image.");
}
}
historyButton.addEventListener('click', async () => {
try {
const response = await fetch('/get_history');
const result = await response.json();
if (response.ok) {
const historyList = document.getElementById('historyList');
historyList.innerHTML = ''; // Clear the list
if (result.images.length === 0) {
historyList.innerHTML = '<li class="list-group-item">No images found in history.</li>';
return;
}
result.images.forEach(image => {
const listItem = document.createElement('li');
listItem.className = 'list-group-item d-flex justify-content-between align-items-center';
listItem.textContent = image;
const deleteButton = document.createElement('button');
deleteButton.className = 'btn btn-danger btn-sm';
deleteButton.textContent = 'Delete';
deleteButton.addEventListener('click', async () => {
if (confirm(`Are you sure you want to delete ${image}?`)) {
await deleteHistoryItem(image, listItem);
}
});
listItem.appendChild(deleteButton);
historyList.appendChild(listItem);
});
new bootstrap.Modal(document.getElementById('historyModal')).show();
} else {
alert("Failed to fetch history.");
}
} catch (error) {
console.error("Error fetching history:", error);
alert("Failed to fetch history.");
}
});
// Function to delete history item
async function deleteHistoryItem(imageName, listItem) {
try {
const response = await fetch('/delete_history_item', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ image_name: imageName })
});
const result = await response.json();
if (response.ok) {
alert(result.message);
listItem.remove(); // Remove the item from the list
} else {
alert("Failed to delete image.");
}
} catch (error) {
console.error("Error deleting image:", error);
alert("Failed to delete image.");
}
}
// Handle Retrain Model button click
retrainModelButton.addEventListener('click', async () => {
if (!trainingInProgress) {
const confirmRetrain = confirm("Are you sure you want to retrain the model?");
if (!confirmRetrain) return;
try {
const response = await fetch('/retrain_model', { method: 'POST' });
const result = await response.json();
if (response.ok) {
// Update button to "Cancel Training"
trainingInProgress = true;
retrainModelButton.textContent = "Cancel Training";
retrainModelButton.classList.replace("btn-primary", "btn-danger");
startTrainingMonitor(); // Start monitoring the training status
} else {
alert(result.error || "Failed to start retraining.");
}
} catch (error) {
console.error("Error starting training:", error);
alert("An error occurred while starting the training process.");
}
} else {
// Handle cancel training
const confirmCancel = confirm("Are you sure you want to cancel the training?");
if (!confirmCancel) return;
try {
const response = await fetch('/cancel_training', { method: 'POST' });
const result = await response.json();
if (response.ok) {
// Reset button to "Retrain Model"
trainingInProgress = false;
retrainModelButton.textContent = "Retrain Model";
retrainModelButton.classList.replace("btn-danger", "btn-primary");
alert(result.message || "Training canceled successfully.");
} else {
alert(result.error || "Failed to cancel training.");
}
} catch (error) {
console.error("Error canceling training:", error);
alert("An error occurred while canceling the training process.");
}
}
});
function startTrainingMonitor() {
const monitorInterval = setInterval(async () => {
try {
const response = await fetch('/training_status');
const result = await response.json();
const retrainButton = document.getElementById('retrainModelButton');
const cancelButton = document.getElementById('cancelTrainingButton');
const etaDisplay = document.getElementById('etaDisplay');
if (result.status === 'running') {
// Show training progress
retrainButton.style.display = 'none';
cancelButton.style.display = 'inline-block';
etaDisplay.textContent = `Estimated Time Left: ${result.eta || "Calculating..."}`;
} else if (result.status === 'idle' || result.status === 'cancelled') {
// Revert button to "Retrain Model" (blue)
cancelButton.style.display = 'none';
retrainButton.style.display = 'inline-block';
retrainButton.textContent = 'Retrain Model';
retrainButton.classList.replace('btn-danger', 'btn-primary');
etaDisplay.textContent = '';
// Stop monitoring if training is idle
if (result.status === 'idle') {
clearInterval(monitorInterval);
}
}
} catch (error) {
console.error("Error fetching training status:", error);
}
}, 5000); // Poll every 5 seconds
}
function resetTrainingUI() {
trainingInProgress = false;
retrainModelButton.textContent = "Retrain Model";
retrainModelButton.classList.replace("btn-danger", "btn-primary");
etaDisplay.textContent = "";
}
clearHistoryButton.addEventListener('click', async () => {
const confirmClear = confirm("Are you sure you want to clear the history? This will delete all images and masks.");
if (!confirmClear) return;
try {
const response = await fetch('/clear_history', { method: 'POST' });
const result = await response.json();
if (response.ok) {
alert(result.message);
// Optionally update UI to reflect the cleared history
const historyList = document.getElementById('historyList');
if (historyList) historyList.innerHTML = '<li class="list-group-item">No images found in history.</li>';
} else {
alert("Failed to clear history.");
}
} catch (error) {
console.error("Error clearing history:", error);
alert("Failed to clear history.");
}
});
// Toggle training progress display
function showTrainingProgress(message = "Initializing...", timeLeft = "Calculating...") {
document.getElementById("trainingProgress").style.display = "block";
document.getElementById("progressMessage").textContent = message;
document.getElementById("estimatedTimeLeft").textContent = `Estimated Time Left: ${timeLeft}`;
}
function hideTrainingProgress() {
document.getElementById("trainingProgress").style.display = "none";
}
// Toggle Cancel Training Button
function showCancelTrainingButton() {
document.getElementById("cancelTrainingButton").style.display = "inline-block";
document.getElementById("retrainModelButton").style.display = "none";
}
function hideCancelTrainingButton() {
document.getElementById("cancelTrainingButton").style.display = "none";
document.getElementById("retrainModelButton").style.display = "inline-block";
}
// Add event listener to Cancel Training button
document.getElementById("cancelTrainingButton").addEventListener("click", async () => {
const confirmCancel = confirm("Are you sure you want to cancel training?");
if (!confirmCancel) return;
try {
const response = await fetch("/cancel_training", { method: "POST" });
const result = await response.json();
if (result.message) {
alert(result.message);
hideTrainingProgress();
hideCancelTrainingButton();
}
} catch (error) {
console.error("Error canceling training:", error);
alert("Failed to cancel training.");
}
});
// Handle training status updates
socket.on('training_status', (data) => {
const trainingButton = document.getElementById('retrainModelButton');
const cancelButton = document.getElementById('cancelTrainingButton');
if (data.status === 'completed') {
// Update UI: change "Cancel Training" to "Retrain Model"
trainingButton.style.display = 'inline-block';
cancelButton.style.display = 'none';
// Show a popup or notification for training completion
alert(data.message || "Training completed successfully!");
} else if (data.status === 'failed') {
// Update UI: change "Cancel Training" to "Retrain Model"
trainingButton.style.display = 'inline-block';
cancelButton.style.display = 'none';
// Show a popup or notification for training failure
alert(data.message || "Training failed. Please try again.");
}
});
socket.on('button_update', (data) => {
const retrainButton = document.getElementById('retrainModelButton');
const cancelButton = document.getElementById('cancelTrainingButton');
if (data.action === 'retrain') {
// Update to "Retrain Model" button
retrainButton.style.display = 'inline-block';
retrainButton.textContent = 'Retrain Model';
retrainButton.classList.replace('btn-danger', 'btn-primary');
cancelButton.style.display = 'none';
}
});
function updateButtonToRetrainModel() {
const button = document.getElementById('retrainModelButton');
button.innerText = "Retrain Model";
button.classList.replace("btn-danger", "btn-primary");
button.disabled = false;
}
socket.on('training_status', (data) => {
const retrainButton = document.getElementById('retrainModelButton');
const cancelButton = document.getElementById('cancelTrainingButton');
if (data.status === 'completed') {
retrainButton.style.display = 'inline-block'; // Show retrain button
retrainButton.textContent = "Retrain Model";
retrainButton.classList.replace("btn-danger", "btn-primary");
cancelButton.style.display = 'none'; // Hide cancel button
// Notify user
alert(data.message);
} else if (data.status === 'cancelled') {
retrainButton.style.display = 'inline-block';
retrainButton.textContent = "Retrain Model";
retrainButton.classList.replace("btn-danger", "btn-primary");
cancelButton.style.display = 'none';
// Notify user
alert(data.message);
}
});
// Ensure the modal backdrop is properly removed when the modal is closed
document.getElementById('historyModal').addEventListener('hidden.bs.modal', function () {
document.body.classList.remove('modal-open');
const backdrop = document.querySelector('.modal-backdrop');
if (backdrop) {
backdrop.remove();
}
});
|