All files / services ocrService.js

0% Statements 0/131
0% Branches 0/68
0% Functions 0/15
0% Lines 0/118

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
const Tesseract = require('tesseract.js');
const { exec } = require('child_process');
const fs = require('fs').promises;
const path = require('path');
const logger = require('../utils/logger');
 
class OCRService {
  constructor() {
    this.initialized = false;
  }
 
  async initialize() {
    try {
      logger.info('Initializing OCR service...');
      this.initialized = true;
      logger.info('OCR service initialized successfully');
    } catch (error) {
      logger.error('Failed to initialize OCR service:', error);
      throw error;
    }
  }
 
  async extractTextFromPDF(pdfPath) {
    if (!this.initialized) {
      await this.initialize();
    }
 
    try {
      logger.info('Starting OCR extraction for PDF', { pdfPath });
 
      const tempDir = '/data/tmp/ocr-temp';
      await fs.mkdir(tempDir, { recursive: true });
      
      // Use pdftoppm to convert PDF to images
      const outputPattern = path.join(tempDir, 'page');
      
      // Convert PDF to PNG images using pdftoppm
      const convertCommand = `pdftoppm -png -r 300 "${pdfPath}" "${outputPattern}"`;
      
      await new Promise((resolve, reject) => {
        exec(convertCommand, (error, stdout, stderr) => {
          if (error) {
            logger.error('PDF conversion failed:', error);
            reject(error);
          } else {
            logger.info('PDF conversion completed');
            resolve();
          }
        });
      });
 
      // Find generated images
      const files = await fs.readdir(tempDir);
      const pageImages = files
        .filter(file => file.startsWith('page-') && file.endsWith('.png'))
        .map(file => path.join(tempDir, file))
        .sort(); // Sort to ensure page order
      
      // Limit to first 3 pages for performance
      const imagesToProcess = pageImages.slice(0, 3);
 
      logger.info(`Converted ${imagesToProcess.length} pages to images`);
 
      let extractedText = '';
      for (let i = 0; i < imagesToProcess.length; i++) {
        const imagePath = imagesToProcess[i];
        try {
          logger.info(`Processing page ${i + 1} with OCR`);
          
          const { data: { text } } = await Tesseract.recognize(imagePath, 'dan');
          extractedText += `\n--- Side ${i + 1} ---\n${text}\n`;
 
          try {
            await fs.unlink(imagePath);
          } catch (unlinkError) {
            logger.warn('Could not delete temp image:', unlinkError);
          }
 
        } catch (ocrError) {
          logger.error(`OCR failed for page ${i + 1}:`, ocrError);
          extractedText += `\n--- Side ${i + 1} (OCR fejlede) ---\n`;
        }
      }
 
      logger.info('OCR extraction completed', { 
        pages: imagesToProcess.length, 
        textLength: extractedText.length 
      });
 
      return extractedText;
 
    } catch (error) {
      logger.error('Error in OCR text extraction:', error);
      return `OCR extraction failed: ${error.message}`;
    }
  }
 
  async extractPriceDataFromText(text, documentType = 'material') {
    try {
      logger.info('Extracting structured price data from OCR text');
 
      const cleanedText = this.cleanOCRText(text);
      const priceLines = this.findPriceLines(cleanedText);
      
      logger.info(`Found ${priceLines.length} potential price lines`);
      if (priceLines.length > 0) {
        logger.info('Price lines found:', priceLines.slice(0, 3)); // Show first 3 lines
      }
 
      const extractedItems = [];
      for (const line of priceLines) {
        const parsed = this.parsePriceLine(line, documentType);
        if (parsed) {
          extractedItems.push(parsed);
        }
      }
 
      return {
        success: true,
        documentType,
        items: extractedItems,
        rawText: cleanedText,
        metadata: {
          totalLines: priceLines.length,
          parsedItems: extractedItems.length,
          timestamp: new Date().toISOString()
        }
      };
 
    } catch (error) {
      logger.error('Error extracting price data from text:', error);
      return {
        success: false,
        error: error.message,
        items: [],
        rawText: text
      };
    }
  }
 
  cleanOCRText(text) {
    let cleaned = text;
    const corrections = [
      [/\b0([0-9]+)\b/g, '$1'],           // Remove leading zeros
      [/([0-9])\s+([0-9])/g, '$1$2'],     // Remove spaces in numbers  
      [/,(\d{2})\s/g, ',$1 '],            // Fix decimal separators
      [/ +/g, ' '],                       // Multiple spaces to single (NOT \s+ which includes newlines!)
      [/\n\s*\n/g, '\n'],                 // Multiple newlines to single
    ];
 
    for (const [pattern, replacement] of corrections) {
      cleaned = cleaned.replace(pattern, replacement);
    }
 
    return cleaned.trim();
  }
 
  findPriceLines(text) {
    const lines = text.split('\n');
    const priceLines = [];
 
    // Enhanced patterns for Danish prices - more flexible
    const pricePatterns = [
      /\d+[.,]\d{2}/,           // Basic price pattern (123.45 or 123,45)
      /\d+,\d{2}/,              // Danish decimal format
      /\d+\.\d{3},\d{2}/,       // Danish thousands format (1.234,56)
      /\d{3,}\.\d{2}/,          // Also catch 1000.50 format
      /\d+\s*pakker/i,          // Lines with "pakker"
      /\d+\s*stk/i,             // Lines with "stk"
      /kr\.?/i,                 // Danish currency
      /DKK/i,                   // Currency code
      /pris\s*pr/i,             // "pris pr" patterns
      /\d+[.,]\d{2}.*\d+[.,]\d{2}/, // Lines with multiple prices
    ];
 
    for (const line of lines) {
      const trimmedLine = line.trim();
      
      // Skip empty lines and very short lines
      if (trimmedLine.length < 5) continue;
      if (/^(side|page|\d+\s*$|---|\s*$)/i.test(trimmedLine)) continue;
      
      // Skip pure header/contact info lines but be more selective
      if (/^(tlf\.|email:|web:|swift:|iban:|reg\.\s*nr\.?:|konto\s*nr\.?:)/i.test(trimmedLine)) continue;
      if (/^(leveringsadresse:|betalingsbetingelser:|leveringsform:)/i.test(trimmedLine)) continue;
      
      // Check if line contains price indicators
      const hasPrice = pricePatterns.some(pattern => pattern.test(trimmedLine));
      
      // Also include lines that look like product lines even without perfect price match
      const looksLikeProduct = /\d+.*mm\..*\d+[.,]\d+/i.test(trimmedLine) ||
                              /varenr.*\d+[.,]\d+/i.test(trimmedLine) ||
                              /\bmatlak\b.*\d+[.,]\d+/i.test(trimmedLine) ||
                              /\bplank\b.*\d+[.,]\d+/i.test(trimmedLine);
      
      if (hasPrice || looksLikeProduct) {
        priceLines.push(trimmedLine);
      }
    }
 
    return priceLines;
  }
 
  parsePriceLine(line, documentType) {
    try {
      // Enhanced price extraction for Danish format
      const priceMatches = line.match(/(\d{1,3}(?:\.\d{3})*,\d{2}|\d+,\d{2}|\d+\.\d{2})/g);
      if (!priceMatches || priceMatches.length === 0) return null;
 
      // Take the largest price found (usually the total)
      const prices = priceMatches.map(p => parseFloat(p.replace(/\./g, '').replace(',', '.')));
      const price = Math.max(...prices);
 
      // Extract units with better patterns
      const unitMatch = line.match(/\b(\d+(?:[.,]\d+)?)\s*(m²|m2|m³|m3|stk|pakker?|kg|timer?|løbm|enheder?|pcs)\b/i);
      const quantity = unitMatch ? parseFloat(unitMatch[1].replace(',', '.')) : 1;
      const unit = unitMatch ? unitMatch[2].toLowerCase() : 'stk';
 
      // Extract product name (everything before first number or specific patterns)
      let name = line;
      
      // Try different patterns to extract product name
      const patterns = [
        /^([^0-9]+?)\s*\d+/,                    // Text before first number
        /^(.*?)\s+\d+[.,]\d+\s*pakker?/i,      // Text before "X,XX pakker"
        /^(.*?)\s+\d+[.,]\d+\s*stk/i,          // Text before "X,XX stk"
        /^(.{10,60}?)\s+\d/,                   // First 10-60 chars before number
      ];
      
      for (const pattern of patterns) {
        const match = line.match(pattern);
        if (match && match[1].trim().length > 3) {
          name = match[1].trim();
          break;
        }
      }
 
      // Clean up name
      name = name
        .replace(/^(varenr\.?|artikel|item)\.?\s*/i, '')
        .replace(/\s*[-–—]\s*$/, '')
        .replace(/[^\w\sæøåÆØÅ\-.,()]/g, '')
        .trim();
 
      // Skip if name is too short or seems invalid
      if (name.length < 3 || /^\d+$/.test(name)) {
        name = `Produkt fra ${documentType}`;
      }
 
      // Extract SKU/article number
      const skuMatch = line.match(/\b([A-Z0-9]{4,}(?:-[A-Z0-9]+)*)\b/);
      const sku = skuMatch ? skuMatch[1] : null;
 
      return {
        sku,
        name: name.substring(0, 100), // Limit name length
        description: line.substring(0, 200), // Limit description length
        quantity,
        unit: this.normalizeUnit(unit),
        price,
        currency: 'DKK',
        source: 'ocr',
        confidence: this.calculatePriceConfidence(line, price, unit, name)
      };
 
    } catch (error) {
      logger.warn('Failed to parse price line:', { line, error: error.message });
      return null;
    }
  }
 
  calculatePriceConfidence(line, price, unit, name) {
    let confidence = 0.3; // Base confidence
 
    // Price seems reasonable
    if (price > 0 && price < 100000) confidence += 0.2;
    if (price > 10 && price < 50000) confidence += 0.1;
    
    // Has valid unit
    if (['m²', 'm³', 'stk', 'pakker', 'kg', 'time'].includes(unit)) confidence += 0.2;
    
    // Line length suggests complete information
    if (line.length > 20 && line.length < 300) confidence += 0.1;
    
    // Name seems reasonable
    if (name && name.length > 5 && name.length < 80) confidence += 0.1;
    
    // Contains product-like keywords
    if (/\b(plank|gulv|lak|eg|træ|mm\b|bredde|længde|pakke|leveringsomkostning|håndtering)/i.test(line)) {
      confidence += 0.1;
    }
 
    return Math.min(confidence, 1.0);
  }
 
  normalizeUnit(unit) {
    const unitMap = {
      'm²': 'm²', 'm2': 'm²', 'm³': 'm³', 'm3': 'm³',
      'stk': 'stk', 'pakker': 'pakker', 'pakke': 'pakker',
      'kg': 'kg', 'timer': 'time', 'time': 'time',
      'enheder': 'stk', 'pcs': 'stk'
    };
    return unitMap[unit.toLowerCase()] || unit;
  }
}
 
module.exports = new OCRService();