End-to-end showcase of the synthetic medical-bill + salvage-claim corpus added for analysis and fine-tuning without proprietary American Family Insurance data.
All documents are fictional. Carrier branding (American Family / AmFam) is used only to simulate intake surfaces — no proprietary claim files are loaded.
0. Setup
from __future__ import annotationsimport jsonimport loggingimport sqlite3import sysimport timefrom collections import Counterfrom pathlib import Pathimport matplotlib.pyplot as pltimport pandas as pdfrom IPython.display import Markdown, displayCWD = Path.cwd().resolve()# Walk up from docs/notebooks/ (or notebooks/) until pyproject.toml is found.REPO_ROOT =next( (p for p in (CWD, *CWD.parents) if (p /"pyproject.toml").exists()),None,)assert REPO_ROOT isnotNone, f"Could not find repo root from {CWD}"ifstr(REPO_ROOT) notin sys.path: sys.path.insert(0, str(REPO_ROOT))from src.docie import DociePipelinefrom src.docie.applications import list_applications, load_applicationfrom src.docie.evalimport evaluate_applicationfrom src.docie.pipeline import run_filefrom src.storage import DocumentStorefrom src.storage.sample_generator import generate_claim_bundle, generate_corpusfrom src.storage.schema import DDL, SCHEMA_VERSIONfrom src.storage.training import ( fit_tfidf_random_forest, prepare_both_applications,)from src.storage.types import ClaimRecord, DocumentRecord, FieldRecordfrom src.utils.config import Configfrom src.utils.io import load_jsonl, read_json, write_jsonlogging.basicConfig(level=logging.INFO, format="%(levelname)s%(name)s: %(message)s")cfg = Config.load()DEMO = REPO_ROOT /"data"/"notebook_demo"/"sample_corpus"DEMO.mkdir(parents=True, exist_ok=True)DB_PATH = DEMO /"documents.db"EXPORTS = DEMO /"exports"EXPORTS.mkdir(parents=True, exist_ok=True)PREPARED = DEMO /"prepared"MODELS = DEMO /"models"MODELS.mkdir(parents=True, exist_ok=True)SEED =42print(f"repo: {REPO_ROOT}")print(f"demo db: {DB_PATH}")print(f"exports: {EXPORTS}")print(f"schema v: {SCHEMA_VERSION}")print(f"apps: {list_applications()}")
corpus = generate_corpus( seed=SEED, medical_per_type=6, salvage_per_type=6, bundles_per_app=2, include_canonical_fixtures=True,)print(f"claims={len(corpus.claims)} documents={len(corpus.documents)}")type_counts = Counter((d.application, d.document_type) for d in corpus.documents)pd.DataFrame( [{"application": a, "document_type": t, "count": n} for (a, t), n insorted(type_counts.items())])
claims=46 documents=54
application
document_type
count
0
medical_bills
hcfa
9
1
medical_bills
other
9
2
medical_bills
ub04
9
3
salvage_claims
log
9
4
salvage_claims
other
9
5
salvage_claims
sales
9
Peek at a Letter of Guarantee and an HCFA
log_doc =next(d for d in corpus.documents if d.document_type =="log")hcfa_doc =next(d for d in corpus.documents if d.document_type =="hcfa")display(Markdown(f"**{log_doc.document_id}** (`{log_doc.document_type}`)"))print(log_doc.text[:800])print("---")display(Markdown(f"**{hcfa_doc.document_id}** (`{hcfa_doc.document_type}`)"))print(hcfa_doc.text[:800])print("\nLOG ground truth:", log_doc.ground_truth_fields())print("HCFA ground truth:", hcfa_doc.ground_truth_fields())
sal-log-001 (log)
LETTER OF GUARANTEE
First National Bank Lienholder Services
This letter guarantees that the insurer reimbursement will pay the bank first.
Claim Number: CLM-2024-100200
VIN: 1HGCM82633A004352
Year: 2018
Make: Honda
Model: Accord
Payoff Amount: $4,250.00
---
med-hcfa-001 (hcfa)
HCFA CMS-1500 HEALTH INSURANCE CLAIM FORM
Physician or Supplier Information
Patient Name: Jane Q Public
Date of Birth: 03/14/1988
Patient ID: PID-778812
Claim Number: CLM-2024-551122
Address: 100 Oak Avenue, Madison WI 53703
Carrier Name: American Family
Diagnosis and procedure codes follow.
LOG ground truth: {'claim_id': 'CLM-2024-100200', 'vin': '1HGCM82633A004352', 'year': '2018', 'make': 'Honda', 'model': 'Accord'}
HCFA ground truth: {'claim_id': 'CLM-2024-551122', 'name': 'Jane Q Public', 'dob': '03/14/1988', 'patient_id': 'PID-778812', 'address': '100 Oak Avenue, Madison WI 53703'}
3. Seed SQLite store
if DB_PATH.exists(): DB_PATH.unlink()store = DocumentStore(DB_PATH)n = store.bulk_upsert(corpus.documents, claims=corpus.claims)store.add_provenance( stage="notebook_seed", source="sample_document_corpus_walkthrough", detail={"documents": n, "seed": SEED},)summary = store.summary()display(summary)pd.DataFrame(summary["by_application_type"])
docs = store.list_documents(limit=8)pd.DataFrame( [ {"document_id": d.document_id,"application": d.application,"document_type": d.document_type,"claim_id": d.claim_id,"split": d.split,"source_kind": d.source_kind,"n_fields": len(d.fields), }for d in docs ])
document_id
application
document_type
claim_id
split
source_kind
n_fields
0
med-hcfa-001
medical_bills
hcfa
CLM-2024-551122
test
canonical_fixture
5
1
med-ub04-002
medical_bills
ub04
CLM-2024-660033
test
canonical_fixture
5
2
med-other-003
medical_bills
other
CLM-SYN-MED-OTHER-003
test
canonical_fixture
5
3
sal-log-001
salvage_claims
log
CLM-2024-100200
test
canonical_fixture
5
4
sal-sales-002
salvage_claims
sales
CLM-2024-100201
test
canonical_fixture
5
5
sal-other-003
salvage_claims
other
CLM-2024-100202
test
canonical_fixture
5
6
med-hcfa-100
medical_bills
hcfa
CLM-2022-719176
test
synthetic_seed
5
7
med-ub04-100
medical_bills
ub04
CLM-2024-946335
test
synthetic_seed
5
canonical = store.get_document("sal-log-001")assert canonical isnotNoneclaim = store.get_claim(canonical.claim_id) if canonical.claim_id elseNoneprint("carrier:", claim.carrier_name if claim elseNone)print("fields:", canonical.ground_truth_fields())print(canonical.text)
carrier: American Family
fields: {'claim_id': 'CLM-2024-100200', 'vin': '1HGCM82633A004352', 'year': '2018', 'make': 'Honda', 'model': 'Accord'}
LETTER OF GUARANTEE
First National Bank Lienholder Services
This letter guarantees that the insurer reimbursement will pay the bank first.
Claim Number: CLM-2024-100200
VIN: 1HGCM82633A004352
Year: 2018
Make: Honda
Model: Accord
Payoff Amount: $4,250.00
5. Claim bundles (multi-document salvage / medical files)
import randomrng = random.Random(7)claim, bundle_docs = generate_claim_bundle(rng, application="salvage_claims", bundle_index=99)store.upsert_claim(claim)for d in bundle_docs: store.upsert_document(d)bundled = store.list_documents(claim_id=claim.claim_id)print(f"claim {claim.claim_id} has {len(bundled)} documents:")for d in bundled:print(f" - {d.document_id:28s}{d.document_type:8s} title={d.title}")
claim CLM-2024-258176 has 3 documents:
- sal-bundle99-log log title=Letter of Guarantee
- sal-bundle99-sales sales title=Salvage Sales Receipt
- sal-bundle99-other other title=Towing / Storage Invoice
6. Export for DICIE / training
salvage_docie = EXPORTS /"salvage_docie.jsonl"medical_docie = EXPORTS /"medical_docie.jsonl"clf_all = EXPORTS /"classification_all.jsonl"ext_all = EXPORTS /"extraction_all.jsonl"n_sal = store.export_jsonl(salvage_docie, format="docie", application="salvage_claims")n_med = store.export_jsonl(medical_docie, format="docie", application="medical_bills")n_clf = store.export_jsonl(clf_all, format="classification")n_ext = store.export_jsonl(ext_all, format="extraction")print({"salvage_docie": n_sal, "medical_docie": n_med, "classification": n_clf, "extraction": n_ext})sample = load_jsonl(salvage_docie)[0]meta = {k: sample[k] for k in sample if k !="text"}print(json.dumps(meta, indent=2)[:800])print("text preview:\n", sample["text"][:400])
{'salvage_docie': 30, 'medical_docie': 27, 'classification': 57, 'extraction': 57}
{
"record_id": "sal-log-001",
"application": "salvage_claims",
"document_type": "log",
"ground_truth_fields": {
"claim_id": "CLM-2024-100200",
"vin": "1HGCM82633A004352",
"year": "2018",
"make": "Honda",
"model": "Accord"
},
"claim_id": "CLM-2024-100200",
"split": "test",
"metadata": {
"carrier_style": "american_family_simulation"
}
}
text preview:
LETTER OF GUARANTEE
First National Bank Lienholder Services
This letter guarantees that the insurer reimbursement will pay the bank first.
Claim Number: CLM-2024-100200
VIN: 1HGCM82633A004352
Year: 2018
Make: Honda
Model: Accord
Payoff Amount: $4,250.00
with sqlite3.connect(DB_PATH) as conn: conn.row_factory = sqlite3.Row rows = conn.execute("SELECT event_id, stage, source, detail_json, created_at ""FROM provenance_events ORDER BY event_id" ).fetchall()pd.DataFrame([dict(r) for r in rows])