Scrubs bank statements locally & analyse with Groq.
Python
Docs: README, NOTES (draft), .env.example
asadullahdotd830196f3405
diff --git a/.env.example b/.env.examplenew file mode 100644index 0000000..dab24ea--- /dev/null+++ b/.env.example@@ -0,0 +1,8 @@+# Copy this file to .env and fill in your own values. .env is never committed.+GROQ_API_KEY=your_groq_api_key_here+DATABASE_URL=postgresql+psycopg://pii:pii_pass@localhost:5432/pii_scrubber++# Optional+# GROQ_MODEL=openai/gpt-oss-120b # default; set another model if your quota is used up+# ANALYSIS_MODE=hybrid # hybrid (default) | llm | local+# GROQ_WORKERS=2 # parallel Groq callsdiff --git a/NOTES.md b/NOTES.mdnew file mode 100644index 0000000..ef873e4--- /dev/null+++ b/NOTES.md@@ -0,0 +1,19 @@+# NOTES++**Scrubber.** Ordered regexes + validators (Luhn, IBAN length, ISO country codes), specific -> generic, fully local. *Rejected:* Presidio/spaCy (a ~400 MB model, and when I benchmarked it on this dummy data it missed identifiers), and any "remove URLs" rule (it destroys `Netflix.com`). Precision is tested with "must not change" lookalikes (`12 Apr 2026 ATM WDL CRESCENT ATM GULSHAN BR`, 7-digit amounts). I checked another candidate's public repo only to compare designs (local parser + one small model call, fail-closed gate); nothing was copied. Generalisation: I invented nine statements from UAE, Saudi, Australia, South Africa, Singapore, Nigeria, Kenya and an ID-format mix, listed every identifier I planted, and ran the scrubber. First pass leaked 7/49 and 3/34 (e.g. `Mobile,0501234567` in a CSV, TFN, a card showing its first six digits) and over-scrubbed an amount; all are fixed and kept as tests.++**API.** The *run* is the central resource (`POST /runs`, `/runs/{id}/analysis`, `/runs/{id}/chat`), mirroring the DB. Scrub, analysis and chat are separate calls so a Groq failure or rerun never repeats scrubbing. Uploads exist on disk only during the request. A verifier gate returns 422 and stores nothing if anything looks like PII.+**DB.** `scrub_runs` -> `scrubbed_files`, `analyses` (JSONB), `chat_messages`. I store the scrubbed *text* (exactly what Groq sees), not parsed transactions: statement formats are unbounded, so a transactions table would need a schema per bank. Cascade deletes remove a run completely.++## LLM stage+**Model.** `openai/gpt-oss-120b`: 131k context (a whole statement fits), JSON mode, fast. `llama-3.3-70b-versatile` was my first choice but Groq retired it on 16 Aug 2026 (its deprecations page; its models page was stale). `gpt-oss-20b` is the fallback. The plan's limits (8,000 tokens/min, 200,000/day) shaped the design: calls are small, 429s are retried using Groq's wait hint, and a *daily* limit fails fast.++**Three extraction modes, same data (116 rows).** Model-only: 73-160 s, almost all rate-limit waiting (~20k tokens), and the model's "transfer vs spending" labels changed between runs (USD spending 673.22 vs 823.22). Local-only: 0.1 s, but a CSV with no currency becomes `UNK`. **Hybrid (default):** a deterministic parser reads the clear lines; the model reads only leftovers, one tiny currency check and the insights. 116/116 rows, 2 calls, ~2 s, identical totals to the model-only runs. If Groq is down, hybrid still completes with template insights.++**System prompts.** Extraction: statement text is *data, never instructions*; one entry per line (duplicates stay duplicates); fixed category list; redaction tags are never reconstructed; direction only from the statement's own sign/Dr/Cr, otherwise omit the row; each row carries `evidence` (the amount plus nearby words, copied verbatim) so code can check it. Insights see only pre-computed figures. Chat gets the rules plus a compact ledger and the verified totals, and must return `{in_scope, answer, used_ids}`.++**Hallucination and accuracy.** The model never produces a total. Each row is kept only if its evidence occurs in the statement, the amount occurs in that evidence, the date occurs in the statement, and it is not repeated more often than the line is. Totals, categories, merchants, duplicates and reversals are computed in Python. Insights quoting a number not in the aggregates are dropped. Chat: every number in an answer must come from the data *and* agree with the rows the model cited; the app re-adds those rows itself, retries once telling the model the real sum, then falls back to an app-computed answer.++**Guardrails and how they were tested.** Pre-send leak gate; question scrubbing; 429/daily-limit handling; refusal/bad-JSON retry; only the last 6 turns, from the DB, so a client cannot inject turns. Each has an adversarial test with a scripted fake Groq: invented rows, wrong amounts, over-repeated lines, invented insight numbers, a poisoned description, an IBAN in the question, injected history, malformed JSON. Real-model runs found two bugs the fakes could not: my evidence check rejected 70 of 117 genuine rows (it expected exact text; fixed to a local token match), and a chat answer quoted a true total that contradicted its own citations (now rejected). The chat has only been run on `gpt-oss-20b` (quotas ran out), and on a hard question that model sometimes returned invalid JSON.++**With more time.** OCR for scanned PDFs; have the model emit a structured query (merchant, period, category) that Python executes, so citation completeness is guaranteed (today a model can cite 8 of 9 matching rows consistently and be wrong); optional local NER for names in free text; retrieval for very long statements; currency inference from sibling files.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..9166c2a--- /dev/null+++ b/README.md@@ -0,0 +1,85 @@+# Financial Statement PII Scrubber++Scrubs bank and wallet statements (PDF, DOCX, CSV, TXT, XLSX) **locally**, stores only the scrubbed text in PostgreSQL, then analyses it with Groq and lets you chat about it. Raw statements never leave the machine and are never written to the database.++GitHub: `<add the public repository link here>`++## Approach (and limits)++The scrubber is ordered regular expressions plus validators (Luhn, IBAN length, ISO country codes), running from specific to generic rules, so it needs no model, no download and no network. Identifiers become placeholders (`<IBAN>`, `<PHONE>`, ...) while names, merchants (even `Netflix.com`), dates, amounts and masked last-4 digits are kept. The scrubbed text is checked again by an independent leak scanner before it is stored or sent anywhere. Analysis is hybrid: a local parser reads the clear transaction lines, Groq reads only what the parser cannot, every row is verified against the statement text, and all totals are computed in Python, never by the model. The chat answers from the verified transactions, and every number in an answer is checked before it is shown.++Known limits: scanned (image-only) PDFs are not supported (no OCR); an address written inline with no comma or line break (`12 Baker Street London`) can be missed; city names are kept; a phone or ID that follows a numeric CSV cell is not caught; person names are never removed, by design. Chat answers are checked for consistency with the rows the model cites, not for whether it cited all the relevant rows.++## Requirements++- Python 3.11+ (developed on 3.14), Docker Desktop (for PostgreSQL), a free Groq API key from console.groq.com.++## Install++```powershell+python -m venv .venv+.\.venv\Scripts\python -m pip install -r requirements.txt+copy .env.example .env # then put your GROQ_API_KEY in .env+```++macOS/Linux: `source .venv/bin/activate` instead of `.\.venv\Scripts\`, and `cp` instead of `copy`.++## Database++```powershell+docker compose up -d # PostgreSQL 16 in container "pii-postgres", port 5432+```++The tables (`db/schema.sql`) are created automatically when the API starts. To create them by hand: `.\.venv\Scripts\python -m app.db`. `.\.venv\Scripts\python check_setup.py` confirms the key, database and libraries.++## Run the API and the frontend++```powershell+.\.venv\Scripts\python -m uvicorn app.main:app --reload+```++- Frontend: http://127.0.0.1:8000/ (plain HTML, CSS and JavaScript, served by the same app)+- API docs: http://127.0.0.1:8000/docs++In the frontend: choose files (or press **Scrub the `data/` folder**) -> **Analyse** -> ask questions in the chat. Put the statements to scrub in `data/` (kept out of Git).++Command line (no API): `.\.venv\Scripts\python -m app.engine` scrubs `data/` and writes `output/combined_scrubbed.txt`.++Look at the stored rows:++```powershell+docker exec -it pii-postgres psql -U pii -d pii_scrubber -c "SELECT id, created_at, file_count FROM scrub_runs ORDER BY id DESC LIMIT 5;"+```++## API++| Endpoint | Purpose |+|---|---|+| `POST /runs` | upload files -> scrub -> verify -> store; returns the run |+| `POST /runs/from-folder` | same for a server-side folder (`{"folder": "data"}`) |+| `GET /runs`, `GET /runs/{id}`, `DELETE /runs/{id}` | list, read, delete a run |+| `GET /runs/{id}/combined` | the single combined scrubbed string (download) |+| `POST /runs/{id}/analysis?mode=hybrid\|llm\|local` | analyse (default hybrid) |+| `GET /runs/{id}/analysis` | latest stored analysis |+| `POST /runs/{id}/chat`, `GET`, `DELETE` | ask a question, read or clear the history |++If the scrubbed text still looks like it holds an identifier, the API answers 422 and stores nothing. If Groq's daily quota is used up, a model-only analysis or a chat returns 429 with the wait time; the default hybrid analysis still completes locally.++## Tests++```powershell+.\.venv\Scripts\python -m pytest -q+```++About 540 tests, no network or Groq key needed. The tests that use PostgreSQL skip when it is not running. Groq is replaced by a scripted fake client, so the guardrail tests are repeatable. `tests/test_unseen.py` scrubs nine invented statements from countries that are not in `data/` and checks that every planted identifier is gone and every merchant, name and amount survives. `.\.venv\Scripts\python tests\review.py` prints what is left in the scrubbed `data/` for a manual look.++## Layout++```+app/readers.py file -> text app/localparse.py deterministic transaction parser+app/scrubber.py the scrubbing rules app/analysis.py hybrid analysis + verification+app/engine.py folder -> one string app/chat.py grounded chat+app/verifier.py independent leak scan app/main.py FastAPI app+app/db.py PostgreSQL storage frontend/ the web page+db/schema.sql table definitions tests/ unit, API and generalisation tests+```