Forge
Skip to main content

Intelligent document processing in finance: Building an insurance claims pipeline with W&B Weave

A step-by-step technical guide to building a fully local, zero-API-cost insurance document extraction pipeline using Qwen2.5-VL via Ollama and the SROIE receipt dataset, benchmarked against legacy Tesseract OCR.
Last updated: July 28, 2026

Table of Contents




Financial institutions and insurance carriers are drowning in unstructured papers. A mid-size P&C (property and casualty) carrier processes tens of thousands of claims documents every month: First Notice of Loss (FNOL) forms, medical expense claims, repair estimates, receipts etc. Most of them arrive as scanned PDFs or hazy mobile photos taken at accident scenes.
For decades, the standard Intelligent Document Processing (IDP) stack looked like this:
Scanned PDF -> Tesseract OCR -> Regex / Rules -> Manual Review Queue
It works, but until a hospital shifts a column by a few millimeters, a claimant writes over a printed line, or a new vendor introduces a slightly different date format. Suddenly, the regex breaks, and adjusters spend hours doing manual data entry.
Legacy IDP Extraction Path and Issues

1. The Business Imperative: Accuracy, Scale, and Privacy

When an IDP pipeline fails, the cost is not just a missing database entry. Extracted fields feed directly into multi-pillar financial analysis systems. If a pipeline extracts the wrong transaction total, the downstream diagnostic and predictive engines generate a lot of flawed risk reports and business trajectories.
Furthermore, the classic tradeoff in modern AI has always been Cost vs. Accuracy vs. Privacy.
Cloud vision APIs (like OpenAI's GPT or Anthropic's Claude Sonnet models) are highly accurate but cost thousands of dollars at enterprise scale to run. More importantly, they introduce massive data residency risks, which is a major concern across industries.

1.1 What local deployment actually solves?

Now, sending a scanned insurance document to a cloud API is not just a cost decision; it is a legal event.
Under GDPR Article 28, routing personal data to a third-party processor requires a Data Processing Agreement (DPA), and cross-border transfers outside the EU require either Standard Contractual Clauses or adequacy decisions.
Under India's DPDP Act 2023, financial institutions must conduct a Data Protection Impact Assessment before any significant automated processing of personal data.
Screen snip from the DPDP Act 2023
A local Ollama deployment eliminates this entire compliance surface -
  1. The document is processed on your infrastructure.
  2. The model weights are on your hardware, and
  3. Nothing is logged to an external server.
Your DPA with the cloud provider does not apply because there is no cloud provider. Your DPIA scope shrinks dramatically because there is no third-party data processor in the chain.
For insurance carriers operating across jurisdictions, this is not a minor operational detail. It is often the deciding factor between a project getting approved by legal or dying in committee.
This post outlines a modern, zero-compromise approach to IDP:
  • 100% Local Deployment: Data never leaves your infrastructure. Zero API costs. Inherently compliant with strict data protection laws.
  • Vision-Language Models (VLMs): Using Alibaba's Qwen2.5-VL via Ollama to read documents spatially, just like a human.
  • W&B Weave: A single-line observability integration to trace latency, track field-level accuracy, and monitor for template drift in production. (link)


Tesseract, the open-source OCR engine that powers most legacy IDP stacks, was tested against the same 20 SROIE receipts used throughout this post and has also established a baseline below in the post.
Modern VLM Path to extract data from receipts using Qwen

2. The Benchmark: SROIE sidelining the 'Perfect' data

To prove this architecture is production-ready, we need chaotic, real-world data. We are using the SROIE dataset (Scanned Receipts OCR and Information Extraction) from the ICDAR 2019 competition. It contains 973 real scanned receipts from stores and restaurants.
Each receipt has four ground-truth fields: company, date, address, and total. These are precisely the fields a financial auditor or insurance adjuster needs to validate a medical reimbursement or travel insurance claim. The receipts vary enormously in scan quality, layout density, language, and font-mirroring the exact distribution a production IDP system sees.

3. The Implementation: Clean, Asynchronous, and Traced

Let us forget writing massive for loops, handling batching logic, or using Pandas just to get an accuracy score. By leveraging Weights & Biases Weave Evaluation, the entire benchmarking and tracing process is handled absolutely natively.

3.1. Step 1: Initialization and observability

In a corporate environment, deploying an AI model without any auditability is not good and should not be done. If a model extracts the wrong total, the compliance teams need to know exactly what the model saw and why it made that decision. Explainability is crucial for technical audits.
This is where Weave comes in handy and provides this audit trail with a single line of code.
import re
import json
import asyncio
from pathlib import Path
from pydantic import BaseModel, Field
import weave
import ollama

DATA_DIR = Path("data/sroie")
MODEL_NAME = "qwen2.5vl:3b"

# Initialize the observability stack
weave.init("insurance-idp-qwen")
Output for Weave initialization

3.2. Step 2: Extraction from raw OCR Text using regex

Let's begin with building the foundations for marking the baseline first. We now define a function to use regex to get rule-based extraction from raw OCR texts using the regex_extract_receipt() function.
def regex_extract_receipt(text: str) -> dict:
lines = [l.strip() for l in text.split("\n") if l.strip()]
company = lines[0] if lines else ""
date = ""
address = " ".join(lines[1:3]) if len(lines) > 2 else ""
total = ""
# Regex for Date matching
date_match = re.search(r"(\d{1,2}[\-/]\d{1,2}[\-/]\d{2,4})", text)
if date_match:
date = date_match.group(1)
#Regex for Total matching
total_match = re.search(r"(?:RM|\$)?\s*([\d,]+\.\d{2})", text, re.IGNORECASE)
if total_match:
total = total_match.group(1)

return {"company": company, "date": date, "address": address, "total": total}

3.3. Step 3: Building the baseline - Tesseract OCR to Regex

Once we have defined the regex_extract_receipt() function, we use it to build the Tesseract pipeline in extract_tesseract(), which we now call the Legacy Pipeline or baseline to prove our performance with the Qwen models.
We use pytesseract to convert the image to text and extract the required values using regex; to monitor performance, we wrap it in Weave to track image-to-string conversion and regex extraction.
@weave.op()
def extract_tesseract(image_path: str) -> dict:
try:
img = Image.open(image_path)
raw_text = pytesseract.image_to_string(img, lang="eng", config="--oem 3 --psm 6")
extracted = regex_extract_receipt(raw_text)
except Exception:
raw_text = ""
extracted = {"company": "", "date": "", "address": "", "total": ""}
return {
"extracted": extracted,
"raw_response": raw_text[:200]
}
On Weave, we get this function call to look like this below.

As you can see here, the extract_tesseract function is being used.

3.4. Step 4: Forcing structured outputs

Moving to the cool and better process. Downstream financial systems require strictly typed data (JSON, XML, SQL inserts). Smaller VLMs are notorious for hallucinating conversational text alongside the data. E.g., "Here is the JSON you requested...". You don't want that; you just need the pure raw text that you have asked for.
By explicitly defining the schema in our prompt and writing a resilient JSON parser, we guarantee the output is machine-readable for Straight-Through Processing (STP). (Read more about STP here)
# Prompt structure
PROMPT = """
You are an expert at extracting information from scanned receipts.
Look at the receipt image carefully and extract exactly these four fields into a valid JSON object:
{
"company": "the store or company name at the top",
"date": "the transaction date",
"address": "the full store address",
"total": "the final total amount paid"
}
Use empty string "" for any field you cannot find. Output ONLY JSON.
"""
We define a prompt structure here asking the model to extract exactly the required fields into a proper JSON structure. On setting this, we parse the JSON and safely extract JSON from Qwen's output, stripping any markdown fences if needed.
def parse_json(raw: str) -> dict:
try:
if raw.strip().startswith("```"):
raw = "\n".join(raw.strip().split("\n")[1:-1])
match = re.search(r"\{.*\}", raw.strip(), re.DOTALL)
return json.loads(match.group()) if match else json.loads(raw)
except Exception:
return {"company": "", "date": "", "address": "", "total": ""}

3.5. Step 5: The Extraction Engine

This is the core of our pipeline. By wrapping the function with the @weave.op() decorator, W&B automatically logs the exact image sent to Ollama, the prompt used, the raw text returned, and the execution time.
@weave.op()
def extract_receipt(image_path: str) -> dict:
response = ollama.chat(
model=MODEL_NAME,
messages=[{"role": "user", "content": PROMPT, "images": [image_path]}],
format="json",
options={"temperature": 0}
)
raw_text = response["message"]["content"]
return {
"extracted": parse_json(raw_text),
"raw_response": raw_text[:200]
}
Notice that we pass format="json" to Ollama. The Qwen2.5-VL model is architected to handle strict tokeniser constraints seamlessly.

3.6. Step 6: Business-Logic Scoring

String equality is a terrible metric for document extraction. 'RM 11.00' and '11.00' refer to the exact same financial reality.
We define a function called normalize() here that lowercases and removes all non-alphanumeric characters for fair scoring and another function called score_extraction()
Our scoring function is also wrapped in Weave for tracking; it normalizes the text by removing spaces, currency symbols, and punctuation before comparing the ground truth to the model's prediction.
def normalize(text: str) -> str:
return re.sub(r'[^a-z0-9]', '', str(text).lower())

@weave.op()
def score_extraction(ground_truth: dict, model_output: dict) -> dict:
"""Scoring logic traced and aggregated by Weave."""
pred = model_output.get("extracted", {})
scores = {}
for field in ["company", "date", "address", "total"]:
gt_val = normalize(ground_truth.get(field, ""))
pred_val = normalize(pred.get(field, ""))
# Pass if there was no ground truth to find, otherwise check for overlap
if not gt_val:
scores[field] = 1
else:
scores[field] = 1 if gt_val in pred_val else 0
return {"overall_accuracy": sum(scores.values()) / 4, **scores}

3.7. Step 7: Load dataset from the data directory

Here we use the load_dataset() function to load matching images and JSON ground truths from the Kaggle's SROIE dataset structure.
def load_dataset(n: int = 20):
dataset = []
entity_map = {p.stem: p for p in DATA_DIR.rglob("*.txt")}
for img_path in sorted(DATA_DIR.rglob("*.jpg")):
if img_path.stem in entity_map:
try:
raw_gt = entity_map[img_path.stem].read_text(errors="ignore")
gt_data = json.loads(raw_gt)
if all(k in gt_data for k in ("company", "date", "address", "total")):
dataset.append({"image_path": str(img_path), "ground_truth": gt_data})
if len(dataset) >= n:
break
except json.JSONDecodeError:
continue
return dataset

3.8. Step 8: The Evaluation Loop

Now, instead of building custom evaluation scripts, weave.Evaluation() (read more) natively batches the dataset, runs the inference, applies the scorer, and logs the final metrics directly to your W&B dashboard.
async def main():
dataset_rows = load_dataset(20)
if not dataset_rows:
print("Dataset empty!")
return
dataset = weave.Dataset(name="sroie-sample", rows=dataset_rows)
evaluation = weave.Evaluation(
name="sroie-receipt-benchmark",
dataset=dataset,
scorers=[score_extraction],
)
print("Evaluating Legacy Tesseract Pipeline...")
await evaluation.evaluate(extract_tesseract)
print(f"\nEvaluating Modern VLM Pipeline ({MODEL_NAME})...")
await evaluation.evaluate(extract_receipt)
print("\nEvaluations Complete. Check W&B dashboard for the comparison view.")

# Run directly in the Jupyter event loop!
await main() Output for the main function with evaluation.
We get 2 outputs for this case.
  1. While evaluating Legacy Tesseract Pipeline -
    
  2. While evaluating the Qwen VLM Pipeline -
    

3.9. The Weave Evaluation

When you run multiple models through the same weave.Evaluation object, Weave automatically unlocks its Comparison View. This is arguably the most powerful feature for an engineering team trying to justify migrating from a legacy stack to an LLM/VLM stack.
Baseline vs New Evaluation Comparison Visualisation
Dataset results for the evaluation comparison on Weave
From this auto-generated dashboard, you can set Tesseract as your baseline and immediately see the delta.
  • Weave highlights exactly where Qwen succeeded where Tesseract failed.
  • You can drill down into specific ground-truth fields to see the raw JSON responses.
  • Evaluate whether the VLM is hallucinating, or
  • Identify the exact edge cases (like faded ink or multi-line addresses) where the legacy regex rules silently break.
Comparative results of the legacy pipeline vs the Qwen-powered pipeline
Based on the ground truth, we can see for every image how the model accuracy has worked out for all the parameters that we had asked for in the code -

4. The Results: ROI and the true cost of IDP

When running the 3-billion parameter version of Qwen2.5-VL against our chaotic receipt dataset, the out-of-the-box baseline results were quite good, as we can see from the above output:
  • Date: 100%
  • Total: 95%
  • Company: 90%
  • Address: 85%
  • Overall Baseline: 92.5%
The visualization below represents the blue area as the legacy pipeline metrics and the red area as the Qwen-powered pipeline metrics.

4.1. What does this mean for the business?

At 100,000 documents a year, the 'free' model isn't actually free. The true cost of an IDP system is measured in adjuster review hours. This means that if a legacy OCR pipeline achieves 60% accuracy, human operators must manually review and correct 40,000 documents. At 5 minutes per document and an assumed burdened rate of $30/hour, that is almost $100,000 a year purely in manual data entry.
By pushing the extraction accuracy to 92.5%, the review queue drops to 7,500 documents. So you've just saved the business roughly $80,000 in operational overhead while radically accelerating the time-to-decision for claims payouts. Furthermore, hitting 95%+ on critical fields like Total and Date means Straight-Through Processing (STP) pipelines can run without human intervention.
Below is a rough calculation stating the above -
MetricLegacy OCR (60%)Qwen2.5-VL (92.5%)
Errors (out of 100k docs)40,0007,500
Review time (5 min/doc)3,333 hours625 hours
Cost ($30/hr burdened)$100,000$18,750
Annual Savings-$81,250


4.2. Catching Silent Failures with Drift Detection

Now when a hospital inevitably updates its receipt template, traditional regex rules break silently, creating massive claims backlogs before anyone notices.
Because every production call in this architecture flows through the @weave.op() decorator, Weave's time-series view alerts the engineering teams to field-level accuracy drops in real time. More importantly, because VLMs like Qwen infer structure visually rather than relying on hardcoded text coordinates, so they are inherently resilient to these template changes.

5. The path to 99% - how to achieve higher accuracies

92.5% is a powerful baseline, but enterprise deployments often demand 98-99% accuracy before full automation is approved. The roadmap to closing that gap using this stack is pretty much straightforward:
  1. If your infrastructure supports it, swapping qwen2.5vl:3b for the 7b or 72b versions drastically enhances spatial reasoning for dense, multi-line addresses. (Learn more here)
  2. VLMs are brilliant zero-shot reasoners, but providing 1-2 examples of complex receipts and their perfect JSON extractions inside the system prompt reliably bumps accuracy by 3-5%.
  3. Use Weave to trace a multi-step workflow. If the first pass returns a blank 'total', write an agentic routing rule that crops the image to the bottom 30% and re-prompts the model: "You missed the total. Look closely at this cropped section."

Closing thoughts

The era of relying on brittle regex rules and fragile OCR pipelines to process critical financial documents is rapidly closing. As we have demonstrated, local Vision-Language Models like Qwen2.5-VL not only just offer a marginal upgrade but they also fundamentally change the math of Intelligent Document Processing. By achieving near-human extraction accuracy entirely on-premise, financial institutions can slash manual review costs and accelerate straight-through processing without ever sending sensitive PII to a cloud provider or running afoul of strict regulatory frameworks like the DPDP Act.
However, raw AI accuracy is useless without enterprise trust. By instrumenting your pipeline with Weights & Biases Weave, you can transform a black-box model into a transparent, auditable, and continuously monitored system that catches template drift before it impacts the bottom line. The tools to build secure, highly accurate, and fully observable IDP pipelines are now completely free and entirely in your control. It's time to stop writing regex and let the models do the reading.