305 lines
14 KiB
Python
305 lines
14 KiB
Python
"""
|
|
Generates two fully-synthetic bank statement fixtures - fake bank/company
|
|
names, fake account numbers, invented transactions - so backend/measure.py
|
|
has a committable regression corpus again, after the real HSBC/RBC
|
|
fixtures were stripped from git history for containing real financial
|
|
data (see CLAUDE.md's "Real fixtures removed from git history" entry).
|
|
|
|
Both fixtures are built from ONE shared Python list of transaction data
|
|
each, used to write BOTH the PDF and its ground-truth .xlsx, so the two
|
|
can never drift apart by a transcription mistake. Every description stays
|
|
on a single line with its amount on the same line - no multi-line
|
|
narrative wrapping, no leading/trailing continuation-text convention -
|
|
that complexity isn't needed to re-prove the extractor's real
|
|
column-detection/dual-engine/checks pipeline, and skipping it keeps the
|
|
ground truth exactly derivable from the same data, not hand-verified by
|
|
eye the way the real fixtures were.
|
|
|
|
Two deliberately different column shapes, to still exercise the
|
|
"bank-agnostic" claim this harness exists to prove:
|
|
Fixture A - split Debit/Credit columns, newest-first order, no in-table
|
|
opening/closing balance (printed as plain statement-level
|
|
text, like HSBC) - debit printed as a plain positive
|
|
magnitude (not self-signed), auto-negated by the extractor.
|
|
Fixture B - a single signed Amount column, oldest-first order, WITH
|
|
in-table Opening balance/Closing balance rows (like RBC).
|
|
|
|
Column x-positions were chosen and verified against real
|
|
reportlab.pdfbase.pdfmetrics.stringWidth measurements (not guessed) so
|
|
every header label's own resolved zone is wide enough for the data below
|
|
it, and so no two money columns' zones overlap - see the inline comments
|
|
at each fixture's own COLUMNS dict.
|
|
|
|
Run: python3 fixtures/generate_synthetic_fixtures.py
|
|
Produces:
|
|
fixtures/Fake-Bank-A-Synthetic.pdf (+ _ground_truth.xlsx)
|
|
fixtures/Fake-Bank-B-Synthetic.pdf (+ _ground_truth.xlsx)
|
|
"""
|
|
import os
|
|
|
|
import openpyxl
|
|
from reportlab.lib.pagesizes import LETTER
|
|
from reportlab.pdfgen import canvas
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
PAGE_W, PAGE_H = LETTER # 612 x 792
|
|
FONT, FONT_SIZE = "Helvetica", 10
|
|
BOLD_FONT = "Helvetica-Bold"
|
|
ROW_HEIGHT = 20
|
|
# The preamble block (title + 3 info lines, see _draw_preamble) occupies
|
|
# y=742 down to y=700 - HEADER_Y must sit well below that with a real
|
|
# gap, not just below the title alone (a first draft set this
|
|
# independently of the preamble's own height and the two overlapped
|
|
# vertically, which layout_quirks then merged into one garbled line -
|
|
# confirmed via a direct _find_zones() debug run before fixing this).
|
|
HEADER_Y = 650
|
|
ROWS_PER_PAGE = 10
|
|
|
|
|
|
def _money(value):
|
|
""""1,234.56" / "-45.00" style text - plain, no currency symbol, the
|
|
simplest _MONEY_RE-matching shape, same convention HSBC/RBC's own
|
|
bare amounts use."""
|
|
sign = "-" if value < 0 else ""
|
|
return f"{sign}{abs(value):,.2f}"
|
|
|
|
|
|
def _draw_preamble(c, title, lines):
|
|
"""Fake org/account preamble, well above any page's own header row
|
|
(HEADER_Y) - excluded from row processing purely by POSITION
|
|
(extract_page's own header-top preamble filter), same as a real
|
|
statement's letterhead/account-summary block."""
|
|
y = PAGE_H - 50
|
|
c.setFont(BOLD_FONT, 12)
|
|
c.drawString(36, y, title)
|
|
c.setFont(FONT, 9)
|
|
for line in lines:
|
|
y -= 14
|
|
c.drawString(36, y, line)
|
|
|
|
|
|
def _draw_header(c, header_y, columns):
|
|
c.setFont(BOLD_FONT, FONT_SIZE)
|
|
for col in columns:
|
|
if col["align"] == "left":
|
|
c.drawString(col["x"], header_y, col["header"])
|
|
else:
|
|
c.drawRightString(col["x"], header_y, col["header"])
|
|
|
|
|
|
def _draw_rows_paginated(c, rows, columns, preamble_title, preamble_lines):
|
|
"""rows: list of dicts, each {col_key: text}. Starts a fresh page
|
|
(with the preamble + header repeated) whenever the current page's
|
|
row budget (ROWS_PER_PAGE) is used up - repeating the header on every
|
|
page is the simplest, most realistic choice (sidesteps relying on
|
|
extract_page's own carry_zones fallback, which is already covered by
|
|
the real fixtures' own historical testing, not this corpus's job to
|
|
re-prove)."""
|
|
def new_page():
|
|
_draw_preamble(c, preamble_title, preamble_lines)
|
|
_draw_header(c, HEADER_Y, columns)
|
|
return HEADER_Y - ROW_HEIGHT
|
|
|
|
y = new_page()
|
|
c.setFont(FONT, FONT_SIZE)
|
|
count_on_page = 0
|
|
for row in rows:
|
|
if count_on_page >= ROWS_PER_PAGE:
|
|
c.showPage()
|
|
y = new_page()
|
|
c.setFont(FONT, FONT_SIZE)
|
|
count_on_page = 0
|
|
for col in columns:
|
|
text = row.get(col["key"], "")
|
|
if not text:
|
|
continue
|
|
if col["align"] == "left":
|
|
c.drawString(col["x"], y, text)
|
|
else:
|
|
c.drawRightString(col["x"], y, text)
|
|
y -= ROW_HEIGHT
|
|
count_on_page += 1
|
|
c.showPage()
|
|
|
|
|
|
def _write_ground_truth(path, txn_rows, opening_balance, closing_balance):
|
|
"""Transactions sheet (date/status/description/amount/balance, same
|
|
canonical order the PDF rows were written in) + Summary sheet
|
|
(opening_balance/closing_balance) - the exact shape
|
|
backend/measure.py's own _load_ground_truth expects."""
|
|
wb = openpyxl.Workbook()
|
|
ws = wb.active
|
|
ws.title = "Transactions"
|
|
ws.append(["date", "status", "description", "amount", "balance"])
|
|
for t in txn_rows:
|
|
ws.append([t["date"], "", t["description"], t["amount"], t["balance"]])
|
|
|
|
ws2 = wb.create_sheet("Summary")
|
|
ws2.append(["key", "value"])
|
|
ws2.append(["opening_balance", opening_balance])
|
|
ws2.append(["closing_balance", closing_balance])
|
|
|
|
wb.save(path)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Fixture A - Debit/Credit columns, newest-first, no in-table balance.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def build_fixture_a():
|
|
# (day, description, signed_delta) in CHRONOLOGICAL (oldest-first)
|
|
# order - delta > 0 is a credit, delta < 0 is a debit. Reversed just
|
|
# before writing, to print/ground-truth in newest-first order.
|
|
chronological = [
|
|
(3, "Payroll Deposit - Northwind Co", 2400.00),
|
|
(4, "Grocery Store Purchase", -86.42),
|
|
(5, "Electric Utility Payment", -142.10),
|
|
(6, "Coffee Shop Purchase", -5.75),
|
|
(7, "Online Retailer Order", -64.99),
|
|
(8, "Mobile Phone Bill", -58.00),
|
|
(9, "Freelance Invoice Payment", 650.00),
|
|
(10, "Streaming Subscription", -15.99),
|
|
(11, "Pharmacy Purchase", -22.30),
|
|
(12, "Restaurant - Dinner", -48.60),
|
|
(13, "Gym Membership Fee", -40.00),
|
|
(14, "Payroll Deposit - Northwind Co", 2400.00),
|
|
(15, "Rent Payment", -1200.00),
|
|
(16, "Internet Service Bill", -70.00),
|
|
(17, "Hardware Store Purchase", -112.85),
|
|
(18, "Gift Refund Credit", 35.00),
|
|
(19, "Fuel Station Purchase", -52.40),
|
|
(20, "Insurance Premium Payment", -95.00),
|
|
(21, "Consulting Fee Deposit", 900.00),
|
|
(22, "Bookstore Purchase", -27.15),
|
|
]
|
|
starting_balance = 12400.00
|
|
running = starting_balance
|
|
chrono_rows = []
|
|
for day, desc, delta in chronological:
|
|
running = round(running + delta, 2)
|
|
chrono_rows.append({
|
|
"date": f"{day:02d} Jan 2027", "description": desc,
|
|
"amount": round(delta, 2), "balance": running,
|
|
})
|
|
newest_first = list(reversed(chrono_rows))
|
|
|
|
columns = [
|
|
# "Transaction Date" is the longest date-field phrase in
|
|
# layout_rules.COLUMN_FIELD_KEYWORDS - its own wide anchor gives
|
|
# the date zone (anchor_x0-5, anchor_x1+15) plenty of room for
|
|
# "DD Mon YYYY" data below it (verified via stringWidth: "03 Jan
|
|
# 2027"'s own last word starts well inside that zone).
|
|
{"key": "date", "header": "Transaction Date", "x": 36, "align": "left"},
|
|
# Description's own zone gets fully overridden by _find_zones'
|
|
# own "widen to span date-end...to money-start" logic - the
|
|
# header label text/width here doesn't matter, only that it
|
|
# resolves the "description" field at all. x=150 - confirmed via
|
|
# a direct _find_zones() debug run that the real date zone's own
|
|
# upper bound lands at 132.13 (not the 127 hand-calculated
|
|
# earlier), which a first draft's x=130 sat inside of - every
|
|
# description's own first word was landing in the DATE zone
|
|
# instead, corrupting both the date text and (for Fixture B's
|
|
# Opening/Closing balance rows specifically) the exact-phrase
|
|
# match those rows depend on. x=150 gives an 18pt margin instead
|
|
# of trusting hand arithmetic a second time.
|
|
{"key": "description", "header": "Description", "x": 150, "align": "left"},
|
|
# Right-aligned at the SAME x as the data below it (near-zero
|
|
# order-preserving-assignment distance - _assign_money_columns'
|
|
# own max_distance=60) and spaced >=15pt apart in x1 from its
|
|
# neighbors (_cluster_by_gap's own gap=15) so the two money
|
|
# columns' zones ((x-80, x+5) each) never overlap: debit zone
|
|
# (290,375), credit zone (390,475) - a clean 15pt gap between them.
|
|
{"key": "debit", "header": "Debit", "x": 370, "align": "right"},
|
|
{"key": "credit", "header": "Credit", "x": 470, "align": "right"},
|
|
{"key": "balance", "header": "Balance", "x": 570, "align": "right"},
|
|
]
|
|
|
|
c = canvas.Canvas(os.path.join(HERE, "Fake-Bank-A-Synthetic.pdf"), pagesize=LETTER)
|
|
rows = []
|
|
for t in newest_first:
|
|
row = {"date": t["date"], "description": t["description"], "balance": _money(t["balance"])}
|
|
if t["amount"] < 0:
|
|
row["debit"] = _money(abs(t["amount"])) # plain positive magnitude - not self-signed
|
|
else:
|
|
row["credit"] = _money(t["amount"])
|
|
rows.append(row)
|
|
_draw_rows_paginated(
|
|
c, rows, columns,
|
|
"Fakebank Financial Group - Business Account Statement",
|
|
["Account holder: Fictional Ventures LLC", "Account number: 0000-SYNTH-0001", "Statement period: 01 Jan 2027 to 31 Jan 2027"],
|
|
)
|
|
c.save()
|
|
|
|
gt_rows = [{"date": t["date"], "description": t["description"], "amount": t["amount"], "balance": t["balance"]} for t in newest_first]
|
|
# HSBC-style: no in-table opening/closing balance line at all - the
|
|
# extractor genuinely returns None/None for this layout (see
|
|
# extract_statement_facts), so the ground truth must match that,
|
|
# not the arbitrary starting_balance this script picked internally.
|
|
_write_ground_truth(os.path.join(HERE, "Fake-Bank-A-Synthetic_ground_truth.xlsx"), gt_rows, None, None)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Fixture B - single signed Amount column, oldest-first, in-table balance.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def build_fixture_b():
|
|
chronological = [
|
|
(2, "Freelance Client Payment", 1800.00),
|
|
(3, "Grocery Store Purchase", -74.20),
|
|
(5, "Electric Utility Payment", -118.65),
|
|
(7, "Streaming Subscription", -12.99),
|
|
(8, "Hardware Store Purchase", -89.40),
|
|
(10, "Consulting Fee Deposit", 650.00),
|
|
(12, "Restaurant - Lunch", -24.50),
|
|
(14, "Mobile Phone Bill", -55.00),
|
|
(16, "Online Retailer Order", -47.85),
|
|
(18, "Fuel Station Purchase", -48.10),
|
|
(19, "Pharmacy Purchase", -19.95),
|
|
(21, "Gift Refund Credit", 25.00),
|
|
(23, "Insurance Premium Payment", -85.00),
|
|
(26, "Payroll Deposit - Oakridge Supply", 2100.00),
|
|
(28, "Bookstore Purchase", -31.60),
|
|
]
|
|
opening_balance = 3250.00
|
|
running = opening_balance
|
|
oldest_first = []
|
|
for day, desc, delta in chronological:
|
|
running = round(running + delta, 2)
|
|
oldest_first.append({
|
|
"date": f"{day:02d} Feb 2027", "description": desc,
|
|
"amount": round(delta, 2), "balance": running,
|
|
})
|
|
closing_balance = running
|
|
|
|
columns = [
|
|
{"key": "date", "header": "Transaction Date", "x": 36, "align": "left"},
|
|
{"key": "description", "header": "Description", "x": 150, "align": "left"},
|
|
# amount zone (340,425), balance zone (480,565) - a 55pt gap,
|
|
# far clear of the 15pt minimum, same verified-widths discipline
|
|
# as Fixture A's own columns.
|
|
{"key": "amount", "header": "Amount", "x": 420, "align": "right"},
|
|
{"key": "balance", "header": "Balance", "x": 560, "align": "right"},
|
|
]
|
|
|
|
c = canvas.Canvas(os.path.join(HERE, "Fake-Bank-B-Synthetic.pdf"), pagesize=LETTER)
|
|
rows = [{"description": "Opening balance", "balance": _money(opening_balance)}]
|
|
for t in oldest_first:
|
|
rows.append({"date": t["date"], "description": t["description"],
|
|
"amount": _money(t["amount"]), "balance": _money(t["balance"])})
|
|
rows.append({"description": "Closing balance", "balance": _money(closing_balance)})
|
|
_draw_rows_paginated(
|
|
c, rows, columns,
|
|
"Oakridge Community Bank - Personal Account Statement",
|
|
["Account holder: Jordan A. Fictional", "Account number: 0000-SYNTH-0002", "Statement period: 01 Feb 2027 to 28 Feb 2027"],
|
|
)
|
|
c.save()
|
|
|
|
gt_rows = [{"date": t["date"], "description": t["description"], "amount": t["amount"], "balance": t["balance"]} for t in oldest_first]
|
|
_write_ground_truth(os.path.join(HERE, "Fake-Bank-B-Synthetic_ground_truth.xlsx"), gt_rows, opening_balance, closing_balance)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
build_fixture_a()
|
|
build_fixture_b()
|
|
print("Wrote Fake-Bank-A-Synthetic.pdf/.xlsx and Fake-Bank-B-Synthetic.pdf/.xlsx")
|