Scrubs bank statements locally & analyse with Groq.
Python
Steps1 - 4 updated
asadullahdot7d25aa3ecd65
diff --git a/app/engine.py b/app/engine.pyindex 55a19fd..388e070 100644--- a/app/engine.py+++ b/app/engine.py@@ -1,17 +1,93 @@-"""Folder in -> ONE combined scrubbed string out. No hardcoded filenames."""+"""Step 4: the engine. FOLDER IN -> ONE COMBINED SCRUBBED STRING OUT.++ scrub_folder("data") ->++ ---- File: crescent_bank_statement_apr2026.pdf ----+ <scrubbed text of the PDF>++ ---- File: paypal_activity_apr2026.txt ----+ <scrubbed text of the TXT>+ ...++This module is the only thing the rest of the project needs to call:+ readers.py turns each file into raw text (contains PII)+ scrubber.py replaces identifiers with placeholders (removes PII)+ engine.py runs both on every file and joins the results++No file names are hard-coded. Every file in the folder is processed, in+alphabetical order so the output is the same every run.+"""+import sysfrom pathlib import Path-from readers import read_file-from scrubber import scrub_text++from app.readers import read_file+from app.scrubber import scrub_text++# The project root is the folder that contains app/. Default paths are built+# from it so the script works no matter which folder your terminal is in.+PROJECT_ROOT = Path(__file__).resolve().parent.parent+DEFAULT_DATA_DIR = PROJECT_ROOT / "data"+DEFAULT_OUTPUT_FILE = PROJECT_ROOT / "output" / "combined_scrubbed.txt"def scrub_folder(folder: str | Path) -> str:+ """Scrub every file in `folder` and return ONE combined string.++ A file that cannot be read (unsupported type, corrupt, scanned PDF) does+ NOT stop the run: it appears in the output as a "[SKIPPED: reason]" line+ so one bad file never loses the rest of the statements.+ """folder = Path(folder)- parts = []- for path in sorted(p for p in folder.iterdir() if p.is_file() and not p.name.startswith(".")):++ # Fail early with a message that shows exactly where we looked.+ if not folder.is_dir():+ raise NotADirectoryError(+ f"Data folder not found: {folder.resolve()}\n"+ f"Create it and put your statements inside, or pass another folder."+ )++ parts = [] # one block of text per file++ # sorted() -> deterministic order. is_file() -> ignore sub-folders.+ # not startswith(".") -> ignore hidden files such as .DS_Store or .gitkeep.+ files = sorted(p for p in folder.iterdir()+ if p.is_file() and not p.name.startswith("."))++ for path in files:header = f"---- File: {path.name} ----"try:- body = scrub_text(read_file(path))- except Exception as e: # one bad file must not kill the run+ raw_text = read_file(path) # readers.py: file -> raw text (has PII)+ body = scrub_text(raw_text) # scrubber.py: raw text -> safe text+ except Exception as e:+ # Report only the error type/message, never the file's contents.body = f"[SKIPPED: {type(e).__name__}: {e}]"parts.append(f"{header}\n{body.strip()}\n")++ # A blank line between files keeps the combined string easy to read.return "\n".join(parts)+++# --------------------------------------------------------------------------+# Command-line use (run from anywhere):+# python -m app.engine data/ -> output/combined_scrubbed.txt+# python -m app.engine my_folder a different input folder+# python -m app.engine my_folder result.txt a different output file too+# --------------------------------------------------------------------------+if __name__ == "__main__":+ # Windows terminals often use a legacy encoding (cp1252) that cannot print+ # symbols like the rupee sign or other currency signs. Force UTF-8 so+ # print() never crashes. (Files are always written as UTF-8 below.)+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")++ folder = Path(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_DATA_DIR+ out_file = Path(sys.argv[2]) if len(sys.argv) > 2 else DEFAULT_OUTPUT_FILE++ try:+ result = scrub_folder(folder)+ except NotADirectoryError as e:+ sys.exit(f"ERROR: {e}") # clean message instead of a long traceback++ out_file.parent.mkdir(parents=True, exist_ok=True) # create output/ if missing+ out_file.write_text(result, encoding="utf-8")+ print(result)+ print(f"\n[saved to {out_file.resolve()}]")diff --git a/app/readers.py b/app/readers.pyindex 80d6fab..0cc7194 100644--- a/app/readers.py+++ b/app/readers.py@@ -1,22 +1,95 @@-"""Step 1: file readers. Every reader takes a Path and returns raw text.+"""Step 1: file readers.-New formats = write one function and register it in READERS.-Nothing here ever touches the network.+Every reader takes a file Path and returns the file's contents as ONE plain+text string. The text is RAW (it still contains PII), so it must only ever be+passed straight into the scrubber and never saved, logged or sent anywhere.++Which reader is used is decided by the file extension (see READERS at the+bottom). To support a new format: write one read_xxx() function and add it+to READERS. Nothing in this file touches the network."""+import csvfrom pathlib import Path+import pandas as pd++# Encodings to try, in order. Bank exports are usually UTF-8, but older+# Windows exports are often cp1252. latin-1 can decode ANY byte sequence, so+# it is the last resort and guarantees we never crash on encoding.+ENCODINGS = ("utf-8-sig", "cp1252", "latin-1")++# --------------------------------------------------------------------------+# TXT -> plain open()+# --------------------------------------------------------------------------def read_txt(path: Path) -> str:- raw = path.read_bytes()- for enc in ("utf-8-sig", "cp1252", "latin-1"): # latin-1 never fails+ """Read a plain text file with open(), trying several encodings."""+ for enc in ENCODINGS:try:- return raw.decode(enc)+ # newline=None lets Python normalise \r\n (Windows) to \n+ with open(path, "r", encoding=enc) as f:+ return f.read()except UnicodeDecodeError:- continue- return raw.decode("utf-8", errors="replace")--+ continue # wrong guess, try the next encoding+ # Unreachable in practice (latin-1 never fails) but keeps the function total.+ with open(path, "r", encoding="utf-8", errors="replace") as f:+ return f.read()+++# --------------------------------------------------------------------------+# CSV / TSV -> pandas DataFrame+# --------------------------------------------------------------------------+def _dataframe_to_text(df: pd.DataFrame) -> str:+ """Turn a DataFrame back into CSV-style text, one line per row."""+ # header=False because we read with header=None: the first row of the file+ # is just another row, so a real header line is output like any other line.+ text = df.to_csv(index=False, header=False, lineterminator="\n")+ # Short rows get padded with empty cells ("a,b,,,"); drop those trailing commas.+ return "\n".join(line.rstrip(",") for line in text.splitlines())+++def read_csv(path: Path) -> str:+ """Read a CSV/TSV with pandas and return it as text.++ Settings that matter for a *scrubber*:+ dtype=str keep every cell exactly as written. Without it pandas+ turns "0300123" into the number 300123 (leading zero+ lost) and "61050.00" into a float, which would break+ the regex rules.+ keep_default_na=False don't turn "NA"/"null"/"" into NaN (that would+ silently delete cells).+ header=None never treat the first row as a header; every line of+ the file is kept as data.+ sep=None + python let pandas sniff the delimiter (comma, semicolon, tab).+ """+ last_error = None+ for enc in ENCODINGS:+ try:+ try:+ df = pd.read_csv(path, header=None, dtype=str, keep_default_na=False,+ sep=None, engine="python", encoding=enc,+ skip_blank_lines=True)+ except pd.errors.ParserError:+ # Rows with different numbers of columns (e.g. a few metadata+ # lines above the table) make pandas fail. Find the widest row+ # and force that many columns so NO row is dropped.+ with open(path, newline="", encoding=enc) as f:+ width = max((len(r) for r in csv.reader(f)), default=1)+ df = pd.read_csv(path, header=None, dtype=str, keep_default_na=False,+ names=range(width), engine="python", encoding=enc,+ skip_blank_lines=True)+ return _dataframe_to_text(df)+ except UnicodeDecodeError as e:+ last_error = e # try the next encoding+ raise ValueError(f"could not decode CSV: {last_error}")+++# --------------------------------------------------------------------------+# PDF -> pdfplumber+# --------------------------------------------------------------------------def read_pdf(path: Path) -> str:+ """Extract the text layer of every page. Scanned PDFs (images) have no+ text layer; we raise a clear error instead of returning an empty string."""import pdfplumberpages = []@@ -29,57 +102,72 @@ def read_pdf(path: Path) -> str:return text+# --------------------------------------------------------------------------+# DOCX -> python-docx+# --------------------------------------------------------------------------def read_docx(path: Path) -> str:- """Paragraphs AND tables in document order, plus headers/footers."""+ """Return paragraphs AND tables in document order, plus headers/footers.++ python-docx's d.paragraphs ignores tables, and bank statements are mostly+ tables, so we walk the document body element by element instead.+ """import docxfrom docx.oxml.ns import qnd = docx.Document(path)lines = []- def para_text(el):- return "".join(t.text or "" for t in el.iter(qn("w:t")))+ def text_of(element):+ # A Word element stores its text in <w:t> tags; join them all.+ return "".join(t.text or "" for t in element.iter(qn("w:t")))- for section in d.sections: # headers/footers often hold account numbers+ # Headers/footers often carry account numbers, so include them.+ for section in d.sections:for part in (section.header, section.footer):for p in part.paragraphs:if p.text.strip():lines.append(p.text)for child in d.element.body.iterchildren():- if child.tag == qn("w:p"):- t = para_text(child)+ if child.tag == qn("w:p"): # normal paragraph+ t = text_of(child)if t.strip():lines.append(t)- elif child.tag == qn("w:tbl"):+ elif child.tag == qn("w:tbl"): # table: one line per rowfor tr in child.iter(qn("w:tr")):- cells = [para_text(tc).strip() for tc in tr.iter(qn("w:tc"))]+ cells = [text_of(tc).strip() for tc in tr.iter(qn("w:tc"))]lines.append(" | ".join(cells))return "\n".join(lines)-# def read_xlsx(path: Path) -> str:-# import openpyxl--# wb = openpyxl.load_workbook(path, data_only=True, read_only=True)-# lines = []-# for ws in wb.worksheets:-# lines.append(f"[Sheet: {ws.title}]")-# for row in ws.iter_rows(values_only=True):-# if any(c is not None for c in row):-# lines.append(", ".join("" if c is None else str(c) for c in row))-# return "\n".join(lines)+# --------------------------------------------------------------------------+# XLSX -> pandas DataFrame (one block per sheet)+# --------------------------------------------------------------------------+def read_excel(path: Path) -> str:+ """Read every sheet of an Excel workbook with pandas."""+ # sheet_name=None -> dict of {sheet name: DataFrame}. header=None and+ # dtype=str for the same reasons as read_csv.+ sheets = pd.read_excel(path, sheet_name=None, header=None, dtype=str)+ blocks = []+ for name, df in sheets.items():+ blocks.append(f"[Sheet: {name}]\n{_dataframe_to_text(df.fillna(''))}")+ return "\n".join(blocks)+# --------------------------------------------------------------------------+# Dispatch table: file extension -> reader function+# --------------------------------------------------------------------------READERS = {- ".txt": read_txt, ".csv": read_txt, ".tsv": read_txt, ".md": read_txt,+ ".txt": read_txt, ".md": read_txt, ".log": read_txt,+ ".csv": read_csv, ".tsv": read_csv,".pdf": read_pdf,".docx": read_docx,- # ".xlsx": read_xlsx, ".xlsm": read_xlsx,+ ".xlsx": read_excel, ".xlsm": read_excel,}def read_file(path: Path) -> str:+ """Pick the right reader from the extension (case-insensitive)."""reader = READERS.get(path.suffix.lower())if reader is None:raise ValueError(f"unsupported file type: {path.suffix or '(none)'}")diff --git a/app/scrubber.py b/app/scrubber.pyindex 3e3aa57..1799a76 100644--- a/app/scrubber.py+++ b/app/scrubber.py@@ -1,123 +1,266 @@-"""Step 2: local PII scrubbing engine (regex + validators, no network).+"""Step 2: the PII scrubbing engine.-Order matters: labelled fields -> emails/handles -> IBAN -> national IDs ->-cards -> bank codes -> phones -> reference/long IDs -> IP.-Anything we KEEP (names, merchants, dates, amounts, last-4) is never matched.+Runs 100% locally: plain regular expressions plus a few validators. No+network, no model, no external service.++HOW IT WORKS+ scrub_text(raw_text) applies a long list of rules, one after another.+ Each rule finds one kind of identifier and replaces it with a placeholder+ such as <IBAN> or <PHONE>.++WHY THE ORDER OF THE RULES MATTERS+ Rules run from MOST specific to MOST generic. If a generic rule ran first+ it would grab pieces of things a specific rule understands better.+ Example: the long-number rule would swallow the digits of a phone number+ before the phone rule could label it <PHONE>.++ 1. labelled fields ("Address: ...", "Account No: ...")+ 2. emails / payment handles+ 3. IBANs+ 4. national IDs (CNIC, SSN, UK NI, PAN, Aadhaar, Emirates ID)+ 5. card numbers+ 6. bank codes (IFSC, SWIFT/BIC)+ 7. phone numbers+ 8. reference IDs and long numbers+ 9. IP addresses++WHAT IS DELIBERATELY *NOT* TOUCHED (it carries analytical value)+ person names, merchant names (even "Netflix.com"), dates, times,+ amounts, balances, currencies, masked last-4 digits (xxxx8821).+ There is intentionally NO "remove URLs/domains" rule, because that would+ destroy merchants like Netflix.com or Daraz.pk."""import re+# Shorthand: make a pattern case-insensitive ("Address" == "ADDRESS").I = re.IGNORECASE-# ---------- helpers ----------++# ==========================================================================+# LOOKUP TABLES AND HELPER FUNCTIONS+# ==========================================================================++# Total length of a valid IBAN per country. Used ONLY to repair IBANs that a+# PDF wrapped onto two lines (see _join_wrapped_ibans).IBAN_LEN = {"PK": 24, "GB": 22, "DE": 22, "FR": 27, "ES": 24, "IT": 27, "NL": 18,"AE": 23, "SA": 24, "IE": 22, "BE": 16, "CH": 21, "TR": 26}++# Real ISO country codes. Lets us tell the SWIFT code "SCBLPKKA" (letters 5-6+# = "PK", a country) from an ordinary English word such as "RESOLVED".ISO_CC = set("""AD AE AF AL AM AR AT AU AZ BA BD BE BG BH BR BY CA CH CL CN CO CZ DE DK DZ EE EG ES FI FRGB GE GR HK HR HU ID IE IL IN IQ IR IS IT JO JP KE KR KW KZ LB LK LT LU LV MA MD MT MX MY NG NL NO NP NZOM PE PH PK PL PT QA RO RS RU SA SE SG SI SK TH TN TR TW UA US UY UZ VN ZA""".split())def luhn_ok(digits: str) -> bool:- s, alt = 0, False- for ch in reversed(digits):+ """Luhn checksum: every real credit/debit card number passes it.++ Used so we only call a long digit string a <CARD_NUMBER> when it is+ mathematically a valid card number, not just any 16 digits.+ """+ total, double = 0, False+ for ch in reversed(digits): # walk from the last digit backwardsd = int(ch)- if alt:- d = d * 2 - 9 if d * 2 > 9 else d * 2- s += d- alt = not alt- return s % 10 == 0+ if double: # double every second digit...+ d = d * 2 - 9 if d * 2 > 9 else d * 2 # ...subtracting 9 if > 9+ total += d+ double = not double+ return total % 10 == 0def _join_wrapped_ibans(text: str) -> str:- """PDF layout can wrap the tail of an IBAN onto the next line ('...567\\n02')."""+ """Re-attach an IBAN whose last digits wrapped onto the next line.++ PDFs sometimes break a long IBAN across two lines, e.g.+ IBAN: PK36SCBL00000011234567+ 02+ Neither half looks like an IBAN alone, so it would leak. We join the two+ parts, but ONLY if the combined length equals the IBAN length for that+ country, so unrelated numbers on the next line are never swallowed.+ """def fix(m):head, tail = m.group(1), m.group(2)want = IBAN_LEN.get(head[:2].upper())+ # join only if the result is exactly a full-length IBANreturn head + tail if want and len(head) + len(tail) == want else m.group(0)++ # group 1: IBAN start (2 letters, 2 digits, more chars) group 2: 1-4 digits+ # sitting alone at the start of the next linereturn re.sub(r"\b([A-Z]{2}\d{2}[A-Z0-9]{8,26})[ \t]*\n[ \t]*(\d{1,4})\b", fix, text)def _sub(pattern, repl, text, flags=0):+ """Tiny wrapper around re.sub so every rule below fits on a few lines."""return re.sub(pattern, repl, text, flags=flags)-# ---------- rules ----------+# ==========================================================================+# THE SCRUBBER+# ==========================================================================def scrub_text(text: str) -> str:+ """Return `text` with every identifier replaced by a <PLACEHOLDER>."""++ # Step 0: repair wrapped IBANs first so rule 3 can see them whole.t = _join_wrapped_ibans(text)- # 1. Labelled fields (label kept, value removed) -------------------------+ # ----------------------------------------------------------------------+ # RULE 1: LABELLED FIELDS+ # The label tells us what the value is, so we can remove values that have+ # no recognisable shape (an address) or an unusual shape (an account+ # number). The label itself is KEPT so the text still reads naturally:+ # "Customer Address: House 5, Karachi" -> "Customer Address: <ADDRESS>"+ # \1 and \2 in the replacement re-insert the label and its separator.+ # ----------------------------------------------------------------------++ # Addresses: remove the whole rest of the line after the label.t = _sub(r"((?:customer\s+|billing\s+|home\s+|mailing\s+)?address|anschrift|adresse)"r"(\s*[:,]\s*)[^\n]+", r"\1\2<ADDRESS>", t, I)++ # Wallet / UPI IDs given as "Wallet ID: xyz" or "Wallet ID,xyz" (CSV).t = _sub(r"\b(wallet\s*id|upi\s*id|vpa|payment\s*handle)(\s*[:,]\s*)\S+",r"\1\2<PAYMENT_HANDLE>", t, I)++ # UK sort code, with an optional second copy in brackets: "40-22-19 (402219)".t = _sub(r"\b(sort\s*code|sort)(\s*[:#]?\s*)\d{2}-?\d{2}-?\d{2}(\s*\(\d{6}\))?",r"\1\2<ROUTING_ID>", t, I)++ # 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, ...+ # "(?:\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)++ # 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)?|"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)++ # Card expiry date: "expires 09/28".t = _sub(r"\bexpires?\s+\d{2}/\d{2,4}", "expires <CARD_EXPIRY>", t, I)- # 2. Emails, then payment handles (handle = name@provider with NO dotted domain)+ # ----------------------------------------------------------------------+ # RULE 2: EMAILS AND PAYMENT HANDLES+ # Order matters: an email has a dotted domain ([email protected]); a payment+ # handle does not (name@easywallet, name@okaxis). Emails first, then+ # whatever "@word" is left must be a handle.+ # ----------------------------------------------------------------------t = _sub(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+", "<EMAIL>", t)t = _sub(r"[\w.+-]+@[A-Za-z][\w-]*\b(?!\.\w)", "<PAYMENT_HANDLE>", t)- t = _sub(r"(?<![\w@])@[A-Za-z0-9][\w-]{2,}", "<PAYMENT_HANDLE>", t) # @venmo-style+ # Venmo/Cash-App style handle with no name part: "@carlos-r-tx"+ t = _sub(r"(?<![\w@])@[A-Za-z0-9][\w-]{2,}", "<PAYMENT_HANDLE>", t)- # 3. IBAN (compact or space-grouped; case-insensitive) --------------------+ # ----------------------------------------------------------------------+ # RULE 3: IBAN+ # Format: 2 letters (country) + 2 check digits + up to 30 letters/digits.+ # Two forms: spaced groups ("GB29 NWBK 6016 1331 9268 19") and compact+ # ("PK36SCBL0000001123456702"). Case-insensitive ("de89 3704 ...").+ # ----------------------------------------------------------------------t = _sub(r"\b[A-Z]{2}\d{2}(?: [A-Z0-9]{4}){3,6}(?: \d{1,4})?\b", "<IBAN>", t, I)- t = _sub(r"\b[A-Z]{2}\d{2}[A-Z0-9]{10,30}\b", lambda m: "<IBAN>" if re.search(r"\d", m.group()[4:]) and+ # Compact form: also require a real country code and at least one digit+ # after the check digits, to avoid matching ordinary words.+ t = _sub(r"\b[A-Z]{2}\d{2}[A-Z0-9]{10,30}\b",+ lambda m: "<IBAN>" if re.search(r"\d", m.group()[4:]) andm.group()[:2].upper() in ISO_CC else m.group(), t, I)- # 4. National IDs with a fixed shape ------------------------------------- t = _sub(r"\b\d{5}-\d{7}-\d\b", "<NATIONAL_ID>", t) # PK CNIC- t = _sub(r"\b\d{3}-\d{2}-\d{4}\b", "<NATIONAL_ID>", t) # US SSN+ # ----------------------------------------------------------------------+ # RULE 4: NATIONAL IDs WITH A FIXED SHAPE+ # These have a unique format, so no label is needed.+ # ----------------------------------------------------------------------+ t = _sub(r"\b\d{5}-\d{7}-\d\b", "<NATIONAL_ID>", t) # Pakistan CNIC: 42201-7654321-3+ t = _sub(r"\b\d{3}-\d{2}-\d{4}\b", "<NATIONAL_ID>", t) # US SSN: 078-05-1120+ # UK National Insurance: 2 letters, 6 digits, suffix A-D. The first group+ # excludes letter pairs the UK never issues (BG, GB, NK, KN, TN, NT, ZZ).t = _sub(r"\b(?!BG|GB|NK|KN|TN|NT|ZZ)[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z]\s?\d{2}\s?\d{2}\s?\d{2}\s?[A-D]\b",- "<NATIONAL_ID>", t) # UK NINO- t = _sub(r"\b[A-Z]{5}\d{4}[A-Z]\b", "<NATIONAL_ID>", t) # IN PAN- t = _sub(r"(?<!\d[ -])\b[2-9]\d{3}[ -]\d{4}[ -]\d{4}\b(?![ -]\d)", "<NATIONAL_ID>", t) # IN Aadhaar- t = _sub(r"\b784-?\d{4}-?\d{7}-?\d\b", "<NATIONAL_ID>", t) # UAE Emirates ID+ "<NATIONAL_ID>", t)+ t = _sub(r"\b[A-Z]{5}\d{4}[A-Z]\b", "<NATIONAL_ID>", t) # India PAN: ABCPD1234F+ # India Aadhaar: 3 groups of 4 digits. The look-around guards make sure it+ # 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- # 5. Cards ---------------------------------------------------------------- t = _sub(r"\b\d{4,6}[ -]?[*Xx•]{4,}[ -]?\d{4}\b", "<CARD_NUMBER>", t) # BIN visible+ # ----------------------------------------------------------------------+ # RULE 5: CARD NUMBERS+ # A masked last-4 such as "xxxx8821" or "****6677" is ALLOWED to stay.+ # But a card showing its first 6 digits (the BIN) is a leak.+ # ----------------------------------------------------------------------+ # Partly masked with leading digits visible: "521234******2070"+ t = _sub(r"\b\d{4,6}[ -]?[*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",lambda m: "<CARD_NUMBER>" if luhn_ok(re.sub(r"\D", "", m.group())) else "<ACCOUNT_ID>", t)+ # 15-16 plain digits starting with 3-6 (real card prefixes) AND Luhn-valid.+ # The (?<![\d.,]) / (?![\d]|[.,]\d) guards stop it matching inside amounts.t = _sub(r"(?<![\d.,])(?=[3-6])\d{15,16}(?![\d]|[.,]\d)",lambda m: "<CARD_NUMBER>" if luhn_ok(m.group()) else m.group(), t)- # 6. Bank codes: IFSC, SWIFT/BIC ------------------------------------------- t = _sub(r"\b[A-Z]{4}0[A-Z0-9]{6}\b", "<ROUTING_ID>", t) # IFSC+ # ----------------------------------------------------------------------+ # RULE 6: BANK CODES (IFSC, SWIFT/BIC)+ # ----------------------------------------------------------------------+ # India IFSC: 4 letters, the digit 0, then 6 letters/digits (SBIN0011223).+ t = _sub(r"\b[A-Z]{4}0[A-Z0-9]{6}\b", "<ROUTING_ID>", t)+ # SWIFT/BIC with a label: "BIC: DEUTDEFF", "SWIFT code CHASUS33XXX".t = _sub(r"\b(bic|swift)(?:\s*code)?(\s*[:,]?\s*)[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b",r"\1\2<SWIFT_BIC>", t, I)- t = _sub(r"\b[A-Z]{6}[A-Z0-9]{2}XXX\b", "<SWIFT_BIC>", t) # ...XXX form- t = _sub(r"(?<=, )[A-Z]{4}([A-Z]{2})[A-Z0-9]{2}(?=[,\s])", # ', SCBLPKKA,'+ # 11-character form ending in XXX (a very distinctive SWIFT ending).+ t = _sub(r"\b[A-Z]{6}[A-Z0-9]{2}XXX\b", "<SWIFT_BIC>", t)+ # Unlabelled 8-letter code that follows ", " (e.g. "..., SCBLPKKA,").+ # Any 8-letter uppercase word *looks* like a BIC, so we also require letters+ # 5-6 to be a real country code. "RESOLVED" would pass that test alone,+ # which is why we additionally demand the ", " in front.+ t = _sub(r"(?<=, )[A-Z]{4}([A-Z]{2})[A-Z0-9]{2}(?=[,\s])",lambda m: "<SWIFT_BIC>" if m.group(1) in ISO_CC else m.group(), t)- # 7. Phones --------------------------------------------------------------+ # ----------------------------------------------------------------------+ # RULE 7: PHONE NUMBERS (many countries, many formats)+ # Phones come BEFORE the long-number rule so they get the right label.+ # (?<![\w.,]) means "not glued to a preceding word, dot or comma", which+ # keeps us from matching the middle of an amount like 1,234.5678.+ # ----------------------------------------------------------------------def phone(m):s = m.group()digits = re.sub(r"\D", "", s)+ # "+118300.00" matches the shape of an international number but is an+ # amount. Reject it, and anything outside 8-15 digits (the real range).if re.fullmatch(r"\+\d+\.\d{2}", s) or not 8 <= len(digits) <= 15:- return s # looks like an amount such as +118300.00+ return sreturn "<PHONE>"- t = _sub(r"(?<![\w.,])\+\d{1,3}(?:[\s.-]?(?:\(\d{1,5}\)|\d{1,5})){2,5}", phone, t) # international- t = _sub(r"(?<![\w.,])\(0\d{3}\)\s?\d{7}\b", "<PHONE>", t) # (0315) 1234567- t = _sub(r"(?<![\w.,])0\d{3}[ -]?\d{7}\b", "<PHONE>", t) # PK local- t = _sub(r"(?<![\w.,])0\d{4}[ ]?\d{6}\b", "<PHONE>", t) # UK local- t = _sub(r"(?<![\w.,])\(?\d{3}\)?[ .-]\d{3}[ .-]\d{4}\b", "<PHONE>", t) # US/CA- t = _sub(r"(?<![\w.,])04\d{2}[ ]?\d{3}[ ]?\d{3}\b", "<PHONE>", t) # AU mobile- t = _sub(r"(?<![\w.,])\(0\d\)[ ]?\d{4}[ ]?\d{4}\b", "<PHONE>", t) # AU landline-- # 8. Reference IDs ---------------------------------------------------------++ # International: +92-300-1234567, +44 7700 900123, +1 (512) 555-0148+ t = _sub(r"(?<![\w.,])\+\d{1,3}(?:[\s.-]?(?:\(\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++ # ----------------------------------------------------------------------+ # RULE 8: REFERENCE / TRACE / TRANSACTION IDs+ # Strongest signal first (a label), weakest last (just "a long number").+ # ----------------------------------------------------------------------+ # Word like REF / ORDER / TRACE / INVOICE / TXN followed by a value that+ # contains at least one digit. (?=[A-Za-z0-9-]*\d) is that "has a digit"+ # check; it stops "REF RENT SHARE" from losing the word RENT.t = _sub(r"\b(ref(?:erence)?s?|mandatsref|order|invoice|trace|txn|utr|"r"transaction\s*ids?|acct)\b([\s#:.-]*)(?=[A-Za-z0-9-]*\d)[A-Za-z0-9][A-Za-z0-9-]{3,}",r"\1\2<REF_ID>", t, I)- t = _sub(r"\b\d{3}-\d{7}-\d{7}\b", "<REF_ID>", t) # marketplace order no.- t = _sub(r"\b[A-Z]{1,4}-\d{4,}-\d{4,}\b", "<REF_ID>", t)+ t = _sub(r"\b\d{3}-\d{7}-\d{7}\b", "<REF_ID>", t) # marketplace order no: 402-8871253-1123456+ t = _sub(r"\b[A-Z]{1,4}-\d{4,}-\d{4,}\b", "<REF_ID>", t) # P-114488-202600, SR-20260501-000341+ # Long mixed letters+digits token (12+ chars): PayPal IDs like 8XJ22190T7002841Mt = _sub(r"\b(?=[A-Za-z0-9]*\d)(?=[A-Za-z0-9]*[A-Za-z])[A-Za-z0-9]{12,}\b", "<REF_ID>", t)- t = _sub(r"(?<![\d.,])\d{7,}(?![\d]|[.,]\d)", "<REF_ID>", t) # long numerics+ # 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)- # 9. IP addresses ---------------------------------------------------------+ # ----------------------------------------------------------------------+ # RULE 9: IP ADDRESSES (four numbers 0-255 separated by dots)+ # ----------------------------------------------------------------------t = _sub(r"(?<![\d.])(?:\d{1,3}\.){3}\d{1,3}(?![\d.])", "<IP_ADDRESS>", t)return tdiff --git a/output/combined_scrubbed.txt b/output/combined_scrubbed.txtnew file mode 100644index 0000000..460cea8--- /dev/null+++ b/output/combined_scrubbed.txt@@ -0,0 +1,224 @@+---- File: crescent_bank_statement_apr2026.pdf ----+Crescent Bank Limited+Statement of Account — 01-Apr-2026 to 30-Apr-2026+Branch: Gulshan-e-Iqbal Branch (0114), Karachi+Customer Name: Bilal Hassan Khan+Customer Address: <ADDRESS>+A/C No: <ACCOUNT_ID>+IBAN: <IBAN>+CNIC No <NATIONAL_ID>+Cell # <PHONE>+Email: <EMAIL>+Statement Request Ref: <REF_ID>+Date Description Amount Balance+01 Apr 2026 BAL B/F PKR18,450.75+01 Apr 2026 SALARY CREDIT TECHVERSE SOLUTIONS PVT LTD REF <REF_ID> PKR185,000.00Cr PKR203,450.75+02 Apr 2026 RAAST P2P FT - Digital <REF_ID> FT <REF_ID> PKR25,000.00Dr PKR178,450.75+<IBAN> <IBAN> BILAL HASSAN+KHAN Others BILAL HASSAN KHAN 2026-Apr-02 10:14:22, <SWIFT_BIC>,+<REF_ID>+02 Apr 2026 WHT ON CASH/TRANSFER SEC 231AA PKR125.00Dr PKR178,325.75+03 Apr 2026 POS PURCHASE IMTIAZ SUPER MARKET KARACHI PK Card xxxx8821 PKR7,340.50Dr PKR170,985.25+04 Apr 2026 NATIONAL FOODS LTD DIVIDEND WARRANT <REF_ID> CDC REF <REF_ID> PKR1,850.00Cr PKR172,835.25+05 Apr 2026 UTILITY BILL K-ELECTRIC Consumer Number: <ACCOUNT_ID> PKR9,120.00Dr PKR163,715.25+07 Apr 2026 RAAST P2P FT - Digital FT CRES-b112 SADA-77c3 BILAL HASSAN KHAN PKR8,000.00Dr PKR155,715.25+Others BILAL HASSAN KHAN 2026-Apr-07 18:40:05, <SWIFT_BIC>, VALUE+DATE:07 Apr 2026+07 Apr 2026 TRANSFER FEE RAAST INTERBANK PKR0.00Dr PKR155,715.25+09 Apr 2026 IBFT CR MEZ4491 Apr09-12:33:41 <REF_ID> -MZN GULF FREELANCE PKR62,500.00Cr PKR218,215.25+PORTAL LLC INTERNET PK OTHERS Onelink R2+09 Apr 2026 CHEQUE NO <REF_ID> CLEARING FAVOURING AL-REHMAN ESTATE AGENCY PKR30,000.00Dr PKR188,215.25+12 Apr 2026 ATM WDL CRESCENT ATM GULSHAN BR Card xxxx8821 Trace <REF_ID> PKR20,000.00Dr PKR168,215.25+12 Apr 2026 ATM WDL CRESCENT ATM GULSHAN BR Card xxxx8821 Trace <REF_ID> PKR20,000.00Dr PKR168,215.25+12 Apr 2026 ATM WDL CHARGES OFF-US PKR23.44Dr PKR168,191.81+15 Apr 2026 ONLINE TRANSFER TO AYESHA SIDDIQUI ACC <ACCOUNT_ID> PKR12,000.00Dr PKR156,191.81+HABIBMETRO REF <REF_ID> POF: FAMILY SUPPORT+18 Apr 2026 NETFLIX.COM AMSTERDAM NL Card xxxx8821 USD 3.99 @ 278.45 INCL FED PKR1,111.02Dr PKR155,080.79+21 Apr 2026 MOBILE TOPUP <PHONE> JAZZ SELF PKR500.00Dr PKR154,580.79+22 Apr 2026 REVERSAL ATM WDL TRACE <REF_ID> DISPUTE RESOLVED PKR20,000.00Cr PKR174,580.79+24 Apr 2026 RAAST IN FT NAYA-45f8 CRES-b112 BILAL HASSAN KHAN Others 2026-Apr-24 PKR15,000.00Cr PKR189,580.79+12:30:11, <SWIFT_BIC>+25 Apr 2026 RAAST P2P FT - Digital FT CRES-b112 NAYA-45f8 BILAL HASSAN KHAN Others PKR10,000.00Dr PKR179,580.79+BILAL HASSAN KHAN 2026-Apr-25 21:02:44, <SWIFT_BIC>, VALUE DATE:25 Apr+2026+28 Apr 2026 FONEPAY QR PAYMENT CHAI WALA CLIFTON KARACHI PKR860.00Dr PKR178,720.79+29 Apr 2026 SMS BANKING CHARGES APR-26 PKR180.00Dr PKR178,540.79+30 Apr 2026 WHT SEC 236P NON-FILER ADJ REVERSED FILER STATUS CONFIRMED PKR0.00Dr PKR178,540.79+CNIC <NATIONAL_ID>+30 Apr 2026 PROFIT PAYMENT SAVINGS APR-26 PKR412.88Cr PKR178,953.67++---- File: international_bank_statements_apr2026.docx ----+Barrow Bank plc (United Kingdom)+Barrow Bank plc — Current Account Statement — April 2026+Account Holder: Daniel R. Whitfield+Address: <ADDRESS>+Sort Code: <ROUTING_ID> Account Number: <ACCOUNT_ID>+IBAN: <IBAN>+BIC: <SWIFT_BIC>+NI Number: <NATIONAL_ID>+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+05 Apr 2026 | DIRECT DEBIT THAMES ENERGY REF <REF_ID> | -£89.00 | £2,977.24+08 Apr 2026 | FASTER PAYMENT TO SARAH WHITFIELD SORT <ROUTING_ID> ACC <ACCOUNT_ID> REF RENT SHARE | -£300.00 | £2,677.24+11 Apr 2026 | SPOTIFY UK LONDON GBR | -£11.99 | £2,665.25+14 Apr 2026 | AMAZON.CO.UK MKTPLACE | -£37.85 | £2,627.40+19 Apr 2026 | CASH WITHDRAWAL LINK ATM PICCADILLY Card ending 4532 | -£100.00 | £2,527.40+24 Apr 2026 | COUNCIL TAX MANCHESTER CC REF <REF_ID> | -£142.00 | £2,385.40+28 Apr 2026 | TRANSFER OVERSEAS REMITLY TO PK BENEFICIARY BILAL HASSAN KHAN IBAN <IBAN> | -£120.00 | £2,265.40+Harborstone National Bank (USA)+Harborstone National Bank — Checking Account — April 2026+Account Holder: Marcus T. Alvarez+Address: <ADDRESS>+Routing Number: <ROUTING_ID> Account Number: <ACCOUNT_ID>+SSN on file: <NATIONAL_ID>+Phone: <PHONE>+Email: <EMAIL>+04/01/2026 | PAYROLL DEPOSIT LONESTAR ANALYTICS LLC ACH TRACE <REF_ID> | +$3,850.00 | $5,214.33+04/03/2026 | STARBUCKS #08841 AUSTIN TX | -$7.25 | $5,207.08+04/05/2026 | ZELLE PAYMENT TO JENNA ALVAREZ REF <REF_ID> | -$250.00 | $4,957.08+04/08/2026 | WHOLE FOODS MKT #10233 AUSTIN TX Card xxxx5590 | -$132.60 | $4,824.48+04/12/2026 | ACH DEBIT AUSTIN ENERGY UTILITY ACCT <REF_ID> | -$95.40 | $4,729.08+04/15/2026 | VENMO PAYMENT TO <PAYMENT_HANDLE> | -$60.00 | $4,669.08+04/18/2026 | GITHUB, INC. SAN FRANCISCO CA | -$10.00 | $4,659.08+04/22/2026 | CHECK #1102 IMAGE REF <REF_ID> | -$400.00 | $4,259.08+04/29/2026 | INTEREST PAYMENT | +$1.12 | $4,260.20+Mapleleaf Credit Union (Canada)+Mapleleaf Credit Union — Chequing Account — April 2026+Account Holder: Priya Raghunathan+Address: <ADDRESS>+Transit: <ROUTING_ID> Institution: <ROUTING_ID> Account: <ACCOUNT_ID>+SIN: <NATIONAL_ID>+Phone: <PHONE>+Email: <EMAIL>+01 Apr 2026 | PAYROLL DEPOSIT NORTHBRIDGE HEALTH INC | +C$3,120.00 | C$4,880.19+02 Apr 2026 | INTERAC e-Transfer TO ROHAN RAGHUNATHAN <EMAIL> REF <REF_ID> | -C$500.00 | C$4,380.19+06 Apr 2026 | TIM HORTONS #4471 TORONTO ON | -C$6.40 | C$4,373.79+09 Apr 2026 | PRESTO FARE TORONTO | -C$43.75 | C$4,330.04+13 Apr 2026 | LOBLAWS #0762 TORONTO ON Card xxxx3308 | -C$118.92 | C$4,211.12+17 Apr 2026 | HYDRO ONE BILL PAYMENT ACCT <REF_ID> | -C$88.10 | C$4,123.02+21 Apr 2026 | NETFLIX.COM | -C$18.99 | C$4,104.03+26 Apr 2026 | INTERAC e-Transfer FROM ANANYA IYER REF <REF_ID> | +C$220.00 | C$4,324.03+Rheinbank AG (Germany)+Rheinbank AG — Kontoauszug April 2026+Kontoinhaber: Lukas Brandt+Anschrift: <ADDRESS>+IBAN: <IBAN>+BIC: <SWIFT_BIC>+Kontonummer: <ACCOUNT_ID> BLZ: <ROUTING_ID>+Steuer-ID: <NATIONAL_ID>+Handynummer: <PHONE>+E-Mail: <EMAIL>+01.04.2026 | GEHALT BERLINER DATENWERK GMBH | +€3.200,00 | €4.150,20+04.04.2026 | REWE MARKT BERLIN DEU | -€64,35 | €4.085,85+07.04.2026 | SEPA-UEBERWEISUNG AN KLAUS MUELLER IBAN <IBAN> VERWENDUNG MIETE APRIL | -€950,00 | €3.135,85+12.04.2026 | Netflix.com AMSTERDAM NLD | -€15,99 | €3.119,86+16.04.2026 | AMAZON.DE MKTPLACE | -€41,20 | €3.078,66+20.04.2026 | SEPA-LASTSCHRIFT VODAFONE GMBH MANDATSREF <REF_ID> GLAEUBIGER-ID <IBAN> | -€39,99 | €3.038,67+23.04.2026 | BVG TICKET BERLIN | -€49,00 | €2.989,67+Shree Vardhaman Bank (India)+Shree Vardhaman Bank — Savings Account Statement — April 2026+Account Holder: Rahul Deshpande+Address: <ADDRESS>+Account No: <ACCOUNT_ID>+IFSC: <ROUTING_ID> MICR: <ROUTING_ID>+PAN: <NATIONAL_ID>+Aadhaar: <NATIONAL_ID>+UPI ID: <PAYMENT_HANDLE>+Mobile: <PHONE>+Email: <EMAIL>+01-Apr-2026 | NEFT CR INFOTECH LABS PVT LTD SALARY UTR <REF_ID> | +₹85,000.00 | ₹1,12,340.00+03-Apr-2026 | UPI/P2M/<REF_ID>/ZOMATO ONLINE ORDER | -₹420.00 | ₹1,11,920.00+06-Apr-2026 | UPI/P2P/<REF_ID>/PRIYA SHARMA/<PAYMENT_HANDLE> | -₹2,000.00 | ₹1,09,920.00+10-Apr-2026 | ATM WDL PUNE CAMP BR Card xxxx7714 | -₹10,000.00 | ₹99,920.00+14-Apr-2026 | BILLPAY MSEB ELECTRICITY CONSUMER <ACCOUNT_ID> | -₹1,860.00 | ₹98,060.00+19-Apr-2026 | UPI/P2M/<REF_ID>/SWIGGY INSTAMART | -₹1,240.00 | ₹96,820.00+23-Apr-2026 | IMPS/P2A/<REF_ID>/TO RAHUL DESHPANDE/<ROUTING_ID>/XXXXXX4321 SELF | -₹15,000.00 | ₹81,820.00+27-Apr-2026 | CREDIT INTEREST | +₹312.00 | ₹82,132.00++---- File: paypal_activity_apr2026.txt ----+PayPal Activity Export — generated 01 May 2026 03:14 UTC+Account: <EMAIL>+Account Holder: Bilal Hassan Khan+Account Type: Personal (Verified)+Linked Card: Visa x-2070 (expires <CARD_EXPIRY>)+Linked Bank: Crescent Bank ****6677+Registered Phone: <PHONE>+Billing Address: <ADDRESS>+Login IP (last): <IP_ADDRESS>++Date, Name / Email, Type, Status, Amount, Fees, Total+03 Apr 2026, Upwork Escrow Inc (<EMAIL>), Payment Received, Completed, +$220.00 USD, -$4.40, +$215.60+03 Apr 2026, Currency Conversion PKR, Transfer, Completed, +PKR 61050.00, PKR 0.00, +PKR 61050.00+08 Apr 2026, GitHub Inc, Preapproved Payment, Completed, -$10.00 USD, $0.00, -$10.00+12 Apr 2026, Payoneer Withdrawal Ref <REF_ID>, Withdrawal, Pending then Completed, -$150.00 USD, -$2.50, -$152.50+15 Apr 2026, Fiverr International Ltd, Payment Received, Completed, +$85.00 USD, -$1.70, +$83.30+15 Apr 2026, Fiverr International Ltd, Payment Received, Completed, +$85.00 USD, -$1.70, +$83.30+16 Apr 2026, Fiverr International Ltd, Payment Reversal, Completed, -$85.00 USD, +$1.70, -$83.30+18 Apr 2026, Namecheap Inc order <REF_ID> domain bilalbuilds.dev, Payment, Completed, -$12.98 USD, $0.00, -$12.98+22 Apr 2026, TRANSFER TO NATIONAL SAVINGS not related note to self, Note, -, -, -, -+26 Apr 2026, <EMAIL>, Money Sent, Completed, -$40.00 USD, $0.00, -$40.00+29 Apr 2026, Steam Games (Valve Corp), Payment, Completed, -$4.99 USD, $0.00, -$4.99++Transaction IDs: <REF_ID>, <REF_ID>, <REF_ID>, <REF_ID>+Customer Support Reference: <REF_ID> (call <PHONE>)++---- File: wallet_transactions.csv ----+Customer Name,Bilal Hassan Khan+Wallet ID,<PAYMENT_HANDLE>+Wallet Account Number,<ACCOUNT_ID>+IBAN,<IBAN>+Registered CNIC,<NATIONAL_ID>+Registered Email,<EMAIL>+Linked Card,<CARD_NUMBER>+Statement Period,01 Apr 2026 to 30 Apr 2026+Opening Balance,"8,450.50",Closing Balance,"21,294.29"+Total Spent,"105,456.21",Total Received,"118,300.00"++TIMESTAMP,TYPE,DESCRIPTION,AMOUNT,BALANCE+2026-04-01 08:55:12,Merchant Payment,Paid to Foodpanda Karachi PK|Visa xxxx2070,-1240.50,7210.00+2026-04-01 18:22:47,Mobile Top-Up,Mobile top-up purchased |Ufone <PHONE> Nickname: my ufone,-500.00,6710.00+2026-04-02 10:14:03,Raast In,"Incoming fund transfer from Bilal Hassan Khan, Crescent Bank IBAN <IBAN>|Transaction ID <REF_ID>","+25,000.00","31,710.00"+2026-04-02 13:40:29,Merchant Payment,Paid to Foodpanda Karachi PK|Visa xxxx2070,-985.75,30724.25+2026-04-03 19:22:51,Peer to Peer,Money sent to Hamza Qureshi|(<PAYMENT_HANDLE>) NayaPay xxxx445,-5000.00,25724.25+2026-04-04 09:12:36,Online,Paid to Careem Rides Karachi PK|Visa xxxx2070,-435.00,25289.25+2026-04-04 21:48:10,Merchant Payment,Paid to Foodpanda Karachi PK|Visa xxxx2070,-1512.30,23776.95+2026-04-05 16:40:44,Bill Payment (1LINK),Paid to StormFiber|Consumer Number: <ACCOUNT_ID> Consumer Name: Bilal Khan Alias: Internet Bill,-4200.00,19576.95+2026-04-06 12:05:18,POS,"Paid to IMTIAZ SUPER MARKET, GULSHAN BRANCH KARACHI PK|Visa xxxx2070",-6320.40,13256.55+2026-04-07 18:41:09,Raast Out,Outgoing fund transfer to Bilal Hassan Khan SadaPay-7703|Nickname: my sadapay Transaction ID <REF_ID>,-8000.00,5256.55+2026-04-08 20:31:55,Merchant Payment,Paid to Foodpanda Karachi PK|Visa xxxx2070,-742.99,4513.56+2026-04-09 12:35:27,Raast In,"Incoming fund transfer from Gulf Freelance Portal LLC MCB-9911|Invoice <REF_ID>, Transaction ID <REF_ID>","+62,500.00","67,013.56"+2026-04-09 13:02:41,Raast Out,Outgoing fund transfer to Ammi Jaan easypaisa Bank-8834|Nickname: Ammi kharcha Transaction ID <REF_ID>,"-15,000.00","52,013.56"+2026-04-10 20:12:33,Online,Paid to Careem Rides Karachi PK|Visa xxxx2070,-850.00,51163.56+2026-04-11 21:30:02,Peer to Peer,Money received from Ayesha Siddiqui|(<PAYMENT_HANDLE>) NayaPay xxxx998,+3000.00,54163.56+2026-04-12 12:01:14,Cash Withdrawal,Cash Withdrawn at ATM|Visa xxxx2070 Trace <REF_ID>,"-20,000.00","34,163.56"+2026-04-12 14:44:58,POS,Paid to CHASE UP SHOPPING KARACHI PK|Visa xxxx2070,-2890.00,31273.56+2026-04-13 09:02:11,Service,SIM reissue verification|CNIC <NATIONAL_ID> submitted at Ufone franchise Gulshan,0.00,31273.56+2026-04-13 23:11:37,Merchant Payment,Paid to Foodpanda Karachi PK|Visa xxxx2070,-1105.50,30168.06+2026-04-14 22:18:26,Merchant Payment,Paid to Foodpanda Karachi PK|Visa xxxx2070,-980.25,29187.81+2026-04-14 22:18:26,Merchant Payment,Paid to Foodpanda Karachi PK|Visa xxxx2070,-980.25,29187.81+2026-04-15 10:20:05,Refund,Refund from Foodpanda Karachi PK|Visa xxxx2070 confirmation sent to <EMAIL>,+980.25,30168.06+2026-04-15 19:35:48,Mobile Top-Up,Mobile top-up purchased |Zong <PHONE> Nickname: office sim,-300.00,29868.06+2026-04-16 21:27:12,Bill Payment (1LINK),Paid to K-Electric|Consumer Number: <ACCOUNT_ID> Consumer Name: Bilal Khan Alias: ELECTRICITY â_x009a_¡,-9120.00,20748.06+2026-04-16 21:31:39,Bill Payment (1LINK),Paid to Karachi Water & Sewerage Corporation|Consumer Number: Consumer Name: Owner Alias: Pani,-1450.00,19298.06+2026-04-17 13:26:44,Merchant Payment,Paid to KFC Gulshan Karachi PK|Visa xxxx2070,-1890.00,17408.06+2026-04-18 15:44:21,Online,Paid to Daraz.pk Karachi PK|Visa xxxx2070 Order <REF_ID>,-3499.00,13909.06+2026-04-19 11:08:53,Peer to Peer,Money received from Hamza Qureshi|(<PAYMENT_HANDLE>) NayaPay xxxx445,+2500.00,16409.06+2026-04-20 10:09:32,Raast Out,Outgoing fund transfer to Muhammad Irfan easypaisa Bank-5521|Nickname: Irfan bhai plumber <PHONE> Transaction ID <REF_ID>,-2500.00,13909.06+2026-04-20 22:47:15,Merchant Payment,Paid to HAMZA GENERAL STORE KARACHI PK|Visa xxxx2070,-664.80,13244.26+2026-04-21 09:15:40,Online,Paid to Careem Rides Karachi PK|Visa xxxx2070,-390.00,12854.26+2026-04-22 17:54:07,Subscription,"Paid to Spotify AB, Stockholm SE|Visa xxxx2070",-499.00,12355.26+2026-04-23 20:02:59,POS,PAID TO SHANDAR SHINWARI RESTAURANT NATIONAL HIGHWAY KARACHI PK|Visa xxxx2070,-3150.00,9205.26+2026-04-24 12:30:11,Raast In,Incoming fund transfer from Bilal Hassan Khan Crescent-6702|Transaction ID <REF_ID>,"+15,000.00","24,205.26"+2026-04-24 12:33:57,Cash Withdrawal,Cash Withdrawn at ATM|Visa xxxx2070 Trace <REF_ID>,"-10,000.00","14,205.26"+2026-04-25 21:03:16,Raast Out,Outgoing fund transfer to Bilal Hassan Khan Crescent-6702|Nickname: main bank Transaction ID <REF_ID>,-5000.00,9205.26+2026-04-26 14:19:02,Merchant Payment,Paid to Foodpanda Karachi PK|Visa xxxx2070,-873.45,8331.81+2026-04-27 00:00:03,Peer to Peer,Money sent to Hamza Qureshi|(<PAYMENT_HANDLE>) NayaPay xxxx445,-1500.00,6831.81+2026-04-28 16:45:23,Raast In,Incoming fund transfer from Bilal Hassan Khan SadaPay-7703|Transaction ID <REF_ID>,"+10,300.00","17,131.81"+2026-04-29 19:21:34,Reversal,Transaction reversal ATM decline Trace <REF_ID>|Visa xxxx2070,+2000.00,19131.81+2026-04-29 23:55:50,Merchant Payment,Paid to Netflix.com Amsterdam NLD|Visa xxxx2070,-1100.00,18031.81+2026-04-30 18:37:29,Mobile Top-Up,Mobile top-up purchased |Ufone <PHONE> Nickname: my ufone,-500.00,17531.81+2026-04-30 21:12:08,Merchant Payment,Paid to Foodpanda Karachi PK|Visa xxxx2070,-898.90,16632.91+2026-04-30 22:40:19,Raast In,Incoming fund transfer from Osman Tariq Meezan-3312|Nickname: cricket fund wapsi Transaction ID <REF_ID>,+6000.00,22632.91+2026-04-30 23:59:58,Fee,Monthly service charges incl. FED|Ref <REF_ID>,-1338.62,21294.29diff --git a/tests/review.py b/tests/review.pyindex f24b49f..497ed41 100644--- a/tests/review.py+++ b/tests/review.py@@ -10,7 +10,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))from app.readers import read_filefrom app.scrubber import scrub_text-folder = Path(sys.argv[1] if len(sys.argv) > 1 else "data")+ROOT = Path(__file__).resolve().parent.parent+folder = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / "data"SUSPECT = re.compile(r"(?<![\d.,])\d{6,}(?![\d]|[.,]\d)|\b(?!PKR|USD|xxxx|XXXX|Apr)[A-Za-z]+-?[A-Za-z0-9]*\d{3,}[A-Za-z0-9-]*\b")IGNORE = re.compile(r"^(PKR|USD|x-?\d|xxxx|XXXX|Apr-)", re.I)@@ -23,5 +24,3 @@ for path in sorted(p for p in folder.iterdir() if p.is_file() and not p.name.staprint("Still present, eyeball these (identifier or fine?):")for tok, n in left.most_common():print(f" {tok} x{n}")--input("Press Enter to end it...")\ No newline at end of filediff --git a/tests/test_readers.py b/tests/test_readers.pynew file mode 100644index 0000000..914e0a0--- /dev/null+++ b/tests/test_readers.py@@ -0,0 +1,43 @@+"""Reader tests. pytest -v"""+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+from app.readers import read_file # noqa: E402+from app.engine import scrub_folder # noqa: E402+++def test_csv_keeps_leading_zeros_and_amounts(tmp_path):+ f = tmp_path / "a.csv"+ f.write_text('Date,Amount,Phone\n2026-04-01,"+25,000.00",03001234567\n', encoding="utf-8")+ out = read_file(f)+ assert "03001234567" in out # dtype=str: leading zero not lost+ assert '"+25,000.00"' in out # amount untouched, quoting kept+ assert "Date,Amount,Phone" in out # header row not swallowed+++def test_csv_with_uneven_rows_loses_nothing(tmp_path):+ f = tmp_path / "ragged.csv"+ f.write_text("Account Holder,Bilal\nWallet ID,abc\nDate,Desc,Amount\n2026-04-01,Netflix.com,-3.99\n",+ encoding="utf-8")+ out = read_file(f)+ assert "Netflix.com" in out and "Wallet ID,abc" in out+++def test_txt_cp1252_encoding(tmp_path):+ f = tmp_path / "a.txt"+ f.write_bytes("Paid £25.00 to Tesco".encode("cp1252"))+ assert "£25.00" in read_file(f)+++def test_unsupported_type_is_reported_not_crashing(tmp_path):+ (tmp_path / "pic.png").write_bytes(b"\x89PNG")+ (tmp_path / "ok.txt").write_text("hello", encoding="utf-8")+ out = scrub_folder(tmp_path)+ assert "---- File: ok.txt ----" in out and "[SKIPPED: ValueError: unsupported file type: .png]" in out+++def test_missing_folder_gives_clear_error(tmp_path):+ import pytest+ with pytest.raises(NotADirectoryError, match="Data folder not found"):+ scrub_folder(tmp_path / "nope")diff --git a/tests/test_scrubber.py b/tests/test_scrubber.pyindex 0f8875d..83844da 100644--- a/tests/test_scrubber.py+++ b/tests/test_scrubber.py@@ -12,8 +12,8 @@ import pytestROOT = Path(__file__).resolve().parent.parentsys.path.insert(0, str(ROOT))-from app.engine import scrub_folder # noqa: E402-from app.scrubber import scrub_text # noqa: E402+from app.engine import scrub_folder+from app.scrubber import scrub_text# ---------------------------------------------------------------- Layer 1# (input, substring that must be GONE, placeholder that must appear)