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 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 12x 12x 2x 12x 2x 12x 12x 12x 12x 12x 1x 1x 11x 11x 11x 11x 9x 2x 2x 7x 7x 12x 12x 12x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 9x 24x 7x 3x 2x 2x 4x 6x 44x 44x 4x 4x 24x 5x 3x 2x 2x 2x 2x 24x 2x 3x 3x 3x 3x 3x 3x 1x 1x 2x 3x 2x 2x 24x 3x 3x 3x 3x 3x 3x 3x 2x 3x 2x 2x 2x 2x 2x 2x 2x 3x 2x 2x 2x 2x 2x 2x 2x 2x 3x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 3x 2x 3x 2x 3x 2x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x | // src/services/barcodeService.server.ts
/**
* @file Barcode Detection Service
* Provides barcode/UPC detection from images using zxing-wasm.
* Supports UPC-A, UPC-E, EAN-13, EAN-8, CODE-128, CODE-39, and QR codes.
*/
import type { Logger } from 'pino';
import type { Job } from 'bullmq';
import type { BarcodeDetectionJobData } from '../types/job-data';
import type { BarcodeDetectionResult } from '../types/upc';
import { upcRepo } from './db/index.db';
import sharp from 'sharp';
import fs from 'node:fs/promises';
/**
* Supported barcode formats for detection.
*/
export type BarcodeFormat =
| 'UPC-A'
| 'UPC-E'
| 'EAN-13'
| 'EAN-8'
| 'CODE-128'
| 'CODE-39'
| 'QR_CODE'
| 'unknown';
/**
* Maps zxing-wasm format names to our BarcodeFormat type.
*/
const formatMap: Record<string, BarcodeFormat> = {
'UPC-A': 'UPC-A',
'UPC-E': 'UPC-E',
'EAN-13': 'EAN-13',
'EAN-8': 'EAN-8',
Code128: 'CODE-128',
Code39: 'CODE-39',
QRCode: 'QR_CODE',
};
/**
* Detects barcodes in an image using zxing-wasm.
*
* @param imagePath Path to the image file
* @param logger Pino logger instance
* @returns Detection result with UPC code if found
*/
export const detectBarcode = async (
imagePath: string,
logger: Logger,
): Promise<BarcodeDetectionResult> => {
const detectionLogger = logger.child({ imagePath });
detectionLogger.info('Starting barcode detection');
try {
// Dynamically import zxing-wasm (ES module)
const { readBarcodesFromImageData } = await import('zxing-wasm/reader');
// Read and process the image with sharp
const imageBuffer = await fs.readFile(imagePath);
// Convert to raw pixel data (RGBA)
const image = sharp(imageBuffer);
const metadata = await image.metadata();
if (!metadata.width || !metadata.height) {
detectionLogger.warn('Could not determine image dimensions');
return {
detected: false,
upc_code: null,
confidence: null,
format: null,
error: 'Could not determine image dimensions',
};
}
// Convert to raw RGBA pixels
const { data, info } = await image.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
// Create ImageData-like object for zxing-wasm
const imageData = {
data: new Uint8ClampedArray(data),
width: info.width,
height: info.height,
colorSpace: 'srgb' as const,
};
detectionLogger.debug(
{ width: info.width, height: info.height },
'Processing image for barcode detection',
);
// Attempt barcode detection
const results = await readBarcodesFromImageData(imageData as ImageData, {
tryHarder: true,
tryRotate: true,
tryInvert: true,
formats: ['UPC-A', 'UPC-E', 'EAN-13', 'EAN-8', 'Code128', 'Code39'],
});
if (results.length === 0) {
detectionLogger.info('No barcode detected in image');
return {
detected: false,
upc_code: null,
confidence: null,
format: null,
error: null,
};
}
// Take the first (best) result
const bestResult = results[0];
const format = formatMap[bestResult.format] || 'unknown';
// Calculate confidence based on result quality indicators
// zxing-wasm doesn't provide direct confidence, so we estimate based on format match
const confidence = bestResult.text ? 0.95 : 0.5;
detectionLogger.info(
{ upcCode: bestResult.text, format, confidence },
'Barcode detected successfully',
);
return {
detected: true,
upc_code: bestResult.text,
confidence,
format,
error: null,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
detectionLogger.error({ err: error }, 'Barcode detection failed');
return {
detected: false,
upc_code: null,
confidence: null,
format: null,
error: errorMessage,
};
}
};
/**
* Validates a UPC code format.
* @param code The code to validate
* @returns True if valid UPC format
*/
export const isValidUpcFormat = (code: string): boolean => {
// UPC-A: 12 digits
// UPC-E: 8 digits
// EAN-13: 13 digits
// EAN-8: 8 digits
return /^[0-9]{8,14}$/.test(code);
};
/**
* Calculates the check digit for a UPC-A code.
* @param code The 11-digit UPC-A code (without check digit)
* @returns The check digit
*/
export const calculateUpcCheckDigit = (code: string): number | null => {
if (code.length !== 11 || !/^\d+$/.test(code)) {
return null;
}
let sum = 0;
for (let i = 0; i < 11; i++) {
const digit = parseInt(code[i], 10);
// Odd positions (0, 2, 4, ...) multiplied by 3
// Even positions (1, 3, 5, ...) multiplied by 1
sum += digit * (i % 2 === 0 ? 3 : 1);
}
const checkDigit = (10 - (sum % 10)) % 10;
return checkDigit;
};
/**
* Validates a UPC code including check digit.
* @param code The complete UPC code
* @returns True if check digit is valid
*/
export const validateUpcCheckDigit = (code: string): boolean => {
if (code.length !== 12 || !/^\d+$/.test(code)) {
return false;
}
const codeWithoutCheck = code.slice(0, 11);
const providedCheck = parseInt(code[11], 10);
const calculatedCheck = calculateUpcCheckDigit(codeWithoutCheck);
return calculatedCheck === providedCheck;
};
/**
* Processes a barcode detection job from the queue.
* @param job The BullMQ job
* @param logger Pino logger instance
* @returns Detection result
*/
export const processBarcodeDetectionJob = async (
job: Job<BarcodeDetectionJobData>,
logger: Logger,
): Promise<BarcodeDetectionResult> => {
const { scanId, imagePath, userId } = job.data;
const jobLogger = logger.child({
jobId: job.id,
scanId,
userId,
requestId: job.data.meta?.requestId,
});
jobLogger.info('Processing barcode detection job');
try {
// Attempt barcode detection
const result = await detectBarcode(imagePath, jobLogger);
// If a code was detected, update the scan record
if (result.detected && result.upc_code) {
await upcRepo.updateScanWithDetectedCode(
scanId,
result.upc_code,
result.confidence,
jobLogger,
);
jobLogger.info(
{ upcCode: result.upc_code, confidence: result.confidence },
'Barcode detected and scan record updated',
);
} else {
jobLogger.info('No barcode detected in image');
}
return result;
} catch (error) {
jobLogger.error({ err: error }, 'Barcode detection job failed');
return {
detected: false,
upc_code: null,
confidence: null,
format: null,
error: error instanceof Error ? error.message : String(error),
};
}
};
/**
* Detects multiple barcodes in an image.
* Useful for receipts or product lists with multiple items.
* @param imagePath Path to the image file
* @param logger Pino logger instance
* @returns Array of detection results
*/
export const detectMultipleBarcodes = async (
imagePath: string,
logger: Logger,
): Promise<BarcodeDetectionResult[]> => {
const detectionLogger = logger.child({ imagePath });
detectionLogger.info('Starting multiple barcode detection');
try {
const { readBarcodesFromImageData } = await import('zxing-wasm/reader');
// Read and process the image
const imageBuffer = await fs.readFile(imagePath);
const image = sharp(imageBuffer);
const { data, info } = await image.ensureAlpha().raw().toBuffer({ resolveWithObject: true });
const imageData = {
data: new Uint8ClampedArray(data),
width: info.width,
height: info.height,
colorSpace: 'srgb' as const,
};
// Detect all barcodes
const results = await readBarcodesFromImageData(imageData as ImageData, {
tryHarder: true,
tryRotate: true,
tryInvert: true,
formats: ['UPC-A', 'UPC-E', 'EAN-13', 'EAN-8', 'Code128', 'Code39'],
});
detectionLogger.info({ count: results.length }, 'Multiple barcode detection complete');
return results.map((result) => ({
detected: true,
upc_code: result.text,
confidence: 0.95,
format: formatMap[result.format] || 'unknown',
error: null,
}));
} catch (error) {
detectionLogger.error({ err: error }, 'Multiple barcode detection failed');
return [];
}
};
/**
* Enhances image for better barcode detection.
* Applies preprocessing like grayscale conversion, contrast adjustment, etc.
* @param imagePath Path to the source image
* @param logger Pino logger instance
* @returns Path to enhanced image (or original if enhancement fails)
*/
export const enhanceImageForDetection = async (
imagePath: string,
logger: Logger,
): Promise<string> => {
const detectionLogger = logger.child({ imagePath });
try {
// Create enhanced version with improved contrast for barcode detection
const enhancedPath = imagePath.replace(/(\.[^.]+)$/, '-enhanced$1');
await sharp(imagePath)
.grayscale()
.normalize() // Improve contrast
.sharpen() // Enhance edges
.toFile(enhancedPath);
detectionLogger.debug({ enhancedPath }, 'Image enhanced for barcode detection');
return enhancedPath;
} catch (error) {
detectionLogger.warn({ err: error }, 'Image enhancement failed, using original');
return imagePath;
}
};
|