Skip to content

Scrubs bank statements locally & analyse with Groq.

Python

Step 5: generalise to unseen countries; extend local parser

asadullahdotca62f5b11fc4
diff --git a/app/analysis.py b/app/analysis.py
index bb356d8..bc59e30 100644
--- a/app/analysis.py
+++ b/app/analysis.py
@@ -246,6 +246,11 @@ def norm(s: str) -> str:
NUMBER_RE = re.compile(r"\d{1,3}(?:,\d{2,3})+(?:\.\d+)?|\d{1,3}(?:\.\d{3})+(?:,\d{1,2})?|\d+(?:[.,]\d+)?")
+# A number whose thousands are separated by a space. numbers_in() accepts it IN ADDITION to the
+# pieces ("1" "245,60"), so a line such as "ROW 5 100.00" still offers 100.00 as an amount.
+SPACED_NUMBER_RE = re.compile(r"(?<![\d.,])\d{1,3}(?:[  ]\d{3})+(?:[.,]\d{1,2})?(?!\d)")
+
+
def _token_values(tok: str) -> set[float]:
"""The possible values of ONE numeric token: read as 1,234.56 (US/Indian)
and as 1.234,56 (European)."""
@@ -264,6 +269,8 @@ def numbers_in(text: str) -> set[float]:
found = set()
for tok in NUMBER_RE.findall(text):
found |= _token_values(tok)
+ for tok in SPACED_NUMBER_RE.findall(text): # "28 450,00" (South Africa, France): one number
+ found |= _token_values(re.sub(r"[  ]", "", tok))
return found
diff --git a/app/localparse.py b/app/localparse.py
index 0fe81aa..a3161d4 100644
--- a/app/localparse.py
+++ b/app/localparse.py
@@ -20,14 +20,16 @@ from dataclasses import dataclass, field
MONTHS = r"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*"
DATE_RE = re.compile(
- rf"\d{{4}}-\d{{2}}-\d{{2}}(?:[ T]\d{{2}}:\d{{2}}(?::\d{{2}})?)?" # 2026-04-01 08:55:12
+ rf"\d{{4}}[-/]\d{{2}}[-/]\d{{2}}(?:[ T]\d{{2}}:\d{{2}}(?::\d{{2}})?)?" # 2026-04-01 08:55:12 / 2026/04/01
rf"|\d{{1,2}}[ -]{MONTHS}[ -]\d{{4}}" # 01 Apr 2026 / 01-Apr-2026
rf"|\d{{1,2}}[/.]\d{{1,2}}[/.]\d{{2,4}}", re.I) # 04/01/2026, 01.04.2026
AMOUNT_LIKE = re.compile(r"\d[\d.,]*[.,]\d{2}(?!\d)") # a number with 2 decimals
-SYMBOLS = {"C$": "CAD", "A$": "AUD", "US$": "USD", "£": "GBP", "$": "USD", "€": "EUR", "₹": "INR"}
-_SYM = r"C\$|A\$|US\$|[£$€₹]"
-_NUM = r"\d[\d.,]*"
+SYMBOLS = {"C$": "CAD", "A$": "AUD", "US$": "USD", "S$": "SGD", "NZ$": "NZD", "HK$": "HKD", "R": "ZAR",
+ "£": "GBP", "$": "USD", "€": "EUR", "₹": "INR"}
+_SYM = r"C\$|A\$|US\$|S\$|NZ\$|HK\$|[£$€₹]|R(?=\s?\d)"
+# one number: "1 245,60" (space-grouped thousands, South Africa/France) or "1,234.56" / "1.234,56" / "61050.00"
+_NUM = r"\d{1,3}(?:[  ]\d{3})+(?:[.,]\d{1,2})?|\d[\d.,]*"
MONEY_RE = re.compile(rf"^\(?\s*([+\-−–])?\s*(?:({_SYM}|[A-Z]{{3}})\s?)?({_NUM})\s*(?:([A-Z]{{3}}))?\s*\)?$")
SUFFIX_RE = re.compile(rf"(?:\b([A-Z]{{3}})\s?)?({_NUM}[.,]\d{{2}})\s?(Cr|Dr|CR|DR)\b")
@@ -54,6 +56,7 @@ def to_amount(tok: str) -> float | None:
tok = tok.strip()
if not re.fullmatch(_NUM, tok):
return None
+ tok = re.sub(r"[  ]", "", tok) # "1 245,60" -> "1245,60"
last_dot, last_com = tok.rfind("."), tok.rfind(",")
if last_dot >= 0 and last_com >= 0: # both: the later one is the decimal mark
dec = "." if last_dot > last_com else ","
@@ -240,19 +243,68 @@ def _csv_row(line: str, d: str, idx: dict):
return money, dm.group(0), desc
+# ------------------------------------------------------------------ shape 4 and 5: padded text columns
+# 4. "<date> <description> -$154.30 $5,966.20" an explicitly signed amount then the balance, at the end of the line.
+# The sign must not be glued to a word ("CHARGES-26 5.00" is not "-26").
+_TRAIL = re.compile(rf"(?<![\w.])([+\-−–]\s?(?:{_SYM})?\s?(?:{_NUM}))\s+(?:(?:{_SYM}|[A-Z]{{3}})\s?)?(?:{_NUM})\s*$")
+# 5. "<date> <description> 0.00 12,500.00 18,230.40" Debit / Credit / Balance columns, only after a header line
+# that names them; the side that is not 0.00 gives the direction.
+_AMT2 = rf"(?:(?:{_SYM})\s?)?\d[\d,. ]*[.,]\d{{2}}"
+_THREE = re.compile(rf"\s({_AMT2})\s+({_AMT2})\s+(?:(?:{_SYM}|[A-Z]{{3}})\s?)?(?:{_NUM})\s*$")
+
+
+def _trailing_signed(line: str):
+ dm = DATE_RE.match(line)
+ m = _TRAIL.search(line, dm.end())
+ money = parse_money(m.group(1)) if m else None
+ if not money or not money[1]:
+ return None
+ return dm.group(0), line[dm.end():m.start()], money[0], money[1], money[2]
+
+
+def _is_three_column_header(line: str):
+ """For a text header naming debit, credit and balance columns: True if debit comes first, else
+ False; None if the line is not such a header."""
+ low = line.lower()
+ if DATE_RE.search(line) or not all(re.search(rf"\b{w}\b", low) for w in ("debit", "credit", "balance")):
+ return None
+ return low.index("debit") < low.index("credit")
+
+
+def _three_columns(line: str, debit_first: bool):
+ dm = DATE_RE.match(line)
+ m = _THREE.search(line, dm.end())
+ if not m:
+ return None
+ a, b = parse_money(m.group(1)), parse_money(m.group(2))
+ if not a or not b:
+ return None
+ debit, credit = (a[0], b[0]) if debit_first else (b[0], a[0])
+ if debit > 0 and credit == 0:
+ return dm.group(0), line[dm.end():m.start()], debit, "debit", a[2] or b[2]
+ if credit > 0 and debit == 0:
+ return dm.group(0), line[dm.end():m.start()], credit, "credit", a[2] or b[2]
+ return None
+
+
# ------------------------------------------------------------------ the parser
def parse_statement(text: str) -> ParseResult:
out = ParseResult()
header = None # (delimiter, columns) while inside a CSV table
+ three = None # debit-first flag while inside a text Debit/Credit/Balance table
for raw in text.splitlines():
line = raw.strip()
if not line:
- header = None
+ header = three = None
continue
- h = _header_columns(line)
+ h = _header_columns(line) # a delimited header comes first ...
if h and not DATE_RE.search(line):
header = h
continue
+ t3 = _is_three_column_header(line) # ... then a padded-text one
+ if t3 is not None and not h:
+ three = t3
+ continue
parsed = None
if header:
r = _csv_row(line, *header)
@@ -274,6 +326,8 @@ def parse_statement(text: str) -> ParseResult:
if amount is not None:
parsed = (dm.group(0), line[dm.end():sm.start()], amount,
"credit" if sm.group(3).lower() == "cr" else "debit", sm.group(1))
+ if parsed is None and DATE_RE.match(line):
+ parsed = (_three_columns(line, three) if three is not None else None) or _trailing_signed(line)
if parsed:
date, desc, amount, direction, cur = parsed
if amount == 0:
diff --git a/app/scrubber.py b/app/scrubber.py
index 751524b..8a3e413 100644
--- a/app/scrubber.py
+++ b/app/scrubber.py
@@ -127,20 +127,37 @@ def scrub_text(text: str) -> str:
# Other routing identifiers: US routing/ABA, CA transit + institution,
# DE BLZ, MICR, AU BSB. Value must contain at least 3 digits.
- t = _sub(r"\b(routing(?:\s*(?:number|no\.?))?|aba|transit|institution|blz|micr|bsb)"
- r"(\s*[:,#]?\s*)\d[\d -]{1,}\d", r"\1\2<ROUTING_ID>", t, I)
-
- # National IDs introduced by a label: SSN, SIN, Steuer-ID, Aadhaar, ...
+ # Digit groups below are joined by ONE optional space or dash (not "[\d -]+"), so a
+ # value followed by wide column padding ("ACC 5566778899 486.20") cannot swallow
+ # the next column.
+ t = _sub(r"\b(routing(?:\s*(?:number|no\.?))?|aba|transit|institution|blz|micr|bsb|"
+ r"branch\s*code|bank\s*code|clearing\s*(?:number|no\.?))"
+ r"(\s*[:,#]?\s*)\d(?:[ -]?\d){2,}", r"\1\2<ROUTING_ID>", t, I)
+
+ # National IDs introduced by a label: SSN, SIN, Steuer-ID, Aadhaar, Iqama, TFN ...
# "(?:\s+on\s+file)?" allows text like "SSN on file: 078-05-1120".
- t = _sub(r"\b(ssn|sin|nin|tin|tax\s*id|steuer-?id|aadhaa?r|cnic|national\s*id)"
- r"((?:\s+on\s+file)?\s*[:,#]?\s*)\d[\d -]{6,}\d", r"\1\2<NATIONAL_ID>", t, I)
+ t = _sub(r"\b(ssn|sin|nin|tin|tax\s*id|tax\s*file\s*number|tfn|steuer-?id|aadhaa?r|cnic|"
+ r"iqama(?:\s*(?:no\.?|number))?|emirates\s*id|id\s*(?:number|no\.?)|"
+ r"national\s*(?:id|identity)(?:\s*(?:no\.?|number))?)"
+ r"((?:\s+on\s+file)?\s*[:,#]?\s*)\d(?:[ -]?\d){6,}", r"\1\2<NATIONAL_ID>", t, I)
+
+ # Passport number: letters+digits after the label ("Passport No: A1234567").
+ t = _sub(r"\b(passport(?:\s*(?:no\.?|number))?)(\s*[:,#]\s*)(?=[A-Z0-9]*\d)[A-Z0-9]{6,9}\b",
+ r"\1\2<NATIONAL_ID>", t, I)
+
+ # Phone numbers introduced by a label (works for "Mobile: ..." and CSV "Mobile,...").
+ # A label makes the value certain, so local formats with no international prefix are
+ # caught too. The value may hold spaces, dots, dashes, slashes and brackets, never a newline.
+ t = _sub(r"\b(mobile|cell|phone|tel(?:ephone)?|landline|whatsapp|fax|"
+ r"(?:alt(?:ernate)?|home|work|office)(?:\s*(?:mobile|phone|tel))?|contact\s*(?:no\.?|number))"
+ r"((?:\s*(?:no\.?|number))?\s*[#:,]\s*)\+?\d[\d ()./-]{5,}\d", r"\1\2<PHONE>", t, I)
# Account numbers: "A/C No", "Account Number", "ACC", "Kontonummer",
# "Consumer Number", "Customer ID", ... The value must START with a digit,
# so "Account Holder: Bilal" is not touched (names must survive).
- t = _sub(r"(a/c\s*no\.?|acc(?:ount)?(?:\s*(?:no\.?|number|num|#))?|konto(?:nummer)?|"
+ t = _sub(r"(a/c\s*no\.?|acc(?:ount)?(?:\s*(?:no\.?|number|num|#))?|konto(?:nummer)?|nuban|"
r"wallet\s*account\s*number|consumer(?:\s*(?:number|no\.?))?|customer\s*id)"
- r"(\s*[:,#]?\s*)\d[\d -]{3,}\d", r"\1\2<ACCOUNT_ID>", t, I)
+ r"(\s*[:,#]?\s*)\d(?:[ -]?\d){4,}", r"\1\2<ACCOUNT_ID>", t, I)
# Card expiry date: "expires 09/28".
t = _sub(r"\bexpires?\s+\d{2}/\d{2,4}", "expires <CARD_EXPIRY>", t, I)
@@ -187,6 +204,9 @@ def scrub_text(text: str) -> str:
# is NOT the first/last 12 digits of a 16-digit card number.
t = _sub(r"(?<!\d[ -])\b[2-9]\d{3}[ -]\d{4}[ -]\d{4}\b(?![ -]\d)", "<NATIONAL_ID>", t)
t = _sub(r"\b784-?\d{4}-?\d{7}-?\d\b", "<NATIONAL_ID>", t) # UAE Emirates ID: 784-YYYY-NNNNNNN-C
+ t = _sub(r"\b[STFGM]\d{7}[A-Z]\b", "<NATIONAL_ID>", t) # Singapore NRIC/FIN: S1234567D
+ t = _sub(r"\b\d{3}\.\d{3}\.\d{3}-\d{2}\b", "<NATIONAL_ID>", t) # Brazil CPF: 123.456.789-09
+ t = _sub(r"(?<![\d-])(?:19|20)?\d{6}[-+]\d{4}(?![\d-])", "<NATIONAL_ID>", t) # Sweden personnummer: 19850101-1234
# ----------------------------------------------------------------------
# RULE 5: CARD NUMBERS
@@ -195,6 +215,8 @@ def scrub_text(text: str) -> str:
# ----------------------------------------------------------------------
# Partly masked with leading digits visible: "521234******2070"
t = _sub(r"\b\d{4,6}[ -]?[*Xx•]{4,}[ -]?\d{4}\b", "<CARD_NUMBER>", t)
+ # ... and the grouped form "4847 12** **** 3456" (first 6 digits, then masked groups).
+ t = _sub(r"\b\d{4}[ -]?\d{2}[*Xx•]{2}[ -]?[*Xx•]{4}[ -]?\d{4}\b", "<CARD_NUMBER>", t)
# 4 groups of 4 digits ("4111 1111 1111 1111"): <CARD_NUMBER> if Luhn-valid,
# otherwise it is more likely a bank account number.
t = _sub(r"\b(?:\d{4}[ -]){3}\d{4}\b",
@@ -239,15 +261,23 @@ def scrub_text(text: str) -> str:
# International: +92-300-1234567, +44 7700 900123, +1 (512) 555-0148
# The separator is a space, tab, dot or dash but NOT a newline: "+44 7700 900123\n01 Apr 2026"
# must not swallow the next line's date.
- t = _sub(r"(?<![\w.,])\+\d{1,3}(?:[ \t .-]?(?:\(\d{1,5}\)|\d{1,5})){2,5}", phone, t)
- t = _sub(r"(?<![\w.,])\(0\d{3}\)\s?\d{7}\b", "<PHONE>", t) # PK: (0315) 1234567
- t = _sub(r"(?<![\w.,])0\d{3}[ -]?\d{7}\b", "<PHONE>", t) # PK: 0300-1234567
- t = _sub(r"(?<![\w.,])0\d{4}[ ]?\d{6}\b", "<PHONE>", t) # UK: 07700 900123
- t = _sub(r"(?<![\w.,])\(?\d{3}\)?[ .-]\d{3}[ .-]\d{4}\b", "<PHONE>", t) # US/CA: 416-555-0177
- t = _sub(r"(?<![\w.,])04\d{2}[ ]?\d{3}[ ]?\d{3}\b", "<PHONE>", t) # AU mobile: 0412 345 678
- t = _sub(r"(?<![\w.,])\(0\d\)[ ]?\d{4}[ ]?\d{4}\b", "<PHONE>", t) # AU landline: (02) 9374 4000
- t = _sub(r"(?<![\w.,])0[1-9](?:[ .-]?\d{2}){4}\b", "<PHONE>", t) # FR: 01 42 68 53 00
- t = _sub(r"(?<![\w.,])0\d{2,4}[ /-]\d{6,9}\b", "<PHONE>", t) # DE local: 030 12345678
+ # Look-behind "(?<![\w.])(?<!\d,)": not glued to a word or a dot, and not the tail of a
+ # thousands-grouped amount ("1,234"), but a number right after a CSV separator
+ # ("Mobile,0501234567" or ",+966 50 765 4321") is fine.
+ t = _sub(r"(?<![\w.])(?<!\d,)\+\d{1,3}(?:[ \t .-]?(?:\(\d{1,5}\)|\d{1,5})){2,5}", phone, t)
+ t = _sub(r"(?<![\w.])(?<!\d,)\(0\d{3}\)\s?\d{7}\b", "<PHONE>", t) # PK: (0315) 1234567
+ t = _sub(r"(?<![\w.])(?<!\d,)0\d{3}[ -]?\d{7}\b", "<PHONE>", t) # PK: 0300-1234567
+ t = _sub(r"(?<![\w.])(?<!\d,)0\d{4}[ ]?\d{6}\b", "<PHONE>", t) # UK: 07700 900123
+ t = _sub(r"(?<![\w.])(?<!\d,)\(?\d{3}\)?[ .-]\d{3}[ .-]\d{4}\b", "<PHONE>", t) # US/CA: 416-555-0177
+ t = _sub(r"(?<![\w.])(?<!\d,)04\d{2}[ ]?\d{3}[ ]?\d{3}\b", "<PHONE>", t) # AU mobile: 0412 345 678
+ t = _sub(r"(?<![\w.])(?<!\d,)\(0\d\)[ ]?\d{4}[ ]?\d{4}\b", "<PHONE>", t) # AU landline: (02) 9374 4000
+ t = _sub(r"(?<![\w.])(?<!\d,)0\d{3}[ -]\d{3}[ -]\d{3}\b", "<PHONE>", t) # KE/NG/AU style: 0722 987 654
+ t = _sub(r"(?<![\w.])(?<!\d,)0[2-9][ -]\d{4}[ -]\d{4}\b", "<PHONE>", t) # AU landline, no brackets: 02 9374 4000
+ t = _sub(r"(?<![\w.])(?<!\d,)0[2-9][ -]\d{3}[ -]\d{4}\b", "<PHONE>", t) # UAE landline: 04 345 6789
+ t = _sub(r"(?<![\w.])(?<!\d,)05\d[ -]\d{3}[ -]\d{4}\b", "<PHONE>", t) # UAE mobile: 055 987 6543
+ t = _sub(r"(?<![\w.])(?<!\d,)05\d{8}\b", "<PHONE>", t) # SA mobile: 0501234567
+ t = _sub(r"(?<![\w.])(?<!\d,)0[1-9](?:[ .-]?\d{2}){4}\b", "<PHONE>", t) # FR: 01 42 68 53 00
+ t = _sub(r"(?<![\w.])(?<!\d,)0\d{2,4}[ /-]\d{6,9}\b", "<PHONE>", t) # DE local: 030 12345678
# ----------------------------------------------------------------------
# RULE 8: REFERENCE / TRACE / TRANSACTION IDs
@@ -265,7 +295,10 @@ def scrub_text(text: str) -> str:
t = _sub(r"\b(?=[A-Za-z0-9]*\d)(?=[A-Za-z0-9]*[A-Za-z])[A-Za-z0-9]{12,}\b", "<REF_ID>", t)
# Last resort: any run of 7+ plain digits. The guards skip digits that are
# part of an amount ("1,234,567.89" or "12345678.00").
- t = _sub(r"(?<![\d.,])\d{7,}(?![\d]|[.,]\d)", "<REF_ID>", t)
+ # A run of 7+ digits can never be a thousands-grouped number (groups have 3 digits), so
+ # "1234567890,380.00" in a CSV is an ID followed by a column. A decimal comma
+ # ("1234567,89") or point ("1234567.89") still marks an amount and is left alone.
+ t = _sub(r"(?<![\d.])(?<!\d,)\d{7,}(?!\d|\.\d|,\d{1,2}(?!\d))", "<REF_ID>", t)
# ----------------------------------------------------------------------
# RULE 9: IP ADDRESSES (four numbers 0-255 separated by dots)
diff --git a/output/combined_scrubbed.txt b/output/combined_scrubbed.txt
index 460cea8..4d8d5d4 100644
--- a/output/combined_scrubbed.txt
+++ b/output/combined_scrubbed.txt
@@ -56,7 +56,7 @@ Sort Code: <ROUTING_ID> Account Number: <ACCOUNT_ID>
IBAN: <IBAN>
BIC: <SWIFT_BIC>
NI Number: <NATIONAL_ID>
-Phone: <PHONE> / <PHONE>
+Phone: <PHONE>
Email: <EMAIL>
01 Apr 2026 | SALARY NORTHERN GRID LTD REF <REF_ID> | +£2,450.00 | £3,120.44
03 Apr 2026 | TESCO STORES 3421 MANCHESTER GBR | -£54.20 | £3,066.24
diff --git a/tests/fixtures/unseen_countries/_truth.json b/tests/fixtures/unseen_countries/_truth.json
new file mode 100644
index 0000000..1bb969d
--- /dev/null
+++ b/tests/fixtures/unseen_countries/_truth.json
@@ -0,0 +1,179 @@
+{
+ "must_remove": [
+ "784-1988-4567123-5",
+ "+971 50 123 4567",
+ "04 345 6789",
+ "1012345678901",
+ "AE07 0331 2345 6789 0123 456",
+ "GHBKAEAD",
+ "100234567890003",
+ "20260402887766",
+ "5425 2334 3010 9903",
+ "5566778899",
+ "AE460260001234567890123",
+ "884433221100",
+ "7766554433",
+ "+971 55 987 6543",
+ "Villa 14",
+ "Al Barsha",
+ "1012345678",
+ "2345678901",
+ "0501234567",
+ "+966 50 765 4321",
+ "SA03 8000 0000 6080 1016 7519",
+ "King Fahd Road",
+ "556677889900",
+ "4847 12** **** 3456",
+ "0555123456",
+ "SA4420000001234567891234",
+ "Wattle Street",
+ "062-000",
+ "1234 5678",
+ "123 456 782",
+ "0412 345 678",
+ "(02) 9374 4000",
+ "+61 412 345 678",
+ "90017788665",
+ "0433 221 100",
+ "987654321",
+ "8001015009087",
+ "250655",
+ "082 123 4567",
+ "+27 21 555 0199",
+ "Protea Road",
+ "778899001122",
+ "0821234567",
+ "99887766",
+ "S1234567D",
+ "+65 9123 4567",
+ "6234 5678",
+ "123-456-789-0",
+ "Blk 123",
+ "201912345K",
+ "91234567",
+ "20260405AB99",
+ "22134567890",
+ "0123456789",
+ "0803 123 4567",
+ "0987654321",
+ "1234567 LAGOS",
+ "+234 803 123 4567",
+ "0712 345 678",
+ "28123456",
+ "254722345678",
+ "14123456789",
+ "0722 987 654",
+ "012180001234567897",
+ "AARP850101AB3",
+ "123.456.789-09",
+ "85010112345",
+ "19850101-1234",
+ "12345678901",
+ "EG38 0019 0005 0000 0000 2631 8000 2",
+ "PL61 1090 1014 0000 0712 1981 2874",
+ "TR33 0006 1005 1978 6457 8413 26",
+ "X1234567",
+ "+52 55 1234 5678",
+ "9988776655"
+ ],
+ "must_keep": [
+ "Omar Khalid Al Mansoori",
+ "FATIMA AL HASHIMI",
+ "CARREFOUR MALL OF THE EMIRATES",
+ "NETFLIX.COM",
+ "CAREEM RIDE",
+ "TALABAT",
+ "NOON.COM",
+ "12,500.00",
+ "18,230.40",
+ "312.75",
+ "2,000.00",
+ "02/04/2026",
+ "DEWA BILL PAYMENT",
+ "Abdullah Saleh Al Qahtani",
+ "MOHAMMED ALQAHTANI",
+ "SARA ALOTAIBI",
+ "PANDA RETAIL",
+ "HUNGERSTATION",
+ "9500.00",
+ "14210.35",
+ "215.40",
+ "2026-04-01",
+ "JARIR BOOKSTORE",
+ "Jessica Anne Tan",
+ "DANIEL TAN",
+ "MARK ELLIS",
+ "WOOLWORTHS 1234 BONDI",
+ "-$154.30",
+ "+$4,250.00",
+ "$6,120.50",
+ "AGL ENERGY",
+ "UBER",
+ "COLES EXPRESS",
+ "01 Apr 2026",
+ "Thandiwe Nomvula Dlamini",
+ "NOMSA DLAMINI",
+ "WOOLWORTHS CAPE TOWN",
+ "TAKEALOT.COM",
+ "+R 28 450,00",
+ "R 31 220,15",
+ "-R 1 245,60",
+ "DISCOVERY HEALTH",
+ "SNAPSCAN",
+ "PICK N PAY",
+ "01 Apr 2026",
+ "Wei Ming Lim",
+ "NETS FAIRPRICE XTRA TAMPINES",
+ "TAN MEI LING",
+ "7-ELEVEN CHANGI",
+ "SPOTIFY SINGAPORE",
+ "+S$5,200.00",
+ "S$7,310.55",
+ "-S$86.40",
+ "Chinedu Emeka Okafor",
+ "SHOPRITE LEKKI",
+ "ADAEZE OKAFOR",
+ "JUMIA",
+ "450000.00",
+ "512340.75",
+ "23450.00",
+ "Wanjiru Grace Kamau",
+ "JOHN KAMAU",
+ "NAIVAS SUPERMARKET",
+ "MARY WAMBUI",
+ "KPLC PREPAID",
+ "5,000.00",
+ "14,250.50",
+ "1,245.00",
+ "2026-04-02 09:14:22",
+ "Pedro Alvarez Ruiz",
+ "OXXO TIENDA 4412",
+ "MERCADO LIBRE",
+ "-$85.00 MXN",
+ "-$1,299.00 MXN",
+ "7-ELEVEN 1234 SYDNEY",
+ "H&M ONLINE",
+ "MCDONALD'S 33221",
+ "-GBP 7.49",
+ "+$1,234,567.89",
+ "$1,235,500.41",
+ "JPY 1,234,567 TRANSFER",
+ "-JPY 1,234,567",
+ "JPY 9,999,999",
+ "ADOBE.COM",
+ "PIZZA HUT 5 STAR PLAZA STREET FOOD",
+ "CINEMA 3 TICKETS ROAD SHOW",
+ "-PKR 4,500.00",
+ "AMAZON.COM",
+ "4 ITEMS",
+ "$1,180,445.42"
+ ]
+}
\ No newline at end of file
diff --git a/tests/fixtures/unseen_countries/australia_southern_cross_apr2026.txt b/tests/fixtures/unseen_countries/australia_southern_cross_apr2026.txt
new file mode 100644
index 0000000..d930733
--- /dev/null
+++ b/tests/fixtures/unseen_countries/australia_southern_cross_apr2026.txt
@@ -0,0 +1,21 @@
+Southern Cross Bank - Everyday Account Statement
+Account name: Jessica Anne Tan
+Address: Unit 5/22 Wattle Street, Surry Hills NSW 2010
+BSB: 062-000 Account number: 1234 5678
+Tax File Number: 123 456 782
+Mobile: 0412 345 678 Home: (02) 9374 4000
+International: +61 412 345 678
+PayID: 0412 345 678
+Card: Visa Debit xxxx 4321
+
+01 Apr 2026 DIRECT CREDIT ACME LOGISTICS PTY LTD SALARY REF 90017788665 +$4,250.00 $6,120.50
+02 Apr 2026 EFTPOS WOOLWORTHS 1234 BONDI NSW AU -$154.30 $5,966.20
+04 Apr 2026 BPAY BILLER 12345 AGL ENERGY REF 987654321 -$212.45 $5,753.75
+06 Apr 2026 OSKO PAYMENT TO DANIEL TAN PayID [email protected] -$300.00 $5,453.75
+09 Apr 2026 UBER *TRIP SYDNEY AU -$27.80 $5,425.95
+12 Apr 2026 NETFLIX.COM -$16.99 $5,408.96
+15 Apr 2026 COLES EXPRESS SURRY HILLS NSW -$48.20 $5,360.76
+18 Apr 2026 ATM WITHDRAWAL CBD SYDNEY NSW -$200.00 $5,160.76
+22 Apr 2026 OSKO PAYMENT FROM MARK ELLIS PayID 0433 221 100 +$120.00 $5,280.76
+27 Apr 2026 INTEREST PAID +$2.31 $5,283.07
diff --git a/tests/fixtures/unseen_countries/kenya_mpesa_apr2026.txt b/tests/fixtures/unseen_countries/kenya_mpesa_apr2026.txt
new file mode 100644
index 0000000..1e9d7e8
--- /dev/null
+++ b/tests/fixtures/unseen_countries/kenya_mpesa_apr2026.txt
@@ -0,0 +1,11 @@
+M-PESA Statement - April 2026
+Customer Name: Wanjiru Grace Kamau
+Mobile Number: 0712 345 678
+National ID No: 28123456
+
+Receipt No. Completion Time Details Paid In Withdrawn Balance
+SDF1AB23CD 2026-04-02 09:14:22 Funds received from 254722345678 - JOHN KAMAU 5,000.00 14,250.50
+SDF2EF45GH 2026-04-03 18:40:05 Customer Payment to NAIVAS SUPERMARKET - WESTLANDS 1,245.00 13,005.50
+SDF3IJ67KL 2026-04-06 12:01:11 Pay Bill to 888880 KPLC PREPAID Acc. 14123456789 1,000.00 12,005.50
+SDF4MN89OP 2026-04-09 07:30:45 Customer Transfer to 0722 987 654 - MARY WAMBUI 2,500.00 9,505.50
diff --git a/tests/fixtures/unseen_countries/latam_eu_ids_apr2026.txt b/tests/fixtures/unseen_countries/latam_eu_ids_apr2026.txt
new file mode 100644
index 0000000..e682547
--- /dev/null
+++ b/tests/fixtures/unseen_countries/latam_eu_ids_apr2026.txt
@@ -0,0 +1,14 @@
+Customer: Pedro Alvarez Ruiz
+CLABE: 012180001234567897
+RFC: AARP850101AB3
+CPF: 123.456.789-09
+PESEL: 85010112345
+Personnummer: 19850101-1234
+TCKN: 12345678901
+IBAN (EG): EG38 0019 0005 0000 0000 2631 8000 2
+IBAN (PL): PL61 1090 1014 0000 0712 1981 2874
+IBAN (TR): TR33 0006 1005 1978 6457 8413 26
+Passport No: X1234567
+Tel: +52 55 1234 5678
+2026/04/02 OXXO TIENDA 4412 CDMX -$85.00 MXN
+2026/04/03 MERCADO LIBRE ORDEN 9988776655 -$1,299.00 MXN
diff --git a/tests/fixtures/unseen_countries/lookalikes.txt b/tests/fixtures/unseen_countries/lookalikes.txt
new file mode 100644
index 0000000..1932184
--- /dev/null
+++ b/tests/fixtures/unseen_countries/lookalikes.txt
@@ -0,0 +1,9 @@
+12 Apr 2026 7-ELEVEN 1234 SYDNEY NSW AU -$8.50 $1,000.00
+13 Apr 2026 H&M ONLINE ORDER A1B2C3 -$59.99 $940.01
+14 Apr 2026 MCDONALD'S 33221 LONDON -GBP 7.49 GBP 932.52
+15 Apr 2026 LOTTERY PAYOUT +$1,234,567.89 $1,235,500.41
+16 Apr 2026 JPY 1,234,567 TRANSFER TO PARTNER -JPY 1,234,567 JPY 9,999,999
+17 Apr 2026 INVOICE 2026-04 SUBSCRIPTION ADOBE.COM -$54.99 $1,180,445.42
+18 Apr 2026 PIZZA HUT 5 STAR PLAZA STREET FOOD -$22.00 $1,180,423.42
+19 Apr 2026 CINEMA 3 TICKETS ROAD SHOW LAHORE -PKR 4,500.00 PKR 95,500.00
+20 Apr 2026 AMAZON.COM*ABC123DEF 4 ITEMS -$41.20 $1,180,382.22
diff --git a/tests/fixtures/unseen_countries/nigeria_apr2026.csv b/tests/fixtures/unseen_countries/nigeria_apr2026.csv
new file mode 100644
index 0000000..eec0cc9
--- /dev/null
+++ b/tests/fixtures/unseen_countries/nigeria_apr2026.csv
@@ -0,0 +1,12 @@
+Transaction Date;Narration;Debit;Credit;Balance
+Customer: Chinedu Emeka Okafor;;;;
+BVN: 22134567890;;;;
+NUBAN: 0123456789;;;;
+Phone: 0803 123 4567;;;;
+Email: [email protected];;;;
+01-Apr-2026;SALARY PAYMENT BAYELSA LOGISTICS LTD;;450000.00;512340.75
+03-Apr-2026;POS/SHOPRITE LEKKI LAGOS NG;23450.00;;488890.75
+05-Apr-2026;NIP TRANSFER TO ADAEZE OKAFOR 0987654321 GTBank;50000.00;;438890.75
+09-Apr-2026;JUMIA ORDER 1234567 LAGOS;18700.00;;420190.75
+12-Apr-2026;NETFLIX.COM;4400.00;;415790.75
+15-Apr-2026;AIRTIME +234 803 123 4567;2000.00;;413790.75
diff --git a/tests/fixtures/unseen_countries/saudi_wallet_apr2026.csv b/tests/fixtures/unseen_countries/saudi_wallet_apr2026.csv
new file mode 100644
index 0000000..e18a7fb
--- /dev/null
+++ b/tests/fixtures/unseen_countries/saudi_wallet_apr2026.csv
@@ -0,0 +1,19 @@
+Date,Description,Debit,Credit,Balance,Currency
+Customer Name,Abdullah Saleh Al Qahtani,,,,
+National ID,1012345678,,,,
+Iqama No,2345678901,,,,
+Mobile,0501234567,,,,
+Alt Mobile,+966 50 765 4321,,,,
+IBAN,SA03 8000 0000 6080 1016 7519,,,,
+Address,"Building 7, King Fahd Road, Al Olaya District, Riyadh 12211",,,,
+2026-04-01,SALARY CREDIT NORTHERN LOGISTICS CO REF 556677889900,,9500.00,14210.35,SAR
+2026-04-02,MADA POS PANDA RETAIL RIYADH Card 4847 12** **** 3456,215.40,,13994.95,SAR
+2026-04-03,SADAD BILL PAYMENT SEC BILLER 1234567890,380.00,,13614.95,SAR
+2026-04-05,STC PAY TRANSFER TO MOHAMMED ALQAHTANI 0555123456,500.00,,13114.95,SAR
+2026-04-08,HUNGERSTATION ORDER RIYADH,72.00,,13042.95,SAR
+2026-04-10,CAREEM RIDE RIYADH,31.50,,13011.45,SAR
+2026-04-12,ALRAJHI LOCAL TRANSFER TO SARA ALOTAIBI IBAN SA4420000001234567891234,1500.00,,11511.45,SAR
+2026-04-15,NETFLIX.COM,44.99,,11466.46,SAR
+2026-04-19,ATM CASH WITHDRAWAL OLAYA BR,800.00,,10666.46,SAR
+2026-04-24,JARIR BOOKSTORE RIYADH PARK,329.00,,10337.46,SAR
diff --git a/tests/fixtures/unseen_countries/singapore_apr2026.txt b/tests/fixtures/unseen_countries/singapore_apr2026.txt
new file mode 100644
index 0000000..f27bb73
--- /dev/null
+++ b/tests/fixtures/unseen_countries/singapore_apr2026.txt
@@ -0,0 +1,14 @@
+Lion City Bank - Savings Statement (April 2026)
+Name: Wei Ming Lim
+NRIC/FIN: S1234567D
+Mobile: +65 9123 4567 Home: 6234 5678
+Account No. 123-456-789-0
+Address: Blk 123 Ang Mo Kio Avenue 3 #12-34, Singapore 560123
+PayNow UEN: 201912345K
+
+01 Apr 2026 GIRO SALARY BRIGHTWAVE PTE LTD +S$5,200.00 S$7,310.55
+03 Apr 2026 NETS FAIRPRICE XTRA TAMPINES -S$86.40 S$7,224.15
+05 Apr 2026 PAYNOW TO TAN MEI LING 91234567 REF 20260405AB99 -S$150.00 S$7,074.15
+08 Apr 2026 GRAB* 7-ELEVEN CHANGI -S$12.30 S$7,061.85
+11 Apr 2026 SPOTIFY SINGAPORE -S$9.99 S$7,051.86
diff --git a/tests/fixtures/unseen_countries/south_africa_cape_meridian_apr2026.docx b/tests/fixtures/unseen_countries/south_africa_cape_meridian_apr2026.docx
new file mode 100644
index 0000000..8fe0ea0
Binary files /dev/null and b/tests/fixtures/unseen_countries/south_africa_cape_meridian_apr2026.docx differ
diff --git a/tests/fixtures/unseen_countries/uae_gulf_horizon_apr2026.txt b/tests/fixtures/unseen_countries/uae_gulf_horizon_apr2026.txt
new file mode 100644
index 0000000..5cb84c7
--- /dev/null
+++ b/tests/fixtures/unseen_countries/uae_gulf_horizon_apr2026.txt
@@ -0,0 +1,24 @@
+Gulf Horizon Bank PJSC - Statement of Account
+Statement period: 01/04/2026 to 30/04/2026
+Account Holder: Omar Khalid Al Mansoori
+Address: Villa 14, Street 22, Al Barsha 1, Dubai, United Arab Emirates
+Emirates ID: 784-1988-4567123-5
+Mobile: +971 50 123 4567 Landline: 04 345 6789
+Account No: 1012345678901
+IBAN: AE07 0331 2345 6789 0123 456
+SWIFT/BIC: GHBKAEAD
+Customer VAT TRN: 100234567890003
+
+Date Description Debit Credit Balance
+02/04/2026 SALARY TRANSFER DUBAI TECH SOLUTIONS FZ LLC REF 20260402887766 0.00 12,500.00 18,230.40
+03/04/2026 CARREFOUR MALL OF THE EMIRATES DUBAI ARE Card 5425 2334 3010 9903 312.75 0.00 17,917.65
+05/04/2026 DEWA BILL PAYMENT ACC 5566778899 486.20 0.00 17,431.45
+07/04/2026 TALABAT FOOD ORDER DUBAI 64.00 0.00 17,367.45
+09/04/2026 IPI TRANSFER TO FATIMA AL HASHIMI IBAN AE460260001234567890123 2,000.00 0.00 15,367.45
+11/04/2026 NETFLIX.COM LOS GATOS USA 55.00 0.00 15,312.45
+14/04/2026 CAREEM RIDE DUBAI 38.50 0.00 15,273.95
+18/04/2026 ATM WDL ENBD ATM DUBAI MARINA Card ending 9903 TRACE 884433221100 1,000.00 0.00 14,273.95
+21/04/2026 NOON.COM ORDER 7766554433 DUBAI 219.00 0.00 14,054.95
+25/04/2026 WALLET TOPUP +971 55 987 6543 100.00 0.00 13,954.95
+28/04/2026 SALIK TOLL RECHARGE 50.00 0.00 13,904.95
diff --git a/tests/test_hybrid.py b/tests/test_hybrid.py
index 7242e3c..0b84dd4 100644
--- a/tests/test_hybrid.py
+++ b/tests/test_hybrid.py
@@ -251,3 +251,61 @@ def test_cheque_lines_get_no_invented_merchant():
def test_two_stacked_prefixes_are_both_stripped():
assert guess_merchant("POS Paid to IMTIAZ SUPER MARKET, GULSHAN BRANCH KARACHI PK|Visa xxxx2070") == "IMTIAZ SUPER MARKET"
+
+
+# ---------------------------------------------------------------- layouts found with the unseen-country statements
+def test_signed_amount_then_balance_without_pipes():
+ r = parse_statement("02 Apr 2026 EFTPOS WOOLWORTHS 1234 BONDI NSW AU -$154.30 $5,966.20\n"
+ "01 Apr 2026 DIRECT CREDIT ACME PTY LTD SALARY +$4,250.00 $6,120.50\n")
+ assert [(x["amount"], x["direction"], x["currency"]) for x in r.rows] == [
+ (154.3, "debit", "USD"), (4250.0, "credit", "USD")]
+
+
+def test_south_african_rand_with_space_grouped_thousands_and_decimal_comma():
+ r = parse_statement("01 Apr 2026 | SALARY CAPE FRESH FOODS PTY LTD | +R 28 450,00 | R 31 220,15\n"
+ "02 Apr 2026 | POS PURCHASE WOOLWORTHS | -R 1 245,60 | R 29 974,55\n")
+ assert [(x["amount"], x["direction"], x["currency"]) for x in r.rows] == [
+ (28450.0, "credit", "ZAR"), (1245.6, "debit", "ZAR")]
+
+
+def test_singapore_dollar_and_slash_year_first_dates():
+ r = parse_statement("03 Apr 2026 NETS FAIRPRICE XTRA TAMPINES -S$86.40 S$7,224.15\n"
+ "2026/04/02 OXXO TIENDA CDMX -$85.00 $915.00\n")
+ assert [(x["amount"], x["currency"]) for x in r.rows] == [(86.4, "SGD"), (85.0, "USD")]
+
+
+def test_text_debit_credit_balance_columns_use_the_nonzero_side():
+ text = ("Date Description Debit Credit Balance\n"
+ "02/04/2026 SALARY DUBAI TECH FZ LLC 0.00 12,500.00 18,230.40\n"
+ "03/04/2026 CARREFOUR MALL OF THE EMIRATES 312.75 0.00 17,917.65\n")
+ r = parse_statement(text)
+ assert [(x["amount"], x["direction"]) for x in r.rows] == [(12500.0, "credit"), (312.75, "debit")]
+
+
+def test_three_columns_are_only_trusted_after_a_header_that_names_them():
+ r = parse_statement("03/04/2026 CARREFOUR MALL 312.75 0.00 17,917.65\n")
+ assert r.rows == [] and len(r.leftover) == 1
+
+
+def test_a_sign_glued_to_a_word_is_not_an_amount_sign():
+ r = parse_statement("29 Apr 2026 SMS CHARGES-26 5.00 1,000.00\n")
+ assert r.rows == [] # left for the model, not read as -26
+
+
+def test_a_csv_header_with_debit_and_credit_still_wins_over_the_text_header_rule():
+ text = "Date,Description,Debit,Credit,Balance,Currency\n2026-04-02,MADA POS PANDA,215.40,,13994.95,SAR\n"
+ r = parse_statement(text)
+ assert [(x["amount"], x["direction"]) for x in r.rows] == [(215.4, "debit")]
+
+
+def test_verification_accepts_space_grouped_amounts_but_still_rejects_wrong_ones():
+ from collections import Counter
+ line = "01 Apr 2026 | SALARY CAPE FRESH FOODS PTY LTD | +R 28 450,00 | R 31 220,15"
+ assert 28450.0 in A.numbers_in(line) and 31220.15 in A.numbers_in(line)
+ assert 100.0 in A.numbers_in("ROW 5 100.00") # the pieces are still offered
+ ok = [dict(date="01 Apr 2026", description="x", merchant=None, amount=28450.0, direction="credit",
+ currency="ZAR", category="income", evidence="+R 28 450,00")]
+ assert len(A.verify_rows(ok, line, Counter())) == 1
+ bad = [dict(ok[0], amount=28540.0)]
+ stats = Counter()
+ assert A.verify_rows(bad, line, stats) == [] and stats["dropped_amount_not_in_evidence"] == 1
diff --git a/tests/test_unseen.py b/tests/test_unseen.py
new file mode 100644
index 0000000..d625c12
--- /dev/null
+++ b/tests/test_unseen.py
@@ -0,0 +1,99 @@
+"""Generalisation test: statements from countries that are NOT in data/ (UAE, Saudi Arabia, Australia,
+South Africa, Singapore, Nigeria, Kenya, plus an ID-format mix and a file of precision lookalikes).
+
+tests/fixtures/unseen_countries/ holds invented statements (TXT, CSV, DOCX) and _truth.json:
+ must_remove every identifier planted in them (it must NOT appear in the output)
+ must_keep names, merchants, amounts and dates that must survive untouched
+All values are made up; none belongs to a real person. Every defect this folder exposed was
+turned into a rule and stays covered here. See also the focused unit tests below.
+"""
+import json
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+from app.engine import scrub_folder # noqa: E402
+from app.scrubber import scrub_text # noqa: E402
+from app.verifier import verify_clean # noqa: E402
+
+FIXTURES = Path(__file__).resolve().parent / "fixtures" / "unseen_countries"
+TRUTH = json.loads((FIXTURES / "_truth.json").read_text(encoding="utf-8"))
+
+
+def _squash(s: str) -> str:
+ return " ".join(s.split())
+
+
[email protected](scope="module")
+def output(tmp_path_factory):
+ work = tmp_path_factory.mktemp("unseen")
+ for p in FIXTURES.iterdir():
+ if p.name != "_truth.json":
+ (work / p.name).write_bytes(p.read_bytes())
+ return _squash(scrub_folder(str(work)))
+
+
[email protected]("secret", TRUTH["must_remove"])
+def test_planted_identifier_is_removed(output, secret):
+ assert _squash(secret) not in output
+
+
[email protected]("keep", sorted(set(TRUTH["must_keep"])))
+def test_meaning_survives(output, keep):
+ assert _squash(keep) in output
+
+
+def test_every_file_has_a_header_and_the_independent_verifier_agrees(output):
+ assert output.count("---- File:") == len([p for p in FIXTURES.iterdir() if p.name != "_truth.json"])
+ assert verify_clean(output).ok
+
+
+# ---------------------------------------------------------------- focused regressions (one per defect found)
[email protected]("raw, expected", [
+ # CSV "label,value" lines and a phone right after a comma
+ ("Mobile,0501234567", "Mobile,<PHONE>"),
+ ("Alt Mobile,+966 50 765 4321", "Alt Mobile,<PHONE>"),
+ ("Iqama No,2345678901", "Iqama No,<NATIONAL_ID>"),
+ ("Home: 6234 5678", "Home: <PHONE>"),
+ ("Landline: 04 345 6789", "Landline: <PHONE>"),
+ ("Cust,0722 987 654,x", "Cust,<PHONE>,x"),
+ # labels that were missing
+ ("Tax File Number: 123 456 782", "Tax File Number: <NATIONAL_ID>"),
+ ("Branch code: 250655", "Branch code: <ROUTING_ID>"),
+ ("NUBAN: 0123456789", "NUBAN: <ACCOUNT_ID>"),
+ ("Passport No: X1234567", "Passport No: <NATIONAL_ID>"),
+ # fixed-shape IDs
+ ("NRIC/FIN: S1234567D", "NRIC/FIN: <NATIONAL_ID>"),
+ ("CPF: 123.456.789-09", "CPF: <NATIONAL_ID>"),
+ ("Personnummer: 19850101-1234", "Personnummer: <NATIONAL_ID>"),
+ # a card that shows its first six digits
+ ("Card 4847 12** **** 3456 POS", "Card <CARD_NUMBER> POS"),
+ # a long number followed by another CSV column
+ ("SEC BILLER 1234567890,380.00,,13614.95", "SEC BILLER <REF_ID>,380.00,,13614.95"),
+])
+def test_defects_found_on_unseen_countries(raw, expected):
+ assert scrub_text(raw) == expected
+
+
+ # amounts next to an account number must not be eaten (the "ACC 5566778899 486.20" bug)
+ "05/04/2026 DEWA BILL PAYMENT ACC <ACCOUNT_ID> 486.20 0.00 17,431.45",
+ # things that look like identifiers but are not
+ "12 Apr 2026 7-ELEVEN 1234 SYDNEY NSW AU -$8.50 $1,000.00",
+ "15 Apr 2026 LOTTERY PAYOUT +$1,234,567.89 $1,235,500.41",
+ "16 Apr 2026 JPY 1,234,567 TRANSFER TO PARTNER -JPY 1,234,567 JPY 9,999,999",
+ "2026-04-02,MADA POS PANDA RETAIL RIYADH Card xxxx3456,215.40,,13994.95,SAR",
+ "9500.00,14210.35,SAR",
+ "02 Apr 2026 SALARY 1,234.56 2,000.00",
+ "1 000,00 R 29 174,55",
+])
+def test_lookalikes_are_not_changed(line):
+ assert scrub_text(line) == line
+
+
+def test_account_value_stops_at_wide_column_padding():
+ out = scrub_text("DEWA BILL PAYMENT ACC 5566778899 486.20 0.00")
+ assert "486.20" in out and "5566778899" not in out