Skip to content

Scrubs bank statements locally & analyse with Groq.

Python

Step 5: PostreSQL schema and storage

asadullahdotfa8fcbe8dbce
diff --git a/app/db.py b/app/db.py
new file mode 100644
index 0000000..f6aaacf
--- /dev/null
+++ b/app/db.py
@@ -0,0 +1,98 @@
+"""Step 5: PostgreSQL storage.
+
+Only SCRUBBED text is ever written here. This module has no access to raw
+text: it receives ScrubbedFile objects produced by engine.py.
+
+ init_db() create the tables (safe to call repeatedly)
+ save_run(files) store one scrub run + its files -> run_id
+ get_run(run_id) fetch a run with its per-file rows
+ list_runs() newest runs first (no big text columns)
+
+Run `python -m app.db` once to create the tables.
+"""
+import json
+import os
+from collections import Counter
+from pathlib import Path
+
+from dotenv import load_dotenv
+from sqlalchemy import create_engine, text
+
+from app.engine import ScrubbedFile, combine
+
+load_dotenv() # reads DATABASE_URL from the .env file in the project root
+
+DATABASE_URL = os.getenv(
+ "DATABASE_URL", "postgresql+psycopg://pii:pii_pass@localhost:5432/pii_scrubber"
+)
+SCHEMA_FILE = Path(__file__).resolve().parent.parent / "db" / "schema.sql"
+
+# One shared connection pool for the whole app. pool_pre_ping drops dead
+# connections (e.g. after the Docker container restarts) instead of erroring.
+engine = create_engine(DATABASE_URL, pool_pre_ping=True)
+
+
+def init_db() -> None:
+ """Create all tables by running db/schema.sql (idempotent)."""
+ sql = SCHEMA_FILE.read_text(encoding="utf-8")
+ # exec_driver_sql sends the file as-is, so it may hold several statements.
+ with engine.begin() as conn:
+ conn.exec_driver_sql(sql)
+
+
+def save_run(files: list[ScrubbedFile]) -> int:
+ """Store one run and all its files in ONE transaction; return the run id.
+
+ The transaction means a run is saved completely or not at all: you can
+ never end up with a run row that is missing some of its files.
+ """
+ combined = combine(files)
+ totals = Counter()
+ for f in files:
+ totals.update(f.placeholder_counts)
+
+ with engine.begin() as conn: # commits on success, rolls back on any error
+ run_id = conn.execute(
+ text("""INSERT INTO scrub_runs (file_count, combined_text, placeholder_counts)
+ VALUES (:n, :combined, CAST(:counts AS jsonb)) RETURNING id"""),
+ {"n": len(files), "combined": combined, "counts": json.dumps(totals)},
+ ).scalar_one()
+
+ for f in files:
+ conn.execute(
+ text("""INSERT INTO scrubbed_files
+ (run_id, filename, file_type, status, scrubbed_text, placeholder_counts)
+ VALUES (:run_id, :name, :ftype, :status, :txt, CAST(:counts AS jsonb))"""),
+ {"run_id": run_id, "name": f.name, "ftype": f.file_type, "status": f.status,
+ "txt": f.text, "counts": json.dumps(f.placeholder_counts)},
+ )
+ return run_id
+
+
+def get_run(run_id: int) -> dict | None:
+ """Return the run (with combined_text) and its files, or None if not found."""
+ with engine.connect() as conn:
+ run = conn.execute(
+ text("SELECT id, created_at, file_count, combined_text, placeholder_counts "
+ "FROM scrub_runs WHERE id = :id"), {"id": run_id}).mappings().first()
+ if run is None:
+ return None
+ files = conn.execute(
+ text("SELECT filename, file_type, status, scrubbed_text, placeholder_counts "
+ "FROM scrubbed_files WHERE run_id = :id ORDER BY filename"),
+ {"id": run_id}).mappings().all()
+ return {**run, "files": [dict(f) for f in files]}
+
+
+def list_runs(limit: int = 20) -> list[dict]:
+ """Newest runs first. Omits the large text columns on purpose."""
+ with engine.connect() as conn:
+ rows = conn.execute(
+ text("SELECT id, created_at, file_count, placeholder_counts "
+ "FROM scrub_runs ORDER BY id DESC LIMIT :limit"), {"limit": limit}).mappings().all()
+ return [dict(r) for r in rows]
+
+
+if __name__ == "__main__":
+ init_db()
+ print("Tables created (or already present).")
diff --git a/app/engine.py b/app/engine.py
index 388e070..cf8e58e 100644
--- a/app/engine.py
+++ b/app/engine.py
@@ -9,7 +9,12 @@
<scrubbed text of the TXT>
...
-This module is the only thing the rest of the project needs to call:
+Two levels of API:
+ scrub_files(folder) -> list[ScrubbedFile] one result per file (used by the
+ database layer to store one row each)
+ combine(files) -> str the single combined string
+ scrub_folder(folder) -> str both steps in one 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
@@ -17,7 +22,10 @@ This module is the only thing the rest of the project needs to call:
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 re
import sys
+from collections import Counter
+from dataclasses import dataclass, field
from pathlib import Path
from app.readers import read_file
@@ -30,12 +38,22 @@ 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.
+@dataclass
+class ScrubbedFile:
+ """The scrubbed result for ONE input file (never contains raw text)."""
+ name: str # original file name, e.g. "paypal_activity_apr2026.txt"
+ file_type: str # lower-case extension, e.g. ".txt"
+ status: str # "ok" or "skipped"
+ text: str # scrubbed text, or "[SKIPPED: reason]"
+ placeholder_counts: dict = field(default_factory=dict) # {"<IBAN>": 3, ...}
+
+
+def scrub_files(folder: str | Path) -> list[ScrubbedFile]:
+ """Scrub every file in `folder`; return one ScrubbedFile per file.
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.
+ NOT stop the run: it comes back with status "skipped" so one bad file
+ never loses the rest of the statements.
"""
folder = Path(folder)
@@ -46,37 +64,45 @@ def scrub_folder(folder: str | Path) -> str:
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()
+ paths = 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} ----"
+ results = []
+ for path in paths:
try:
raw_text = read_file(path) # readers.py: file -> raw text (has PII)
- body = scrub_text(raw_text) # scrubber.py: raw text -> safe text
+ text = scrub_text(raw_text) # scrubber.py: raw text -> safe text
+ status = "ok"
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")
+ text, status = f"[SKIPPED: {type(e).__name__}: {e}]", "skipped"
+ counts = dict(Counter(re.findall(r"<[A-Z_]+>", text)))
+ results.append(ScrubbedFile(path.name, path.suffix.lower(), status, text.strip(), counts))
+ return results
+
+def combine(files: list[ScrubbedFile]) -> str:
+ """Join per-file results into ONE string with a header before each file."""
# A blank line between files keeps the combined string easy to read.
- return "\n".join(parts)
+ return "\n".join(f"---- File: {f.name} ----\n{f.text}\n" for f in files)
+
+
+def scrub_folder(folder: str | Path) -> str:
+ """Scrub every file in `folder` and return ONE combined string."""
+ return combine(scrub_files(folder))
# --------------------------------------------------------------------------
-# Command-line use (run from anywhere):
+# Command-line use (run from the project root):
# 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.)
+ # symbols like the rupee sign. Force UTF-8 so print() never crashes.
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
folder = Path(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_DATA_DIR
diff --git a/db/schema.sql b/db/schema.sql
new file mode 100644
index 0000000..02a9a2f
--- /dev/null
+++ b/db/schema.sql
@@ -0,0 +1,65 @@
+-- PII Scrubber - PostgreSQL schema. Safe to run repeatedly (IF NOT EXISTS).
+--
+-- GOLDEN RULE: this database only ever holds SCRUBBED text. Raw statement
+-- text is never written here (it lives only in memory inside readers.py ->
+-- scrubber.py).
+--
+-- Relationships:
+-- scrub_runs 1 --- * scrubbed_files one row per input file
+-- scrub_runs 1 --- * analyses Groq analysis results (Step 7)
+-- scrub_runs 1 --- * chat_messages chat history (Step 8)
+
+-- One row per "scrub the whole folder" action. This is the unit everything
+-- else hangs off: the analysis and the chat both refer to a run.
+CREATE TABLE IF NOT EXISTS scrub_runs (
+ id BIGSERIAL PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ file_count INTEGER NOT NULL CHECK (file_count >= 0),
+ -- The exact single string the engine produced (per-file headers included).
+ -- It is what gets sent to Groq, so we keep it byte-for-byte for
+ -- reproducibility and to ground/verify the model's numbers later.
+ combined_text TEXT NOT NULL,
+ placeholder_counts JSONB NOT NULL DEFAULT '{}'::jsonb
+);
+
+-- One row per input file inside a run: lets you inspect or query each
+-- statement separately and see which files were skipped and why.
+CREATE TABLE IF NOT EXISTS scrubbed_files (
+ id BIGSERIAL PRIMARY KEY,
+ run_id BIGINT NOT NULL REFERENCES scrub_runs(id) ON DELETE CASCADE,
+ filename TEXT NOT NULL,
+ file_type TEXT NOT NULL, -- '.pdf', '.csv', ...
+ status TEXT NOT NULL CHECK (status IN ('ok', 'skipped')),
+ scrubbed_text TEXT NOT NULL, -- or the "[SKIPPED: reason]" note
+ placeholder_counts JSONB NOT NULL DEFAULT '{}'::jsonb, -- {"<IBAN>": 3, ...}
+ UNIQUE (run_id, filename)
+);
+
+-- Groq analysis of a run (filled in Step 7). JSONB because the analysis is
+-- structured (categories, merchants, insights) and may evolve between prompt
+-- versions. Several analyses per run are allowed (re-run with another model).
+CREATE TABLE IF NOT EXISTS analyses (
+ id BIGSERIAL PRIMARY KEY,
+ run_id BIGINT NOT NULL REFERENCES scrub_runs(id) ON DELETE CASCADE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ model TEXT NOT NULL,
+ prompt_version TEXT NOT NULL,
+ result JSONB NOT NULL, -- the model's structured analysis
+ validation JSONB NOT NULL DEFAULT '{}'::jsonb -- our grounding/number checks
+);
+
+-- Chat turns about a run (Step 8). Stored so the conversation survives a page
+-- refresh and the API can rebuild the history window for each new question.
+CREATE TABLE IF NOT EXISTS chat_messages (
+ id BIGSERIAL PRIMARY KEY,
+ run_id BIGINT NOT NULL REFERENCES scrub_runs(id) ON DELETE CASCADE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ role TEXT NOT NULL CHECK (role IN ('user', 'assistant')),
+ content TEXT NOT NULL
+);
+
+-- Foreign keys are not indexed automatically in PostgreSQL. These make
+-- "all files / analyses / chat of run X, in order" fast.
+CREATE INDEX IF NOT EXISTS idx_files_run ON scrubbed_files (run_id);
+CREATE INDEX IF NOT EXISTS idx_analyses_run ON analyses (run_id, created_at DESC);
+CREATE INDEX IF NOT EXISTS idx_chat_run ON chat_messages (run_id, id);
diff --git a/tests/test_db.py b/tests/test_db.py
new file mode 100644
index 0000000..d979c79
--- /dev/null
+++ b/tests/test_db.py
@@ -0,0 +1,65 @@
+"""Database tests. Need PostgreSQL running (docker compose up -d); skipped otherwise."""
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT))
+
+from sqlalchemy import text # noqa: E402
+from app import db # noqa: E402
+from app.engine import scrub_files, combine # noqa: E402
+
+try:
+ with db.engine.connect() as c:
+ c.execute(text("SELECT 1"))
+ DB_UP = True
+except Exception:
+ DB_UP = False
+
+pytestmark = pytest.mark.skipif(not DB_UP, reason="PostgreSQL not reachable")
+
+
+def run_id():
+ db.init_db()
+ files = scrub_files(ROOT / "data")
+ rid = db.save_run(files)
+ yield rid
+ with db.engine.begin() as c: # clean up; files cascade-delete
+ c.execute(text("DELETE FROM scrub_runs WHERE id = :i"), {"i": rid})
+
+
+def test_roundtrip_preserves_combined_string(run_id):
+ stored = db.get_run(run_id)
+ assert stored["combined_text"] == combine(scrub_files(ROOT / "data"))
+ assert stored["file_count"] == len(stored["files"]) > 0
+
+
+def test_one_row_per_file_with_status(run_id):
+ names = {f["filename"] for f in db.get_run(run_id)["files"]}
+ assert {p.name for p in (ROOT / "data").iterdir() if p.is_file()} == names
+
+
+def test_stored_text_has_no_obvious_pii(run_id):
+ import re
+ text_ = db.get_run(run_id)["combined_text"]
+ assert not re.search(r"[\w.+-]+@[\w-]+\.[\w.]+", text_) # no emails
+ assert not re.search(r"(?<![\d.,])\d{8,}(?![\d]|[.,]\d)", text_) # no long digit runs
+
+
+def test_failed_save_rolls_back_everything():
+ from app.engine import ScrubbedFile
+ db.init_db()
+ before = len(db.list_runs(1000))
+ bad = [ScrubbedFile("a.txt", ".txt", "ok", "x", {}),
+ ScrubbedFile("a.txt", ".txt", "ok", "y", {})] # duplicate name violates UNIQUE
+ with pytest.raises(Exception):
+ db.save_run(bad)
+ assert len(db.list_runs(1000)) == before # no half-saved run
+
+
+def test_get_missing_run_returns_none():
+ db.init_db()
+ assert db.get_run(-1) is None