File size: 17,218 Bytes
1ccc4ec 2dab624 1ccc4ec 2dab624 a78c902 1ccc4ec a78c902 1ccc4ec 2dab624 1ccc4ec 2dab624 1ccc4ec 2dab624 1ccc4ec 2dab624 1ccc4ec 2dab624 a78c902 2dab624 adf4a4e 2dab624 adf4a4e 2dab624 adf4a4e 2dab624 a78c902 78205e4 a78c902 78205e4 a78c902 78205e4 a78c902 78205e4 a78c902 1ccc4ec 71f7767 e1f32ed 95cf7f2 e1f32ed 95cf7f2 e1f32ed 95cf7f2 e1f32ed 95cf7f2 e1f32ed 95cf7f2 e1f32ed 95cf7f2 2dab624 1ccc4ec 2dab624 1ccc4ec | 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 | // Dashboard functionality for Marine Species API
class MarineDashboard {
constructor() {
this.currentImage = null;
this.currentImageFile = null;
this.isProcessing = false;
this.initializeElements();
this.bindEvents();
this.checkAPIStatus();
this.loadSampleImages();
}
initializeElements() {
// Upload elements
this.uploadArea = document.getElementById('uploadArea');
this.fileInput = document.getElementById('fileInput');
this.identifyBtn = document.getElementById('identifyBtn');
// Settings elements
this.confidenceSlider = document.getElementById('confidenceSlider');
this.confidenceValue = document.getElementById('confidenceValue');
this.iouSlider = document.getElementById('iouSlider');
this.iouValue = document.getElementById('iouValue');
// Display elements
this.annotatedImageContainer = document.getElementById('annotatedImageContainer');
// Results elements
this.metadataSection = document.getElementById('metadataSection');
this.speciesSection = document.getElementById('speciesSection');
this.processingTime = document.getElementById('processingTime');
this.speciesCount = document.getElementById('speciesCount');
this.imageSize = document.getElementById('imageSize');
this.speciesList = document.getElementById('speciesList');
// Status elements
this.statusDot = document.getElementById('statusDot');
this.statusText = document.getElementById('statusText');
this.modelInfo = document.getElementById('modelInfo');
// Model details elements
this.totalSpecies = document.getElementById('totalSpecies');
this.deviceInfo = document.getElementById('deviceInfo');
// Sample images
this.sampleImagesSlider = document.getElementById('sampleImagesSlider');
this.sliderPrev = document.getElementById('sliderPrev');
this.sliderNext = document.getElementById('sliderNext');
}
bindEvents() {
// Upload area events
this.uploadArea.addEventListener('click', () => this.fileInput.click());
this.uploadArea.addEventListener('dragover', this.handleDragOver.bind(this));
this.uploadArea.addEventListener('dragleave', this.handleDragLeave.bind(this));
this.uploadArea.addEventListener('drop', this.handleDrop.bind(this));
// File input change
this.fileInput.addEventListener('change', this.handleFileSelect.bind(this));
// Settings sliders
this.confidenceSlider.addEventListener('input', this.updateConfidenceValue.bind(this));
this.iouSlider.addEventListener('input', this.updateIouValue.bind(this));
// Identify button
this.identifyBtn.addEventListener('click', this.identifySpecies.bind(this));
// Slider controls
this.sliderPrev.addEventListener('click', this.scrollSliderLeft.bind(this));
this.sliderNext.addEventListener('click', this.scrollSliderRight.bind(this));
}
// API Status Check
async checkAPIStatus() {
try {
const response = await fetch('/api/v1/health');
const data = await response.json();
if (data.model_loaded) {
this.statusDot.className = 'status-dot healthy';
this.statusText.textContent = 'API Ready';
if (data.model_info) {
this.modelInfo.textContent = `Model: ${data.model_info.model_name} (${data.model_info.total_classes} species)`;
this.totalSpecies.textContent = data.model_info.total_classes;
this.deviceInfo.textContent = data.model_info.device;
}
} else {
this.statusDot.className = 'status-dot error';
this.statusText.textContent = 'Model Loading...';
this.modelInfo.textContent = 'Please wait while the model loads';
}
} catch (error) {
this.statusDot.className = 'status-dot error';
this.statusText.textContent = 'API Unavailable';
this.modelInfo.textContent = 'Unable to connect to API';
console.error('API status check failed:', error);
}
}
// Drag and Drop Handlers
handleDragOver(e) {
e.preventDefault();
this.uploadArea.classList.add('dragover');
}
handleDragLeave(e) {
e.preventDefault();
this.uploadArea.classList.remove('dragover');
}
handleDrop(e) {
e.preventDefault();
this.uploadArea.classList.remove('dragover');
const files = e.dataTransfer.files;
if (files.length > 0) {
this.processFile(files[0]);
}
}
// File Selection Handler
handleFileSelect(e) {
const file = e.target.files[0];
if (file) {
this.processFile(file);
}
}
// Process Selected File
processFile(file) {
// Validate file type
if (!file.type.startsWith('image/')) {
window.MarineAPI.utils.showNotification('Please select an image file', 'error');
return;
}
// Validate file size (10MB limit)
if (file.size > 10 * 1024 * 1024) {
window.MarineAPI.utils.showNotification('File size must be less than 10MB', 'error');
return;
}
this.currentImageFile = file;
this.displayUploadedImage(file);
this.identifyBtn.disabled = false;
// Update upload area
this.uploadArea.classList.add('has-image');
}
// Display Uploaded Image in Upload Area
displayUploadedImage(file) {
const reader = new FileReader();
reader.onload = (e) => {
this.currentImage = e.target.result;
this.uploadArea.innerHTML = `
<img src="${e.target.result}" alt="Uploaded image" style="width: 100%; height: 100%; object-fit: cover; border-radius: 8px;" />
`;
};
reader.readAsDataURL(file);
}
// Settings Handlers
updateConfidenceValue() {
this.confidenceValue.textContent = `${this.confidenceSlider.value}%`;
}
updateIouValue() {
this.iouValue.textContent = `${this.iouSlider.value}%`;
}
// Main Identification Function
async identifySpecies() {
if (!this.currentImage || this.isProcessing) return;
this.isProcessing = true;
window.MarineAPI.utils.setLoading(this.identifyBtn, true);
try {
// Prepare request data
const requestData = {
image: this.currentImage.split(',')[1], // Remove data:image/jpeg;base64, prefix
confidence_threshold: this.confidenceSlider.value / 100,
iou_threshold: this.iouSlider.value / 100,
image_size: 640,
return_annotated_image: true
};
// Make API request
const response = await fetch('/api/v1/detect', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestData)
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`);
}
const result = await response.json();
this.displayResults(result);
window.MarineAPI.utils.showNotification('Species identification completed!', 'success');
} catch (error) {
console.error('Identification failed:', error);
window.MarineAPI.utils.showNotification('Identification failed. Please try again.', 'error');
} finally {
this.isProcessing = false;
window.MarineAPI.utils.setLoading(this.identifyBtn, false);
}
}
// Display Results
displayResults(result) {
const { detections, annotated_image, processing_time, image_dimensions } = result;
// Display annotated image
if (annotated_image) {
this.annotatedImageContainer.innerHTML = `
<img src="data:image/jpeg;base64,${annotated_image}" alt="Annotated results" />
`;
}
// Update metadata
this.processingTime.textContent = `${processing_time.toFixed(3)}s`;
this.speciesCount.textContent = detections.length;
this.imageSize.textContent = `${image_dimensions.width}×${image_dimensions.height}`;
// Show metadata section
this.metadataSection.style.display = 'block';
// Display species list
if (detections.length > 0) {
this.speciesList.innerHTML = detections.map(detection => `
<div class="species-item">
<span class="species-name">${detection.class_name}</span>
<span class="species-confidence">${(detection.confidence * 100).toFixed(1)}%</span>
</div>
`).join('');
this.speciesSection.style.display = 'block';
} else {
this.speciesList.innerHTML = '<p class="no-detections">No marine species detected. Try adjusting the confidence threshold.</p>';
this.speciesSection.style.display = 'block';
}
}
// Load Sample Images
loadSampleImages() {
const sampleImages = [
{ name: 'crab.png', description: 'Crab Species' },
{ name: 'fish.png', description: 'Fish Species' },
{ name: 'fish_2.png', description: 'Fish Variety' },
{ name: 'fish_3.png', description: 'Marine Fish' },
{ name: 'fish_4.png', description: 'Ocean Fish' },
{ name: 'fish_5.png', description: 'Deep Sea Fish' },
{ name: 'flat_fish.png', description: 'Flatfish' },
{ name: 'flat_red_fish.png', description: 'Red Flatfish' },
{ name: 'jelly.png', description: 'Jellyfish' },
{ name: 'jelly_2.png', description: 'Jellyfish Species' },
{ name: 'jelly_3.png', description: 'Marine Jelly' },
{ name: 'puff.png', description: 'Pufferfish' },
{ name: 'red_fish.png', description: 'Red Fish' },
{ name: 'red_fish_2.png', description: 'Red Fish Species' },
{ name: 'scene.png', description: 'Marine Scene' },
{ name: 'scene_2.png', description: 'Ocean Scene' },
{ name: 'scene_3.png', description: 'Underwater Scene' },
{ name: 'scene_4.png', description: 'Deep Sea Scene' },
{ name: 'scene_5.png', description: 'Marine Habitat' },
{ name: 'scene_6.png', description: 'Ocean Floor' },
{ name: 'soft_coral.png', description: 'Soft Coral' },
{ name: 'starfish.png', description: 'Starfish' },
{ name: 'starfish_2.png', description: 'Sea Star' }
].map(img => ({
...img,
url: `https://huggingface.co/seamo-ai/marina-species-v1/resolve/main/images/${img.name}`
}));
this.sampleImagesSlider.innerHTML = sampleImages.map(image => `
<div class="sample-image-item" onclick="dashboard.loadSampleImage('${image.url}', '${image.name}')">
<img src="${image.url}" alt="${image.description}" loading="lazy" />
<div class="sample-image-overlay">${image.description}</div>
</div>
`).join('');
}
// Load Sample Image
async loadSampleImage(imageUrl, imageName) {
try {
// Show loading state
window.MarineAPI.utils.showNotification('Loading sample image...', 'info');
let finalUrl = imageUrl;
// Try local URL first, fallback to HuggingFace if needed
try {
const testResponse = await fetch(imageUrl, { method: 'HEAD' });
if (!testResponse.ok) {
finalUrl = `https://huggingface.co/seamo-ai/marina-species-v1/resolve/main/images/${imageName}`;
}
} catch (e) {
finalUrl = `https://huggingface.co/seamo-ai/marina-species-v1/resolve/main/images/${imageName}`;
}
// Fetch the image
const response = await fetch(finalUrl);
if (!response.ok) {
throw new Error(`Failed to fetch image: ${response.status}`);
}
const blob = await response.blob();
// Convert to File object
const file = new File([blob], imageName, { type: blob.type });
// Process the file
this.processFile(file);
window.MarineAPI.utils.showNotification('Sample image loaded successfully!', 'success');
} catch (error) {
console.error('Failed to load sample image:', error);
window.MarineAPI.utils.showNotification('Failed to load sample image. Please try uploading your own image.', 'error');
}
}
// Slider Control Functions
scrollSliderLeft() {
const containerWidth = this.sampleImagesSlider.clientWidth;
this.sampleImagesSlider.scrollBy({
left: -containerWidth, // Scroll by full container width (2 images)
behavior: 'smooth'
});
}
scrollSliderRight() {
const containerWidth = this.sampleImagesSlider.clientWidth;
this.sampleImagesSlider.scrollBy({
left: containerWidth, // Scroll by full container width (2 images)
behavior: 'smooth'
});
}
}
// Global function for copy to clipboard (used by API docs)
window.copyToClipboard = function(elementId) {
const element = document.getElementById(elementId);
if (!element) {
console.error('Element not found:', elementId);
return;
}
const text = element.textContent;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(() => {
window.MarineAPI.utils.showNotification('Code copied to clipboard!', 'success');
}).catch(err => {
console.error('Failed to copy text: ', err);
fallbackCopyTextToClipboard(text);
});
} else {
fallbackCopyTextToClipboard(text);
}
};
// Fallback copy function for older browsers
function fallbackCopyTextToClipboard(text) {
const textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const successful = document.execCommand('copy');
if (successful) {
window.MarineAPI.utils.showNotification('Code copied to clipboard!', 'success');
} else {
window.MarineAPI.utils.showNotification('Failed to copy code', 'error');
}
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
window.MarineAPI.utils.showNotification('Failed to copy code', 'error');
}
document.body.removeChild(textArea);
}
// API Documentation Tabs
document.addEventListener('DOMContentLoaded', function() {
const tabButtons = document.querySelectorAll('.tab-button');
const tabContents = document.querySelectorAll('.tab-content');
tabButtons.forEach(button => {
button.addEventListener('click', function() {
const targetTab = this.getAttribute('data-tab');
// Remove active class from all buttons and contents
tabButtons.forEach(b => b.classList.remove('active'));
tabContents.forEach(c => c.classList.remove('active'));
// Add active class to clicked button
this.classList.add('active');
// Show corresponding tab content
const targetContent = document.getElementById(targetTab + '-tab');
if (targetContent) {
targetContent.classList.add('active');
}
});
});
});
// Copy code functionality
function copyCode(elementId) {
const codeElement = document.getElementById(elementId);
const text = codeElement.textContent;
navigator.clipboard.writeText(text).then(function() {
// Find the copy button and show feedback
const button = codeElement.parentElement.querySelector('.copy-button');
const originalText = button.textContent;
button.textContent = 'Copied!';
button.classList.add('copied');
setTimeout(() => {
button.textContent = originalText;
button.classList.remove('copied');
}, 2000);
}).catch(function(err) {
console.error('Failed to copy text: ', err);
});
}
// Make dashboard instance globally available for sample image clicks
let dashboard;
// Initialize dashboard when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
dashboard = new MarineDashboard();
});
|