"""Generates a deliberately MESSY ten-year archive, so you can practise on realistic
problems without real customer data. Everything is fictional and deterministic.
data/raw/pdfs/ born-digital, scanned, skewed, faxed, sideways, mixed,
duplicated, re-scanned, blank and corrupted PDFs
data/raw/mainframe/ EBCDIC files (FB + VB) with their COBOL copybooks
data/raw/db2/ a "DB2" table of agent notes (SQLite stand-in)
data/raw/golden.jsonl questions with known answers, for measuring retrieval
"""
from __future__ import annotations
import io
import json
import random
import shutil
import sqlite3
from decimal import Decimal
from pathlib import Path
import cv2
import numpy as np
import pymupdf
from .sources.ebcdic import encode_alnum, encode_binary, encode_packed, encode_zoned
BANK = "ACME SAVINGS BANK"
FILLER = [
"This document supersedes all prior guidance on the subject and applies to every branch and operations center.",
"Managers are responsible for ensuring that staff complete the related training within thirty days of publication.",
"Questions regarding interpretation should be directed to the Compliance Department through the usual channels.",
"Exceptions must be documented, approved in writing, and retained with the related customer file for audit review.",
"Internal Audit will test adherence to this standard as part of the annual operational risk assessment.",
"Where local regulations are stricter than this document, the stricter requirement shall always apply.",
"Records created under this procedure are classified as internal and must not be shared outside the bank.",
]
# (path, title, date, kind, facts, table)
DOCS = [
("2015/Overdraft_Fee_Schedule_2015.pdf", "Overdraft Fee Schedule", "January 12, 2015", "digital",
["The standard overdraft fee is $35 per item, with a maximum of three overdraft fees charged per business day.",
"No overdraft fee is charged when the account is overdrawn by $5 or less at the end of the business day."],
[["Item", "Fee", "Daily cap"], ["Overdraft paid", "$35.00", "3 items"], ["Returned item (NSF)", "$35.00", "3 items"], ["Extended overdraft", "$7.00 per day", "n/a"]]),
("2016/scans/wire_cutoff_policy.pdf", "Wire Transfer Cutoff Policy", "March 3, 2016", "scan",
["Domestic wire transfer requests received after the 4:30 PM Eastern cutoff are processed on the next business day.",
"International wires require dual approval when the amount exceeds $50,000."], None),
("2017/escrow_procedure_scan.pdf", "Mortgage Escrow Analysis Procedure", "April 18, 2017", "scan-noisy",
["When the annual escrow analysis shows a shortage, the shortage is spread evenly over the next 12 monthly payments.",
"A surplus of $50 or more is refunded to the borrower within 30 days of the analysis."], None),
("2018/records/data_retention_standard_FAX.pdf", "Data Retention Standard", "June 5, 2018", "fax",
["Loan files must be retained for seven years after the loan is closed or paid off.",
"Teller journals are retained for five years and then securely destroyed."], None),
("2018/letters/customer_letter_dispute.pdf", "Customer Dispute Letter", "September 21, 2018", "digital",
["Re: dispute of card transaction. Customer SSN 123-45-6789 and card 4111 1111 1111 1111 were verified by phone.",
"The disputed amount of $412.80 was provisionally credited while the claim is investigated.",
"Please contact the customer at jane.doe@example.com with the outcome."], None),
("2019/branch_cash_limits.pdf", "Branch Cash Limits", "February 11, 2019", "digital",
["The maximum cash held in a single teller drawer is $25,000; excess cash must be moved to the vault.",
"Vault cash above $400,000 must be shipped to the cash center the same day."],
[["Location", "Limit"], ["Teller drawer", "$25,000"], ["Branch vault", "$400,000"], ["ATM cassette", "$60,000"]]),
("2020/payment_deferral_program.pdf", "Pandemic Payment Deferral Program", "April 2, 2020", "scan-sideways",
["Eligible borrowers may defer consumer loan payments for up to 180 days without late fees.",
"Deferred payments are added to the end of the loan term; interest continues to accrue."], None),
("2021/incident_atm_outage_riverside.pdf", "Incident Report: ATM Outage at Riverside Branch", "August 14, 2021", "mixed",
["The Riverside branch ATMs were unavailable for six hours on August 14, 2021.",
"The root cause was a failed uninterruptible power supply (UPS) in the branch network closet."], None),
("2022/small_business_credit_policy.pdf", "Small Business Loan Credit Policy", "January 20, 2022", "digital-long",
["Small business loans require a minimum debt service coverage ratio (DSCR) of 1.25.",
"Personal guarantees are required from any owner holding 20 percent or more of the business."], None),
("2023/fraud_alert_check_kiting.pdf", "Fraud Alert: Check Kiting", "May 8, 2023", "scan-noisy",
["When check kiting is suspected, a hold of five business days is placed on deposited checks.",
"Report suspected kiting on account 4400123456 with SSN 987-65-4321 to the Fraud Unit immediately."], None),
("2024/complaint_handling_sla.pdf", "Customer Complaint Handling SLA", "March 1, 2024", "digital",
["Every customer complaint must be acknowledged within two business days.",
"Complaints must be resolved, or escalated to the Complaints Officer, within 15 business days."], None),
]
GOLDEN = [
("What is the overdraft fee per item?", "pdf:2015/Overdraft_Fee_Schedule_2015.pdf"),
("What time is the domestic wire transfer cutoff?", "pdf:2016/scans/wire_cutoff_policy.pdf"),
("How is an escrow shortage repaid?", "pdf:2017/escrow_procedure_scan.pdf"),
("How long must loan files be kept after the loan closes?", "pdf:2018/records/data_retention_standard_FAX.pdf"),
("What is the maximum cash allowed in a teller drawer?", "pdf:2019/branch_cash_limits.pdf"),
("For how long could borrowers defer payments during the pandemic?", "pdf:2020/payment_deferral_program.pdf"),
("What caused the ATM outage at the Riverside branch?", "pdf:2021/incident_atm_outage_riverside.pdf"),
("What debt service coverage ratio do small business loans need?", "pdf:2022/small_business_credit_policy.pdf"),
("How long is the hold when check kiting is suspected?", "pdf:2023/fraud_alert_check_kiting.pdf"),
("How quickly must a customer complaint be acknowledged?", "pdf:2024/complaint_handling_sla.pdf"),
("Which bakery customer is delinquent?", "custmast:00010042"),
("customer 00010017", "custmast:00010017"),
("Why was the overdraft limit increase for the bakery declined?", "db2:loan_notes:1027"),
# Paraphrases: different words than the source (where dense embeddings should shine)
("What happens to a wire request submitted late in the afternoon?", "pdf:2016/scans/wire_cutoff_policy.pdf"),
("How many years do we keep old mortgage paperwork?", "pdf:2018/records/data_retention_standard_FAX.pdf"),
("Can a teller keep thirty thousand dollars at the window?", "pdf:2019/branch_cash_limits.pdf"),
("Why did the cash machines stop working in 2021?", "pdf:2021/incident_atm_outage_riverside.pdf"),
("Who has to personally guarantee a business loan?", "pdf:2022/small_business_credit_policy.pdf"),
("What happens if the escrow account has extra money?", "pdf:2017/escrow_procedure_scan.pdf"),
# Exact tokens: codes, IDs, jargon (where sparse/BM25 should shine)
("NSF CHG RETURNED CHK 1043", "custmast:00010042"),
("DSCR 1.25", "pdf:2022/small_business_credit_policy.pdf"),
("customer 00010023", "custmast:00010023"),
("MARGARET O'NEIL", "custmast:00010017"),
("Riverside Bakery overdraft limit 5000", "db2:loan_notes:1027"),
("extended overdraft $7.00 per day", "pdf:2015/Overdraft_Fee_Schedule_2015.pdf"),
]
# --------------------------------------------------------------- PDF build --
def _wrap(text: str, width: float, font: str, size: float) -> list[str]:
"""Wrap text to a width, hyphenating some long words at line ends, like typeset docs."""
from reportlab.pdfbase.pdfmetrics import stringWidth
lines, line = [], ""
for word in text.split():
trial = f"{line} {word}".strip()
if stringWidth(trial, font, size) <= width:
line = trial
continue
if len(word) >= 9: # split long words: "pro-" + "cessing"
for cut in range(len(word) - 4, 3, -1):
head = f"{line} {word[:cut]}-".strip()
if stringWidth(head, font, size) <= width:
lines.append(head)
line = word[cut:]
break
else:
lines.append(line)
line = word
else:
lines.append(line)
line = word
if line:
lines.append(line)
return lines
def _digital_pdf(title: str, date: str, facts: list[str], table, rng: random.Random, long: bool = False) -> bytes:
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
sections = [("1. PURPOSE", [f"This document describes the {title.lower()} of {BANK.title()}.", rng.choice(FILLER)]),
("2. SCOPE", [rng.choice(FILLER), rng.choice(FILLER)]),
("3. POLICY", facts + [rng.choice(FILLER)]),
("4. PROCEDURE", [rng.choice(FILLER) for _ in range(6 if long else 2)]),
("5. EXCEPTIONS", [rng.choice(FILLER) for _ in range(5 if long else 1)])]
if long:
sections.insert(4, ("4A. UNDERWRITING REQUIREMENTS", [
f"Underwriters must analyze {k} for every application and document the analysis in the credit memorandum. " + rng.choice(FILLER)
for k in ["three years of business tax returns", "interim financial statements", "the business plan",
"collateral valuations", "the guarantor's personal financial statement", "industry risk", "management experience"]]))
buf = io.BytesIO()
c = canvas.Canvas(buf, pagesize=letter, invariant=1) # no timestamps/random IDs: reproducible bytes
c.setTitle(title)
W, H = letter
pages: list[list[tuple]] = [[]]
y = H - 110
def emit(item, height):
nonlocal y
if y - height < 80:
pages.append([])
y = H - 110
pages[-1].append((item, y))
y -= height
emit(("title", title), 26)
emit(("text", f"Date: {date}"), 16)
emit(("text", f"From: Policy Office To: All Branches Classification: Internal"), 24)
for heading, paras in sections:
emit(("heading", heading), 20)
for p in paras:
for line in _wrap(p, W - 144, "Helvetica", 10.5):
emit(("text", line), 14)
y -= 6
if heading == "3. POLICY" and table:
emit(("table", table), 22 * len(table) + 12)
total = len(pages)
for n, items in enumerate(pages, 1):
c.setFont("Helvetica-Bold", 9)
c.drawString(72, H - 50, f"{BANK} - INTERNAL")
c.setFont("Helvetica", 8)
c.drawString(72, 40, "Confidential - do not distribute outside the bank")
c.drawRightString(W - 72, 40, f"Page {n} of {total}")
for (kind, val), yy in items:
if kind == "title":
c.setFont("Helvetica-Bold", 16)
c.drawString(72, yy, val)
elif kind == "heading":
c.setFont("Helvetica-Bold", 11)
c.drawString(72, yy, val)
elif kind == "text":
c.setFont("Helvetica", 10.5)
c.drawString(72, yy, val)
elif kind == "table":
col_w = (W - 144) / len(val[0])
for r, row in enumerate(val):
ry = yy - r * 22
c.setFont("Helvetica-Bold" if r == 0 else "Helvetica", 10)
for ci, cell in enumerate(row):
c.drawString(72 + ci * col_w + 6, ry - 15, cell)
c.line(72, ry, W - 72, ry)
bottom = yy - len(val) * 22
c.line(72, bottom, W - 72, bottom)
for ci in range(len(val[0]) + 1):
c.line(72 + ci * col_w, yy, 72 + ci * col_w, bottom)
c.showPage()
c.save()
return buf.getvalue()
def _degrade(gray: np.ndarray, rng: np.random.Generator, skew: float, noise: float, fax: bool) -> np.ndarray:
"""Make a clean render look like a real scan: tilt, grey uneven paper, blur, speckles, JPEG."""
h, w = gray.shape
img = cv2.warpAffine(gray, cv2.getRotationMatrix2D((w / 2, h / 2), skew, 1.0), (w, h), borderValue=255)
if fax:
img = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA)
img = np.where(img < 150, 0, 255).astype(np.uint8) # 1-bit fax look
img = cv2.resize(img, (w, h), interpolation=cv2.INTER_NEAREST)
gradient = np.linspace(0, 40, w)[None, :] + np.linspace(0, 25, h)[:, None] # uneven lighting
img = img.astype(np.float32) - gradient * (img > 128)
img = cv2.GaussianBlur(img, (3, 3), 0) + rng.normal(0, noise, img.shape)
speckles = rng.random(img.shape) < 0.002
img[speckles] = 0
img = np.clip(img, 0, 255).astype(np.uint8)
ok, jpg = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 45])
return cv2.imdecode(jpg, cv2.IMREAD_GRAYSCALE)
def _to_scanned(pdf_bytes: bytes, rng: np.random.Generator, *, dpi: int = 200, skew: float = 0, noise: float = 8,
fax: bool = False, sideways_pages: tuple = (), keep_digital: tuple = ()) -> bytes:
src = pymupdf.open(stream=pdf_bytes, filetype="pdf")
out = pymupdf.open()
for page in src:
if page.number in keep_digital:
out.insert_pdf(src, from_page=page.number, to_page=page.number)
continue
pix = page.get_pixmap(dpi=dpi, colorspace=pymupdf.csGRAY)
gray = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width)
img = _degrade(gray, rng, skew + rng.uniform(-0.4, 0.4), noise, fax)
rect = page.rect
if page.number in sideways_pages:
img = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE) # fed into the scanner sideways
rect = pymupdf.Rect(0, 0, rect.height, rect.width)
new = out.new_page(width=rect.width, height=rect.height)
new.insert_image(rect, stream=cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 70])[1].tobytes())
data = out.tobytes(garbage=3, deflate=True, no_new_id=True) # reproducible: same input -> same bytes
out.close()
src.close()
return data
def build_pdfs(root: Path, rng: random.Random, nrng: np.random.Generator) -> None:
for path, title, date, kind, facts, table in DOCS:
target = root / path
target.parent.mkdir(parents=True, exist_ok=True)
digital = _digital_pdf(title, date, facts, table, random.Random(title), long=kind in ("digital-long", "mixed"))
data = {
"digital": lambda: digital,
"digital-long": lambda: digital,
"scan": lambda: _to_scanned(digital, nrng, skew=2.5),
"scan-noisy": lambda: _to_scanned(digital, nrng, skew=-1.8, noise=18),
"fax": lambda: _to_scanned(digital, nrng, skew=0.8, fax=True),
"scan-sideways": lambda: _to_scanned(digital, nrng, skew=1.0, sideways_pages=(0,)),
"mixed": lambda: _to_scanned(digital, nrng, skew=-1.2, keep_digital=(0,)),
}[kind]()
target.write_bytes(data)
# The mess every archive has:
(root / "archive").mkdir(exist_ok=True)
shutil.copy(root / DOCS[1][0], root / "archive/COPY_OF_wire_cutoff_policy.pdf") # exact duplicate
rescan = _to_scanned((root / DOCS[5][0]).read_bytes(), nrng, skew=1.5, noise=10) # same memo, scanned later
(root / "2019/scans").mkdir(parents=True, exist_ok=True)
(root / "2019/scans/branch_cash_limits_rescan.pdf").write_bytes(rescan)
(root / "misc").mkdir(exist_ok=True)
blank = pymupdf.open()
page = blank.new_page()
noise_img = np.clip(235 + nrng.normal(0, 12, (1100, 850)), 0, 255).astype(np.uint8)
page.insert_image(page.rect, stream=cv2.imencode(".jpg", noise_img)[1].tobytes())
(root / "misc/blank_scan.pdf").write_bytes(blank.tobytes(no_new_id=True)) # the back side of a page, scanned
(root / "misc/corrupted_transfer.pdf").write_bytes(digital[:900]) # truncated during an old FTP copy
# ------------------------------------------------------------ mainframe -----
FIRST = ["JAMES", "MARY", "ROBERT", "PATRICIA", "JOHN", "JENNIFER", "MICHAEL", "LINDA", "DAVID", "ELIZABETH", "WILLIAM", "BARBARA", "RICHARD", "SUSAN"]
LAST = ["SMITH", "JOHNSON", "WILLIAMS", "BROWN", "JONES", "GARCIA", "MILLER", "DAVIS", "RODRIGUEZ", "MARTINEZ", "HERNANDEZ", "LOPEZ"]
CITIES = [("SPRINGFIELD", "IL", 62701), ("RIVERSIDE", "CA", 92501), ("FAIRVIEW", "TX", 75069), ("MADISON", "WI", 53703), ("GEORGETOWN", "KY", 40324)]
MEMOS = {"DEP": ["PAYROLL DEP", "MOBILE DEP CHK", "CASH DEP BR 12"], "WDL": ["ATM WDL", "BR WDL", "POS PURCHASE"],
"FEE": ["OD FEE CHG", "NSF CHG RETURNED CHK", "MONTHLY SVC CHG"], "XFR": ["XFER TO SAVINGS", "XFER FROM SAVINGS", "ONLINE XFER"]}
def _customer_record(cid: int, rng: random.Random) -> bytes:
business = cid == 10042 or rng.random() < 0.15
name = "RIVERSIDE BAKERY LLC" if cid == 10042 else (f"{rng.choice(LAST)} {rng.choice(['HARDWARE', 'DENTAL', 'FARMS'])} INC" if business else f"{rng.choice(FIRST)} {rng.choice(LAST)}")
foreign = cid == 10017
if cid == 10017:
name = "MARGARET O'NEIL"
city, state, zipc = ("RIVERSIDE", "CA", 92501) if cid == 10042 else rng.choice(CITIES)
year = rng.randint(1995, 2024)
open_date = 0 if cid in (10005, 10033) else int(f"{year}{rng.randint(1, 12):02d}{rng.randint(1, 28):02d}")
status = "D" if cid in (10042, 10051) else rng.choice("AAAAAAAC")
balance = Decimal(rng.randint(-50000, 9000000)) / 100
phones = [f"{rng.randint(200, 989)}-555-{rng.randint(1000, 9999)}" for _ in range(rng.randint(0, 3))]
rec = encode_zoned(cid, 8) + encode_alnum("B" if business else "P", 1) + encode_alnum(name, 30)
rec += encode_alnum("F" if foreign else "D", 1)
if foreign:
rec += encode_alnum("12 BAKER STREET", 30) + encode_alnum("UNITED KINGDOM", 20) + encode_alnum("NW1 6XE", 7)
else:
rec += encode_alnum(f"{rng.randint(1, 9999)} {rng.choice(['MAIN', 'OAK', 'ELM', 'MARKET'])} ST", 30) + encode_alnum(city, 20) + encode_alnum(state, 2) + encode_zoned(zipc, 5)
rec += encode_zoned(open_date, 8)
rec += b"\x12\x34\x5a\xbc\xde\xff" if cid == 10023 else encode_packed(balance, 6, scale=2) # 10023: corrupted COMP-3
rec += encode_packed(Decimal(rng.choice([1000, 2500, 5000, 10000])), 5, scale=2)
rec += encode_binary(rng.randint(300, 850), 2)
rec += encode_zoned(Decimal(rng.randint(-99999, 99999)) / 100, 7, scale=2, signed=True)
rec += encode_zoned(len(phones), 1)
rec += b"".join(encode_alnum(p, 12) for p in (phones + ["", "", ""])[:3])
rec += encode_alnum(status, 1) + b"\x00" * 10 # FILLER of LOW-VALUES
assert len(rec) == 173, len(rec)
return rec
def _txn_record(cid: int, d: tuple[int, int, int], code: str, amount: Decimal, memo: str) -> bytes:
y, m, day = d
cyymmdd = int(f"{(y - 1900) // 100}{y % 100:02d}{m:02d}{day:02d}")
body = encode_zoned(cid, 8) + encode_zoned(cyymmdd, 7) + encode_alnum(code, 3) + encode_packed(amount, 5, scale=2)
body += encode_binary(len(memo), 2) + encode_alnum(memo, len(memo))
return (len(body) + 4).to_bytes(2, "big") + b"\x00\x00" + body # RDW + record
def build_mainframe(root: Path, rng: random.Random, copybooks: Path) -> None:
root.mkdir(parents=True, exist_ok=True)
for cb in copybooks.glob("*.cpy"):
shutil.copy(cb, root / cb.name)
ids = range(10001, 10061)
(root / "CUSTMAST.DAT").write_bytes(b"".join(_customer_record(c, rng) for c in ids))
txns = []
for c in ids:
for _ in range(rng.randint(2, 7)):
code = rng.choice(list(MEMOS))
amount = Decimal(rng.randint(500, 250000)) / 100 * (-1 if code in ("WDL", "FEE") else 1)
memo = rng.choice(MEMOS[code]) + (f" {rng.randint(1000, 1999)}" if "CHK" in MEMOS[code][0] else "")
txns.append(_txn_record(c, (rng.randint(2015, 2024), rng.randint(1, 12), rng.randint(1, 28)), code, amount, memo))
txns.append(_txn_record(10042, (2023, 5, 15), "FEE", Decimal("-35.00"), "NSF CHG RETURNED CHK 1043"))
txns.append(_txn_record(10042, (2023, 5, 16), "FEE", Decimal("-35.00"), "OD FEE CHG"))
(root / "TXNHIST.DAT").write_bytes(b"".join(txns))
def build_db2(root: Path, rng: random.Random) -> None:
root.mkdir(parents=True, exist_ok=True)
db = root / "loan_notes.sqlite"
db.unlink(missing_ok=True)
with sqlite3.connect(db) as conn:
conn.execute("CREATE TABLE LOAN_NOTES (NOTE_ID INTEGER PRIMARY KEY, CUST_ID INTEGER, AGENT TEXT, CREATED_TS TEXT, UPDATED_TS TEXT, NOTE_TEXT TEXT)")
templates = ["CUST CALLED RE LATE PMT - PROMISED PMT BY FRIDAY", "LVM RE ACCT REVIEW - CB REQ", "CUST REQ ADDR CHG - SENT FORM",
"PMT ARRANGEMENT APPR 3 MOS", "CUST DISPUTES FEE CHG - REFERRED TO BR MGR", "ESCROW BAL INQUIRY - EXPLAINED ANALYSIS"]
rows = []
for i in range(1001, 1041):
ts = f"{rng.randint(2016, 2024)}-{rng.randint(1, 12):02d}-{rng.randint(1, 28):02d} 10:{rng.randint(10, 59)}:00"
text = rng.choice(templates)
cust = rng.randint(10001, 10060)
if i == 1027:
cust, ts, text = 10042, "2023-05-17 14:05:00", "CUST REQ OD LIMIT INCREASE TO 5000 - DECL DUE TO NSF HISTORY. ADVISED CUST TO REAPPLY IN 6 MOS"
rows.append((i, cust, rng.choice(["JTR", "MKL", "SAB", "DPW"]), ts, ts, text))
conn.executemany("INSERT INTO LOAN_NOTES VALUES (?,?,?,?,?,?)", rows)
def generate(raw: Path, copybooks: Path) -> None:
rng, nrng = random.Random(2026), np.random.default_rng(2026)
if raw.exists():
shutil.rmtree(raw)
build_pdfs(raw / "pdfs", rng, nrng)
build_mainframe(raw / "mainframe", rng, copybooks)
build_db2(raw / "db2", rng)
with open(raw / "golden.jsonl", "w") as f:
for q, expect in GOLDEN:
f.write(json.dumps({"question": q, "expect": expect}) + "\n")