All files objectDetection.js

67.39% Statements 93/138
48.21% Branches 27/56
94.11% Functions 16/17
67.96% Lines 87/128

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            1x 1x   1x   1x 1x 1x 1x   1x             1x                                                                               6x 6x       3x   3x 3x   3x   3x                               3x     3x 3x 3x       3x   3x   3x             3x     3x   3x                   3x         3x     3x 3x 1228800x 1228800x 1228800x       3x 3x               3x                                                                                                                                     4x   1x   1x 3x   3x 2x 1x 1x 1x 1x         3x 2x       1x       1x 1x 1x 1x   1x 1x 1x 1x   1x         3x   20x                             2x 2x     3x 3x   2x 3x   1x 1x                     2x 3x 1x                     2x 3x 3x 2x 2x                       2x       2x                 2x       1x           1x       2x 2x 2x 2x 2x       1x  
/**
 * Object Detection Service
 * Uses ONNX Runtime for inference with YOLO-based models
 */
 
let ort;
try {
  ort = require('onnxruntime-node');
} catch {
  console.warn('onnxruntime-node not available, using fallback mode');
}
const sharp = require('sharp');
const path = require('path');
const fs = require('fs').promises;
const winston = require('winston');
 
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.simple(),
  transports: [new winston.transports.Console()]
});
 
// Component definitions for different object types
const COMPONENT_DEFINITIONS = {
  atm: [
    { id: 'card_reader', name: 'Card Reader', critical: true },
    { id: 'pin_pad', name: 'PIN Pad', critical: true },
    { id: 'display', name: 'Display', critical: false },
    { id: 'cash_dispenser', name: 'Cash Dispenser', critical: true },
    { id: 'nfc_reader', name: 'NFC Reader', critical: false },
    { id: 'receipt_printer', name: 'Receipt Printer', critical: false },
    { id: 'camera', name: 'Camera', critical: false },
    { id: 'speaker', name: 'Speaker', critical: false },
    { id: 'skimmer', name: 'Skimmer Device', critical: true, anomaly: true },
    { id: 'extra_device', name: 'Extra Device', critical: true, anomaly: true }
  ],
  charging_station: [
    { id: 'display', name: 'Display', critical: false },
    { id: 'cable', name: 'Cable', critical: true },
    { id: 'connector', name: 'Connector', critical: true },
    { id: 'payment_terminal', name: 'Payment Terminal', critical: true },
    { id: 'status_lights', name: 'Status Lights', critical: false },
    { id: 'emergency_stop', name: 'Emergency Stop', critical: true }
  ],
  parking_meter: [
    { id: 'display', name: 'Display', critical: false },
    { id: 'coin_slot', name: 'Coin Slot', critical: true },
    { id: 'card_reader', name: 'Card Reader', critical: true },
    { id: 'receipt_printer', name: 'Receipt Printer', critical: false },
    { id: 'keypad', name: 'Keypad', critical: true },
    { id: 'qr_scanner', name: 'QR Scanner', critical: false }
  ],
  defibrillator: [
    { id: 'cabinet', name: 'Cabinet', critical: true },
    { id: 'status_indicator', name: 'Status Indicator', critical: true },
    { id: 'access_handle', name: 'Access Handle', critical: true },
    { id: 'instructions', name: 'Instructions', critical: false },
    { id: 'speaker', name: 'Speaker', critical: false }
  ]
};
 
class ObjectDetectionService {
  constructor() {
    this.sessions = new Map();
    this.modelPath = process.env.MODEL_PATH || './data/models';
  }
 
  async loadModel(objectType) {
    const modelFile = path.join(this.modelPath, `${objectType}_detection.onnx`);
    
    try {
      await fs.access(modelFile);
    } catch {
      logger.warn(`Model not found for ${objectType}, using generic`);
      // Fallback to generic model
      return null;
    }
 
    try {
      if (!ort) throw new Error('ONNX not available');
      const session = await ort.InferenceSession.create(modelFile);
      this.sessions.set(objectType, session);
      logger.info(`Loaded model for ${objectType}`);
      return session;
    } catch (error) {
      logger.error(`Failed to load model for ${objectType}:`, error);
      return null;
    }
  }
 
  async detect(imageBuffer, objectType, options = {}) {
    const startTime = Date.now();
    
    // Get or load model
    let session = this.sessions.get(objectType);
    Eif (!session) {
      session = await this.loadModel(objectType);
    }
 
    // Preprocess image
    const { tensor, originalSize } = await this.preprocess(imageBuffer);
    
    let detections = [];
    
    Iif (session) {
      // Run ONNX inference
      const feeds = { input: tensor };
      const results = await session.run(feeds);
      detections = this.postprocess(results, originalSize, objectType, options);
    } else {
      // Fallback: Simulate detection for testing
      detections = this.simulateDetection(objectType, options);
    }
 
    const duration = Date.now() - startTime;
    
    return {
      detections,
      modelVersion: 'v1.0.0',
      inferenceTime: duration,
      imageSize: originalSize
    };
  }
 
  async preprocess(imageBuffer) {
    // Resize to model input size (typically 640x640 for YOLO)
    const processed = await sharp(imageBuffer)
      .resize(640, 640, { fit: 'contain', background: { r: 114, g: 114, b: 114 } })
      .raw()
      .toBuffer({ resolveWithObject: true });
 
    const { data, info } = processed;
    
    // Convert to float32 and normalize
    const floatData = new Float32Array(640 * 640 * 3);
    for (let i = 0; i < data.length; i += 3) {
      floatData[i / 3 * 3] = data[i] / 255.0;
      floatData[i / 3 * 3 + 1] = data[i + 1] / 255.0;
      floatData[i / 3 * 3 + 2] = data[i + 2] / 255.0;
    }
 
    // Create tensor [1, 3, 640, 640] if ONNX is available
    let tensor = null;
    Iif (ort) {
      try {
        tensor = new ort.Tensor('float32', floatData, [1, 3, 640, 640]);
      } catch (e) {
        // Fallback if Tensor creation fails
      }
    }
 
    return {
      tensor,
      originalSize: { width: info.width, height: info.height }
    };
  }
 
  postprocess(results, originalSize, objectType, options) {
    const { confidenceThreshold = 0.5 } = options;
    const components = COMPONENT_DEFINITIONS[objectType] || [];
    
    // Parse YOLO output format
    // This is a simplified version - real implementation depends on model format
    const output = results.output || results['output0'];
    if (!output) return [];
 
    const detections = [];
    const data = output.data;
    const dims = output.dims;
    
    // YOLOv8 output: [batch, 84, 8400] where 84 = 4 bbox + 80 classes
    const numDetections = dims[2];
    const numClasses = dims[1] - 4;
    
    for (let i = 0; i < numDetections; i++) {
      const offset = i * (4 + numClasses);
      const x = data[offset];
      const y = data[offset + 1];
      const w = data[offset + 2];
      const h = data[offset + 3];
      
      // Find best class
      let bestScore = 0;
      let bestClass = -1;
      
      for (let c = 0; c < numClasses && c < components.length; c++) {
        const score = data[offset + 4 + c];
        if (score > bestScore) {
          bestScore = score;
          bestClass = c;
        }
      }
      
      if (bestScore > confidenceThreshold && bestClass >= 0) {
        const component = components[bestClass];
        if (component) {
          detections.push({
            componentType: component.id,
            componentName: component.name,
            confidence: bestScore,
            boundingBox: {
              x: (x - w / 2) / 640,
              y: (y - h / 2) / 640,
              width: w / 640,
              height: h / 640
            },
            critical: component.critical || false
          });
        }
      }
    }
 
    // Apply NMS (Non-Maximum Suppression)
    return this.applyNMS(detections, 0.45);
  }
 
  applyNMS(detections, iouThreshold) {
    // Sort by confidence
    detections.sort((a, b) => b.confidence - a.confidence);
    
    const kept = [];
    
    for (const det of detections) {
      let shouldKeep = true;
      
      for (const keptDet of kept) {
        if (det.componentType === keptDet.componentType) {
          const iou = this.calculateIoU(det.boundingBox, keptDet.boundingBox);
          Eif (iou > iouThreshold) {
            shouldKeep = false;
            break;
          }
        }
      }
      
      if (shouldKeep) {
        kept.push(det);
      }
    }
    
    return kept;
  }
 
  calculateIoU(box1, box2) {
    const x1 = Math.max(box1.x, box2.x);
    const y1 = Math.max(box1.y, box2.y);
    const x2 = Math.min(box1.x + box1.width, box2.x + box2.width);
    const y2 = Math.min(box1.y + box1.height, box2.y + box2.height);
    
    const intersection = Math.max(0, x2 - x1) * Math.max(0, y2 - y1);
    const area1 = box1.width * box1.height;
    const area2 = box2.width * box2.height;
    const union = area1 + area2 - intersection;
    
    return union > 0 ? intersection / union : 0;
  }
 
  simulateDetection(objectType, options) {
    // For testing without a real model
    const components = COMPONENT_DEFINITIONS[objectType] || [];
    
    return components.map(comp => ({
      componentType: comp.id,
      componentName: comp.name,
      confidence: 0.85 + Math.random() * 0.14,
      boundingBox: {
        x: Math.random() * 0.7,
        y: Math.random() * 0.7,
        width: 0.1 + Math.random() * 0.2,
        height: 0.1 + Math.random() * 0.2
      },
      critical: comp.critical || false
    }));
  }
 
  async detectAnomalies(detections, referenceDetections, objectType) {
    const anomalies = [];
    const riskRules = this.getRiskRules(objectType);
    
    // Check for new components
    const currentTypes = new Set(detections.map(d => d.componentType));
    const referenceTypes = new Set(referenceDetections.map(d => d.componentType));
    
    for (const det of detections) {
      if (!referenceTypes.has(det.componentType)) {
        // New component detected
        const riskLevel = riskRules[`new_${det.componentType}`] || 'yellow';
        anomalies.push({
          type: 'new_object',
          component: det.componentType,
          confidence: det.confidence,
          severity: this.riskToSeverity(riskLevel),
          description: `New component detected: ${det.componentName}`
        });
      }
    }
    
    // Check for missing components
    for (const ref of referenceDetections) {
      if (!currentTypes.has(ref.componentType)) {
        anomalies.push({
          type: 'missing_component',
          component: ref.componentType,
          confidence: 0.9,
          severity: 'high',
          description: `Missing component: ${ref.componentName}`
        });
      }
    }
    
    // Check for position changes in critical components
    for (const det of detections) {
      const ref = referenceDetections.find(r => r.componentType === det.componentType);
      if (ref) {
        const distance = this.calculateDistance(det.boundingBox, ref.boundingBox);
        Iif (distance > 0.1) { // 10% of image size
          anomalies.push({
            type: 'position_shift',
            component: det.componentType,
            confidence: 0.8,
            severity: 'medium',
            description: `Component position changed: ${det.componentName}`
          });
        }
      }
    }
    
    return anomalies;
  }
 
  getRiskRules(objectType) {
    const rules = {
      atm: {
        new_object_near_card_reader: 'orange',
        extra_plastic_on_card_reader: 'red',
        pin_pad_modified: 'red',
        display_changed: 'yellow',
        camera_blocked: 'orange'
      }
    };
    return rules[objectType] || {};
  }
 
  riskToSeverity(risk) {
    const map = {
      green: 'low',
      yellow: 'medium',
      orange: 'high',
      red: 'critical'
    };
    return map[risk] || 'medium';
  }
 
  calculateDistance(box1, box2) {
    const cx1 = box1.x + box1.width / 2;
    const cy1 = box1.y + box1.height / 2;
    const cx2 = box2.x + box2.width / 2;
    const cy2 = box2.y + box2.height / 2;
    return Math.sqrt(Math.pow(cx2 - cx1, 2) + Math.pow(cy2 - cy1, 2));
  }
}
 
module.exports = { ObjectDetectionService };