bettersight-statement-extra.../docs/bank_statement_categorizer/logic.py

420 lines
17 KiB
Python

import os, re
import pdfplumber
import openpyxl
from openpyxl.styles import Font
import common
RULES_PATH = os.path.join(os.path.dirname(__file__), "description_rules.csv")
FONT_NAME = "Arial"
FONT_SIZE = 11
REGULAR_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=False)
BOLD_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=True)
ACCOUNTING_FORMAT = '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)'
RECONCILE_TOLERANCE = 0.01
# RBC Business Account Statement's own column layout (confirmed against
# a real statement with pdfplumber - see _extract_words). Words are
# classified into a column by their own x-position, not by line order,
# since the table has no gridlines and the Balance column in particular
# is only populated on a day's LAST line (see _group_into_transactions).
# Values are right-aligned within each zone, so matching on x1 (the
# word's right edge) is what actually distinguishes "0.60" that's part
# of a fee-breakdown description ("Drs @ 0.60", x1 ~244 - nowhere near
# any zone) from a real column value. These three zones are wide enough
# to hold steady across the whole statement; the Date/Description split
# is NOT (confirmed for real: continuation pages shift their entire
# table ~27pt left of page 1's own margin, so a single fixed threshold
# there misreads "Misc" as date text on every continuation page) - see
# _date_col_max_x, computed fresh per page instead.
DEBIT_ZONE = (300, 400)
CREDIT_ZONE = (405, 500)
BALANCE_ZONE = (540, 600)
# pdfplumber's default word-gap threshold (x_tolerance=3) merges this
# statement's own words together ("Misc"+"Payment" have only a 2pt real
# gap) - confirmed by inspecting page.chars directly. 1.5 splits exactly
# on real word boundaries without over-splitting inside a single word
# (those gaps are consistently 0).
X_TOLERANCE = 1.5
_MONEY_RE = re.compile(r"^-?[\d,]+\.\d{2}$")
def _row_amount(text, x1):
"""None unless text is money-shaped AND positioned inside one of
the three real value columns - see the zone constants above."""
if not _MONEY_RE.match(text):
return None
value = float(text.replace(",", ""))
if DEBIT_ZONE[0] <= x1 <= DEBIT_ZONE[1]:
return "debit", value
if CREDIT_ZONE[0] <= x1 <= CREDIT_ZONE[1]:
return "credit", value
if BALANCE_ZONE[0] <= x1 <= BALANCE_ZONE[1]:
return "balance", value
return None
def _date_col_max_x(words):
"""
The x-position splitting the Date column from the Description
column, derived from THIS page's own "Date"/"Description" header
words (the midpoint between them) - see the module-level comment on
why this can't be a fixed constant. Falls back to 85 (page 1's own
layout) if a page is ever missing its header row entirely.
"""
date_w = next((w for w in words if w["text"] == "Date"), None)
desc_w = next((w for w in words if w["text"] == "Description"), None)
if date_w and desc_w:
return (date_w["x1"] + desc_w["x0"]) / 2
return 85
def _extract_rows(page):
"""
One dict per physical line on this page: {"top", "date", "desc",
"debit", "credit", "balance"}. Words are grouped into lines by their
"top" coordinate (small tolerance - pdfplumber gives highly
consistent values per visual row in this statement), then each
word is bucketed into Date/Description/Debit/Credit/Balance by
position (see _date_col_max_x / _row_amount).
"""
# Some bank-generated PDFs fake bold text by printing it twice at
# the exact same position (confirmed here: a continuation page's
# repeated date label, e.g. "14 Sep" at the top of a day's block
# that spans a page break) - left alone, pdfplumber's word-builder
# interleaves the duplicate characters into garbage ("1144 SSeepp").
# dedupe_chars() is pdfplumber's own fix for exactly this.
page = page.dedupe_chars()
words = page.extract_words(x_tolerance=X_TOLERANCE)
date_col_max_x = _date_col_max_x(words)
lines = {}
for w in words:
key = round(w["top"])
lines.setdefault(key, []).append(w)
rows = []
for top in sorted(lines.keys()):
line_words = sorted(lines[top], key=lambda w: w["x0"])
date_parts, desc_parts = [], []
debit = credit = balance = None
for w in line_words:
amount = _row_amount(w["text"], w["x1"])
if amount:
kind, value = amount
if kind == "debit":
debit = value
elif kind == "credit":
credit = value
else:
balance = value
continue
if w["x1"] <= date_col_max_x:
date_parts.append(w["text"])
else:
desc_parts.append(w["text"])
rows.append({
"top": top,
"date": " ".join(date_parts).strip(),
"desc": " ".join(desc_parts).strip(),
"debit": debit, "credit": credit, "balance": balance,
})
# Everything above the "Date / Description / ..." table header - the
# letterhead and "Account Summary for this Period" block on page 1,
# repeated page furniture on every page - is NOT part of the
# transaction table and must be excluded, or its own numbers (e.g.
# the summary's own "Total deposits & credits (54) + 26,956.19"
# line) get misread as transaction amounts. The header row's own
# text splits across two of our rounded-top buckets here ("Description"
# alone, then "Date ...Cheques & Debits..." one bucket below it) -
# take the LATER of the two as the real cutoff.
header_idx = -1
for i, r in enumerate(rows):
if r["desc"] == "Description" or r["date"] == "Date":
header_idx = i
rows = rows[header_idx + 1:] if header_idx >= 0 else rows
# Drop page furniture below the table too: the "N of M" page-number
# footer (no amount of its own, so left alone it gets silently
# absorbed as a continuation line into the NEXT page's first real
# transaction - see _group_into_transactions) and anything after a
# "Closing balance" row on the statement's last page (e.g. an
# "Account Fees: $58.35" footer line).
cleaned = []
for r in rows:
if re.match(r"^\d+ of \d+$", r["desc"]):
continue
cleaned.append(r)
if r["desc"].strip().lower() == "closing balance" and r["balance"] is not None:
break
return cleaned
def _group_into_transactions(rows):
"""
Walk a statement's rows (already in top-to-bottom order, across all
pages concatenated) and turn them into individual transactions plus
the opening/closing balance.
Date is forward-filled (blank on every row after a day's first
transaction - see the module docstring-level comment on
DATE_COL_MAX_X). A row with no Debit/Credit amount is a continuation
of the NEXT amount-bearing row's description (e.g. "Regular
transaction fee 43 Drs @ 0.60" / "48 Crs @ 0.60 54.60" is one
$54.60 transaction, not two) - text accumulates across consecutive
amount-less rows and the transaction completes the moment a row
with a real Debit or Credit is reached. The header row ("Date
Description...", repeated on every page) and blank/noise rows are
skipped by virtue of having no date, no amount, and description
text that never matches a real transaction shape - harmless no-ops
since they contribute nothing to accumulate.
Returns (opening_balance, closing_balance, transactions) where each
transaction is {"date", "description", "amount"} - amount signed
(credit positive, debit negative).
"""
opening_balance = closing_balance = None
transactions = []
pending_desc = []
last_date = ""
for row in rows:
if row["date"]:
last_date = row["date"]
desc = row["desc"].strip()
norm = desc.lower()
if norm == "opening balance" and row["balance"] is not None:
opening_balance = row["balance"]
continue
if norm == "closing balance" and row["balance"] is not None:
closing_balance = row["balance"]
continue
if norm in ("date description", "description") or desc == "":
continue
if row["debit"] is None and row["credit"] is None:
# Continuation line - no amount yet, keep accumulating.
if desc:
pending_desc.append(desc)
continue
full_desc = " ".join(pending_desc + [desc]).strip()
pending_desc = []
amount = row["credit"] if row["credit"] is not None else -row["debit"]
transactions.append({"date": last_date, "description": full_desc, "amount": round(amount, 2)})
return opening_balance, closing_balance, transactions
_SUMMARY_RE = re.compile(
r"Total (deposits & credits|cheques & debits)\s*\((\d+)\)\s*[+-]\s*([\d,]+\.\d{2})",
)
def _extract_summary_totals(full_text):
"""
The statement's own "Account Summary for this Period" block states
its transaction counts and totals directly (e.g. "Total deposits &
credits (54) + 26,956.19") - an independent cross-check on the
parsed transaction list, same idea as app/tools/eib/logic.py's
extract_balances_from_markdown pulling a stated total to verify
against. Returns {"credit_count", "credit_total", "debit_count",
"debit_total"} - any key missing if that line wasn't found.
"""
result = {}
for m in _SUMMARY_RE.finditer(full_text):
kind = "credit" if "deposits" in m.group(1) else "debit"
result[f"{kind}_count"] = int(m.group(2))
result[f"{kind}_total"] = float(m.group(3).replace(",", ""))
return result
def parse_rbc_statement(pdf_path):
"""
Parse an RBC Business Account Statement PDF (text-based, not
scanned - confirmed real statements extract cleanly with
pdfplumber) into individual transactions plus opening/closing
balance. See _extract_rows/_group_into_transactions for the actual
column-position and multi-line-continuation handling this requires.
Returns {"opening_balance", "closing_balance", "transactions":
[{"date","description","amount"}...], "summary_totals": {...}}.
Raises ValueError if this doesn't look like a parseable RBC
statement (no opening/closing balance found at all).
"""
all_rows = []
full_text_parts = []
with pdfplumber.open(pdf_path) as pdf:
for page in pdf.pages:
all_rows.extend(_extract_rows(page))
full_text_parts.append(page.extract_text(x_tolerance=X_TOLERANCE) or "")
opening_balance, closing_balance, transactions = _group_into_transactions(all_rows)
if opening_balance is None or closing_balance is None:
raise ValueError(
"Could not find an Opening balance and Closing balance row - this doesn't look like "
"a parseable RBC Business Account Statement."
)
return {
"opening_balance": opening_balance,
"closing_balance": closing_balance,
"transactions": transactions,
"summary_totals": _extract_summary_totals("\n".join(full_text_parts)),
}
# ── Categorization rules (description_rules.csv) ───────────────────────────
# Read/write/match mechanics live in app/common.py - shared with
# app/tools/hsbc_statement_categorizer/, the second tool to need this
# exact shape (see common.py's own comment on the "lift once a second
# tool duplicates something" trigger). Each tool keeps its own
# description_rules.csv path, passed in below.
def list_rules():
return common.load_description_rules(RULES_PATH)
def upsert_rules(entries):
common.upsert_description_rules(RULES_PATH, entries)
def delete_rule(pattern):
common.delete_description_rule(RULES_PATH, pattern)
def match_rule(description, rules):
return common.match_description_rule(description, rules)
def categorize(description, rules):
"""Just the accounting_description half of match_rule() - kept for
callers that don't need to know which pattern actually matched."""
rule = match_rule(description, rules)
return rule["accounting_description"] if rule else None
# ── Aggregation + reconciliation ────────────────────────────────────────────
def build_categorized_summary(parsed, rules):
"""
Categorize every parsed transaction, group by accounting_description
and sum - this is what makes two differently-matched transactions
that happen to share similar raw text (see categorize) land in
separate output rows automatically, with no special "keep separate"
case needed anywhere in this function.
Returns {"rows": [{"bank_description","accounting_description",
"amount"}...] (one per distinct accounting_description, sorted by
first appearance in the statement), "unmapped": [{"description",
"amount", "count"}...] (grouped by distinct raw description text -
see routes.py's review gate), "opening_balance", "closing_balance",
"reconciled", "credit_total", "debit_total", "summary_totals"}.
"""
opening = parsed["opening_balance"]
closing = parsed["closing_balance"]
transactions = parsed["transactions"]
groups = {} # accounting_description -> {"amount": float, "bank_descriptions": set}
unmapped = {} # raw description -> {"amount": total, "count": n}
credit_total = debit_total = 0.0
for t in transactions:
if t["amount"] >= 0:
credit_total += t["amount"]
else:
debit_total += t["amount"]
rule = match_rule(t["description"], rules)
if rule is None:
entry = unmapped.setdefault(t["description"], {"description": t["description"], "amount": 0.0, "count": 0})
entry["amount"] = round(entry["amount"] + t["amount"], 2)
entry["count"] += 1
continue
target = rule["accounting_description"]
entry = groups.setdefault(target, {"amount": 0.0, "bank_descriptions": [], "first_seen": len(groups)})
entry["amount"] = round(entry["amount"] + t["amount"], 2)
# The matched PATTERN, not the raw description - a dozen "Misc
# Payment MC FEE..." lines with different trailing reference
# numbers all collapse to one clean "Misc Payment MC FEE" label
# instead of a long slash-joined wall of near-duplicate text.
if rule["pattern"] not in entry["bank_descriptions"]:
entry["bank_descriptions"].append(rule["pattern"])
rows = [
{
"bank_description": " / ".join(v["bank_descriptions"]),
"accounting_description": target,
"amount": v["amount"],
}
for target, v in sorted(groups.items(), key=lambda kv: kv[1]["first_seen"])
]
net = round(credit_total + debit_total, 2)
reconciled = bool(abs(opening + net - closing) < RECONCILE_TOLERANCE) if not unmapped else False
return {
"rows": rows,
"unmapped": sorted(unmapped.values(), key=lambda u: u["description"]),
"opening_balance": opening,
"closing_balance": closing,
"reconciled": reconciled,
"credit_total": round(credit_total, 2),
"debit_total": round(debit_total, 2),
"summary_totals": parsed["summary_totals"],
}
# ── Output workbook ──────────────────────────────────────────────────────
def _write_cell(ws, row, col, value, bold=False, number_format=None):
c = ws.cell(row=row, column=col, value=value)
c.font = BOLD_FONT if bold else REGULAR_FONT
if number_format:
c.number_format = number_format
return c
def write_output_workbook(summary, output_path, title="Bank Statement Categorizer"):
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Categorized"
for col, width in zip("ABC", (46, 56, 16)):
ws.column_dimensions[col].width = width
_write_cell(ws, 1, 1, title, bold=True)
row = 3
for col, label in enumerate(["Bank Description", "Accounting Description", "Amount"], start=1):
_write_cell(ws, row, col, label, bold=True)
row += 1
_write_cell(ws, row, 1, "Opening balance", bold=True)
_write_cell(ws, row, 2, "Opening balance", bold=True)
_write_cell(ws, row, 3, summary["opening_balance"], bold=True, number_format=ACCOUNTING_FORMAT)
row += 1
for r in summary["rows"]:
_write_cell(ws, row, 1, r["bank_description"])
_write_cell(ws, row, 2, r["accounting_description"])
_write_cell(ws, row, 3, r["amount"], number_format=ACCOUNTING_FORMAT)
row += 1
_write_cell(ws, row, 1, "Closing balance", bold=True)
_write_cell(ws, row, 2, "Closing balance", bold=True)
_write_cell(ws, row, 3, summary["closing_balance"], bold=True, number_format=ACCOUNTING_FORMAT)
row += 2
_write_cell(ws, row, 1, "Reconciled" if summary["reconciled"] else "NOT RECONCILED", bold=True)
row += 1
_write_cell(ws, row, 1, "Opening + categorized net")
_write_cell(ws, row, 3, round(summary["opening_balance"] + summary["credit_total"] + summary["debit_total"], 2), number_format=ACCOUNTING_FORMAT)
row += 1
_write_cell(ws, row, 1, "Closing balance (per statement)")
_write_cell(ws, row, 3, summary["closing_balance"], number_format=ACCOUNTING_FORMAT)
wb.save(output_path)