// ===== GLOBAL STATE ===== let currentImage = null; let currentRectangles = []; let currentCoordinateString = ''; let currentFileName = ''; let canvas = null; let ctx = null; let batchFiles = []; let batchResults = []; let isProcessingBatch = false; let currentBatchDetailIndex = -1; // New State for tracking detail view let detailCanvas = null; let detailCtx = null; let detailImage = null; // ===== DETAIL CANVAS INTERACTION STATE (must be at top level, not TDZ) ===== let isDetailDragging = false; let detailDragTargetIndex = -1; let detailDragHandle = null; let detailDragStartPoint = null; let detailDragStartRect = null; let isDetailDrawing = false; let detailDrawStartPoint = null; // ===== INITIALIZATION ===== // ===== FORMAT SETTINGS MANAGEMENT ===== const FormatManager = { settings: { coordFormat: '{tl_x}:{tl_y},{br_x}:{br_y}', rotFormat: '{rot_x}:{rot_y}', separator: ';' }, // Load settings load: function () { const saved = localStorage.getItem('formatSettings_facial_v2'); console.log('🔧 FormatManager.load() - localStorage value:', saved); if (saved) { try { const parsed = JSON.parse(saved); if (parsed.coordFormat) this.settings.coordFormat = parsed.coordFormat; if (parsed.rotFormat) this.settings.rotFormat = parsed.rotFormat; if (parsed.separator) this.settings.separator = parsed.separator; console.log('✅ Loaded custom settings:', this.settings); } catch (e) { console.error('Error loading settings', e); } } else { console.log('ℹ️ No saved settings found (v2), using defaults:', this.settings); } this.applyToUI(); }, // Save settings save: function () { this.settings.coordFormat = document.getElementById('coordFormat').value || '{tl_x}:{tl_y},{br_x}:{br_y}'; this.settings.rotFormat = document.getElementById('rotFormat').value || '{rot_x}:{rot_y}'; this.settings.separator = document.getElementById('sepFrame').value || ';'; localStorage.setItem('formatSettings_facial_v2', JSON.stringify(this.settings)); this.updatePreview(); }, // Apply values to UI inputs applyToUI: function () { const coordInput = document.getElementById('coordFormat'); const rotInput = document.getElementById('rotFormat'); const sepInput = document.getElementById('sepFrame'); if(coordInput) coordInput.value = this.settings.coordFormat; if(rotInput) rotInput.value = this.settings.rotFormat; if(sepInput) sepInput.value = this.settings.separator; // Add listeners for live preview [coordInput, rotInput, sepInput].forEach(el => { if(el) el.addEventListener('input', () => this.updatePreview(true)); }); this.updatePreview(); }, // Generate Formats Object { coord, rot } generateFormats: function (rectangles) { if (!rectangles || rectangles.length === 0) return { coord: '', rot: '' }; const coordStrings = []; const rotStrings = []; // UI inputs might be live (during preview) or settings (during final gen) // actually let's always use `this.settings` for consistency, // but `updatePreview` will temporarily override or pass custom. // For now, simpler: always read from settings which are updated on Save. // But for live preview, we want to read from inputs. // Let's rely on `this.settings` being current. const cFmt = this.settings.coordFormat; const rFmt = this.settings.rotFormat; rectangles.forEach(rect => { const corners = rect.corners || { top_left: {x: rect.x, y: rect.y}, top_right: {x: rect.x + rect.width, y: rect.y}, bottom_right: {x: rect.x + rect.width, y: rect.y + rect.height}, bottom_left: {x: rect.x, y: rect.y + rect.height} }; const rot = rect.rotation_point || {x: 0, y: 0}; // Helper to replace const replacer = (fmt) => { return fmt .replace(/{tl_x}/g, corners.top_left.x) .replace(/{tl_y}/g, corners.top_left.y) .replace(/{tr_x}/g, corners.top_right.x) .replace(/{tr_y}/g, corners.top_right.y) .replace(/{br_x}/g, corners.bottom_right.x) .replace(/{br_y}/g, corners.bottom_right.y) .replace(/{bl_x}/g, corners.bottom_left.x) .replace(/{bl_y}/g, corners.bottom_left.y) .replace(/{rot_x}/g, rot.x) .replace(/{rot_y}/g, rot.y) .replace(/{width}/g, rect.width) .replace(/{height}/g, rect.height) .replace(/{angle}/g, rect.angle !== undefined ? rect.angle : 0); }; coordStrings.push(replacer(cFmt)); rotStrings.push(replacer(rFmt)); }); const sep = this.settings.separator; return { coord: coordStrings.join(sep), rot: rotStrings.join(sep) }; }, // Generates format based on CURRENT INPUTS (for live preview) generatePreviewFormats: function(rectangles) { const cFmt = document.getElementById('coordFormat').value || ''; const rFmt = document.getElementById('rotFormat').value || ''; const sep = document.getElementById('sepFrame').value || ';'; const coordStrings = []; const rotStrings = []; rectangles.forEach(rect => { const corners = rect.corners || { top_left: {x: rect.x, y: rect.y}, top_right: {x: rect.x + rect.width, y: rect.y}, bottom_right: {x: rect.x + rect.width, y: rect.y + rect.height}, bottom_left: {x: rect.x, y: rect.y + rect.height} }; const rot = rect.rotation_point || {x: 0, y: 0}; const replacer = (fmt) => { return fmt .replace(/{tl_x}/g, corners.top_left.x) .replace(/{tl_y}/g, corners.top_left.y) .replace(/{tr_x}/g, corners.top_right.x) .replace(/{tr_y}/g, corners.top_right.y) .replace(/{br_x}/g, corners.bottom_right.x) .replace(/{br_y}/g, corners.bottom_right.y) .replace(/{bl_x}/g, corners.bottom_left.x) .replace(/{bl_y}/g, corners.bottom_left.y) .replace(/{rot_x}/g, rot.x) .replace(/{rot_y}/g, rot.y) .replace(/{width}/g, rect.width) .replace(/{height}/g, rect.height) .replace(/{angle}/g, rect.angle !== undefined ? rect.angle : 0); }; coordStrings.push(replacer(cFmt)); rotStrings.push(replacer(rFmt)); }); return { coord: coordStrings.join(sep), rot: rotStrings.join(sep) }; }, updatePreview: function (isLive = false) { const mockRects = [{ x: 100, y: 100, width: 200, height: 200, corners: { top_left: { x: 100, y: 100 }, top_right: { x: 300, y: 100 }, bottom_right: { x: 300, y: 300 }, bottom_left: { x: 100, y: 300 } }, rotation_point: { x: 200, y: 300 } }]; let result; if(isLive) { result = this.generatePreviewFormats(mockRects); } else { result = this.generateFormats(mockRects); } const previewEl = document.getElementById('formatPreview'); if(previewEl) { previewEl.innerHTML = `
C: ${result.coord}
R: ${result.rot}
`; } } }; document.addEventListener('DOMContentLoaded', function () { // Initialize canvas canvas = document.getElementById('imageCanvas'); ctx = canvas.getContext('2d'); // Initialize Detail Canvas detailCanvas = document.getElementById('detailCanvas'); detailCtx = detailCanvas.getContext('2d'); // Setup event listeners setupEventListeners(); // Setup detail canvas interactions (must be after detailCanvas is assigned) setupDetailInteractions(); // Load format settings from localStorage FormatManager.load(); // Load initial results loadResults(); // Check server health checkServerHealth(); }); // ===== EVENT LISTENERS SETUP ===== function setupEventListeners() { // File input const fileInput = document.getElementById('fileInput'); if (fileInput) { fileInput.addEventListener('change', handleFileSelect); } // Folder input const folderInput = document.getElementById('folderInput'); if (folderInput) { folderInput.addEventListener('change', handleFolderSelect); } // Drag and drop const uploadArea = document.getElementById('uploadArea'); if (uploadArea) { uploadArea.addEventListener('dragover', handleDragOver); uploadArea.addEventListener('dragleave', handleDragLeave); uploadArea.addEventListener('drop', handleDrop); } } // ===== DRAG AND DROP HANDLERS ===== function handleDragOver(e) { e.preventDefault(); e.stopPropagation(); e.currentTarget.classList.add('drag-over'); } function handleDragLeave(e) { e.preventDefault(); e.stopPropagation(); e.currentTarget.classList.remove('drag-over'); } function handleDrop(e) { e.preventDefault(); e.stopPropagation(); e.currentTarget.classList.remove('drag-over'); const files = e.dataTransfer.files; if (files.length > 0) { const file = files[0]; if (file.type.startsWith('image/')) { loadImageFile(file); } else { showMessage('Please drop an image file', 'error'); } } } // ===== FILE HANDLING ===== function handleFileSelect(e) { const file = e.target.files[0]; if (file) { loadImageFile(file); } } function handleFolderSelect(e) { const files = Array.from(e.target.files); batchFiles = files.filter(file => file.type.startsWith('image/')); if (batchFiles.length > 0) { const folderName = batchFiles[0].webkitRelativePath.split('/')[0]; document.getElementById('batchStatus').innerHTML = ` Selected Folder: ${folderName}
Images Found: ${batchFiles.length} files `; document.getElementById('progressContainer').style.display = 'block'; document.getElementById('batchResults').style.display = 'block'; document.getElementById('batchResultsList').innerHTML = ''; showMessage(`Found ${batchFiles.length} images in folder`, 'info'); } else { showMessage('No image files found in selected folder', 'error'); } } function loadImageFile(file) { const reader = new FileReader(); reader.onload = function (e) { const img = new Image(); img.onload = function () { displayImage(img); currentFileName = file.name; }; img.onerror = function () { showMessage('Failed to load image', 'error'); }; img.src = e.target.result; }; reader.readAsDataURL(file); } function displayImage(img) { currentImage = img; canvas.width = img.width; canvas.height = img.height; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0); document.getElementById('emptyState').style.display = 'none'; canvas.style.display = 'block'; currentRectangles = []; updateCoordinatesList(); showMessage('Image loaded successfully', 'info'); } // ===== IMAGE ANALYSIS ===== // ===== INTERACTION STATE ===== let isDragging = false; let dragTargetIndex = -1; let dragHandle = null; // 'tl','tr','bl','br','rot','body','img' let dragStartPoint = null; let dragStartRect = null; let isDrawing = false; let drawStartPoint = null; // ===== IMAGE ANALYSIS ===== function analyzeImage() { if (!currentImage) { showMessage('Please select an image first', 'error'); return; } showLoading(true); const analyzeBtn = document.getElementById('analyzeBtn'); analyzeBtn.disabled = true; canvas.toBlob(function (blob) { if (!blob) { showMessage('Failed to process image', 'error'); showLoading(false); analyzeBtn.disabled = false; return; } const formData = new FormData(); formData.append('file', blob, currentFileName || 'image.png'); const minF = document.getElementById('minFaces'); const maxF = document.getElementById('maxFaces'); const confT = document.getElementById('confThreshold'); if (minF) formData.append('min_faces', minF.value || 0); if (maxF) formData.append('max_faces', maxF.value || 0); if (confT) formData.append('conf_threshold', confT.value || 0.15); fetch('/upload', { method: 'POST', body: formData }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => { if (data.success) { currentRectangles = data.rectangles || []; currentCoordinateString = data.coordinate_string || ''; if (currentRectangles.length > 0) { currentRectangles.forEach((rect, idx) => { if (!rect.id) rect.id = idx + 1; if (!rect.shape_type) rect.shape_type = 'Face'; if (!rect.color) rect.color = { hex: '#00FF00' }; }); // Switch to client-side rendering for interactivity redrawCanvas(); updateCoordinatesList(); document.getElementById('saveBtn').disabled = false; showMessage(`Found ${currentRectangles.length} face(s)`, 'success'); } else { showMessage('No faces detected', 'error'); redrawCanvas(); updateCoordinatesList(); } } else { showMessage(data.error || 'Analysis failed', 'error'); } }) .catch(error => { console.error('Error:', error); showMessage('Error: ' + error.message, 'error'); }) .finally(() => { showLoading(false); analyzeBtn.disabled = false; }); }, 'image/png'); } function redrawCanvas() { if (!currentImage) return; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(currentImage, 0, 0); // Calculate visual scale for handles const rect = canvas.getBoundingClientRect(); const scale = canvas.width / rect.width; const hSize = 12 * scale; // 12px visual size const lineWidth = Math.max(2 * scale, 2); currentRectangles.forEach((rect, i) => { // Draw Box ctx.beginPath(); ctx.rect(rect.x, rect.y, rect.width, rect.height); ctx.lineWidth = lineWidth; ctx.strokeStyle = '#00FF00'; ctx.stroke(); // Draw Handles (Corners) ctx.fillStyle = '#00FF00'; // TL ctx.fillRect(rect.x - hSize/2, rect.y - hSize/2, hSize, hSize); // TR ctx.fillRect(rect.x + rect.width - hSize/2, rect.y - hSize/2, hSize, hSize); // BR ctx.fillRect(rect.x + rect.width - hSize/2, rect.y + rect.height - hSize/2, hSize, hSize); // BL ctx.fillRect(rect.x - hSize/2, rect.y + rect.height - hSize/2, hSize, hSize); // Rotation Point if (rect.rotation_point) { ctx.beginPath(); ctx.arc(rect.rotation_point.x, rect.rotation_point.y, hSize/2, 0, 2 * Math.PI); ctx.fillStyle = '#FF0000'; ctx.fill(); // Highlight rotation point handle ctx.strokeStyle = '#FFFFFF'; ctx.lineWidth = 1 * scale; ctx.stroke(); } }); // Draw temporary box if drawing if (isDrawing && drawStartPoint && dragStartPoint) { const w = dragStartPoint.x - drawStartPoint.x; const h = dragStartPoint.y - drawStartPoint.y; ctx.beginPath(); ctx.rect(drawStartPoint.x, drawStartPoint.y, w, h); ctx.lineWidth = lineWidth; ctx.strokeStyle = '#FFFF00'; ctx.setLineDash([5 * scale, 5 * scale]); ctx.stroke(); ctx.setLineDash([]); } } // ===== CANVAS INTERACTION ===== function toggleCreateMode() { isDrawing = !isDrawing; const btn = document.getElementById('addBoxBtn'); if (isDrawing) { btn.classList.add('active'); canvas.style.cursor = 'crosshair'; showMessage('Draw a box on the image', 'info'); } else { btn.classList.remove('active'); canvas.style.cursor = 'default'; showMessage('Edit mode', 'info'); } } function getMousePos(canvas, evt) { const rect = canvas.getBoundingClientRect(); const scaleX = canvas.width / rect.width; const scaleY = canvas.height / rect.height; return { x: (evt.clientX - rect.left) * scaleX, y: (evt.clientY - rect.top) * scaleY }; } canvas.addEventListener('mousedown', function (e) { if (!currentImage) return; const pos = getMousePos(canvas, e); const rectBounds = canvas.getBoundingClientRect(); const scale = canvas.width / rectBounds.width; const hSize = 14 * scale; // Slightly larger hit area // Check if hitting existing handles or body // Reverse order to check top-most first let hitFound = false; for (let i = currentRectangles.length - 1; i >= 0; i--) { const rect = currentRectangles[i]; // Check Rotation Point if (rect.rotation_point) { const dx = pos.x - rect.rotation_point.x; const dy = pos.y - rect.rotation_point.y; // Radius check including scale if (dx*dx + dy*dy <= (hSize/2 * 1.5)**2) { isDragging = true; dragTargetIndex = i; dragHandle = 'rot'; hitFound = true; break; } } // Check Corners // TL if (Math.abs(pos.x - (rect.x)) < hSize && Math.abs(pos.y - (rect.y)) < hSize) { isDragging = true; dragTargetIndex = i; dragHandle = 'tl'; hitFound = true; break; } // TR if (Math.abs(pos.x - (rect.x + rect.width)) < hSize && Math.abs(pos.y - (rect.y)) < hSize) { isDragging = true; dragTargetIndex = i; dragHandle = 'tr'; hitFound = true; break; } // BR if (Math.abs(pos.x - (rect.x + rect.width)) < hSize && Math.abs(pos.y - (rect.y + rect.height)) < hSize) { isDragging = true; dragTargetIndex = i; dragHandle = 'br'; hitFound = true; break; } // BL if (Math.abs(pos.x - (rect.x)) < hSize && Math.abs(pos.y - (rect.y + rect.height)) < hSize) { isDragging = true; dragTargetIndex = i; dragHandle = 'bl'; hitFound = true; break; } // Check Body (Move) if (pos.x >= rect.x && pos.x <= rect.x + rect.width && pos.y >= rect.y && pos.y <= rect.y + rect.height) { isDragging = true; dragTargetIndex = i; dragHandle = 'body'; dragStartPoint = pos; // For delta calculation dragStartRect = { ...rect, rotation_point: { ...rect.rotation_point } }; hitFound = true; break; } } if (!hitFound && isDrawing) { // Start Drawing isDragging = true; dragHandle = 'draw'; drawStartPoint = pos; dragStartPoint = pos; // Current end point } }); canvas.addEventListener('mousemove', function (e) { if (!currentImage) return; const pos = getMousePos(canvas, e); const rectBounds = canvas.getBoundingClientRect(); const scale = canvas.width / rectBounds.width; const hSize = 14 * scale; // Update Cursor and Hover State if not dragging if (!isDragging) { let cursor = isDrawing ? 'crosshair' : 'default'; for (let i = currentRectangles.length - 1; i >= 0; i--) { const rect = currentRectangles[i]; // TL/BR if ((Math.abs(pos.x - rect.x) < hSize && Math.abs(pos.y - rect.y) < hSize) || (Math.abs(pos.x - (rect.x + rect.width)) < hSize && Math.abs(pos.y - (rect.y + rect.height)) < hSize)) { cursor = 'nwse-resize'; } // TR/BL else if ((Math.abs(pos.x - (rect.x + rect.width)) < hSize && Math.abs(pos.y - rect.y) < hSize) || (Math.abs(pos.x - rect.x) < hSize && Math.abs(pos.y - (rect.y + rect.height)) < hSize)) { cursor = 'nesw-resize'; } // Rot else if (rect.rotation_point) { const dx = pos.x - rect.rotation_point.x; const dy = pos.y - rect.rotation_point.y; if (dx*dx + dy*dy <= (hSize/2 * 1.5)**2) cursor = 'move'; } // Body else if (cursor === 'default' && pos.x >= rect.x && pos.x <= rect.x + rect.width && pos.y >= rect.y && pos.y <= rect.y + rect.height) { cursor = 'move'; } } canvas.style.cursor = cursor; return; } // Handle Dragging if (dragHandle === 'draw') { dragStartPoint = pos; // Update end point redrawCanvas(); return; } const rect = currentRectangles[dragTargetIndex]; if (!rect) return; if (dragHandle === 'rot') { rect.rotation_point.x = Math.round(pos.x); rect.rotation_point.y = Math.round(pos.y); } else if (dragHandle === 'body') { const dx = pos.x - dragStartPoint.x; const dy = pos.y - dragStartPoint.y; rect.x = Math.round(dragStartRect.x + dx); rect.y = Math.round(dragStartRect.y + dy); rect.rotation_point.x = Math.round(dragStartRect.rotation_point.x + dx); rect.rotation_point.y = Math.round(dragStartRect.rotation_point.y + dy); // Correct corners/bbox? rect.x/y is x1, y1. // We shouldn't exceed canvas bounds? } else { // Resizing // Preserve rotation point relative position? Or fixed? User didn't specify. // Usually fixed is safer unless scaled. I'll leave it fixed for now, simplest. if (dragHandle === 'tl') { const maxX = rect.x + rect.width - 10; const maxY = rect.y + rect.height - 10; const newX = Math.min(pos.x, maxX); const newY = Math.min(pos.y, maxY); rect.width += (rect.x - newX); rect.height += (rect.y - newY); rect.x = newX; rect.y = newY; } else if (dragHandle === 'tr') { const minX = rect.x + 10; const maxY = rect.y + rect.height - 10; const newW = Math.max(pos.x - rect.x, 10); const newY = Math.min(pos.y, maxY); rect.height += (rect.y - newY); rect.y = newY; rect.width = newW; } else if (dragHandle === 'bl') { const maxX = rect.x + rect.width - 10; const newX = Math.min(pos.x, maxX); const newH = Math.max(pos.y - rect.y, 10); rect.width += (rect.x - newX); rect.x = newX; rect.height = newH; } else if (dragHandle === 'br') { rect.width = Math.max(pos.x - rect.x, 10); rect.height = Math.max(pos.y - rect.y, 10); } rect.x = Math.round(rect.x); rect.y = Math.round(rect.y); rect.width = Math.round(rect.width); rect.height = Math.round(rect.height); // Update corners struct if it exists (for backend compat)? // Backend returns corners logic, but formatted string is what matters. // `FormatManager` uses `rect.corners` or calculates from x,y,w,h? // Wait, `FormatManager` uses `rect.corners.top_left` etc. // I MUST update `rect.corners` too! rect.corners = { top_left: { x: rect.x, y: rect.y }, top_right: { x: rect.x + rect.width, y: rect.y }, bottom_right: { x: rect.x + rect.width, y: rect.y + rect.height }, bottom_left: { x: rect.x, y: rect.y + rect.height } }; } redrawCanvas(); }); canvas.addEventListener('mouseup', function (e) { if (!isDragging) return; if (dragHandle === 'draw' && drawStartPoint && dragStartPoint) { // Finalize new box const x = Math.min(drawStartPoint.x, dragStartPoint.x); const y = Math.min(drawStartPoint.y, dragStartPoint.y); const w = Math.abs(drawStartPoint.x - dragStartPoint.x); const h = Math.abs(drawStartPoint.y - dragStartPoint.y); if (w > 10 && h > 10) { const newRect = { id: currentRectangles.length + 1, shape_type: 'Face', box_2d: [x, y, x + w, y + h], // Format matching backend x: Math.round(x), y: Math.round(y), width: Math.round(w), height: Math.round(h), rotation_point: { x: Math.round(x + w/2), y: Math.round(y + h/2) }, corners: { top_left: { x: Math.round(x), y: Math.round(y) }, top_right: { x: Math.round(x + w), y: Math.round(y) }, bottom_right: { x: Math.round(x + w), y: Math.round(y + h) }, bottom_left: { x: Math.round(x), y: Math.round(y + h) } }, color: { hex: '#00FF00' } }; currentRectangles.push(newRect); showMessage('New box added', 'success'); // Turn off create mode toggleCreateMode(); } } // For Edits (resize/move), we already updated `rect` in real-time. // Just sync UI list. updateCoordinatesList(); isDragging = false; dragHandle = null; dragTargetIndex = -1; drawStartPoint = null; dragStartPoint = null; redrawCanvas(); }); // ===== COORDINATES DISPLAY ===== function updateCoordinatesList() { const listElement = document.getElementById('coordinatesList'); if (!currentRectangles || currentRectangles.length === 0) { listElement.innerHTML = `

No faces detected

`; return; } let html = ''; currentRectangles.forEach((rect, index) => { if (!rect.id) rect.id = index + 1; if (!rect.shape_type) rect.shape_type = 'Face'; if (!rect.color) rect.color = { hex: '#00FF00' }; // Generate coordinate string using FormatManager for consistency const formats = FormatManager.generateFormats([rect]); // Use labels and newlines for clear separation let displayStr = `
C: ${formats.coord}
`; if (formats.rot) { displayStr += `
R: ${formats.rot}
`; } html += `
${rect.shape_type} ${rect.id}
${rect.width}×${rect.height}px
${displayStr}
`; }); listElement.innerHTML = html; } function removeFace(index) { if (!confirm('Delete this face? It will not be saved.')) return; currentRectangles.splice(index, 1); updateCoordinatesList(); showMessage('Face removed from list. It will not be saved.', 'info'); // Optional: Redraw canvas to remove the baked-in box if possible if (currentImage) { // Clear and draw original ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(currentImage, 0, 0); // Draw remaining boxes using JS currentRectangles.forEach(rect => { // Box ctx.beginPath(); ctx.rect(rect.x, rect.y, rect.width, rect.height); ctx.lineWidth = 2; ctx.strokeStyle = '#00FF00'; ctx.stroke(); // Rotation Point if (rect.rotation_point) { ctx.beginPath(); ctx.arc(rect.rotation_point.x, rect.rotation_point.y, 4, 0, 2 * Math.PI); ctx.fillStyle = '#FF0000'; ctx.fill(); } }); } } // ===== SAVE OPERATIONS ===== // ===== SAVE OPERATIONS ===== function saveCoordinates() { try { // Generate flexible string const formats = FormatManager.generateFormats(currentRectangles); console.log('💾 Saving coordinates:', formats); if (!formats.coord && !formats.rot) { showMessage('No coordinates to save', 'error'); return; } showLoading(true); fetch('/save_coordinates', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ image_name: currentFileName, coordinate_string: formats.coord, rotation_string: formats.rot, rectangles: currentRectangles }) }) .then(response => { if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); return response.json(); }) .then(data => { if (data.success) { showMessage('Coordinates saved successfully!', 'success'); loadResults(); } else { showMessage(data.error || 'Failed to save', 'error'); } }) .catch(error => { console.error('Error in save fetch:', error); showMessage('Error: ' + error.message, 'error'); }) .finally(() => { console.log('Save operation finished, hiding loader'); showLoading(false); }); } catch (e) { console.error('Synchronous error in saveCoordinates:', e); showLoading(false); showMessage('Error preparing save data', 'error'); } } // ===== BATCH PROCESSING ===== function startBatchProcessing() { if (batchFiles.length === 0) { showMessage('Please select a folder first', 'error'); return; } if (isProcessingBatch) { showMessage('Batch processing already in progress', 'error'); return; } isProcessingBatch = true; batchResults = []; document.getElementById('batchStartBtn').disabled = true; document.getElementById('saveAllBtn').disabled = true; document.getElementById('batchResultsList').innerHTML = ''; const totalFiles = batchFiles.length; let processedFiles = 0; let successfulFiles = 0; updateProgress(totalFiles, 0, 0); function processNextFile(index) { if (index >= totalFiles) { isProcessingBatch = false; document.getElementById('batchStartBtn').disabled = false; if (batchResults.length > 0) { document.getElementById('saveAllBtn').disabled = false; } showMessage(`Batch complete: ${successfulFiles}/${totalFiles} successful`, 'success'); return; } const file = batchFiles[index]; const formData = new FormData(); formData.append('file', file); const minF = document.getElementById('minFaces'); const maxF = document.getElementById('maxFaces'); const confT = document.getElementById('confThreshold'); if (minF) formData.append('min_faces', minF.value || 0); if (maxF) formData.append('max_faces', maxF.value || 0); if (confT) formData.append('conf_threshold', confT.value || 0.15); fetch('/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { processedFiles++; const resultItem = document.createElement('div'); resultItem.className = 'batch-item'; if (data.success && data.rectangles) { successfulFiles++; // Show device info once at the start of batch if (processedFiles === 1) { const deviceMsg = data.device === 'cuda' ? 'GPU (CUDA)' : 'CPU'; showMessage(`Batch started using ${deviceMsg}`, 'success'); } // Generate formatted coordinate string using FormatManager const formats = FormatManager.generateFormats(data.rectangles); const displayStr = formats.rot ? `${formats.coord}
${formats.rot}` : formats.coord; batchResults.push({ filename: file.name, warning: data.warning || null, coordinates: formats.coord, rotations: formats.rot, rectangles: data.rectangles, image_url: data.image_url, original_url: data.original_url }); // Determine badge overlay on image const noFaceMark = data.rectangles.length === 0 ? `
` : data.warning ? `
` : ''; const headerIcon = data.warning ? 'fa-exclamation-triangle' : (data.rectangles.length === 0 ? 'fa-exclamation-circle' : 'fa-check-circle'); const headerColor = data.warning ? '#f5a623' : (data.rectangles.length === 0 ? 'red' : 'var(--success-color)'); const warningDetail = data.warning ? `⚠ ${data.warning}
` : ''; resultItem.classList.add(data.warning ? 'warning' : 'success'); resultItem.innerHTML = `
${file.name} ${noFaceMark}
${file.name}
${warningDetail} ${data.rectangles.length} face(s)
${displayStr}
`; } else { resultItem.classList.add('error'); resultItem.innerHTML = `
Analysis Failed
${file.name}
${data.error || 'No faces detected'}
`; } document.getElementById('batchResultsList').appendChild(resultItem); // Auto-scroll container to the end (newest item) const listContainer = document.getElementById('batchResultsList'); listContainer.scrollTo({ left: listContainer.scrollWidth, behavior: 'smooth' }); updateProgress(totalFiles, processedFiles, successfulFiles); setTimeout(() => processNextFile(index + 1), 100); }) .catch(error => { console.error('Error processing file:', error); processedFiles++; const resultItem = document.createElement('div'); resultItem.className = 'batch-item error'; resultItem.innerHTML = `
Error
${file.name}
${error.message}
`; document.getElementById('batchResultsList').appendChild(resultItem); updateProgress(totalFiles, processedFiles, successfulFiles); setTimeout(() => processNextFile(index + 1), 100); }); } processNextFile(0); } function updateProgress(total, processed, successful) { const percent = Math.round((processed / total) * 100); document.getElementById('progressFill').style.width = percent + '%'; document.getElementById('progressPercent').textContent = percent + '%'; document.getElementById('progressText').textContent = `Processing: ${processed}/${total}`; document.getElementById('batchStats').innerHTML = ` Files: ${total} | Successful: ${successful} | Failed: ${processed - successful} `; } function saveAllCoordinates() { try { if (batchResults.length === 0) { showMessage('No batch results to save', 'error'); return; } showLoading(true); const formattedResults = batchResults.map(item => { // Fix: Use generateFormats instead of removed generateString const formats = FormatManager.generateFormats(item.rectangles); return { filename: item.filename, coordinate_string: formats.coord, rotation_string: formats.rot, rectangles: currentRectangles, rectangles: item.rectangles }; }); console.log('💾 Saving batch coordinates:', formattedResults); fetch('/save_all_coordinates', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ results: formattedResults }) }) .then(response => { if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); return response.json(); }) .then(data => { if (data.success) { showMessage(`Saved ${batchResults.length} images to coordinates file`, 'success'); loadResults(); } else { showMessage(data.error || 'Failed to save', 'error'); } }) .catch(error => { console.error('Error:', error); showMessage('Error: ' + error.message, 'error'); }) .finally(() => { showLoading(false); }); } catch (e) { console.error('Synchronous error in saveAllCoordinates:', e); showLoading(false); showMessage('Error preparing batch data: ' + e.message, 'error'); } } function clearBatch() { if (!confirm('Clear batch results?')) return; batchFiles = []; batchResults = []; document.getElementById('batchStatus').innerHTML = 'No folder selected'; document.getElementById('batchResults').style.display = 'none'; document.getElementById('batchResultsList').innerHTML = ''; document.getElementById('progressContainer').style.display = 'none'; document.getElementById('saveAllBtn').disabled = true; document.getElementById('folderInput').value = ''; showMessage('Batch results cleared', 'info'); } // ===== RESULTS MANAGEMENT ===== function loadResults() { fetch('/get_coordinates') .then(response => { if (!response.ok) throw new Error('Failed to fetch coordinates'); return response.json(); }) .then(data => { const resultsContent = document.getElementById('resultsContent'); if (data.content && data.content.trim()) { resultsContent.textContent = data.content; // Update recent entries - New Format Parsing // Separator: 50 dashes const entries = data.content.split(/-{5,}/).filter(e => e.trim().length > 0); const recent = entries.slice(-10).reverse(); let recentHtml = ''; recent.forEach(entryText => { const lines = entryText.split('\n').map(l => l.trim()).filter(l => l.length > 0); let imgName = 'Unknown'; let coord = ''; let rot = ''; lines.forEach(line => { if (line.startsWith('Image:')) imgName = line.replace('Image:', '').trim(); if (line.startsWith('coordinate:')) coord = line.replace('coordinate:', '').trim(); if (line.startsWith('rotationpoint:')) rot = line.replace('rotationpoint:', '').trim(); }); if (imgName !== 'Unknown') { recentHtml += `
${imgName}
C: ${coord.substring(0, 50)}${coord.length > 50 ? '...' : ''}
R: ${rot.substring(0, 50)}${rot.length > 50 ? '...' : ''}
`; } }); document.getElementById('recentEntries').innerHTML = recentHtml || '

No recent entries

'; } else { resultsContent.textContent = 'No coordinates saved yet'; document.getElementById('recentEntries').innerHTML = '

No recent entries

'; } }) .catch(error => { console.error('Error loading results:', error); const resultsContent = document.getElementById('resultsContent'); if (resultsContent) resultsContent.textContent = 'Error loading results'; }); } function clearResults() { if (!confirm('Clear all saved coordinates? This cannot be undone.')) return; fetch('/clear_coordinates', { method: 'POST' }) .then(response => response.json()) .then(data => { if (data.success) { showMessage('All coordinates cleared', 'success'); loadResults(); } else { showMessage(data.error || 'Failed to clear', 'error'); } }) .catch(error => { console.error('Error:', error); showMessage('Error: ' + error.message, 'error'); }); } function downloadResults(format = 'text') { const TOOL_BASE = window.location.pathname.replace(/\/+$/, ''); let url; let filename; // Check if we have data first // Since we download from backend file, we can just trigger it. // But helpful to check if resultsContent is empty to avoid 404 or empty file if possible, // though backend handles it. if (format === 'json') { url = TOOL_BASE + '/download/json'; filename = `results_${new Date().toISOString().slice(0, 10)}.json`; } else { url = TOOL_BASE + '/download/text'; filename = `coordinates_${new Date().toISOString().slice(0, 10)}.txt`; } const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); showMessage(`Downloading ${format.toUpperCase()} results...`, 'success'); } // ===== TAB NAVIGATION ===== // ===== TAB NAVIGATION ===== function switchTab(tabName) { document.querySelectorAll('.tab-content').forEach(tab => { tab.classList.remove('active'); }); document.querySelectorAll('.tab').forEach(tab => { tab.classList.remove('active'); }); document.getElementById(tabName + '-tab').classList.add('active'); document.getElementById(tabName + '-content').classList.add('active'); if (tabName === 'results') { loadResults(); } } // ===== UI INTERACTION ===== function toggleFormatInfo() { const info = document.querySelector('.format-info'); info.classList.toggle('collapsed'); } // ===== UTILITY FUNCTIONS ===== function clearImage() { if (!confirm('Clear current image?')) return; currentImage = null; currentRectangles = []; currentCoordinateString = ''; currentFileName = ''; ctx.clearRect(0, 0, canvas.width, canvas.height); canvas.style.display = 'none'; document.getElementById('emptyState').style.display = 'block'; updateCoordinatesList(); document.getElementById('saveBtn').disabled = true; document.getElementById('fileInput').value = ''; // Format info collapse state is preserved in UI showMessage('Image cleared', 'info'); } function showLoading(show) { document.getElementById('loading').style.display = show ? 'flex' : 'none'; } function showMessage(text, type = 'info') { const message = document.getElementById('message'); message.textContent = text; message.className = `message ${type}`; setTimeout(() => { message.classList.add('show'); }, 10); setTimeout(() => { message.classList.remove('show'); }, 5000); } // ===== BATCH SCROLLING ===== function scrollBatch(direction) { const list = document.getElementById('batchResultsList'); const scrollAmount = 340; // Approx card width (320) + gap (20) if (direction === 'left') { list.scrollBy({ left: -scrollAmount, behavior: 'smooth' }); } else { list.scrollBy({ left: scrollAmount, behavior: 'smooth' }); } } // Global modal functions function toggleFormatModal(show) { const modal = document.getElementById('formatModal'); if (show) { modal.classList.add('show'); FormatManager.load(); // Refresh/Init } else { modal.classList.remove('show'); } } function saveFormatSettings() { FormatManager.save(); toggleFormatModal(false); showMessage('Format settings saved', 'success'); } // Add listeners for real-time preview document.addEventListener('DOMContentLoaded', function () { // Inputs (separators) ['sepCoord', 'sepPoint', 'sepFrame'].forEach(id => { const el = document.getElementById(id); if (el) { el.addEventListener('input', () => FormatManager.updatePreview()); } }); }); function checkServerHealth() { fetch('/health') .then(response => response.json()) .then(data => { if (data.status === 'healthy') { console.log('Server is healthy'); } }) .catch(error => { console.error('Server health check failed:', error); showMessage('Warning: Server connection issues', 'error'); }); } // ===== BATCH DETAIL VIEW FUNCTIONS ===== function openBatchDetail(index) { if (index < 0 || index >= batchResults.length) return; currentBatchDetailIndex = index; const result = batchResults[index]; // Load image for canvas detailImage = new Image(); detailImage.onload = function() { document.getElementById('batchDetailModal').classList.add('show'); renderDetailView(); }; detailImage.onerror = function() { console.error("Failed to load image for detail view:", detailImage.src); showMessage("Failed to load image for details.", "error"); }; // Use original URL if available (to avoid ghost boxes), otherwise fallback to processed detailImage.src = result.original_url || result.image_url; } function closeBatchDetail() { document.getElementById('batchDetailModal').classList.remove('show'); currentBatchDetailIndex = -1; detailImage = null; } function renderDetailView() { if (currentBatchDetailIndex === -1 || !detailImage) return; const result = batchResults[currentBatchDetailIndex]; const rectangles = result.rectangles; // 1. Render Canvas detailCanvas.width = detailImage.width; detailCanvas.height = detailImage.height; detailCtx.clearRect(0, 0, detailCanvas.width, detailCanvas.height); detailCtx.drawImage(detailImage, 0, 0); // Calculate visual scale for handles const rectBounds = detailCanvas.getBoundingClientRect(); const scale = detailCanvas.width / rectBounds.width; const hSize = 12 * scale; // 12px visual size const lineWidth = Math.max(2 * scale, 2); // Draw rectangles rectangles.forEach((rect, i) => { // Draw Box detailCtx.beginPath(); detailCtx.rect(rect.x, rect.y, rect.width, rect.height); detailCtx.lineWidth = lineWidth; detailCtx.strokeStyle = '#00FF00'; // Green detailCtx.stroke(); // Draw Handles (Corners) detailCtx.fillStyle = '#00FF00'; // TL detailCtx.fillRect(rect.x - hSize/2, rect.y - hSize/2, hSize, hSize); // TR detailCtx.fillRect(rect.x + rect.width - hSize/2, rect.y - hSize/2, hSize, hSize); // BR detailCtx.fillRect(rect.x + rect.width - hSize/2, rect.y + rect.height - hSize/2, hSize, hSize); // BL detailCtx.fillRect(rect.x - hSize/2, rect.y + rect.height - hSize/2, hSize, hSize); // Draw Rotation Point if (rect.rotation_point) { detailCtx.beginPath(); detailCtx.arc(rect.rotation_point.x, rect.rotation_point.y, hSize/2, 0, 2 * Math.PI); detailCtx.fillStyle = '#FF0000'; detailCtx.fill(); detailCtx.strokeStyle = '#FFFFFF'; detailCtx.lineWidth = 1 * scale; detailCtx.stroke(); } // Draw Label detailCtx.font = `bold ${Math.max(16 * scale, 16)}px Arial`; detailCtx.fillStyle = '#00FF00'; detailCtx.fillText(`Face ${i + 1}`, rect.x, rect.y - 5); }); // Draw temporary box if drawing if (isDetailDrawing && detailDrawStartPoint && detailDragStartPoint && detailDragHandle === 'draw') { const w = detailDragStartPoint.x - detailDrawStartPoint.x; const h = detailDragStartPoint.y - detailDrawStartPoint.y; detailCtx.beginPath(); detailCtx.rect(detailDrawStartPoint.x, detailDrawStartPoint.y, w, h); detailCtx.lineWidth = lineWidth; detailCtx.strokeStyle = '#FFFF00'; detailCtx.setLineDash([5 * scale, 5 * scale]); detailCtx.stroke(); detailCtx.setLineDash([]); } // 2. Render List const listContainer = document.getElementById('detailList'); listContainer.innerHTML = ''; if (rectangles.length === 0) { listContainer.innerHTML = '

No faces detected (or all removed)

'; return; } rectangles.forEach((rect, i) => { const item = document.createElement('div'); item.className = 'detail-item'; const color = '#44CC44'; // Green item.innerHTML = `
${i + 1}
Face #${i + 1}
Box: ${rect.width}x${rect.height} • (${rect.x}, ${rect.y}) • Angle: ${rect.angle !== undefined ? rect.angle : 0}°
Rot: ${rect.rotation_point ? `(${rect.rotation_point.x}, ${rect.rotation_point.y})` : 'Drag red dot to set'}
`; listContainer.appendChild(item); }); } function removeFaceFromBatch(batchIndex, frameIndex) { if (batchIndex !== currentBatchDetailIndex) return; if (!confirm('Remove this face? It will not be saved.')) return; const result = batchResults[batchIndex]; // Remove from array result.rectangles.splice(frameIndex, 1); // Regenerate coordinate string using FormatManager const formats = FormatManager.generateFormats(result.rectangles); result.coordinates = formats.coord; result.rotations = formats.rot; // Update Batch Item UI in the background list const batchDetailsEl = document.getElementById(`batch-details-${batchIndex}`); if (batchDetailsEl) { const displayStr = formats.rot ? `${formats.coord}
${formats.rot}` : formats.coord; batchDetailsEl.innerHTML = ` ${result.rectangles.length} face(s)
${displayStr} `; } // Re-render Detail View renderDetailView(); showMessage('Face removed', 'success'); }// ===== DETAIL VIEW INTERACTION ===== // (State variables moved to top of file to avoid Temporal Dead Zone) function toggleDetailCreateMode() { isDetailDrawing = !isDetailDrawing; const btn = document.getElementById('detailAddBoxBtn'); if (isDetailDrawing) { btn.classList.add('active'); if (detailCanvas) detailCanvas.style.cursor = 'crosshair'; showMessage('Draw a box on the image', 'info'); } else { btn.classList.remove('active'); if (detailCanvas) detailCanvas.style.cursor = 'default'; showMessage('Edit mode', 'info'); } } // Add listeners to detailCanvas when main.js loads (it's in DOM) // Ensure detailCanvas is available. It is init in DOMContentLoaded. // So we hook into DOMContentLoaded or just run this if defer. // We'll add a helper and call it. function setupDetailInteractions() { if (!detailCanvas) return; function getDetailMousePos(evt) { const rect = detailCanvas.getBoundingClientRect(); const scaleX = detailCanvas.width / rect.width; const scaleY = detailCanvas.height / rect.height; return { x: (evt.clientX - rect.left) * scaleX, y: (evt.clientY - rect.top) * scaleY }; } detailCanvas.addEventListener('mousedown', function(e) { if (currentBatchDetailIndex === -1) return; const pos = getDetailMousePos(e); const rectBounds = detailCanvas.getBoundingClientRect(); const scale = detailCanvas.width / rectBounds.width; const hSize = 14 * scale; const rectangles = batchResults[currentBatchDetailIndex].rectangles; let hitFound = false; // Reverse check for (let i = rectangles.length - 1; i >= 0; i--) { const rect = rectangles[i]; // Rot if (rect.rotation_point) { const dx = pos.x - rect.rotation_point.x; const dy = pos.y - rect.rotation_point.y; if (dx*dx + dy*dy <= (hSize/2 * 1.5)**2) { isDetailDragging = true; detailDragTargetIndex = i; detailDragHandle = 'rot'; hitFound = true; break; } } // Corners if (Math.abs(pos.x - rect.x) < hSize && Math.abs(pos.y - rect.y) < hSize) { isDetailDragging=true; detailDragTargetIndex=i; detailDragHandle='tl'; hitFound=true; break; } if (Math.abs(pos.x - (rect.x+rect.width)) < hSize && Math.abs(pos.y - rect.y) < hSize) { isDetailDragging=true; detailDragTargetIndex=i; detailDragHandle='tr'; hitFound=true; break; } if (Math.abs(pos.x - (rect.x+rect.width)) < hSize && Math.abs(pos.y - (rect.y+rect.height)) < hSize) { isDetailDragging=true; detailDragTargetIndex=i; detailDragHandle='br'; hitFound=true; break; } if (Math.abs(pos.x - rect.x) < hSize && Math.abs(pos.y - (rect.y+rect.height)) < hSize) { isDetailDragging=true; detailDragTargetIndex=i; detailDragHandle='bl'; hitFound=true; break; } // Body if (pos.x >= rect.x && pos.x <= rect.x + rect.width && pos.y >= rect.y && pos.y <= rect.y + rect.height) { isDetailDragging = true; detailDragTargetIndex = i; detailDragHandle = 'body'; detailDragStartPoint = pos; detailDragStartRect = { ...rect, rotation_point: { ...rect.rotation_point } }; hitFound = true; break; } } if (!hitFound && isDetailDrawing) { isDetailDragging = true; detailDragHandle = 'draw'; detailDrawStartPoint = pos; detailDragStartPoint = pos; // current end point } }); detailCanvas.addEventListener('mousemove', function(e) { if (currentBatchDetailIndex === -1) return; const pos = getDetailMousePos(e); const rectBounds = detailCanvas.getBoundingClientRect(); const scale = detailCanvas.width / rectBounds.width; const hSize = 14 * scale; const rectangles = batchResults[currentBatchDetailIndex].rectangles; if (!isDetailDragging) { let cursor = isDetailDrawing ? 'crosshair' : 'default'; for (let i = rectangles.length - 1; i >= 0; i--) { const rect = rectangles[i]; if ((Math.abs(pos.x-rect.x)=rect.x && pos.x<=rect.x+rect.width && pos.y>=rect.y && pos.y<=rect.y+rect.height) cursor='move'; } detailCanvas.style.cursor = cursor; return; } if (detailDragHandle === 'draw') { detailDragStartPoint = pos; renderDetailView(); return; } // Dragging logic const rect = rectangles[detailDragTargetIndex]; if (!rect) return; if (detailDragHandle === 'rot') { rect.rotation_point.x = Math.round(pos.x); rect.rotation_point.y = Math.round(pos.y); } else if (detailDragHandle === 'body') { const dx = pos.x - detailDragStartPoint.x; const dy = pos.y - detailDragStartPoint.y; rect.x = Math.round(detailDragStartRect.x + dx); rect.y = Math.round(detailDragStartRect.y + dy); rect.rotation_point.x = Math.round(detailDragStartRect.rotation_point.x + dx); rect.rotation_point.y = Math.round(detailDragStartRect.rotation_point.y + dy); } else { // Resize (tl, tr, bl, br) - Simplified if (detailDragHandle === 'tl') { const maxX = rect.x + rect.width - 10; const maxY = rect.y + rect.height - 10; const newX = Math.min(pos.x, maxX); const newY = Math.min(pos.y, maxY); rect.width += (rect.x - newX); rect.height += (rect.y - newY); rect.x = newX; rect.y = newY; } else if (detailDragHandle === 'tr') { const maxY = rect.y + rect.height - 10; const newW = Math.max(pos.x - rect.x, 10); const newY = Math.min(pos.y, maxY); rect.height += (rect.y - newY); rect.y = newY; rect.width = newW; } else if (detailDragHandle === 'bl') { const maxX = rect.x + rect.width - 10; const newX = Math.min(pos.x, maxX); const newH = Math.max(pos.y - rect.y, 10); rect.width += (rect.x - newX); rect.x = newX; rect.height = newH; } else if (detailDragHandle === 'br') { rect.width = Math.max(pos.x - rect.x, 10); rect.height = Math.max(pos.y - rect.y, 10); } // Round all rect coordinates to integer to avoid floats in formatting rect.x = Math.round(rect.x); rect.y = Math.round(rect.y); rect.width = Math.round(rect.width); rect.height = Math.round(rect.height); // Update corners rect.corners = { top_left: { x: rect.x, y: rect.y }, top_right: { x: rect.x + rect.width, y: rect.y }, bottom_right: { x: rect.x + rect.width, y: rect.y + rect.height }, bottom_left: { x: rect.x, y: rect.y + rect.height } }; } renderDetailView(); }); detailCanvas.addEventListener('mouseup', function() { if (!isDetailDragging) return; if (detailDragHandle === 'draw' && detailDrawStartPoint && detailDragStartPoint) { const x = Math.min(detailDrawStartPoint.x, detailDragStartPoint.x); const y = Math.min(detailDrawStartPoint.y, detailDragStartPoint.y); const w = Math.abs(detailDrawStartPoint.x - detailDragStartPoint.x); const h = Math.abs(detailDrawStartPoint.y - detailDragStartPoint.y); if (w > 10 && h > 10) { const newRect = { x: Math.round(x), y: Math.round(y), width: Math.round(w), height: Math.round(h), rotation_point: { x: Math.round(x + w/2), y: Math.round(y + h) }, corners: { top_left: { x: Math.round(x), y: Math.round(y) }, top_right: { x: Math.round(x + w), y: Math.round(y) }, bottom_right: { x: Math.round(x + w), y: Math.round(y + h) }, bottom_left: { x: Math.round(x), y: Math.round(y + h) } } }; const result = batchResults[currentBatchDetailIndex]; result.rectangles.push(newRect); const formats = FormatManager.generateFormats(result.rectangles); result.coordinates = formats.coord; result.rotations = formats.rot; const batchDetailsEl = document.getElementById(`batch-details-${currentBatchDetailIndex}`); if (batchDetailsEl) { const displayStr = formats.rot ? `${formats.coord}
${formats.rot}` : formats.coord; batchDetailsEl.innerHTML = ` ${result.rectangles.length} face(s)
${displayStr} `; } // Update batch UI marker if needed const itemEl = batchDetailsEl.parentElement; if (itemEl && result.rectangles.length > 0) { const iconEl = itemEl.querySelector('.batch-item-header i'); if (iconEl) { iconEl.className = 'fas fa-check-circle'; iconEl.style.color = 'var(--success-color)'; } const markEl = itemEl.querySelector('.batch-image-container div[title="No faces detected"]'); if (markEl) markEl.remove(); } showMessage('New box added', 'success'); toggleDetailCreateMode(); } } else { // Updating existing coordinates for saving later const result = batchResults[currentBatchDetailIndex]; const formats = FormatManager.generateFormats(result.rectangles); result.coordinates = formats.coord; result.rotations = formats.rot; const batchDetailsEl = document.getElementById(`batch-details-${currentBatchDetailIndex}`); if (batchDetailsEl) { const displayStr = formats.rot ? `${formats.coord}
${formats.rot}` : formats.coord; batchDetailsEl.innerHTML = ` ${result.rectangles.length} face(s)
${displayStr} `; } } isDetailDragging = false; detailDragTargetIndex = -1; detailDragHandle = null; detailDrawStartPoint = null; detailDragStartPoint = null; renderDetailView(); }); } // Detail interactions are now set up inside DOMContentLoaded (above)