How do you extract data from scanned invoices using vision LLMs combined with bounding-box OCR verification? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

How do you extract data from scanned invoices using vision LLMs combined with bounding-box OCR verification?

message-square
0

Overview

Vision LLMs can read scanned invoices well, but they can still misread small numbers, tax rows, or totals. Combining a vision LLM with bounding-box OCR lets you verify where each extracted value came from on the page.

  • Vision LLM for structure, OCR for exact text and coordinates: The vision LLM maps fields like invoiceNumber, totalAmount, and line items into a clean schema. The OCR engine returns exact words and bounding boxes (x, y, width, height, page number) so your code can match and verify values.
  • Spatial proof reduces silent number errors: Matching an extracted amount or date against OCR boxes near the right label or column catches hallucinations. If a value has no matching OCR text or low confidence, your code can flag it for review.

Steps

  1. Run OCR with word/line bounding boxes on each page: Extract text tokens along with normalized or pixel coordinates and page numbers from the scanned invoice image or PDF page.
  2. Pass the invoice image and OCR hints to the vision LLM: Ask the vision LLM to extract structured invoice fields and include supporting quotes or rough box hints when helpful.
  3. Match extracted fields against OCR bounding boxes: Search OCR tokens/lines for each extracted string or numeric value and compute text similarity and spatial proximity.
  4. Score confidence and enforce math/review gates: Check line-item sums against subtotal, tax, and total, and mark low-match or mismatched fields for human review.

Example

export interface BoundingBox {
  x: number; // Normalized 0..1 or pixel coordinate
  y: number;
  width: number;
  height: number;
  page: number;
}

export interface OcrToken {
  text: string;
  confidence: number;
  box: BoundingBox;
}

export interface LineItemExtraction {
  description: string;
  quantity: number | null;
  unitPrice: number | null;
  lineTotal: number | null;
}

export interface InvoiceExtraction {
  invoiceNumber: string | null;
  invoiceDate: string | null;
  currency: string | null;
  subtotal: number | null;
  tax: number | null;
  total: number | null;
  lineItems: LineItemExtraction[];
}

export interface VerifiedField<T> {
  value: T;
  verified: boolean;
  matchedText: string | null;
  ocrConfidence: number;
  boxes: BoundingBox[];
  reason: string;
}

export interface VerifiedInvoiceResult {
  data: InvoiceExtraction;
  fields: {
    invoiceNumber: VerifiedField<string | null>;
    total: VerifiedField<number | null>;
  };
  mathConsistent: boolean;
  needsHumanReview: boolean;
}

function normalizeForMatch(input: string): string {
  return input
    .toLowerCase()
    .replace(/[\$€£¥,\s]/g, "")
    .replace(/[^a-z0-9.-]/g, "");
}

function formatNumberVariants(num: number): string[] {
  return [
    num.toFixed(2),
    num.toFixed(0),
    String(num),
  ].map((s) => normalizeForMatch(s));
}

/**
 * Finds OCR tokens matching a target string or number and returns verification metadata.
 */
export function verifyAgainstOcr(
  label: string,
  value: string | number | null,
  tokens: OcrToken[]
): VerifiedField<typeof value> {
  if (value === null || value === "") {
    return {
      value,
      verified: false,
      matchedText: null,
      ocrConfidence: 0,
      boxes: [],
      reason: `${label} is missing from extraction.`,
    };
  }

  const needles =
    typeof value === "number"
      ? formatNumberVariants(value)
      : [normalizeForMatch(value)].filter(Boolean);

  const hits = tokens.filter((tok) => {
    const normTok = normalizeForMatch(tok.text);
    if (!normTok) return false;
    return needles.some((n) => n.length > 0 && (normTok === n || normTok.includes(n) || n.includes(normTok)));
  });

  if (hits.length === 0) {
    return {
      value,
      verified: false,
      matchedText: null,
      ocrConfidence: 0,
      boxes: [],
      reason: `No OCR bounding box matched ${label} ("${String(value)}").`,
    };
  }

  const avgConf =
    hits.reduce((sum, t) => sum + t.confidence, 0) / hits.length;

  return {
    value,
    verified: avgConf >= 0.7,
    matchedText: hits.map((h) => h.text).join(" "),
    ocrConfidence: Number(avgConf.toFixed(3)),
    boxes: hits.map((h) => h.box),
    reason: avgConf >= 0.7 ? "Matched OCR token(s)." : "Matched OCR token(s) with low confidence.",
  };
}

/**
 * Checks whether line items and tax reconcile with the extracted invoice total.
 */
export function checkInvoiceMath(extraction: InvoiceExtraction): boolean {
  if (extraction.total === null) return false;

  const itemsSum = extraction.lineItems.reduce((acc, item) => {
    return acc + (typeof item.lineTotal === "number" ? item.lineTotal : 0);
  }, 0);

  const baseAmount = extraction.subtotal ?? (itemsSum > 0 ? itemsSum : null);
  if (baseAmount === null) return true;

  const taxAmount = extraction.tax ?? 0;
  const expectedTotal = baseAmount + taxAmount;
  return Math.abs(expectedTotal - extraction.total) <= 0.02;
}

/**
 * Combines vision LLM structured output with OCR bounding-box checks.
 */
export function verifyInvoiceExtraction(
  extraction: InvoiceExtraction,
  ocrTokens: OcrToken[]
): VerifiedInvoiceResult {
  const invoiceNumberField = verifyAgainstOcr("invoiceNumber", extraction.invoiceNumber, ocrTokens);
  const totalField = verifyAgainstOcr("total", extraction.total, ocrTokens);
  const mathConsistent = checkInvoiceMath(extraction);

  const needsHumanReview =
    !invoiceNumberField.verified ||
    !totalField.verified ||
    !mathConsistent;

  return {
    data: extraction,
    fields: {
      invoiceNumber: invoiceNumberField,
      total: totalField,
    },
    mathConsistent,
    needsHumanReview,
  };
}

Tips

  • Deskew and render scanned PDFs at high DPI first: Tilted or low-resolution scans hurt both OCR boxes and vision LLM digits, so normalize orientation and render at ~200–300 DPI before running extraction.
  • Group OCR words into lines before matching multi-word totals or IDs: A single invoice number or formatted total often spans two or three OCR word boxes, so line-level grouping improves matching accuracy.
  • Route uncertain invoices to a human queue instead of guessing: When OCR boxes conflict with the vision LLM or totals do not add up, surface the highlighted bounding boxes in your UI for fast human review.