Compare commits

...

3 Commits

Author SHA1 Message Date
JasonFraser 41c42690ab Document the real-fixture removal and synthetic replacement corpus
Records, in CLAUDE.md's own established voice/discipline, why the real
HSBC/RBC fixtures (and a handful of docs/ files) were stripped from git
history before this repo's first remote push, and how
fixtures/generate_synthetic_fixtures.py replaces measure.py's now-empty
regression corpus with two fully-synthetic statements - what was built,
why, and what running python3 backend/measure.py actually confirmed.
Also updates the stale "Outstanding before Phase 1" checklist bullet
that still described the real fixtures as currently committed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-24 09:08:39 -04:00
JasonFraser 18494a0f19 Add a fully-synthetic fixture corpus for measure.py
Replaces the real HSBC/RBC fixtures stripped from git history (real
account numbers/org names - see "Real fixtures removed from git history")
with two invented bank statements, built from a shared Python generator
(fixtures/generate_synthetic_fixtures.py, reportlab + openpyxl) so the
PDF and its ground-truth .xlsx can never drift apart by a transcription
mistake:

- Fake-Bank-A-Synthetic: split Debit/Credit columns, newest-first order,
  no in-table opening/closing balance (HSBC-style) - debit printed as a
  plain positive magnitude, not self-signed.
- Fake-Bank-B-Synthetic: a single signed Amount column, oldest-first
  order, WITH in-table Opening balance/Closing balance rows (RBC-style).

Both auto-detect cleanly via the real keyword/geometry detector alone -
no layout_quirks, no manual mapping. Verified directly against the real
pipeline (python3 backend/measure.py): both report field_accuracy=1.0,
zero count/balance mismatches. Neither reaches "Verified" in this
environment because the Docling container isn't running here - every
page degrades to pdfplumber-only (engine_agreement=needs_review), the
harness's own already-documented degraded mode, not a fixture defect;
every other check (statement_balance/running_balance/date_sanity/
structure_sanity/page_coverage/narrative_direction) passes cleanly for
both. The three real fixtures (still on disk, gitignored by exact
filename) were re-measured in the same run and are unaffected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-24 09:07:23 -04:00
JasonFraser 96a99543cd Narrow gitignore for real fixtures to exact filenames, not a blanket fixtures/
Clears the way for a synthetic replacement fixture corpus to be tracked -
a blanket fixtures/ ignore would have hidden it too.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-24 08:56:12 -04:00
7 changed files with 581 additions and 2 deletions

10
.gitignore vendored
View File

@ -12,8 +12,14 @@ results/*.json
# measure.py and manual testing, deliberately never committed. Removed
# from git history entirely on 2026-11-24 before this repo was pushed to
# a remote for the first time - see CLAUDE.md's "Real fixtures removed
# from git history" entry.
fixtures/
# from git history" entry. Named individually, not a blanket fixtures/
# ignore, so a later SYNTHETIC replacement fixture can still be tracked.
fixtures/HSBC-USD-Sep2026.pdf
fixtures/HSBC-USD-August2026.pdf
fixtures/HSBC-USD-Sep2026_ground_truth.xlsx
fixtures/HSBC-USD-August2026_ground_truth.xlsx
fixtures/RBC-CAD-Aug26.pdf
fixtures/RBC-CAD-Aug26_ground_truth.xlsx
docs/HSBC-USD-Sep2026.pdf
docs/RBC-CAD-Aug26.pdf
docs/scanned_statement.pdf

View File

@ -5314,6 +5314,83 @@ decision. If that turns out to matter in practice (e.g. the same new bank layout
showing up for two of one bookkeeper's own clients), it's a new, separate feature
request to design later, not something this decision already covers.
**Real fixtures removed from git history, replaced with a synthetic corpus,
2026-11-24 - ahead of this repo's first push to a remote.** Before this repo had
ever been pushed anywhere, a check of what it actually tracks found that
`fixtures/HSBC-USD-Sep2026.pdf`/`HSBC-USD-August2026.pdf`/`RBC-CAD-Aug26.pdf` (plus
their own `_ground_truth.xlsx` siblings) and a handful of `docs/` files
(`docs/HSBC-USD-Sep2026.pdf`, `docs/RBC-CAD-Aug26.pdf`, `docs/scanned_statement.pdf`,
`docs/scanned_statement_2page.pdf`, `docs/scan_test_page-1.png`,
`docs/bank_statement_categorizer/description_rules.csv`) all contain REAL financial
data, not synthetic test material - a real account name ("PLANETERRA INTERNATIONAL
FOUNDATION"), a real account number, and a real Royal Bank of Canada business
account statement, confirmed by actually reading the PDFs' own extracted text
(`pdftotext`), not assumed from the filenames. These had been sitting in this
repo's git history since the very first commits this file documents, entirely
unflagged at the time - this repo's own "no DB, no PII" framing never actually
applied to its own test fixtures.
Fixed in two parts, both completed BEFORE the first push: all of those files were
removed from EVERY commit in git history (not just the latest) via `git-filter-repo
--invert-paths`, confirmed clean afterward (`git log --all -- <path>` returns
nothing for any of them); the real files themselves were then restored to disk from
a backup and re-added to `.gitignore` by EXACT filename (not a blanket `fixtures/`
ignore, which would have hidden a future synthetic replacement fixture too) -
`measure.py` and manual local testing keep working off the real files, they just
never reach the remote.
**This left `backend/measure.py`'s whole regression corpus empty from a fresh
clone** - `fixtures/` had nothing else in it, so removing those three pairs left
nothing committed for `measure.py` to discover at all; a clone on another machine
(or a different environment, like the one that built the fix below) would see zero
fixtures. Fixed the same day with `fixtures/generate_synthetic_fixtures.py`
(reportlab + openpyxl) - two invented bank statements (fake org names, fake account
numbers), each built from one shared Python list of transaction data used to write
BOTH the PDF and its own `_ground_truth.xlsx`, so the two can never drift apart by a
transcription mistake the way a hand-verified real fixture's ground truth could.
Deliberately keeps every description on a single line with its amount on the same
line - no attempt to replicate HSBC's trailing-"Narrative"-label convention or
RBC's leading-wrap convention; that row-grouping complexity is already proven
elsewhere in this file's own history and isn't this corpus's job to re-prove, and
skipping it is what makes the ground truth exactly derivable from the generator's
own data rather than needing a human to re-verify it page by page the way the real
fixtures' own ground truth was built.
Two genuinely different column shapes, still exercising the "bank-agnostic" claim
this harness exists to prove: `Fake-Bank-A-Synthetic` (split Debit/Credit columns,
newest-first order, no in-table opening/closing balance - HSBC-style, debit printed
as a plain positive magnitude rather than self-signed) and `Fake-Bank-B-Synthetic`
(a single signed Amount column, oldest-first order, WITH in-table Opening
balance/Closing balance rows - RBC-style). Column x-positions were tuned against
real `reportlab.pdfbase.pdfmetrics.stringWidth` measurements and a real
`_find_zones()` debug run, not hand-calculated and trusted blind - a first draft's
description column sat close enough to the date zone's own computed upper bound
that every row's description bled its own first word into the date field (and, for
Fixture B specifically, broke the exact-phrase match its Opening/Closing balance
rows depend on) - caught by actually running the real extractor against the
generated PDF before ever treating it as finished, the same discipline this file's
own history already insists on everywhere else.
**Verified, all real:** `python3 backend/measure.py` against the full 5-fixture
corpus (the two new ones alongside the three real, still-local ones) - both new
fixtures report `field_accuracy=1.0`, zero count mismatches, and correct
opening/closing balance matches (`None`/`None` for Fixture A, matching
`extract_statement_facts`' own real behavior for a layout with no in-table balance;
the real printed figures for Fixture B). Neither reaches "Verified" in THIS
environment specifically because the Docling container isn't running here - every
page degrades to pdfplumber-only (`engine_agreement` = `needs_review`), which is
`measure.py`'s own already-documented degraded mode ("Works with or without the
Docling container up... same behavior as the live app"), not a defect in either
fixture - confirmed by running every other check directly and seeing
`statement_balance`/`running_balance`/`date_sanity`/`structure_sanity`/
`page_coverage`/`narrative_direction` all pass cleanly for both. The three real
fixtures were re-measured in the same run and are unaffected (same field accuracy,
same statuses modulo the one expected Docling-unavailability difference: RBC reads
"Needs review" here rather than its documented "Failed", since reproducing that
real page-4 engine MISMATCH needs Docling to actually respond and disagree, not
just be unreachable - HSBC-Aug's own "Failed" is untouched, since that one comes
from a real running-balance break, not engine agreement at all).
## Frontend / UI state (as of 2026-10-13)
**Theme is enterprise-light, not the Bettersight brand default.** `UI_DESIGN_THEME.md`
@ -5610,6 +5687,12 @@ restructure; the behavior itself predates it and is unchanged:
(see below) the same way — all 31 transactions visually confirmed page-by-page,
including the two blank-balance rows and the Cancelled wire around the
`running_balance` flag (also `None`/`None` opening/closing, same reason as Sep).
**These three real fixtures were removed from git history outright on
2026-11-24 and replaced with a fully-synthetic corpus** - see "Real fixtures
removed from git history, replaced with a synthetic corpus" under Key
decisions & lessons. This bullet is kept as the accurate historical record of
what was originally built and verified, not as a description of what
`fixtures/` currently holds in git.
- [x] `git init` this repo — done 2026-10-11, initial commit `16f74f7`.
- [x] Decide whether a `README.md` is wanted — yes; added 2026-10-12. Short: what the
product is, `docker compose up`, project layout, `measure.py` usage, and a pointer

View File

@ -0,0 +1,93 @@
%PDF-1.3
%“Œ‹ž ReportLab Generated PDF document http://www.reportlab.com
1 0 obj
<<
/F1 2 0 R /F2 3 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font
>>
endobj
4 0 obj
<<
/Contents 9 0 R /MediaBox [ 0 0 612 792 ] /Parent 8 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
5 0 obj
<<
/Contents 10 0 R /MediaBox [ 0 0 612 792 ] /Parent 8 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
6 0 obj
<<
/PageMode /UseNone /Pages 8 0 R /Type /Catalog
>>
endobj
7 0 obj
<<
/Author (anonymous) /CreationDate (D:20261124090604+00'00') /Creator (ReportLab PDF Library - www.reportlab.com) /Keywords () /ModDate (D:20261124090604+00'00') /Producer (ReportLab PDF Library - www.reportlab.com)
/Subject (unspecified) /Title (untitled) /Trapped /False
>>
endobj
8 0 obj
<<
/Count 2 /Kids [ 4 0 R 5 0 R ] /Type /Pages
>>
endobj
9 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 852
>>
stream
GasbZ?#Q2d'Sc)R/'d67;9q/_CNiFW[%"WVC=/h_;W9<8_2\r*lG&r72JLn7O[r>9hK-t`m.2,$@.P`$B3kWj;Y[mO5U`Fh5T!slhS?VmU:X1H?7.Xb+%!ois!<%pB2AFKP>ACu16]8i$FnNafu#*eRS$+W<U_ll<?l:hYHs[a>h0u?r<qkf^)DQu.u$oK^)2jA@P6&''jIiUR$r:PPVb7IRB2D1(#7Rq:U@f26eFsKfp!"a)Ji`HpV1XqlV$i/%*)l5`V4erSnk%.-3Jf@R08C]"LS=2q"&@'Amo]2.m;X$(`Z/D3g3RpFU'Eq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4]@eRi?@9NHB$9d/gfGi[n?V5s2V:2C#Z,aHRrm<,c"oU&9>(t!^i%(`CBWNeoc'4IlCuU>p9kGuBfa>l.47*8:cuN7+-ef+_sYJO,=HBBpo==.l&PLcs*>Jrr?%oXm;5S)1H31gCYqYnr+U[jg<]48"XdgT^%f3Gahg>^Zk>'X75;IA5)LX&Z+Z=I$)PPlIO9"r#2>()<8i"MGS$0&HinS)I:5[9aG=/E9\?'qN!Ic/>i99(\ei]bj.d0ih!!Rj3HaatZjgQZk&%n*#9GmJfF(IQ:gc0_]FeKe,.C&(nAEC8gAS8)_kY\M@,ajFL+UkG-S-U#-N3_aUs_!m?L/^QEae\03C+T=DMN$pPK:-ebT=7[0aSF2?uMo!*5h3`DP`=F$CHaB0'2&1kuJb8q'X]2B"Do]+inL(9o<=Fn\rb-G#OmC<5Y4*4<m=A~>endstream
endobj
xref
0 11
0000000000 65535 f
0000000073 00000 n
0000000114 00000 n
0000000221 00000 n
0000000333 00000 n
0000000526 00000 n
0000000720 00000 n
0000000788 00000 n
0000001084 00000 n
0000001149 00000 n
0000002091 00000 n
trailer
<<
/ID
[<95fafa301e428ab1a456739b691e1070><95fafa301e428ab1a456739b691e1070>]
% ReportLab generated PDF document -- digest (http://www.reportlab.com)
/Info 7 0 R
/Root 6 0 R
/Size 11
>>
startxref
3064
%%EOF

Binary file not shown.

View File

@ -0,0 +1,93 @@
%PDF-1.3
%“Œ‹ž ReportLab Generated PDF document http://www.reportlab.com
1 0 obj
<<
/F1 2 0 R /F2 3 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding /Name /F2 /Subtype /Type1 /Type /Font
>>
endobj
4 0 obj
<<
/Contents 9 0 R /MediaBox [ 0 0 612 792 ] /Parent 8 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
5 0 obj
<<
/Contents 10 0 R /MediaBox [ 0 0 612 792 ] /Parent 8 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
6 0 obj
<<
/PageMode /UseNone /Pages 8 0 R /Type /Catalog
>>
endobj
7 0 obj
<<
/Author (anonymous) /CreationDate (D:20261124090604+00'00') /Creator (ReportLab PDF Library - www.reportlab.com) /Keywords () /ModDate (D:20261124090604+00'00') /Producer (ReportLab PDF Library - www.reportlab.com)
/Subject (unspecified) /Title (untitled) /Trapped /False
>>
endobj
8 0 obj
<<
/Count 2 /Kids [ 4 0 R 5 0 R ] /Type /Pages
>>
endobj
9 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 849
>>
stream
Gat%b9lldX&;KZL'mjaY7[8YF7rNA[2q(@a9L97Qb#jYRJFEi3:B#YFQ>#%j9[/M$_n3P,Y')*)_"JuNG?t>%1\eI(5U^/-JM>"b]7ZU>U45p64t"WE(dZC4q\%bf`NrFr-OEjS=ghKk0<c/e)$7=7VQR9Si%iWZ<]BO#Ldm\.2t%pe"keYS(kK&TKi)kO(/=X-hU/JU[aKPT09t2t%@7?$.W89&m+CuH++t[1cu$>XHslgX*e/R\D?G5Ua6bVLm=urp09*!?ecUJgg]5;ML8G$ql@8f&V_'Cd';[)*N;+PaAq[<UT+G8^BW%8S<I9X>=m&9A4,]4(&rL?^kV(,^#,e;f&esk%\eKkF\U;#"j/MZ]iPBoTQWiW$fUR!R3[@H)RrCYR7Mq2h777VP9Lh^'7,l-8,A#1$=,#qjmp<Z>D8s<o4!6OnZ:OIEP37$u^;/4q4E^S\%"9l/CoUa/(HY'NO`93HHme3AJqe!SL>FbC)5>UH?HO$tbY^.3*]nO/LY[f*$CNhBjm]r\7CP^UWI9G=3Z&*T,W;-+r7L$W4@WjLgu5lR`pk$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YrV~>endstream
endobj
xref
0 11
0000000000 65535 f
0000000073 00000 n
0000000114 00000 n
0000000221 00000 n
0000000333 00000 n
0000000526 00000 n
0000000720 00000 n
0000000788 00000 n
0000001084 00000 n
0000001149 00000 n
0000002088 00000 n
trailer
<<
/ID
[<9ccca9e44bb99743addb9285215d9d17><9ccca9e44bb99743addb9285215d9d17>]
% ReportLab generated PDF document -- digest (http://www.reportlab.com)
/Info 7 0 R
/Root 6 0 R
/Size 11
>>
startxref
2858
%%EOF

Binary file not shown.

View File

@ -0,0 +1,304 @@
"""
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")