From 5149ab1a8829c196921d6b945a8a7b235f108424 Mon Sep 17 00:00:00 2001 From: John O'Keefe Date: Mon, 13 Apr 2026 20:14:04 -0400 Subject: [PATCH] refactor(detector): improve COCO-SSD model loading and caching - Add #model private field to cache loaded model instance - Properly await model.load() before using the model - Pass cached model to detection function instead of global reference - Add model cleanup in clear() method to release resources This prevents redundant model loading and ensures the model is fully initialized before use, improving performance and reliability of ML-based panel detection. --- panel-detection/detector.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/panel-detection/detector.js b/panel-detection/detector.js index 2314c1d..0e09130 100644 --- a/panel-detection/detector.js +++ b/panel-detection/detector.js @@ -1,11 +1,10 @@ -import { loadMLLibraries, getLibrariesStatus } from "./load-scripts.js"; - // panel-detection/detector.js // Main panel detector with lazy-loaded fallback chain import { loadMLLibraries, getLibrariesStatus } from "./load-scripts.js"; export class PanelDetector { #cache = new Map(); #scriptsLoaded = false; + #model = null; async detectPanels(doc, index, force = false) { const cacheKey = `${doc.location?.pathname || ""}-${index}`; @@ -94,14 +93,14 @@ export class PanelDetector { // Try ML (uses global cocoSsd) try { - const cocoSsd = globalThis.cocoSsd; - if (cocoSsd) { - // Wait for COCO-SSD to be ready - if (!cocoSsd.load) { - await new Promise((resolve) => setTimeout(resolve, 100)); + const cocoSsdModule = globalThis.cocoSsd; + if (cocoSsdModule && cocoSsdModule.load) { + // Load model if not cached + if (!this.#model) { + this.#model = await cocoSsdModule.load(); } - const panels = await detectPanelsML(imageData, cocoSsd); + const panels = await detectPanelsML(imageData, this.#model); if (this.#validatePanels(panels, imageData)) { return { panels, method: "ml", confidence: 0.7 }; } @@ -132,6 +131,7 @@ export class PanelDetector { clear() { this.#cache.clear(); + this.#model = null; } // Expose library status for debugging