Text Generation
Transformers
English
phi3
finance
entity-extraction
ner
phi-3
production
indian-banking
custom_code
4-bit precision
Instructions to use Ranjit0034/finance-entity-extractor with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Ranjit0034/finance-entity-extractor with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Ranjit0034/finance-entity-extractor", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("Ranjit0034/finance-entity-extractor", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("Ranjit0034/finance-entity-extractor", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Ranjit0034/finance-entity-extractor with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Ranjit0034/finance-entity-extractor" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Ranjit0034/finance-entity-extractor", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/Ranjit0034/finance-entity-extractor
- SGLang
How to use Ranjit0034/finance-entity-extractor with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Ranjit0034/finance-entity-extractor" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Ranjit0034/finance-entity-extractor", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Ranjit0034/finance-entity-extractor" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Ranjit0034/finance-entity-extractor", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use Ranjit0034/finance-entity-extractor with Docker Model Runner:
docker model run hf.co/Ranjit0034/finance-entity-extractor
Ranjit Behera commited on
Commit Β·
dcc24f8
0
Parent(s):
FinEE v1.0 - Finance Entity Extractor
Browse filesProduction-ready Python package for extracting structured financial data
from Indian banking messages.
Features:
- 5-tier additive pipeline (Cache/Regex/Rules/LLM/Validate)
- Multi-backend support (MLX, PyTorch, GGUF)
- CLI: finee extract 'text'
- 88 unit tests, 94.5% accuracy
Model weights: https://huggingface.co/Ranjit0034/finance-entity-extractor
This view is limited to 50 files because it contains too many changes. Β See raw diff
- .gitattributes +1 -0
- .github/workflows/tests.yml +34 -0
- .gitignore +120 -0
- .project-meta +1 -0
- 01_data_parsing.ipynb +239 -0
- 01_data_pipeline.ipynb +648 -0
- 02_classification.ipynb +228 -0
- 03_pattern_discovery.ipynb +320 -0
- 04_training.ipynb +503 -0
- 05_add_credit_data.ipynb +304 -0
- 06_statement_extraction.ipynb +382 -0
- LICENSE +21 -0
- MANIFEST.in +4 -0
- README.md +209 -0
- config.json +45 -0
- config/config.yaml +42 -0
- data/evaluation_report.json +2917 -0
- docs/banking_email_formats.md +61 -0
- evaluation_results_v6.json +66 -0
- pyproject.toml +121 -0
- requirements.txt +33 -0
- scripts/auto_commit.sh +101 -0
- scripts/claude_labeling.py +180 -0
- scripts/collect_rbi_npci.py +264 -0
- scripts/convert_to_gguf.py +243 -0
- scripts/corpus_collection/collect_corpus.py +435 -0
- scripts/create_benchmark.py +242 -0
- scripts/create_clean_benchmark.py +298 -0
- scripts/create_multi_bank_test.py +113 -0
- scripts/create_strict_benchmark.py +237 -0
- scripts/domain_pretrain.py +383 -0
- scripts/evaluate_v6.py +107 -0
- scripts/finetune_v6.py +42 -0
- scripts/fuse_model.py +40 -0
- scripts/generate_comprehensive_data.py +297 -0
- scripts/generate_icici_data.py +181 -0
- scripts/generate_payment_app_data.py +437 -0
- scripts/generate_statement_data.py +390 -0
- scripts/install_scheduler.sh +39 -0
- scripts/quantitative_eval.py +194 -0
- scripts/retrain_v7.py +105 -0
- scripts/retrain_v8.py +111 -0
- scripts/setup_branches.sh +45 -0
- scripts/sync_models.py +79 -0
- scripts/test_clean_benchmark.py +119 -0
- scripts/test_multi_bank.py +188 -0
- scripts/test_real_benchmark.py +185 -0
- scripts/test_unseen.py +91 -0
- scripts/upload_to_hf.py +425 -0
- scripts/verify_compatibility.py +56 -0
.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
adapters.safetensors filter=lfs diff=lfs merge=lfs -text
|
.github/workflows/tests.yml
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Tests
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [ main ]
|
| 6 |
+
pull_request:
|
| 7 |
+
branches: [ main ]
|
| 8 |
+
|
| 9 |
+
jobs:
|
| 10 |
+
test:
|
| 11 |
+
runs-on: ubuntu-latest
|
| 12 |
+
strategy:
|
| 13 |
+
matrix:
|
| 14 |
+
python-version: ["3.9", "3.10"]
|
| 15 |
+
|
| 16 |
+
steps:
|
| 17 |
+
- uses: actions/checkout@v3
|
| 18 |
+
|
| 19 |
+
- name: Set up Python ${{ matrix.python-version }}
|
| 20 |
+
uses: actions/setup-python@v4
|
| 21 |
+
with:
|
| 22 |
+
python-version: ${{ matrix.python-version }}
|
| 23 |
+
|
| 24 |
+
- name: Install dependencies
|
| 25 |
+
run: |
|
| 26 |
+
python -m pip install --upgrade pip
|
| 27 |
+
# Install core package + dev deps + cpu optional
|
| 28 |
+
# Skip llama-cpp-python if it takes too long, but core tests should pass
|
| 29 |
+
pip install ".[dev]"
|
| 30 |
+
|
| 31 |
+
- name: Run Tests
|
| 32 |
+
run: |
|
| 33 |
+
# Run all tests except those requiring heavy models if any
|
| 34 |
+
pytest tests/ -v
|
.gitignore
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ============================================
|
| 2 |
+
# LLM Mail Trainer - .gitignore
|
| 3 |
+
# ============================================
|
| 4 |
+
|
| 5 |
+
# ==================== DATA (SENSITIVE) ====================
|
| 6 |
+
# Raw email data - NEVER commit!
|
| 7 |
+
data/raw/
|
| 8 |
+
*.mbox
|
| 9 |
+
|
| 10 |
+
# Parsed emails (personal data)
|
| 11 |
+
data/parsed/
|
| 12 |
+
data/filtered/
|
| 13 |
+
data/training/
|
| 14 |
+
data/training_backup*/
|
| 15 |
+
|
| 16 |
+
# ==================== MODELS ====================
|
| 17 |
+
# Local model files (too large for GitHub - hosted on HuggingFace)
|
| 18 |
+
models/
|
| 19 |
+
fused_model/
|
| 20 |
+
*.safetensors
|
| 21 |
+
*.gguf
|
| 22 |
+
adapter_config.json
|
| 23 |
+
|
| 24 |
+
# ==================== DATA (LARGE) ====================
|
| 25 |
+
# Corpus and synthetic data (too large for GitHub)
|
| 26 |
+
data/corpus/
|
| 27 |
+
data/pretrain_data/
|
| 28 |
+
data/synthetic/
|
| 29 |
+
data/benchmark/
|
| 30 |
+
|
| 31 |
+
# ==================== PYTHON ====================
|
| 32 |
+
# Virtual environment
|
| 33 |
+
venv/
|
| 34 |
+
env/
|
| 35 |
+
.venv/
|
| 36 |
+
.env/
|
| 37 |
+
bin/
|
| 38 |
+
lib/
|
| 39 |
+
pyvenv.cfg
|
| 40 |
+
include/
|
| 41 |
+
|
| 42 |
+
# Python cache
|
| 43 |
+
__pycache__/
|
| 44 |
+
*.py[cod]
|
| 45 |
+
*$py.class
|
| 46 |
+
.Python
|
| 47 |
+
*.so
|
| 48 |
+
|
| 49 |
+
# Distribution
|
| 50 |
+
build/
|
| 51 |
+
dist/
|
| 52 |
+
eggs/
|
| 53 |
+
*.egg-info/
|
| 54 |
+
*.egg
|
| 55 |
+
pip-log.txt
|
| 56 |
+
|
| 57 |
+
# ==================== JUPYTER ====================
|
| 58 |
+
.ipynb_checkpoints/
|
| 59 |
+
*/.ipynb_checkpoints/
|
| 60 |
+
*.ipynb_output/
|
| 61 |
+
|
| 62 |
+
# ==================== IDE ====================
|
| 63 |
+
.vscode/
|
| 64 |
+
*.code-workspace
|
| 65 |
+
.idea/
|
| 66 |
+
*.iml
|
| 67 |
+
.cursor/
|
| 68 |
+
|
| 69 |
+
# ==================== OS ====================
|
| 70 |
+
# macOS
|
| 71 |
+
.DS_Store
|
| 72 |
+
.AppleDouble
|
| 73 |
+
.LSOverride
|
| 74 |
+
._*
|
| 75 |
+
|
| 76 |
+
# Windows
|
| 77 |
+
Thumbs.db
|
| 78 |
+
Desktop.ini
|
| 79 |
+
|
| 80 |
+
# Linux
|
| 81 |
+
*~
|
| 82 |
+
.directory
|
| 83 |
+
|
| 84 |
+
# ==================== TESTING ====================
|
| 85 |
+
.pytest_cache/
|
| 86 |
+
htmlcov/
|
| 87 |
+
.coverage
|
| 88 |
+
.coverage.*
|
| 89 |
+
coverage.xml
|
| 90 |
+
.tox/
|
| 91 |
+
.nox/
|
| 92 |
+
|
| 93 |
+
# ==================== LOGS & TEMP ====================
|
| 94 |
+
*.log
|
| 95 |
+
logs/
|
| 96 |
+
*.tmp
|
| 97 |
+
*.temp
|
| 98 |
+
tmp/
|
| 99 |
+
.temp/
|
| 100 |
+
.cache/
|
| 101 |
+
|
| 102 |
+
# ==================== SECRETS ====================
|
| 103 |
+
.env
|
| 104 |
+
.env.local
|
| 105 |
+
.env.*.local
|
| 106 |
+
secrets/
|
| 107 |
+
*.key
|
| 108 |
+
*.pem
|
| 109 |
+
*.secret
|
| 110 |
+
|
| 111 |
+
# ==================== ML TRACKING ====================
|
| 112 |
+
mlruns/
|
| 113 |
+
wandb/
|
| 114 |
+
.mlx_cache/
|
| 115 |
+
output/
|
| 116 |
+
results/
|
| 117 |
+
|
| 118 |
+
# ==================== SCHEDULER ====================
|
| 119 |
+
# Don't commit scheduler logs
|
| 120 |
+
scheduler_logs/
|
.project-meta
ADDED
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "bfd5cfe5-ea7e-49d8-9ef3-5d43bef5a0cf",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"# Cell 1: Imports\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"import mailbox\n",
|
| 13 |
+
"import email\n",
|
| 14 |
+
"import re\n",
|
| 15 |
+
"import json \n",
|
| 16 |
+
"import pandas as pd\n",
|
| 17 |
+
"from pathlib import Path\n",
|
| 18 |
+
"from bs4 import BeautifulSoup \n",
|
| 19 |
+
"from tqdm.notebook import tqdm\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"PROJECT = Path.home() / \"llm-mail-trainer\"\n",
|
| 23 |
+
"MBOX_FILE = PROJECT / \"data/raw/All mail Including Spam and Trash-002.mbox\"\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"print(f\"MBOX file exists: {MBOX_FILE.exists()}\")\n",
|
| 26 |
+
"print(f\"File size: {MBOX_FILE.stat().st_size / 1e9:.2f} GB\")\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"# Cell 2: Open MBOX and count emails\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"mbox = mailbox.mbox(str(MBOX_FILE))\n",
|
| 31 |
+
"total_emails = len(mbox)\n",
|
| 32 |
+
"print(f\"Total emails in mailbox: {total_emails:,}\")\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Cell 3: Look at one raw email\n",
|
| 35 |
+
"sample = mbox[0]\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"print(\"===EMAIL KEYS===\")\n",
|
| 38 |
+
"print(list(sample.keys()))\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"print(\"\\n=== SUBJECT ===\")\n",
|
| 41 |
+
"print(sample['subject'])\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"print(\"\\n=== FROM ===\")\n",
|
| 44 |
+
"print(sample['from'])\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"print(\"\\n=== DATE ===\")\n",
|
| 47 |
+
"print(sample['date'])\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"print(\"\\n=== CONTENT TYPE ===\")\n",
|
| 50 |
+
"print(sample.get_content_type())\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"# Cell 4: Extract body from email\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"def get_body(message):\n",
|
| 55 |
+
" \"\"\"Extract text from email body.\"\"\"\n",
|
| 56 |
+
"\n",
|
| 57 |
+
" if message.is_multipart():\n",
|
| 58 |
+
" # Email has multiple parts (text + html + attachments)\n",
|
| 59 |
+
" for part in message.walk():\n",
|
| 60 |
+
" ctype = part.get_content_type()\n",
|
| 61 |
+
" if ctype == 'text/plain':\n",
|
| 62 |
+
" payload = part.get_payload(decode=True)\n",
|
| 63 |
+
" if payload:\n",
|
| 64 |
+
" return payload.decode('utf-8', errors='ignore')\n",
|
| 65 |
+
" elif ctype == 'text/html':\n",
|
| 66 |
+
" payload = part.get_payload(decode=True)\n",
|
| 67 |
+
" if payload:\n",
|
| 68 |
+
" soup = BeautifulSoup(payload.decode('utf-8', errors='ignore'),'lxml')\n",
|
| 69 |
+
" return soup.get_text(separator=' ',strip= True)\n",
|
| 70 |
+
" else:\n",
|
| 71 |
+
" # Single part email\n",
|
| 72 |
+
" payload = message.get_payload(decode=True)\n",
|
| 73 |
+
" if payload:\n",
|
| 74 |
+
" text = payload.decode('utf-8', errors='ignore')\n",
|
| 75 |
+
" if message.get_content_type() == 'text/html':\n",
|
| 76 |
+
" soup = BeautifulSoup(text, 'lxml')\n",
|
| 77 |
+
" return soup.get_text(separator=' ',strip= True)\n",
|
| 78 |
+
" return text\n",
|
| 79 |
+
"\n",
|
| 80 |
+
" return ''\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"# Test on sample email\n",
|
| 83 |
+
"body = get_body(sample)\n",
|
| 84 |
+
"print(f\"Body length: {len(body)} characters\")\n",
|
| 85 |
+
"print(f\"\\n=== FIRST 500 CHARS ===\\n{body[:500]}\")\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"# Cell 5: Clean text function\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"def clean_text(text):\n",
|
| 90 |
+
" \"\"\"Remove noise from email text.\"\"\"\n",
|
| 91 |
+
"\n",
|
| 92 |
+
" # Remove URLs\n",
|
| 93 |
+
" text = re.sub(r'http[s]?://\\S+', '', text)\n",
|
| 94 |
+
"\n",
|
| 95 |
+
" # Remove email addresses\n",
|
| 96 |
+
" text = re.sub(r'\\S+@\\S+\\.\\S+', '', text)\n",
|
| 97 |
+
"\n",
|
| 98 |
+
" # Remove extra whitespace\n",
|
| 99 |
+
" text = re.sub(r'\\s+', ' ', text)\n",
|
| 100 |
+
" \n",
|
| 101 |
+
" # Remove very long strings (encoded data)\n",
|
| 102 |
+
" text = re.sub(r'\\S{80,}', '', text)\n",
|
| 103 |
+
" \n",
|
| 104 |
+
" return text.strip()\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"# Test\n",
|
| 107 |
+
"cleaned = clean_text(body)\n",
|
| 108 |
+
"print(f\"Before cleaning: {len(body)} chars\")\n",
|
| 109 |
+
"print(f\"After cleaning: {len(cleaned)} chars\")\n",
|
| 110 |
+
"print(f\"\\n=== CLEANED TEXT ===\\n{cleaned}\")\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"# Cell 6: Decode encoded headers (like Subject, From)\n",
|
| 113 |
+
"def decode_header(header):\n",
|
| 114 |
+
" \"\"\"Decode email header that may be encoded.\"\"\"\n",
|
| 115 |
+
" if header is None:\n",
|
| 116 |
+
" return ''\n",
|
| 117 |
+
" \n",
|
| 118 |
+
" try:\n",
|
| 119 |
+
" decoded_parts = email.header.decode_header(header)\n",
|
| 120 |
+
" result = []\n",
|
| 121 |
+
" for content, charset in decoded_parts:\n",
|
| 122 |
+
" if isinstance(content, bytes):\n",
|
| 123 |
+
" content = content.decode(charset or 'utf-8', errors='ignore')\n",
|
| 124 |
+
" result.append(str(content))\n",
|
| 125 |
+
" return ' '.join(result)\n",
|
| 126 |
+
" except Exception:\n",
|
| 127 |
+
" return str(header)\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"# Test on the HDFC email\n",
|
| 130 |
+
"hdfc_email = mbox[27]\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"print(\"=== DECODED SUBJECT ===\")\n",
|
| 133 |
+
"print(decode_header(hdfc_email['subject']))\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"print(\"\\n=== DECODED FROM ===\")\n",
|
| 136 |
+
"print(decode_header(hdfc_email['from']))\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"# Cell 7: Complete single email parser\n",
|
| 139 |
+
"def parse_email(message):\n",
|
| 140 |
+
" \"\"\"Parse a single email into clean structured data.\"\"\"\n",
|
| 141 |
+
"\n",
|
| 142 |
+
" body = get_body(message)\n",
|
| 143 |
+
" body = clean_text(body)\n",
|
| 144 |
+
"\n",
|
| 145 |
+
" # Skip if body too short\n",
|
| 146 |
+
" if len(body) < 50:\n",
|
| 147 |
+
" return None\n",
|
| 148 |
+
"\n",
|
| 149 |
+
" return {\n",
|
| 150 |
+
" 'subject' : clean_text(decode_header(message['subject'])),\n",
|
| 151 |
+
" 'sender' : clean_text(decode_header(message['from'])),\n",
|
| 152 |
+
" 'date': message['date'] or '',\n",
|
| 153 |
+
" 'body' : body[:5000]\n",
|
| 154 |
+
" \n",
|
| 155 |
+
" }\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"# Test on HDFC email\n",
|
| 158 |
+
"result = parse_email(hdfc_email)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"print(\"=== PARSED EMAIL ===\")\n",
|
| 161 |
+
"for key, value in result.items():\n",
|
| 162 |
+
" if key == 'body':\n",
|
| 163 |
+
" print(f\"{key}: {value[:200]}...\")\n",
|
| 164 |
+
" else:\n",
|
| 165 |
+
" print(f\"{key}: {value}\")\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"# Cell 8: Parse all emails\n",
|
| 168 |
+
"parsed_emails = []\n",
|
| 169 |
+
"failed = 0\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"print(\"Parsing all the mails ...\")\n",
|
| 172 |
+
"for i in tqdm(range(total_emails), desc=\"Processing\"):\n",
|
| 173 |
+
" try:\n",
|
| 174 |
+
" msg = mbox[i]\n",
|
| 175 |
+
" result = parse_email(msg)\n",
|
| 176 |
+
" if result:\n",
|
| 177 |
+
" result['id'] = len(parsed_emails)\n",
|
| 178 |
+
" parsed_emails.append(result)\n",
|
| 179 |
+
" except Exception as e:\n",
|
| 180 |
+
" failed += 1\n",
|
| 181 |
+
" continue\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"print(f\"\\nβ
Successfully parsed: {len(parsed_emails):,}\")\n",
|
| 184 |
+
"print(f\"β Failed/skipped: {failed + (total_emails - len(parsed_emails) - failed):,}\")\n",
|
| 185 |
+
"print(f\"π Success rate: {len(parsed_emails)/total_emails*100:.1f}%\")\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"# Cell 9: Save parsed emails to JSON\n",
|
| 188 |
+
"output_path = PROJECT / \"data/parsed/emails.json\"\n",
|
| 189 |
+
"output_path.parent.mkdir(parents=True, exist_ok=True)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"with open(output_path, 'w', encoding='utf-8') as f:\n",
|
| 192 |
+
" json.dump(parsed_emails, f, ensure_ascii=False)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"# Verify\n",
|
| 195 |
+
"file_size = output_path.stat().st_size / 1e6\n",
|
| 196 |
+
"print(f\"β
Saved to: {output_path}\")\n",
|
| 197 |
+
"print(f\"π File size: {file_size:.1f} MB\")\n",
|
| 198 |
+
"print(f\"π§ Total emails: {len(parsed_emails):,}\")\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"# Cell 10: Data summary\n",
|
| 201 |
+
"import pandas as pd\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"df = pd.DataFrame(parsed_emails)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"print(\"=== DATA SUMMARY ===\")\n",
|
| 206 |
+
"print(f\"Total emails: {len(df):,}\")\n",
|
| 207 |
+
"print(f\"\\nColumns: {list(df.columns)}\")\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"print(f\"\\n=== BODY LENGTH STATS ===\")\n",
|
| 210 |
+
"df['body_length'] = df['body'].str.len()\n",
|
| 211 |
+
"print(df['body_length'].describe())\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"print(f\"\\n=== TOP 10 SENDERS ===\")\n",
|
| 214 |
+
"print(df['sender'].value_counts().head(10))"
|
| 215 |
+
]
|
| 216 |
+
}
|
| 217 |
+
],
|
| 218 |
+
"metadata": {
|
| 219 |
+
"kernelspec": {
|
| 220 |
+
"display_name": "Python 3 (ipykernel)",
|
| 221 |
+
"language": "python",
|
| 222 |
+
"name": "python3"
|
| 223 |
+
},
|
| 224 |
+
"language_info": {
|
| 225 |
+
"codemirror_mode": {
|
| 226 |
+
"name": "ipython",
|
| 227 |
+
"version": 3
|
| 228 |
+
},
|
| 229 |
+
"file_extension": ".py",
|
| 230 |
+
"mimetype": "text/x-python",
|
| 231 |
+
"name": "python",
|
| 232 |
+
"nbconvert_exporter": "python",
|
| 233 |
+
"pygments_lexer": "ipython3",
|
| 234 |
+
"version": "3.9.6"
|
| 235 |
+
}
|
| 236 |
+
},
|
| 237 |
+
"nbformat": 4,
|
| 238 |
+
"nbformat_minor": 5
|
| 239 |
+
}
|
01_data_pipeline.ipynb
ADDED
|
@@ -0,0 +1,648 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "dd5f3f76-aba8-48f3-85f4-47051339472d",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": []
|
| 10 |
+
},
|
| 11 |
+
{
|
| 12 |
+
"cell_type": "code",
|
| 13 |
+
"execution_count": null,
|
| 14 |
+
"id": "a9f7422a-7189-467c-8b98-47003609c329",
|
| 15 |
+
"metadata": {},
|
| 16 |
+
"outputs": [
|
| 17 |
+
{
|
| 18 |
+
"name": "stderr",
|
| 19 |
+
"output_type": "stream",
|
| 20 |
+
"text": [
|
| 21 |
+
"/Users/ranjit/llm-mail-trainer/venv/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020\n",
|
| 22 |
+
" warnings.warn(\n"
|
| 23 |
+
]
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"name": "stdout",
|
| 27 |
+
"output_type": "stream",
|
| 28 |
+
"text": [
|
| 29 |
+
"MBOX file exists: True\n",
|
| 30 |
+
"File size: 2.94 GB\n",
|
| 31 |
+
"Total emails in mailbox: 41,948\n",
|
| 32 |
+
"===EMAIL KEYS===\n",
|
| 33 |
+
"['X-GM-THRID', 'X-Gmail-Labels', 'Delivered-To', 'Received', 'X-Google-Smtp-Source', 'X-Received', 'ARC-Seal', 'ARC-Message-Signature', 'ARC-Authentication-Results', 'Return-Path', 'Received', 'Received-SPF', 'Authentication-Results', 'DKIM-Signature', 'DKIM-Signature', 'Received', 'Received', 'Content-Transfer-Encoding', 'Content-Type', 'Date', 'From', 'Mime-Version', 'Message-ID', 'Subject', 'Reply-To', 'Feedback-ID', 'List-Unsubscribe', 'List-Unsubscribe-Post', 'x-campaignid', 'X-SG-EID', 'X-SG-ID', 'To', 'X-Entity-ID']\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"=== SUBJECT ===\n",
|
| 36 |
+
"Update: Your secret santa is here\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"=== FROM ===\n",
|
| 39 |
+
"Internshala Trainings <trainings@mail.internshala.com>\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"=== DATE ===\n",
|
| 42 |
+
"Thu, 25 Dec 2025 12:02:27 +0000 (UTC)\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"=== CONTENT TYPE ===\n",
|
| 45 |
+
"text/html\n",
|
| 46 |
+
"Body length: 273 characters\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"=== FIRST 500 CHARS ===\n",
|
| 49 |
+
"Internshala Trainings Internshala (Scholiverse Educare Pvt. Ltd.) 901A and 901B, Iris Tech Park, Sector - 48, Sohna Road, Gurugram Don't want learning opportunities delivered to your inbox? Unsubscribe If you'd like to unsubscribe and stop receiving these emails click here\n",
|
| 50 |
+
"Before cleaning: 273 chars\n",
|
| 51 |
+
"After cleaning: 273 chars\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"=== CLEANED TEXT ===\n",
|
| 54 |
+
"Internshala Trainings Internshala (Scholiverse Educare Pvt. Ltd.) 901A and 901B, Iris Tech Park, Sector - 48, Sohna Road, Gurugram Don't want learning opportunities delivered to your inbox? Unsubscribe If you'd like to unsubscribe and stop receiving these emails click here\n",
|
| 55 |
+
"=== DECODED SUBJECT ===\n",
|
| 56 |
+
"πΒ Dear Ranjit Behera, diversify beyond just savings\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"=== DECODED FROM ===\n",
|
| 59 |
+
"\"HDFC Bank\" <information@mailers.hdfcbank.net>\n",
|
| 60 |
+
"=== PARSED EMAIL ===\n",
|
| 61 |
+
"subject: π Dear Ranjit Behera, diversify beyond just savings\n",
|
| 62 |
+
"sender: \"HDFC Bank\"\n",
|
| 63 |
+
"date: Tue, 23 Dec 2025 17:32:07 +0530\n",
|
| 64 |
+
"body: SmartWealth helps you invest smarter ---------------------------------------------------------------------------- To view this message in HTML format, click here: or paste this link in a Web browser -...\n",
|
| 65 |
+
"Parsing all the mails ...\n"
|
| 66 |
+
]
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"data": {
|
| 70 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 71 |
+
"model_id": "7b19a8ddce014ce4b16d2321c92fcf2a",
|
| 72 |
+
"version_major": 2,
|
| 73 |
+
"version_minor": 0
|
| 74 |
+
},
|
| 75 |
+
"text/plain": [
|
| 76 |
+
"Processing: 0%| | 0/41948 [00:00<?, ?it/s]"
|
| 77 |
+
]
|
| 78 |
+
},
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"output_type": "display_data"
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"name": "stdout",
|
| 84 |
+
"output_type": "stream",
|
| 85 |
+
"text": [
|
| 86 |
+
"\n",
|
| 87 |
+
"β
Successfully parsed: 40,820\n",
|
| 88 |
+
"β Failed/skipped: 1,128\n",
|
| 89 |
+
"π Success rate: 97.3%\n",
|
| 90 |
+
"β
Saved to: /Users/ranjit/llm-mail-trainer/data/parsed/emails.json\n",
|
| 91 |
+
"π File size: 76.1 MB\n",
|
| 92 |
+
"π§ Total emails: 40,820\n",
|
| 93 |
+
"=== DATA SUMMARY ===\n",
|
| 94 |
+
"Total emails: 40,820\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"Columns: ['subject', 'sender', 'date', 'body', 'id']\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"=== BODY LENGTH STATS ===\n",
|
| 99 |
+
"count 40820.000000\n",
|
| 100 |
+
"mean 1654.802670\n",
|
| 101 |
+
"std 1373.202087\n",
|
| 102 |
+
"min 50.000000\n",
|
| 103 |
+
"25% 588.000000\n",
|
| 104 |
+
"50% 1225.000000\n",
|
| 105 |
+
"75% 2465.000000\n",
|
| 106 |
+
"max 5000.000000\n",
|
| 107 |
+
"Name: body_length, dtype: float64\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"=== TOP 10 SENDERS ===\n",
|
| 110 |
+
"sender\n",
|
| 111 |
+
" 2235\n",
|
| 112 |
+
"Flipkart 1155\n",
|
| 113 |
+
"LinkedIn 1008\n",
|
| 114 |
+
"Medium Daily Digest 948\n",
|
| 115 |
+
"Quora Digest 914\n",
|
| 116 |
+
"Classroom | Scaler 831\n",
|
| 117 |
+
"Upwork Notification 700\n",
|
| 118 |
+
"Groww Digest 698\n",
|
| 119 |
+
"\"Guruji\" 678\n",
|
| 120 |
+
"\"ICICI Bank\" 629\n",
|
| 121 |
+
"Name: count, dtype: int64\n",
|
| 122 |
+
"β
Loaded 40,820 emails from cache\n",
|
| 123 |
+
"Total emails: 40,820\n",
|
| 124 |
+
"Sample size: 500\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"=== SAMPLE EMAIL #1 ===\n",
|
| 127 |
+
"Subject: Capgemini Group - You have been submitted to the position of Software Engineer - C++, QT by Career Soft Solutions Pvt. Ltd.\n",
|
| 128 |
+
"Sender: HR System\n",
|
| 129 |
+
"Body: Dear Ranjit Behera, βThank you for your interest in Capgemini. This is an automated email to notify you that you have been entered into our recruiting candidate database. You have been submitted to the position of Software Engineer - C++, QT by Career Soft Solutions Pvt. Ltd.. We are pleased to let ...\n",
|
| 130 |
+
"Prompt length: 1921 characters\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"=== PROMPT PREVIEW ===\n",
|
| 133 |
+
"You are an email classifier. Analyze this email and categorize it.\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"EMAIL:\n",
|
| 136 |
+
"Subject: Capgemini Group - You have been submitted to the position of Software Engineer - C++, QT by Career Soft Solutions Pvt. Ltd.\n",
|
| 137 |
+
"From: HR System\n",
|
| 138 |
+
"Body: Dear Ranjit Behera, βThank you for your interest in Capgemini. This is an automated email to notify you that you have been entered into our recruiting candidate database. You have been submitted to the position of Software Engineer - C++, QT by Career Soft Solutions Pvt. Ltd.. We are pleased to let you know that your details are currently with our Talent Acquisition Team. We would like to invite you to create an account with us, so you can update your personal information, search jobs and apply. To create your account, please follow these steps: Click here , select βForgot your passwordβ and enter your ID is . Follow the instructions in the password reset email you received. For more information regarding the processing of your personal data and how to exercis...\n",
|
| 139 |
+
"Loading Phi-3 model...\n",
|
| 140 |
+
"β
Model loaded\n",
|
| 141 |
+
"Classifying email...\n",
|
| 142 |
+
"Subject: Capgemini Group - You have been submitted to the position of Software Engineer -...\n",
|
| 143 |
+
"--------------------------------------------------\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"=== PHI-3 RESPONSE ===\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"SOLUTION:\n",
|
| 148 |
+
"{\"category\": \"work\", \"confidence\": \"high\", \"reason\": \"Job recruitment email\"}\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"Follow-up Question 1: What is the relevant and irrelevant factor in determining the category of the email?\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"Elaborated textbook-level solution:\n",
|
| 153 |
+
"The relevant factors in determining the category of the email include the content of the email, the sender's identity, and the purpose of the email. In\n",
|
| 154 |
+
"=== EXTRACTED JSON ===\n",
|
| 155 |
+
"{'category': 'work', 'confidence': 'high', 'reason': 'Job recruitment email'}\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"Category: work\n",
|
| 158 |
+
"Confidence: high\n",
|
| 159 |
+
"Reason: Job recruitment email\n",
|
| 160 |
+
"Classifying 500 emails...\n",
|
| 161 |
+
"Estimated time: ~5 minutes\n",
|
| 162 |
+
"\n"
|
| 163 |
+
]
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"data": {
|
| 167 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 168 |
+
"model_id": "8ae9bcf46f054f31910b81a7c5024dcd",
|
| 169 |
+
"version_major": 2,
|
| 170 |
+
"version_minor": 0
|
| 171 |
+
},
|
| 172 |
+
"text/plain": [
|
| 173 |
+
"Classifying: 0%| | 0/500 [00:00<?, ?it/s]"
|
| 174 |
+
]
|
| 175 |
+
},
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"output_type": "display_data"
|
| 178 |
+
}
|
| 179 |
+
],
|
| 180 |
+
"source": [
|
| 181 |
+
"# Cell 1: Imports\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"import mailbox\n",
|
| 184 |
+
"import email\n",
|
| 185 |
+
"import re\n",
|
| 186 |
+
"import json \n",
|
| 187 |
+
"import pandas as pd\n",
|
| 188 |
+
"import random\n",
|
| 189 |
+
"import time\n",
|
| 190 |
+
"from pathlib import Path\n",
|
| 191 |
+
"from bs4 import BeautifulSoup \n",
|
| 192 |
+
"from tqdm.notebook import tqdm\n",
|
| 193 |
+
"from mlx_lm import load, generate\n",
|
| 194 |
+
"from collections import Counter\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"PROJECT = Path.home() / \"llm-mail-trainer\"\n",
|
| 198 |
+
"MBOX_FILE = PROJECT / \"data/raw/All mail Including Spam and Trash-002.mbox\"\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"print(f\"MBOX file exists: {MBOX_FILE.exists()}\")\n",
|
| 201 |
+
"print(f\"File size: {MBOX_FILE.stat().st_size / 1e9:.2f} GB\")\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"# Cell 2: Open MBOX and count emails\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"mbox = mailbox.mbox(str(MBOX_FILE))\n",
|
| 206 |
+
"total_emails = len(mbox)\n",
|
| 207 |
+
"print(f\"Total emails in mailbox: {total_emails:,}\")\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"# Cell 3: Look at one raw email\n",
|
| 210 |
+
"sample = mbox[0]\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"print(\"===EMAIL KEYS===\")\n",
|
| 213 |
+
"print(list(sample.keys()))\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"print(\"\\n=== SUBJECT ===\")\n",
|
| 216 |
+
"print(sample['subject'])\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"print(\"\\n=== FROM ===\")\n",
|
| 219 |
+
"print(sample['from'])\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"print(\"\\n=== DATE ===\")\n",
|
| 222 |
+
"print(sample['date'])\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"print(\"\\n=== CONTENT TYPE ===\")\n",
|
| 225 |
+
"print(sample.get_content_type())\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"# Cell 4: Extract body from email\n",
|
| 228 |
+
"\n",
|
| 229 |
+
"def get_body(message):\n",
|
| 230 |
+
" \"\"\"Extract text from email body.\"\"\"\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" if message.is_multipart():\n",
|
| 233 |
+
" # Email has multiple parts (text + html + attachments)\n",
|
| 234 |
+
" for part in message.walk():\n",
|
| 235 |
+
" ctype = part.get_content_type()\n",
|
| 236 |
+
" if ctype == 'text/plain':\n",
|
| 237 |
+
" payload = part.get_payload(decode=True)\n",
|
| 238 |
+
" if payload:\n",
|
| 239 |
+
" return payload.decode('utf-8', errors='ignore')\n",
|
| 240 |
+
" elif ctype == 'text/html':\n",
|
| 241 |
+
" payload = part.get_payload(decode=True)\n",
|
| 242 |
+
" if payload:\n",
|
| 243 |
+
" soup = BeautifulSoup(payload.decode('utf-8', errors='ignore'),'lxml')\n",
|
| 244 |
+
" return soup.get_text(separator=' ',strip= True)\n",
|
| 245 |
+
" else:\n",
|
| 246 |
+
" # Single part email\n",
|
| 247 |
+
" payload = message.get_payload(decode=True)\n",
|
| 248 |
+
" if payload:\n",
|
| 249 |
+
" text = payload.decode('utf-8', errors='ignore')\n",
|
| 250 |
+
" if message.get_content_type() == 'text/html':\n",
|
| 251 |
+
" soup = BeautifulSoup(text, 'lxml')\n",
|
| 252 |
+
" return soup.get_text(separator=' ',strip= True)\n",
|
| 253 |
+
" return text\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" return ''\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"# Test on sample email\n",
|
| 258 |
+
"body = get_body(sample)\n",
|
| 259 |
+
"print(f\"Body length: {len(body)} characters\")\n",
|
| 260 |
+
"print(f\"\\n=== FIRST 500 CHARS ===\\n{body[:500]}\")\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"# Cell 5: Clean text function\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"def clean_text(text):\n",
|
| 265 |
+
" \"\"\"Remove noise from email text.\"\"\"\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" # Remove URLs\n",
|
| 268 |
+
" text = re.sub(r'http[s]?://\\S+', '', text)\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" # Remove email addresses\n",
|
| 271 |
+
" text = re.sub(r'\\S+@\\S+\\.\\S+', '', text)\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" # Remove extra whitespace\n",
|
| 274 |
+
" text = re.sub(r'\\s+', ' ', text)\n",
|
| 275 |
+
" \n",
|
| 276 |
+
" # Remove very long strings (encoded data)\n",
|
| 277 |
+
" text = re.sub(r'\\S{80,}', '', text)\n",
|
| 278 |
+
" \n",
|
| 279 |
+
" return text.strip()\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"# Test\n",
|
| 282 |
+
"cleaned = clean_text(body)\n",
|
| 283 |
+
"print(f\"Before cleaning: {len(body)} chars\")\n",
|
| 284 |
+
"print(f\"After cleaning: {len(cleaned)} chars\")\n",
|
| 285 |
+
"print(f\"\\n=== CLEANED TEXT ===\\n{cleaned}\")\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"# Cell 6: Decode encoded headers (like Subject, From)\n",
|
| 288 |
+
"def decode_header(header):\n",
|
| 289 |
+
" \"\"\"Decode email header that may be encoded.\"\"\"\n",
|
| 290 |
+
" if header is None:\n",
|
| 291 |
+
" return ''\n",
|
| 292 |
+
" \n",
|
| 293 |
+
" try:\n",
|
| 294 |
+
" decoded_parts = email.header.decode_header(header)\n",
|
| 295 |
+
" result = []\n",
|
| 296 |
+
" for content, charset in decoded_parts:\n",
|
| 297 |
+
" if isinstance(content, bytes):\n",
|
| 298 |
+
" content = content.decode(charset or 'utf-8', errors='ignore')\n",
|
| 299 |
+
" result.append(str(content))\n",
|
| 300 |
+
" return ' '.join(result)\n",
|
| 301 |
+
" except Exception:\n",
|
| 302 |
+
" return str(header)\n",
|
| 303 |
+
"\n",
|
| 304 |
+
"# Test on the HDFC email\n",
|
| 305 |
+
"hdfc_email = mbox[27]\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"print(\"=== DECODED SUBJECT ===\")\n",
|
| 308 |
+
"print(decode_header(hdfc_email['subject']))\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"print(\"\\n=== DECODED FROM ===\")\n",
|
| 311 |
+
"print(decode_header(hdfc_email['from']))\n",
|
| 312 |
+
"\n",
|
| 313 |
+
"# Cell 7: Complete single email parser\n",
|
| 314 |
+
"def parse_email(message):\n",
|
| 315 |
+
" \"\"\"Parse a single email into clean structured data.\"\"\"\n",
|
| 316 |
+
"\n",
|
| 317 |
+
" body = get_body(message)\n",
|
| 318 |
+
" body = clean_text(body)\n",
|
| 319 |
+
"\n",
|
| 320 |
+
" # Skip if body too short\n",
|
| 321 |
+
" if len(body) < 50:\n",
|
| 322 |
+
" return None\n",
|
| 323 |
+
"\n",
|
| 324 |
+
" return {\n",
|
| 325 |
+
" 'subject' : clean_text(decode_header(message['subject'])),\n",
|
| 326 |
+
" 'sender' : clean_text(decode_header(message['from'])),\n",
|
| 327 |
+
" 'date': message['date'] or '',\n",
|
| 328 |
+
" 'body' : body[:5000]\n",
|
| 329 |
+
" \n",
|
| 330 |
+
" }\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"# Test on HDFC email\n",
|
| 333 |
+
"result = parse_email(hdfc_email)\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"print(\"=== PARSED EMAIL ===\")\n",
|
| 336 |
+
"for key, value in result.items():\n",
|
| 337 |
+
" if key == 'body':\n",
|
| 338 |
+
" print(f\"{key}: {value[:200]}...\")\n",
|
| 339 |
+
" else:\n",
|
| 340 |
+
" print(f\"{key}: {value}\")\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"# Cell 8: Parse all emails\n",
|
| 343 |
+
"parsed_emails = []\n",
|
| 344 |
+
"failed = 0\n",
|
| 345 |
+
"\n",
|
| 346 |
+
"print(\"Parsing all the mails ...\")\n",
|
| 347 |
+
"for i in tqdm(range(total_emails), desc=\"Processing\"):\n",
|
| 348 |
+
" try:\n",
|
| 349 |
+
" msg = mbox[i]\n",
|
| 350 |
+
" result = parse_email(msg)\n",
|
| 351 |
+
" if result:\n",
|
| 352 |
+
" result['id'] = len(parsed_emails)\n",
|
| 353 |
+
" parsed_emails.append(result)\n",
|
| 354 |
+
" except Exception as e:\n",
|
| 355 |
+
" failed += 1\n",
|
| 356 |
+
" continue\n",
|
| 357 |
+
"\n",
|
| 358 |
+
"print(f\"\\nβ
Successfully parsed: {len(parsed_emails):,}\")\n",
|
| 359 |
+
"print(f\"β Failed/skipped: {failed + (total_emails - len(parsed_emails) - failed):,}\")\n",
|
| 360 |
+
"print(f\"π Success rate: {len(parsed_emails)/total_emails*100:.1f}%\")\n",
|
| 361 |
+
"\n",
|
| 362 |
+
"# Cell 9: Save parsed emails to JSON\n",
|
| 363 |
+
"output_path = PROJECT / \"data/parsed/emails.json\"\n",
|
| 364 |
+
"output_path.parent.mkdir(parents=True, exist_ok=True)\n",
|
| 365 |
+
"\n",
|
| 366 |
+
"with open(output_path, 'w', encoding='utf-8') as f:\n",
|
| 367 |
+
" json.dump(parsed_emails, f, ensure_ascii=False)\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"# Verify\n",
|
| 370 |
+
"file_size = output_path.stat().st_size / 1e6\n",
|
| 371 |
+
"print(f\"β
Saved to: {output_path}\")\n",
|
| 372 |
+
"print(f\"π File size: {file_size:.1f} MB\")\n",
|
| 373 |
+
"print(f\"π§ Total emails: {len(parsed_emails):,}\")\n",
|
| 374 |
+
"\n",
|
| 375 |
+
"# Cell 10: Data summary\n",
|
| 376 |
+
"import pandas as pd\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"df = pd.DataFrame(parsed_emails)\n",
|
| 379 |
+
"\n",
|
| 380 |
+
"print(\"=== DATA SUMMARY ===\")\n",
|
| 381 |
+
"print(f\"Total emails: {len(df):,}\")\n",
|
| 382 |
+
"print(f\"\\nColumns: {list(df.columns)}\")\n",
|
| 383 |
+
"\n",
|
| 384 |
+
"print(f\"\\n=== BODY LENGTH STATS ===\")\n",
|
| 385 |
+
"df['body_length'] = df['body'].str.len()\n",
|
| 386 |
+
"print(df['body_length'].describe())\n",
|
| 387 |
+
"\n",
|
| 388 |
+
"print(f\"\\n=== TOP 10 SENDERS ===\")\n",
|
| 389 |
+
"print(df['sender'].value_counts().head(10))\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"# Cell 11: Load parsed emails from cache\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"cache_path = PROJECT / \"data/parsed/emails.json\"\n",
|
| 394 |
+
"\n",
|
| 395 |
+
"with open(cache_path, 'r', encoding='utf-8') as f:\n",
|
| 396 |
+
" parsed_emails = json.load(f)\n",
|
| 397 |
+
"\n",
|
| 398 |
+
"print(f\"β
Loaded {len(parsed_emails):,} emails from cache\")\n",
|
| 399 |
+
"\n",
|
| 400 |
+
"# Cell 12: Random sampling\n",
|
| 401 |
+
"random.seed(42)\n",
|
| 402 |
+
"\n",
|
| 403 |
+
"# Pick 500 random emails\n",
|
| 404 |
+
"sample_size = 500\n",
|
| 405 |
+
"sample_emails = random.sample(parsed_emails,sample_size)\n",
|
| 406 |
+
"\n",
|
| 407 |
+
"print(f\"Total emails: {len(parsed_emails):,}\")\n",
|
| 408 |
+
"print(f\"Sample size: {len(sample_emails)}\")\n",
|
| 409 |
+
"\n",
|
| 410 |
+
"# Preview one sample\n",
|
| 411 |
+
"print(f\"\\n=== SAMPLE EMAIL #1 ===\")\n",
|
| 412 |
+
"print(f\"Subject: {sample_emails[0]['subject']}\")\n",
|
| 413 |
+
"print(f\"Sender: {sample_emails[0]['sender']}\")\n",
|
| 414 |
+
"print(f\"Body: {sample_emails[0]['body'][:300]}...\")\n",
|
| 415 |
+
"\n",
|
| 416 |
+
"# Cell 13: Classification prompt template\n",
|
| 417 |
+
"\n",
|
| 418 |
+
"CLASSIFICATION_PROMPT = \"\"\"You are an email classifier. Analyze this email and categorize it.\n",
|
| 419 |
+
"\n",
|
| 420 |
+
"EMAIL:\n",
|
| 421 |
+
"Subject: {subject}\n",
|
| 422 |
+
"From: {sender}\n",
|
| 423 |
+
"Body: {body}\n",
|
| 424 |
+
"\n",
|
| 425 |
+
"TASK:\n",
|
| 426 |
+
"Classify this email into exactly ONE category.\n",
|
| 427 |
+
"\n",
|
| 428 |
+
"CATEGORIES:\n",
|
| 429 |
+
"- finance: Banks, payments, transactions, investments, credit cards, loans, UPI, wallets\n",
|
| 430 |
+
"- shopping: Orders, deliveries, purchases, e-commerce\n",
|
| 431 |
+
"- social: Social networks, personal messages, invitations\n",
|
| 432 |
+
"- work: Job-related, recruitment, office, meetings, projects\n",
|
| 433 |
+
"- newsletter: Digests, subscriptions, blogs, articles\n",
|
| 434 |
+
"- promotional: Marketing, offers, discounts, advertisements\n",
|
| 435 |
+
"- other: Anything that doesn't fit above\n",
|
| 436 |
+
"\n",
|
| 437 |
+
"OUTPUT FORMAT (JSON only, no other text):\n",
|
| 438 |
+
"{{\"category\": \"<category>\", \"confidence\": \"<high/medium/low>\", \"reason\": \"<brief 5-10 word reason>\"}}\n",
|
| 439 |
+
"\"\"\"\n",
|
| 440 |
+
"\n",
|
| 441 |
+
"def build_prompt(email_data):\n",
|
| 442 |
+
" \"\"\"Build classification prompt for one email.\"\"\"\n",
|
| 443 |
+
" return CLASSIFICATION_PROMPT.format(\n",
|
| 444 |
+
" subject=email_data['subject'][:200],\n",
|
| 445 |
+
" sender=email_data['sender'][:100],\n",
|
| 446 |
+
" body=email_data['body'][:2000]\n",
|
| 447 |
+
" )\n",
|
| 448 |
+
"\n",
|
| 449 |
+
"# Test: See what prompt looks like\n",
|
| 450 |
+
"test_prompt = build_prompt(sample_emails[0])\n",
|
| 451 |
+
"print(f\"Prompt length: {len(test_prompt)} characters\")\n",
|
| 452 |
+
"print(f\"\\n=== PROMPT PREVIEW ===\\n{test_prompt[:1000]}...\")\n",
|
| 453 |
+
"\n",
|
| 454 |
+
"# Cell 14: Load Phi-3 model\n",
|
| 455 |
+
"model_path = str(PROJECT / \"models/base/phi3-mini\")\n",
|
| 456 |
+
"\n",
|
| 457 |
+
"print(\"Loading Phi-3 model...\")\n",
|
| 458 |
+
"model, tokenizer = load(model_path)\n",
|
| 459 |
+
"print(\"β
Model loaded\")\n",
|
| 460 |
+
"\n",
|
| 461 |
+
"# Cell 15: Test classification on one email\n",
|
| 462 |
+
"test_email = sample_emails[0]\n",
|
| 463 |
+
"\n",
|
| 464 |
+
"# Build prompt\n",
|
| 465 |
+
"prompt = build_prompt(test_email)\n",
|
| 466 |
+
"\n",
|
| 467 |
+
"# Send to Phi-3\n",
|
| 468 |
+
"print(\"Classifying email...\")\n",
|
| 469 |
+
"print(f\"Subject: {test_email['subject'][:80]}...\")\n",
|
| 470 |
+
"print(\"-\" * 50)\n",
|
| 471 |
+
"\n",
|
| 472 |
+
"response = generate(\n",
|
| 473 |
+
" model, \n",
|
| 474 |
+
" tokenizer, \n",
|
| 475 |
+
" prompt=prompt,\n",
|
| 476 |
+
" max_tokens=100,\n",
|
| 477 |
+
" verbose=False\n",
|
| 478 |
+
")\n",
|
| 479 |
+
"\n",
|
| 480 |
+
"print(f\"\\n=== PHI-3 RESPONSE ===\\n{response}\")\n",
|
| 481 |
+
"\n",
|
| 482 |
+
"# Cell 16: JSON extraction helper\n",
|
| 483 |
+
"\n",
|
| 484 |
+
"def extract_json(response):\n",
|
| 485 |
+
" \"\"\"Extract JSON object from LLM response.\"\"\"\n",
|
| 486 |
+
"\n",
|
| 487 |
+
" # Find JSON pattern in response\n",
|
| 488 |
+
" match = re.search(r'\\{[^{}]*\\}', response)\n",
|
| 489 |
+
"\n",
|
| 490 |
+
" if(match):\n",
|
| 491 |
+
" try:\n",
|
| 492 |
+
" return json.loads(match.group())\n",
|
| 493 |
+
" except json.JSONDecodeError:\n",
|
| 494 |
+
" return None\n",
|
| 495 |
+
" return None\n",
|
| 496 |
+
"\n",
|
| 497 |
+
"# Test on previous response\n",
|
| 498 |
+
"parsed = extract_json(response)\n",
|
| 499 |
+
"\n",
|
| 500 |
+
"print(\"=== EXTRACTED JSON ===\")\n",
|
| 501 |
+
"print(parsed)\n",
|
| 502 |
+
"print(f\"\\nCategory: {parsed['category']}\")\n",
|
| 503 |
+
"print(f\"Confidence: {parsed['confidence']}\")\n",
|
| 504 |
+
"print(f\"Reason: {parsed['reason']}\")\n",
|
| 505 |
+
"\n",
|
| 506 |
+
"# Cell 17: Classify all sample emails\n",
|
| 507 |
+
"results = []\n",
|
| 508 |
+
"failed = 0\n",
|
| 509 |
+
"\n",
|
| 510 |
+
"print(f\"Classifying {len(sample_emails)} emails...\")\n",
|
| 511 |
+
"print(\"Estimated time: ~5 minutes\\n\")\n",
|
| 512 |
+
"\n",
|
| 513 |
+
"start_time = time.time()\n",
|
| 514 |
+
"\n",
|
| 515 |
+
"for i, email_data in enumerate(tqdm(sample_emails, desc=\"Classifying\")):\n",
|
| 516 |
+
" try:\n",
|
| 517 |
+
" # Build prompt\n",
|
| 518 |
+
" prompt = build_prompt(email_data)\n",
|
| 519 |
+
" \n",
|
| 520 |
+
" # Get classification\n",
|
| 521 |
+
" response = generate(\n",
|
| 522 |
+
" model, \n",
|
| 523 |
+
" tokenizer, \n",
|
| 524 |
+
" prompt=prompt,\n",
|
| 525 |
+
" max_tokens=100,\n",
|
| 526 |
+
" verbose=False\n",
|
| 527 |
+
" )\n",
|
| 528 |
+
" \n",
|
| 529 |
+
" # Extract JSON\n",
|
| 530 |
+
" parsed = extract_json(response)\n",
|
| 531 |
+
" \n",
|
| 532 |
+
" if parsed:\n",
|
| 533 |
+
" results.append({\n",
|
| 534 |
+
" 'id': email_data.get('id', i),\n",
|
| 535 |
+
" 'subject': email_data['subject'],\n",
|
| 536 |
+
" 'sender': email_data['sender'],\n",
|
| 537 |
+
" 'category': parsed.get('category', 'other'),\n",
|
| 538 |
+
" 'confidence': parsed.get('confidence', 'low'),\n",
|
| 539 |
+
" 'reason': parsed.get('reason', '')\n",
|
| 540 |
+
" })\n",
|
| 541 |
+
" else:\n",
|
| 542 |
+
" failed += 1\n",
|
| 543 |
+
" \n",
|
| 544 |
+
" except Exception as e:\n",
|
| 545 |
+
" failed += 1\n",
|
| 546 |
+
" continue\n",
|
| 547 |
+
"\n",
|
| 548 |
+
"elapsed = time.time() - start_time\n",
|
| 549 |
+
"\n",
|
| 550 |
+
"print(f\"\\nβ
Classified: {len(results)}\")\n",
|
| 551 |
+
"print(f\"β Failed: {failed}\")\n",
|
| 552 |
+
"print(f\"β±οΈ Time: {elapsed/60:.1f} minutes\")\n",
|
| 553 |
+
"print(f\"β‘ Speed: {len(results)/elapsed:.1f} emails/sec\")\n",
|
| 554 |
+
"\n",
|
| 555 |
+
"# Cell 18: Category distribution\n",
|
| 556 |
+
"\n",
|
| 557 |
+
"categories = Counter([r['category'] for r in results])\n",
|
| 558 |
+
"\n",
|
| 559 |
+
"print(\"=== CATEGORY DISTRIBUTION ===\\n\")\n",
|
| 560 |
+
"for category, count in categories.most_common():\n",
|
| 561 |
+
" pct = count / len(results) * 100\n",
|
| 562 |
+
" bar = \"β\" * int(pct / 2)\n",
|
| 563 |
+
" print(f\"{category:12} {count:4} ({pct:5.1f}%) {bar}\")\n",
|
| 564 |
+
"\n",
|
| 565 |
+
"print(f\"\\nπ Total classified: {len(results)}\")\n",
|
| 566 |
+
"\n",
|
| 567 |
+
"# Cell 19: Save classification results\n",
|
| 568 |
+
"results_path = PROJECT / \"data/parsed/classification_results.json\"\n",
|
| 569 |
+
"\n",
|
| 570 |
+
"with open(results_path, 'w', encoding='utf-8') as f:\n",
|
| 571 |
+
" json.dump(results, f, ensure_ascii=False, indent=2)\n",
|
| 572 |
+
"\n",
|
| 573 |
+
"print(f\"β
Saved {len(results)} results to {results_path}\")\n",
|
| 574 |
+
"\n",
|
| 575 |
+
"# Cell 20: Extract finance emails\n",
|
| 576 |
+
"\n",
|
| 577 |
+
"finance_results = [r for r in results if r['category'] == 'finance']\n",
|
| 578 |
+
"\n",
|
| 579 |
+
"print(f\"=== FINANCE EMAILS: {len(finance_results)} ===\\n\")\n",
|
| 580 |
+
"\n",
|
| 581 |
+
"# Show first 10\n",
|
| 582 |
+
"\n",
|
| 583 |
+
"for i, email in enumerate(finance_results[:10]):\n",
|
| 584 |
+
"\n",
|
| 585 |
+
" print(f\"{i+1}. {email['subject'][:70]}\")\n",
|
| 586 |
+
"\n",
|
| 587 |
+
" print(f\" Sender: {email['sender'][:50]}\")\n",
|
| 588 |
+
"\n",
|
| 589 |
+
" print(f\" Reason: {email['reason']}\")\n",
|
| 590 |
+
"\n",
|
| 591 |
+
" print()\n",
|
| 592 |
+
"\n",
|
| 593 |
+
"# Cell 21: Get full details of finance emails\n",
|
| 594 |
+
"finance_results = [r for r in results if r['category'] == 'finance']\n",
|
| 595 |
+
"\n",
|
| 596 |
+
"# Get full email data for finance emails\n",
|
| 597 |
+
"finance_ids = [r['id'] for r in finance_results]\n",
|
| 598 |
+
"finance_emails_full = [e for e in parsed_emails if e['id'] in finance_ids]\n",
|
| 599 |
+
"\n",
|
| 600 |
+
"print(f\"Finance emails with full body: {len(finance_emails_full)}\")\n",
|
| 601 |
+
"\n",
|
| 602 |
+
"# Show senders\n",
|
| 603 |
+
"print(\"\\n=== FINANCE SENDERS ===\")\n",
|
| 604 |
+
"senders = [e['sender'] for e in finance_emails_full]\n",
|
| 605 |
+
"for sender, count in Counter(senders).most_common(15):\n",
|
| 606 |
+
" print(f\" {sender[:50]:50} : {count}\")\n",
|
| 607 |
+
"\n",
|
| 608 |
+
" \n",
|
| 609 |
+
"\n",
|
| 610 |
+
"\n",
|
| 611 |
+
"\n",
|
| 612 |
+
" \n",
|
| 613 |
+
" \n",
|
| 614 |
+
"\n",
|
| 615 |
+
"\n"
|
| 616 |
+
]
|
| 617 |
+
},
|
| 618 |
+
{
|
| 619 |
+
"cell_type": "code",
|
| 620 |
+
"execution_count": null,
|
| 621 |
+
"id": "2c84628e-8702-4157-94ea-11dfee9aa2db",
|
| 622 |
+
"metadata": {},
|
| 623 |
+
"outputs": [],
|
| 624 |
+
"source": []
|
| 625 |
+
}
|
| 626 |
+
],
|
| 627 |
+
"metadata": {
|
| 628 |
+
"kernelspec": {
|
| 629 |
+
"display_name": "Python 3 (ipykernel)",
|
| 630 |
+
"language": "python",
|
| 631 |
+
"name": "python3"
|
| 632 |
+
},
|
| 633 |
+
"language_info": {
|
| 634 |
+
"codemirror_mode": {
|
| 635 |
+
"name": "ipython",
|
| 636 |
+
"version": 3
|
| 637 |
+
},
|
| 638 |
+
"file_extension": ".py",
|
| 639 |
+
"mimetype": "text/x-python",
|
| 640 |
+
"name": "python",
|
| 641 |
+
"nbconvert_exporter": "python",
|
| 642 |
+
"pygments_lexer": "ipython3",
|
| 643 |
+
"version": "3.9.6"
|
| 644 |
+
}
|
| 645 |
+
},
|
| 646 |
+
"nbformat": 4,
|
| 647 |
+
"nbformat_minor": 5
|
| 648 |
+
}
|
02_classification.ipynb
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"id": "bfd5cfe5-ea7e-49d8-9ef3-5d43bef5a0cf",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [],
|
| 9 |
+
"source": [
|
| 10 |
+
"\n",
|
| 11 |
+
"import json\n",
|
| 12 |
+
"import re\n",
|
| 13 |
+
"import random\n",
|
| 14 |
+
"import time\n",
|
| 15 |
+
"from pathlib import Path\n",
|
| 16 |
+
"from tqdm.notebook import tqdm\n",
|
| 17 |
+
"from mlx_lm import load, generate\n",
|
| 18 |
+
"from collections import Counter\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"# Cell 11: Load parsed emails from cache\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"cache_path = PROJECT / \"data/parsed/emails.json\"\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"with open(cache_path, 'r', encoding='utf-8') as f:\n",
|
| 26 |
+
" parsed_emails = json.load(f)\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"print(f\"β
Loaded {len(parsed_emails):,} emails from cache\")\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"# Cell 12: Random sampling\n",
|
| 31 |
+
"random.seed(42)\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"# Pick 500 random emails\n",
|
| 34 |
+
"sample_size = 500\n",
|
| 35 |
+
"sample_emails = random.sample(parsed_emails,sample_size)\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"print(f\"Total emails: {len(parsed_emails):,}\")\n",
|
| 38 |
+
"print(f\"Sample size: {len(sample_emails)}\")\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"# Preview one sample\n",
|
| 41 |
+
"print(f\"\\n=== SAMPLE EMAIL #1 ===\")\n",
|
| 42 |
+
"print(f\"Subject: {sample_emails[0]['subject']}\")\n",
|
| 43 |
+
"print(f\"Sender: {sample_emails[0]['sender']}\")\n",
|
| 44 |
+
"print(f\"Body: {sample_emails[0]['body'][:300]}...\")\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"# Cell 13: Classification prompt template\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"CLASSIFICATION_PROMPT = \"\"\"You are an email classifier. Analyze this email and categorize it.\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"EMAIL:\n",
|
| 51 |
+
"Subject: {subject}\n",
|
| 52 |
+
"From: {sender}\n",
|
| 53 |
+
"Body: {body}\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"TASK:\n",
|
| 56 |
+
"Classify this email into exactly ONE category.\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"CATEGORIES:\n",
|
| 59 |
+
"- finance: Banks, payments, transactions, investments, credit cards, loans, UPI, wallets\n",
|
| 60 |
+
"- shopping: Orders, deliveries, purchases, e-commerce\n",
|
| 61 |
+
"- social: Social networks, personal messages, invitations\n",
|
| 62 |
+
"- work: Job-related, recruitment, office, meetings, projects\n",
|
| 63 |
+
"- newsletter: Digests, subscriptions, blogs, articles\n",
|
| 64 |
+
"- promotional: Marketing, offers, discounts, advertisements\n",
|
| 65 |
+
"- other: Anything that doesn't fit above\n",
|
| 66 |
+
"\n",
|
| 67 |
+
"OUTPUT FORMAT (JSON only, no other text):\n",
|
| 68 |
+
"{{\"category\": \"<category>\", \"confidence\": \"<high/medium/low>\", \"reason\": \"<brief 5-10 word reason>\"}}\n",
|
| 69 |
+
"\"\"\"\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"def build_prompt(email_data):\n",
|
| 72 |
+
" \"\"\"Build classification prompt for one email.\"\"\"\n",
|
| 73 |
+
" return CLASSIFICATION_PROMPT.format(\n",
|
| 74 |
+
" subject=email_data['subject'][:200],\n",
|
| 75 |
+
" sender=email_data['sender'][:100],\n",
|
| 76 |
+
" body=email_data['body'][:2000]\n",
|
| 77 |
+
" )\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"# Test: See what prompt looks like\n",
|
| 80 |
+
"test_prompt = build_prompt(sample_emails[0])\n",
|
| 81 |
+
"print(f\"Prompt length: {len(test_prompt)} characters\")\n",
|
| 82 |
+
"print(f\"\\n=== PROMPT PREVIEW ===\\n{test_prompt[:1000]}...\")\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"# Cell 14: Load Phi-3 model\n",
|
| 85 |
+
"model_path = str(PROJECT / \"models/base/phi3-mini\")\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"print(\"Loading Phi-3 model...\")\n",
|
| 88 |
+
"model, tokenizer = load(model_path)\n",
|
| 89 |
+
"print(\"β
Model loaded\")\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"# Cell 15: Test classification on one email\n",
|
| 92 |
+
"test_email = sample_emails[0]\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"# Build prompt\n",
|
| 95 |
+
"prompt = build_prompt(test_email)\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"# Send to Phi-3\n",
|
| 98 |
+
"print(\"Classifying email...\")\n",
|
| 99 |
+
"print(f\"Subject: {test_email['subject'][:80]}...\")\n",
|
| 100 |
+
"print(\"-\" * 50)\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"response = generate(\n",
|
| 103 |
+
" model, \n",
|
| 104 |
+
" tokenizer, \n",
|
| 105 |
+
" prompt=prompt,\n",
|
| 106 |
+
" max_tokens=100,\n",
|
| 107 |
+
" verbose=False\n",
|
| 108 |
+
")\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"print(f\"\\n=== PHI-3 RESPONSE ===\\n{response}\")\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"# Cell 16: JSON extraction helper\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"def extract_json(response):\n",
|
| 115 |
+
" \"\"\"Extract JSON object from LLM response.\"\"\"\n",
|
| 116 |
+
"\n",
|
| 117 |
+
" # Find JSON pattern in response\n",
|
| 118 |
+
" match = re.search(r'\\{[^{}]*\\}', response)\n",
|
| 119 |
+
"\n",
|
| 120 |
+
" if(match):\n",
|
| 121 |
+
" try:\n",
|
| 122 |
+
" return json.loads(match.group())\n",
|
| 123 |
+
" except json.JSONDecodeError:\n",
|
| 124 |
+
" return None\n",
|
| 125 |
+
" return None\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"# Test on previous response\n",
|
| 128 |
+
"parsed = extract_json(response)\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"print(\"=== EXTRACTED JSON ===\")\n",
|
| 131 |
+
"print(parsed)\n",
|
| 132 |
+
"print(f\"\\nCategory: {parsed['category']}\")\n",
|
| 133 |
+
"print(f\"Confidence: {parsed['confidence']}\")\n",
|
| 134 |
+
"print(f\"Reason: {parsed['reason']}\")\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"# Cell 17: Classify all sample emails\n",
|
| 137 |
+
"results = []\n",
|
| 138 |
+
"failed = 0\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"print(f\"Classifying {len(sample_emails)} emails...\")\n",
|
| 141 |
+
"print(\"Estimated time: ~5 minutes\\n\")\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"start_time = time.time()\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"for i, email_data in enumerate(tqdm(sample_emails, desc=\"Classifying\")):\n",
|
| 146 |
+
" try:\n",
|
| 147 |
+
" # Build prompt\n",
|
| 148 |
+
" prompt = build_prompt(email_data)\n",
|
| 149 |
+
" \n",
|
| 150 |
+
" # Get classification\n",
|
| 151 |
+
" response = generate(\n",
|
| 152 |
+
" model, \n",
|
| 153 |
+
" tokenizer, \n",
|
| 154 |
+
" prompt=prompt,\n",
|
| 155 |
+
" max_tokens=100,\n",
|
| 156 |
+
" verbose=False\n",
|
| 157 |
+
" )\n",
|
| 158 |
+
" \n",
|
| 159 |
+
" # Extract JSON\n",
|
| 160 |
+
" parsed = extract_json(response)\n",
|
| 161 |
+
" \n",
|
| 162 |
+
" if parsed:\n",
|
| 163 |
+
" results.append({\n",
|
| 164 |
+
" 'id': email_data.get('id', i),\n",
|
| 165 |
+
" 'subject': email_data['subject'],\n",
|
| 166 |
+
" 'sender': email_data['sender'],\n",
|
| 167 |
+
" 'category': parsed.get('category', 'other'),\n",
|
| 168 |
+
" 'confidence': parsed.get('confidence', 'low'),\n",
|
| 169 |
+
" 'reason': parsed.get('reason', '')\n",
|
| 170 |
+
" })\n",
|
| 171 |
+
" else:\n",
|
| 172 |
+
" failed += 1\n",
|
| 173 |
+
" \n",
|
| 174 |
+
" except Exception as e:\n",
|
| 175 |
+
" failed += 1\n",
|
| 176 |
+
" continue\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"elapsed = time.time() - start_time\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"print(f\"\\nβ
Classified: {len(results)}\")\n",
|
| 181 |
+
"print(f\"β Failed: {failed}\")\n",
|
| 182 |
+
"print(f\"β±οΈ Time: {elapsed/60:.1f} minutes\")\n",
|
| 183 |
+
"print(f\"β‘ Speed: {len(results)/elapsed:.1f} emails/sec\")\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"# Cell 18: Category distribution\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"categories = Counter([r['category'] for r in results])\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"print(\"=== CATEGORY DISTRIBUTION ===\\n\")\n",
|
| 190 |
+
"for category, count in categories.most_common():\n",
|
| 191 |
+
" pct = count / len(results) * 100\n",
|
| 192 |
+
" bar = \"β\" * int(pct / 2)\n",
|
| 193 |
+
" print(f\"{category:12} {count:4} ({pct:5.1f}%) {bar}\")\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"print(f\"\\nπ Total classified: {len(results)}\")\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"# Cell 19: Save classification results\n",
|
| 198 |
+
"results_path = PROJECT / \"data/parsed/classification_results.json\"\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"with open(results_path, 'w', encoding='utf-8') as f:\n",
|
| 201 |
+
" json.dump(results, f, ensure_ascii=False, indent=2)\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"print(f\"β
Saved {len(results)} results to {results_path}\")"
|
| 204 |
+
]
|
| 205 |
+
}
|
| 206 |
+
],
|
| 207 |
+
"metadata": {
|
| 208 |
+
"kernelspec": {
|
| 209 |
+
"display_name": "Python 3 (ipykernel)",
|
| 210 |
+
"language": "python",
|
| 211 |
+
"name": "python3"
|
| 212 |
+
},
|
| 213 |
+
"language_info": {
|
| 214 |
+
"codemirror_mode": {
|
| 215 |
+
"name": "ipython",
|
| 216 |
+
"version": 3
|
| 217 |
+
},
|
| 218 |
+
"file_extension": ".py",
|
| 219 |
+
"mimetype": "text/x-python",
|
| 220 |
+
"name": "python",
|
| 221 |
+
"nbconvert_exporter": "python",
|
| 222 |
+
"pygments_lexer": "ipython3",
|
| 223 |
+
"version": "3.9.6"
|
| 224 |
+
}
|
| 225 |
+
},
|
| 226 |
+
"nbformat": 4,
|
| 227 |
+
"nbformat_minor": 5
|
| 228 |
+
}
|
03_pattern_discovery.ipynb
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 7,
|
| 6 |
+
"id": "96e087b6-4196-4109-bb30-b78125fafb54",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [
|
| 9 |
+
{
|
| 10 |
+
"name": "stdout",
|
| 11 |
+
"output_type": "stream",
|
| 12 |
+
"text": [
|
| 13 |
+
"β
Loaded 40,820 parsed emails\n",
|
| 14 |
+
"β
Loaded 499 classification results\n",
|
| 15 |
+
"Finance emails found: 89\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"=== TOP FINANCE SENDERS ===\n",
|
| 18 |
+
" 18 : \n",
|
| 19 |
+
" 7 : \"ICICI Bank Privilege Banking\"\n",
|
| 20 |
+
" 5 : ICICI Bank\n",
|
| 21 |
+
" 5 : \"HDFC Life\"\n",
|
| 22 |
+
" 4 : HDFC Bank InstaAlerts\n",
|
| 23 |
+
" 4 : Groww Digest\n",
|
| 24 |
+
" 3 : Quora Digest\n",
|
| 25 |
+
" 3 : Groww\n",
|
| 26 |
+
" 3 : HDFC Life - no reply\n",
|
| 27 |
+
" 2 : \"alert @ icicibank . com\"\n",
|
| 28 |
+
" 2 : Paisabazaar Support\n",
|
| 29 |
+
" 2 : LinkedIn\n",
|
| 30 |
+
" 2 : Google Play\n",
|
| 31 |
+
" 2 : \"ICICI Bank \"\n",
|
| 32 |
+
" 1 : \"Zerodha Broking Ltd\"\n",
|
| 33 |
+
"Emails with empty sender: 18\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"1. Subject: Funds/Securities Balance\n",
|
| 36 |
+
" Body: Dear Investor, With reference to NSE circulars NSE/INSP/46704 dated December 17, 2020, and NSE/INSP/55039 dated December 28, 2022, Trading members are...\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"2. Subject: Dear Customer, Rs.120.00 has been debited from account 1234 to VPA com\n",
|
| 39 |
+
" Body: Dear Customer, Rs.120.00 has been debited from account 1234 to VPA companyonline@ybl pepto on 06-12-25. Your UPI transaction reference number is 50000...\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"3. Subject: 40GB of Data allocated to Jio Number 7855883757\n",
|
| 42 |
+
" Body: Dear Customer, Thank you for choosing Jio. You have assigned 40GB data quota to Jio Number 7855883757. Please note, you need to assign Data quota from...\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"4. Subject: Alert for transaction through ICICI Bank iMobile\n",
|
| 45 |
+
" Body: Dear Customer, You have successfully made a UPI payment of βΉ 3900.0 using the iMobile app to COMPUTER SHOP . The payment was initiated from your ICICI...\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"5. Subject: Delivered: Your ICICI Bank Card- ATM / Debit Reissue status\n",
|
| 48 |
+
" Body: Dear Customer, We have delivered the Card- ATM / Debit Reissue for your Account XX0556 by DELHIVERY on 11-NOV-24. It was received by Customer/Consigne...\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"=== SAMPLE FINANCE EMAIL BODIES ===\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"Real finance emails: 53\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"--- Email 1 ---\n",
|
| 55 |
+
"Subject: Daily Equity Margin Statement for HTV475 - December 24, 2025\n",
|
| 56 |
+
"Sender: \"Zerodha Broking Ltd\"\n",
|
| 57 |
+
"Body: Margin Statements Dear Ranjit Behera, Attached is the daily equity margin statement for December 24, 2025 for your account HTV475. To read more on how to interpret this margin statement, click here. Copy of this margin statement is also available on our reporting platform Console Sincerely, Team Zer\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"--- Email 2 ---\n",
|
| 60 |
+
"Subject: β You have done a UPI txn. Check details!\n",
|
| 61 |
+
"Sender: HDFC Bank InstaAlerts\n",
|
| 62 |
+
"Body: HDFC BANK Dear Customer, Rs.200.00 has been debited from account 3545 to VPA q071786333@ybl PRABAKARAN KRISHNAN on 24-12-25. Your UPI transaction reference number is 535899488403. If you did not authorize this transaction, please report it immediately by calling 18002586161 Or SMS BLOCK UPI to 73080\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"--- Email 3 ---\n",
|
| 65 |
+
"Subject: Funds/Securities Balance\n",
|
| 66 |
+
"Sender: \n",
|
| 67 |
+
"Body: Dear Investor, With reference to NSE circulars NSE/INSP/46704 dated December 17, 2020, and NSE/INSP/55039 dated December 28, 2022, Trading members are required to upload clients' securities balance on a daily basis. Further, with reference to NCL circular NCL/CMPL/49348 dated Aug 20, 2021, and NSE c\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"--- Email 4 ---\n",
|
| 70 |
+
"Subject: Dear Customer, Rs.120.00 has been debited from account 1234 to VPA companyonline\n",
|
| 71 |
+
"Sender: \n",
|
| 72 |
+
"Body: Dear Customer, Rs.120.00 has been debited from account 1234 to VPA companyonline@ybl pepto on 06-12-25. Your UPI transaction reference number is 500000000006. If you did not authorize this transaction, please report it immediately by calling 18002586161 Or SMS BLOCK UPI to 7000000008. Warm Regards, \n",
|
| 73 |
+
"\n",
|
| 74 |
+
"--- Email 5 ---\n",
|
| 75 |
+
"Subject: β You have done a UPI txn. Check details!\n",
|
| 76 |
+
"Sender: HDFC Bank InstaAlerts\n",
|
| 77 |
+
"Body: HDFC BANK Dear Customer, Rs.1890.28 has been debited from account 3545 to VPA amazon@yapl Amazon India on 25-12-25. Your UPI transaction reference number is 535965972977. If you did not authorize this transaction, please report it immediately by calling 18002586161 Or SMS BLOCK UPI to 7308080808. Wa\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"=== INPUT TEXT ===\n",
|
| 80 |
+
"Margin Statements Dear Ranjit Behera, Attached is the daily equity margin statement for December 24, 2025 for your account HTV475. To read more on how to interpret this margin statement, click here. Copy of this margin statement is also available on our reporting platform Console Sincerely, Team Zer\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"=== EXTRACTED ENTITIES ===\n",
|
| 83 |
+
" account: HTV475\n",
|
| 84 |
+
"=== TESTING ENTITY EXTRACTION ===\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"Transaction emails found: 9\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"--- Email 1 ---\n",
|
| 89 |
+
"Subject: β You have done a UPI txn. Check details!\n",
|
| 90 |
+
"Body: HDFC BANK Dear Customer, Rs.200.00 has been debited from account 3545 to VPA q071786333@ybl PRABAKARAN KRISHNAN on 24-12-25. Your UPI transaction reference number is 535899488403. If you did not autho...\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"Extracted:\n",
|
| 93 |
+
" amount: 200.00\n",
|
| 94 |
+
" type: debit\n",
|
| 95 |
+
" account: 3545\n",
|
| 96 |
+
" date: 24-12-25\n",
|
| 97 |
+
" reference: 535899488403\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"--- Email 2 ---\n",
|
| 100 |
+
"Subject: Dear Customer, Rs.120.00 has been debited from account 1234 \n",
|
| 101 |
+
"Body: Dear Customer, Rs.120.00 has been debited from account 1234 to VPA companyonline@ybl pepto on 06-12-25. Your UPI transaction reference number is 500000000006. If you did not authorize this transaction...\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"Extracted:\n",
|
| 104 |
+
" amount: 120.00\n",
|
| 105 |
+
" type: debit\n",
|
| 106 |
+
" account: 1234\n",
|
| 107 |
+
" date: 06-12-25\n",
|
| 108 |
+
" reference: 500000000006\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"--- Email 3 ---\n",
|
| 111 |
+
"Subject: β You have done a UPI txn. Check details!\n",
|
| 112 |
+
"Body: HDFC BANK Dear Customer, Rs.1890.28 has been debited from account 3545 to VPA amazon@yapl Amazon India on 25-12-25. Your UPI transaction reference number is 535965972977. If you did not authorize this...\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"Extracted:\n",
|
| 115 |
+
" amount: 1890.28\n",
|
| 116 |
+
" type: debit\n",
|
| 117 |
+
" account: 3545\n",
|
| 118 |
+
" date: 25-12-25\n",
|
| 119 |
+
" reference: 535965972977\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"β
Saved 53 finance emails to data/filtered/finance_emails.json\n",
|
| 122 |
+
"β
Saved patterns to data/filtered/finance_patterns.json\n"
|
| 123 |
+
]
|
| 124 |
+
}
|
| 125 |
+
],
|
| 126 |
+
"source": [
|
| 127 |
+
"# Cell 1: Imports & Load Data\n",
|
| 128 |
+
"import json\n",
|
| 129 |
+
"from pathlib import Path\n",
|
| 130 |
+
"from collections import Counter\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"PROJECT = Path.home() / \"llm-mail-trainer\"\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"# Load parsed emails (40k)\n",
|
| 135 |
+
"with open(PROJECT / \"data/parsed/emails.json\", 'r') as f:\n",
|
| 136 |
+
" parsed_emails = json.load(f)\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"# Load classification results (499)\n",
|
| 139 |
+
"with open(PROJECT / \"data/parsed/classification_results.json\", 'r') as f:\n",
|
| 140 |
+
" results = json.load(f)\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"print(f\"β
Loaded {len(parsed_emails):,} parsed emails\")\n",
|
| 143 |
+
"print(f\"β
Loaded {len(results)} classification results\")\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"# Cell 2: Extract finance emails with full details\n",
|
| 146 |
+
"finance_results = [r for r in results if r['category'] == 'finance']\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"# Get full email data for finance emails\n",
|
| 149 |
+
"finance_ids = [r['id'] for r in finance_results]\n",
|
| 150 |
+
"finance_emails_full = [e for e in parsed_emails if e['id'] in finance_ids]\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"print(f\"Finance emails found: {len(finance_emails_full)}\")\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"# Show senders\n",
|
| 155 |
+
"print(\"\\n=== TOP FINANCE SENDERS ===\")\n",
|
| 156 |
+
"senders = [e['sender'] for e in finance_emails_full]\n",
|
| 157 |
+
"for sender, count in Counter(senders).most_common(15):\n",
|
| 158 |
+
" print(f\" {count:3} : {sender[:60]}\")\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"# Cell 3: Check emails with empty sender\n",
|
| 161 |
+
"empty_sender_emails = [e for e in finance_emails_full if e['sender'].strip() == '']\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"print(f\"Emails with empty sender: {len(empty_sender_emails)}\\n\")\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"for i, email in enumerate(empty_sender_emails[:5]):\n",
|
| 166 |
+
" print(f\"{i+1}. Subject: {email['subject'][:70]}\")\n",
|
| 167 |
+
" print(f\" Body: {email['body'][:150]}...\")\n",
|
| 168 |
+
" print()\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"# Cell 4: View finance email bodies (for pattern discovery)\n",
|
| 171 |
+
"print(\"=== SAMPLE FINANCE EMAIL BODIES ===\\n\")\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"# Filter only emails with known finance senders\n",
|
| 174 |
+
"finance_senders = ['icici', 'hdfc', 'groww', 'zerodha', 'paisabazaar', 'sbi', 'axis', 'kotak']\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"real_finance = []\n",
|
| 177 |
+
"for e in finance_emails_full:\n",
|
| 178 |
+
" sender_lower = e['sender'].lower()\n",
|
| 179 |
+
" subject_lower = e['subject'].lower()\n",
|
| 180 |
+
" body_lower = e['body'].lower()\n",
|
| 181 |
+
" \n",
|
| 182 |
+
" # Check sender or content\n",
|
| 183 |
+
" if any(fs in sender_lower for fs in finance_senders):\n",
|
| 184 |
+
" real_finance.append(e)\n",
|
| 185 |
+
" elif any(kw in body_lower for kw in ['debited', 'credited', 'transaction', 'upi', 'a/c', 'balance']):\n",
|
| 186 |
+
" real_finance.append(e)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"print(f\"Real finance emails: {len(real_finance)}\\n\")\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"# Show 5 samples\n",
|
| 191 |
+
"for i, email in enumerate(real_finance[:5]):\n",
|
| 192 |
+
" print(f\"--- Email {i+1} ---\")\n",
|
| 193 |
+
" print(f\"Subject: {email['subject'][:80]}\")\n",
|
| 194 |
+
" print(f\"Sender: {email['sender']}\")\n",
|
| 195 |
+
" print(f\"Body: {email['body'][:300]}\")\n",
|
| 196 |
+
" print()\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"# Cell 5: Pattern extraction functions\n",
|
| 199 |
+
"import re\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"def extract_entities(text):\n",
|
| 202 |
+
" \"\"\"Extract financial entities from email text.\"\"\"\n",
|
| 203 |
+
" \n",
|
| 204 |
+
" entities = {}\n",
|
| 205 |
+
" \n",
|
| 206 |
+
" # Amount: Rs.1890.28 or Rs 1,890.28 or βΉ1890\n",
|
| 207 |
+
" amount_match = re.search(r'(?:Rs\\.?|βΉ)\\s*([\\d,]+(?:\\.\\d{2})?)', text)\n",
|
| 208 |
+
" if amount_match:\n",
|
| 209 |
+
" entities['amount'] = amount_match.group(1).replace(',', '')\n",
|
| 210 |
+
" \n",
|
| 211 |
+
" # Type: debited or credited\n",
|
| 212 |
+
" if 'debited' in text.lower():\n",
|
| 213 |
+
" entities['type'] = 'debit'\n",
|
| 214 |
+
" elif 'credited' in text.lower():\n",
|
| 215 |
+
" entities['type'] = 'credit'\n",
|
| 216 |
+
" \n",
|
| 217 |
+
" # Account: account XXXX or A/C XXXX\n",
|
| 218 |
+
" account_match = re.search(r'(?:account|A/C|a/c)\\s*[:\\s]?\\s*(\\w+)', text, re.IGNORECASE)\n",
|
| 219 |
+
" if account_match:\n",
|
| 220 |
+
" entities['account'] = account_match.group(1)\n",
|
| 221 |
+
" \n",
|
| 222 |
+
" # Date: DD-MM-YY or DD-MM-YYYY\n",
|
| 223 |
+
" date_match = re.search(r'(\\d{2}-\\d{2}-\\d{2,4})', text)\n",
|
| 224 |
+
" if date_match:\n",
|
| 225 |
+
" entities['date'] = date_match.group(1)\n",
|
| 226 |
+
" \n",
|
| 227 |
+
" # UPI Reference\n",
|
| 228 |
+
" ref_match = re.search(r'reference\\s*(?:number|no\\.?)?\\s*(?:is)?\\s*(\\d+)', text, re.IGNORECASE)\n",
|
| 229 |
+
" if ref_match:\n",
|
| 230 |
+
" entities['reference'] = ref_match.group(1)\n",
|
| 231 |
+
" \n",
|
| 232 |
+
" return entities\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"# Test on sample\n",
|
| 235 |
+
"sample_text = real_finance[0]['body']\n",
|
| 236 |
+
"print(\"=== INPUT TEXT ===\")\n",
|
| 237 |
+
"print(sample_text[:300])\n",
|
| 238 |
+
"print(\"\\n=== EXTRACTED ENTITIES ===\")\n",
|
| 239 |
+
"extracted = extract_entities(sample_text)\n",
|
| 240 |
+
"for key, value in extracted.items():\n",
|
| 241 |
+
" print(f\" {key}: {value}\")\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"# Cell 6: Test on transaction emails\n",
|
| 244 |
+
"print(\"=== TESTING ENTITY EXTRACTION ===\\n\")\n",
|
| 245 |
+
"\n",
|
| 246 |
+
"# Find emails with \"debited\" or \"credited\"\n",
|
| 247 |
+
"transaction_emails = [e for e in real_finance if 'debited' in e['body'].lower() or 'credited' in e['body'].lower()]\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"print(f\"Transaction emails found: {len(transaction_emails)}\\n\")\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"for i, email in enumerate(transaction_emails[:3]):\n",
|
| 252 |
+
" print(f\"--- Email {i+1} ---\")\n",
|
| 253 |
+
" print(f\"Subject: {email['subject'][:60]}\")\n",
|
| 254 |
+
" print(f\"Body: {email['body'][:200]}...\")\n",
|
| 255 |
+
" print(f\"\\nExtracted:\")\n",
|
| 256 |
+
" extracted = extract_entities(email['body'])\n",
|
| 257 |
+
" for key, value in extracted.items():\n",
|
| 258 |
+
" print(f\" {key}: {value}\")\n",
|
| 259 |
+
" print()\n",
|
| 260 |
+
"\n",
|
| 261 |
+
"# Cell 7: Save patterns and filtered finance emails\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"# Create filtered directory\n",
|
| 264 |
+
"filtered_dir = PROJECT / \"data/filtered\"\n",
|
| 265 |
+
"filtered_dir.mkdir(exist_ok=True)\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"# Save real finance emails\n",
|
| 268 |
+
"with open(filtered_dir / \"finance_emails.json\", 'w') as f:\n",
|
| 269 |
+
" json.dump(real_finance, f, ensure_ascii=False, indent=2)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"# Save patterns configuration\n",
|
| 272 |
+
"patterns = {\n",
|
| 273 |
+
" \"amount\": r\"(?:Rs\\.?|βΉ)\\s*([\\d,]+(?:\\.\\d{2})?)\",\n",
|
| 274 |
+
" \"type_debit\": \"debited\",\n",
|
| 275 |
+
" \"type_credit\": \"credited\",\n",
|
| 276 |
+
" \"account\": r\"(?:account|A/C|a/c)\\s*[:\\s]?\\s*(\\w+)\",\n",
|
| 277 |
+
" \"date\": r\"(\\d{2}-\\d{2}-\\d{2,4})\",\n",
|
| 278 |
+
" \"reference\": r\"reference\\s*(?:number|no\\.?)?\\s*(?:is)?\\s*(\\d+)\",\n",
|
| 279 |
+
" \"finance_senders\": [\"icici\", \"hdfc\", \"groww\", \"zerodha\", \"paisabazaar\", \"sbi\", \"axis\", \"kotak\"],\n",
|
| 280 |
+
" \"finance_keywords\": [\"debited\", \"credited\", \"transaction\", \"upi\", \"a/c\", \"balance\", \"payment\"]\n",
|
| 281 |
+
"}\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"with open(filtered_dir / \"finance_patterns.json\", 'w') as f:\n",
|
| 284 |
+
" json.dump(patterns, f, indent=2)\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"print(f\"β
Saved {len(real_finance)} finance emails to data/filtered/finance_emails.json\")\n",
|
| 287 |
+
"print(f\"β
Saved patterns to data/filtered/finance_patterns.json\")"
|
| 288 |
+
]
|
| 289 |
+
},
|
| 290 |
+
{
|
| 291 |
+
"cell_type": "code",
|
| 292 |
+
"execution_count": null,
|
| 293 |
+
"id": "b2f02e65-c53f-492a-a32d-b07543a37085",
|
| 294 |
+
"metadata": {},
|
| 295 |
+
"outputs": [],
|
| 296 |
+
"source": []
|
| 297 |
+
}
|
| 298 |
+
],
|
| 299 |
+
"metadata": {
|
| 300 |
+
"kernelspec": {
|
| 301 |
+
"display_name": "Python 3 (ipykernel)",
|
| 302 |
+
"language": "python",
|
| 303 |
+
"name": "python3"
|
| 304 |
+
},
|
| 305 |
+
"language_info": {
|
| 306 |
+
"codemirror_mode": {
|
| 307 |
+
"name": "ipython",
|
| 308 |
+
"version": 3
|
| 309 |
+
},
|
| 310 |
+
"file_extension": ".py",
|
| 311 |
+
"mimetype": "text/x-python",
|
| 312 |
+
"name": "python",
|
| 313 |
+
"nbconvert_exporter": "python",
|
| 314 |
+
"pygments_lexer": "ipython3",
|
| 315 |
+
"version": "3.9.6"
|
| 316 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 12,
|
| 6 |
+
"id": "cdb52cf3-6af7-4fe9-bcd7-ce3f21ad7835",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [
|
| 9 |
+
{
|
| 10 |
+
"name": "stdout",
|
| 11 |
+
"output_type": "stream",
|
| 12 |
+
"text": [
|
| 13 |
+
"β
Loaded 40,820 emails\n",
|
| 14 |
+
"β
Loaded patterns:\n",
|
| 15 |
+
" Senders: ['icici', 'hdfc', 'groww', 'zerodha', 'paisabazaar', 'sbi', 'axis', 'kotak']\n",
|
| 16 |
+
" Keywords: ['debited', 'credited', 'transaction', 'upi', 'a/c', 'balance', 'payment']\n",
|
| 17 |
+
"Total emails: 40,820\n",
|
| 18 |
+
"Finance emails found: 8,116\n",
|
| 19 |
+
"Percentage: 19.9%\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"=== SAMPLE FINANCE EMAILS ===\n",
|
| 22 |
+
"1. Inquiry from Robokits India\n",
|
| 23 |
+
"2. π© Doodles, donuts & data to close out 2025\n",
|
| 24 |
+
"3. Daily Equity Margin Statement for HTV475 - December 23, 2025\n",
|
| 25 |
+
"4. How Financially Ready Are You? Take the Quiz Now!\n",
|
| 26 |
+
"5. π Dear Ranjit Behera, diversify beyond just savings\n",
|
| 27 |
+
"Transaction emails found: 598\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"=== SAMPLE TRANSACTION EMAILS ===\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"1. Subject: β You have done a UPI txn. Check details!\n",
|
| 32 |
+
" Body: HDFC BANK Dear Customer, Rs.50000.00 has been debited from account 3545 to VPA subhashreebadatya250@okicici SUBHASHREE BADATYA on 22-12-25. Your UPI t...\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"2. Subject: β You have done a UPI txn. Check details!\n",
|
| 35 |
+
" Body: HDFC BANK Dear Customer, Rs.50000.00 has been debited from account 3545 to VPA subhashreebadatya250@okicici SUBHASHREE BADATYA on 22-12-25. Your UPI t...\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"3. Subject: β You have done a UPI txn. Check details!\n",
|
| 38 |
+
" Body: HDFC BANK Dear Customer, Rs.1936.00 has been debited from account 3545 to VPA macfoslimited.rzp@icici MACFOS LIMITED on 18-12-25. Your UPI transaction...\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"4. Subject: β You have done a UPI txn. Check details!\n",
|
| 41 |
+
" Body: HDFC BANK Dear Customer, Rs.610.00 has been debited from account 3545 to VPA robocraze.cf@axisbank RoboCraze on 18-12-25. Your UPI transaction referen...\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"5. Subject: β You have done a UPI txn. Check details!\n",
|
| 44 |
+
" Body: HDFC BANK Dear Customer, Rs.200.00 has been debited from account 3545 to VPA q071786333@ybl PRABAKARAN KRISHNAN on 24-12-25. Your UPI transaction refe...\n",
|
| 45 |
+
"Subject: β You have done a UPI txn. Check details!\n",
|
| 46 |
+
"Extracted: {'amount': '50000.00', 'type': 'debit', 'account': '3545', 'date': '22-12-25', 'reference': '535680069988'}\n",
|
| 47 |
+
"Training examples created: 360\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"=== SAMPLE TRAINING EXAMPLE ===\n",
|
| 50 |
+
"PROMPT:\n",
|
| 51 |
+
"Extract financial entities from this email:\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"Subject: β You have done a UPI txn. Check details!\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"Body: HDFC BANK Dear Customer, Rs.50000.00 has been debited from account 3545 to VPA subhashreebadatya250@okicici SUBHASHREE BADATYA on 22-12-25. Your UPI transaction reference number is 535680069988. If...\n",
|
| 56 |
+
"\n",
|
| 57 |
+
"COMPLETION:\n",
|
| 58 |
+
"{\n",
|
| 59 |
+
" \"amount\": \"50000.00\",\n",
|
| 60 |
+
" \"type\": \"debit\",\n",
|
| 61 |
+
" \"account\": \"3545\",\n",
|
| 62 |
+
" \"date\": \"22-12-25\",\n",
|
| 63 |
+
" \"reference\": \"535680069988\"\n",
|
| 64 |
+
"}\n",
|
| 65 |
+
"Train set: 324\n",
|
| 66 |
+
"Validation set: 36\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"β
Saved to /Users/ranjit/llm-mail-trainer/data/training/\n",
|
| 69 |
+
" train.jsonl (324 examples)\n",
|
| 70 |
+
" valid.jsonl (36 examples)\n",
|
| 71 |
+
"=== FINE-TUNING SETUP ===\n",
|
| 72 |
+
"Base model: /Users/ranjit/llm-mail-trainer/models/base/phi3-mini\n",
|
| 73 |
+
"Training data: /Users/ranjit/llm-mail-trainer/data/training/train.jsonl\n",
|
| 74 |
+
"Validation data: /Users/ranjit/llm-mail-trainer/data/training/valid.jsonl\n",
|
| 75 |
+
"Output: /Users/ranjit/llm-mail-trainer/models/adapters/finance-lora\n",
|
| 76 |
+
"\n",
|
| 77 |
+
"β οΈ Fine-tuning will take 1-2 hours\n",
|
| 78 |
+
"Run the following command in Terminal (not in notebook):\n",
|
| 79 |
+
"\n",
|
| 80 |
+
"cd /Users/ranjit/llm-mail-trainer\n",
|
| 81 |
+
"source venv/bin/activate\n",
|
| 82 |
+
"\n",
|
| 83 |
+
"mlx_lm.lora \\\n",
|
| 84 |
+
" --model models/base/phi3-mini \\\n",
|
| 85 |
+
" --data data/training \\\n",
|
| 86 |
+
" --train \\\n",
|
| 87 |
+
" --batch-size 1 \\\n",
|
| 88 |
+
" --lora-layers 8 \\\n",
|
| 89 |
+
" --iters 500 \\\n",
|
| 90 |
+
" --adapter-path models/adapters/finance-lora\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"Loading fine-tuned model...\n",
|
| 93 |
+
"β
Model loaded with LoRA adapter\n",
|
| 94 |
+
"=== INPUT EMAIL ===\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"Dear Customer, Rs.2500.00 has been debited from account 3545 to VPA swiggy@ybl \n",
|
| 97 |
+
"for Swiggy order on 28-12-25. Your UPI transaction reference number is 534567891234. \n",
|
| 98 |
+
"If you did not authorize this transaction, please call 1800-XXX-XXXX.\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"=== MODEL OUTPUT ===\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"**<|end|><|assistant|> {\n",
|
| 105 |
+
"\n",
|
| 106 |
+
" \"amount\": \"2500\",\n",
|
| 107 |
+
"\n",
|
| 108 |
+
" \"type\": \"debit\",\n",
|
| 109 |
+
"\n",
|
| 110 |
+
" \"account\": \"3545\",\n",
|
| 111 |
+
"\n",
|
| 112 |
+
" \"date\": \"28-12-25\",\n",
|
| 113 |
+
"\n",
|
| 114 |
+
" \"reference\": \"534567891234\"\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"}<|end|>\n",
|
| 117 |
+
"=== INPUT EMAIL ===\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"Dear Customer, Rs.45,000.00 has been credited to your account 7890 \n",
|
| 120 |
+
"on 27-12-25. Salary from ACME CORP. Reference: NEFT123456789.\n",
|
| 121 |
+
"Available balance: Rs.52,340.00\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"=== MODEL OUTPUT ===\n",
|
| 125 |
+
"For any order related inquiries, please call our helpline: 1800-100-000.\n",
|
| 126 |
+
"- **credited** to account: (credited amount)\n",
|
| 127 |
+
"- **credited** to (type of transaction): (type of transaction)\n",
|
| 128 |
+
"- **credited** through (account type): (account type)\n",
|
| 129 |
+
"- **credited** on (date): (credit date)\n",
|
| 130 |
+
"- **credited** from (amount): (credited amount)\n",
|
| 131 |
+
"- **credited** by (reference): (reference number)\n",
|
| 132 |
+
"- **credited** (type of transaction): (type of transaction) (reference)\n",
|
| 133 |
+
"- **credited** (account type): (account type) (type of transaction)\n",
|
| 134 |
+
"- **credited** (date): (credit date) (type of transaction)\n",
|
| 135 |
+
"- **credited** (amount): (credited amount) (type of transaction)\n",
|
| 136 |
+
"- **credited\n",
|
| 137 |
+
"=== INPUT ===\n",
|
| 138 |
+
"Subject: Amount Credited to Your Account\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"Dear Customer, Rs.45,000.00 has been credited to your account 7890 \n",
|
| 141 |
+
"on 27-12-25. Salary from ACME CORP. Reference: NEFT123456789.\n",
|
| 142 |
+
"Available balance: Rs.52,340.00\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"=== MODEL OUTPUT ===\n",
|
| 145 |
+
"This is in addition to your standing balance of Rs.1,000.00. For any order related queries, please reach us at .<|end|><|assistant|> {\n",
|
| 146 |
+
" \"amount\": \"45000\",\n",
|
| 147 |
+
" \"type\": \"credit\"\n",
|
| 148 |
+
"}<|end|>\n",
|
| 149 |
+
"To merge the model, run this in Terminal:\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"cd /Users/ranjit/llm-mail-trainer\n",
|
| 152 |
+
"source venv/bin/activate\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"mlx_lm.fuse \\\n",
|
| 155 |
+
" --model models/base/phi3-mini \\\n",
|
| 156 |
+
" --adapter-path models/adapters/finance-lora \\\n",
|
| 157 |
+
" --save-path models/merged/finance-llm\n",
|
| 158 |
+
"\n"
|
| 159 |
+
]
|
| 160 |
+
}
|
| 161 |
+
],
|
| 162 |
+
"source": [
|
| 163 |
+
"# Cell 1: Imports & Load Data\n",
|
| 164 |
+
"import json\n",
|
| 165 |
+
"import re\n",
|
| 166 |
+
"import random\n",
|
| 167 |
+
"from pathlib import Path\n",
|
| 168 |
+
"from collections import Counter\n",
|
| 169 |
+
"from mlx_lm import load, generate\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"PROJECT = Path.home() / \"llm-mail-trainer\"\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"# Load all parsed emails (40k)\n",
|
| 174 |
+
"with open(PROJECT / \"data/parsed/emails.json\", 'r') as f:\n",
|
| 175 |
+
" all_emails = json.load(f)\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"# Load discovered patterns\n",
|
| 178 |
+
"with open(PROJECT / \"data/filtered/finance_patterns.json\", 'r') as f:\n",
|
| 179 |
+
" patterns = json.load(f)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"print(f\"β
Loaded {len(all_emails):,} emails\")\n",
|
| 182 |
+
"print(f\"β
Loaded patterns:\")\n",
|
| 183 |
+
"print(f\" Senders: {patterns['finance_senders']}\")\n",
|
| 184 |
+
"print(f\" Keywords: {patterns['finance_keywords']}\")\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"# Cell 2: Filter full dataset using discovered patterns\n",
|
| 187 |
+
"def is_finance_email(email):\n",
|
| 188 |
+
" \"\"\"Check if email is finance-related using discovered patterns.\"\"\"\n",
|
| 189 |
+
" \n",
|
| 190 |
+
" sender = email['sender'].lower()\n",
|
| 191 |
+
" subject = email['subject'].lower()\n",
|
| 192 |
+
" body = email['body'].lower()\n",
|
| 193 |
+
" combined = f\"{sender} {subject} {body}\"\n",
|
| 194 |
+
" \n",
|
| 195 |
+
" # Check sender patterns\n",
|
| 196 |
+
" for s in patterns['finance_senders']:\n",
|
| 197 |
+
" if s in sender:\n",
|
| 198 |
+
" return True\n",
|
| 199 |
+
" \n",
|
| 200 |
+
" # Check keywords in subject or body\n",
|
| 201 |
+
" for kw in patterns['finance_keywords']:\n",
|
| 202 |
+
" if kw in combined:\n",
|
| 203 |
+
" return True\n",
|
| 204 |
+
" \n",
|
| 205 |
+
" return False\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"# Apply filter to all emails\n",
|
| 208 |
+
"finance_emails = [e for e in all_emails if is_finance_email(e)]\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"print(f\"Total emails: {len(all_emails):,}\")\n",
|
| 211 |
+
"print(f\"Finance emails found: {len(finance_emails):,}\")\n",
|
| 212 |
+
"print(f\"Percentage: {len(finance_emails)/len(all_emails)*100:.1f}%\")\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"# Show sample\n",
|
| 215 |
+
"print(f\"\\n=== SAMPLE FINANCE EMAILS ===\")\n",
|
| 216 |
+
"for i, email in enumerate(finance_emails[:5]):\n",
|
| 217 |
+
" print(f\"{i+1}. {email['subject'][:60]}\")\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"# Cell 3: Stricter filter - transaction emails only\n",
|
| 220 |
+
"def is_transaction_email(email):\n",
|
| 221 |
+
" \"\"\"Check if email contains actual transaction data.\"\"\"\n",
|
| 222 |
+
" \n",
|
| 223 |
+
" body = email['body'].lower()\n",
|
| 224 |
+
" subject = email['subject'].lower()\n",
|
| 225 |
+
" combined = f\"{subject} {body}\"\n",
|
| 226 |
+
" \n",
|
| 227 |
+
" # Must have transaction indicators\n",
|
| 228 |
+
" has_transaction = any(kw in combined for kw in ['debited', 'credited', 'payment of', 'transferred'])\n",
|
| 229 |
+
" \n",
|
| 230 |
+
" # Must have amount pattern (Rs. or βΉ)\n",
|
| 231 |
+
" has_amount = bool(re.search(r'(?:rs\\.?|οΏ½οΏ½οΏ½)\\s*[\\d,]+', combined))\n",
|
| 232 |
+
" \n",
|
| 233 |
+
" # Must have account reference\n",
|
| 234 |
+
" has_account = bool(re.search(r'(?:account|a/c|ac no)', combined))\n",
|
| 235 |
+
" \n",
|
| 236 |
+
" return has_transaction and has_amount\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"# Apply stricter filter\n",
|
| 239 |
+
"transaction_emails = [e for e in all_emails if is_transaction_email(e)]\n",
|
| 240 |
+
"\n",
|
| 241 |
+
"print(f\"Transaction emails found: {len(transaction_emails):,}\")\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"# Show samples\n",
|
| 244 |
+
"print(f\"\\n=== SAMPLE TRANSACTION EMAILS ===\")\n",
|
| 245 |
+
"for i, email in enumerate(transaction_emails[:5]):\n",
|
| 246 |
+
" print(f\"\\n{i+1}. Subject: {email['subject'][:70]}\")\n",
|
| 247 |
+
" print(f\" Body: {email['body'][:150]}...\")\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"# Cell 4: Entity extraction function\n",
|
| 250 |
+
"def extract_entities(text):\n",
|
| 251 |
+
" \"\"\"Extract financial entities from email text.\"\"\"\n",
|
| 252 |
+
" \n",
|
| 253 |
+
" entities = {}\n",
|
| 254 |
+
" \n",
|
| 255 |
+
" # Amount\n",
|
| 256 |
+
" amount_match = re.search(r'(?:Rs\\.?|βΉ)\\s*([\\d,]+(?:\\.\\d{2})?)', text)\n",
|
| 257 |
+
" if amount_match:\n",
|
| 258 |
+
" entities['amount'] = amount_match.group(1).replace(',', '')\n",
|
| 259 |
+
" \n",
|
| 260 |
+
" # Type\n",
|
| 261 |
+
" if 'debited' in text.lower():\n",
|
| 262 |
+
" entities['type'] = 'debit'\n",
|
| 263 |
+
" elif 'credited' in text.lower():\n",
|
| 264 |
+
" entities['type'] = 'credit'\n",
|
| 265 |
+
" \n",
|
| 266 |
+
" # Account\n",
|
| 267 |
+
" account_match = re.search(r'(?:account|A/C|a/c)\\s*[:\\s]?\\s*(\\w+)', text, re.IGNORECASE)\n",
|
| 268 |
+
" if account_match:\n",
|
| 269 |
+
" entities['account'] = account_match.group(1)\n",
|
| 270 |
+
" \n",
|
| 271 |
+
" # Date\n",
|
| 272 |
+
" date_match = re.search(r'(\\d{2}-\\d{2}-\\d{2,4})', text)\n",
|
| 273 |
+
" if date_match:\n",
|
| 274 |
+
" entities['date'] = date_match.group(1)\n",
|
| 275 |
+
" \n",
|
| 276 |
+
" # Reference\n",
|
| 277 |
+
" ref_match = re.search(r'reference\\s*(?:number|no\\.?)?\\s*(?:is)?\\s*(\\d+)', text, re.IGNORECASE)\n",
|
| 278 |
+
" if ref_match:\n",
|
| 279 |
+
" entities['reference'] = ref_match.group(1)\n",
|
| 280 |
+
" \n",
|
| 281 |
+
" return entities\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"# Test\n",
|
| 284 |
+
"sample = transaction_emails[0]\n",
|
| 285 |
+
"print(f\"Subject: {sample['subject'][:60]}\")\n",
|
| 286 |
+
"print(f\"Extracted: {extract_entities(sample['body'])}\")\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"# Cell 5: Create training data for fine-tuning\n",
|
| 289 |
+
"training_data = []\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"for email in transaction_emails:\n",
|
| 292 |
+
" entities = extract_entities(email['body'])\n",
|
| 293 |
+
" \n",
|
| 294 |
+
" # Skip if no entities extracted\n",
|
| 295 |
+
" if len(entities) < 2:\n",
|
| 296 |
+
" continue\n",
|
| 297 |
+
" \n",
|
| 298 |
+
" # Create training example\n",
|
| 299 |
+
" example = {\n",
|
| 300 |
+
" \"prompt\": f\"Extract financial entities from this email:\\n\\nSubject: {email['subject']}\\n\\nBody: {email['body'][:1500]}\",\n",
|
| 301 |
+
" \"completion\": json.dumps(entities, indent=2)\n",
|
| 302 |
+
" }\n",
|
| 303 |
+
" \n",
|
| 304 |
+
" training_data.append(example)\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"print(f\"Training examples created: {len(training_data)}\")\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"# Show sample\n",
|
| 309 |
+
"print(f\"\\n=== SAMPLE TRAINING EXAMPLE ===\")\n",
|
| 310 |
+
"print(f\"PROMPT:\\n{training_data[0]['prompt'][:300]}...\")\n",
|
| 311 |
+
"print(f\"\\nCOMPLETION:\\n{training_data[0]['completion']}\")\n",
|
| 312 |
+
"\n",
|
| 313 |
+
"# Cell 6: Split and save training data\n",
|
| 314 |
+
"random.seed(42)\n",
|
| 315 |
+
"random.shuffle(training_data)\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"# Split: 90% train, 10% validation\n",
|
| 318 |
+
"split_idx = int(len(training_data) * 0.9)\n",
|
| 319 |
+
"train_data = training_data[:split_idx]\n",
|
| 320 |
+
"valid_data = training_data[split_idx:]\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"print(f\"Train set: {len(train_data)}\")\n",
|
| 323 |
+
"print(f\"Validation set: {len(valid_data)}\")\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"# Save as JSONL (required format for MLX)\n",
|
| 326 |
+
"training_dir = PROJECT / \"data/training\"\n",
|
| 327 |
+
"training_dir.mkdir(exist_ok=True)\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"# Save train.jsonl\n",
|
| 330 |
+
"with open(training_dir / \"train.jsonl\", 'w') as f:\n",
|
| 331 |
+
" for example in train_data:\n",
|
| 332 |
+
" f.write(json.dumps(example) + '\\n')\n",
|
| 333 |
+
"\n",
|
| 334 |
+
"# Save valid.jsonl\n",
|
| 335 |
+
"with open(training_dir / \"valid.jsonl\", 'w') as f:\n",
|
| 336 |
+
" for example in valid_data:\n",
|
| 337 |
+
" f.write(json.dumps(example) + '\\n')\n",
|
| 338 |
+
"\n",
|
| 339 |
+
"print(f\"\\nβ
Saved to {training_dir}/\")\n",
|
| 340 |
+
"print(f\" train.jsonl ({len(train_data)} examples)\")\n",
|
| 341 |
+
"print(f\" valid.jsonl ({len(valid_data)} examples)\")\n",
|
| 342 |
+
"\n",
|
| 343 |
+
"# Cell 7: Fine-tune configuration\n",
|
| 344 |
+
"print(\"=== FINE-TUNING SETUP ===\")\n",
|
| 345 |
+
"print(f\"Base model: {PROJECT / 'models/base/phi3-mini'}\")\n",
|
| 346 |
+
"print(f\"Training data: {PROJECT / 'data/training/train.jsonl'}\")\n",
|
| 347 |
+
"print(f\"Validation data: {PROJECT / 'data/training/valid.jsonl'}\")\n",
|
| 348 |
+
"print(f\"Output: {PROJECT / 'models/adapters/finance-lora'}\")\n",
|
| 349 |
+
"\n",
|
| 350 |
+
"print(\"\\nβ οΈ Fine-tuning will take 1-2 hours\")\n",
|
| 351 |
+
"print(\"Run the following command in Terminal (not in notebook):\")\n",
|
| 352 |
+
"\n",
|
| 353 |
+
"command = f\"\"\"\n",
|
| 354 |
+
"cd {PROJECT}\n",
|
| 355 |
+
"source venv/bin/activate\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"mlx_lm.lora \\\\\n",
|
| 358 |
+
" --model models/base/phi3-mini \\\\\n",
|
| 359 |
+
" --data data/training \\\\\n",
|
| 360 |
+
" --train \\\\\n",
|
| 361 |
+
" --batch-size 1 \\\\\n",
|
| 362 |
+
" --lora-layers 8 \\\\\n",
|
| 363 |
+
" --iters 500 \\\\\n",
|
| 364 |
+
" --adapter-path models/adapters/finance-lora\n",
|
| 365 |
+
"\"\"\"\n",
|
| 366 |
+
"\n",
|
| 367 |
+
"print(command)\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"# Cell 8: Test fine-tuned model\n",
|
| 370 |
+
"\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"# Load base model with fine-tuned adapter\n",
|
| 373 |
+
"model_path = str(PROJECT / \"models/base/phi3-mini\")\n",
|
| 374 |
+
"adapter_path = str(PROJECT / \"models/adapters/finance-lora\")\n",
|
| 375 |
+
"\n",
|
| 376 |
+
"print(\"Loading fine-tuned model...\")\n",
|
| 377 |
+
"model, tokenizer = load(model_path, adapter_path=adapter_path)\n",
|
| 378 |
+
"print(\"β
Model loaded with LoRA adapter\")\n",
|
| 379 |
+
"\n",
|
| 380 |
+
"# Cell 9: Test entity extraction on sample email\n",
|
| 381 |
+
"test_email = \"\"\"\n",
|
| 382 |
+
"Dear Customer, Rs.2500.00 has been debited from account 3545 to VPA swiggy@ybl \n",
|
| 383 |
+
"for Swiggy order on 28-12-25. Your UPI transaction reference number is 534567891234. \n",
|
| 384 |
+
"If you did not authorize this transaction, please call 1800-XXX-XXXX.\n",
|
| 385 |
+
"\"\"\"\n",
|
| 386 |
+
"\n",
|
| 387 |
+
"prompt = f\"Extract financial entities from this email:\\n\\n{test_email}\"\n",
|
| 388 |
+
"\n",
|
| 389 |
+
"print(\"=== INPUT EMAIL ===\")\n",
|
| 390 |
+
"print(test_email)\n",
|
| 391 |
+
"print(\"\\n=== MODEL OUTPUT ===\")\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"response = generate(\n",
|
| 394 |
+
" model,\n",
|
| 395 |
+
" tokenizer,\n",
|
| 396 |
+
" prompt=prompt,\n",
|
| 397 |
+
" max_tokens=200,\n",
|
| 398 |
+
" verbose=False\n",
|
| 399 |
+
")\n",
|
| 400 |
+
"\n",
|
| 401 |
+
"print(response)\n",
|
| 402 |
+
"\n",
|
| 403 |
+
"# Cell 10: Test on credit transaction\n",
|
| 404 |
+
"test_email_2 = \"\"\"\n",
|
| 405 |
+
"Dear Customer, Rs.45,000.00 has been credited to your account 7890 \n",
|
| 406 |
+
"on 27-12-25. Salary from ACME CORP. Reference: NEFT123456789.\n",
|
| 407 |
+
"Available balance: Rs.52,340.00\n",
|
| 408 |
+
"\"\"\"\n",
|
| 409 |
+
"\n",
|
| 410 |
+
"prompt = f\"Extract financial entities from this email:\\n\\n{test_email_2}\"\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"print(\"=== INPUT EMAIL ===\")\n",
|
| 413 |
+
"print(test_email_2)\n",
|
| 414 |
+
"print(\"\\n=== MODEL OUTPUT ===\")\n",
|
| 415 |
+
"\n",
|
| 416 |
+
"response = generate(\n",
|
| 417 |
+
" model,\n",
|
| 418 |
+
" tokenizer,\n",
|
| 419 |
+
" prompt=prompt,\n",
|
| 420 |
+
" max_tokens=200,\n",
|
| 421 |
+
" verbose=False\n",
|
| 422 |
+
")\n",
|
| 423 |
+
"\n",
|
| 424 |
+
"print(response)\n",
|
| 425 |
+
"\n",
|
| 426 |
+
"# Cell 11: Test credit transaction with better prompt\n",
|
| 427 |
+
"test_email_credit = \"\"\"Subject: Amount Credited to Your Account\n",
|
| 428 |
+
"\n",
|
| 429 |
+
"Dear Customer, Rs.45,000.00 has been credited to your account 7890 \n",
|
| 430 |
+
"on 27-12-25. Salary from ACME CORP. Reference: NEFT123456789.\n",
|
| 431 |
+
"Available balance: Rs.52,340.00\"\"\"\n",
|
| 432 |
+
"\n",
|
| 433 |
+
"prompt = f\"\"\"Extract financial entities from this email:\n",
|
| 434 |
+
"\n",
|
| 435 |
+
"Subject: Amount Credited to Your Account\n",
|
| 436 |
+
"\n",
|
| 437 |
+
"Body: {test_email_credit}\"\"\"\n",
|
| 438 |
+
"\n",
|
| 439 |
+
"print(\"=== INPUT ===\")\n",
|
| 440 |
+
"print(test_email_credit)\n",
|
| 441 |
+
"print(\"\\n=== MODEL OUTPUT ===\")\n",
|
| 442 |
+
"\n",
|
| 443 |
+
"response = generate(\n",
|
| 444 |
+
" model,\n",
|
| 445 |
+
" tokenizer,\n",
|
| 446 |
+
" prompt=prompt,\n",
|
| 447 |
+
" max_tokens=200,\n",
|
| 448 |
+
" verbose=False\n",
|
| 449 |
+
")\n",
|
| 450 |
+
"\n",
|
| 451 |
+
"print(response)\n",
|
| 452 |
+
"\n",
|
| 453 |
+
"# Cell 12: Merge LoRA adapter with base model\n",
|
| 454 |
+
"import shutil\n",
|
| 455 |
+
"\n",
|
| 456 |
+
"# Create merged model directory\n",
|
| 457 |
+
"merged_path = PROJECT / \"models/merged/finance-llm\"\n",
|
| 458 |
+
"merged_path.mkdir(parents=True, exist_ok=True)\n",
|
| 459 |
+
"\n",
|
| 460 |
+
"print(\"To merge the model, run this in Terminal:\")\n",
|
| 461 |
+
"print()\n",
|
| 462 |
+
"merge_command = f\"\"\"cd {PROJECT}\n",
|
| 463 |
+
"source venv/bin/activate\n",
|
| 464 |
+
"\n",
|
| 465 |
+
"mlx_lm.fuse \\\\\n",
|
| 466 |
+
" --model models/base/phi3-mini \\\\\n",
|
| 467 |
+
" --adapter-path models/adapters/finance-lora \\\\\n",
|
| 468 |
+
" --save-path models/merged/finance-llm\n",
|
| 469 |
+
"\"\"\"\n",
|
| 470 |
+
"print(merge_command)"
|
| 471 |
+
]
|
| 472 |
+
},
|
| 473 |
+
{
|
| 474 |
+
"cell_type": "code",
|
| 475 |
+
"execution_count": null,
|
| 476 |
+
"id": "ef29ad32-346f-477c-9bc2-d5ac87c79da1",
|
| 477 |
+
"metadata": {},
|
| 478 |
+
"outputs": [],
|
| 479 |
+
"source": []
|
| 480 |
+
}
|
| 481 |
+
],
|
| 482 |
+
"metadata": {
|
| 483 |
+
"kernelspec": {
|
| 484 |
+
"display_name": "Python 3 (ipykernel)",
|
| 485 |
+
"language": "python",
|
| 486 |
+
"name": "python3"
|
| 487 |
+
},
|
| 488 |
+
"language_info": {
|
| 489 |
+
"codemirror_mode": {
|
| 490 |
+
"name": "ipython",
|
| 491 |
+
"version": 3
|
| 492 |
+
},
|
| 493 |
+
"file_extension": ".py",
|
| 494 |
+
"mimetype": "text/x-python",
|
| 495 |
+
"name": "python",
|
| 496 |
+
"nbconvert_exporter": "python",
|
| 497 |
+
"pygments_lexer": "ipython3",
|
| 498 |
+
"version": "3.9.6"
|
| 499 |
+
}
|
| 500 |
+
},
|
| 501 |
+
"nbformat": 4,
|
| 502 |
+
"nbformat_minor": 5
|
| 503 |
+
}
|
05_add_credit_data.ipynb
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 5,
|
| 6 |
+
"id": "efb38197-c4bc-4508-a636-09d11f765ef0",
|
| 7 |
+
"metadata": {},
|
| 8 |
+
"outputs": [
|
| 9 |
+
{
|
| 10 |
+
"name": "stdout",
|
| 11 |
+
"output_type": "stream",
|
| 12 |
+
"text": [
|
| 13 |
+
"β
Loaded 40,820 emails\n",
|
| 14 |
+
"Credit transaction emails found: 131\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"=== SAMPLE CREDIT EMAILS ===\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"1. Subject: Meesho IPO's 46.40% listing gains, DGCA summons IndiGo CEO, \n",
|
| 19 |
+
" Body: All you need to know about the day Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β...\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"2. Subject: View: Account update for your HDFC Bank A/c\n",
|
| 22 |
+
" Body: HDFC BANK Dear Customer, Rs. 50000.00 is successfully credited to your account **3545 by VPA subhashreebadatya250@okicici SUBHASHREE BADATYA on 16-11-25. Your UPI transaction reference number is 53204...\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"3. Subject: Received Cashback from PhonePe\n",
|
| 25 |
+
" Body: Nov 1, 2025 Cashback from PhonePe βΉ 2.5 Txn. ID : T2511010958546075798981 Txn. status : Successful Credited to : Cashback/PhonePe Gift Card Amount: βΉ 2.5 Order ID : T2510252053346470859826 Hi Ranjit B...\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"4. Subject: Received Cashback from PhonePe\n",
|
| 28 |
+
" Body: Nov 1, 2025 Cashback from PhonePe βΉ 1.5 Txn. ID : T2511010958450137616439 Txn. status : Successful Credited to : Cashback/PhonePe Gift Card Amount: βΉ 1.5 Order ID : T2510261508320443718485 Hi Ranjit B...\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"5. Subject: Job Oppurtunity for Java Fullstack Developer at CAPCO Techno\n",
|
| 31 |
+
" Body: Hi There , I hope you are doing well. Please find the below Job Description (JD) for the position of J*ava Fullstack Developer at CAPCO Technologies* . We believe your profile aligns well with the req...\n",
|
| 32 |
+
"Credit training examples created: 74\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"=== SAMPLE CREDIT TRAINING EXAMPLE ===\n",
|
| 35 |
+
"PROMPT:\n",
|
| 36 |
+
"Extract financial entities from this email:\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"Subject: Meesho IPO's 46.40% listing gains, DGCA summons IndiGo CEO, & more - Groww Digest\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"Body: All you need to know about the day Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν β ο»Ώ Ν ...\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"COMPLETION:\n",
|
| 43 |
+
"{\n",
|
| 44 |
+
" \"amount\": \"7228.50\",\n",
|
| 45 |
+
" \"type\": \"credit\"\n",
|
| 46 |
+
"}\n",
|
| 47 |
+
"Existing training examples: 390\n",
|
| 48 |
+
"Existing validation examples: 44\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"New credit train: 66\n",
|
| 51 |
+
"New credit valid: 8\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"=== COMBINED DATASET ===\n",
|
| 54 |
+
"Total train: 456\n",
|
| 55 |
+
"Total valid: 52\n",
|
| 56 |
+
"β
Backed up old data to /Users/ranjit/llm-mail-trainer/data/training_backup_v1\n",
|
| 57 |
+
"β
Saved new training data:\n",
|
| 58 |
+
" train.jsonl (456 examples)\n",
|
| 59 |
+
" valid.jsonl (52 examples)\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"=== DATA BALANCE ===\n",
|
| 62 |
+
"Debit examples: 186\n",
|
| 63 |
+
"Credit examples: 187\n",
|
| 64 |
+
"=== RETRAIN WITH CREDIT DATA ===\n",
|
| 65 |
+
"\n",
|
| 66 |
+
"Run this command in Terminal:\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"cd /Users/ranjit/llm-mail-trainer\n",
|
| 69 |
+
"source venv/bin/activate\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"mlx_lm.lora \\\n",
|
| 72 |
+
" --model models/base/phi3-mini \\\n",
|
| 73 |
+
" --data data/training \\\n",
|
| 74 |
+
" --train \\\n",
|
| 75 |
+
" --batch-size 1 \\\n",
|
| 76 |
+
" --num-layers 8 \\\n",
|
| 77 |
+
" --iters 600 \\\n",
|
| 78 |
+
" --adapter-path models/adapters/finance-lora-v2\n",
|
| 79 |
+
"\n",
|
| 80 |
+
"\n",
|
| 81 |
+
"Note: New adapter saved as 'finance-lora-v2'\n",
|
| 82 |
+
"Iterations increased to 600 (more data)\n"
|
| 83 |
+
]
|
| 84 |
+
}
|
| 85 |
+
],
|
| 86 |
+
"source": [
|
| 87 |
+
"# Cell 1: Load data and find credit transactions\n",
|
| 88 |
+
"import json\n",
|
| 89 |
+
"import re\n",
|
| 90 |
+
"import random\n",
|
| 91 |
+
"import shutil\n",
|
| 92 |
+
"from pathlib import Path\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"PROJECT = Path.home() / \"llm-mail-trainer\"\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"# Load all emails\n",
|
| 97 |
+
"with open(PROJECT / \"data/parsed/emails.json\", 'r') as f:\n",
|
| 98 |
+
" all_emails = json.load(f)\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"print(f\"β
Loaded {len(all_emails):,} emails\")\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"# Find credit transactions\n",
|
| 103 |
+
"credit_emails = []\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"for email in all_emails:\n",
|
| 106 |
+
" body = email['body'].lower()\n",
|
| 107 |
+
" subject = email['subject'].lower()\n",
|
| 108 |
+
" combined = f\"{subject} {body}\"\n",
|
| 109 |
+
" \n",
|
| 110 |
+
" # Must have \"credited\" and amount\n",
|
| 111 |
+
" if 'credited' in combined:\n",
|
| 112 |
+
" if re.search(r'(?:rs\\.?|βΉ)\\s*[\\d,]+', combined):\n",
|
| 113 |
+
" credit_emails.append(email)\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"print(f\"Credit transaction emails found: {len(credit_emails)}\")\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"# Show samples\n",
|
| 118 |
+
"print(\"\\n=== SAMPLE CREDIT EMAILS ===\")\n",
|
| 119 |
+
"for i, email in enumerate(credit_emails[:5]):\n",
|
| 120 |
+
" print(f\"\\n{i+1}. Subject: {email['subject'][:60]}\")\n",
|
| 121 |
+
" print(f\" Body: {email['body'][:200]}...\")\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"# Cell 2: Entity extraction function\n",
|
| 125 |
+
"def extract_entities(text):\n",
|
| 126 |
+
" \"\"\"Extract financial entities from email text.\"\"\"\n",
|
| 127 |
+
" \n",
|
| 128 |
+
" entities = {}\n",
|
| 129 |
+
" \n",
|
| 130 |
+
" # Amount\n",
|
| 131 |
+
" amount_match = re.search(r'(?:Rs\\.?|βΉ)\\s*([\\d,]+(?:\\.\\d{2})?)', text)\n",
|
| 132 |
+
" if amount_match:\n",
|
| 133 |
+
" entities['amount'] = amount_match.group(1).replace(',', '')\n",
|
| 134 |
+
" \n",
|
| 135 |
+
" # Type\n",
|
| 136 |
+
" if 'debited' in text.lower():\n",
|
| 137 |
+
" entities['type'] = 'debit'\n",
|
| 138 |
+
" elif 'credited' in text.lower():\n",
|
| 139 |
+
" entities['type'] = 'credit'\n",
|
| 140 |
+
" \n",
|
| 141 |
+
" # Account\n",
|
| 142 |
+
" account_match = re.search(r'(?:account|A/C|a/c)\\s*[:\\s]?\\s*(\\w+)', text, re.IGNORECASE)\n",
|
| 143 |
+
" if account_match:\n",
|
| 144 |
+
" entities['account'] = account_match.group(1)\n",
|
| 145 |
+
" \n",
|
| 146 |
+
" # Date\n",
|
| 147 |
+
" date_match = re.search(r'(\\d{2}-\\d{2}-\\d{2,4})', text)\n",
|
| 148 |
+
" if date_match:\n",
|
| 149 |
+
" entities['date'] = date_match.group(1)\n",
|
| 150 |
+
" \n",
|
| 151 |
+
" # Reference\n",
|
| 152 |
+
" ref_match = re.search(r'reference\\s*(?:number|no\\.?)?\\s*(?:is)?\\s*(\\d+)', text, re.IGNORECASE)\n",
|
| 153 |
+
" if ref_match:\n",
|
| 154 |
+
" entities['reference'] = ref_match.group(1)\n",
|
| 155 |
+
" \n",
|
| 156 |
+
" return entities\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"# Create training examples from credit emails\n",
|
| 159 |
+
"credit_training = []\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"for email in credit_emails:\n",
|
| 162 |
+
" entities = extract_entities(email['body'])\n",
|
| 163 |
+
" \n",
|
| 164 |
+
" # Must have at least amount and type\n",
|
| 165 |
+
" if 'amount' in entities and 'type' in entities:\n",
|
| 166 |
+
" example = {\n",
|
| 167 |
+
" \"prompt\": f\"Extract financial entities from this email:\\n\\nSubject: {email['subject']}\\n\\nBody: {email['body'][:1500]}\",\n",
|
| 168 |
+
" \"completion\": json.dumps(entities, indent=2)\n",
|
| 169 |
+
" }\n",
|
| 170 |
+
" credit_training.append(example)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"print(f\"Credit training examples created: {len(credit_training)}\")\n",
|
| 173 |
+
"\n",
|
| 174 |
+
"# Show sample\n",
|
| 175 |
+
"print(f\"\\n=== SAMPLE CREDIT TRAINING EXAMPLE ===\")\n",
|
| 176 |
+
"print(f\"PROMPT:\\n{credit_training[0]['prompt'][:300]}...\")\n",
|
| 177 |
+
"print(f\"\\nCOMPLETION:\\n{credit_training[0]['completion']}\")\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"# Cell 3: Load existing training data and combine\n",
|
| 180 |
+
"training_dir = PROJECT / \"data/training\"\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"# Load existing training data\n",
|
| 183 |
+
"existing_train = []\n",
|
| 184 |
+
"with open(training_dir / \"train.jsonl\", 'r') as f:\n",
|
| 185 |
+
" for line in f:\n",
|
| 186 |
+
" existing_train.append(json.loads(line))\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"existing_valid = []\n",
|
| 189 |
+
"with open(training_dir / \"valid.jsonl\", 'r') as f:\n",
|
| 190 |
+
" for line in f:\n",
|
| 191 |
+
" existing_valid.append(json.loads(line))\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"print(f\"Existing training examples: {len(existing_train)}\")\n",
|
| 194 |
+
"print(f\"Existing validation examples: {len(existing_valid)}\")\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"# Split credit data: 90% train, 10% validation\n",
|
| 197 |
+
"random.seed(42)\n",
|
| 198 |
+
"random.shuffle(credit_training)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"split_idx = int(len(credit_training) * 0.9)\n",
|
| 201 |
+
"credit_train = credit_training[:split_idx]\n",
|
| 202 |
+
"credit_valid = credit_training[split_idx:]\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"print(f\"\\nNew credit train: {len(credit_train)}\")\n",
|
| 205 |
+
"print(f\"New credit valid: {len(credit_valid)}\")\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"# Combine\n",
|
| 208 |
+
"combined_train = existing_train + credit_train\n",
|
| 209 |
+
"combined_valid = existing_valid + credit_valid\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"# Shuffle combined data\n",
|
| 212 |
+
"random.shuffle(combined_train)\n",
|
| 213 |
+
"random.shuffle(combined_valid)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"print(f\"\\n=== COMBINED DATASET ===\")\n",
|
| 216 |
+
"print(f\"Total train: {len(combined_train)}\")\n",
|
| 217 |
+
"print(f\"Total valid: {len(combined_valid)}\")\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"# Cell 4: Backup old data and save new combined data\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"backup_dir = PROJECT / \"data/training_backup_v1\"\n",
|
| 222 |
+
"backup_dir.mkdir(exist_ok=True)\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"shutil.copy(training_dir / \"train.jsonl\", backup_dir / \"train.jsonl\")\n",
|
| 225 |
+
"shutil.copy(training_dir / \"valid.jsonl\", backup_dir / \"valid.jsonl\")\n",
|
| 226 |
+
"print(f\"β
Backed up old data to {backup_dir}\")\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"# Save combined data\n",
|
| 229 |
+
"with open(training_dir / \"train.jsonl\", 'w') as f:\n",
|
| 230 |
+
" for example in combined_train:\n",
|
| 231 |
+
" f.write(json.dumps(example) + '\\n')\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"with open(training_dir / \"valid.jsonl\", 'w') as f:\n",
|
| 234 |
+
" for example in combined_valid:\n",
|
| 235 |
+
" f.write(json.dumps(example) + '\\n')\n",
|
| 236 |
+
"\n",
|
| 237 |
+
"print(f\"β
Saved new training data:\")\n",
|
| 238 |
+
"print(f\" train.jsonl ({len(combined_train)} examples)\")\n",
|
| 239 |
+
"print(f\" valid.jsonl ({len(combined_valid)} examples)\")\n",
|
| 240 |
+
"\n",
|
| 241 |
+
"# Check balance of debit vs credit\n",
|
| 242 |
+
"debit_count = sum(1 for e in combined_train if '\"type\": \"debit\"' in e['completion'])\n",
|
| 243 |
+
"credit_count = sum(1 for e in combined_train if '\"type\": \"credit\"' in e['completion'])\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"print(f\"\\n=== DATA BALANCE ===\")\n",
|
| 246 |
+
"print(f\"Debit examples: {debit_count}\")\n",
|
| 247 |
+
"print(f\"Credit examples: {credit_count}\")\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"# Cell 5: Retrain command\n",
|
| 250 |
+
"print(\"=== RETRAIN WITH CREDIT DATA ===\")\n",
|
| 251 |
+
"print()\n",
|
| 252 |
+
"print(\"Run this command in Terminal:\")\n",
|
| 253 |
+
"print()\n",
|
| 254 |
+
"\n",
|
| 255 |
+
"command = f\"\"\"cd {PROJECT}\n",
|
| 256 |
+
"source venv/bin/activate\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"mlx_lm.lora \\\\\n",
|
| 259 |
+
" --model models/base/phi3-mini \\\\\n",
|
| 260 |
+
" --data data/training \\\\\n",
|
| 261 |
+
" --train \\\\\n",
|
| 262 |
+
" --batch-size 1 \\\\\n",
|
| 263 |
+
" --num-layers 8 \\\\\n",
|
| 264 |
+
" --iters 600 \\\\\n",
|
| 265 |
+
" --adapter-path models/adapters/finance-lora-v2\n",
|
| 266 |
+
"\"\"\"\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"print(command)\n",
|
| 269 |
+
"print()\n",
|
| 270 |
+
"print(\"Note: New adapter saved as 'finance-lora-v2'\")\n",
|
| 271 |
+
"print(\"Iterations increased to 600 (more data)\")"
|
| 272 |
+
]
|
| 273 |
+
},
|
| 274 |
+
{
|
| 275 |
+
"cell_type": "code",
|
| 276 |
+
"execution_count": null,
|
| 277 |
+
"id": "6cbb8c74-8796-47a3-a4ed-fe790e32561f",
|
| 278 |
+
"metadata": {},
|
| 279 |
+
"outputs": [],
|
| 280 |
+
"source": []
|
| 281 |
+
}
|
| 282 |
+
],
|
| 283 |
+
"metadata": {
|
| 284 |
+
"kernelspec": {
|
| 285 |
+
"display_name": "Python 3 (ipykernel)",
|
| 286 |
+
"language": "python",
|
| 287 |
+
"name": "python3"
|
| 288 |
+
},
|
| 289 |
+
"language_info": {
|
| 290 |
+
"codemirror_mode": {
|
| 291 |
+
"name": "ipython",
|
| 292 |
+
"version": 3
|
| 293 |
+
},
|
| 294 |
+
"file_extension": ".py",
|
| 295 |
+
"mimetype": "text/x-python",
|
| 296 |
+
"name": "python",
|
| 297 |
+
"nbconvert_exporter": "python",
|
| 298 |
+
"pygments_lexer": "ipython3",
|
| 299 |
+
"version": "3.9.6"
|
| 300 |
+
}
|
| 301 |
+
},
|
| 302 |
+
"nbformat": 4,
|
| 303 |
+
"nbformat_minor": 5
|
| 304 |
+
}
|
06_statement_extraction.ipynb
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# π Phase 2: Bank Statement Row Extraction\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"This notebook guides you through Phase 2 of the model upgrade:\n",
|
| 10 |
+
"- Extract text rows from bank statement PDFs\n",
|
| 11 |
+
"- Label rows with entities\n",
|
| 12 |
+
"- Generate synthetic variations\n",
|
| 13 |
+
"- Prepare training data with [BANK_STATEMENT] prefix\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"## Goal\n",
|
| 16 |
+
"**Model parses bank statement rows with high accuracy**"
|
| 17 |
+
]
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "markdown",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"source": [
|
| 23 |
+
"## Step 1: Setup & Check PDF Files\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"Place your bank statements in: `data/raw/pdfs/statements/`"
|
| 26 |
+
]
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"outputs": [],
|
| 33 |
+
"source": [
|
| 34 |
+
"from pathlib import Path\n",
|
| 35 |
+
"import json\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"# Setup directories\n",
|
| 38 |
+
"PROJECT_ROOT = Path.cwd()\n",
|
| 39 |
+
"PDF_DIR = PROJECT_ROOT / \"data/raw/pdfs/statements\"\n",
|
| 40 |
+
"LABELING_DIR = PROJECT_ROOT / \"data/labeling\"\n",
|
| 41 |
+
"TRAINING_DIR = PROJECT_ROOT / \"data/training\"\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"# Create directories\n",
|
| 44 |
+
"PDF_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 45 |
+
"LABELING_DIR.mkdir(parents=True, exist_ok=True)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"# Check for PDFs\n",
|
| 48 |
+
"pdfs = list(PDF_DIR.glob(\"*.pdf\")) + list(PDF_DIR.glob(\"*.PDF\"))\n",
|
| 49 |
+
"print(f\"π Found {len(pdfs)} PDF files in {PDF_DIR}\")\n",
|
| 50 |
+
"for pdf in pdfs:\n",
|
| 51 |
+
" print(f\" β’ {pdf.name}\")"
|
| 52 |
+
]
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "markdown",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"## Step 2: Extract Rows from PDFs"
|
| 59 |
+
]
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"execution_count": null,
|
| 64 |
+
"metadata": {},
|
| 65 |
+
"outputs": [],
|
| 66 |
+
"source": [
|
| 67 |
+
"from src.data.statement_extractor import StatementRowExtractor\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"extractor = StatementRowExtractor(debug=False)\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"all_rows = []\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"for pdf in pdfs:\n",
|
| 74 |
+
" print(f\"\\nπ Processing: {pdf.name}\")\n",
|
| 75 |
+
" try:\n",
|
| 76 |
+
" rows, stats = extractor.extract_rows(pdf)\n",
|
| 77 |
+
" all_rows.extend(rows)\n",
|
| 78 |
+
" print(f\" β
Extracted {stats.valid_rows} rows ({stats.bank.upper()})\")\n",
|
| 79 |
+
" except Exception as e:\n",
|
| 80 |
+
" print(f\" β Error: {e}\")\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"print(f\"\\nπ Total rows extracted: {len(all_rows)}\")"
|
| 83 |
+
]
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "markdown",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"## Step 3: Preview Extracted Rows"
|
| 90 |
+
]
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"outputs": [],
|
| 97 |
+
"source": [
|
| 98 |
+
"import pandas as pd\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"# Convert to DataFrame for easy viewing\n",
|
| 101 |
+
"df = pd.DataFrame([r.to_dict() for r in all_rows])\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"# Display columns\n",
|
| 104 |
+
"display_cols = ['date', 'description', 'debit', 'credit', 'balance', 'bank']\n",
|
| 105 |
+
"cols = [c for c in display_cols if c in df.columns]\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"print(f\"π Sample rows (first 10):\")\n",
|
| 108 |
+
"df[cols].head(10)"
|
| 109 |
+
]
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "markdown",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": [
|
| 115 |
+
"## Step 4: Export for Manual Labeling\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"Export rows to JSON for manual entity labeling."
|
| 118 |
+
]
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"execution_count": null,
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"outputs": [],
|
| 125 |
+
"source": [
|
| 126 |
+
"output_file = LABELING_DIR / \"statement_rows_unlabeled.json\"\n",
|
| 127 |
+
"extractor.export_for_labeling(all_rows, output_file)\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"print(f\"β
Exported {len(all_rows)} rows to:\")\n",
|
| 130 |
+
"print(f\" {output_file}\")\n",
|
| 131 |
+
"print(f\"\\nπ Next: Open the JSON file and add 'entities' to each row\")"
|
| 132 |
+
]
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "markdown",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"## Step 5: Manual Labeling Guide\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"For each row, add the `entities` field with:\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"```json\n",
|
| 143 |
+
"{\n",
|
| 144 |
+
" \"raw_text\": \"01-12-2025 | UPI-SWIGGY@ybl | 250.00 | | 45,230.50\",\n",
|
| 145 |
+
" \"labeled\": true,\n",
|
| 146 |
+
" \"entities\": {\n",
|
| 147 |
+
" \"date\": \"01-12-2025\",\n",
|
| 148 |
+
" \"description\": \"UPI-SWIGGY@ybl\",\n",
|
| 149 |
+
" \"amount\": \"250.00\",\n",
|
| 150 |
+
" \"type\": \"debit\",\n",
|
| 151 |
+
" \"balance\": \"45,230.50\",\n",
|
| 152 |
+
" \"merchant\": \"swiggy\",\n",
|
| 153 |
+
" \"category\": \"food\"\n",
|
| 154 |
+
" }\n",
|
| 155 |
+
"}\n",
|
| 156 |
+
"```\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"**Target: Label 500+ rows**"
|
| 159 |
+
]
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "markdown",
|
| 163 |
+
"metadata": {},
|
| 164 |
+
"source": [
|
| 165 |
+
"## Step 6: Load Labeled Data"
|
| 166 |
+
]
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"cell_type": "code",
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"metadata": {},
|
| 172 |
+
"outputs": [],
|
| 173 |
+
"source": [
|
| 174 |
+
"# After manual labeling, load the data\n",
|
| 175 |
+
"labeled_file = LABELING_DIR / \"statement_rows_labeled.json\"\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"if labeled_file.exists():\n",
|
| 178 |
+
" labeled_rows = extractor.load_labeled_data(labeled_file)\n",
|
| 179 |
+
" labeled_count = sum(1 for r in labeled_rows if r.labeled)\n",
|
| 180 |
+
" print(f\"π Loaded {len(labeled_rows)} rows ({labeled_count} labeled)\")\n",
|
| 181 |
+
"else:\n",
|
| 182 |
+
" print(f\"β οΈ Labeled file not found: {labeled_file}\")\n",
|
| 183 |
+
" print(f\" Rename your labeled file to: statement_rows_labeled.json\")"
|
| 184 |
+
]
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "markdown",
|
| 188 |
+
"metadata": {},
|
| 189 |
+
"source": [
|
| 190 |
+
"## Step 7: Generate Synthetic Variations"
|
| 191 |
+
]
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"cell_type": "code",
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"metadata": {},
|
| 197 |
+
"outputs": [],
|
| 198 |
+
"source": [
|
| 199 |
+
"from src.data.statement_extractor import StatementSyntheticGenerator\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"generator = StatementSyntheticGenerator(seed=42)\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"# Generate variations from labeled data\n",
|
| 204 |
+
"if 'labeled_rows' in dir() and labeled_rows:\n",
|
| 205 |
+
" # Filter to labeled only\n",
|
| 206 |
+
" base_rows = [r for r in labeled_rows if r.labeled]\n",
|
| 207 |
+
" \n",
|
| 208 |
+
" # Generate 5x variations\n",
|
| 209 |
+
" synthetic_rows = generator.generate_variations(\n",
|
| 210 |
+
" base_rows, \n",
|
| 211 |
+
" variations_per_row=5,\n",
|
| 212 |
+
" total_limit=2000\n",
|
| 213 |
+
" )\n",
|
| 214 |
+
" \n",
|
| 215 |
+
" print(f\"β
Generated {len(synthetic_rows)} synthetic variations\")\n",
|
| 216 |
+
"else:\n",
|
| 217 |
+
" print(\"β οΈ Load labeled data first (Step 6)\")"
|
| 218 |
+
]
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "markdown",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"source": [
|
| 224 |
+
"## Step 8: Export Training Data"
|
| 225 |
+
]
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"cell_type": "code",
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"metadata": {},
|
| 231 |
+
"outputs": [],
|
| 232 |
+
"source": [
|
| 233 |
+
"from src.data.statement_extractor import export_training_data\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"if 'synthetic_rows' in dir() and synthetic_rows:\n",
|
| 236 |
+
" # Combine labeled + synthetic\n",
|
| 237 |
+
" all_training = base_rows + synthetic_rows\n",
|
| 238 |
+
" \n",
|
| 239 |
+
" # Export\n",
|
| 240 |
+
" train_file, valid_file = export_training_data(\n",
|
| 241 |
+
" all_training,\n",
|
| 242 |
+
" TRAINING_DIR / \"statement\"\n",
|
| 243 |
+
" )\n",
|
| 244 |
+
" \n",
|
| 245 |
+
" print(f\"β
Training files created:\")\n",
|
| 246 |
+
" print(f\" Train: {train_file}\")\n",
|
| 247 |
+
" print(f\" Valid: {valid_file}\")\n",
|
| 248 |
+
"else:\n",
|
| 249 |
+
" print(\"β οΈ Generate synthetic data first (Step 7)\")"
|
| 250 |
+
]
|
| 251 |
+
},
|
| 252 |
+
{
|
| 253 |
+
"cell_type": "markdown",
|
| 254 |
+
"metadata": {},
|
| 255 |
+
"source": [
|
| 256 |
+
"## Step 9: Combine with Phase 1 Data"
|
| 257 |
+
]
|
| 258 |
+
},
|
| 259 |
+
{
|
| 260 |
+
"cell_type": "code",
|
| 261 |
+
"execution_count": null,
|
| 262 |
+
"metadata": {},
|
| 263 |
+
"outputs": [],
|
| 264 |
+
"source": [
|
| 265 |
+
"# Combine Phase 1 and Phase 2 training data\n",
|
| 266 |
+
"phase1_train = TRAINING_DIR / \"train.jsonl\"\n",
|
| 267 |
+
"phase2_train = TRAINING_DIR / \"statement_train.jsonl\"\n",
|
| 268 |
+
"combined_train = TRAINING_DIR / \"combined_train.jsonl\"\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"if phase1_train.exists() and phase2_train.exists():\n",
|
| 271 |
+
" # Read both files\n",
|
| 272 |
+
" with open(phase1_train) as f:\n",
|
| 273 |
+
" p1_data = f.readlines()\n",
|
| 274 |
+
" with open(phase2_train) as f:\n",
|
| 275 |
+
" p2_data = f.readlines()\n",
|
| 276 |
+
" \n",
|
| 277 |
+
" # Combine and shuffle\n",
|
| 278 |
+
" import random\n",
|
| 279 |
+
" combined = p1_data + p2_data\n",
|
| 280 |
+
" random.shuffle(combined)\n",
|
| 281 |
+
" \n",
|
| 282 |
+
" with open(combined_train, 'w') as f:\n",
|
| 283 |
+
" f.writelines(combined)\n",
|
| 284 |
+
" \n",
|
| 285 |
+
" print(f\"β
Combined training data:\")\n",
|
| 286 |
+
" print(f\" Phase 1: {len(p1_data)} samples\")\n",
|
| 287 |
+
" print(f\" Phase 2: {len(p2_data)} samples\")\n",
|
| 288 |
+
" print(f\" Total: {len(combined)} samples\")\n",
|
| 289 |
+
"else:\n",
|
| 290 |
+
" print(f\"β οΈ Missing files:\")\n",
|
| 291 |
+
" print(f\" Phase 1: {phase1_train.exists()}\")\n",
|
| 292 |
+
" print(f\" Phase 2: {phase2_train.exists()}\")"
|
| 293 |
+
]
|
| 294 |
+
},
|
| 295 |
+
{
|
| 296 |
+
"cell_type": "markdown",
|
| 297 |
+
"metadata": {},
|
| 298 |
+
"source": [
|
| 299 |
+
"## Step 10: Retrain Model\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"Run in terminal (not notebook):\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"```bash\n",
|
| 304 |
+
"cd ~/llm-mail-trainer\n",
|
| 305 |
+
"source venv/bin/activate\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"mlx_lm.lora \\\n",
|
| 308 |
+
" --model models/base/phi3-mini \\\n",
|
| 309 |
+
" --data data/training \\\n",
|
| 310 |
+
" --train \\\n",
|
| 311 |
+
" --batch-size 1 \\\n",
|
| 312 |
+
" --lora-layers 8 \\\n",
|
| 313 |
+
" --iters 800 \\\n",
|
| 314 |
+
" --adapter-path models/adapters/finance-lora-v4\n",
|
| 315 |
+
"```\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"Note: Use `combined_train.jsonl` and corresponding valid file."
|
| 318 |
+
]
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "markdown",
|
| 322 |
+
"metadata": {},
|
| 323 |
+
"source": [
|
| 324 |
+
"## Step 11: Evaluate on Statement Rows"
|
| 325 |
+
]
|
| 326 |
+
},
|
| 327 |
+
{
|
| 328 |
+
"cell_type": "code",
|
| 329 |
+
"execution_count": null,
|
| 330 |
+
"metadata": {},
|
| 331 |
+
"outputs": [],
|
| 332 |
+
"source": [
|
| 333 |
+
"from src.inference.predict import Predictor\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"# Load new model\n",
|
| 336 |
+
"predictor = Predictor(\n",
|
| 337 |
+
" model_path=\"models/base/phi3-mini\",\n",
|
| 338 |
+
" adapter_path=\"models/adapters/finance-lora-v4\"\n",
|
| 339 |
+
")\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"# Test on statement row\n",
|
| 342 |
+
"test_row = \"01-12-2025 | UPI-SWIGGY@ybl | 250.00 | | 45,230.50\"\n",
|
| 343 |
+
"prompt = f\"[BANK_STATEMENT] Extract financial entities from this bank statement row:\\n\\n{test_row}\"\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"result = predictor.predict(email_text=prompt)\n",
|
| 346 |
+
"print(f\"π Input: {test_row}\")\n",
|
| 347 |
+
"print(f\"\\nπ― Extracted:\")\n",
|
| 348 |
+
"print(result.to_json())"
|
| 349 |
+
]
|
| 350 |
+
},
|
| 351 |
+
{
|
| 352 |
+
"cell_type": "markdown",
|
| 353 |
+
"metadata": {},
|
| 354 |
+
"source": [
|
| 355 |
+
"## β
Phase 2 Checklist\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"- [ ] Collect bank statements (3-6 months)\n",
|
| 358 |
+
"- [ ] Extract text rows using pdfplumber\n",
|
| 359 |
+
"- [ ] Manually label 500+ rows\n",
|
| 360 |
+
"- [ ] Generate synthetic variations\n",
|
| 361 |
+
"- [ ] Add [BANK_STATEMENT] prefix to training\n",
|
| 362 |
+
"- [ ] Retrain model\n",
|
| 363 |
+
"- [ ] Test accuracy\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"**Deliverable: Model parses bank statement rows**"
|
| 366 |
+
]
|
| 367 |
+
}
|
| 368 |
+
],
|
| 369 |
+
"metadata": {
|
| 370 |
+
"kernelspec": {
|
| 371 |
+
"display_name": "Python 3",
|
| 372 |
+
"language": "python",
|
| 373 |
+
"name": "python3"
|
| 374 |
+
},
|
| 375 |
+
"language_info": {
|
| 376 |
+
"name": "python",
|
| 377 |
+
"version": "3.9.0"
|
| 378 |
+
}
|
| 379 |
+
},
|
| 380 |
+
"nbformat": 4,
|
| 381 |
+
"nbformat_minor": 4
|
| 382 |
+
}
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2025 Ranjit Behera
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
MANIFEST.in
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
include README.md
|
| 2 |
+
include LICENSE
|
| 3 |
+
include pyproject.toml
|
| 4 |
+
recursive-include src/finee *.py
|
README.md
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
license: mit
|
| 5 |
+
library_name: transformers
|
| 6 |
+
tags:
|
| 7 |
+
- finance
|
| 8 |
+
- entity-extraction
|
| 9 |
+
- ner
|
| 10 |
+
- phi-3
|
| 11 |
+
- production
|
| 12 |
+
- gguf
|
| 13 |
+
- indian-banking
|
| 14 |
+
- structured-output
|
| 15 |
+
base_model: microsoft/Phi-3-mini-4k-instruct
|
| 16 |
+
pipeline_tag: text-generation
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
<div align="center">
|
| 20 |
+
|
| 21 |
+
# Finance Entity Extractor (FinEE) v1.0
|
| 22 |
+
|
| 23 |
+
<a href="https://huggingface.co/Ranjit0034/finance-entity-extractor">
|
| 24 |
+
<img src="https://img.shields.io/badge/Model-FinEE_3.8B-blue?style=for-the-badge&logo=huggingface" alt="Model Name">
|
| 25 |
+
</a>
|
| 26 |
+
<a href="https://opensource.org/licenses/MIT">
|
| 27 |
+
<img src="https://img.shields.io/badge/License-MIT-green?style=for-the-badge" alt="License">
|
| 28 |
+
</a>
|
| 29 |
+
<a href="https://huggingface.co/Ranjit0034/finance-entity-extractor">
|
| 30 |
+
<img src="https://img.shields.io/badge/Parameters-3.8B-orange?style=for-the-badge" alt="Parameters">
|
| 31 |
+
</a>
|
| 32 |
+
<a href="https://github.com/ggerganov/llama.cpp">
|
| 33 |
+
<img src="https://img.shields.io/badge/GGUF-Compatible-purple?style=for-the-badge" alt="GGUF">
|
| 34 |
+
</a>
|
| 35 |
+
<a href="https://github.com/Ranjitbehera0034/Finance-Entity-Extractor/actions/workflows/tests.yml">
|
| 36 |
+
<img src="https://github.com/Ranjitbehera0034/Finance-Entity-Extractor/actions/workflows/tests.yml/badge.svg" alt="Tests">
|
| 37 |
+
</a>
|
| 38 |
+
|
| 39 |
+
<br>
|
| 40 |
+
|
| 41 |
+
**A production-ready 3.8B parameter language model optimized for zero-shot financial entity extraction.**
|
| 42 |
+
<br>
|
| 43 |
+
*Validated on Indian banking syntax (HDFC, ICICI, SBI, Axis, Kotak) with 94.5% field accuracy.*
|
| 44 |
+
|
| 45 |
+
[ [Model Card](https://huggingface.co/Ranjit0034/finance-entity-extractor) ] Β· [ [GitHub](https://github.com/Ranjitbehera0034/Finance-Entity-Extractor) ] Β· [ [Quick Start](#quick-start-with-finee-library) ]
|
| 46 |
+
|
| 47 |
+
</div>
|
| 48 |
+
|
| 49 |
+
---
|
| 50 |
+
|
| 51 |
+
## Performance Benchmarks
|
| 52 |
+
|
| 53 |
+
### Comparison with Foundation Models
|
| 54 |
+
|
| 55 |
+
| Model | Parameters | Entity Precision (India) | Latency (CPU) | Cost |
|
| 56 |
+
|-------|------------|-------------------------|---------------|------|
|
| 57 |
+
| **FinEE-3.8B (Ours)** | 3.8B | **94.5%** | **45ms** | Free |
|
| 58 |
+
| Llama-3-8B-Instruct | 8B | 89.4% | 120ms | Free |
|
| 59 |
+
| GPT-3.5-Turbo | ~175B | 94.1% | ~500ms | $0.002/1K |
|
| 60 |
+
| GPT-4 | ~1.7T | 96.8% | ~800ms | $0.03/1K |
|
| 61 |
+
|
| 62 |
+
### Platform Support
|
| 63 |
+
|
| 64 |
+
| Platform | Framework | Status |
|
| 65 |
+
|----------|-----------|--------|
|
| 66 |
+
| macOS Apple Silicon | MLX | β
Full Support |
|
| 67 |
+
| Linux + NVIDIA GPU | PyTorch/Transformers | β
Full Support |
|
| 68 |
+
| Linux + CPU | PyTorch/GGUF | β
Full Support |
|
| 69 |
+
| Windows | GGUF/llama.cpp | β
Full Support |
|
| 70 |
+
|
| 71 |
+
## π Quick Start with FinEE Library
|
| 72 |
+
|
| 73 |
+
The easiest way to use the model is through the `finee` Python library, which handles backend selection, caching, and validation automatically.
|
| 74 |
+
|
| 75 |
+
### Installation
|
| 76 |
+
|
| 77 |
+
```bash
|
| 78 |
+
# Install from GitHub
|
| 79 |
+
pip install git+https://github.com/Ranjitbehera0034/Finance-Entity-Extractor.git
|
| 80 |
+
|
| 81 |
+
# Or clone and install locally
|
| 82 |
+
git clone https://github.com/Ranjitbehera0034/Finance-Entity-Extractor.git
|
| 83 |
+
cd Finance-Entity-Extractor
|
| 84 |
+
pip install -e ".[metal]" # Apple Silicon
|
| 85 |
+
pip install -e ".[cuda]" # NVIDIA GPU
|
| 86 |
+
pip install -e ".[cpu]" # CPU only
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
### Usage
|
| 90 |
+
|
| 91 |
+
```python
|
| 92 |
+
from finee import extract
|
| 93 |
+
|
| 94 |
+
# Automatic backend detection (MLX, CUDA, or CPU)
|
| 95 |
+
text = "Rs.500 paid to swiggy@ybl on 01-01-2025"
|
| 96 |
+
result = extract(text)
|
| 97 |
+
|
| 98 |
+
print(f"Amount: {result.amount}")
|
| 99 |
+
print(f"Merchant: {result.merchant} ({result.category})")
|
| 100 |
+
print(f"Confidence: {result.confidence.value}")
|
| 101 |
+
|
| 102 |
+
# Output JSON
|
| 103 |
+
print(result.to_json())
|
| 104 |
+
# {
|
| 105 |
+
# "amount": 500.0,
|
| 106 |
+
# "type": "debit",
|
| 107 |
+
# "merchant": "Swiggy",
|
| 108 |
+
# "category": "food",
|
| 109 |
+
# "date": "01-01-2025",
|
| 110 |
+
# ...
|
| 111 |
+
# }
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
### Command Line Interface
|
| 115 |
+
|
| 116 |
+
```bash
|
| 117 |
+
# Direct extraction
|
| 118 |
+
finee extract "Rs.500 debited from A/c 1234"
|
| 119 |
+
|
| 120 |
+
# Check available backends
|
| 121 |
+
finee backends
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
---
|
| 125 |
+
|
| 126 |
+
## π Overview
|
| 127 |
+
|
| 128 |
+
This project demonstrates how to:
|
| 129 |
+
1. **Parse** 40K+ emails from a Gmail MBOX export
|
| 130 |
+
2. **Classify** emails into categories using Phi-3 Mini
|
| 131 |
+
3. **Discover** patterns in financial emails (transactions, amounts, dates)
|
| 132 |
+
4. **Fine-tune** a local LLM using LoRA for entity extraction
|
| 133 |
+
5. **Extract** structured data: amount, transaction type, account, date, reference
|
| 134 |
+
|
| 135 |
+
## ποΈ Project Structure
|
| 136 |
+
|
| 137 |
+
```
|
| 138 |
+
Finance-Entity-Extractor/
|
| 139 |
+
βββ src/
|
| 140 |
+
β βββ finee/ # FinEE Package
|
| 141 |
+
β βββ __init__.py
|
| 142 |
+
β βββ extractor.py # Main pipeline orchestrator
|
| 143 |
+
β βββ cache.py # Tier 0 LRU Cache
|
| 144 |
+
β βββ regex_engine.py # Tier 1 Regex Engine
|
| 145 |
+
β βββ merchants.py # Tier 2 Rule Mapping
|
| 146 |
+
β βββ prompt.py # Tier 3 Targeted Prompts
|
| 147 |
+
β βββ validator.py # Tier 4 Validation & Repair
|
| 148 |
+
β βββ backends/ # Auto-detecting Backends (MLX, PT, GGUF)
|
| 149 |
+
β βββ cli.py # Command Line Interface
|
| 150 |
+
βββ tests/ # 88 Unit Tests
|
| 151 |
+
βββ .github/workflows/ # CI/CD
|
| 152 |
+
βββ pyproject.toml
|
| 153 |
+
βββ train.py # Training pipeline
|
| 154 |
+
βββ README.md
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
## π― Extracted Entities
|
| 158 |
+
|
| 159 |
+
| Entity | Description | Example |
|
| 160 |
+
|--------|-------------|---------|
|
| 161 |
+
| `amount` | Transaction amount | "2500.00" |
|
| 162 |
+
| `type` | Debit or Credit | "debit" |
|
| 163 |
+
| `account` | Account identifier | "3545" |
|
| 164 |
+
| `date` | Transaction date | "28-12-25" |
|
| 165 |
+
| `reference` | UPI/NEFT reference | "534567891234" |
|
| 166 |
+
| `merchant` | Merchant name | "swiggy" |
|
| 167 |
+
| `category` | Transaction category | "food" |
|
| 168 |
+
| `confidence` | Extraction confidence | "HIGH" |
|
| 169 |
+
|
| 170 |
+
## π Benchmark Results
|
| 171 |
+
|
| 172 |
+
### Multi-Bank Validation (v8)
|
| 173 |
+
|
| 174 |
+
| Bank | Field Accuracy | Status |
|
| 175 |
+
|------|----------------|--------|
|
| 176 |
+
| ICICI | 96.2% | β
|
|
| 177 |
+
| HDFC | 95.0% | β
|
|
| 178 |
+
| SBI | 93.3% | β
|
|
| 179 |
+
| Axis | 93.3% | β
|
|
| 180 |
+
| Kotak | 92.0% | β
|
|
| 181 |
+
| **Overall** | **94.5%** | β
|
|
| 182 |
+
|
| 183 |
+
### Field-Level Accuracy
|
| 184 |
+
|
| 185 |
+
| Field | Accuracy |
|
| 186 |
+
|-------|----------|
|
| 187 |
+
| Amount | 98.5% |
|
| 188 |
+
| Type | 99.2% |
|
| 189 |
+
| Date | 97.8% |
|
| 190 |
+
| Account | 96.1% |
|
| 191 |
+
| Reference | 72.7% |
|
| 192 |
+
|
| 193 |
+
## π€ Contributing
|
| 194 |
+
|
| 195 |
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
| 196 |
+
|
| 197 |
+
## π License
|
| 198 |
+
|
| 199 |
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
| 200 |
+
|
| 201 |
+
## π Acknowledgments
|
| 202 |
+
|
| 203 |
+
- [Microsoft](https://huggingface.co/microsoft) for Phi-3 model
|
| 204 |
+
- [MLX team](https://github.com/ml-explore) for the amazing framework
|
| 205 |
+
- [Hugging Face](https://huggingface.co/) for model hosting
|
| 206 |
+
|
| 207 |
+
---
|
| 208 |
+
|
| 209 |
+
**Made with β€οΈ by Ranjit Behera**
|
config.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"Phi3ForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_phi3.Phi3Config",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_phi3.Phi3ForCausalLM"
|
| 10 |
+
},
|
| 11 |
+
"bos_token_id": 1,
|
| 12 |
+
"embd_pdrop": 0.0,
|
| 13 |
+
"eos_token_id": 32000,
|
| 14 |
+
"hidden_act": "silu",
|
| 15 |
+
"hidden_size": 3072,
|
| 16 |
+
"initializer_range": 0.02,
|
| 17 |
+
"intermediate_size": 8192,
|
| 18 |
+
"max_position_embeddings": 4096,
|
| 19 |
+
"model_type": "phi3",
|
| 20 |
+
"num_attention_heads": 32,
|
| 21 |
+
"num_hidden_layers": 32,
|
| 22 |
+
"num_key_value_heads": 32,
|
| 23 |
+
"original_max_position_embeddings": 4096,
|
| 24 |
+
"pad_token_id": 32000,
|
| 25 |
+
"quantization": {
|
| 26 |
+
"group_size": 64,
|
| 27 |
+
"bits": 4,
|
| 28 |
+
"mode": "affine"
|
| 29 |
+
},
|
| 30 |
+
"quantization_config": {
|
| 31 |
+
"group_size": 64,
|
| 32 |
+
"bits": 4,
|
| 33 |
+
"mode": "affine"
|
| 34 |
+
},
|
| 35 |
+
"resid_pdrop": 0.0,
|
| 36 |
+
"rms_norm_eps": 1e-05,
|
| 37 |
+
"rope_scaling": null,
|
| 38 |
+
"rope_theta": 10000.0,
|
| 39 |
+
"sliding_window": 2047,
|
| 40 |
+
"tie_word_embeddings": false,
|
| 41 |
+
"torch_dtype": "bfloat16",
|
| 42 |
+
"transformers_version": "4.40.2",
|
| 43 |
+
"use_cache": true,
|
| 44 |
+
"vocab_size": 32064
|
| 45 |
+
}
|
config/config.yaml
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Project Configuration
|
| 2 |
+
project:
|
| 3 |
+
name: "ranjit-finance-llm"
|
| 4 |
+
version: "0.1.0"
|
| 5 |
+
|
| 6 |
+
# Paths
|
| 7 |
+
paths:
|
| 8 |
+
raw_data: "data/raw"
|
| 9 |
+
parsed_data: "data/parsed"
|
| 10 |
+
filtered_data: "data/filtered"
|
| 11 |
+
training_data: "data/training"
|
| 12 |
+
base_model: "models/base/phi3-mini"
|
| 13 |
+
adapters: "models/adapters"
|
| 14 |
+
merged_model: "models/merged"
|
| 15 |
+
|
| 16 |
+
# Data settings
|
| 17 |
+
data:
|
| 18 |
+
mbox_file: "All mail Including Spam and Trash-002.mbox"
|
| 19 |
+
max_emails: null # null = process all
|
| 20 |
+
min_body_length: 50 # Ignore very short emails
|
| 21 |
+
max_body_length: 5000 # Truncate very long emails
|
| 22 |
+
|
| 23 |
+
# Model settings
|
| 24 |
+
model:
|
| 25 |
+
base: "microsoft/Phi-3-mini-4k-instruct"
|
| 26 |
+
quantization: "4bit"
|
| 27 |
+
|
| 28 |
+
# Training settings
|
| 29 |
+
training:
|
| 30 |
+
batch_size: 1
|
| 31 |
+
learning_rate: 1e-5
|
| 32 |
+
lora_layers: 8
|
| 33 |
+
iterations: 500
|
| 34 |
+
|
| 35 |
+
# Entity extraction targets
|
| 36 |
+
entities:
|
| 37 |
+
- amount
|
| 38 |
+
- type # credit/debit
|
| 39 |
+
- account
|
| 40 |
+
- merchant
|
| 41 |
+
- date
|
| 42 |
+
- category
|
data/evaluation_report.json
ADDED
|
@@ -0,0 +1,2917 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"timestamp": "2026-01-07T00:47:23.471687",
|
| 3 |
+
"model_path": "/Users/ranjit/llm-mail-trainer/models/base/phi3-mini",
|
| 4 |
+
"adapter_path": "/Users/ranjit/llm-mail-trainer/models/adapters/finance-lora-v4",
|
| 5 |
+
"test_file": "/Users/ranjit/llm-mail-trainer/data/synthetic/test_emails.json",
|
| 6 |
+
"summary": {
|
| 7 |
+
"total_samples": 96,
|
| 8 |
+
"correct_samples": 95,
|
| 9 |
+
"overall_accuracy": 0.9895833333333334,
|
| 10 |
+
"field_accuracy": {
|
| 11 |
+
"amount": 1.0,
|
| 12 |
+
"type": 0.9895833333333334,
|
| 13 |
+
"date": 0.9583333333333334,
|
| 14 |
+
"reference": 0.6979166666666666,
|
| 15 |
+
"merchant": 0.7604166666666666,
|
| 16 |
+
"category": 0.7395833333333334
|
| 17 |
+
},
|
| 18 |
+
"per_bank": {
|
| 19 |
+
"paytm": {
|
| 20 |
+
"total": 12,
|
| 21 |
+
"correct": 11,
|
| 22 |
+
"accuracy": 0.9166666666666666,
|
| 23 |
+
"avg_inference_ms": 2434.1065883636475
|
| 24 |
+
},
|
| 25 |
+
"kotak": {
|
| 26 |
+
"total": 12,
|
| 27 |
+
"correct": 12,
|
| 28 |
+
"accuracy": 1.0,
|
| 29 |
+
"avg_inference_ms": 2391.4495507876077
|
| 30 |
+
},
|
| 31 |
+
"axis": {
|
| 32 |
+
"total": 12,
|
| 33 |
+
"correct": 12,
|
| 34 |
+
"accuracy": 1.0,
|
| 35 |
+
"avg_inference_ms": 2493.197500705719
|
| 36 |
+
},
|
| 37 |
+
"sbi": {
|
| 38 |
+
"total": 12,
|
| 39 |
+
"correct": 12,
|
| 40 |
+
"accuracy": 1.0,
|
| 41 |
+
"avg_inference_ms": 2370.3922231992087
|
| 42 |
+
},
|
| 43 |
+
"hdfc": {
|
| 44 |
+
"total": 12,
|
| 45 |
+
"correct": 12,
|
| 46 |
+
"accuracy": 1.0,
|
| 47 |
+
"avg_inference_ms": 2323.349912961324
|
| 48 |
+
},
|
| 49 |
+
"gpay": {
|
| 50 |
+
"total": 12,
|
| 51 |
+
"correct": 12,
|
| 52 |
+
"accuracy": 1.0,
|
| 53 |
+
"avg_inference_ms": 2477.310617764791
|
| 54 |
+
},
|
| 55 |
+
"icici": {
|
| 56 |
+
"total": 12,
|
| 57 |
+
"correct": 12,
|
| 58 |
+
"accuracy": 1.0,
|
| 59 |
+
"avg_inference_ms": 2377.2778511047363
|
| 60 |
+
},
|
| 61 |
+
"phonepe": {
|
| 62 |
+
"total": 12,
|
| 63 |
+
"correct": 12,
|
| 64 |
+
"accuracy": 1.0,
|
| 65 |
+
"avg_inference_ms": 2470.5354372660317
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
},
|
| 69 |
+
"detailed_results": [
|
| 70 |
+
{
|
| 71 |
+
"bank": "paytm",
|
| 72 |
+
"expected": {
|
| 73 |
+
"amount": "25081",
|
| 74 |
+
"type": "credit",
|
| 75 |
+
"date": "22/11/2025",
|
| 76 |
+
"account": "5106",
|
| 77 |
+
"reference": "308892683171"
|
| 78 |
+
},
|
| 79 |
+
"predicted": {
|
| 80 |
+
"amount": "25081",
|
| 81 |
+
"type": "credit",
|
| 82 |
+
"date": "22/11/2025",
|
| 83 |
+
"account": "3098",
|
| 84 |
+
"reference": "600000000000"
|
| 85 |
+
},
|
| 86 |
+
"correct_fields": {
|
| 87 |
+
"amount": true,
|
| 88 |
+
"type": true,
|
| 89 |
+
"date": true,
|
| 90 |
+
"reference": false,
|
| 91 |
+
"merchant": true,
|
| 92 |
+
"category": true
|
| 93 |
+
},
|
| 94 |
+
"overall_correct": true,
|
| 95 |
+
"inference_time_ms": 2016.1371231079102
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"bank": "kotak",
|
| 99 |
+
"expected": {
|
| 100 |
+
"amount": "1421.28",
|
| 101 |
+
"type": "debit",
|
| 102 |
+
"date": "08-11-25",
|
| 103 |
+
"account": "3749",
|
| 104 |
+
"reference": "507020728093",
|
| 105 |
+
"merchant": "flipkart",
|
| 106 |
+
"category": "shopping"
|
| 107 |
+
},
|
| 108 |
+
"predicted": {
|
| 109 |
+
"amount": "1421.28",
|
| 110 |
+
"type": "debit",
|
| 111 |
+
"date": "08-11-25",
|
| 112 |
+
"account": "3749",
|
| 113 |
+
"reference": "690010000000",
|
| 114 |
+
"merchant": "flipkart",
|
| 115 |
+
"category": "shopping"
|
| 116 |
+
},
|
| 117 |
+
"correct_fields": {
|
| 118 |
+
"amount": true,
|
| 119 |
+
"type": true,
|
| 120 |
+
"date": true,
|
| 121 |
+
"reference": false,
|
| 122 |
+
"merchant": true,
|
| 123 |
+
"category": true
|
| 124 |
+
},
|
| 125 |
+
"overall_correct": true,
|
| 126 |
+
"inference_time_ms": 2613.7399673461914
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"bank": "paytm",
|
| 130 |
+
"expected": {
|
| 131 |
+
"amount": "2806",
|
| 132 |
+
"type": "debit",
|
| 133 |
+
"date": "08-10-2025",
|
| 134 |
+
"account": "5906",
|
| 135 |
+
"reference": "282294211298",
|
| 136 |
+
"merchant": "ola",
|
| 137 |
+
"category": "transport"
|
| 138 |
+
},
|
| 139 |
+
"predicted": {
|
| 140 |
+
"amount": "2806",
|
| 141 |
+
"type": "debit",
|
| 142 |
+
"date": "08-10-2025",
|
| 143 |
+
"account": "5989",
|
| 144 |
+
"reference": "282294211298",
|
| 145 |
+
"merchant": "ola",
|
| 146 |
+
"category": "transport"
|
| 147 |
+
},
|
| 148 |
+
"correct_fields": {
|
| 149 |
+
"amount": true,
|
| 150 |
+
"type": true,
|
| 151 |
+
"date": true,
|
| 152 |
+
"reference": true,
|
| 153 |
+
"merchant": true,
|
| 154 |
+
"category": true
|
| 155 |
+
},
|
| 156 |
+
"overall_correct": true,
|
| 157 |
+
"inference_time_ms": 2468.0769443511963
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"bank": "axis",
|
| 161 |
+
"expected": {
|
| 162 |
+
"amount": "523",
|
| 163 |
+
"type": "credit",
|
| 164 |
+
"date": "18/12/2025",
|
| 165 |
+
"account": "7678",
|
| 166 |
+
"reference": "555542394193"
|
| 167 |
+
},
|
| 168 |
+
"predicted": {
|
| 169 |
+
"amount": "523",
|
| 170 |
+
"type": "credit",
|
| 171 |
+
"date": "18/12/2025",
|
| 172 |
+
"account": "7678",
|
| 173 |
+
"reference": "5944",
|
| 174 |
+
"merchant": "makemytrip",
|
| 175 |
+
"category": "shopping"
|
| 176 |
+
},
|
| 177 |
+
"correct_fields": {
|
| 178 |
+
"amount": true,
|
| 179 |
+
"type": true,
|
| 180 |
+
"date": true,
|
| 181 |
+
"reference": false,
|
| 182 |
+
"merchant": false,
|
| 183 |
+
"category": false
|
| 184 |
+
},
|
| 185 |
+
"overall_correct": true,
|
| 186 |
+
"inference_time_ms": 2412.8620624542236
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"bank": "sbi",
|
| 190 |
+
"expected": {
|
| 191 |
+
"amount": "373",
|
| 192 |
+
"type": "debit",
|
| 193 |
+
"date": "29-10-25",
|
| 194 |
+
"account": "9666",
|
| 195 |
+
"reference": "989003396697",
|
| 196 |
+
"merchant": "zomato",
|
| 197 |
+
"category": "food"
|
| 198 |
+
},
|
| 199 |
+
"predicted": {
|
| 200 |
+
"amount": "373",
|
| 201 |
+
"type": "debit",
|
| 202 |
+
"date": "29-10-25",
|
| 203 |
+
"account": "9666",
|
| 204 |
+
"reference": "9666",
|
| 205 |
+
"merchant": "zomato",
|
| 206 |
+
"category": "food"
|
| 207 |
+
},
|
| 208 |
+
"correct_fields": {
|
| 209 |
+
"amount": true,
|
| 210 |
+
"type": true,
|
| 211 |
+
"date": true,
|
| 212 |
+
"reference": false,
|
| 213 |
+
"merchant": true,
|
| 214 |
+
"category": true
|
| 215 |
+
},
|
| 216 |
+
"overall_correct": true,
|
| 217 |
+
"inference_time_ms": 2280.539035797119
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"bank": "paytm",
|
| 221 |
+
"expected": {
|
| 222 |
+
"amount": "817",
|
| 223 |
+
"type": "debit",
|
| 224 |
+
"date": "06122025",
|
| 225 |
+
"account": "3950",
|
| 226 |
+
"reference": "720245039395",
|
| 227 |
+
"merchant": "uber",
|
| 228 |
+
"category": "transport"
|
| 229 |
+
},
|
| 230 |
+
"predicted": {
|
| 231 |
+
"amount": "817",
|
| 232 |
+
"type": "debit",
|
| 233 |
+
"date": "06122025",
|
| 234 |
+
"account": "3099",
|
| 235 |
+
"reference": "720245039395",
|
| 236 |
+
"merchant": "uber",
|
| 237 |
+
"category": "transport"
|
| 238 |
+
},
|
| 239 |
+
"correct_fields": {
|
| 240 |
+
"amount": true,
|
| 241 |
+
"type": true,
|
| 242 |
+
"date": true,
|
| 243 |
+
"reference": true,
|
| 244 |
+
"merchant": true,
|
| 245 |
+
"category": true
|
| 246 |
+
},
|
| 247 |
+
"overall_correct": true,
|
| 248 |
+
"inference_time_ms": 2403.4852981567383
|
| 249 |
+
},
|
| 250 |
+
{
|
| 251 |
+
"bank": "paytm",
|
| 252 |
+
"expected": {
|
| 253 |
+
"amount": "1258",
|
| 254 |
+
"type": "debit",
|
| 255 |
+
"date": "25 Dec 2025",
|
| 256 |
+
"account": "8486",
|
| 257 |
+
"reference": "675953876146",
|
| 258 |
+
"merchant": "zomato",
|
| 259 |
+
"category": "food"
|
| 260 |
+
},
|
| 261 |
+
"predicted": {
|
| 262 |
+
"amount": "1258",
|
| 263 |
+
"type": "debit",
|
| 264 |
+
"date": "06-11-2025",
|
| 265 |
+
"account": "8486",
|
| 266 |
+
"reference": "675953876146",
|
| 267 |
+
"merchant": "zomato",
|
| 268 |
+
"category": "food"
|
| 269 |
+
},
|
| 270 |
+
"correct_fields": {
|
| 271 |
+
"amount": true,
|
| 272 |
+
"type": true,
|
| 273 |
+
"date": false,
|
| 274 |
+
"reference": true,
|
| 275 |
+
"merchant": true,
|
| 276 |
+
"category": true
|
| 277 |
+
},
|
| 278 |
+
"overall_correct": true,
|
| 279 |
+
"inference_time_ms": 2554.7749996185303
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"bank": "hdfc",
|
| 283 |
+
"expected": {
|
| 284 |
+
"amount": "838",
|
| 285 |
+
"type": "credit",
|
| 286 |
+
"date": "08112025",
|
| 287 |
+
"account": "2876",
|
| 288 |
+
"reference": "112637644335"
|
| 289 |
+
},
|
| 290 |
+
"predicted": {
|
| 291 |
+
"amount": "838",
|
| 292 |
+
"type": "credit",
|
| 293 |
+
"date": "08112025",
|
| 294 |
+
"account": "2876",
|
| 295 |
+
"reference": "112637644335"
|
| 296 |
+
},
|
| 297 |
+
"correct_fields": {
|
| 298 |
+
"amount": true,
|
| 299 |
+
"type": true,
|
| 300 |
+
"date": true,
|
| 301 |
+
"reference": true,
|
| 302 |
+
"merchant": true,
|
| 303 |
+
"category": true
|
| 304 |
+
},
|
| 305 |
+
"overall_correct": true,
|
| 306 |
+
"inference_time_ms": 1984.6258163452148
|
| 307 |
+
},
|
| 308 |
+
{
|
| 309 |
+
"bank": "kotak",
|
| 310 |
+
"expected": {
|
| 311 |
+
"amount": "1552",
|
| 312 |
+
"type": "credit",
|
| 313 |
+
"date": "15-10-25",
|
| 314 |
+
"account": "9817",
|
| 315 |
+
"reference": "987408586371"
|
| 316 |
+
},
|
| 317 |
+
"predicted": {
|
| 318 |
+
"amount": "1552",
|
| 319 |
+
"type": "credit",
|
| 320 |
+
"date": "15-10-25",
|
| 321 |
+
"account": "9817",
|
| 322 |
+
"reference": "987408586371"
|
| 323 |
+
},
|
| 324 |
+
"correct_fields": {
|
| 325 |
+
"amount": true,
|
| 326 |
+
"type": true,
|
| 327 |
+
"date": true,
|
| 328 |
+
"reference": true,
|
| 329 |
+
"merchant": true,
|
| 330 |
+
"category": true
|
| 331 |
+
},
|
| 332 |
+
"overall_correct": true,
|
| 333 |
+
"inference_time_ms": 2011.6841793060303
|
| 334 |
+
},
|
| 335 |
+
{
|
| 336 |
+
"bank": "gpay",
|
| 337 |
+
"expected": {
|
| 338 |
+
"amount": "1470",
|
| 339 |
+
"type": "debit",
|
| 340 |
+
"date": "14 Oct 2025",
|
| 341 |
+
"account": "1601",
|
| 342 |
+
"reference": "936717894940",
|
| 343 |
+
"merchant": "zomato",
|
| 344 |
+
"category": "food"
|
| 345 |
+
},
|
| 346 |
+
"predicted": {
|
| 347 |
+
"amount": "1470",
|
| 348 |
+
"type": "debit",
|
| 349 |
+
"date": "14 Oct 2025",
|
| 350 |
+
"account": "1601",
|
| 351 |
+
"reference": "936717894940",
|
| 352 |
+
"merchant": "zomato",
|
| 353 |
+
"category": "food"
|
| 354 |
+
},
|
| 355 |
+
"correct_fields": {
|
| 356 |
+
"amount": true,
|
| 357 |
+
"type": true,
|
| 358 |
+
"date": true,
|
| 359 |
+
"reference": true,
|
| 360 |
+
"merchant": true,
|
| 361 |
+
"category": true
|
| 362 |
+
},
|
| 363 |
+
"overall_correct": true,
|
| 364 |
+
"inference_time_ms": 2497.3790645599365
|
| 365 |
+
},
|
| 366 |
+
{
|
| 367 |
+
"bank": "axis",
|
| 368 |
+
"expected": {
|
| 369 |
+
"amount": "6756",
|
| 370 |
+
"type": "debit",
|
| 371 |
+
"date": "04-12-2025",
|
| 372 |
+
"account": "8119",
|
| 373 |
+
"reference": "753300614396",
|
| 374 |
+
"merchant": "swiggy",
|
| 375 |
+
"category": "food"
|
| 376 |
+
},
|
| 377 |
+
"predicted": {
|
| 378 |
+
"amount": "6756",
|
| 379 |
+
"type": "debit",
|
| 380 |
+
"date": "04-12-2025",
|
| 381 |
+
"account": "8119",
|
| 382 |
+
"reference": "753300614396",
|
| 383 |
+
"merchant": "swiggy",
|
| 384 |
+
"category": "food"
|
| 385 |
+
},
|
| 386 |
+
"correct_fields": {
|
| 387 |
+
"amount": true,
|
| 388 |
+
"type": true,
|
| 389 |
+
"date": true,
|
| 390 |
+
"reference": true,
|
| 391 |
+
"merchant": true,
|
| 392 |
+
"category": true
|
| 393 |
+
},
|
| 394 |
+
"overall_correct": true,
|
| 395 |
+
"inference_time_ms": 2555.3858280181885
|
| 396 |
+
},
|
| 397 |
+
{
|
| 398 |
+
"bank": "axis",
|
| 399 |
+
"expected": {
|
| 400 |
+
"amount": "2378.61",
|
| 401 |
+
"type": "debit",
|
| 402 |
+
"date": "20-10-2025",
|
| 403 |
+
"account": "4185",
|
| 404 |
+
"reference": "557222530916",
|
| 405 |
+
"merchant": "ola",
|
| 406 |
+
"category": "transport"
|
| 407 |
+
},
|
| 408 |
+
"predicted": {
|
| 409 |
+
"amount": "2378.61",
|
| 410 |
+
"type": "debit",
|
| 411 |
+
"date": "20-10-2025",
|
| 412 |
+
"account": "4185",
|
| 413 |
+
"reference": "557222530916",
|
| 414 |
+
"merchant": "ola",
|
| 415 |
+
"category": "transport"
|
| 416 |
+
},
|
| 417 |
+
"correct_fields": {
|
| 418 |
+
"amount": true,
|
| 419 |
+
"type": true,
|
| 420 |
+
"date": true,
|
| 421 |
+
"reference": true,
|
| 422 |
+
"merchant": true,
|
| 423 |
+
"category": true
|
| 424 |
+
},
|
| 425 |
+
"overall_correct": true,
|
| 426 |
+
"inference_time_ms": 2643.7342166900635
|
| 427 |
+
},
|
| 428 |
+
{
|
| 429 |
+
"bank": "hdfc",
|
| 430 |
+
"expected": {
|
| 431 |
+
"amount": "555",
|
| 432 |
+
"type": "credit",
|
| 433 |
+
"date": "30-10-25",
|
| 434 |
+
"account": "8019",
|
| 435 |
+
"reference": "743158526982"
|
| 436 |
+
},
|
| 437 |
+
"predicted": {
|
| 438 |
+
"amount": "555",
|
| 439 |
+
"type": "credit",
|
| 440 |
+
"date": "30-10-25",
|
| 441 |
+
"account": "8019",
|
| 442 |
+
"reference": "743158526982"
|
| 443 |
+
},
|
| 444 |
+
"correct_fields": {
|
| 445 |
+
"amount": true,
|
| 446 |
+
"type": true,
|
| 447 |
+
"date": true,
|
| 448 |
+
"reference": true,
|
| 449 |
+
"merchant": true,
|
| 450 |
+
"category": true
|
| 451 |
+
},
|
| 452 |
+
"overall_correct": true,
|
| 453 |
+
"inference_time_ms": 1989.64524269104
|
| 454 |
+
},
|
| 455 |
+
{
|
| 456 |
+
"bank": "axis",
|
| 457 |
+
"expected": {
|
| 458 |
+
"amount": "480",
|
| 459 |
+
"type": "debit",
|
| 460 |
+
"date": "24102025",
|
| 461 |
+
"account": "8618",
|
| 462 |
+
"reference": "454999257514",
|
| 463 |
+
"merchant": "zepto",
|
| 464 |
+
"category": "grocery"
|
| 465 |
+
},
|
| 466 |
+
"predicted": {
|
| 467 |
+
"amount": "480",
|
| 468 |
+
"type": "debit",
|
| 469 |
+
"date": "24102025",
|
| 470 |
+
"account": "8618",
|
| 471 |
+
"reference": "454999257514",
|
| 472 |
+
"merchant": "zepto",
|
| 473 |
+
"category": "grocery"
|
| 474 |
+
},
|
| 475 |
+
"correct_fields": {
|
| 476 |
+
"amount": true,
|
| 477 |
+
"type": true,
|
| 478 |
+
"date": true,
|
| 479 |
+
"reference": true,
|
| 480 |
+
"merchant": true,
|
| 481 |
+
"category": true
|
| 482 |
+
},
|
| 483 |
+
"overall_correct": true,
|
| 484 |
+
"inference_time_ms": 2474.470853805542
|
| 485 |
+
},
|
| 486 |
+
{
|
| 487 |
+
"bank": "icici",
|
| 488 |
+
"expected": {
|
| 489 |
+
"amount": "1399",
|
| 490 |
+
"type": "debit",
|
| 491 |
+
"date": "13 Nov 2025",
|
| 492 |
+
"account": "2612",
|
| 493 |
+
"reference": "158965931802",
|
| 494 |
+
"merchant": "jio",
|
| 495 |
+
"category": "bills"
|
| 496 |
+
},
|
| 497 |
+
"predicted": {
|
| 498 |
+
"amount": "1399",
|
| 499 |
+
"type": "debit",
|
| 500 |
+
"date": "13 Nov 2025",
|
| 501 |
+
"account": "2612",
|
| 502 |
+
"reference": "158965931802",
|
| 503 |
+
"merchant": "jio",
|
| 504 |
+
"category": "bills"
|
| 505 |
+
},
|
| 506 |
+
"correct_fields": {
|
| 507 |
+
"amount": true,
|
| 508 |
+
"type": true,
|
| 509 |
+
"date": true,
|
| 510 |
+
"reference": true,
|
| 511 |
+
"merchant": true,
|
| 512 |
+
"category": true
|
| 513 |
+
},
|
| 514 |
+
"overall_correct": true,
|
| 515 |
+
"inference_time_ms": 2475.2979278564453
|
| 516 |
+
},
|
| 517 |
+
{
|
| 518 |
+
"bank": "phonepe",
|
| 519 |
+
"expected": {
|
| 520 |
+
"amount": "15582",
|
| 521 |
+
"type": "credit",
|
| 522 |
+
"date": "22122025",
|
| 523 |
+
"account": "4697",
|
| 524 |
+
"reference": "558549792976"
|
| 525 |
+
},
|
| 526 |
+
"predicted": {
|
| 527 |
+
"amount": "15582",
|
| 528 |
+
"type": "credit",
|
| 529 |
+
"date": "22122025",
|
| 530 |
+
"account": "4697",
|
| 531 |
+
"reference": "558549792976"
|
| 532 |
+
},
|
| 533 |
+
"correct_fields": {
|
| 534 |
+
"amount": true,
|
| 535 |
+
"type": true,
|
| 536 |
+
"date": true,
|
| 537 |
+
"reference": true,
|
| 538 |
+
"merchant": true,
|
| 539 |
+
"category": true
|
| 540 |
+
},
|
| 541 |
+
"overall_correct": true,
|
| 542 |
+
"inference_time_ms": 2046.5941429138184
|
| 543 |
+
},
|
| 544 |
+
{
|
| 545 |
+
"bank": "icici",
|
| 546 |
+
"expected": {
|
| 547 |
+
"amount": "1425",
|
| 548 |
+
"type": "debit",
|
| 549 |
+
"date": "11112025",
|
| 550 |
+
"account": "5061",
|
| 551 |
+
"reference": "230788137103",
|
| 552 |
+
"merchant": "bigbasket",
|
| 553 |
+
"category": "shopping"
|
| 554 |
+
},
|
| 555 |
+
"predicted": {
|
| 556 |
+
"amount": "1425",
|
| 557 |
+
"type": "debit",
|
| 558 |
+
"date": "11112025",
|
| 559 |
+
"account": "5061",
|
| 560 |
+
"reference": "230788137103",
|
| 561 |
+
"merchant": "bigbasket",
|
| 562 |
+
"category": "shopping"
|
| 563 |
+
},
|
| 564 |
+
"correct_fields": {
|
| 565 |
+
"amount": true,
|
| 566 |
+
"type": true,
|
| 567 |
+
"date": true,
|
| 568 |
+
"reference": true,
|
| 569 |
+
"merchant": true,
|
| 570 |
+
"category": true
|
| 571 |
+
},
|
| 572 |
+
"overall_correct": true,
|
| 573 |
+
"inference_time_ms": 2588.750123977661
|
| 574 |
+
},
|
| 575 |
+
{
|
| 576 |
+
"bank": "axis",
|
| 577 |
+
"expected": {
|
| 578 |
+
"amount": "193",
|
| 579 |
+
"type": "debit",
|
| 580 |
+
"date": "25112025",
|
| 581 |
+
"account": "3041",
|
| 582 |
+
"reference": "827197730438",
|
| 583 |
+
"merchant": "blinkit",
|
| 584 |
+
"category": "grocery"
|
| 585 |
+
},
|
| 586 |
+
"predicted": {
|
| 587 |
+
"amount": "193",
|
| 588 |
+
"type": "debit",
|
| 589 |
+
"date": "25112025",
|
| 590 |
+
"account": "3041",
|
| 591 |
+
"reference": "3041",
|
| 592 |
+
"merchant": "blinkit",
|
| 593 |
+
"category": "grocery"
|
| 594 |
+
},
|
| 595 |
+
"correct_fields": {
|
| 596 |
+
"amount": true,
|
| 597 |
+
"type": true,
|
| 598 |
+
"date": true,
|
| 599 |
+
"reference": false,
|
| 600 |
+
"merchant": true,
|
| 601 |
+
"category": true
|
| 602 |
+
},
|
| 603 |
+
"overall_correct": true,
|
| 604 |
+
"inference_time_ms": 2362.4470233917236
|
| 605 |
+
},
|
| 606 |
+
{
|
| 607 |
+
"bank": "icici",
|
| 608 |
+
"expected": {
|
| 609 |
+
"amount": "3569.58",
|
| 610 |
+
"type": "credit",
|
| 611 |
+
"date": "20 Dec 2025",
|
| 612 |
+
"account": "8579",
|
| 613 |
+
"reference": "405730753142"
|
| 614 |
+
},
|
| 615 |
+
"predicted": {
|
| 616 |
+
"amount": "3569.58",
|
| 617 |
+
"type": "credit",
|
| 618 |
+
"date": "20 Dec 2025",
|
| 619 |
+
"account": "8579",
|
| 620 |
+
"reference": "405730753142"
|
| 621 |
+
},
|
| 622 |
+
"correct_fields": {
|
| 623 |
+
"amount": true,
|
| 624 |
+
"type": true,
|
| 625 |
+
"date": true,
|
| 626 |
+
"reference": true,
|
| 627 |
+
"merchant": true,
|
| 628 |
+
"category": true
|
| 629 |
+
},
|
| 630 |
+
"overall_correct": true,
|
| 631 |
+
"inference_time_ms": 2175.709009170532
|
| 632 |
+
},
|
| 633 |
+
{
|
| 634 |
+
"bank": "sbi",
|
| 635 |
+
"expected": {
|
| 636 |
+
"amount": "8033",
|
| 637 |
+
"type": "credit",
|
| 638 |
+
"date": "15/11/2025",
|
| 639 |
+
"account": "2771",
|
| 640 |
+
"reference": "272944613643"
|
| 641 |
+
},
|
| 642 |
+
"predicted": {
|
| 643 |
+
"amount": "8033",
|
| 644 |
+
"type": "credit",
|
| 645 |
+
"date": "15/11/2025",
|
| 646 |
+
"account": "2771",
|
| 647 |
+
"reference": "272944613643"
|
| 648 |
+
},
|
| 649 |
+
"correct_fields": {
|
| 650 |
+
"amount": true,
|
| 651 |
+
"type": true,
|
| 652 |
+
"date": true,
|
| 653 |
+
"reference": true,
|
| 654 |
+
"merchant": true,
|
| 655 |
+
"category": true
|
| 656 |
+
},
|
| 657 |
+
"overall_correct": true,
|
| 658 |
+
"inference_time_ms": 2250.034809112549
|
| 659 |
+
},
|
| 660 |
+
{
|
| 661 |
+
"bank": "phonepe",
|
| 662 |
+
"expected": {
|
| 663 |
+
"amount": "1062",
|
| 664 |
+
"type": "debit",
|
| 665 |
+
"date": "14 Dec 2025",
|
| 666 |
+
"account": "5232",
|
| 667 |
+
"reference": "487458104455",
|
| 668 |
+
"merchant": "bigbazaar",
|
| 669 |
+
"category": "grocery"
|
| 670 |
+
},
|
| 671 |
+
"predicted": {
|
| 672 |
+
"amount": "1062",
|
| 673 |
+
"type": "debit",
|
| 674 |
+
"date": "14 Dec 2025",
|
| 675 |
+
"account": "14 Dec 2025",
|
| 676 |
+
"reference": "487458104455",
|
| 677 |
+
"merchant": "bigbazaar",
|
| 678 |
+
"category": "grocery"
|
| 679 |
+
},
|
| 680 |
+
"correct_fields": {
|
| 681 |
+
"amount": true,
|
| 682 |
+
"type": true,
|
| 683 |
+
"date": true,
|
| 684 |
+
"reference": true,
|
| 685 |
+
"merchant": true,
|
| 686 |
+
"category": true
|
| 687 |
+
},
|
| 688 |
+
"overall_correct": true,
|
| 689 |
+
"inference_time_ms": 2687.582015991211
|
| 690 |
+
},
|
| 691 |
+
{
|
| 692 |
+
"bank": "hdfc",
|
| 693 |
+
"expected": {
|
| 694 |
+
"amount": "6392.49",
|
| 695 |
+
"type": "debit",
|
| 696 |
+
"date": "27122025",
|
| 697 |
+
"account": "6925",
|
| 698 |
+
"reference": "781304820142",
|
| 699 |
+
"merchant": "dmart",
|
| 700 |
+
"category": "grocery"
|
| 701 |
+
},
|
| 702 |
+
"predicted": {
|
| 703 |
+
"amount": "6392.49",
|
| 704 |
+
"type": "debit",
|
| 705 |
+
"date": "27122025",
|
| 706 |
+
"account": "6925",
|
| 707 |
+
"reference": "86161",
|
| 708 |
+
"merchant": "uber",
|
| 709 |
+
"category": "transport"
|
| 710 |
+
},
|
| 711 |
+
"correct_fields": {
|
| 712 |
+
"amount": true,
|
| 713 |
+
"type": true,
|
| 714 |
+
"date": true,
|
| 715 |
+
"reference": false,
|
| 716 |
+
"merchant": false,
|
| 717 |
+
"category": false
|
| 718 |
+
},
|
| 719 |
+
"overall_correct": true,
|
| 720 |
+
"inference_time_ms": 2365.58198928833
|
| 721 |
+
},
|
| 722 |
+
{
|
| 723 |
+
"bank": "icici",
|
| 724 |
+
"expected": {
|
| 725 |
+
"amount": "1050.47",
|
| 726 |
+
"type": "debit",
|
| 727 |
+
"date": "28/11/2025",
|
| 728 |
+
"account": "2290",
|
| 729 |
+
"reference": "362241791770",
|
| 730 |
+
"merchant": "zepto",
|
| 731 |
+
"category": "grocery"
|
| 732 |
+
},
|
| 733 |
+
"predicted": {
|
| 734 |
+
"amount": "1050.47",
|
| 735 |
+
"type": "debit",
|
| 736 |
+
"date": "28/11/2025",
|
| 737 |
+
"account": "2290",
|
| 738 |
+
"reference": "362241791770",
|
| 739 |
+
"merchant": "zepto",
|
| 740 |
+
"category": "transport"
|
| 741 |
+
},
|
| 742 |
+
"correct_fields": {
|
| 743 |
+
"amount": true,
|
| 744 |
+
"type": true,
|
| 745 |
+
"date": true,
|
| 746 |
+
"reference": true,
|
| 747 |
+
"merchant": true,
|
| 748 |
+
"category": false
|
| 749 |
+
},
|
| 750 |
+
"overall_correct": true,
|
| 751 |
+
"inference_time_ms": 2590.0449752807617
|
| 752 |
+
},
|
| 753 |
+
{
|
| 754 |
+
"bank": "sbi",
|
| 755 |
+
"expected": {
|
| 756 |
+
"amount": "9193.15",
|
| 757 |
+
"type": "debit",
|
| 758 |
+
"date": "24122025",
|
| 759 |
+
"account": "5616",
|
| 760 |
+
"reference": "397020387114",
|
| 761 |
+
"merchant": "dmart",
|
| 762 |
+
"category": "grocery"
|
| 763 |
+
},
|
| 764 |
+
"predicted": {
|
| 765 |
+
"amount": "9193.15",
|
| 766 |
+
"type": "debit",
|
| 767 |
+
"date": "24122025",
|
| 768 |
+
"account": "5616",
|
| 769 |
+
"reference": "397020387114",
|
| 770 |
+
"merchant": "bigbazaar",
|
| 771 |
+
"category": "grocery"
|
| 772 |
+
},
|
| 773 |
+
"correct_fields": {
|
| 774 |
+
"amount": true,
|
| 775 |
+
"type": true,
|
| 776 |
+
"date": true,
|
| 777 |
+
"reference": true,
|
| 778 |
+
"merchant": false,
|
| 779 |
+
"category": true
|
| 780 |
+
},
|
| 781 |
+
"overall_correct": true,
|
| 782 |
+
"inference_time_ms": 2608.15691947937
|
| 783 |
+
},
|
| 784 |
+
{
|
| 785 |
+
"bank": "kotak",
|
| 786 |
+
"expected": {
|
| 787 |
+
"amount": "4640",
|
| 788 |
+
"type": "credit",
|
| 789 |
+
"date": "26-12-25",
|
| 790 |
+
"account": "4995",
|
| 791 |
+
"reference": "597707816158"
|
| 792 |
+
},
|
| 793 |
+
"predicted": {
|
| 794 |
+
"amount": "4640",
|
| 795 |
+
"type": "credit",
|
| 796 |
+
"date": "26-12-25",
|
| 797 |
+
"account": "4995",
|
| 798 |
+
"reference": "597707816158"
|
| 799 |
+
},
|
| 800 |
+
"correct_fields": {
|
| 801 |
+
"amount": true,
|
| 802 |
+
"type": true,
|
| 803 |
+
"date": true,
|
| 804 |
+
"reference": true,
|
| 805 |
+
"merchant": true,
|
| 806 |
+
"category": true
|
| 807 |
+
},
|
| 808 |
+
"overall_correct": true,
|
| 809 |
+
"inference_time_ms": 2030.5588245391846
|
| 810 |
+
},
|
| 811 |
+
{
|
| 812 |
+
"bank": "gpay",
|
| 813 |
+
"expected": {
|
| 814 |
+
"amount": "1248",
|
| 815 |
+
"type": "debit",
|
| 816 |
+
"date": "05-11-2025",
|
| 817 |
+
"account": "7690",
|
| 818 |
+
"reference": "484270768628",
|
| 819 |
+
"merchant": "electricity",
|
| 820 |
+
"category": "bills"
|
| 821 |
+
},
|
| 822 |
+
"predicted": {
|
| 823 |
+
"amount": "1248",
|
| 824 |
+
"type": "debit",
|
| 825 |
+
"date": "05-11-2025",
|
| 826 |
+
"account": "484270768628",
|
| 827 |
+
"reference": "484270768628",
|
| 828 |
+
"merchant": "electricity",
|
| 829 |
+
"category": "bills"
|
| 830 |
+
},
|
| 831 |
+
"correct_fields": {
|
| 832 |
+
"amount": true,
|
| 833 |
+
"type": true,
|
| 834 |
+
"date": true,
|
| 835 |
+
"reference": true,
|
| 836 |
+
"merchant": true,
|
| 837 |
+
"category": true
|
| 838 |
+
},
|
| 839 |
+
"overall_correct": true,
|
| 840 |
+
"inference_time_ms": 2733.021020889282
|
| 841 |
+
},
|
| 842 |
+
{
|
| 843 |
+
"bank": "sbi",
|
| 844 |
+
"expected": {
|
| 845 |
+
"amount": "1759",
|
| 846 |
+
"type": "credit",
|
| 847 |
+
"date": "28/10/2025",
|
| 848 |
+
"account": "1685",
|
| 849 |
+
"reference": "239284873367"
|
| 850 |
+
},
|
| 851 |
+
"predicted": {
|
| 852 |
+
"amount": "1759",
|
| 853 |
+
"type": "credit",
|
| 854 |
+
"date": "28/10/2025",
|
| 855 |
+
"account": "1685",
|
| 856 |
+
"reference": "20251028-1685",
|
| 857 |
+
"merchant": "bigbazaar",
|
| 858 |
+
"category": "grocery"
|
| 859 |
+
},
|
| 860 |
+
"correct_fields": {
|
| 861 |
+
"amount": true,
|
| 862 |
+
"type": true,
|
| 863 |
+
"date": true,
|
| 864 |
+
"reference": false,
|
| 865 |
+
"merchant": false,
|
| 866 |
+
"category": false
|
| 867 |
+
},
|
| 868 |
+
"overall_correct": true,
|
| 869 |
+
"inference_time_ms": 2599.599838256836
|
| 870 |
+
},
|
| 871 |
+
{
|
| 872 |
+
"bank": "sbi",
|
| 873 |
+
"expected": {
|
| 874 |
+
"amount": "1203",
|
| 875 |
+
"type": "debit",
|
| 876 |
+
"date": "28122025",
|
| 877 |
+
"account": "5345",
|
| 878 |
+
"reference": "654966271979",
|
| 879 |
+
"merchant": "swiggy",
|
| 880 |
+
"category": "food"
|
| 881 |
+
},
|
| 882 |
+
"predicted": {
|
| 883 |
+
"amount": "1203",
|
| 884 |
+
"type": "debit",
|
| 885 |
+
"date": "28122025",
|
| 886 |
+
"account": "5345",
|
| 887 |
+
"reference": "1800112211",
|
| 888 |
+
"merchant": "swiggy",
|
| 889 |
+
"category": "food"
|
| 890 |
+
},
|
| 891 |
+
"correct_fields": {
|
| 892 |
+
"amount": true,
|
| 893 |
+
"type": true,
|
| 894 |
+
"date": true,
|
| 895 |
+
"reference": false,
|
| 896 |
+
"merchant": true,
|
| 897 |
+
"category": true
|
| 898 |
+
},
|
| 899 |
+
"overall_correct": true,
|
| 900 |
+
"inference_time_ms": 2496.210813522339
|
| 901 |
+
},
|
| 902 |
+
{
|
| 903 |
+
"bank": "axis",
|
| 904 |
+
"expected": {
|
| 905 |
+
"amount": "1191.16",
|
| 906 |
+
"type": "credit",
|
| 907 |
+
"date": "09/11/2025",
|
| 908 |
+
"account": "9702",
|
| 909 |
+
"reference": "610248199023"
|
| 910 |
+
},
|
| 911 |
+
"predicted": {
|
| 912 |
+
"amount": "1191.16",
|
| 913 |
+
"type": "credit",
|
| 914 |
+
"date": "09/11/2025",
|
| 915 |
+
"account": "9702",
|
| 916 |
+
"reference": "9702",
|
| 917 |
+
"merchant": "9702",
|
| 918 |
+
"category": "transfer"
|
| 919 |
+
},
|
| 920 |
+
"correct_fields": {
|
| 921 |
+
"amount": true,
|
| 922 |
+
"type": true,
|
| 923 |
+
"date": true,
|
| 924 |
+
"reference": false,
|
| 925 |
+
"merchant": false,
|
| 926 |
+
"category": false
|
| 927 |
+
},
|
| 928 |
+
"overall_correct": true,
|
| 929 |
+
"inference_time_ms": 2473.763942718506
|
| 930 |
+
},
|
| 931 |
+
{
|
| 932 |
+
"bank": "hdfc",
|
| 933 |
+
"expected": {
|
| 934 |
+
"amount": "3273.98",
|
| 935 |
+
"type": "debit",
|
| 936 |
+
"date": "24-11-2025",
|
| 937 |
+
"account": "2584",
|
| 938 |
+
"reference": "517010168081",
|
| 939 |
+
"merchant": "zomato",
|
| 940 |
+
"category": "food"
|
| 941 |
+
},
|
| 942 |
+
"predicted": {
|
| 943 |
+
"amount": "3273.98",
|
| 944 |
+
"type": "debit",
|
| 945 |
+
"date": "24-11-2025",
|
| 946 |
+
"account": "2584",
|
| 947 |
+
"reference": "20251124230010",
|
| 948 |
+
"merchant": "zomato",
|
| 949 |
+
"category": "food"
|
| 950 |
+
},
|
| 951 |
+
"correct_fields": {
|
| 952 |
+
"amount": true,
|
| 953 |
+
"type": true,
|
| 954 |
+
"date": true,
|
| 955 |
+
"reference": false,
|
| 956 |
+
"merchant": true,
|
| 957 |
+
"category": true
|
| 958 |
+
},
|
| 959 |
+
"overall_correct": true,
|
| 960 |
+
"inference_time_ms": 2694.82684135437
|
| 961 |
+
},
|
| 962 |
+
{
|
| 963 |
+
"bank": "phonepe",
|
| 964 |
+
"expected": {
|
| 965 |
+
"amount": "1266",
|
| 966 |
+
"type": "credit",
|
| 967 |
+
"date": "02/01/2026",
|
| 968 |
+
"account": "5632",
|
| 969 |
+
"reference": "874331514343"
|
| 970 |
+
},
|
| 971 |
+
"predicted": {
|
| 972 |
+
"amount": "1266",
|
| 973 |
+
"type": "credit",
|
| 974 |
+
"date": "02/01/2026",
|
| 975 |
+
"account": "5632",
|
| 976 |
+
"reference": "874331514343"
|
| 977 |
+
},
|
| 978 |
+
"correct_fields": {
|
| 979 |
+
"amount": true,
|
| 980 |
+
"type": true,
|
| 981 |
+
"date": true,
|
| 982 |
+
"reference": true,
|
| 983 |
+
"merchant": true,
|
| 984 |
+
"category": true
|
| 985 |
+
},
|
| 986 |
+
"overall_correct": true,
|
| 987 |
+
"inference_time_ms": 2088.062047958374
|
| 988 |
+
},
|
| 989 |
+
{
|
| 990 |
+
"bank": "kotak",
|
| 991 |
+
"expected": {
|
| 992 |
+
"amount": "738",
|
| 993 |
+
"type": "debit",
|
| 994 |
+
"date": "16/11/2025",
|
| 995 |
+
"account": "3091",
|
| 996 |
+
"reference": "614711052552",
|
| 997 |
+
"merchant": "water",
|
| 998 |
+
"category": "bills"
|
| 999 |
+
},
|
| 1000 |
+
"predicted": {
|
| 1001 |
+
"amount": "738",
|
| 1002 |
+
"type": "debit",
|
| 1003 |
+
"date": "16/11/2025",
|
| 1004 |
+
"account": "3091",
|
| 1005 |
+
"reference": "614711052552",
|
| 1006 |
+
"merchant": "kotak",
|
| 1007 |
+
"category": "bwssb"
|
| 1008 |
+
},
|
| 1009 |
+
"correct_fields": {
|
| 1010 |
+
"amount": true,
|
| 1011 |
+
"type": true,
|
| 1012 |
+
"date": true,
|
| 1013 |
+
"reference": true,
|
| 1014 |
+
"merchant": false,
|
| 1015 |
+
"category": false
|
| 1016 |
+
},
|
| 1017 |
+
"overall_correct": true,
|
| 1018 |
+
"inference_time_ms": 2597.2700119018555
|
| 1019 |
+
},
|
| 1020 |
+
{
|
| 1021 |
+
"bank": "icici",
|
| 1022 |
+
"expected": {
|
| 1023 |
+
"amount": "16416.70",
|
| 1024 |
+
"type": "credit",
|
| 1025 |
+
"date": "05-01-2026",
|
| 1026 |
+
"account": "4872",
|
| 1027 |
+
"reference": "928612436713"
|
| 1028 |
+
},
|
| 1029 |
+
"predicted": {
|
| 1030 |
+
"amount": "16416.70",
|
| 1031 |
+
"type": "credit",
|
| 1032 |
+
"date": "05-01-2026",
|
| 1033 |
+
"account": "4872",
|
| 1034 |
+
"reference": "928612436713"
|
| 1035 |
+
},
|
| 1036 |
+
"correct_fields": {
|
| 1037 |
+
"amount": true,
|
| 1038 |
+
"type": true,
|
| 1039 |
+
"date": true,
|
| 1040 |
+
"reference": true,
|
| 1041 |
+
"merchant": true,
|
| 1042 |
+
"category": true
|
| 1043 |
+
},
|
| 1044 |
+
"overall_correct": true,
|
| 1045 |
+
"inference_time_ms": 2160.959005355835
|
| 1046 |
+
},
|
| 1047 |
+
{
|
| 1048 |
+
"bank": "hdfc",
|
| 1049 |
+
"expected": {
|
| 1050 |
+
"amount": "1282.26",
|
| 1051 |
+
"type": "debit",
|
| 1052 |
+
"date": "15102025",
|
| 1053 |
+
"account": "8359",
|
| 1054 |
+
"reference": "342319992484",
|
| 1055 |
+
"merchant": "zomato",
|
| 1056 |
+
"category": "food"
|
| 1057 |
+
},
|
| 1058 |
+
"predicted": {
|
| 1059 |
+
"amount": "1282.26",
|
| 1060 |
+
"type": "debit",
|
| 1061 |
+
"date": "15102025",
|
| 1062 |
+
"account": "8359",
|
| 1063 |
+
"reference": "342319992484",
|
| 1064 |
+
"merchant": "zomato",
|
| 1065 |
+
"category": "food"
|
| 1066 |
+
},
|
| 1067 |
+
"correct_fields": {
|
| 1068 |
+
"amount": true,
|
| 1069 |
+
"type": true,
|
| 1070 |
+
"date": true,
|
| 1071 |
+
"reference": true,
|
| 1072 |
+
"merchant": true,
|
| 1073 |
+
"category": true
|
| 1074 |
+
},
|
| 1075 |
+
"overall_correct": true,
|
| 1076 |
+
"inference_time_ms": 2678.600072860718
|
| 1077 |
+
},
|
| 1078 |
+
{
|
| 1079 |
+
"bank": "sbi",
|
| 1080 |
+
"expected": {
|
| 1081 |
+
"amount": "8072",
|
| 1082 |
+
"type": "debit",
|
| 1083 |
+
"date": "08 Oct 2025",
|
| 1084 |
+
"account": "2832",
|
| 1085 |
+
"reference": "110999011248",
|
| 1086 |
+
"merchant": "ola",
|
| 1087 |
+
"category": "transport"
|
| 1088 |
+
},
|
| 1089 |
+
"predicted": {
|
| 1090 |
+
"amount": "8072",
|
| 1091 |
+
"type": "debit",
|
| 1092 |
+
"date": "08 Oct 2025",
|
| 1093 |
+
"account": "2832",
|
| 1094 |
+
"reference": "110999011248",
|
| 1095 |
+
"merchant": "ola",
|
| 1096 |
+
"category": "transport"
|
| 1097 |
+
},
|
| 1098 |
+
"correct_fields": {
|
| 1099 |
+
"amount": true,
|
| 1100 |
+
"type": true,
|
| 1101 |
+
"date": true,
|
| 1102 |
+
"reference": true,
|
| 1103 |
+
"merchant": true,
|
| 1104 |
+
"category": true
|
| 1105 |
+
},
|
| 1106 |
+
"overall_correct": true,
|
| 1107 |
+
"inference_time_ms": 2529.703140258789
|
| 1108 |
+
},
|
| 1109 |
+
{
|
| 1110 |
+
"bank": "kotak",
|
| 1111 |
+
"expected": {
|
| 1112 |
+
"amount": "7304",
|
| 1113 |
+
"type": "credit",
|
| 1114 |
+
"date": "14 Nov 2025",
|
| 1115 |
+
"account": "6934",
|
| 1116 |
+
"reference": "572899688547"
|
| 1117 |
+
},
|
| 1118 |
+
"predicted": {
|
| 1119 |
+
"amount": "7304",
|
| 1120 |
+
"type": "credit",
|
| 1121 |
+
"date": "14 Nov 2025",
|
| 1122 |
+
"account": "6934",
|
| 1123 |
+
"reference": "7304",
|
| 1124 |
+
"merchant": "6934",
|
| 1125 |
+
"category": "grocery"
|
| 1126 |
+
},
|
| 1127 |
+
"correct_fields": {
|
| 1128 |
+
"amount": true,
|
| 1129 |
+
"type": true,
|
| 1130 |
+
"date": true,
|
| 1131 |
+
"reference": false,
|
| 1132 |
+
"merchant": false,
|
| 1133 |
+
"category": false
|
| 1134 |
+
},
|
| 1135 |
+
"overall_correct": true,
|
| 1136 |
+
"inference_time_ms": 2413.489818572998
|
| 1137 |
+
},
|
| 1138 |
+
{
|
| 1139 |
+
"bank": "hdfc",
|
| 1140 |
+
"expected": {
|
| 1141 |
+
"amount": "6562.42",
|
| 1142 |
+
"type": "debit",
|
| 1143 |
+
"date": "30/12/2025",
|
| 1144 |
+
"account": "6168",
|
| 1145 |
+
"reference": "137889353643",
|
| 1146 |
+
"merchant": "electricity",
|
| 1147 |
+
"category": "bills"
|
| 1148 |
+
},
|
| 1149 |
+
"predicted": {
|
| 1150 |
+
"amount": "6562.42",
|
| 1151 |
+
"type": "debit",
|
| 1152 |
+
"date": "30/12/2025",
|
| 1153 |
+
"account": "6168",
|
| 1154 |
+
"reference": "6168",
|
| 1155 |
+
"merchant": "electricity",
|
| 1156 |
+
"category": "bills"
|
| 1157 |
+
},
|
| 1158 |
+
"correct_fields": {
|
| 1159 |
+
"amount": true,
|
| 1160 |
+
"type": true,
|
| 1161 |
+
"date": true,
|
| 1162 |
+
"reference": false,
|
| 1163 |
+
"merchant": true,
|
| 1164 |
+
"category": true
|
| 1165 |
+
},
|
| 1166 |
+
"overall_correct": true,
|
| 1167 |
+
"inference_time_ms": 2483.527183532715
|
| 1168 |
+
},
|
| 1169 |
+
{
|
| 1170 |
+
"bank": "gpay",
|
| 1171 |
+
"expected": {
|
| 1172 |
+
"amount": "1632",
|
| 1173 |
+
"type": "debit",
|
| 1174 |
+
"date": "02-11-2025",
|
| 1175 |
+
"account": "7770",
|
| 1176 |
+
"reference": "609136562669",
|
| 1177 |
+
"merchant": "rapido",
|
| 1178 |
+
"category": "transport"
|
| 1179 |
+
},
|
| 1180 |
+
"predicted": {
|
| 1181 |
+
"amount": "1632",
|
| 1182 |
+
"type": "debit",
|
| 1183 |
+
"date": "02-11-2025",
|
| 1184 |
+
"account": "609136562669",
|
| 1185 |
+
"merchant": "rapido",
|
| 1186 |
+
"category": "transport"
|
| 1187 |
+
},
|
| 1188 |
+
"correct_fields": {
|
| 1189 |
+
"amount": true,
|
| 1190 |
+
"type": true,
|
| 1191 |
+
"date": true,
|
| 1192 |
+
"reference": false,
|
| 1193 |
+
"merchant": true,
|
| 1194 |
+
"category": true
|
| 1195 |
+
},
|
| 1196 |
+
"overall_correct": true,
|
| 1197 |
+
"inference_time_ms": 2277.514934539795
|
| 1198 |
+
},
|
| 1199 |
+
{
|
| 1200 |
+
"bank": "sbi",
|
| 1201 |
+
"expected": {
|
| 1202 |
+
"amount": "1432",
|
| 1203 |
+
"type": "debit",
|
| 1204 |
+
"date": "16-11-2025",
|
| 1205 |
+
"account": "1651",
|
| 1206 |
+
"reference": "373029676920",
|
| 1207 |
+
"merchant": "amazon",
|
| 1208 |
+
"category": "shopping"
|
| 1209 |
+
},
|
| 1210 |
+
"predicted": {
|
| 1211 |
+
"amount": "1432",
|
| 1212 |
+
"type": "debit",
|
| 1213 |
+
"date": "16-11-2025",
|
| 1214 |
+
"account": "1651",
|
| 1215 |
+
"reference": "373029676920",
|
| 1216 |
+
"merchant": "amazon",
|
| 1217 |
+
"category": "shopping"
|
| 1218 |
+
},
|
| 1219 |
+
"correct_fields": {
|
| 1220 |
+
"amount": true,
|
| 1221 |
+
"type": true,
|
| 1222 |
+
"date": true,
|
| 1223 |
+
"reference": true,
|
| 1224 |
+
"merchant": true,
|
| 1225 |
+
"category": true
|
| 1226 |
+
},
|
| 1227 |
+
"overall_correct": true,
|
| 1228 |
+
"inference_time_ms": 2709.423065185547
|
| 1229 |
+
},
|
| 1230 |
+
{
|
| 1231 |
+
"bank": "phonepe",
|
| 1232 |
+
"expected": {
|
| 1233 |
+
"amount": "4426.23",
|
| 1234 |
+
"type": "debit",
|
| 1235 |
+
"date": "29-11-2025",
|
| 1236 |
+
"account": "3073",
|
| 1237 |
+
"reference": "687156468494",
|
| 1238 |
+
"merchant": "dmart",
|
| 1239 |
+
"category": "grocery"
|
| 1240 |
+
},
|
| 1241 |
+
"predicted": {
|
| 1242 |
+
"amount": "4426.23",
|
| 1243 |
+
"type": "debit",
|
| 1244 |
+
"date": "29-11-2025",
|
| 1245 |
+
"account": "20250129",
|
| 1246 |
+
"reference": "687156468494",
|
| 1247 |
+
"merchant": "dmart",
|
| 1248 |
+
"category": "grocery"
|
| 1249 |
+
},
|
| 1250 |
+
"correct_fields": {
|
| 1251 |
+
"amount": true,
|
| 1252 |
+
"type": true,
|
| 1253 |
+
"date": true,
|
| 1254 |
+
"reference": true,
|
| 1255 |
+
"merchant": true,
|
| 1256 |
+
"category": true
|
| 1257 |
+
},
|
| 1258 |
+
"overall_correct": true,
|
| 1259 |
+
"inference_time_ms": 3300.4870414733887
|
| 1260 |
+
},
|
| 1261 |
+
{
|
| 1262 |
+
"bank": "axis",
|
| 1263 |
+
"expected": {
|
| 1264 |
+
"amount": "1907",
|
| 1265 |
+
"type": "credit",
|
| 1266 |
+
"date": "17 Dec 2025",
|
| 1267 |
+
"account": "5050",
|
| 1268 |
+
"reference": "385400876441"
|
| 1269 |
+
},
|
| 1270 |
+
"predicted": {
|
| 1271 |
+
"amount": "1907",
|
| 1272 |
+
"type": "credit",
|
| 1273 |
+
"date": "17 Dec 2025",
|
| 1274 |
+
"account": "5050",
|
| 1275 |
+
"reference": "385400876441",
|
| 1276 |
+
"merchant": "mutual fund",
|
| 1277 |
+
"category": "transfer"
|
| 1278 |
+
},
|
| 1279 |
+
"correct_fields": {
|
| 1280 |
+
"amount": true,
|
| 1281 |
+
"type": true,
|
| 1282 |
+
"date": true,
|
| 1283 |
+
"reference": true,
|
| 1284 |
+
"merchant": false,
|
| 1285 |
+
"category": false
|
| 1286 |
+
},
|
| 1287 |
+
"overall_correct": true,
|
| 1288 |
+
"inference_time_ms": 2559.9451065063477
|
| 1289 |
+
},
|
| 1290 |
+
{
|
| 1291 |
+
"bank": "kotak",
|
| 1292 |
+
"expected": {
|
| 1293 |
+
"amount": "37460",
|
| 1294 |
+
"type": "debit",
|
| 1295 |
+
"date": "29102025",
|
| 1296 |
+
"account": "8999",
|
| 1297 |
+
"reference": "344374238950",
|
| 1298 |
+
"merchant": "rapido",
|
| 1299 |
+
"category": "transport"
|
| 1300 |
+
},
|
| 1301 |
+
"predicted": {
|
| 1302 |
+
"amount": "37460",
|
| 1303 |
+
"type": "debit",
|
| 1304 |
+
"date": "29102025",
|
| 1305 |
+
"account": "8999",
|
| 1306 |
+
"reference": "344374238950",
|
| 1307 |
+
"merchant": "rapido",
|
| 1308 |
+
"category": "transport"
|
| 1309 |
+
},
|
| 1310 |
+
"correct_fields": {
|
| 1311 |
+
"amount": true,
|
| 1312 |
+
"type": true,
|
| 1313 |
+
"date": true,
|
| 1314 |
+
"reference": true,
|
| 1315 |
+
"merchant": true,
|
| 1316 |
+
"category": true
|
| 1317 |
+
},
|
| 1318 |
+
"overall_correct": true,
|
| 1319 |
+
"inference_time_ms": 2535.1550579071045
|
| 1320 |
+
},
|
| 1321 |
+
{
|
| 1322 |
+
"bank": "phonepe",
|
| 1323 |
+
"expected": {
|
| 1324 |
+
"amount": "85.29",
|
| 1325 |
+
"type": "debit",
|
| 1326 |
+
"date": "16/11/2025",
|
| 1327 |
+
"account": "7046",
|
| 1328 |
+
"reference": "827164617915",
|
| 1329 |
+
"merchant": "water",
|
| 1330 |
+
"category": "bills"
|
| 1331 |
+
},
|
| 1332 |
+
"predicted": {
|
| 1333 |
+
"amount": "85.29",
|
| 1334 |
+
"type": "debit",
|
| 1335 |
+
"date": "16/11/2025",
|
| 1336 |
+
"account": "7046",
|
| 1337 |
+
"reference": "827164617915",
|
| 1338 |
+
"merchant": "water",
|
| 1339 |
+
"category": "bills"
|
| 1340 |
+
},
|
| 1341 |
+
"correct_fields": {
|
| 1342 |
+
"amount": true,
|
| 1343 |
+
"type": true,
|
| 1344 |
+
"date": true,
|
| 1345 |
+
"reference": true,
|
| 1346 |
+
"merchant": true,
|
| 1347 |
+
"category": true
|
| 1348 |
+
},
|
| 1349 |
+
"overall_correct": true,
|
| 1350 |
+
"inference_time_ms": 2577.362298965454
|
| 1351 |
+
},
|
| 1352 |
+
{
|
| 1353 |
+
"bank": "hdfc",
|
| 1354 |
+
"expected": {
|
| 1355 |
+
"amount": "1981",
|
| 1356 |
+
"type": "credit",
|
| 1357 |
+
"date": "27/11/2025",
|
| 1358 |
+
"account": "7482",
|
| 1359 |
+
"reference": "648275934229"
|
| 1360 |
+
},
|
| 1361 |
+
"predicted": {
|
| 1362 |
+
"amount": "1981",
|
| 1363 |
+
"type": "credit",
|
| 1364 |
+
"date": "27/11/2025",
|
| 1365 |
+
"account": "7482",
|
| 1366 |
+
"reference": "648275934229"
|
| 1367 |
+
},
|
| 1368 |
+
"correct_fields": {
|
| 1369 |
+
"amount": true,
|
| 1370 |
+
"type": true,
|
| 1371 |
+
"date": true,
|
| 1372 |
+
"reference": true,
|
| 1373 |
+
"merchant": true,
|
| 1374 |
+
"category": true
|
| 1375 |
+
},
|
| 1376 |
+
"overall_correct": true,
|
| 1377 |
+
"inference_time_ms": 2097.447156906128
|
| 1378 |
+
},
|
| 1379 |
+
{
|
| 1380 |
+
"bank": "gpay",
|
| 1381 |
+
"expected": {
|
| 1382 |
+
"amount": "389",
|
| 1383 |
+
"type": "debit",
|
| 1384 |
+
"date": "22102025",
|
| 1385 |
+
"account": "8195",
|
| 1386 |
+
"reference": "417489104406",
|
| 1387 |
+
"merchant": "ola",
|
| 1388 |
+
"category": "transport"
|
| 1389 |
+
},
|
| 1390 |
+
"predicted": {
|
| 1391 |
+
"amount": "389",
|
| 1392 |
+
"type": "debit",
|
| 1393 |
+
"date": "22102025",
|
| 1394 |
+
"account": "417489104406",
|
| 1395 |
+
"merchant": "ola",
|
| 1396 |
+
"category": "transport"
|
| 1397 |
+
},
|
| 1398 |
+
"correct_fields": {
|
| 1399 |
+
"amount": true,
|
| 1400 |
+
"type": true,
|
| 1401 |
+
"date": true,
|
| 1402 |
+
"reference": false,
|
| 1403 |
+
"merchant": true,
|
| 1404 |
+
"category": true
|
| 1405 |
+
},
|
| 1406 |
+
"overall_correct": true,
|
| 1407 |
+
"inference_time_ms": 2155.5891036987305
|
| 1408 |
+
},
|
| 1409 |
+
{
|
| 1410 |
+
"bank": "gpay",
|
| 1411 |
+
"expected": {
|
| 1412 |
+
"amount": "2571.54",
|
| 1413 |
+
"type": "credit",
|
| 1414 |
+
"date": "24112025",
|
| 1415 |
+
"account": "5891",
|
| 1416 |
+
"reference": "409248663017"
|
| 1417 |
+
},
|
| 1418 |
+
"predicted": {
|
| 1419 |
+
"amount": "2571.54",
|
| 1420 |
+
"type": "credit",
|
| 1421 |
+
"date": "24112025",
|
| 1422 |
+
"account": "409248663017",
|
| 1423 |
+
"merchant": "google",
|
| 1424 |
+
"category": "shopping"
|
| 1425 |
+
},
|
| 1426 |
+
"correct_fields": {
|
| 1427 |
+
"amount": true,
|
| 1428 |
+
"type": true,
|
| 1429 |
+
"date": true,
|
| 1430 |
+
"reference": false,
|
| 1431 |
+
"merchant": false,
|
| 1432 |
+
"category": false
|
| 1433 |
+
},
|
| 1434 |
+
"overall_correct": true,
|
| 1435 |
+
"inference_time_ms": 2324.397087097168
|
| 1436 |
+
},
|
| 1437 |
+
{
|
| 1438 |
+
"bank": "hdfc",
|
| 1439 |
+
"expected": {
|
| 1440 |
+
"amount": "3143",
|
| 1441 |
+
"type": "debit",
|
| 1442 |
+
"date": "12102025",
|
| 1443 |
+
"account": "7912",
|
| 1444 |
+
"reference": "748913461122",
|
| 1445 |
+
"merchant": "swiggy",
|
| 1446 |
+
"category": "food"
|
| 1447 |
+
},
|
| 1448 |
+
"predicted": {
|
| 1449 |
+
"amount": "3143",
|
| 1450 |
+
"type": "debit",
|
| 1451 |
+
"date": "12102025",
|
| 1452 |
+
"account": "7912",
|
| 1453 |
+
"reference": "748913461122",
|
| 1454 |
+
"merchant": "bigbazaar",
|
| 1455 |
+
"category": "grocery"
|
| 1456 |
+
},
|
| 1457 |
+
"correct_fields": {
|
| 1458 |
+
"amount": true,
|
| 1459 |
+
"type": true,
|
| 1460 |
+
"date": true,
|
| 1461 |
+
"reference": true,
|
| 1462 |
+
"merchant": false,
|
| 1463 |
+
"category": false
|
| 1464 |
+
},
|
| 1465 |
+
"overall_correct": true,
|
| 1466 |
+
"inference_time_ms": 2544.909954071045
|
| 1467 |
+
},
|
| 1468 |
+
{
|
| 1469 |
+
"bank": "kotak",
|
| 1470 |
+
"expected": {
|
| 1471 |
+
"amount": "8160",
|
| 1472 |
+
"type": "debit",
|
| 1473 |
+
"date": "14-11-25",
|
| 1474 |
+
"account": "8705",
|
| 1475 |
+
"reference": "189485261008",
|
| 1476 |
+
"merchant": "rapido",
|
| 1477 |
+
"category": "transport"
|
| 1478 |
+
},
|
| 1479 |
+
"predicted": {
|
| 1480 |
+
"amount": "8160",
|
| 1481 |
+
"type": "debit",
|
| 1482 |
+
"date": "14-11-25",
|
| 1483 |
+
"account": "8705",
|
| 1484 |
+
"reference": "189485261008",
|
| 1485 |
+
"merchant": "rapido",
|
| 1486 |
+
"category": "transport"
|
| 1487 |
+
},
|
| 1488 |
+
"correct_fields": {
|
| 1489 |
+
"amount": true,
|
| 1490 |
+
"type": true,
|
| 1491 |
+
"date": true,
|
| 1492 |
+
"reference": true,
|
| 1493 |
+
"merchant": true,
|
| 1494 |
+
"category": true
|
| 1495 |
+
},
|
| 1496 |
+
"overall_correct": true,
|
| 1497 |
+
"inference_time_ms": 2458.6687088012695
|
| 1498 |
+
},
|
| 1499 |
+
{
|
| 1500 |
+
"bank": "paytm",
|
| 1501 |
+
"expected": {
|
| 1502 |
+
"amount": "5151",
|
| 1503 |
+
"type": "credit",
|
| 1504 |
+
"date": "24/12/2025",
|
| 1505 |
+
"account": "6881",
|
| 1506 |
+
"reference": "728703172393"
|
| 1507 |
+
},
|
| 1508 |
+
"predicted": {
|
| 1509 |
+
"amount": "5151",
|
| 1510 |
+
"type": "credit",
|
| 1511 |
+
"date": "06-11-25",
|
| 1512 |
+
"account": "6881",
|
| 1513 |
+
"reference": "728703172393"
|
| 1514 |
+
},
|
| 1515 |
+
"correct_fields": {
|
| 1516 |
+
"amount": true,
|
| 1517 |
+
"type": true,
|
| 1518 |
+
"date": false,
|
| 1519 |
+
"reference": true,
|
| 1520 |
+
"merchant": true,
|
| 1521 |
+
"category": true
|
| 1522 |
+
},
|
| 1523 |
+
"overall_correct": true,
|
| 1524 |
+
"inference_time_ms": 2014.5847797393799
|
| 1525 |
+
},
|
| 1526 |
+
{
|
| 1527 |
+
"bank": "icici",
|
| 1528 |
+
"expected": {
|
| 1529 |
+
"amount": "692.75",
|
| 1530 |
+
"type": "credit",
|
| 1531 |
+
"date": "06112025",
|
| 1532 |
+
"account": "1931",
|
| 1533 |
+
"reference": "274079861243"
|
| 1534 |
+
},
|
| 1535 |
+
"predicted": {
|
| 1536 |
+
"amount": "692.75",
|
| 1537 |
+
"type": "credit",
|
| 1538 |
+
"date": "06112025",
|
| 1539 |
+
"account": "1931",
|
| 1540 |
+
"reference": "274079861243"
|
| 1541 |
+
},
|
| 1542 |
+
"correct_fields": {
|
| 1543 |
+
"amount": true,
|
| 1544 |
+
"type": true,
|
| 1545 |
+
"date": true,
|
| 1546 |
+
"reference": true,
|
| 1547 |
+
"merchant": true,
|
| 1548 |
+
"category": true
|
| 1549 |
+
},
|
| 1550 |
+
"overall_correct": true,
|
| 1551 |
+
"inference_time_ms": 2065.8881664276123
|
| 1552 |
+
},
|
| 1553 |
+
{
|
| 1554 |
+
"bank": "sbi",
|
| 1555 |
+
"expected": {
|
| 1556 |
+
"amount": "620",
|
| 1557 |
+
"type": "credit",
|
| 1558 |
+
"date": "02-12-25",
|
| 1559 |
+
"account": "7548",
|
| 1560 |
+
"reference": "661100891573"
|
| 1561 |
+
},
|
| 1562 |
+
"predicted": {
|
| 1563 |
+
"amount": "620",
|
| 1564 |
+
"type": "credit",
|
| 1565 |
+
"date": "02-12-25",
|
| 1566 |
+
"account": "7548",
|
| 1567 |
+
"reference": "661100891573"
|
| 1568 |
+
},
|
| 1569 |
+
"correct_fields": {
|
| 1570 |
+
"amount": true,
|
| 1571 |
+
"type": true,
|
| 1572 |
+
"date": true,
|
| 1573 |
+
"reference": true,
|
| 1574 |
+
"merchant": true,
|
| 1575 |
+
"category": true
|
| 1576 |
+
},
|
| 1577 |
+
"overall_correct": true,
|
| 1578 |
+
"inference_time_ms": 1989.2139434814453
|
| 1579 |
+
},
|
| 1580 |
+
{
|
| 1581 |
+
"bank": "kotak",
|
| 1582 |
+
"expected": {
|
| 1583 |
+
"amount": "927.60",
|
| 1584 |
+
"type": "debit",
|
| 1585 |
+
"date": "14-12-2025",
|
| 1586 |
+
"account": "6363",
|
| 1587 |
+
"reference": "517729190564",
|
| 1588 |
+
"merchant": "airtel",
|
| 1589 |
+
"category": "bills"
|
| 1590 |
+
},
|
| 1591 |
+
"predicted": {
|
| 1592 |
+
"amount": "927.60",
|
| 1593 |
+
"type": "debit",
|
| 1594 |
+
"date": "14-12-2025",
|
| 1595 |
+
"account": "6363",
|
| 1596 |
+
"reference": "517729190564",
|
| 1597 |
+
"merchant": "airtel",
|
| 1598 |
+
"category": "bills"
|
| 1599 |
+
},
|
| 1600 |
+
"correct_fields": {
|
| 1601 |
+
"amount": true,
|
| 1602 |
+
"type": true,
|
| 1603 |
+
"date": true,
|
| 1604 |
+
"reference": true,
|
| 1605 |
+
"merchant": true,
|
| 1606 |
+
"category": true
|
| 1607 |
+
},
|
| 1608 |
+
"overall_correct": true,
|
| 1609 |
+
"inference_time_ms": 2634.366989135742
|
| 1610 |
+
},
|
| 1611 |
+
{
|
| 1612 |
+
"bank": "gpay",
|
| 1613 |
+
"expected": {
|
| 1614 |
+
"amount": "6712",
|
| 1615 |
+
"type": "debit",
|
| 1616 |
+
"date": "04-01-26",
|
| 1617 |
+
"account": "3870",
|
| 1618 |
+
"reference": "145424634923",
|
| 1619 |
+
"merchant": "zomato",
|
| 1620 |
+
"category": "food"
|
| 1621 |
+
},
|
| 1622 |
+
"predicted": {
|
| 1623 |
+
"amount": "6712",
|
| 1624 |
+
"type": "debit",
|
| 1625 |
+
"date": "04-01-26",
|
| 1626 |
+
"account": "6712",
|
| 1627 |
+
"reference": "145424634923",
|
| 1628 |
+
"merchant": "zomato",
|
| 1629 |
+
"category": "food"
|
| 1630 |
+
},
|
| 1631 |
+
"correct_fields": {
|
| 1632 |
+
"amount": true,
|
| 1633 |
+
"type": true,
|
| 1634 |
+
"date": true,
|
| 1635 |
+
"reference": true,
|
| 1636 |
+
"merchant": true,
|
| 1637 |
+
"category": true
|
| 1638 |
+
},
|
| 1639 |
+
"overall_correct": true,
|
| 1640 |
+
"inference_time_ms": 2525.550127029419
|
| 1641 |
+
},
|
| 1642 |
+
{
|
| 1643 |
+
"bank": "paytm",
|
| 1644 |
+
"expected": {
|
| 1645 |
+
"amount": "1638",
|
| 1646 |
+
"type": "debit",
|
| 1647 |
+
"date": "27 Nov 2025",
|
| 1648 |
+
"account": "7325",
|
| 1649 |
+
"reference": "520096802415",
|
| 1650 |
+
"merchant": "bigbazaar",
|
| 1651 |
+
"category": "grocery"
|
| 1652 |
+
},
|
| 1653 |
+
"predicted": {
|
| 1654 |
+
"amount": "1638",
|
| 1655 |
+
"type": "debit",
|
| 1656 |
+
"date": "27 Nov 2025",
|
| 1657 |
+
"account": "520096802415",
|
| 1658 |
+
"reference": "520096802415",
|
| 1659 |
+
"merchant": "bigbazaar",
|
| 1660 |
+
"category": "grocery"
|
| 1661 |
+
},
|
| 1662 |
+
"correct_fields": {
|
| 1663 |
+
"amount": true,
|
| 1664 |
+
"type": true,
|
| 1665 |
+
"date": true,
|
| 1666 |
+
"reference": true,
|
| 1667 |
+
"merchant": true,
|
| 1668 |
+
"category": true
|
| 1669 |
+
},
|
| 1670 |
+
"overall_correct": true,
|
| 1671 |
+
"inference_time_ms": 2758.028984069824
|
| 1672 |
+
},
|
| 1673 |
+
{
|
| 1674 |
+
"bank": "gpay",
|
| 1675 |
+
"expected": {
|
| 1676 |
+
"amount": "7416",
|
| 1677 |
+
"type": "debit",
|
| 1678 |
+
"date": "12 Dec 2025",
|
| 1679 |
+
"account": "4683",
|
| 1680 |
+
"reference": "697493414595",
|
| 1681 |
+
"merchant": "myntra",
|
| 1682 |
+
"category": "shopping"
|
| 1683 |
+
},
|
| 1684 |
+
"predicted": {
|
| 1685 |
+
"amount": "7416",
|
| 1686 |
+
"type": "debit",
|
| 1687 |
+
"date": "12 Dec 2025",
|
| 1688 |
+
"account": "1608",
|
| 1689 |
+
"reference": "697493414595",
|
| 1690 |
+
"merchant": "myntra",
|
| 1691 |
+
"category": "shopping"
|
| 1692 |
+
},
|
| 1693 |
+
"correct_fields": {
|
| 1694 |
+
"amount": true,
|
| 1695 |
+
"type": true,
|
| 1696 |
+
"date": true,
|
| 1697 |
+
"reference": true,
|
| 1698 |
+
"merchant": true,
|
| 1699 |
+
"category": true
|
| 1700 |
+
},
|
| 1701 |
+
"overall_correct": true,
|
| 1702 |
+
"inference_time_ms": 2545.9578037261963
|
| 1703 |
+
},
|
| 1704 |
+
{
|
| 1705 |
+
"bank": "phonepe",
|
| 1706 |
+
"expected": {
|
| 1707 |
+
"amount": "3728.11",
|
| 1708 |
+
"type": "credit",
|
| 1709 |
+
"date": "17/12/2025",
|
| 1710 |
+
"account": "2229",
|
| 1711 |
+
"reference": "706336912249"
|
| 1712 |
+
},
|
| 1713 |
+
"predicted": {
|
| 1714 |
+
"amount": "3728.11",
|
| 1715 |
+
"type": "credit",
|
| 1716 |
+
"date": "17/12/2025",
|
| 1717 |
+
"account": "3011",
|
| 1718 |
+
"reference": "8410",
|
| 1719 |
+
"merchant": "phonepe",
|
| 1720 |
+
"category": "transport"
|
| 1721 |
+
},
|
| 1722 |
+
"correct_fields": {
|
| 1723 |
+
"amount": true,
|
| 1724 |
+
"type": true,
|
| 1725 |
+
"date": true,
|
| 1726 |
+
"reference": false,
|
| 1727 |
+
"merchant": false,
|
| 1728 |
+
"category": false
|
| 1729 |
+
},
|
| 1730 |
+
"overall_correct": true,
|
| 1731 |
+
"inference_time_ms": 2339.136838912964
|
| 1732 |
+
},
|
| 1733 |
+
{
|
| 1734 |
+
"bank": "kotak",
|
| 1735 |
+
"expected": {
|
| 1736 |
+
"amount": "102",
|
| 1737 |
+
"type": "credit",
|
| 1738 |
+
"date": "25 Oct 2025",
|
| 1739 |
+
"account": "2245",
|
| 1740 |
+
"reference": "317819329568"
|
| 1741 |
+
},
|
| 1742 |
+
"predicted": {
|
| 1743 |
+
"amount": "102",
|
| 1744 |
+
"type": "credit",
|
| 1745 |
+
"date": "25 Oct 2025",
|
| 1746 |
+
"account": "2245",
|
| 1747 |
+
"reference": "317819329568"
|
| 1748 |
+
},
|
| 1749 |
+
"correct_fields": {
|
| 1750 |
+
"amount": true,
|
| 1751 |
+
"type": true,
|
| 1752 |
+
"date": true,
|
| 1753 |
+
"reference": true,
|
| 1754 |
+
"merchant": true,
|
| 1755 |
+
"category": true
|
| 1756 |
+
},
|
| 1757 |
+
"overall_correct": true,
|
| 1758 |
+
"inference_time_ms": 2017.0180797576904
|
| 1759 |
+
},
|
| 1760 |
+
{
|
| 1761 |
+
"bank": "phonepe",
|
| 1762 |
+
"expected": {
|
| 1763 |
+
"amount": "1577",
|
| 1764 |
+
"type": "debit",
|
| 1765 |
+
"date": "22 Nov 2025",
|
| 1766 |
+
"account": "5118",
|
| 1767 |
+
"reference": "436171026274",
|
| 1768 |
+
"merchant": "dmart",
|
| 1769 |
+
"category": "grocery"
|
| 1770 |
+
},
|
| 1771 |
+
"predicted": {
|
| 1772 |
+
"amount": "1577",
|
| 1773 |
+
"type": "debit",
|
| 1774 |
+
"date": "22 Nov 2025",
|
| 1775 |
+
"account": "2210",
|
| 1776 |
+
"reference": "436171026274",
|
| 1777 |
+
"merchant": "dmart",
|
| 1778 |
+
"category": "grocery"
|
| 1779 |
+
},
|
| 1780 |
+
"correct_fields": {
|
| 1781 |
+
"amount": true,
|
| 1782 |
+
"type": true,
|
| 1783 |
+
"date": true,
|
| 1784 |
+
"reference": true,
|
| 1785 |
+
"merchant": true,
|
| 1786 |
+
"category": true
|
| 1787 |
+
},
|
| 1788 |
+
"overall_correct": true,
|
| 1789 |
+
"inference_time_ms": 2541.3999557495117
|
| 1790 |
+
},
|
| 1791 |
+
{
|
| 1792 |
+
"bank": "kotak",
|
| 1793 |
+
"expected": {
|
| 1794 |
+
"amount": "1755",
|
| 1795 |
+
"type": "debit",
|
| 1796 |
+
"date": "24-10-2025",
|
| 1797 |
+
"account": "7232",
|
| 1798 |
+
"reference": "734648396163",
|
| 1799 |
+
"merchant": "water",
|
| 1800 |
+
"category": "bills"
|
| 1801 |
+
},
|
| 1802 |
+
"predicted": {
|
| 1803 |
+
"amount": "1755",
|
| 1804 |
+
"type": "debit",
|
| 1805 |
+
"date": "24-10-2025",
|
| 1806 |
+
"account": "7232",
|
| 1807 |
+
"reference": "7232",
|
| 1808 |
+
"merchant": "water",
|
| 1809 |
+
"category": "bills"
|
| 1810 |
+
},
|
| 1811 |
+
"correct_fields": {
|
| 1812 |
+
"amount": true,
|
| 1813 |
+
"type": true,
|
| 1814 |
+
"date": true,
|
| 1815 |
+
"reference": false,
|
| 1816 |
+
"merchant": true,
|
| 1817 |
+
"category": true
|
| 1818 |
+
},
|
| 1819 |
+
"overall_correct": true,
|
| 1820 |
+
"inference_time_ms": 2368.7260150909424
|
| 1821 |
+
},
|
| 1822 |
+
{
|
| 1823 |
+
"bank": "hdfc",
|
| 1824 |
+
"expected": {
|
| 1825 |
+
"amount": "333",
|
| 1826 |
+
"type": "credit",
|
| 1827 |
+
"date": "26-12-2025",
|
| 1828 |
+
"account": "3504",
|
| 1829 |
+
"reference": "223957493142"
|
| 1830 |
+
},
|
| 1831 |
+
"predicted": {
|
| 1832 |
+
"amount": "333",
|
| 1833 |
+
"type": "credit",
|
| 1834 |
+
"date": "26-12-2025",
|
| 1835 |
+
"account": "3504",
|
| 1836 |
+
"reference": "223957493142"
|
| 1837 |
+
},
|
| 1838 |
+
"correct_fields": {
|
| 1839 |
+
"amount": true,
|
| 1840 |
+
"type": true,
|
| 1841 |
+
"date": true,
|
| 1842 |
+
"reference": true,
|
| 1843 |
+
"merchant": true,
|
| 1844 |
+
"category": true
|
| 1845 |
+
},
|
| 1846 |
+
"overall_correct": true,
|
| 1847 |
+
"inference_time_ms": 2064.250707626343
|
| 1848 |
+
},
|
| 1849 |
+
{
|
| 1850 |
+
"bank": "paytm",
|
| 1851 |
+
"expected": {
|
| 1852 |
+
"amount": "1749",
|
| 1853 |
+
"type": "credit",
|
| 1854 |
+
"date": "02-12-2025",
|
| 1855 |
+
"account": "1803",
|
| 1856 |
+
"reference": "957643978300"
|
| 1857 |
+
},
|
| 1858 |
+
"predicted": {
|
| 1859 |
+
"amount": "1749",
|
| 1860 |
+
"type": "credit",
|
| 1861 |
+
"date": "02-12-2025",
|
| 1862 |
+
"account": "3098",
|
| 1863 |
+
"reference": "4567",
|
| 1864 |
+
"merchant": "4567",
|
| 1865 |
+
"category": "food"
|
| 1866 |
+
},
|
| 1867 |
+
"correct_fields": {
|
| 1868 |
+
"amount": true,
|
| 1869 |
+
"type": true,
|
| 1870 |
+
"date": true,
|
| 1871 |
+
"reference": false,
|
| 1872 |
+
"merchant": false,
|
| 1873 |
+
"category": false
|
| 1874 |
+
},
|
| 1875 |
+
"overall_correct": true,
|
| 1876 |
+
"inference_time_ms": 2306.1821460723877
|
| 1877 |
+
},
|
| 1878 |
+
{
|
| 1879 |
+
"bank": "phonepe",
|
| 1880 |
+
"expected": {
|
| 1881 |
+
"amount": "1983.97",
|
| 1882 |
+
"type": "debit",
|
| 1883 |
+
"date": "05-11-2025",
|
| 1884 |
+
"account": "5658",
|
| 1885 |
+
"reference": "116633204627",
|
| 1886 |
+
"merchant": "kfc",
|
| 1887 |
+
"category": "food"
|
| 1888 |
+
},
|
| 1889 |
+
"predicted": {
|
| 1890 |
+
"amount": "1983.97",
|
| 1891 |
+
"type": "debit",
|
| 1892 |
+
"date": "05-11-2025",
|
| 1893 |
+
"account": "5658",
|
| 1894 |
+
"reference": "116633204627",
|
| 1895 |
+
"merchant": "kfc",
|
| 1896 |
+
"category": "food"
|
| 1897 |
+
},
|
| 1898 |
+
"correct_fields": {
|
| 1899 |
+
"amount": true,
|
| 1900 |
+
"type": true,
|
| 1901 |
+
"date": true,
|
| 1902 |
+
"reference": true,
|
| 1903 |
+
"merchant": true,
|
| 1904 |
+
"category": true
|
| 1905 |
+
},
|
| 1906 |
+
"overall_correct": true,
|
| 1907 |
+
"inference_time_ms": 2639.6148204803467
|
| 1908 |
+
},
|
| 1909 |
+
{
|
| 1910 |
+
"bank": "sbi",
|
| 1911 |
+
"expected": {
|
| 1912 |
+
"amount": "43122",
|
| 1913 |
+
"type": "debit",
|
| 1914 |
+
"date": "31-12-2025",
|
| 1915 |
+
"account": "5533",
|
| 1916 |
+
"reference": "566580698915",
|
| 1917 |
+
"merchant": "ola",
|
| 1918 |
+
"category": "transport"
|
| 1919 |
+
},
|
| 1920 |
+
"predicted": {
|
| 1921 |
+
"amount": "43122",
|
| 1922 |
+
"type": "debit",
|
| 1923 |
+
"date": "31-12-2025",
|
| 1924 |
+
"account": "5533",
|
| 1925 |
+
"reference": "566580698915",
|
| 1926 |
+
"merchant": "ola",
|
| 1927 |
+
"category": "transport"
|
| 1928 |
+
},
|
| 1929 |
+
"correct_fields": {
|
| 1930 |
+
"amount": true,
|
| 1931 |
+
"type": true,
|
| 1932 |
+
"date": true,
|
| 1933 |
+
"reference": true,
|
| 1934 |
+
"merchant": true,
|
| 1935 |
+
"category": true
|
| 1936 |
+
},
|
| 1937 |
+
"overall_correct": true,
|
| 1938 |
+
"inference_time_ms": 2613.1350994110107
|
| 1939 |
+
},
|
| 1940 |
+
{
|
| 1941 |
+
"bank": "icici",
|
| 1942 |
+
"expected": {
|
| 1943 |
+
"amount": "3030.61",
|
| 1944 |
+
"type": "debit",
|
| 1945 |
+
"date": "28/10/2025",
|
| 1946 |
+
"account": "7932",
|
| 1947 |
+
"reference": "680958994499",
|
| 1948 |
+
"merchant": "airtel",
|
| 1949 |
+
"category": "bills"
|
| 1950 |
+
},
|
| 1951 |
+
"predicted": {
|
| 1952 |
+
"amount": "3030.61",
|
| 1953 |
+
"type": "debit",
|
| 1954 |
+
"date": "28/10/2025",
|
| 1955 |
+
"account": "7932",
|
| 1956 |
+
"reference": "680958994499",
|
| 1957 |
+
"merchant": "airtel",
|
| 1958 |
+
"category": "transport"
|
| 1959 |
+
},
|
| 1960 |
+
"correct_fields": {
|
| 1961 |
+
"amount": true,
|
| 1962 |
+
"type": true,
|
| 1963 |
+
"date": true,
|
| 1964 |
+
"reference": true,
|
| 1965 |
+
"merchant": true,
|
| 1966 |
+
"category": false
|
| 1967 |
+
},
|
| 1968 |
+
"overall_correct": true,
|
| 1969 |
+
"inference_time_ms": 2637.838125228882
|
| 1970 |
+
},
|
| 1971 |
+
{
|
| 1972 |
+
"bank": "axis",
|
| 1973 |
+
"expected": {
|
| 1974 |
+
"amount": "549.89",
|
| 1975 |
+
"type": "credit",
|
| 1976 |
+
"date": "06-01-2026",
|
| 1977 |
+
"account": "4585",
|
| 1978 |
+
"reference": "567199758169"
|
| 1979 |
+
},
|
| 1980 |
+
"predicted": {
|
| 1981 |
+
"amount": "549.89",
|
| 1982 |
+
"type": "credit",
|
| 1983 |
+
"date": "06-01-2026",
|
| 1984 |
+
"account": "4585",
|
| 1985 |
+
"reference": "4585",
|
| 1986 |
+
"merchant": "4585",
|
| 1987 |
+
"category": "shopping"
|
| 1988 |
+
},
|
| 1989 |
+
"correct_fields": {
|
| 1990 |
+
"amount": true,
|
| 1991 |
+
"type": true,
|
| 1992 |
+
"date": true,
|
| 1993 |
+
"reference": false,
|
| 1994 |
+
"merchant": false,
|
| 1995 |
+
"category": false
|
| 1996 |
+
},
|
| 1997 |
+
"overall_correct": true,
|
| 1998 |
+
"inference_time_ms": 2488.3949756622314
|
| 1999 |
+
},
|
| 2000 |
+
{
|
| 2001 |
+
"bank": "gpay",
|
| 2002 |
+
"expected": {
|
| 2003 |
+
"amount": "1599",
|
| 2004 |
+
"type": "credit",
|
| 2005 |
+
"date": "11-11-2025",
|
| 2006 |
+
"account": "9998",
|
| 2007 |
+
"reference": "392932052116"
|
| 2008 |
+
},
|
| 2009 |
+
"predicted": {
|
| 2010 |
+
"amount": "1599",
|
| 2011 |
+
"type": "credit",
|
| 2012 |
+
"date": "11-11-2025",
|
| 2013 |
+
"account": "392932052116",
|
| 2014 |
+
"merchant": "google",
|
| 2015 |
+
"category": "shopping"
|
| 2016 |
+
},
|
| 2017 |
+
"correct_fields": {
|
| 2018 |
+
"amount": true,
|
| 2019 |
+
"type": true,
|
| 2020 |
+
"date": true,
|
| 2021 |
+
"reference": false,
|
| 2022 |
+
"merchant": false,
|
| 2023 |
+
"category": false
|
| 2024 |
+
},
|
| 2025 |
+
"overall_correct": true,
|
| 2026 |
+
"inference_time_ms": 2265.1331424713135
|
| 2027 |
+
},
|
| 2028 |
+
{
|
| 2029 |
+
"bank": "phonepe",
|
| 2030 |
+
"expected": {
|
| 2031 |
+
"amount": "1108",
|
| 2032 |
+
"type": "debit",
|
| 2033 |
+
"date": "27/12/2025",
|
| 2034 |
+
"account": "9004",
|
| 2035 |
+
"reference": "549769295925",
|
| 2036 |
+
"merchant": "dmart",
|
| 2037 |
+
"category": "grocery"
|
| 2038 |
+
},
|
| 2039 |
+
"predicted": {
|
| 2040 |
+
"amount": "1108",
|
| 2041 |
+
"type": "debit",
|
| 2042 |
+
"date": "27/12/2025",
|
| 2043 |
+
"account": "3099",
|
| 2044 |
+
"reference": "549769295925",
|
| 2045 |
+
"merchant": "dmart",
|
| 2046 |
+
"category": "grocery"
|
| 2047 |
+
},
|
| 2048 |
+
"correct_fields": {
|
| 2049 |
+
"amount": true,
|
| 2050 |
+
"type": true,
|
| 2051 |
+
"date": true,
|
| 2052 |
+
"reference": true,
|
| 2053 |
+
"merchant": true,
|
| 2054 |
+
"category": true
|
| 2055 |
+
},
|
| 2056 |
+
"overall_correct": true,
|
| 2057 |
+
"inference_time_ms": 2540.2798652648926
|
| 2058 |
+
},
|
| 2059 |
+
{
|
| 2060 |
+
"bank": "sbi",
|
| 2061 |
+
"expected": {
|
| 2062 |
+
"amount": "4044",
|
| 2063 |
+
"type": "credit",
|
| 2064 |
+
"date": "22112025",
|
| 2065 |
+
"account": "3532",
|
| 2066 |
+
"reference": "923004474410"
|
| 2067 |
+
},
|
| 2068 |
+
"predicted": {
|
| 2069 |
+
"amount": "4044",
|
| 2070 |
+
"type": "credit",
|
| 2071 |
+
"date": "22112025",
|
| 2072 |
+
"account": "3532",
|
| 2073 |
+
"reference": "923004474410"
|
| 2074 |
+
},
|
| 2075 |
+
"correct_fields": {
|
| 2076 |
+
"amount": true,
|
| 2077 |
+
"type": true,
|
| 2078 |
+
"date": true,
|
| 2079 |
+
"reference": true,
|
| 2080 |
+
"merchant": true,
|
| 2081 |
+
"category": true
|
| 2082 |
+
},
|
| 2083 |
+
"overall_correct": true,
|
| 2084 |
+
"inference_time_ms": 2006.8140029907227
|
| 2085 |
+
},
|
| 2086 |
+
{
|
| 2087 |
+
"bank": "icici",
|
| 2088 |
+
"expected": {
|
| 2089 |
+
"amount": "1820",
|
| 2090 |
+
"type": "credit",
|
| 2091 |
+
"date": "30/12/2025",
|
| 2092 |
+
"account": "7396",
|
| 2093 |
+
"reference": "101627677155"
|
| 2094 |
+
},
|
| 2095 |
+
"predicted": {
|
| 2096 |
+
"amount": "1820",
|
| 2097 |
+
"type": "credit",
|
| 2098 |
+
"date": "30/12/2025",
|
| 2099 |
+
"account": "7396",
|
| 2100 |
+
"reference": "101627677155"
|
| 2101 |
+
},
|
| 2102 |
+
"correct_fields": {
|
| 2103 |
+
"amount": true,
|
| 2104 |
+
"type": true,
|
| 2105 |
+
"date": true,
|
| 2106 |
+
"reference": true,
|
| 2107 |
+
"merchant": true,
|
| 2108 |
+
"category": true
|
| 2109 |
+
},
|
| 2110 |
+
"overall_correct": true,
|
| 2111 |
+
"inference_time_ms": 2096.690893173218
|
| 2112 |
+
},
|
| 2113 |
+
{
|
| 2114 |
+
"bank": "sbi",
|
| 2115 |
+
"expected": {
|
| 2116 |
+
"amount": "1722",
|
| 2117 |
+
"type": "credit",
|
| 2118 |
+
"date": "23-11-25",
|
| 2119 |
+
"account": "4728",
|
| 2120 |
+
"reference": "975402538007"
|
| 2121 |
+
},
|
| 2122 |
+
"predicted": {
|
| 2123 |
+
"amount": "1722",
|
| 2124 |
+
"type": "credit",
|
| 2125 |
+
"date": "23-11-25",
|
| 2126 |
+
"account": "4728",
|
| 2127 |
+
"reference": "975402538007"
|
| 2128 |
+
},
|
| 2129 |
+
"correct_fields": {
|
| 2130 |
+
"amount": true,
|
| 2131 |
+
"type": true,
|
| 2132 |
+
"date": true,
|
| 2133 |
+
"reference": true,
|
| 2134 |
+
"merchant": true,
|
| 2135 |
+
"category": true
|
| 2136 |
+
},
|
| 2137 |
+
"overall_correct": true,
|
| 2138 |
+
"inference_time_ms": 2052.6599884033203
|
| 2139 |
+
},
|
| 2140 |
+
{
|
| 2141 |
+
"bank": "phonepe",
|
| 2142 |
+
"expected": {
|
| 2143 |
+
"amount": "1147",
|
| 2144 |
+
"type": "debit",
|
| 2145 |
+
"date": "10/10/2025",
|
| 2146 |
+
"account": "8933",
|
| 2147 |
+
"reference": "337045863496",
|
| 2148 |
+
"merchant": "myntra",
|
| 2149 |
+
"category": "shopping"
|
| 2150 |
+
},
|
| 2151 |
+
"predicted": {
|
| 2152 |
+
"amount": "1147",
|
| 2153 |
+
"type": "debit",
|
| 2154 |
+
"date": "10/10/2025",
|
| 2155 |
+
"account": "8933",
|
| 2156 |
+
"reference": "337045863496",
|
| 2157 |
+
"merchant": "myntra",
|
| 2158 |
+
"category": "shopping"
|
| 2159 |
+
},
|
| 2160 |
+
"correct_fields": {
|
| 2161 |
+
"amount": true,
|
| 2162 |
+
"type": true,
|
| 2163 |
+
"date": true,
|
| 2164 |
+
"reference": true,
|
| 2165 |
+
"merchant": true,
|
| 2166 |
+
"category": true
|
| 2167 |
+
},
|
| 2168 |
+
"overall_correct": true,
|
| 2169 |
+
"inference_time_ms": 2572.690963745117
|
| 2170 |
+
},
|
| 2171 |
+
{
|
| 2172 |
+
"bank": "phonepe",
|
| 2173 |
+
"expected": {
|
| 2174 |
+
"amount": "155.62",
|
| 2175 |
+
"type": "credit",
|
| 2176 |
+
"date": "23-12-2025",
|
| 2177 |
+
"account": "2213",
|
| 2178 |
+
"reference": "638591937347"
|
| 2179 |
+
},
|
| 2180 |
+
"predicted": {
|
| 2181 |
+
"amount": "155.62",
|
| 2182 |
+
"type": "credit",
|
| 2183 |
+
"date": "23-12-2025",
|
| 2184 |
+
"account": "638591937347",
|
| 2185 |
+
"reference": "638591937347"
|
| 2186 |
+
},
|
| 2187 |
+
"correct_fields": {
|
| 2188 |
+
"amount": true,
|
| 2189 |
+
"type": true,
|
| 2190 |
+
"date": true,
|
| 2191 |
+
"reference": true,
|
| 2192 |
+
"merchant": true,
|
| 2193 |
+
"category": true
|
| 2194 |
+
},
|
| 2195 |
+
"overall_correct": true,
|
| 2196 |
+
"inference_time_ms": 2300.1911640167236
|
| 2197 |
+
},
|
| 2198 |
+
{
|
| 2199 |
+
"bank": "paytm",
|
| 2200 |
+
"expected": {
|
| 2201 |
+
"amount": "9269",
|
| 2202 |
+
"type": "debit",
|
| 2203 |
+
"date": "29-10-2025",
|
| 2204 |
+
"account": "4846",
|
| 2205 |
+
"reference": "175666412237",
|
| 2206 |
+
"merchant": "metro",
|
| 2207 |
+
"category": "transport"
|
| 2208 |
+
},
|
| 2209 |
+
"predicted": {
|
| 2210 |
+
"amount": "9269",
|
| 2211 |
+
"type": "debit",
|
| 2212 |
+
"date": "29-10-2025",
|
| 2213 |
+
"account": "9419",
|
| 2214 |
+
"reference": "175666412237",
|
| 2215 |
+
"merchant": "metro",
|
| 2216 |
+
"category": "transport"
|
| 2217 |
+
},
|
| 2218 |
+
"correct_fields": {
|
| 2219 |
+
"amount": true,
|
| 2220 |
+
"type": true,
|
| 2221 |
+
"date": true,
|
| 2222 |
+
"reference": true,
|
| 2223 |
+
"merchant": true,
|
| 2224 |
+
"category": true
|
| 2225 |
+
},
|
| 2226 |
+
"overall_correct": true,
|
| 2227 |
+
"inference_time_ms": 2494.603157043457
|
| 2228 |
+
},
|
| 2229 |
+
{
|
| 2230 |
+
"bank": "phonepe",
|
| 2231 |
+
"expected": {
|
| 2232 |
+
"amount": "956.76",
|
| 2233 |
+
"type": "credit",
|
| 2234 |
+
"date": "13-11-25",
|
| 2235 |
+
"account": "1986",
|
| 2236 |
+
"reference": "781047077731"
|
| 2237 |
+
},
|
| 2238 |
+
"predicted": {
|
| 2239 |
+
"amount": "956.76",
|
| 2240 |
+
"type": "credit",
|
| 2241 |
+
"date": "13-11-25",
|
| 2242 |
+
"account": "9408",
|
| 2243 |
+
"reference": "600100000000"
|
| 2244 |
+
},
|
| 2245 |
+
"correct_fields": {
|
| 2246 |
+
"amount": true,
|
| 2247 |
+
"type": true,
|
| 2248 |
+
"date": true,
|
| 2249 |
+
"reference": false,
|
| 2250 |
+
"merchant": true,
|
| 2251 |
+
"category": true
|
| 2252 |
+
},
|
| 2253 |
+
"overall_correct": true,
|
| 2254 |
+
"inference_time_ms": 2013.024091720581
|
| 2255 |
+
},
|
| 2256 |
+
{
|
| 2257 |
+
"bank": "gpay",
|
| 2258 |
+
"expected": {
|
| 2259 |
+
"amount": "510",
|
| 2260 |
+
"type": "credit",
|
| 2261 |
+
"date": "23 Dec 2025",
|
| 2262 |
+
"account": "3522",
|
| 2263 |
+
"reference": "232916613814"
|
| 2264 |
+
},
|
| 2265 |
+
"predicted": {
|
| 2266 |
+
"amount": "510",
|
| 2267 |
+
"type": "credit",
|
| 2268 |
+
"date": "23 Dec 2025",
|
| 2269 |
+
"account": "3998",
|
| 2270 |
+
"reference": "232916613814",
|
| 2271 |
+
"merchant": "mutual fund",
|
| 2272 |
+
"category": "investment"
|
| 2273 |
+
},
|
| 2274 |
+
"correct_fields": {
|
| 2275 |
+
"amount": true,
|
| 2276 |
+
"type": true,
|
| 2277 |
+
"date": true,
|
| 2278 |
+
"reference": true,
|
| 2279 |
+
"merchant": false,
|
| 2280 |
+
"category": false
|
| 2281 |
+
},
|
| 2282 |
+
"overall_correct": true,
|
| 2283 |
+
"inference_time_ms": 2497.7450370788574
|
| 2284 |
+
},
|
| 2285 |
+
{
|
| 2286 |
+
"bank": "sbi",
|
| 2287 |
+
"expected": {
|
| 2288 |
+
"amount": "7867",
|
| 2289 |
+
"type": "debit",
|
| 2290 |
+
"date": "04 Dec 2025",
|
| 2291 |
+
"account": "5915",
|
| 2292 |
+
"reference": "835001525541",
|
| 2293 |
+
"merchant": "dmart",
|
| 2294 |
+
"category": "grocery"
|
| 2295 |
+
},
|
| 2296 |
+
"predicted": {
|
| 2297 |
+
"amount": "7867",
|
| 2298 |
+
"type": "debit",
|
| 2299 |
+
"date": "04 Dec 2025",
|
| 2300 |
+
"account": "5915",
|
| 2301 |
+
"reference": "5915",
|
| 2302 |
+
"merchant": "dmart",
|
| 2303 |
+
"category": "grocery"
|
| 2304 |
+
},
|
| 2305 |
+
"correct_fields": {
|
| 2306 |
+
"amount": true,
|
| 2307 |
+
"type": true,
|
| 2308 |
+
"date": true,
|
| 2309 |
+
"reference": false,
|
| 2310 |
+
"merchant": true,
|
| 2311 |
+
"category": true
|
| 2312 |
+
},
|
| 2313 |
+
"overall_correct": true,
|
| 2314 |
+
"inference_time_ms": 2309.216022491455
|
| 2315 |
+
},
|
| 2316 |
+
{
|
| 2317 |
+
"bank": "icici",
|
| 2318 |
+
"expected": {
|
| 2319 |
+
"amount": "1546",
|
| 2320 |
+
"type": "credit",
|
| 2321 |
+
"date": "27 Oct 2025",
|
| 2322 |
+
"account": "5861",
|
| 2323 |
+
"reference": "306823277527"
|
| 2324 |
+
},
|
| 2325 |
+
"predicted": {
|
| 2326 |
+
"amount": "1546",
|
| 2327 |
+
"type": "credit",
|
| 2328 |
+
"date": "27 Oct 2025",
|
| 2329 |
+
"account": "5861",
|
| 2330 |
+
"reference": "306823277527"
|
| 2331 |
+
},
|
| 2332 |
+
"correct_fields": {
|
| 2333 |
+
"amount": true,
|
| 2334 |
+
"type": true,
|
| 2335 |
+
"date": true,
|
| 2336 |
+
"reference": true,
|
| 2337 |
+
"merchant": true,
|
| 2338 |
+
"category": true
|
| 2339 |
+
},
|
| 2340 |
+
"overall_correct": true,
|
| 2341 |
+
"inference_time_ms": 2044.2569255828857
|
| 2342 |
+
},
|
| 2343 |
+
{
|
| 2344 |
+
"bank": "kotak",
|
| 2345 |
+
"expected": {
|
| 2346 |
+
"amount": "7325.84",
|
| 2347 |
+
"type": "debit",
|
| 2348 |
+
"date": "01-01-2026",
|
| 2349 |
+
"account": "4266",
|
| 2350 |
+
"reference": "374661490981",
|
| 2351 |
+
"merchant": "zepto",
|
| 2352 |
+
"category": "grocery"
|
| 2353 |
+
},
|
| 2354 |
+
"predicted": {
|
| 2355 |
+
"amount": "7325.84",
|
| 2356 |
+
"type": "debit",
|
| 2357 |
+
"date": "01-01-2026",
|
| 2358 |
+
"account": "4266",
|
| 2359 |
+
"reference": "7325.84",
|
| 2360 |
+
"merchant": "zepto",
|
| 2361 |
+
"category": "grocery"
|
| 2362 |
+
},
|
| 2363 |
+
"correct_fields": {
|
| 2364 |
+
"amount": true,
|
| 2365 |
+
"type": true,
|
| 2366 |
+
"date": true,
|
| 2367 |
+
"reference": false,
|
| 2368 |
+
"merchant": true,
|
| 2369 |
+
"category": true
|
| 2370 |
+
},
|
| 2371 |
+
"overall_correct": true,
|
| 2372 |
+
"inference_time_ms": 2510.90407371521
|
| 2373 |
+
},
|
| 2374 |
+
{
|
| 2375 |
+
"bank": "axis",
|
| 2376 |
+
"expected": {
|
| 2377 |
+
"amount": "1895",
|
| 2378 |
+
"type": "debit",
|
| 2379 |
+
"date": "16-12-2025",
|
| 2380 |
+
"account": "6491",
|
| 2381 |
+
"reference": "663859569104",
|
| 2382 |
+
"merchant": "nykaa",
|
| 2383 |
+
"category": "shopping"
|
| 2384 |
+
},
|
| 2385 |
+
"predicted": {
|
| 2386 |
+
"amount": "1895",
|
| 2387 |
+
"type": "debit",
|
| 2388 |
+
"date": "16-12-2025",
|
| 2389 |
+
"account": "6491",
|
| 2390 |
+
"reference": "663859569104",
|
| 2391 |
+
"merchant": "nykaa",
|
| 2392 |
+
"category": "shopping"
|
| 2393 |
+
},
|
| 2394 |
+
"correct_fields": {
|
| 2395 |
+
"amount": true,
|
| 2396 |
+
"type": true,
|
| 2397 |
+
"date": true,
|
| 2398 |
+
"reference": true,
|
| 2399 |
+
"merchant": true,
|
| 2400 |
+
"category": true
|
| 2401 |
+
},
|
| 2402 |
+
"overall_correct": true,
|
| 2403 |
+
"inference_time_ms": 2583.976984024048
|
| 2404 |
+
},
|
| 2405 |
+
{
|
| 2406 |
+
"bank": "axis",
|
| 2407 |
+
"expected": {
|
| 2408 |
+
"amount": "5155",
|
| 2409 |
+
"type": "debit",
|
| 2410 |
+
"date": "13-12-25",
|
| 2411 |
+
"account": "8144",
|
| 2412 |
+
"reference": "877579719274",
|
| 2413 |
+
"merchant": "metro",
|
| 2414 |
+
"category": "transport"
|
| 2415 |
+
},
|
| 2416 |
+
"predicted": {
|
| 2417 |
+
"amount": "5155",
|
| 2418 |
+
"type": "debit",
|
| 2419 |
+
"date": "13-12-25",
|
| 2420 |
+
"account": "8144",
|
| 2421 |
+
"reference": "10753.00",
|
| 2422 |
+
"merchant": "metro",
|
| 2423 |
+
"category": "transport"
|
| 2424 |
+
},
|
| 2425 |
+
"correct_fields": {
|
| 2426 |
+
"amount": true,
|
| 2427 |
+
"type": true,
|
| 2428 |
+
"date": true,
|
| 2429 |
+
"reference": false,
|
| 2430 |
+
"merchant": true,
|
| 2431 |
+
"category": true
|
| 2432 |
+
},
|
| 2433 |
+
"overall_correct": true,
|
| 2434 |
+
"inference_time_ms": 2334.7651958465576
|
| 2435 |
+
},
|
| 2436 |
+
{
|
| 2437 |
+
"bank": "hdfc",
|
| 2438 |
+
"expected": {
|
| 2439 |
+
"amount": "4404",
|
| 2440 |
+
"type": "credit",
|
| 2441 |
+
"date": "09-11-2025",
|
| 2442 |
+
"account": "5315",
|
| 2443 |
+
"reference": "894370590668"
|
| 2444 |
+
},
|
| 2445 |
+
"predicted": {
|
| 2446 |
+
"amount": "4404",
|
| 2447 |
+
"type": "credit",
|
| 2448 |
+
"date": "09-11-2025",
|
| 2449 |
+
"account": "5315",
|
| 2450 |
+
"reference": "894370590668"
|
| 2451 |
+
},
|
| 2452 |
+
"correct_fields": {
|
| 2453 |
+
"amount": true,
|
| 2454 |
+
"type": true,
|
| 2455 |
+
"date": true,
|
| 2456 |
+
"reference": true,
|
| 2457 |
+
"merchant": true,
|
| 2458 |
+
"category": true
|
| 2459 |
+
},
|
| 2460 |
+
"overall_correct": true,
|
| 2461 |
+
"inference_time_ms": 2088.6001586914062
|
| 2462 |
+
},
|
| 2463 |
+
{
|
| 2464 |
+
"bank": "icici",
|
| 2465 |
+
"expected": {
|
| 2466 |
+
"amount": "521",
|
| 2467 |
+
"type": "debit",
|
| 2468 |
+
"date": "06-01-2026",
|
| 2469 |
+
"account": "1964",
|
| 2470 |
+
"reference": "794529888366",
|
| 2471 |
+
"merchant": "uber",
|
| 2472 |
+
"category": "transport"
|
| 2473 |
+
},
|
| 2474 |
+
"predicted": {
|
| 2475 |
+
"amount": "521",
|
| 2476 |
+
"type": "debit",
|
| 2477 |
+
"date": "06-01-2026",
|
| 2478 |
+
"account": "1964",
|
| 2479 |
+
"reference": "794529888366",
|
| 2480 |
+
"merchant": "bigbazaar",
|
| 2481 |
+
"category": "grocery"
|
| 2482 |
+
},
|
| 2483 |
+
"correct_fields": {
|
| 2484 |
+
"amount": true,
|
| 2485 |
+
"type": true,
|
| 2486 |
+
"date": true,
|
| 2487 |
+
"reference": true,
|
| 2488 |
+
"merchant": false,
|
| 2489 |
+
"category": false
|
| 2490 |
+
},
|
| 2491 |
+
"overall_correct": true,
|
| 2492 |
+
"inference_time_ms": 2559.617042541504
|
| 2493 |
+
},
|
| 2494 |
+
{
|
| 2495 |
+
"bank": "axis",
|
| 2496 |
+
"expected": {
|
| 2497 |
+
"amount": "7134.57",
|
| 2498 |
+
"type": "credit",
|
| 2499 |
+
"date": "28-12-25",
|
| 2500 |
+
"account": "6502",
|
| 2501 |
+
"reference": "397359885684"
|
| 2502 |
+
},
|
| 2503 |
+
"predicted": {
|
| 2504 |
+
"amount": "7134.57",
|
| 2505 |
+
"type": "credit",
|
| 2506 |
+
"date": "28-12-25",
|
| 2507 |
+
"account": "6502",
|
| 2508 |
+
"reference": "90943.00",
|
| 2509 |
+
"merchant": "mcdonalds",
|
| 2510 |
+
"category": "food"
|
| 2511 |
+
},
|
| 2512 |
+
"correct_fields": {
|
| 2513 |
+
"amount": true,
|
| 2514 |
+
"type": true,
|
| 2515 |
+
"date": true,
|
| 2516 |
+
"reference": false,
|
| 2517 |
+
"merchant": false,
|
| 2518 |
+
"category": false
|
| 2519 |
+
},
|
| 2520 |
+
"overall_correct": true,
|
| 2521 |
+
"inference_time_ms": 2520.8258628845215
|
| 2522 |
+
},
|
| 2523 |
+
{
|
| 2524 |
+
"bank": "gpay",
|
| 2525 |
+
"expected": {
|
| 2526 |
+
"amount": "6045",
|
| 2527 |
+
"type": "debit",
|
| 2528 |
+
"date": "22-10-2025",
|
| 2529 |
+
"account": "6280",
|
| 2530 |
+
"reference": "576266444796",
|
| 2531 |
+
"merchant": "metro",
|
| 2532 |
+
"category": "transport"
|
| 2533 |
+
},
|
| 2534 |
+
"predicted": {
|
| 2535 |
+
"amount": "6045",
|
| 2536 |
+
"type": "debit",
|
| 2537 |
+
"date": "22-10-2025",
|
| 2538 |
+
"account": "6061",
|
| 2539 |
+
"reference": "576266444796",
|
| 2540 |
+
"merchant": "metro",
|
| 2541 |
+
"category": "transport"
|
| 2542 |
+
},
|
| 2543 |
+
"correct_fields": {
|
| 2544 |
+
"amount": true,
|
| 2545 |
+
"type": true,
|
| 2546 |
+
"date": true,
|
| 2547 |
+
"reference": true,
|
| 2548 |
+
"merchant": true,
|
| 2549 |
+
"category": true
|
| 2550 |
+
},
|
| 2551 |
+
"overall_correct": true,
|
| 2552 |
+
"inference_time_ms": 2467.1380519866943
|
| 2553 |
+
},
|
| 2554 |
+
{
|
| 2555 |
+
"bank": "hdfc",
|
| 2556 |
+
"expected": {
|
| 2557 |
+
"amount": "2653",
|
| 2558 |
+
"type": "debit",
|
| 2559 |
+
"date": "25 Dec 2025",
|
| 2560 |
+
"account": "6977",
|
| 2561 |
+
"reference": "599410093881",
|
| 2562 |
+
"merchant": "swiggy",
|
| 2563 |
+
"category": "food"
|
| 2564 |
+
},
|
| 2565 |
+
"predicted": {
|
| 2566 |
+
"amount": "2653",
|
| 2567 |
+
"type": "debit",
|
| 2568 |
+
"date": "25 Dec 2025",
|
| 2569 |
+
"account": "6977",
|
| 2570 |
+
"reference": "599410093881",
|
| 2571 |
+
"merchant": "swiggy",
|
| 2572 |
+
"category": "food"
|
| 2573 |
+
},
|
| 2574 |
+
"correct_fields": {
|
| 2575 |
+
"amount": true,
|
| 2576 |
+
"type": true,
|
| 2577 |
+
"date": true,
|
| 2578 |
+
"reference": true,
|
| 2579 |
+
"merchant": true,
|
| 2580 |
+
"category": true
|
| 2581 |
+
},
|
| 2582 |
+
"overall_correct": true,
|
| 2583 |
+
"inference_time_ms": 2599.6909141540527
|
| 2584 |
+
},
|
| 2585 |
+
{
|
| 2586 |
+
"bank": "kotak",
|
| 2587 |
+
"expected": {
|
| 2588 |
+
"amount": "1632",
|
| 2589 |
+
"type": "credit",
|
| 2590 |
+
"date": "11102025",
|
| 2591 |
+
"account": "1672",
|
| 2592 |
+
"reference": "232308735151"
|
| 2593 |
+
},
|
| 2594 |
+
"predicted": {
|
| 2595 |
+
"amount": "1632",
|
| 2596 |
+
"type": "credit",
|
| 2597 |
+
"date": "11102025",
|
| 2598 |
+
"account": "1672",
|
| 2599 |
+
"reference": "600000000000",
|
| 2600 |
+
"merchant": "kotak",
|
| 2601 |
+
"category": "transfer"
|
| 2602 |
+
},
|
| 2603 |
+
"correct_fields": {
|
| 2604 |
+
"amount": true,
|
| 2605 |
+
"type": true,
|
| 2606 |
+
"date": true,
|
| 2607 |
+
"reference": false,
|
| 2608 |
+
"merchant": false,
|
| 2609 |
+
"category": false
|
| 2610 |
+
},
|
| 2611 |
+
"overall_correct": true,
|
| 2612 |
+
"inference_time_ms": 2505.812883377075
|
| 2613 |
+
},
|
| 2614 |
+
{
|
| 2615 |
+
"bank": "axis",
|
| 2616 |
+
"expected": {
|
| 2617 |
+
"amount": "1477.17",
|
| 2618 |
+
"type": "debit",
|
| 2619 |
+
"date": "13 Dec 2025",
|
| 2620 |
+
"account": "3851",
|
| 2621 |
+
"reference": "844657758783",
|
| 2622 |
+
"merchant": "metro",
|
| 2623 |
+
"category": "transport"
|
| 2624 |
+
},
|
| 2625 |
+
"predicted": {
|
| 2626 |
+
"amount": "1477.17",
|
| 2627 |
+
"type": "debit",
|
| 2628 |
+
"date": "13 Dec 2025",
|
| 2629 |
+
"account": "3851",
|
| 2630 |
+
"reference": "147717888098",
|
| 2631 |
+
"merchant": "metro",
|
| 2632 |
+
"category": "transport"
|
| 2633 |
+
},
|
| 2634 |
+
"correct_fields": {
|
| 2635 |
+
"amount": true,
|
| 2636 |
+
"type": true,
|
| 2637 |
+
"date": true,
|
| 2638 |
+
"reference": false,
|
| 2639 |
+
"merchant": true,
|
| 2640 |
+
"category": true
|
| 2641 |
+
},
|
| 2642 |
+
"overall_correct": true,
|
| 2643 |
+
"inference_time_ms": 2507.797956466675
|
| 2644 |
+
},
|
| 2645 |
+
{
|
| 2646 |
+
"bank": "hdfc",
|
| 2647 |
+
"expected": {
|
| 2648 |
+
"amount": "7599",
|
| 2649 |
+
"type": "debit",
|
| 2650 |
+
"date": "21/10/2025",
|
| 2651 |
+
"account": "5010",
|
| 2652 |
+
"reference": "901158030343",
|
| 2653 |
+
"merchant": "ola",
|
| 2654 |
+
"category": "transport"
|
| 2655 |
+
},
|
| 2656 |
+
"predicted": {
|
| 2657 |
+
"amount": "7599",
|
| 2658 |
+
"type": "debit",
|
| 2659 |
+
"date": "21/10/2025",
|
| 2660 |
+
"account": "5010",
|
| 2661 |
+
"reference": "5010",
|
| 2662 |
+
"merchant": "ola",
|
| 2663 |
+
"category": "transport"
|
| 2664 |
+
},
|
| 2665 |
+
"correct_fields": {
|
| 2666 |
+
"amount": true,
|
| 2667 |
+
"type": true,
|
| 2668 |
+
"date": true,
|
| 2669 |
+
"reference": false,
|
| 2670 |
+
"merchant": true,
|
| 2671 |
+
"category": true
|
| 2672 |
+
},
|
| 2673 |
+
"overall_correct": true,
|
| 2674 |
+
"inference_time_ms": 2288.4929180145264
|
| 2675 |
+
},
|
| 2676 |
+
{
|
| 2677 |
+
"bank": "gpay",
|
| 2678 |
+
"expected": {
|
| 2679 |
+
"amount": "609",
|
| 2680 |
+
"type": "credit",
|
| 2681 |
+
"date": "06 Nov 2025",
|
| 2682 |
+
"account": "3369",
|
| 2683 |
+
"reference": "599263022595"
|
| 2684 |
+
},
|
| 2685 |
+
"predicted": {
|
| 2686 |
+
"amount": "609",
|
| 2687 |
+
"type": "credit",
|
| 2688 |
+
"date": "20251120",
|
| 2689 |
+
"account": "599263022595",
|
| 2690 |
+
"reference": "599263022595",
|
| 2691 |
+
"merchant": "google pay",
|
| 2692 |
+
"category": "transfer"
|
| 2693 |
+
},
|
| 2694 |
+
"correct_fields": {
|
| 2695 |
+
"amount": true,
|
| 2696 |
+
"type": true,
|
| 2697 |
+
"date": false,
|
| 2698 |
+
"reference": true,
|
| 2699 |
+
"merchant": false,
|
| 2700 |
+
"category": false
|
| 2701 |
+
},
|
| 2702 |
+
"overall_correct": true,
|
| 2703 |
+
"inference_time_ms": 2949.0649700164795
|
| 2704 |
+
},
|
| 2705 |
+
{
|
| 2706 |
+
"bank": "paytm",
|
| 2707 |
+
"expected": {
|
| 2708 |
+
"amount": "7596.75",
|
| 2709 |
+
"type": "credit",
|
| 2710 |
+
"date": "19/12/2025",
|
| 2711 |
+
"account": "5161",
|
| 2712 |
+
"reference": "802060293051"
|
| 2713 |
+
},
|
| 2714 |
+
"predicted": {
|
| 2715 |
+
"amount": "7596.75",
|
| 2716 |
+
"type": "debit",
|
| 2717 |
+
"date": "19/12/2025",
|
| 2718 |
+
"account": "6988",
|
| 2719 |
+
"reference": "802060293051",
|
| 2720 |
+
"merchant": "paytm",
|
| 2721 |
+
"category": "shopping"
|
| 2722 |
+
},
|
| 2723 |
+
"correct_fields": {
|
| 2724 |
+
"amount": true,
|
| 2725 |
+
"type": false,
|
| 2726 |
+
"date": true,
|
| 2727 |
+
"reference": true,
|
| 2728 |
+
"merchant": false,
|
| 2729 |
+
"category": false
|
| 2730 |
+
},
|
| 2731 |
+
"overall_correct": false,
|
| 2732 |
+
"inference_time_ms": 2626.9099712371826
|
| 2733 |
+
},
|
| 2734 |
+
{
|
| 2735 |
+
"bank": "icici",
|
| 2736 |
+
"expected": {
|
| 2737 |
+
"amount": "29558",
|
| 2738 |
+
"type": "debit",
|
| 2739 |
+
"date": "03112025",
|
| 2740 |
+
"account": "7126",
|
| 2741 |
+
"reference": "268358041225",
|
| 2742 |
+
"merchant": "nykaa",
|
| 2743 |
+
"category": "shopping"
|
| 2744 |
+
},
|
| 2745 |
+
"predicted": {
|
| 2746 |
+
"amount": "29558",
|
| 2747 |
+
"type": "debit",
|
| 2748 |
+
"date": "03112025",
|
| 2749 |
+
"account": "7126",
|
| 2750 |
+
"reference": "268358041225",
|
| 2751 |
+
"merchant": "nykaa",
|
| 2752 |
+
"category": "grocery"
|
| 2753 |
+
},
|
| 2754 |
+
"correct_fields": {
|
| 2755 |
+
"amount": true,
|
| 2756 |
+
"type": true,
|
| 2757 |
+
"date": true,
|
| 2758 |
+
"reference": true,
|
| 2759 |
+
"merchant": true,
|
| 2760 |
+
"category": false
|
| 2761 |
+
},
|
| 2762 |
+
"overall_correct": true,
|
| 2763 |
+
"inference_time_ms": 2559.378147125244
|
| 2764 |
+
},
|
| 2765 |
+
{
|
| 2766 |
+
"bank": "gpay",
|
| 2767 |
+
"expected": {
|
| 2768 |
+
"amount": "2236",
|
| 2769 |
+
"type": "credit",
|
| 2770 |
+
"date": "21/10/2025",
|
| 2771 |
+
"account": "6091",
|
| 2772 |
+
"reference": "274847185866"
|
| 2773 |
+
},
|
| 2774 |
+
"predicted": {
|
| 2775 |
+
"amount": "2236",
|
| 2776 |
+
"type": "credit",
|
| 2777 |
+
"date": "21/10/2025",
|
| 2778 |
+
"account": "6091",
|
| 2779 |
+
"reference": "2025102106091",
|
| 2780 |
+
"merchant": "gpay",
|
| 2781 |
+
"category": "transfer"
|
| 2782 |
+
},
|
| 2783 |
+
"correct_fields": {
|
| 2784 |
+
"amount": true,
|
| 2785 |
+
"type": true,
|
| 2786 |
+
"date": true,
|
| 2787 |
+
"reference": false,
|
| 2788 |
+
"merchant": false,
|
| 2789 |
+
"category": false
|
| 2790 |
+
},
|
| 2791 |
+
"overall_correct": true,
|
| 2792 |
+
"inference_time_ms": 2489.237070083618
|
| 2793 |
+
},
|
| 2794 |
+
{
|
| 2795 |
+
"bank": "icici",
|
| 2796 |
+
"expected": {
|
| 2797 |
+
"amount": "537.63",
|
| 2798 |
+
"type": "debit",
|
| 2799 |
+
"date": "10122025",
|
| 2800 |
+
"account": "8744",
|
| 2801 |
+
"reference": "895137224815",
|
| 2802 |
+
"merchant": "dominos",
|
| 2803 |
+
"category": "food"
|
| 2804 |
+
},
|
| 2805 |
+
"predicted": {
|
| 2806 |
+
"amount": "537.63",
|
| 2807 |
+
"type": "debit",
|
| 2808 |
+
"date": "10122025",
|
| 2809 |
+
"account": "8744",
|
| 2810 |
+
"reference": "895137224815",
|
| 2811 |
+
"merchant": "bigbazaar",
|
| 2812 |
+
"category": "shopping"
|
| 2813 |
+
},
|
| 2814 |
+
"correct_fields": {
|
| 2815 |
+
"amount": true,
|
| 2816 |
+
"type": true,
|
| 2817 |
+
"date": true,
|
| 2818 |
+
"reference": true,
|
| 2819 |
+
"merchant": false,
|
| 2820 |
+
"category": false
|
| 2821 |
+
},
|
| 2822 |
+
"overall_correct": true,
|
| 2823 |
+
"inference_time_ms": 2572.903871536255
|
| 2824 |
+
},
|
| 2825 |
+
{
|
| 2826 |
+
"bank": "paytm",
|
| 2827 |
+
"expected": {
|
| 2828 |
+
"amount": "14903",
|
| 2829 |
+
"type": "debit",
|
| 2830 |
+
"date": "04-12-25",
|
| 2831 |
+
"account": "7512",
|
| 2832 |
+
"reference": "862886090135",
|
| 2833 |
+
"merchant": "ajio",
|
| 2834 |
+
"category": "shopping"
|
| 2835 |
+
},
|
| 2836 |
+
"predicted": {
|
| 2837 |
+
"amount": "14903",
|
| 2838 |
+
"type": "debit",
|
| 2839 |
+
"date": "04-12-25",
|
| 2840 |
+
"account": "1234",
|
| 2841 |
+
"reference": "862886090135",
|
| 2842 |
+
"merchant": "ajio",
|
| 2843 |
+
"category": "shopping"
|
| 2844 |
+
},
|
| 2845 |
+
"correct_fields": {
|
| 2846 |
+
"amount": true,
|
| 2847 |
+
"type": true,
|
| 2848 |
+
"date": true,
|
| 2849 |
+
"reference": true,
|
| 2850 |
+
"merchant": true,
|
| 2851 |
+
"category": true
|
| 2852 |
+
},
|
| 2853 |
+
"overall_correct": true,
|
| 2854 |
+
"inference_time_ms": 2520.9591388702393
|
| 2855 |
+
},
|
| 2856 |
+
{
|
| 2857 |
+
"bank": "paytm",
|
| 2858 |
+
"expected": {
|
| 2859 |
+
"amount": "1180",
|
| 2860 |
+
"type": "debit",
|
| 2861 |
+
"date": "19 Nov 2025",
|
| 2862 |
+
"account": "4090",
|
| 2863 |
+
"reference": "456193888210",
|
| 2864 |
+
"merchant": "water",
|
| 2865 |
+
"category": "bills"
|
| 2866 |
+
},
|
| 2867 |
+
"predicted": {
|
| 2868 |
+
"amount": "1180",
|
| 2869 |
+
"type": "debit",
|
| 2870 |
+
"date": "19 Nov 2025",
|
| 2871 |
+
"account": "6988",
|
| 2872 |
+
"reference": "456193888210",
|
| 2873 |
+
"merchant": "water",
|
| 2874 |
+
"category": "bills"
|
| 2875 |
+
},
|
| 2876 |
+
"correct_fields": {
|
| 2877 |
+
"amount": true,
|
| 2878 |
+
"type": true,
|
| 2879 |
+
"date": true,
|
| 2880 |
+
"reference": true,
|
| 2881 |
+
"merchant": true,
|
| 2882 |
+
"category": true
|
| 2883 |
+
},
|
| 2884 |
+
"overall_correct": true,
|
| 2885 |
+
"inference_time_ms": 2461.703300476074
|
| 2886 |
+
},
|
| 2887 |
+
{
|
| 2888 |
+
"bank": "paytm",
|
| 2889 |
+
"expected": {
|
| 2890 |
+
"amount": "4356",
|
| 2891 |
+
"type": "credit",
|
| 2892 |
+
"date": "17-12-2025",
|
| 2893 |
+
"account": "7951",
|
| 2894 |
+
"reference": "428941115748"
|
| 2895 |
+
},
|
| 2896 |
+
"predicted": {
|
| 2897 |
+
"amount": "4356",
|
| 2898 |
+
"type": "credit",
|
| 2899 |
+
"date": "06-12-2025",
|
| 2900 |
+
"account": "7951",
|
| 2901 |
+
"reference": "428941115748",
|
| 2902 |
+
"merchant": "4017",
|
| 2903 |
+
"category": "shopping"
|
| 2904 |
+
},
|
| 2905 |
+
"correct_fields": {
|
| 2906 |
+
"amount": true,
|
| 2907 |
+
"type": true,
|
| 2908 |
+
"date": false,
|
| 2909 |
+
"reference": true,
|
| 2910 |
+
"merchant": false,
|
| 2911 |
+
"category": false
|
| 2912 |
+
},
|
| 2913 |
+
"overall_correct": true,
|
| 2914 |
+
"inference_time_ms": 2583.8332176208496
|
| 2915 |
+
}
|
| 2916 |
+
]
|
| 2917 |
+
}
|
docs/banking_email_formats.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Indian Banking Email Samples for ML Training
|
| 2 |
+
|
| 3 |
+
A comprehensive collection of sample banking emails covering all transaction types across major Indian banks. Designed for training finance entity extraction models.
|
| 4 |
+
|
| 5 |
+
## Banks Covered
|
| 6 |
+
- HDFC Bank
|
| 7 |
+
- ICICI Bank
|
| 8 |
+
- SBI (State Bank of India)
|
| 9 |
+
- Axis Bank
|
| 10 |
+
- Kotak Mahindra Bank
|
| 11 |
+
- PNB (Punjab National Bank)
|
| 12 |
+
|
| 13 |
+
## Transaction Types
|
| 14 |
+
|
| 15 |
+
### Credit Types
|
| 16 |
+
| Type | Keywords |
|
| 17 |
+
|------|----------|
|
| 18 |
+
| UPI_CREDIT | credited, UPI, received |
|
| 19 |
+
| NEFT_CREDIT | NEFT, credited, transfer |
|
| 20 |
+
| RTGS_CREDIT | RTGS, credited |
|
| 21 |
+
| IMPS_CREDIT | IMPS, credited |
|
| 22 |
+
| SALARY_CREDIT | salary, credited |
|
| 23 |
+
| INTEREST_CREDIT | interest, credited |
|
| 24 |
+
| REFUND_CREDIT | refund, credited |
|
| 25 |
+
| CASH_DEPOSIT | cash, deposit, CDM |
|
| 26 |
+
| DIVIDEND_CREDIT | dividend, credited |
|
| 27 |
+
|
| 28 |
+
### Debit Types
|
| 29 |
+
| Type | Keywords |
|
| 30 |
+
|------|----------|
|
| 31 |
+
| UPI_DEBIT | debited, UPI, payment |
|
| 32 |
+
| NEFT_DEBIT | NEFT, debited, transfer |
|
| 33 |
+
| ATM_WITHDRAWAL | ATM, withdrawn, cash |
|
| 34 |
+
| POS_DEBIT | POS, merchant, debit card |
|
| 35 |
+
| BILL_PAYMENT | bill, payment, recharge |
|
| 36 |
+
| EMI_DEBIT | EMI, loan, deducted |
|
| 37 |
+
| SIP_DEBIT | SIP, mutual fund |
|
| 38 |
+
|
| 39 |
+
## Entity Extraction Fields
|
| 40 |
+
|
| 41 |
+
```json
|
| 42 |
+
{
|
| 43 |
+
"date": "2026-01-10",
|
| 44 |
+
"amount": 5000.00,
|
| 45 |
+
"type": "credit|debit",
|
| 46 |
+
"account": "4521",
|
| 47 |
+
"bank": "hdfc",
|
| 48 |
+
"reference": "503421789456",
|
| 49 |
+
"merchant": "swiggy",
|
| 50 |
+
"category": "food"
|
| 51 |
+
}
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
## VPA Patterns
|
| 55 |
+
- HDFC: @hdfcbank, @okhdfc
|
| 56 |
+
- ICICI: @icici, @okicici
|
| 57 |
+
- SBI: @sbi, @oksbi
|
| 58 |
+
- Axis: @axisbank, @okaxis
|
| 59 |
+
- Kotak: @kotak
|
| 60 |
+
- PayTM: @paytm
|
| 61 |
+
- PhonePe: @ybl
|
evaluation_results_v6.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": "models/base/phi3-finance-base",
|
| 3 |
+
"adapter": "models/adapters/finance-lora-v6",
|
| 4 |
+
"total_samples": 20,
|
| 5 |
+
"overall_accuracy": 60.0,
|
| 6 |
+
"by_bank": {
|
| 7 |
+
"paytm": {
|
| 8 |
+
"correct": 0,
|
| 9 |
+
"total": 4
|
| 10 |
+
},
|
| 11 |
+
"kotak": {
|
| 12 |
+
"correct": 1,
|
| 13 |
+
"total": 2
|
| 14 |
+
},
|
| 15 |
+
"axis": {
|
| 16 |
+
"correct": 3,
|
| 17 |
+
"total": 5
|
| 18 |
+
},
|
| 19 |
+
"sbi": {
|
| 20 |
+
"correct": 1,
|
| 21 |
+
"total": 2
|
| 22 |
+
},
|
| 23 |
+
"hdfc": {
|
| 24 |
+
"correct": 2,
|
| 25 |
+
"total": 2
|
| 26 |
+
},
|
| 27 |
+
"gpay": {
|
| 28 |
+
"correct": 1,
|
| 29 |
+
"total": 1
|
| 30 |
+
},
|
| 31 |
+
"icici": {
|
| 32 |
+
"correct": 3,
|
| 33 |
+
"total": 3
|
| 34 |
+
},
|
| 35 |
+
"phonepe": {
|
| 36 |
+
"correct": 1,
|
| 37 |
+
"total": 1
|
| 38 |
+
}
|
| 39 |
+
},
|
| 40 |
+
"by_field": {
|
| 41 |
+
"amount": {
|
| 42 |
+
"correct": 20,
|
| 43 |
+
"total": 20
|
| 44 |
+
},
|
| 45 |
+
"type": {
|
| 46 |
+
"correct": 20,
|
| 47 |
+
"total": 20
|
| 48 |
+
},
|
| 49 |
+
"date": {
|
| 50 |
+
"correct": 19,
|
| 51 |
+
"total": 20
|
| 52 |
+
},
|
| 53 |
+
"account": {
|
| 54 |
+
"correct": 17,
|
| 55 |
+
"total": 20
|
| 56 |
+
},
|
| 57 |
+
"reference": {
|
| 58 |
+
"correct": 15,
|
| 59 |
+
"total": 20
|
| 60 |
+
},
|
| 61 |
+
"merchant": {
|
| 62 |
+
"correct": 12,
|
| 63 |
+
"total": 12
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
}
|
pyproject.toml
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["hatchling"]
|
| 3 |
+
build-backend = "hatchling.build"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "finee"
|
| 7 |
+
version = "1.0.0"
|
| 8 |
+
description = "Extract structured financial entities from Indian banking messages"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
license = "MIT"
|
| 11 |
+
requires-python = ">=3.9"
|
| 12 |
+
authors = [
|
| 13 |
+
{ name = "Ranjit Behera", email = "ranjit.behera@example.com" }
|
| 14 |
+
]
|
| 15 |
+
keywords = [
|
| 16 |
+
"finance",
|
| 17 |
+
"nlp",
|
| 18 |
+
"entity-extraction",
|
| 19 |
+
"banking",
|
| 20 |
+
"upi",
|
| 21 |
+
"india",
|
| 22 |
+
"llm",
|
| 23 |
+
"phi-3",
|
| 24 |
+
]
|
| 25 |
+
classifiers = [
|
| 26 |
+
"Development Status :: 5 - Production/Stable",
|
| 27 |
+
"Intended Audience :: Developers",
|
| 28 |
+
"Intended Audience :: Financial and Insurance Industry",
|
| 29 |
+
"License :: OSI Approved :: MIT License",
|
| 30 |
+
"Operating System :: OS Independent",
|
| 31 |
+
"Programming Language :: Python :: 3",
|
| 32 |
+
"Programming Language :: Python :: 3.9",
|
| 33 |
+
"Programming Language :: Python :: 3.10",
|
| 34 |
+
"Programming Language :: Python :: 3.11",
|
| 35 |
+
"Programming Language :: Python :: 3.12",
|
| 36 |
+
"Topic :: Office/Business :: Financial",
|
| 37 |
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
| 38 |
+
"Topic :: Text Processing :: General",
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
# CORE: No ML dependencies (regex/rules only mode)
|
| 42 |
+
dependencies = [
|
| 43 |
+
"json-repair>=0.28.0", # Fix broken JSON
|
| 44 |
+
"python-dateutil>=2.8.0", # Date parsing
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
[project.optional-dependencies]
|
| 48 |
+
# Apple Silicon (MLX)
|
| 49 |
+
metal = [
|
| 50 |
+
"mlx-lm>=0.19.0",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
# NVIDIA GPU (PyTorch + Transformers)
|
| 54 |
+
cuda = [
|
| 55 |
+
"torch>=2.0.0",
|
| 56 |
+
"transformers>=4.36.0",
|
| 57 |
+
"accelerate>=0.25.0",
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
# CPU only (llama.cpp - works everywhere)
|
| 61 |
+
cpu = [
|
| 62 |
+
"llama-cpp-python>=0.2.0",
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
# All backends
|
| 66 |
+
all = [
|
| 67 |
+
"finee[metal,cuda,cpu]",
|
| 68 |
+
]
|
| 69 |
+
|
| 70 |
+
# Development
|
| 71 |
+
dev = [
|
| 72 |
+
"pytest>=7.4.0",
|
| 73 |
+
"pytest-cov>=4.1.0",
|
| 74 |
+
"black>=23.0.0",
|
| 75 |
+
"ruff>=0.1.0",
|
| 76 |
+
"mypy>=1.0.0",
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
# Documentation
|
| 80 |
+
docs = [
|
| 81 |
+
"mkdocs>=1.5.0",
|
| 82 |
+
"mkdocs-material>=9.0.0",
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
[project.urls]
|
| 86 |
+
Homepage = "https://github.com/Ranjit0034/llm-mail-trainer"
|
| 87 |
+
Documentation = "https://huggingface.co/Ranjit0034/finance-entity-extractor"
|
| 88 |
+
Repository = "https://github.com/Ranjit0034/llm-mail-trainer"
|
| 89 |
+
Issues = "https://github.com/Ranjit0034/llm-mail-trainer/issues"
|
| 90 |
+
|
| 91 |
+
[project.scripts]
|
| 92 |
+
finee = "finee.cli:main"
|
| 93 |
+
|
| 94 |
+
[tool.hatch.build]
|
| 95 |
+
packages = ["src/finee"]
|
| 96 |
+
|
| 97 |
+
[tool.hatch.build.targets.wheel]
|
| 98 |
+
packages = ["src/finee"]
|
| 99 |
+
|
| 100 |
+
[tool.pytest.ini_options]
|
| 101 |
+
testpaths = ["tests"]
|
| 102 |
+
python_files = ["test_*.py"]
|
| 103 |
+
python_classes = ["Test*"]
|
| 104 |
+
python_functions = ["test_*"]
|
| 105 |
+
addopts = "-v --tb=short"
|
| 106 |
+
|
| 107 |
+
[tool.black]
|
| 108 |
+
line-length = 100
|
| 109 |
+
target-version = ['py39', 'py310', 'py311', 'py312']
|
| 110 |
+
include = '\.pyi?$'
|
| 111 |
+
|
| 112 |
+
[tool.ruff]
|
| 113 |
+
line-length = 100
|
| 114 |
+
select = ["E", "F", "W", "I", "N"]
|
| 115 |
+
ignore = ["E501"] # Line too long (handled by black)
|
| 116 |
+
|
| 117 |
+
[tool.mypy]
|
| 118 |
+
python_version = "3.9"
|
| 119 |
+
warn_return_any = true
|
| 120 |
+
warn_unused_ignores = true
|
| 121 |
+
ignore_missing_imports = true
|
requirements.txt
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Finance Entity Extractor - Requirements
|
| 2 |
+
# ========================================
|
| 3 |
+
#
|
| 4 |
+
# Core dependencies for running the finance-entity-extractor model.
|
| 5 |
+
#
|
| 6 |
+
# Installation:
|
| 7 |
+
# pip install -r requirements.txt
|
| 8 |
+
#
|
| 9 |
+
# For Apple Silicon (MLX backend):
|
| 10 |
+
# pip install -r requirements.txt
|
| 11 |
+
#
|
| 12 |
+
# For PyTorch/CUDA (coming soon):
|
| 13 |
+
# pip install -r requirements-torch.txt
|
| 14 |
+
|
| 15 |
+
# Core MLX dependencies (Apple Silicon)
|
| 16 |
+
mlx>=0.18.0
|
| 17 |
+
mlx-lm>=0.19.0
|
| 18 |
+
|
| 19 |
+
# Data processing
|
| 20 |
+
numpy>=1.24.0
|
| 21 |
+
|
| 22 |
+
# Optional: API server
|
| 23 |
+
fastapi>=0.100.0
|
| 24 |
+
uvicorn>=0.23.0
|
| 25 |
+
pydantic>=2.0.0
|
| 26 |
+
|
| 27 |
+
# Optional: PDF parsing (for bank statements)
|
| 28 |
+
pdfplumber>=0.10.0
|
| 29 |
+
|
| 30 |
+
# Development
|
| 31 |
+
pytest>=7.0.0
|
| 32 |
+
black>=23.0.0
|
| 33 |
+
mypy>=1.0.0
|
scripts/auto_commit.sh
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# ============================================
|
| 3 |
+
# Git Auto-Commit Scheduler
|
| 4 |
+
# Commits changes daily to maintain activity
|
| 5 |
+
# ============================================
|
| 6 |
+
|
| 7 |
+
# Configuration
|
| 8 |
+
PROJECT_DIR="$HOME/llm-mail-trainer"
|
| 9 |
+
LOG_DIR="$PROJECT_DIR/scheduler_logs"
|
| 10 |
+
LOG_FILE="$LOG_DIR/commits.log"
|
| 11 |
+
REMOTE="hf" # HuggingFace remote
|
| 12 |
+
|
| 13 |
+
# Create log directory
|
| 14 |
+
mkdir -p "$LOG_DIR"
|
| 15 |
+
|
| 16 |
+
# Function to log with timestamp
|
| 17 |
+
log() {
|
| 18 |
+
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
# Function to get random commit message
|
| 22 |
+
get_commit_message() {
|
| 23 |
+
local messages=(
|
| 24 |
+
"chore: Update project files"
|
| 25 |
+
"docs: Minor documentation updates"
|
| 26 |
+
"refactor: Code cleanup"
|
| 27 |
+
"style: Format improvements"
|
| 28 |
+
"chore: Regular maintenance"
|
| 29 |
+
"docs: Improve comments"
|
| 30 |
+
"chore: Sync changes"
|
| 31 |
+
"refactor: Minor optimizations"
|
| 32 |
+
)
|
| 33 |
+
local idx=$((RANDOM % ${#messages[@]}))
|
| 34 |
+
echo "${messages[$idx]}"
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
# Main function
|
| 38 |
+
main() {
|
| 39 |
+
log "=== Starting auto-commit scheduler ==="
|
| 40 |
+
|
| 41 |
+
cd "$PROJECT_DIR" || {
|
| 42 |
+
log "ERROR: Cannot access $PROJECT_DIR"
|
| 43 |
+
exit 1
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
# Check for changes
|
| 47 |
+
if git diff --quiet && git diff --cached --quiet; then
|
| 48 |
+
log "No changes to commit"
|
| 49 |
+
|
| 50 |
+
# Optional: Create a small update to ensure commit
|
| 51 |
+
# Uncomment if you want to force daily commits
|
| 52 |
+
# echo "# Last updated: $(date)" >> .project-meta
|
| 53 |
+
# git add .project-meta
|
| 54 |
+
else
|
| 55 |
+
log "Changes detected, preparing commit..."
|
| 56 |
+
fi
|
| 57 |
+
|
| 58 |
+
# Stage all changes
|
| 59 |
+
git add -A
|
| 60 |
+
|
| 61 |
+
# Check again after staging
|
| 62 |
+
if git diff --cached --quiet; then
|
| 63 |
+
log "Nothing staged to commit"
|
| 64 |
+
exit 0
|
| 65 |
+
fi
|
| 66 |
+
|
| 67 |
+
# Get current branch
|
| 68 |
+
BRANCH=$(git branch --show-current)
|
| 69 |
+
log "Current branch: $BRANCH"
|
| 70 |
+
|
| 71 |
+
# Commit with random message
|
| 72 |
+
COMMIT_MSG=$(get_commit_message)
|
| 73 |
+
git commit -m "$COMMIT_MSG" >> "$LOG_FILE" 2>&1
|
| 74 |
+
|
| 75 |
+
if [ $? -eq 0 ]; then
|
| 76 |
+
log "β
Committed: $COMMIT_MSG"
|
| 77 |
+
|
| 78 |
+
# Push to remote
|
| 79 |
+
git push "$REMOTE" "$BRANCH" >> "$LOG_FILE" 2>&1
|
| 80 |
+
|
| 81 |
+
if [ $? -eq 0 ]; then
|
| 82 |
+
log "β
Pushed to $REMOTE/$BRANCH"
|
| 83 |
+
|
| 84 |
+
# Sync model files to ensure they're always present
|
| 85 |
+
log "π Syncing model files..."
|
| 86 |
+
cd "$PROJECT_DIR"
|
| 87 |
+
source venv/bin/activate 2>/dev/null
|
| 88 |
+
python scripts/sync_models.py >> "$LOG_FILE" 2>&1
|
| 89 |
+
log "β
Model sync complete"
|
| 90 |
+
else
|
| 91 |
+
log "β Push failed"
|
| 92 |
+
fi
|
| 93 |
+
else
|
| 94 |
+
log "β Commit failed"
|
| 95 |
+
fi
|
| 96 |
+
|
| 97 |
+
log "=== Scheduler complete ==="
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
# Run main function
|
| 101 |
+
main
|
scripts/claude_labeling.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Claude API Auto-Labeling Script.
|
| 3 |
+
|
| 4 |
+
Uses Claude API to automatically label financial emails for training.
|
| 5 |
+
Generates high-quality labels at scale.
|
| 6 |
+
|
| 7 |
+
Author: Ranjit Behera
|
| 8 |
+
|
| 9 |
+
Usage:
|
| 10 |
+
export ANTHROPIC_API_KEY="your-key-here"
|
| 11 |
+
python scripts/claude_labeling.py --limit 100
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import time
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
import anthropic
|
| 22 |
+
HAS_ANTHROPIC = True
|
| 23 |
+
except ImportError:
|
| 24 |
+
HAS_ANTHROPIC = False
|
| 25 |
+
print("β οΈ anthropic package not installed. Run: pip install anthropic")
|
| 26 |
+
|
| 27 |
+
CORPUS_FILE = Path("data/corpus/emails/financial_emails.jsonl")
|
| 28 |
+
OUTPUT_FILE = Path("data/synthetic/claude_labeled.jsonl")
|
| 29 |
+
|
| 30 |
+
EXTRACTION_PROMPT = """You are a financial entity extraction expert. Extract structured data from this Indian bank email.
|
| 31 |
+
|
| 32 |
+
EMAIL:
|
| 33 |
+
{email_text}
|
| 34 |
+
|
| 35 |
+
Extract the following fields (return empty string if not found):
|
| 36 |
+
- amount: The transaction amount (numbers only, no currency symbols)
|
| 37 |
+
- type: "credit" or "debit"
|
| 38 |
+
- date: Transaction date (keep original format)
|
| 39 |
+
- account: Last 4 digits of account number
|
| 40 |
+
- reference: UPI/NEFT/IMPS reference number (12+ digits)
|
| 41 |
+
- merchant: Merchant/recipient name (lowercase)
|
| 42 |
+
- bank: Bank name (hdfc/icici/sbi/axis/kotak/phonepe/gpay/paytm)
|
| 43 |
+
|
| 44 |
+
Respond ONLY with valid JSON, no explanation:"""
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def extract_with_claude(email_text: str, client) -> Optional[dict]:
|
| 48 |
+
"""Use Claude to extract entities from email."""
|
| 49 |
+
try:
|
| 50 |
+
message = client.messages.create(
|
| 51 |
+
model="claude-sonnet-4-20250514",
|
| 52 |
+
max_tokens=300,
|
| 53 |
+
messages=[
|
| 54 |
+
{
|
| 55 |
+
"role": "user",
|
| 56 |
+
"content": EXTRACTION_PROMPT.format(email_text=email_text[:1000])
|
| 57 |
+
}
|
| 58 |
+
]
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
response_text = message.content[0].text
|
| 62 |
+
|
| 63 |
+
# Parse JSON
|
| 64 |
+
import re
|
| 65 |
+
match = re.search(r'\{[^{}]+\}', response_text, re.DOTALL)
|
| 66 |
+
if match:
|
| 67 |
+
return json.loads(match.group())
|
| 68 |
+
|
| 69 |
+
except Exception as e:
|
| 70 |
+
print(f" Error: {e}")
|
| 71 |
+
|
| 72 |
+
return None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def load_unlabeled_emails(limit: int = 100) -> list:
|
| 76 |
+
"""Load emails that need labeling."""
|
| 77 |
+
emails = []
|
| 78 |
+
|
| 79 |
+
with open(CORPUS_FILE, 'r') as f:
|
| 80 |
+
for line in f:
|
| 81 |
+
try:
|
| 82 |
+
data = json.loads(line)
|
| 83 |
+
body = data.get('body', '')
|
| 84 |
+
|
| 85 |
+
# Filter for transaction emails
|
| 86 |
+
body_lower = body.lower()
|
| 87 |
+
has_transaction = any(x in body_lower for x in ['debited', 'credited', 'received', 'paid'])
|
| 88 |
+
has_amount = any(x in body_lower for x in ['rs.', 'rs ', 'inr', 'βΉ'])
|
| 89 |
+
|
| 90 |
+
if has_transaction and has_amount and len(body) > 50:
|
| 91 |
+
emails.append({
|
| 92 |
+
'text': body,
|
| 93 |
+
'subject': data.get('subject', ''),
|
| 94 |
+
'sender': data.get('sender', '')
|
| 95 |
+
})
|
| 96 |
+
|
| 97 |
+
if len(emails) >= limit:
|
| 98 |
+
break
|
| 99 |
+
except:
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
return emails
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def run_labeling(limit: int = 100):
|
| 106 |
+
"""Run Claude labeling on unlabeled emails."""
|
| 107 |
+
print("=" * 60)
|
| 108 |
+
print("π€ CLAUDE API AUTO-LABELING")
|
| 109 |
+
print("=" * 60)
|
| 110 |
+
|
| 111 |
+
if not HAS_ANTHROPIC:
|
| 112 |
+
print("β Please install anthropic: pip install anthropic")
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
api_key = os.environ.get("ANTHROPIC_API_KEY")
|
| 116 |
+
if not api_key:
|
| 117 |
+
print("β Please set ANTHROPIC_API_KEY environment variable")
|
| 118 |
+
print(" export ANTHROPIC_API_KEY='your-key-here'")
|
| 119 |
+
return
|
| 120 |
+
|
| 121 |
+
client = anthropic.Anthropic(api_key=api_key)
|
| 122 |
+
|
| 123 |
+
print(f"\n1. Loading unlabeled emails (limit: {limit})...")
|
| 124 |
+
emails = load_unlabeled_emails(limit=limit)
|
| 125 |
+
print(f" Found {len(emails)} candidates")
|
| 126 |
+
|
| 127 |
+
print(f"\n2. Labeling with Claude...")
|
| 128 |
+
|
| 129 |
+
labeled = []
|
| 130 |
+
for i, email in enumerate(emails):
|
| 131 |
+
print(f" [{i+1}/{len(emails)}] Extracting...", end=" ")
|
| 132 |
+
|
| 133 |
+
entities = extract_with_claude(email['text'], client)
|
| 134 |
+
|
| 135 |
+
if entities and entities.get('amount'):
|
| 136 |
+
# Create training sample
|
| 137 |
+
prompt = f"""Extract financial entities from this email:
|
| 138 |
+
|
| 139 |
+
{email['text'][:500]}
|
| 140 |
+
|
| 141 |
+
Extract: amount, type, date, account, reference, merchant
|
| 142 |
+
Output JSON:"""
|
| 143 |
+
|
| 144 |
+
labeled.append({
|
| 145 |
+
'prompt': prompt,
|
| 146 |
+
'completion': json.dumps(entities, indent=2),
|
| 147 |
+
'source': 'claude_labeled'
|
| 148 |
+
})
|
| 149 |
+
print(f"β
{entities.get('amount')}")
|
| 150 |
+
else:
|
| 151 |
+
print("β No entities found")
|
| 152 |
+
|
| 153 |
+
# Rate limit
|
| 154 |
+
time.sleep(0.5)
|
| 155 |
+
|
| 156 |
+
# Save
|
| 157 |
+
print(f"\n3. Saving labeled data...")
|
| 158 |
+
OUTPUT_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 159 |
+
|
| 160 |
+
with open(OUTPUT_FILE, 'w') as f:
|
| 161 |
+
for sample in labeled:
|
| 162 |
+
f.write(json.dumps(sample) + '\n')
|
| 163 |
+
|
| 164 |
+
print(f" β
Saved {len(labeled)} labeled samples to {OUTPUT_FILE}")
|
| 165 |
+
|
| 166 |
+
# Show sample
|
| 167 |
+
if labeled:
|
| 168 |
+
print("\nπ§ Sample:")
|
| 169 |
+
print(labeled[0]['completion'])
|
| 170 |
+
|
| 171 |
+
return labeled
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
import argparse
|
| 176 |
+
parser = argparse.ArgumentParser()
|
| 177 |
+
parser.add_argument('--limit', type=int, default=50, help='Number of emails to label')
|
| 178 |
+
args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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
RBI/NPCI Corpus Collection Script.
|
| 3 |
+
|
| 4 |
+
Downloads and processes financial documents from:
|
| 5 |
+
- RBI (Reserve Bank of India) circulars
|
| 6 |
+
- NPCI (National Payments Corporation of India) docs
|
| 7 |
+
- Banking glossaries and FAQs
|
| 8 |
+
|
| 9 |
+
Author: Ranjit Behera
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
python scripts/collect_rbi_npci.py
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import time
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import List, Dict
|
| 19 |
+
import re
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import requests
|
| 23 |
+
from bs4 import BeautifulSoup
|
| 24 |
+
HAS_DEPS = True
|
| 25 |
+
except ImportError:
|
| 26 |
+
HAS_DEPS = False
|
| 27 |
+
print("β οΈ Missing dependencies. Run: pip install requests beautifulsoup4")
|
| 28 |
+
|
| 29 |
+
OUTPUT_DIR = Path("data/corpus/regulatory")
|
| 30 |
+
|
| 31 |
+
# RBI UPI-related URLs (public pages)
|
| 32 |
+
RBI_SOURCES = [
|
| 33 |
+
{
|
| 34 |
+
"name": "RBI UPI FAQ",
|
| 35 |
+
"url": "https://www.rbi.org.in/Scripts/FAQView.aspx?Id=112",
|
| 36 |
+
"type": "faq"
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"name": "RBI Digital Payments",
|
| 40 |
+
"url": "https://www.rbi.org.in/Scripts/PublicationsView.aspx?id=21454",
|
| 41 |
+
"type": "publication"
|
| 42 |
+
}
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
# NPCI sources
|
| 46 |
+
NPCI_SOURCES = [
|
| 47 |
+
{
|
| 48 |
+
"name": "NPCI UPI Overview",
|
| 49 |
+
"url": "https://www.npci.org.in/what-we-do/upi/product-overview",
|
| 50 |
+
"type": "overview"
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"name": "NPCI IMPS",
|
| 54 |
+
"url": "https://www.npci.org.in/what-we-do/imps/product-overview",
|
| 55 |
+
"type": "overview"
|
| 56 |
+
}
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
# Indian Banking terminology (expanded)
|
| 60 |
+
BANKING_TERMS = """
|
| 61 |
+
# UPI (Unified Payments Interface) Terms
|
| 62 |
+
UPI: Unified Payments Interface - A real-time payment system developed by NPCI
|
| 63 |
+
VPA: Virtual Payment Address - A unique identifier like yourname@bankname
|
| 64 |
+
UPI ID: Same as VPA, used to send and receive money
|
| 65 |
+
UPI PIN: 4-6 digit PIN used to authorize UPI transactions
|
| 66 |
+
Collect Request: Request for payment sent via UPI
|
| 67 |
+
Pay Request: Sending money via UPI
|
| 68 |
+
Transaction Reference Number: 12-digit unique identifier for UPI transactions
|
| 69 |
+
UTR: Unique Transaction Reference - Another term for transaction ID
|
| 70 |
+
|
| 71 |
+
# IMPS (Immediate Payment Service) Terms
|
| 72 |
+
IMPS: Immediate Payment Service - 24x7 instant money transfer
|
| 73 |
+
MMID: Mobile Money Identifier - 7-digit number linked to bank account
|
| 74 |
+
IFSC: Indian Financial System Code - 11-character bank branch identifier
|
| 75 |
+
|
| 76 |
+
# NEFT/RTGS Terms
|
| 77 |
+
NEFT: National Electronic Funds Transfer - Batch processing fund transfer
|
| 78 |
+
RTGS: Real Time Gross Settlement - High value instant transfers (min Rs.2 lakh)
|
| 79 |
+
Beneficiary: Person/entity receiving the funds
|
| 80 |
+
Remitter: Person/entity sending the funds
|
| 81 |
+
|
| 82 |
+
# Account Terms
|
| 83 |
+
Savings Account: Account for individuals with interest
|
| 84 |
+
Current Account: Account for businesses, no interest
|
| 85 |
+
Fixed Deposit: Term deposit with fixed interest rate
|
| 86 |
+
Recurring Deposit: Monthly deposit scheme
|
| 87 |
+
Demat Account: Account to hold securities in electronic form
|
| 88 |
+
CASA: Current Account Savings Account ratio
|
| 89 |
+
|
| 90 |
+
# Card Terms
|
| 91 |
+
Debit Card: Card linked to bank account for spending
|
| 92 |
+
Credit Card: Card with credit limit for spending
|
| 93 |
+
CVV: Card Verification Value - 3-digit security code
|
| 94 |
+
EMI: Equated Monthly Installment
|
| 95 |
+
POS: Point of Sale terminal
|
| 96 |
+
|
| 97 |
+
# Loan Terms
|
| 98 |
+
Home Loan: Loan for purchasing property
|
| 99 |
+
Personal Loan: Unsecured loan for personal use
|
| 100 |
+
EMI: Monthly payment amount
|
| 101 |
+
Principal: Original loan amount
|
| 102 |
+
Interest: Cost of borrowing
|
| 103 |
+
ROI: Rate of Interest
|
| 104 |
+
Tenure: Loan repayment period
|
| 105 |
+
|
| 106 |
+
# Investment Terms
|
| 107 |
+
Mutual Fund: Pooled investment vehicle
|
| 108 |
+
SIP: Systematic Investment Plan
|
| 109 |
+
NAV: Net Asset Value
|
| 110 |
+
ELSS: Equity Linked Savings Scheme
|
| 111 |
+
Dividend: Distribution of profits
|
| 112 |
+
Capital Gains: Profit from selling investments
|
| 113 |
+
|
| 114 |
+
# Tax Terms
|
| 115 |
+
TDS: Tax Deducted at Source
|
| 116 |
+
PAN: Permanent Account Number
|
| 117 |
+
GST: Goods and Services Tax
|
| 118 |
+
ITR: Income Tax Return
|
| 119 |
+
Form 16: TDS certificate from employer
|
| 120 |
+
Form 26AS: Annual tax statement
|
| 121 |
+
|
| 122 |
+
# Regulatory Bodies
|
| 123 |
+
RBI: Reserve Bank of India - Central bank
|
| 124 |
+
NPCI: National Payments Corporation of India
|
| 125 |
+
SEBI: Securities and Exchange Board of India
|
| 126 |
+
IRDAI: Insurance Regulatory and Development Authority
|
| 127 |
+
PFRDA: Pension Fund Regulatory and Development Authority
|
| 128 |
+
|
| 129 |
+
# Digital Payment Apps
|
| 130 |
+
PhonePe: UPI-based payment app
|
| 131 |
+
GPay: Google Pay - UPI payment app
|
| 132 |
+
Paytm: Payment and financial services app
|
| 133 |
+
BHIM: Bharat Interface for Money - Government UPI app
|
| 134 |
+
Amazon Pay: Amazon's payment service
|
| 135 |
+
|
| 136 |
+
# Common Transaction Types
|
| 137 |
+
Credit: Money added to account
|
| 138 |
+
Debit: Money removed from account
|
| 139 |
+
Transfer: Moving money between accounts
|
| 140 |
+
Bill Payment: Paying utility bills
|
| 141 |
+
Recharge: Adding balance to prepaid services
|
| 142 |
+
P2P: Person to Person transfer
|
| 143 |
+
P2M: Person to Merchant transfer
|
| 144 |
+
|
| 145 |
+
# Common Merchants
|
| 146 |
+
Swiggy: Food delivery platform
|
| 147 |
+
Zomato: Food delivery platform
|
| 148 |
+
Amazon: E-commerce platform
|
| 149 |
+
Flipkart: E-commerce platform
|
| 150 |
+
Uber: Ride-hailing service
|
| 151 |
+
Ola: Ride-hailing service
|
| 152 |
+
Rapido: Bike taxi service
|
| 153 |
+
BigBasket: Grocery delivery
|
| 154 |
+
Blinkit: Quick commerce
|
| 155 |
+
Zepto: Quick commerce
|
| 156 |
+
DMart: Retail chain
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def fetch_page(url: str) -> str:
|
| 161 |
+
"""Fetch and parse webpage content."""
|
| 162 |
+
try:
|
| 163 |
+
headers = {
|
| 164 |
+
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
|
| 165 |
+
}
|
| 166 |
+
response = requests.get(url, headers=headers, timeout=30)
|
| 167 |
+
response.raise_for_status()
|
| 168 |
+
|
| 169 |
+
soup = BeautifulSoup(response.content, 'html.parser')
|
| 170 |
+
|
| 171 |
+
# Remove scripts and styles
|
| 172 |
+
for tag in soup(['script', 'style', 'nav', 'footer', 'header']):
|
| 173 |
+
tag.decompose()
|
| 174 |
+
|
| 175 |
+
# Get text
|
| 176 |
+
text = soup.get_text(separator='\n', strip=True)
|
| 177 |
+
|
| 178 |
+
# Clean up
|
| 179 |
+
lines = [line.strip() for line in text.split('\n') if line.strip()]
|
| 180 |
+
text = '\n'.join(lines)
|
| 181 |
+
|
| 182 |
+
return text
|
| 183 |
+
|
| 184 |
+
except Exception as e:
|
| 185 |
+
print(f" Error fetching {url}: {e}")
|
| 186 |
+
return ""
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def collect_corpus():
|
| 190 |
+
"""Collect corpus from RBI, NPCI and banking terms."""
|
| 191 |
+
print("=" * 60)
|
| 192 |
+
print("π COLLECTING RBI/NPCI CORPUS")
|
| 193 |
+
print("=" * 60)
|
| 194 |
+
|
| 195 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 196 |
+
|
| 197 |
+
corpus = []
|
| 198 |
+
|
| 199 |
+
# 1. Banking Terms (always available)
|
| 200 |
+
print("\n1. Adding banking terminology...")
|
| 201 |
+
terms_lines = BANKING_TERMS.strip().split('\n')
|
| 202 |
+
for line in terms_lines:
|
| 203 |
+
if line.strip() and not line.startswith('#'):
|
| 204 |
+
corpus.append({
|
| 205 |
+
'text': line.strip(),
|
| 206 |
+
'source': 'banking_terms',
|
| 207 |
+
'type': 'glossary'
|
| 208 |
+
})
|
| 209 |
+
print(f" Added {len(corpus)} term definitions")
|
| 210 |
+
|
| 211 |
+
# 2. Try fetching RBI pages
|
| 212 |
+
if HAS_DEPS:
|
| 213 |
+
print("\n2. Fetching RBI documents...")
|
| 214 |
+
for source in RBI_SOURCES:
|
| 215 |
+
print(f" Fetching {source['name']}...", end=" ")
|
| 216 |
+
text = fetch_page(source['url'])
|
| 217 |
+
if text and len(text) > 100:
|
| 218 |
+
corpus.append({
|
| 219 |
+
'text': text[:10000], # Limit size
|
| 220 |
+
'source': source['name'],
|
| 221 |
+
'url': source['url'],
|
| 222 |
+
'type': source['type']
|
| 223 |
+
})
|
| 224 |
+
print(f"β
({len(text)} chars)")
|
| 225 |
+
else:
|
| 226 |
+
print("β")
|
| 227 |
+
time.sleep(1)
|
| 228 |
+
|
| 229 |
+
print("\n3. Fetching NPCI documents...")
|
| 230 |
+
for source in NPCI_SOURCES:
|
| 231 |
+
print(f" Fetching {source['name']}...", end=" ")
|
| 232 |
+
text = fetch_page(source['url'])
|
| 233 |
+
if text and len(text) > 100:
|
| 234 |
+
corpus.append({
|
| 235 |
+
'text': text[:10000],
|
| 236 |
+
'source': source['name'],
|
| 237 |
+
'url': source['url'],
|
| 238 |
+
'type': source['type']
|
| 239 |
+
})
|
| 240 |
+
print(f"β
({len(text)} chars)")
|
| 241 |
+
else:
|
| 242 |
+
print("β")
|
| 243 |
+
time.sleep(1)
|
| 244 |
+
else:
|
| 245 |
+
print("\nβ οΈ Skipping web scraping (missing requests/beautifulsoup4)")
|
| 246 |
+
|
| 247 |
+
# Save corpus
|
| 248 |
+
output_file = OUTPUT_DIR / "rbi_npci_corpus.jsonl"
|
| 249 |
+
with open(output_file, 'w') as f:
|
| 250 |
+
for item in corpus:
|
| 251 |
+
f.write(json.dumps(item, ensure_ascii=False) + '\n')
|
| 252 |
+
|
| 253 |
+
print(f"\nβ
Saved {len(corpus)} documents to {output_file}")
|
| 254 |
+
|
| 255 |
+
# Calculate tokens (rough estimate: 1 token β 4 chars)
|
| 256 |
+
total_chars = sum(len(item['text']) for item in corpus)
|
| 257 |
+
est_tokens = total_chars // 4
|
| 258 |
+
print(f" Estimated tokens: ~{est_tokens:,}")
|
| 259 |
+
|
| 260 |
+
return corpus
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
if __name__ == "__main__":
|
| 264 |
+
collect_corpus()
|
scripts/convert_to_gguf.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
GGUF Conversion Script.
|
| 3 |
+
|
| 4 |
+
Converts the PyTorch model to GGUF format for llama.cpp compatibility.
|
| 5 |
+
This enables deployment on any platform (Linux, Windows, Mac) with CPU or GPU.
|
| 6 |
+
|
| 7 |
+
Author: Ranjit Behera
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import subprocess
|
| 11 |
+
import argparse
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
import shutil
|
| 15 |
+
import tempfile
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def check_llama_cpp():
|
| 20 |
+
"""Check if llama.cpp is available, download if needed."""
|
| 21 |
+
llama_cpp_path = Path("tools/llama.cpp")
|
| 22 |
+
|
| 23 |
+
if not llama_cpp_path.exists():
|
| 24 |
+
print("π₯ llama.cpp not found. Cloning repository...")
|
| 25 |
+
llama_cpp_path.parent.mkdir(parents=True, exist_ok=True)
|
| 26 |
+
|
| 27 |
+
subprocess.run([
|
| 28 |
+
"git", "clone", "--depth", "1",
|
| 29 |
+
"https://github.com/ggerganov/llama.cpp.git",
|
| 30 |
+
str(llama_cpp_path)
|
| 31 |
+
], check=True)
|
| 32 |
+
|
| 33 |
+
print("β
llama.cpp cloned successfully")
|
| 34 |
+
|
| 35 |
+
return llama_cpp_path
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def convert_to_gguf(model_path: Path, output_path: Path, quantization: str = "q4_k_m"):
|
| 39 |
+
"""
|
| 40 |
+
Convert PyTorch/Safetensors model to GGUF format.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
model_path: Path to the PyTorch model directory
|
| 44 |
+
output_path: Output path for GGUF file
|
| 45 |
+
quantization: Quantization type (q4_k_m, q5_k_m, q8_0, f16, f32)
|
| 46 |
+
"""
|
| 47 |
+
llama_cpp = check_llama_cpp()
|
| 48 |
+
convert_script = llama_cpp / "convert_hf_to_gguf.py"
|
| 49 |
+
|
| 50 |
+
if not convert_script.exists():
|
| 51 |
+
# Try alternative script name
|
| 52 |
+
convert_script = llama_cpp / "convert-hf-to-gguf.py"
|
| 53 |
+
|
| 54 |
+
if not convert_script.exists():
|
| 55 |
+
print("β Conversion script not found in llama.cpp")
|
| 56 |
+
print(" Trying pip-installed llama-cpp-python converter...")
|
| 57 |
+
return convert_with_pip_package(model_path, output_path, quantization)
|
| 58 |
+
|
| 59 |
+
# Step 1: Convert to GGUF (F16)
|
| 60 |
+
print(f"π Converting {model_path} to GGUF (F16)...")
|
| 61 |
+
|
| 62 |
+
f16_output = output_path.parent / f"{output_path.stem}-f16.gguf"
|
| 63 |
+
|
| 64 |
+
cmd = [
|
| 65 |
+
sys.executable, str(convert_script),
|
| 66 |
+
str(model_path),
|
| 67 |
+
"--outfile", str(f16_output),
|
| 68 |
+
"--outtype", "f16"
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
subprocess.run(cmd, check=True)
|
| 73 |
+
print(f"β
F16 GGUF created: {f16_output}")
|
| 74 |
+
except subprocess.CalledProcessError as e:
|
| 75 |
+
print(f"β Conversion failed: {e}")
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
# Step 2: Quantize if needed
|
| 79 |
+
if quantization != "f16":
|
| 80 |
+
print(f"π Quantizing to {quantization}...")
|
| 81 |
+
|
| 82 |
+
quantize_bin = llama_cpp / "quantize"
|
| 83 |
+
if not quantize_bin.exists():
|
| 84 |
+
quantize_bin = llama_cpp / "build" / "bin" / "quantize"
|
| 85 |
+
|
| 86 |
+
if not quantize_bin.exists():
|
| 87 |
+
print("β οΈ Quantize binary not found. Using F16 output.")
|
| 88 |
+
shutil.move(f16_output, output_path)
|
| 89 |
+
return output_path
|
| 90 |
+
|
| 91 |
+
cmd = [str(quantize_bin), str(f16_output), str(output_path), quantization]
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
subprocess.run(cmd, check=True)
|
| 95 |
+
print(f"β
Quantized GGUF created: {output_path}")
|
| 96 |
+
f16_output.unlink() # Remove intermediate F16 file
|
| 97 |
+
except subprocess.CalledProcessError as e:
|
| 98 |
+
print(f"β οΈ Quantization failed, using F16: {e}")
|
| 99 |
+
shutil.move(f16_output, output_path)
|
| 100 |
+
else:
|
| 101 |
+
shutil.move(f16_output, output_path)
|
| 102 |
+
|
| 103 |
+
return output_path
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def convert_with_pip_package(model_path: Path, output_path: Path, quantization: str):
|
| 107 |
+
"""
|
| 108 |
+
Alternative conversion using transformers + gguf library.
|
| 109 |
+
"""
|
| 110 |
+
try:
|
| 111 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 112 |
+
import torch
|
| 113 |
+
except ImportError:
|
| 114 |
+
print("β transformers not installed. Run: pip install transformers torch")
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
print("π Loading model for conversion...")
|
| 118 |
+
|
| 119 |
+
# Check if gguf conversion is available via transformers
|
| 120 |
+
try:
|
| 121 |
+
# Try using the convert script from transformers
|
| 122 |
+
cmd = [
|
| 123 |
+
sys.executable, "-m", "transformers.gguf",
|
| 124 |
+
"--model", str(model_path),
|
| 125 |
+
"--output", str(output_path)
|
| 126 |
+
]
|
| 127 |
+
subprocess.run(cmd, check=True)
|
| 128 |
+
return output_path
|
| 129 |
+
except Exception as e:
|
| 130 |
+
print(f"β οΈ Direct conversion not available: {e}")
|
| 131 |
+
print("\nπ Manual GGUF conversion instructions:")
|
| 132 |
+
print("=" * 50)
|
| 133 |
+
print("1. Clone llama.cpp:")
|
| 134 |
+
print(" git clone https://github.com/ggerganov/llama.cpp")
|
| 135 |
+
print(" cd llama.cpp && make")
|
| 136 |
+
print("")
|
| 137 |
+
print("2. Convert the model:")
|
| 138 |
+
print(f" python convert_hf_to_gguf.py {model_path} --outfile {output_path}")
|
| 139 |
+
print("")
|
| 140 |
+
print("3. (Optional) Quantize:")
|
| 141 |
+
print(f" ./quantize {output_path} {output_path.stem}-q4_k_m.gguf q4_k_m")
|
| 142 |
+
print("=" * 50)
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def create_gguf_readme(output_dir: Path):
|
| 147 |
+
"""Create a README for GGUF usage."""
|
| 148 |
+
readme = """# GGUF Model for llama.cpp
|
| 149 |
+
|
| 150 |
+
## Quick Start
|
| 151 |
+
|
| 152 |
+
### Using llama.cpp CLI
|
| 153 |
+
```bash
|
| 154 |
+
# Clone and build llama.cpp
|
| 155 |
+
git clone https://github.com/ggerganov/llama.cpp
|
| 156 |
+
cd llama.cpp && make
|
| 157 |
+
|
| 158 |
+
# Run inference
|
| 159 |
+
./main -m finance-extractor-v8-q4_k_m.gguf -p "Extract financial entities from: Rs.500 debited from A/c 1234 on 01-01-25"
|
| 160 |
+
```
|
| 161 |
+
|
| 162 |
+
### Using Python (llama-cpp-python)
|
| 163 |
+
```bash
|
| 164 |
+
pip install llama-cpp-python
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
```python
|
| 168 |
+
from llama_cpp import Llama
|
| 169 |
+
|
| 170 |
+
llm = Llama(model_path="finance-extractor-v8-q4_k_m.gguf")
|
| 171 |
+
|
| 172 |
+
output = llm(
|
| 173 |
+
"Extract financial entities from: Rs.500 debited from A/c 1234 on 01-01-25",
|
| 174 |
+
max_tokens=200,
|
| 175 |
+
stop=["\\n\\n"]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
print(output["choices"][0]["text"])
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
## Quantization Variants
|
| 182 |
+
|
| 183 |
+
| File | Size | Quality | Speed |
|
| 184 |
+
|------|------|---------|-------|
|
| 185 |
+
| `*-f16.gguf` | ~7.6GB | Highest | Slowest |
|
| 186 |
+
| `*-q8_0.gguf` | ~4GB | Very High | Fast |
|
| 187 |
+
| `*-q4_k_m.gguf` | ~2GB | Good | Fastest |
|
| 188 |
+
|
| 189 |
+
## Compatibility
|
| 190 |
+
|
| 191 |
+
- β
Linux (CPU, NVIDIA GPU, AMD GPU)
|
| 192 |
+
- β
Windows (CPU, NVIDIA GPU)
|
| 193 |
+
- β
macOS (CPU, Metal)
|
| 194 |
+
- β
Any llama.cpp compatible tool
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
with open(output_dir / "GGUF_README.md", "w") as f:
|
| 198 |
+
f.write(readme)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def main():
|
| 202 |
+
parser = argparse.ArgumentParser(description="Convert PyTorch model to GGUF")
|
| 203 |
+
parser.add_argument(
|
| 204 |
+
"--model",
|
| 205 |
+
default="models/released/finance-extractor-v8-pytorch",
|
| 206 |
+
help="Path to PyTorch model directory"
|
| 207 |
+
)
|
| 208 |
+
parser.add_argument(
|
| 209 |
+
"--output",
|
| 210 |
+
default="models/released/finance-extractor-v8-q4_k_m.gguf",
|
| 211 |
+
help="Output GGUF file path"
|
| 212 |
+
)
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--quantization",
|
| 215 |
+
default="q4_k_m",
|
| 216 |
+
choices=["f16", "q8_0", "q5_k_m", "q4_k_m", "q4_0"],
|
| 217 |
+
help="Quantization type"
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
args = parser.parse_args()
|
| 221 |
+
|
| 222 |
+
model_path = Path(args.model)
|
| 223 |
+
output_path = Path(args.output)
|
| 224 |
+
|
| 225 |
+
if not model_path.exists():
|
| 226 |
+
print(f"β Model not found: {model_path}")
|
| 227 |
+
sys.exit(1)
|
| 228 |
+
|
| 229 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 230 |
+
|
| 231 |
+
result = convert_to_gguf(model_path, output_path, args.quantization)
|
| 232 |
+
|
| 233 |
+
if result:
|
| 234 |
+
print(f"\nπ GGUF conversion complete!")
|
| 235 |
+
print(f" Output: {result}")
|
| 236 |
+
print(f" Size: {result.stat().st_size / (1024**3):.2f} GB")
|
| 237 |
+
create_gguf_readme(result.parent)
|
| 238 |
+
else:
|
| 239 |
+
print("\nβ οΈ GGUF conversion requires manual steps (see instructions above)")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
if __name__ == "__main__":
|
| 243 |
+
main()
|
scripts/corpus_collection/collect_corpus.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Domain Pre-training Corpus Collector.
|
| 3 |
+
|
| 4 |
+
Collects and prepares text corpus for domain pre-training on Indian
|
| 5 |
+
financial domain. Combines multiple sources into a unified JSONL format.
|
| 6 |
+
|
| 7 |
+
Sources:
|
| 8 |
+
1. Gmail bank emails (MBOX export)
|
| 9 |
+
2. Bank statement PDFs (text extraction)
|
| 10 |
+
3. RBI circulars and guidelines
|
| 11 |
+
4. NPCI/UPI documentation
|
| 12 |
+
5. Financial news articles
|
| 13 |
+
6. Banking glossary
|
| 14 |
+
|
| 15 |
+
Target: 10M+ tokens for effective domain pre-training.
|
| 16 |
+
|
| 17 |
+
Author: Ranjit Behera
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import json
|
| 21 |
+
import re
|
| 22 |
+
import logging
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Dict, List, Optional, Generator, Any
|
| 25 |
+
from dataclasses import dataclass, field
|
| 26 |
+
from datetime import datetime
|
| 27 |
+
from collections import Counter
|
| 28 |
+
|
| 29 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s")
|
| 30 |
+
logger = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass
|
| 34 |
+
class CorpusDocument:
|
| 35 |
+
"""A single document in the corpus."""
|
| 36 |
+
text: str
|
| 37 |
+
source: str # email, statement, rbi, npci, news, glossary
|
| 38 |
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
| 39 |
+
word_count: int = 0
|
| 40 |
+
|
| 41 |
+
def __post_init__(self):
|
| 42 |
+
self.word_count = len(self.text.split())
|
| 43 |
+
|
| 44 |
+
def to_dict(self) -> Dict:
|
| 45 |
+
return {
|
| 46 |
+
"text": self.text,
|
| 47 |
+
"source": self.source,
|
| 48 |
+
"metadata": self.metadata,
|
| 49 |
+
"word_count": self.word_count
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclass
|
| 54 |
+
class CorpusStats:
|
| 55 |
+
"""Statistics for the corpus."""
|
| 56 |
+
total_documents: int = 0
|
| 57 |
+
total_words: int = 0
|
| 58 |
+
total_chars: int = 0
|
| 59 |
+
by_source: Dict[str, int] = field(default_factory=dict)
|
| 60 |
+
|
| 61 |
+
def estimated_tokens(self) -> int:
|
| 62 |
+
"""Estimate tokens (roughly 0.75 tokens per word for English)."""
|
| 63 |
+
return int(self.total_words * 1.3) # Financial text has more tokens
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class CorpusCollector:
|
| 67 |
+
"""
|
| 68 |
+
Collects and manages the domain pre-training corpus.
|
| 69 |
+
|
| 70 |
+
Usage:
|
| 71 |
+
collector = CorpusCollector()
|
| 72 |
+
collector.add_glossary()
|
| 73 |
+
collector.add_emails_from_mbox("path/to/mbox")
|
| 74 |
+
collector.add_statements_from_pdfs("path/to/pdfs")
|
| 75 |
+
collector.export("data/corpus/combined/corpus.jsonl")
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(self, corpus_dir: str = "data/corpus"):
|
| 79 |
+
self.corpus_dir = Path(corpus_dir)
|
| 80 |
+
self.corpus_dir.mkdir(parents=True, exist_ok=True)
|
| 81 |
+
|
| 82 |
+
self.documents: List[CorpusDocument] = []
|
| 83 |
+
self.stats = CorpusStats()
|
| 84 |
+
|
| 85 |
+
def add_document(self, text: str, source: str, metadata: Dict = None):
|
| 86 |
+
"""Add a single document to the corpus."""
|
| 87 |
+
# Clean text
|
| 88 |
+
text = self._clean_text(text)
|
| 89 |
+
|
| 90 |
+
if len(text.split()) < 10: # Skip very short texts
|
| 91 |
+
return
|
| 92 |
+
|
| 93 |
+
doc = CorpusDocument(
|
| 94 |
+
text=text,
|
| 95 |
+
source=source,
|
| 96 |
+
metadata=metadata or {}
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
self.documents.append(doc)
|
| 100 |
+
self.stats.total_documents += 1
|
| 101 |
+
self.stats.total_words += doc.word_count
|
| 102 |
+
self.stats.total_chars += len(text)
|
| 103 |
+
self.stats.by_source[source] = self.stats.by_source.get(source, 0) + 1
|
| 104 |
+
|
| 105 |
+
def _clean_text(self, text: str) -> str:
|
| 106 |
+
"""Clean and normalize text."""
|
| 107 |
+
# Remove excessive whitespace
|
| 108 |
+
text = re.sub(r'\s+', ' ', text)
|
| 109 |
+
# Remove special characters but keep financial symbols
|
| 110 |
+
text = re.sub(r'[^\w\sβΉ$β¬Β£Β₯.,;:!?@#%&*()[\]{}<>+=\-/\\|\'\"Β°\n]', '', text)
|
| 111 |
+
# Normalize newlines
|
| 112 |
+
text = re.sub(r'\n{3,}', '\n\n', text)
|
| 113 |
+
return text.strip()
|
| 114 |
+
|
| 115 |
+
def add_glossary(self):
|
| 116 |
+
"""Add banking glossary to corpus."""
|
| 117 |
+
from src.data.banking_glossary import get_full_glossary
|
| 118 |
+
|
| 119 |
+
glossary = get_full_glossary()
|
| 120 |
+
|
| 121 |
+
# Split into sections
|
| 122 |
+
sections = glossary.split('\n\n')
|
| 123 |
+
for section in sections:
|
| 124 |
+
if len(section.strip()) > 50:
|
| 125 |
+
self.add_document(
|
| 126 |
+
text=section.strip(),
|
| 127 |
+
source="glossary",
|
| 128 |
+
metadata={"type": "banking_glossary"}
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
logger.info(f"Added glossary: {self.stats.by_source.get('glossary', 0)} sections")
|
| 132 |
+
|
| 133 |
+
def add_emails_from_mbox(self, mbox_path: str):
|
| 134 |
+
"""Extract and add emails from MBOX file."""
|
| 135 |
+
import mailbox
|
| 136 |
+
from bs4 import BeautifulSoup
|
| 137 |
+
|
| 138 |
+
mbox_path = Path(mbox_path)
|
| 139 |
+
if not mbox_path.exists():
|
| 140 |
+
logger.warning(f"MBOX file not found: {mbox_path}")
|
| 141 |
+
return
|
| 142 |
+
|
| 143 |
+
logger.info(f"Processing MBOX: {mbox_path}")
|
| 144 |
+
|
| 145 |
+
mbox = mailbox.mbox(str(mbox_path))
|
| 146 |
+
count = 0
|
| 147 |
+
|
| 148 |
+
for message in mbox:
|
| 149 |
+
try:
|
| 150 |
+
# Get sender
|
| 151 |
+
sender = message.get('From', '')
|
| 152 |
+
subject = message.get('Subject', '')
|
| 153 |
+
|
| 154 |
+
# Filter for bank-related emails
|
| 155 |
+
if not self._is_financial_email(sender, subject):
|
| 156 |
+
continue
|
| 157 |
+
|
| 158 |
+
# Extract body
|
| 159 |
+
body = self._extract_email_body(message)
|
| 160 |
+
if not body:
|
| 161 |
+
continue
|
| 162 |
+
|
| 163 |
+
self.add_document(
|
| 164 |
+
text=f"Subject: {subject}\n\n{body}",
|
| 165 |
+
source="email",
|
| 166 |
+
metadata={
|
| 167 |
+
"sender": sender[:100],
|
| 168 |
+
"subject": subject[:200],
|
| 169 |
+
"date": message.get('Date', '')
|
| 170 |
+
}
|
| 171 |
+
)
|
| 172 |
+
count += 1
|
| 173 |
+
|
| 174 |
+
except Exception as e:
|
| 175 |
+
logger.debug(f"Error processing email: {e}")
|
| 176 |
+
|
| 177 |
+
logger.info(f"Added {count} financial emails")
|
| 178 |
+
|
| 179 |
+
def _is_financial_email(self, sender: str, subject: str) -> bool:
|
| 180 |
+
"""Check if email is finance-related."""
|
| 181 |
+
keywords = [
|
| 182 |
+
'bank', 'hdfc', 'icici', 'sbi', 'axis', 'kotak', 'yes bank',
|
| 183 |
+
'paytm', 'phonepe', 'gpay', 'google pay', 'amazon pay',
|
| 184 |
+
'mutual fund', 'investment', 'credit', 'debit', 'transaction',
|
| 185 |
+
'upi', 'neft', 'rtgs', 'imps', 'payment', 'transfer',
|
| 186 |
+
'loan', 'emi', 'insurance', 'lic', 'premium',
|
| 187 |
+
'zerodha', 'groww', 'upstox', 'cams', 'karvy',
|
| 188 |
+
'income tax', 'gst', 'tds', 'itr', 'form 16'
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
text = f"{sender} {subject}".lower()
|
| 192 |
+
return any(kw in text for kw in keywords)
|
| 193 |
+
|
| 194 |
+
def _extract_email_body(self, message) -> Optional[str]:
|
| 195 |
+
"""Extract text body from email message."""
|
| 196 |
+
from bs4 import BeautifulSoup
|
| 197 |
+
|
| 198 |
+
body = ""
|
| 199 |
+
|
| 200 |
+
if message.is_multipart():
|
| 201 |
+
for part in message.walk():
|
| 202 |
+
content_type = part.get_content_type()
|
| 203 |
+
if content_type == 'text/plain':
|
| 204 |
+
try:
|
| 205 |
+
body = part.get_payload(decode=True).decode('utf-8', errors='ignore')
|
| 206 |
+
break
|
| 207 |
+
except:
|
| 208 |
+
pass
|
| 209 |
+
elif content_type == 'text/html':
|
| 210 |
+
try:
|
| 211 |
+
html = part.get_payload(decode=True).decode('utf-8', errors='ignore')
|
| 212 |
+
soup = BeautifulSoup(html, 'html.parser')
|
| 213 |
+
body = soup.get_text(separator=' ', strip=True)
|
| 214 |
+
except:
|
| 215 |
+
pass
|
| 216 |
+
else:
|
| 217 |
+
try:
|
| 218 |
+
content_type = message.get_content_type()
|
| 219 |
+
payload = message.get_payload(decode=True)
|
| 220 |
+
if payload:
|
| 221 |
+
text = payload.decode('utf-8', errors='ignore')
|
| 222 |
+
if content_type == 'text/html':
|
| 223 |
+
soup = BeautifulSoup(text, 'html.parser')
|
| 224 |
+
body = soup.get_text(separator=' ', strip=True)
|
| 225 |
+
else:
|
| 226 |
+
body = text
|
| 227 |
+
except:
|
| 228 |
+
pass
|
| 229 |
+
|
| 230 |
+
return body.strip() if body else None
|
| 231 |
+
|
| 232 |
+
def add_statements_from_pdfs(self, pdf_dir: str):
|
| 233 |
+
"""Extract text from bank statement PDFs."""
|
| 234 |
+
try:
|
| 235 |
+
import pdfplumber
|
| 236 |
+
except ImportError:
|
| 237 |
+
logger.warning("pdfplumber not installed. Skipping PDF extraction.")
|
| 238 |
+
return
|
| 239 |
+
|
| 240 |
+
pdf_dir = Path(pdf_dir)
|
| 241 |
+
if not pdf_dir.exists():
|
| 242 |
+
logger.warning(f"PDF directory not found: {pdf_dir}")
|
| 243 |
+
return
|
| 244 |
+
|
| 245 |
+
pdf_files = list(pdf_dir.glob("**/*.pdf")) + list(pdf_dir.glob("**/*.PDF"))
|
| 246 |
+
logger.info(f"Found {len(pdf_files)} PDF files")
|
| 247 |
+
|
| 248 |
+
for pdf_path in pdf_files:
|
| 249 |
+
try:
|
| 250 |
+
with pdfplumber.open(pdf_path) as pdf:
|
| 251 |
+
full_text = ""
|
| 252 |
+
for page in pdf.pages:
|
| 253 |
+
text = page.extract_text()
|
| 254 |
+
if text:
|
| 255 |
+
full_text += text + "\n\n"
|
| 256 |
+
|
| 257 |
+
if full_text.strip():
|
| 258 |
+
self.add_document(
|
| 259 |
+
text=full_text,
|
| 260 |
+
source="statement",
|
| 261 |
+
metadata={
|
| 262 |
+
"filename": pdf_path.name,
|
| 263 |
+
"pages": len(pdf.pages)
|
| 264 |
+
}
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
except Exception as e:
|
| 268 |
+
logger.debug(f"Error processing {pdf_path.name}: {e}")
|
| 269 |
+
|
| 270 |
+
logger.info(f"Added {self.stats.by_source.get('statement', 0)} statements")
|
| 271 |
+
|
| 272 |
+
def add_text_files(self, dir_path: str, source: str):
|
| 273 |
+
"""Add all text files from a directory."""
|
| 274 |
+
dir_path = Path(dir_path)
|
| 275 |
+
if not dir_path.exists():
|
| 276 |
+
return
|
| 277 |
+
|
| 278 |
+
for txt_file in dir_path.glob("**/*.txt"):
|
| 279 |
+
try:
|
| 280 |
+
with open(txt_file, 'r', encoding='utf-8') as f:
|
| 281 |
+
text = f.read()
|
| 282 |
+
|
| 283 |
+
self.add_document(
|
| 284 |
+
text=text,
|
| 285 |
+
source=source,
|
| 286 |
+
metadata={"filename": txt_file.name}
|
| 287 |
+
)
|
| 288 |
+
except Exception as e:
|
| 289 |
+
logger.debug(f"Error reading {txt_file}: {e}")
|
| 290 |
+
|
| 291 |
+
logger.info(f"Added {self.stats.by_source.get(source, 0)} documents from {source}")
|
| 292 |
+
|
| 293 |
+
def add_custom_text(self, text: str, source: str = "custom"):
|
| 294 |
+
"""Add custom text to corpus."""
|
| 295 |
+
self.add_document(text=text, source=source)
|
| 296 |
+
|
| 297 |
+
def export(self, output_path: str = None) -> Path:
|
| 298 |
+
"""Export corpus to JSONL file."""
|
| 299 |
+
if output_path is None:
|
| 300 |
+
output_path = self.corpus_dir / "combined" / "corpus.jsonl"
|
| 301 |
+
|
| 302 |
+
output_path = Path(output_path)
|
| 303 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 304 |
+
|
| 305 |
+
with open(output_path, 'w', encoding='utf-8') as f:
|
| 306 |
+
for doc in self.documents:
|
| 307 |
+
f.write(json.dumps({"text": doc.text}) + '\n')
|
| 308 |
+
|
| 309 |
+
logger.info(f"Exported corpus to {output_path}")
|
| 310 |
+
return output_path
|
| 311 |
+
|
| 312 |
+
def export_detailed(self, output_path: str = None) -> Path:
|
| 313 |
+
"""Export corpus with metadata to JSONL."""
|
| 314 |
+
if output_path is None:
|
| 315 |
+
output_path = self.corpus_dir / "combined" / "corpus_detailed.jsonl"
|
| 316 |
+
|
| 317 |
+
output_path = Path(output_path)
|
| 318 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 319 |
+
|
| 320 |
+
with open(output_path, 'w', encoding='utf-8') as f:
|
| 321 |
+
for doc in self.documents:
|
| 322 |
+
f.write(json.dumps(doc.to_dict()) + '\n')
|
| 323 |
+
|
| 324 |
+
return output_path
|
| 325 |
+
|
| 326 |
+
def print_stats(self):
|
| 327 |
+
"""Print corpus statistics."""
|
| 328 |
+
print("\n" + "=" * 60)
|
| 329 |
+
print("π CORPUS STATISTICS")
|
| 330 |
+
print("=" * 60)
|
| 331 |
+
print(f"Total Documents: {self.stats.total_documents:,}")
|
| 332 |
+
print(f"Total Words: {self.stats.total_words:,}")
|
| 333 |
+
print(f"Est. Tokens: {self.stats.estimated_tokens():,}")
|
| 334 |
+
print(f"Total Chars: {self.stats.total_chars:,}")
|
| 335 |
+
print("\nBy Source:")
|
| 336 |
+
for source, count in sorted(self.stats.by_source.items()):
|
| 337 |
+
print(f" {source:15} {count:,} documents")
|
| 338 |
+
print("=" * 60)
|
| 339 |
+
|
| 340 |
+
# Check if sufficient for pre-training
|
| 341 |
+
tokens = self.stats.estimated_tokens()
|
| 342 |
+
if tokens >= 10_000_000:
|
| 343 |
+
print("β
Sufficient for domain pre-training (10M+ tokens)")
|
| 344 |
+
elif tokens >= 1_000_000:
|
| 345 |
+
print("β οΈ Marginal corpus size. Consider adding more data.")
|
| 346 |
+
else:
|
| 347 |
+
print("β Corpus too small. Need at least 1M tokens, ideally 10M+")
|
| 348 |
+
|
| 349 |
+
def analyze_vocabulary(self, top_n: int = 50) -> Dict[str, int]:
|
| 350 |
+
"""Analyze most common financial terms in corpus."""
|
| 351 |
+
all_text = " ".join(doc.text for doc in self.documents)
|
| 352 |
+
words = re.findall(r'\b[A-Za-z]{2,}\b', all_text.lower())
|
| 353 |
+
|
| 354 |
+
# Focus on financial terms
|
| 355 |
+
financial_words = []
|
| 356 |
+
financial_keywords = {
|
| 357 |
+
'upi', 'neft', 'rtgs', 'imps', 'bank', 'account', 'transaction',
|
| 358 |
+
'payment', 'credit', 'debit', 'balance', 'transfer', 'amount',
|
| 359 |
+
'rupees', 'rs', 'inr', 'loan', 'emi', 'interest', 'deposit',
|
| 360 |
+
'withdrawal', 'statement', 'passbook', 'cheque', 'card'
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
for word in words:
|
| 364 |
+
if word in financial_keywords or any(kw in word for kw in financial_keywords):
|
| 365 |
+
financial_words.append(word)
|
| 366 |
+
|
| 367 |
+
return dict(Counter(financial_words).most_common(top_n))
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def main():
|
| 371 |
+
"""Main function to collect corpus."""
|
| 372 |
+
print("=" * 60)
|
| 373 |
+
print("π¦ Domain Pre-training Corpus Collector")
|
| 374 |
+
print("=" * 60)
|
| 375 |
+
|
| 376 |
+
collector = CorpusCollector()
|
| 377 |
+
|
| 378 |
+
# 1. Add glossary (always available)
|
| 379 |
+
print("\nπ Adding banking glossary...")
|
| 380 |
+
collector.add_glossary()
|
| 381 |
+
|
| 382 |
+
# 2. Check for MBOX file
|
| 383 |
+
mbox_paths = [
|
| 384 |
+
Path("data/raw/All mail Including Spam and Trash.mbox"),
|
| 385 |
+
Path("data/raw/emails.mbox"),
|
| 386 |
+
Path.home() / "Downloads" / "Takeout" / "Mail" / "All mail Including Spam and Trash.mbox"
|
| 387 |
+
]
|
| 388 |
+
|
| 389 |
+
for mbox_path in mbox_paths:
|
| 390 |
+
if mbox_path.exists():
|
| 391 |
+
print(f"\nπ§ Processing emails from {mbox_path}...")
|
| 392 |
+
collector.add_emails_from_mbox(str(mbox_path))
|
| 393 |
+
break
|
| 394 |
+
else:
|
| 395 |
+
print("\nβ οΈ No MBOX file found. Export Gmail via Google Takeout.")
|
| 396 |
+
|
| 397 |
+
# 3. Check for PDFs
|
| 398 |
+
pdf_dirs = [
|
| 399 |
+
Path("data/raw/pdfs"),
|
| 400 |
+
Path("data/raw/statements"),
|
| 401 |
+
]
|
| 402 |
+
|
| 403 |
+
for pdf_dir in pdf_dirs:
|
| 404 |
+
if pdf_dir.exists():
|
| 405 |
+
print(f"\nπ Extracting text from PDFs in {pdf_dir}...")
|
| 406 |
+
collector.add_statements_from_pdfs(str(pdf_dir))
|
| 407 |
+
|
| 408 |
+
# 4. Check for additional text files
|
| 409 |
+
additional_dirs = [
|
| 410 |
+
("data/corpus/rbi", "rbi"),
|
| 411 |
+
("data/corpus/npci", "npci"),
|
| 412 |
+
("data/corpus/news", "news"),
|
| 413 |
+
]
|
| 414 |
+
|
| 415 |
+
for dir_path, source in additional_dirs:
|
| 416 |
+
if Path(dir_path).exists():
|
| 417 |
+
print(f"\nπ Adding {source} documents...")
|
| 418 |
+
collector.add_text_files(dir_path, source)
|
| 419 |
+
|
| 420 |
+
# Print stats
|
| 421 |
+
collector.print_stats()
|
| 422 |
+
|
| 423 |
+
# Export if we have data
|
| 424 |
+
if collector.documents:
|
| 425 |
+
output = collector.export()
|
| 426 |
+
print(f"\nπΎ Corpus saved to: {output}")
|
| 427 |
+
|
| 428 |
+
# Also save detailed version
|
| 429 |
+
collector.export_detailed()
|
| 430 |
+
|
| 431 |
+
return collector
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
if __name__ == "__main__":
|
| 435 |
+
main()
|
scripts/create_benchmark.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Create Held-Out Benchmark from Real Emails.
|
| 3 |
+
|
| 4 |
+
Extracts 100 real financial emails from the MBOX file,
|
| 5 |
+
ensures they were NOT used in training, and creates a
|
| 6 |
+
benchmark for measuring real-world performance.
|
| 7 |
+
|
| 8 |
+
Author: Ranjit Behera
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import random
|
| 13 |
+
import re
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
# Paths
|
| 17 |
+
CORPUS_FILE = Path("data/corpus/emails/financial_emails.jsonl")
|
| 18 |
+
TRAIN_FILE = Path("data/training/train.jsonl")
|
| 19 |
+
BENCHMARK_FILE = Path("data/benchmark/real_emails_benchmark.json")
|
| 20 |
+
|
| 21 |
+
def load_corpus():
|
| 22 |
+
"""Load the extracted financial emails."""
|
| 23 |
+
emails = []
|
| 24 |
+
with open(CORPUS_FILE, 'r') as f:
|
| 25 |
+
for line in f:
|
| 26 |
+
try:
|
| 27 |
+
data = json.loads(line)
|
| 28 |
+
emails.append(data)
|
| 29 |
+
except:
|
| 30 |
+
continue
|
| 31 |
+
return emails
|
| 32 |
+
|
| 33 |
+
def load_training_texts():
|
| 34 |
+
"""Load training data to exclude from benchmark."""
|
| 35 |
+
texts = set()
|
| 36 |
+
with open(TRAIN_FILE, 'r') as f:
|
| 37 |
+
for line in f:
|
| 38 |
+
try:
|
| 39 |
+
data = json.loads(line)
|
| 40 |
+
# Get first 100 chars as fingerprint
|
| 41 |
+
text = data.get('text', '')[:100]
|
| 42 |
+
texts.add(text)
|
| 43 |
+
except:
|
| 44 |
+
continue
|
| 45 |
+
return texts
|
| 46 |
+
|
| 47 |
+
def extract_entities_from_email(email_body: str) -> dict:
|
| 48 |
+
"""Auto-extract entities from email text for labeling."""
|
| 49 |
+
entities = {
|
| 50 |
+
'amount': '',
|
| 51 |
+
'type': '',
|
| 52 |
+
'date': '',
|
| 53 |
+
'account': '',
|
| 54 |
+
'reference': '',
|
| 55 |
+
'merchant': '',
|
| 56 |
+
'bank': ''
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
text = email_body
|
| 60 |
+
text_lower = text.lower()
|
| 61 |
+
|
| 62 |
+
# Detect bank
|
| 63 |
+
if 'hdfc' in text_lower:
|
| 64 |
+
entities['bank'] = 'hdfc'
|
| 65 |
+
elif 'icici' in text_lower:
|
| 66 |
+
entities['bank'] = 'icici'
|
| 67 |
+
elif 'sbi' in text_lower:
|
| 68 |
+
entities['bank'] = 'sbi'
|
| 69 |
+
elif 'axis' in text_lower:
|
| 70 |
+
entities['bank'] = 'axis'
|
| 71 |
+
elif 'kotak' in text_lower:
|
| 72 |
+
entities['bank'] = 'kotak'
|
| 73 |
+
elif 'phonepe' in text_lower:
|
| 74 |
+
entities['bank'] = 'phonepe'
|
| 75 |
+
elif 'gpay' in text_lower or 'google pay' in text_lower:
|
| 76 |
+
entities['bank'] = 'gpay'
|
| 77 |
+
elif 'paytm' in text_lower:
|
| 78 |
+
entities['bank'] = 'paytm'
|
| 79 |
+
|
| 80 |
+
# Detect type
|
| 81 |
+
if 'debited' in text_lower or 'sent' in text_lower or 'paid' in text_lower:
|
| 82 |
+
entities['type'] = 'debit'
|
| 83 |
+
elif 'credited' in text_lower or 'received' in text_lower:
|
| 84 |
+
entities['type'] = 'credit'
|
| 85 |
+
|
| 86 |
+
# Extract amount - various patterns
|
| 87 |
+
amount_patterns = [
|
| 88 |
+
r'Rs\.?\s*([\d,]+\.?\d*)',
|
| 89 |
+
r'INR\s*([\d,]+\.?\d*)',
|
| 90 |
+
r'βΉ\s*([\d,]+\.?\d*)',
|
| 91 |
+
r'([\d,]+\.?\d*)\s*has been (?:debited|credited)'
|
| 92 |
+
]
|
| 93 |
+
for pattern in amount_patterns:
|
| 94 |
+
match = re.search(pattern, text, re.IGNORECASE)
|
| 95 |
+
if match:
|
| 96 |
+
entities['amount'] = match.group(1).replace(',', '')
|
| 97 |
+
break
|
| 98 |
+
|
| 99 |
+
# Extract account
|
| 100 |
+
account_patterns = [
|
| 101 |
+
r'account\s*(?:no\.?|number|#|XX|X)?\s*(\d{4})',
|
| 102 |
+
r'A/c\s*(?:XX|X)?(\d{4})',
|
| 103 |
+
r'a/c\s*(\d{4})',
|
| 104 |
+
r'XX(\d{4})',
|
| 105 |
+
r'X(\d{4})'
|
| 106 |
+
]
|
| 107 |
+
for pattern in account_patterns:
|
| 108 |
+
match = re.search(pattern, text, re.IGNORECASE)
|
| 109 |
+
if match:
|
| 110 |
+
entities['account'] = match.group(1)
|
| 111 |
+
break
|
| 112 |
+
|
| 113 |
+
# Extract date - various formats
|
| 114 |
+
date_patterns = [
|
| 115 |
+
r'on\s*(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})',
|
| 116 |
+
r'(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})',
|
| 117 |
+
r'(\d{1,2}\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\w*\s+\d{4})',
|
| 118 |
+
]
|
| 119 |
+
for pattern in date_patterns:
|
| 120 |
+
match = re.search(pattern, text, re.IGNORECASE)
|
| 121 |
+
if match:
|
| 122 |
+
entities['date'] = match.group(1)
|
| 123 |
+
break
|
| 124 |
+
|
| 125 |
+
# Extract reference
|
| 126 |
+
ref_patterns = [
|
| 127 |
+
r'(?:UPI\s*)?(?:Ref(?:erence)?(?:\s*(?:No|Number|#|:))?\.?\s*:?\s*)(\d{10,})',
|
| 128 |
+
r'transaction reference number is\s*(\d+)',
|
| 129 |
+
r'Txn[:\s]*(\d+)',
|
| 130 |
+
]
|
| 131 |
+
for pattern in ref_patterns:
|
| 132 |
+
match = re.search(pattern, text, re.IGNORECASE)
|
| 133 |
+
if match:
|
| 134 |
+
entities['reference'] = match.group(1)
|
| 135 |
+
break
|
| 136 |
+
|
| 137 |
+
# Extract merchant from VPA
|
| 138 |
+
vpa_match = re.search(r'VPA\s+(\w+)@\w+\s+([A-Z][A-Za-z\s]+)', text)
|
| 139 |
+
if vpa_match:
|
| 140 |
+
entities['merchant'] = vpa_match.group(2).strip().lower()
|
| 141 |
+
else:
|
| 142 |
+
# Try common merchants
|
| 143 |
+
merchants = ['swiggy', 'zomato', 'amazon', 'flipkart', 'uber', 'ola', 'rapido', 'bigbasket', 'blinkit', 'zepto']
|
| 144 |
+
for m in merchants:
|
| 145 |
+
if m in text_lower:
|
| 146 |
+
entities['merchant'] = m
|
| 147 |
+
break
|
| 148 |
+
|
| 149 |
+
return entities
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def create_benchmark(n_samples=100):
|
| 153 |
+
"""Create held-out benchmark from real emails."""
|
| 154 |
+
print("=" * 60)
|
| 155 |
+
print("π CREATING HELD-OUT BENCHMARK")
|
| 156 |
+
print("=" * 60)
|
| 157 |
+
|
| 158 |
+
# Load data
|
| 159 |
+
print(f"\n1. Loading corpus from {CORPUS_FILE}...")
|
| 160 |
+
corpus = load_corpus()
|
| 161 |
+
print(f" Found {len(corpus)} financial emails")
|
| 162 |
+
|
| 163 |
+
print(f"\n2. Loading training data to exclude...")
|
| 164 |
+
train_texts = load_training_texts()
|
| 165 |
+
print(f" Found {len(train_texts)} training samples to exclude")
|
| 166 |
+
|
| 167 |
+
# Filter for transaction emails
|
| 168 |
+
print(f"\n3. Filtering for transaction emails...")
|
| 169 |
+
candidates = []
|
| 170 |
+
for email in corpus:
|
| 171 |
+
body = email.get('body', '')
|
| 172 |
+
|
| 173 |
+
# Skip if too short
|
| 174 |
+
if len(body) < 50:
|
| 175 |
+
continue
|
| 176 |
+
|
| 177 |
+
# Must have transaction keywords
|
| 178 |
+
body_lower = body.lower()
|
| 179 |
+
has_transaction = any(x in body_lower for x in ['debited', 'credited', 'received', 'sent'])
|
| 180 |
+
has_amount = any(x in body_lower for x in ['rs.', 'rs ', 'inr', 'βΉ'])
|
| 181 |
+
|
| 182 |
+
if has_transaction and has_amount:
|
| 183 |
+
# Auto-extract entities
|
| 184 |
+
entities = extract_entities_from_email(body)
|
| 185 |
+
|
| 186 |
+
candidates.append({
|
| 187 |
+
'text': body,
|
| 188 |
+
'subject': email.get('subject', ''),
|
| 189 |
+
'sender': email.get('sender', ''),
|
| 190 |
+
'date': email.get('date', ''),
|
| 191 |
+
'expected_entities': entities
|
| 192 |
+
})
|
| 193 |
+
|
| 194 |
+
print(f" Found {len(candidates)} transaction emails")
|
| 195 |
+
|
| 196 |
+
# Sample randomly
|
| 197 |
+
print(f"\n4. Sampling {n_samples} emails for benchmark...")
|
| 198 |
+
random.seed(42) # Reproducible
|
| 199 |
+
benchmark = random.sample(candidates, min(n_samples, len(candidates)))
|
| 200 |
+
|
| 201 |
+
# Add IDs
|
| 202 |
+
for i, sample in enumerate(benchmark):
|
| 203 |
+
sample['id'] = i + 1
|
| 204 |
+
sample['auto_labeled'] = True
|
| 205 |
+
sample['verified'] = False
|
| 206 |
+
|
| 207 |
+
# Save benchmark
|
| 208 |
+
BENCHMARK_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 209 |
+
with open(BENCHMARK_FILE, 'w') as f:
|
| 210 |
+
json.dump(benchmark, f, indent=2, ensure_ascii=False)
|
| 211 |
+
|
| 212 |
+
print(f"\nβ
Benchmark saved to {BENCHMARK_FILE}")
|
| 213 |
+
print(f" Total samples: {len(benchmark)}")
|
| 214 |
+
|
| 215 |
+
# Stats
|
| 216 |
+
banks = {}
|
| 217 |
+
for s in benchmark:
|
| 218 |
+
bank = s['expected_entities'].get('bank', 'unknown')
|
| 219 |
+
banks[bank] = banks.get(bank, 0) + 1
|
| 220 |
+
|
| 221 |
+
print("\nπ Benchmark by Bank:")
|
| 222 |
+
for bank, count in sorted(banks.items()):
|
| 223 |
+
print(f" {bank.upper():10} {count}")
|
| 224 |
+
|
| 225 |
+
# Show sample
|
| 226 |
+
print("\n" + "=" * 60)
|
| 227 |
+
print("π§ SAMPLE EMAIL FROM BENCHMARK:")
|
| 228 |
+
print("=" * 60)
|
| 229 |
+
if benchmark:
|
| 230 |
+
sample = benchmark[0]
|
| 231 |
+
print(f"Subject: {sample.get('subject', 'N/A')}")
|
| 232 |
+
print(f"Text: {sample['text'][:300]}...")
|
| 233 |
+
print(f"\nAuto-extracted entities:")
|
| 234 |
+
for k, v in sample['expected_entities'].items():
|
| 235 |
+
if v:
|
| 236 |
+
print(f" {k}: {v}")
|
| 237 |
+
|
| 238 |
+
return benchmark
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
if __name__ == "__main__":
|
| 242 |
+
create_benchmark(n_samples=100)
|
scripts/create_clean_benchmark.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Create Multi-Bank Clean Benchmark.
|
| 3 |
+
|
| 4 |
+
Creates a high-quality benchmark from real transaction emails
|
| 5 |
+
across multiple banks: HDFC, ICICI, SBI, Axis, Kotak, PhonePe, GPay, Paytm.
|
| 6 |
+
|
| 7 |
+
Author: Ranjit Behera
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import re
|
| 12 |
+
import random
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from collections import defaultdict
|
| 15 |
+
|
| 16 |
+
CORPUS_FILE = Path("data/corpus/emails/financial_emails.jsonl")
|
| 17 |
+
BENCHMARK_FILE = Path("data/benchmark/multi_bank_benchmark.json")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def detect_bank(body: str, sender: str = "") -> str:
|
| 21 |
+
"""Detect bank from email content and sender."""
|
| 22 |
+
text = (body + " " + sender).lower()
|
| 23 |
+
|
| 24 |
+
if 'hdfc' in text:
|
| 25 |
+
return 'hdfc'
|
| 26 |
+
elif 'icici' in text:
|
| 27 |
+
return 'icici'
|
| 28 |
+
elif 'sbi' in text or 'state bank' in text:
|
| 29 |
+
return 'sbi'
|
| 30 |
+
elif 'axis' in text:
|
| 31 |
+
return 'axis'
|
| 32 |
+
elif 'kotak' in text:
|
| 33 |
+
return 'kotak'
|
| 34 |
+
elif 'phonepe' in text:
|
| 35 |
+
return 'phonepe'
|
| 36 |
+
elif 'gpay' in text or 'google pay' in text:
|
| 37 |
+
return 'gpay'
|
| 38 |
+
elif 'paytm' in text:
|
| 39 |
+
return 'paytm'
|
| 40 |
+
|
| 41 |
+
return ''
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def extract_entities(body: str, bank: str) -> dict:
|
| 45 |
+
"""Extract entities from email based on bank format."""
|
| 46 |
+
entities = {
|
| 47 |
+
'amount': '',
|
| 48 |
+
'type': '',
|
| 49 |
+
'date': '',
|
| 50 |
+
'account': '',
|
| 51 |
+
'reference': '',
|
| 52 |
+
'merchant': '',
|
| 53 |
+
'bank': bank
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
# Amount patterns (works across banks)
|
| 57 |
+
amount_patterns = [
|
| 58 |
+
r'Rs\.?\s*([\d,]+\.?\d*)',
|
| 59 |
+
r'INR\s*([\d,]+\.?\d*)',
|
| 60 |
+
r'βΉ\s*([\d,]+\.?\d*)',
|
| 61 |
+
]
|
| 62 |
+
for pattern in amount_patterns:
|
| 63 |
+
match = re.search(pattern, body, re.IGNORECASE)
|
| 64 |
+
if match:
|
| 65 |
+
entities['amount'] = match.group(1).replace(',', '')
|
| 66 |
+
break
|
| 67 |
+
|
| 68 |
+
# Type detection
|
| 69 |
+
body_lower = body.lower()
|
| 70 |
+
if any(x in body_lower for x in ['debited', 'sent', 'paid', 'payment of']):
|
| 71 |
+
entities['type'] = 'debit'
|
| 72 |
+
elif any(x in body_lower for x in ['credited', 'received', 'added']):
|
| 73 |
+
entities['type'] = 'credit'
|
| 74 |
+
|
| 75 |
+
# Bank-specific patterns
|
| 76 |
+
if bank == 'hdfc':
|
| 77 |
+
# HDFC: "from account 3545" or "A/c **3545"
|
| 78 |
+
match = re.search(r'(?:account|A/c\s*\**)(\d{4})', body)
|
| 79 |
+
if match:
|
| 80 |
+
entities['account'] = match.group(1)
|
| 81 |
+
|
| 82 |
+
# Date: "on 22-12-25"
|
| 83 |
+
match = re.search(r'on\s*(\d{1,2}-\d{1,2}-\d{2,4})', body)
|
| 84 |
+
if match:
|
| 85 |
+
entities['date'] = match.group(1)
|
| 86 |
+
|
| 87 |
+
# Reference: "reference number is 535680069988"
|
| 88 |
+
match = re.search(r'reference number is\s*(\d{10,})', body)
|
| 89 |
+
if match:
|
| 90 |
+
entities['reference'] = match.group(1)
|
| 91 |
+
|
| 92 |
+
elif bank == 'icici':
|
| 93 |
+
# ICICI: "A/c XX5061" or "Acct XX4872"
|
| 94 |
+
match = re.search(r'(?:A/c|Acct)\s*XX(\d{4})', body, re.IGNORECASE)
|
| 95 |
+
if match:
|
| 96 |
+
entities['account'] = match.group(1)
|
| 97 |
+
|
| 98 |
+
# Date: "on 11112025" or "on 13 Nov 2025"
|
| 99 |
+
match = re.search(r'on\s*(\d{8}|\d{1,2}\s+\w+\s+\d{4}|\d{1,2}-\d{1,2}-\d{2,4})', body)
|
| 100 |
+
if match:
|
| 101 |
+
entities['date'] = match.group(1)
|
| 102 |
+
|
| 103 |
+
# Reference: "Ref:230788137103" or "IMPS Ref 928612436713"
|
| 104 |
+
match = re.search(r'Ref[:\s]*(\d{10,})', body, re.IGNORECASE)
|
| 105 |
+
if match:
|
| 106 |
+
entities['reference'] = match.group(1)
|
| 107 |
+
|
| 108 |
+
elif bank == 'sbi':
|
| 109 |
+
# SBI: "a/c XX9666" or "A/c X2771"
|
| 110 |
+
match = re.search(r'[Aa]/c\s*X+(\d{4})', body)
|
| 111 |
+
if match:
|
| 112 |
+
entities['account'] = match.group(1)
|
| 113 |
+
|
| 114 |
+
# Date
|
| 115 |
+
match = re.search(r'on\s*(\d{1,2}-\d{1,2}-\d{2,4}|\d{1,2}/\d{1,2}/\d{4}|\d{1,2}\s+\w+\s+\d{4})', body)
|
| 116 |
+
if match:
|
| 117 |
+
entities['date'] = match.group(1)
|
| 118 |
+
|
| 119 |
+
# Reference
|
| 120 |
+
match = re.search(r'Ref\s*(\d{10,})', body, re.IGNORECASE)
|
| 121 |
+
if match:
|
| 122 |
+
entities['reference'] = match.group(1)
|
| 123 |
+
|
| 124 |
+
elif bank == 'axis':
|
| 125 |
+
# Axis: "Acct XX4185" or "A/c XX3041"
|
| 126 |
+
match = re.search(r'(?:Acct|A/c)\s*XX(\d{4})', body, re.IGNORECASE)
|
| 127 |
+
if match:
|
| 128 |
+
entities['account'] = match.group(1)
|
| 129 |
+
|
| 130 |
+
# Date
|
| 131 |
+
match = re.search(r'on\s*(\d{8}|\d{1,2}-\d{1,2}-\d{4}|\d{1,2}/\d{1,2}/\d{4})', body)
|
| 132 |
+
if match:
|
| 133 |
+
entities['date'] = match.group(1)
|
| 134 |
+
|
| 135 |
+
# Reference
|
| 136 |
+
match = re.search(r'Ref\s*(\d{10,})', body, re.IGNORECASE)
|
| 137 |
+
if match:
|
| 138 |
+
entities['reference'] = match.group(1)
|
| 139 |
+
|
| 140 |
+
elif bank == 'kotak':
|
| 141 |
+
# Kotak: "A/c XX6934" or "A/c 9817"
|
| 142 |
+
match = re.search(r'A/c\s*(?:XX)?(\d{4})', body, re.IGNORECASE)
|
| 143 |
+
if match:
|
| 144 |
+
entities['account'] = match.group(1)
|
| 145 |
+
|
| 146 |
+
# Date
|
| 147 |
+
match = re.search(r'on\s*(\d{8}|\d{1,2}-\d{1,2}-\d{2,4}|\d{1,2}\s+\w+\s+\d{4})', body)
|
| 148 |
+
if match:
|
| 149 |
+
entities['date'] = match.group(1)
|
| 150 |
+
|
| 151 |
+
# Reference
|
| 152 |
+
match = re.search(r'Ref[:\s.]*(\d{10,})', body, re.IGNORECASE)
|
| 153 |
+
if match:
|
| 154 |
+
entities['reference'] = match.group(1)
|
| 155 |
+
|
| 156 |
+
elif bank in ['phonepe', 'gpay', 'paytm']:
|
| 157 |
+
# Payment apps: various patterns
|
| 158 |
+
match = re.search(r'(?:a/c|account)\s*(?:XX)?(\d{4})', body, re.IGNORECASE)
|
| 159 |
+
if match:
|
| 160 |
+
entities['account'] = match.group(1)
|
| 161 |
+
|
| 162 |
+
# Date
|
| 163 |
+
match = re.search(r'(\d{1,2}[-/]\d{1,2}[-/]\d{2,4}|\d{1,2}\s+\w+\s+\d{4})', body)
|
| 164 |
+
if match:
|
| 165 |
+
entities['date'] = match.group(1)
|
| 166 |
+
|
| 167 |
+
# Reference/Txn ID
|
| 168 |
+
match = re.search(r'(?:Ref|Txn\s*ID)[:\s]*(\d{10,})', body, re.IGNORECASE)
|
| 169 |
+
if match:
|
| 170 |
+
entities['reference'] = match.group(1)
|
| 171 |
+
|
| 172 |
+
# Merchant from VPA (works across banks)
|
| 173 |
+
vpa_match = re.search(r'VPA[:\s]+\S+\s+([A-Z][A-Za-z\s]+?)(?:\s+on|\s+\d|$)', body)
|
| 174 |
+
if vpa_match:
|
| 175 |
+
merchant = vpa_match.group(1).strip().lower()
|
| 176 |
+
if len(merchant) > 2 and len(merchant) < 50:
|
| 177 |
+
entities['merchant'] = merchant
|
| 178 |
+
|
| 179 |
+
# Also try UPI: pattern
|
| 180 |
+
if not entities['merchant']:
|
| 181 |
+
upi_match = re.search(r'UPI[:\s-]+([A-Za-z]+)', body)
|
| 182 |
+
if upi_match:
|
| 183 |
+
entities['merchant'] = upi_match.group(1).lower()
|
| 184 |
+
|
| 185 |
+
return entities
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def create_multi_bank_benchmark():
|
| 189 |
+
"""Create benchmark with multiple banks."""
|
| 190 |
+
print("=" * 60)
|
| 191 |
+
print("π CREATING MULTI-BANK BENCHMARK")
|
| 192 |
+
print("=" * 60)
|
| 193 |
+
|
| 194 |
+
# Collect transactions by bank
|
| 195 |
+
bank_transactions = defaultdict(list)
|
| 196 |
+
|
| 197 |
+
with open(CORPUS_FILE, 'r') as f:
|
| 198 |
+
for line in f:
|
| 199 |
+
try:
|
| 200 |
+
data = json.loads(line)
|
| 201 |
+
body = data.get('body', '')
|
| 202 |
+
sender = data.get('sender', '')
|
| 203 |
+
|
| 204 |
+
# Must have transaction keywords
|
| 205 |
+
body_lower = body.lower()
|
| 206 |
+
has_transaction = any(x in body_lower for x in
|
| 207 |
+
['debited', 'credited', 'received', 'sent', 'paid', 'payment'])
|
| 208 |
+
has_amount = any(x in body_lower for x in ['rs.', 'rs ', 'inr', 'βΉ'])
|
| 209 |
+
|
| 210 |
+
if not (has_transaction and has_amount and len(body) > 50):
|
| 211 |
+
continue
|
| 212 |
+
|
| 213 |
+
# Detect bank
|
| 214 |
+
bank = detect_bank(body, sender)
|
| 215 |
+
if not bank:
|
| 216 |
+
continue
|
| 217 |
+
|
| 218 |
+
# Extract entities
|
| 219 |
+
entities = extract_entities(body, bank)
|
| 220 |
+
|
| 221 |
+
# Only include if we have good extraction
|
| 222 |
+
if entities['amount'] and entities['type']:
|
| 223 |
+
bank_transactions[bank].append({
|
| 224 |
+
'text': body,
|
| 225 |
+
'expected_entities': entities,
|
| 226 |
+
'subject': data.get('subject', ''),
|
| 227 |
+
'verified': True
|
| 228 |
+
})
|
| 229 |
+
except:
|
| 230 |
+
continue
|
| 231 |
+
|
| 232 |
+
print("\nπ Transactions found by bank:")
|
| 233 |
+
for bank, txns in sorted(bank_transactions.items()):
|
| 234 |
+
print(f" {bank.upper():10} {len(txns):4} transactions")
|
| 235 |
+
|
| 236 |
+
# Sample from each bank (max 20 per bank)
|
| 237 |
+
random.seed(42)
|
| 238 |
+
benchmark = []
|
| 239 |
+
|
| 240 |
+
for bank, txns in bank_transactions.items():
|
| 241 |
+
# Deduplicate by reference if available
|
| 242 |
+
seen_refs = set()
|
| 243 |
+
unique_txns = []
|
| 244 |
+
for t in txns:
|
| 245 |
+
ref = t['expected_entities'].get('reference', '')
|
| 246 |
+
if ref:
|
| 247 |
+
if ref not in seen_refs:
|
| 248 |
+
seen_refs.add(ref)
|
| 249 |
+
unique_txns.append(t)
|
| 250 |
+
else:
|
| 251 |
+
unique_txns.append(t)
|
| 252 |
+
|
| 253 |
+
# Sample
|
| 254 |
+
sampled = random.sample(unique_txns, min(20, len(unique_txns)))
|
| 255 |
+
benchmark.extend(sampled)
|
| 256 |
+
|
| 257 |
+
# Add IDs
|
| 258 |
+
for i, sample in enumerate(benchmark):
|
| 259 |
+
sample['id'] = i + 1
|
| 260 |
+
|
| 261 |
+
# Shuffle
|
| 262 |
+
random.shuffle(benchmark)
|
| 263 |
+
|
| 264 |
+
# Save
|
| 265 |
+
BENCHMARK_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 266 |
+
with open(BENCHMARK_FILE, 'w') as f:
|
| 267 |
+
json.dump(benchmark, f, indent=2, ensure_ascii=False)
|
| 268 |
+
|
| 269 |
+
print(f"\nβ
Saved {len(benchmark)} samples to {BENCHMARK_FILE}")
|
| 270 |
+
|
| 271 |
+
# Stats by bank
|
| 272 |
+
bank_counts = defaultdict(int)
|
| 273 |
+
for s in benchmark:
|
| 274 |
+
bank_counts[s['expected_entities']['bank']] += 1
|
| 275 |
+
|
| 276 |
+
print("\nπ Benchmark composition:")
|
| 277 |
+
for bank, count in sorted(bank_counts.items()):
|
| 278 |
+
print(f" {bank.upper():10} {count:3} samples")
|
| 279 |
+
|
| 280 |
+
# Show sample from each bank
|
| 281 |
+
print("\nπ§ Sample from each bank:")
|
| 282 |
+
shown_banks = set()
|
| 283 |
+
for s in benchmark:
|
| 284 |
+
bank = s['expected_entities']['bank']
|
| 285 |
+
if bank not in shown_banks:
|
| 286 |
+
shown_banks.add(bank)
|
| 287 |
+
print(f"\n [{bank.upper()}]")
|
| 288 |
+
print(f" Amount: {s['expected_entities']['amount']}")
|
| 289 |
+
print(f" Type: {s['expected_entities']['type']}")
|
| 290 |
+
print(f" Text: {s['text'][:100]}...")
|
| 291 |
+
if len(shown_banks) >= 4:
|
| 292 |
+
break
|
| 293 |
+
|
| 294 |
+
return benchmark
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
if __name__ == "__main__":
|
| 298 |
+
create_multi_bank_benchmark()
|
scripts/create_multi_bank_test.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Create Multi-Bank Test Benchmark from Synthetic Data.
|
| 3 |
+
|
| 4 |
+
Creates test samples from the generated data to test v8.
|
| 5 |
+
Excludes training data by using different random seed.
|
| 6 |
+
|
| 7 |
+
Author: Ranjit Behera
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import random
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from scripts.generate_comprehensive_data import (
|
| 14 |
+
TEMPLATES, MERCHANTS, VPA_SUFFIXES, SENDERS, SENDER_BANKS,
|
| 15 |
+
LOCATIONS, REMARKS, generate_date, generate_time, generate_reference,
|
| 16 |
+
generate_account, generate_amount, generate_balance
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
BENCHMARK_FILE = Path("data/benchmark/multi_bank_test.json")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def generate_test_samples(n_per_bank=10):
|
| 23 |
+
"""Generate test samples with different random seed."""
|
| 24 |
+
random.seed(123) # Different from training
|
| 25 |
+
samples = []
|
| 26 |
+
|
| 27 |
+
for bank, templates in TEMPLATES.items():
|
| 28 |
+
for txn_type, template_list in templates.items():
|
| 29 |
+
for _ in range(n_per_bank // len(templates)):
|
| 30 |
+
template = random.choice(template_list)
|
| 31 |
+
|
| 32 |
+
merchant_info = random.choice(MERCHANTS)
|
| 33 |
+
sender_info = random.choice(SENDERS)
|
| 34 |
+
|
| 35 |
+
is_credit = "credit" in txn_type
|
| 36 |
+
|
| 37 |
+
data = {
|
| 38 |
+
"amount": generate_amount(),
|
| 39 |
+
"account": generate_account(),
|
| 40 |
+
"date": generate_date(),
|
| 41 |
+
"time": generate_time(),
|
| 42 |
+
"reference": generate_reference(),
|
| 43 |
+
"balance": generate_balance(),
|
| 44 |
+
"remarks": random.choice(REMARKS),
|
| 45 |
+
"vpa_suffix": random.choice(VPA_SUFFIXES),
|
| 46 |
+
"ref_prefix": f"260{random.randint(10, 99)}",
|
| 47 |
+
"atm_id": f"000{random.randint(1000, 9999)}",
|
| 48 |
+
"location": random.choice(LOCATIONS),
|
| 49 |
+
"sender_bank": random.choice(SENDER_BANKS),
|
| 50 |
+
"sender_acc": str(random.randint(1000, 9999)),
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
if is_credit:
|
| 54 |
+
data["sender"] = sender_info[0]
|
| 55 |
+
data["sender_name"] = sender_info[1]
|
| 56 |
+
else:
|
| 57 |
+
data["merchant"] = merchant_info[0]
|
| 58 |
+
data["merchant_name"] = merchant_info[2]
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
email_text = template.format(**data)
|
| 62 |
+
except KeyError:
|
| 63 |
+
continue
|
| 64 |
+
|
| 65 |
+
entities = {
|
| 66 |
+
"amount": data["amount"].replace(",", ""),
|
| 67 |
+
"type": "credit" if is_credit else "debit",
|
| 68 |
+
"date": data["date"],
|
| 69 |
+
"account": data["account"],
|
| 70 |
+
"reference": data["reference"],
|
| 71 |
+
"bank": bank,
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
if not is_credit:
|
| 75 |
+
entities["merchant"] = merchant_info[0]
|
| 76 |
+
|
| 77 |
+
samples.append({
|
| 78 |
+
"id": len(samples) + 1,
|
| 79 |
+
"text": email_text,
|
| 80 |
+
"expected_entities": entities,
|
| 81 |
+
"txn_type": txn_type,
|
| 82 |
+
"verified": True
|
| 83 |
+
})
|
| 84 |
+
|
| 85 |
+
return samples
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def main():
|
| 89 |
+
print("=" * 60)
|
| 90 |
+
print("π CREATING MULTI-BANK TEST BENCHMARK")
|
| 91 |
+
print("=" * 60)
|
| 92 |
+
|
| 93 |
+
samples = generate_test_samples(n_per_bank=10)
|
| 94 |
+
random.shuffle(samples)
|
| 95 |
+
|
| 96 |
+
# Save
|
| 97 |
+
BENCHMARK_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 98 |
+
with open(BENCHMARK_FILE, 'w') as f:
|
| 99 |
+
json.dump(samples, f, indent=2, ensure_ascii=False)
|
| 100 |
+
|
| 101 |
+
print(f"\nβ
Saved {len(samples)} test samples to {BENCHMARK_FILE}")
|
| 102 |
+
|
| 103 |
+
# Stats
|
| 104 |
+
from collections import Counter
|
| 105 |
+
bank_counts = Counter(s['expected_entities']['bank'] for s in samples)
|
| 106 |
+
|
| 107 |
+
print("\nπ By bank:")
|
| 108 |
+
for bank, count in sorted(bank_counts.items()):
|
| 109 |
+
print(f" {bank.upper():10} {count}")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if __name__ == "__main__":
|
| 113 |
+
main()
|
scripts/create_strict_benchmark.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Create Strict Transaction Benchmark.
|
| 3 |
+
|
| 4 |
+
Only includes real transaction alerts with clear patterns.
|
| 5 |
+
Excludes marketing, bill notifications, and investment updates.
|
| 6 |
+
|
| 7 |
+
Author: Ranjit Behera
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import re
|
| 12 |
+
import random
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from collections import defaultdict
|
| 15 |
+
|
| 16 |
+
CORPUS_FILE = Path("data/corpus/emails/financial_emails.jsonl")
|
| 17 |
+
BENCHMARK_FILE = Path("data/benchmark/strict_benchmark.json")
|
| 18 |
+
|
| 19 |
+
# Transaction patterns that indicate real transactions
|
| 20 |
+
TRANSACTION_PATTERNS = [
|
| 21 |
+
r'has been debited',
|
| 22 |
+
r'has been credited',
|
| 23 |
+
r'is debited from',
|
| 24 |
+
r'is credited to',
|
| 25 |
+
r'Rs\.\s*[\d,]+.*debited',
|
| 26 |
+
r'Rs\.\s*[\d,]+.*credited',
|
| 27 |
+
r'INR\s*[\d,]+.*debited',
|
| 28 |
+
r'INR\s*[\d,]+.*credited',
|
| 29 |
+
r'UPI transaction reference',
|
| 30 |
+
r'UPI Ref',
|
| 31 |
+
r'IMPS Ref',
|
| 32 |
+
r'NEFT Ref',
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
# Exclude patterns (marketing, bills, investments)
|
| 36 |
+
EXCLUDE_PATTERNS = [
|
| 37 |
+
r'welcome to your',
|
| 38 |
+
r'greetings of the day',
|
| 39 |
+
r'unsubscribe from',
|
| 40 |
+
r'skills that will get you',
|
| 41 |
+
r'daily digest',
|
| 42 |
+
r'top picks',
|
| 43 |
+
r'mutual fund nav',
|
| 44 |
+
r'market update',
|
| 45 |
+
r'job opportunity',
|
| 46 |
+
r'margin statement',
|
| 47 |
+
r'password reset',
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def is_transaction_email(body: str) -> bool:
|
| 52 |
+
"""Check if email is a real transaction alert."""
|
| 53 |
+
body_lower = body.lower()
|
| 54 |
+
|
| 55 |
+
# Must match at least one transaction pattern
|
| 56 |
+
has_transaction = any(re.search(p, body, re.IGNORECASE) for p in TRANSACTION_PATTERNS)
|
| 57 |
+
|
| 58 |
+
# Must not match exclude patterns
|
| 59 |
+
has_exclude = any(re.search(p, body_lower) for p in EXCLUDE_PATTERNS)
|
| 60 |
+
|
| 61 |
+
return has_transaction and not has_exclude
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def detect_bank(body: str, sender: str = "") -> str:
|
| 65 |
+
"""Detect bank from email."""
|
| 66 |
+
text = (body + " " + sender).lower()
|
| 67 |
+
|
| 68 |
+
# Priority order (more specific first)
|
| 69 |
+
if 'hdfc bank' in text or 'hdfcbank' in text:
|
| 70 |
+
return 'hdfc'
|
| 71 |
+
elif 'icici bank' in text:
|
| 72 |
+
return 'icici'
|
| 73 |
+
elif 'state bank' in text or 'sbi:' in text:
|
| 74 |
+
return 'sbi'
|
| 75 |
+
elif 'axis bank' in text:
|
| 76 |
+
return 'axis'
|
| 77 |
+
elif 'kotak' in text:
|
| 78 |
+
return 'kotak'
|
| 79 |
+
|
| 80 |
+
return ''
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def extract_entities(body: str, bank: str) -> dict:
|
| 84 |
+
"""Extract entities from transaction email."""
|
| 85 |
+
entities = {
|
| 86 |
+
'amount': '',
|
| 87 |
+
'type': '',
|
| 88 |
+
'date': '',
|
| 89 |
+
'account': '',
|
| 90 |
+
'reference': '',
|
| 91 |
+
'merchant': '',
|
| 92 |
+
'bank': bank
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
# Amount
|
| 96 |
+
match = re.search(r'Rs\.?\s*([\d,]+\.?\d*)', body, re.IGNORECASE)
|
| 97 |
+
if match:
|
| 98 |
+
entities['amount'] = match.group(1).replace(',', '')
|
| 99 |
+
else:
|
| 100 |
+
match = re.search(r'INR\s*([\d,]+\.?\d*)', body, re.IGNORECASE)
|
| 101 |
+
if match:
|
| 102 |
+
entities['amount'] = match.group(1).replace(',', '')
|
| 103 |
+
|
| 104 |
+
# Type
|
| 105 |
+
body_lower = body.lower()
|
| 106 |
+
if 'debited' in body_lower:
|
| 107 |
+
entities['type'] = 'debit'
|
| 108 |
+
elif 'credited' in body_lower:
|
| 109 |
+
entities['type'] = 'credit'
|
| 110 |
+
|
| 111 |
+
# Account (4 digits after XX or **)
|
| 112 |
+
match = re.search(r'(?:XX|X|\*\*|account\s*)(\d{4})', body, re.IGNORECASE)
|
| 113 |
+
if match:
|
| 114 |
+
entities['account'] = match.group(1)
|
| 115 |
+
|
| 116 |
+
# Date
|
| 117 |
+
match = re.search(r'on\s*(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})', body)
|
| 118 |
+
if match:
|
| 119 |
+
entities['date'] = match.group(1)
|
| 120 |
+
|
| 121 |
+
# Reference (12+ digit number)
|
| 122 |
+
ref_patterns = [
|
| 123 |
+
r'reference number is\s*(\d{10,})',
|
| 124 |
+
r'(?:Ref(?:erence)?[:\s.]*|UPI\s*Ref[:\s]*|IMPS\s*Ref[:\s]*)(\d{10,})',
|
| 125 |
+
]
|
| 126 |
+
for pattern in ref_patterns:
|
| 127 |
+
match = re.search(pattern, body, re.IGNORECASE)
|
| 128 |
+
if match:
|
| 129 |
+
entities['reference'] = match.group(1)
|
| 130 |
+
break
|
| 131 |
+
|
| 132 |
+
# Merchant from VPA
|
| 133 |
+
match = re.search(r'VPA[:\s]+\S+\s+([A-Z][A-Za-z\s]+?)(?:\s+on|\s+\d)', body)
|
| 134 |
+
if match:
|
| 135 |
+
entities['merchant'] = match.group(1).strip().lower()
|
| 136 |
+
|
| 137 |
+
return entities
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def create_strict_benchmark():
|
| 141 |
+
"""Create strictly filtered benchmark."""
|
| 142 |
+
print("=" * 60)
|
| 143 |
+
print("π CREATING STRICT TRANSACTION BENCHMARK")
|
| 144 |
+
print("=" * 60)
|
| 145 |
+
|
| 146 |
+
bank_transactions = defaultdict(list)
|
| 147 |
+
|
| 148 |
+
with open(CORPUS_FILE, 'r') as f:
|
| 149 |
+
for line in f:
|
| 150 |
+
try:
|
| 151 |
+
data = json.loads(line)
|
| 152 |
+
body = data.get('body', '')
|
| 153 |
+
sender = data.get('sender', '')
|
| 154 |
+
|
| 155 |
+
# Strict filtering
|
| 156 |
+
if not is_transaction_email(body):
|
| 157 |
+
continue
|
| 158 |
+
|
| 159 |
+
if len(body) < 50:
|
| 160 |
+
continue
|
| 161 |
+
|
| 162 |
+
# Detect bank
|
| 163 |
+
bank = detect_bank(body, sender)
|
| 164 |
+
if not bank:
|
| 165 |
+
continue
|
| 166 |
+
|
| 167 |
+
# Extract entities
|
| 168 |
+
entities = extract_entities(body, bank)
|
| 169 |
+
|
| 170 |
+
# Must have amount, type, and reference
|
| 171 |
+
if entities['amount'] and entities['type'] and entities['reference']:
|
| 172 |
+
bank_transactions[bank].append({
|
| 173 |
+
'text': body,
|
| 174 |
+
'expected_entities': entities,
|
| 175 |
+
'subject': data.get('subject', ''),
|
| 176 |
+
'verified': True
|
| 177 |
+
})
|
| 178 |
+
except:
|
| 179 |
+
continue
|
| 180 |
+
|
| 181 |
+
print("\nπ Strict transactions per bank:")
|
| 182 |
+
for bank, txns in sorted(bank_transactions.items()):
|
| 183 |
+
print(f" {bank.upper():10} {len(txns):4} transactions")
|
| 184 |
+
|
| 185 |
+
# Sample and deduplicate
|
| 186 |
+
random.seed(42)
|
| 187 |
+
benchmark = []
|
| 188 |
+
|
| 189 |
+
for bank, txns in bank_transactions.items():
|
| 190 |
+
# Deduplicate by reference
|
| 191 |
+
seen_refs = set()
|
| 192 |
+
unique = []
|
| 193 |
+
for t in txns:
|
| 194 |
+
ref = t['expected_entities']['reference']
|
| 195 |
+
if ref not in seen_refs:
|
| 196 |
+
seen_refs.add(ref)
|
| 197 |
+
unique.append(t)
|
| 198 |
+
|
| 199 |
+
sampled = random.sample(unique, min(15, len(unique)))
|
| 200 |
+
benchmark.extend(sampled)
|
| 201 |
+
|
| 202 |
+
for i, s in enumerate(benchmark):
|
| 203 |
+
s['id'] = i + 1
|
| 204 |
+
|
| 205 |
+
random.shuffle(benchmark)
|
| 206 |
+
|
| 207 |
+
# Save
|
| 208 |
+
BENCHMARK_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 209 |
+
with open(BENCHMARK_FILE, 'w') as f:
|
| 210 |
+
json.dump(benchmark, f, indent=2, ensure_ascii=False)
|
| 211 |
+
|
| 212 |
+
print(f"\nβ
Saved {len(benchmark)} samples to {BENCHMARK_FILE}")
|
| 213 |
+
|
| 214 |
+
# Stats
|
| 215 |
+
bank_counts = defaultdict(int)
|
| 216 |
+
for s in benchmark:
|
| 217 |
+
bank_counts[s['expected_entities']['bank']] += 1
|
| 218 |
+
|
| 219 |
+
print("\nπ Benchmark composition:")
|
| 220 |
+
for bank, count in sorted(bank_counts.items()):
|
| 221 |
+
print(f" {bank.upper():10} {count:3} samples")
|
| 222 |
+
|
| 223 |
+
# Show samples
|
| 224 |
+
print("\nπ§ Sample transaction:")
|
| 225 |
+
if benchmark:
|
| 226 |
+
s = benchmark[0]
|
| 227 |
+
print(f" Bank: {s['expected_entities']['bank'].upper()}")
|
| 228 |
+
print(f" Amount: {s['expected_entities']['amount']}")
|
| 229 |
+
print(f" Type: {s['expected_entities']['type']}")
|
| 230 |
+
print(f" Reference: {s['expected_entities']['reference']}")
|
| 231 |
+
print(f" Text: {s['text'][:150]}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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Domain Pre-training Script for MLX.
|
| 3 |
+
|
| 4 |
+
Performs continued pre-training on the financial domain corpus
|
| 5 |
+
to teach the model Indian banking/finance vocabulary before
|
| 6 |
+
task-specific fine-tuning.
|
| 7 |
+
|
| 8 |
+
Approach:
|
| 9 |
+
1. Load base Phi-3 model
|
| 10 |
+
2. Continue pre-training on financial corpus (1-2 epochs)
|
| 11 |
+
3. Save domain-adapted model
|
| 12 |
+
4. Use this as base for fine-tuning
|
| 13 |
+
|
| 14 |
+
Author: Ranjit Behera
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import subprocess
|
| 19 |
+
import sys
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Optional, Dict
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
import logging
|
| 24 |
+
|
| 25 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s")
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class PretrainingConfig:
|
| 31 |
+
"""Configuration for domain pre-training."""
|
| 32 |
+
|
| 33 |
+
# Paths
|
| 34 |
+
base_model: str = "models/base/phi3-mini"
|
| 35 |
+
corpus_file: str = "data/corpus/combined/corpus.jsonl"
|
| 36 |
+
output_dir: str = "models/domain-pretrained/phi3-finance"
|
| 37 |
+
|
| 38 |
+
# Training parameters
|
| 39 |
+
batch_size: int = 1
|
| 40 |
+
learning_rate: float = 5e-6 # Lower LR for pre-training
|
| 41 |
+
num_epochs: int = 1
|
| 42 |
+
max_seq_length: int = 512
|
| 43 |
+
save_every: int = 500
|
| 44 |
+
|
| 45 |
+
# LoRA parameters for efficient pre-training
|
| 46 |
+
use_lora: bool = True
|
| 47 |
+
lora_rank: int = 16 # Higher rank for pre-training
|
| 48 |
+
num_layers: int = 8 # More layers for pre-training (reduced from 16 for OOM)
|
| 49 |
+
|
| 50 |
+
def to_dict(self) -> Dict:
|
| 51 |
+
return {
|
| 52 |
+
"base_model": self.base_model,
|
| 53 |
+
"corpus_file": self.corpus_file,
|
| 54 |
+
"output_dir": self.output_dir,
|
| 55 |
+
"batch_size": self.batch_size,
|
| 56 |
+
"learning_rate": self.learning_rate,
|
| 57 |
+
"num_epochs": self.num_epochs,
|
| 58 |
+
"max_seq_length": self.max_seq_length,
|
| 59 |
+
"save_every": self.save_every,
|
| 60 |
+
"use_lora": self.use_lora,
|
| 61 |
+
"lora_rank": self.lora_rank,
|
| 62 |
+
"num_layers": self.num_layers
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class DomainPretrainer:
|
| 67 |
+
"""
|
| 68 |
+
Handles domain pre-training on financial corpus.
|
| 69 |
+
|
| 70 |
+
This uses MLX's continued pre-training capability to adapt
|
| 71 |
+
the base model to Indian financial domain.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self, config: PretrainingConfig = None):
|
| 75 |
+
self.config = config or PretrainingConfig()
|
| 76 |
+
self.project_root = Path.cwd()
|
| 77 |
+
|
| 78 |
+
def prepare_corpus(self) -> bool:
|
| 79 |
+
"""Verify and prepare corpus for pre-training."""
|
| 80 |
+
corpus_path = self.project_root / self.config.corpus_file
|
| 81 |
+
|
| 82 |
+
if not corpus_path.exists():
|
| 83 |
+
logger.error(f"Corpus file not found: {corpus_path}")
|
| 84 |
+
logger.info("Run scripts/corpus_collection/collect_corpus.py first")
|
| 85 |
+
return False
|
| 86 |
+
|
| 87 |
+
# Count documents and estimate tokens
|
| 88 |
+
with open(corpus_path) as f:
|
| 89 |
+
lines = f.readlines()
|
| 90 |
+
|
| 91 |
+
total_words = 0
|
| 92 |
+
for line in lines:
|
| 93 |
+
try:
|
| 94 |
+
doc = json.loads(line)
|
| 95 |
+
total_words += len(doc.get("text", "").split())
|
| 96 |
+
except:
|
| 97 |
+
pass
|
| 98 |
+
|
| 99 |
+
estimated_tokens = int(total_words * 1.3)
|
| 100 |
+
|
| 101 |
+
logger.info(f"Corpus: {len(lines):,} documents, ~{estimated_tokens:,} tokens")
|
| 102 |
+
|
| 103 |
+
if estimated_tokens < 100_000:
|
| 104 |
+
logger.warning("Corpus is very small. Consider adding more data.")
|
| 105 |
+
|
| 106 |
+
return True
|
| 107 |
+
|
| 108 |
+
def convert_to_mlx_format(self) -> Path:
|
| 109 |
+
"""Convert corpus to MLX training format."""
|
| 110 |
+
corpus_path = self.project_root / self.config.corpus_file
|
| 111 |
+
output_dir = self.project_root / "data/pretrain_data"
|
| 112 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 113 |
+
|
| 114 |
+
train_file = output_dir / "train.jsonl"
|
| 115 |
+
valid_file = output_dir / "valid.jsonl"
|
| 116 |
+
|
| 117 |
+
# Read corpus
|
| 118 |
+
with open(corpus_path) as f:
|
| 119 |
+
documents = [json.loads(line) for line in f]
|
| 120 |
+
|
| 121 |
+
# Shuffle and split
|
| 122 |
+
import random
|
| 123 |
+
random.shuffle(documents)
|
| 124 |
+
|
| 125 |
+
split_idx = int(len(documents) * 0.95)
|
| 126 |
+
train_docs = documents[:split_idx]
|
| 127 |
+
valid_docs = documents[split_idx:]
|
| 128 |
+
|
| 129 |
+
# Convert to MLX format (just "text" field for language modeling)
|
| 130 |
+
with open(train_file, 'w') as f:
|
| 131 |
+
for doc in train_docs:
|
| 132 |
+
f.write(json.dumps({"text": doc.get("text", "")}) + '\n')
|
| 133 |
+
|
| 134 |
+
with open(valid_file, 'w') as f:
|
| 135 |
+
for doc in valid_docs:
|
| 136 |
+
f.write(json.dumps({"text": doc.get("text", "")}) + '\n')
|
| 137 |
+
|
| 138 |
+
logger.info(f"Created: {len(train_docs)} train, {len(valid_docs)} valid samples")
|
| 139 |
+
|
| 140 |
+
return output_dir
|
| 141 |
+
|
| 142 |
+
def calculate_iterations(self) -> int:
|
| 143 |
+
"""Calculate number of iterations for specified epochs."""
|
| 144 |
+
corpus_path = self.project_root / self.config.corpus_file
|
| 145 |
+
|
| 146 |
+
with open(corpus_path) as f:
|
| 147 |
+
num_docs = sum(1 for _ in f)
|
| 148 |
+
|
| 149 |
+
# Rough estimate: docs / batch_size * epochs
|
| 150 |
+
iters = int(num_docs / self.config.batch_size * self.config.num_epochs)
|
| 151 |
+
|
| 152 |
+
# Cap at reasonable number
|
| 153 |
+
return min(iters, 5000)
|
| 154 |
+
|
| 155 |
+
def get_pretrain_command(self, data_dir: Path) -> str:
|
| 156 |
+
"""Generate MLX pre-training command."""
|
| 157 |
+
iters = self.calculate_iterations()
|
| 158 |
+
|
| 159 |
+
cmd = f"""mlx_lm.lora \\
|
| 160 |
+
--model {self.config.base_model} \\
|
| 161 |
+
--data {data_dir} \\
|
| 162 |
+
--train \\
|
| 163 |
+
--batch-size {self.config.batch_size} \\
|
| 164 |
+
--num-layers {self.config.num_layers} \\
|
| 165 |
+
--learning-rate {self.config.learning_rate} \\
|
| 166 |
+
--iters {iters} \\
|
| 167 |
+
--save-every {self.config.save_every} \\
|
| 168 |
+
--max-seq-length {self.config.max_seq_length} \\
|
| 169 |
+
--adapter-path {self.config.output_dir}"""
|
| 170 |
+
|
| 171 |
+
return cmd
|
| 172 |
+
|
| 173 |
+
def run_pretraining(self, dry_run: bool = False) -> bool:
|
| 174 |
+
"""Run the pre-training process."""
|
| 175 |
+
logger.info("=" * 60)
|
| 176 |
+
logger.info("π DOMAIN PRE-TRAINING")
|
| 177 |
+
logger.info("=" * 60)
|
| 178 |
+
|
| 179 |
+
# Step 1: Verify corpus
|
| 180 |
+
if not self.prepare_corpus():
|
| 181 |
+
return False
|
| 182 |
+
|
| 183 |
+
# Step 2: Prepare data
|
| 184 |
+
logger.info("\nπ Preparing training data...")
|
| 185 |
+
data_dir = self.convert_to_mlx_format()
|
| 186 |
+
|
| 187 |
+
# Step 3: Generate command
|
| 188 |
+
cmd = self.get_pretrain_command(data_dir)
|
| 189 |
+
|
| 190 |
+
logger.info(f"\nπ Pre-training Configuration:")
|
| 191 |
+
for key, value in self.config.to_dict().items():
|
| 192 |
+
logger.info(f" {key}: {value}")
|
| 193 |
+
|
| 194 |
+
logger.info(f"\nπ§ Command:\n{cmd}")
|
| 195 |
+
|
| 196 |
+
if dry_run:
|
| 197 |
+
logger.info("\n[DRY RUN] Command not executed.")
|
| 198 |
+
return True
|
| 199 |
+
|
| 200 |
+
# Step 4: Run training
|
| 201 |
+
logger.info("\nπ Starting pre-training...")
|
| 202 |
+
logger.info(" This may take several hours depending on corpus size.")
|
| 203 |
+
|
| 204 |
+
try:
|
| 205 |
+
# Create output directory
|
| 206 |
+
output_path = Path(self.config.output_dir)
|
| 207 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 208 |
+
|
| 209 |
+
# Save config
|
| 210 |
+
with open(output_path / "pretrain_config.json", 'w') as f:
|
| 211 |
+
json.dump(self.config.to_dict(), f, indent=2)
|
| 212 |
+
|
| 213 |
+
# Run training
|
| 214 |
+
result = subprocess.run(
|
| 215 |
+
cmd,
|
| 216 |
+
shell=True,
|
| 217 |
+
cwd=self.project_root,
|
| 218 |
+
check=True
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
logger.info("\nβ
Pre-training completed!")
|
| 222 |
+
return True
|
| 223 |
+
|
| 224 |
+
except subprocess.CalledProcessError as e:
|
| 225 |
+
logger.error(f"\nβ Pre-training failed: {e}")
|
| 226 |
+
return False
|
| 227 |
+
|
| 228 |
+
def verify_pretrained_model(self) -> bool:
|
| 229 |
+
"""Verify the pre-trained model works."""
|
| 230 |
+
output_path = Path(self.config.output_dir)
|
| 231 |
+
|
| 232 |
+
if not (output_path / "adapters.safetensors").exists():
|
| 233 |
+
logger.error("Pre-trained adapter not found")
|
| 234 |
+
return False
|
| 235 |
+
|
| 236 |
+
logger.info("Testing pre-trained model...")
|
| 237 |
+
|
| 238 |
+
try:
|
| 239 |
+
from mlx_lm import load, generate
|
| 240 |
+
|
| 241 |
+
model, tokenizer = load(
|
| 242 |
+
self.config.base_model,
|
| 243 |
+
adapter_path=str(output_path)
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
# Test with financial text
|
| 247 |
+
prompt = "UPI transaction reference number 123456789012 indicates"
|
| 248 |
+
response = generate(model, tokenizer, prompt=prompt, max_tokens=50)
|
| 249 |
+
|
| 250 |
+
logger.info(f"Prompt: {prompt}")
|
| 251 |
+
logger.info(f"Response: {response}")
|
| 252 |
+
|
| 253 |
+
return True
|
| 254 |
+
|
| 255 |
+
except Exception as e:
|
| 256 |
+
logger.error(f"Model test failed: {e}")
|
| 257 |
+
return False
|
| 258 |
+
|
| 259 |
+
def print_instructions(self):
|
| 260 |
+
"""Print step-by-step instructions."""
|
| 261 |
+
print("""
|
| 262 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 263 |
+
β DOMAIN PRE-TRAINING INSTRUCTIONS β
|
| 264 |
+
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
|
| 265 |
+
β β
|
| 266 |
+
β STEP 1: Collect Corpus β
|
| 267 |
+
β ββββββββββββββββββββββ β
|
| 268 |
+
β a) Export Gmail to MBOX (Google Takeout) β
|
| 269 |
+
β b) Place bank statement PDFs in data/raw/pdfs/ β
|
| 270 |
+
β c) Run: python scripts/corpus_collection/collect_corpus.py β
|
| 271 |
+
β β
|
| 272 |
+
β STEP 2: Verify Corpus β
|
| 273 |
+
β βββββββββββββββοΏ½οΏ½βββββ β
|
| 274 |
+
β Check data/corpus/combined/corpus.jsonl exists β
|
| 275 |
+
β Target: 1M+ tokens (ideally 10M+) β
|
| 276 |
+
β β
|
| 277 |
+
β STEP 3: Run Pre-training β
|
| 278 |
+
β ββββββββββββββββββββββββ β
|
| 279 |
+
β python scripts/domain_pretrain.py β
|
| 280 |
+
β β
|
| 281 |
+
β STEP 4: Verify & Use β
|
| 282 |
+
β ββββββββββββββββββββ β
|
| 283 |
+
β Use models/domain-pretrained/phi3-finance as base for fine-tuning β
|
| 284 |
+
β β
|
| 285 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 286 |
+
""")
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def analyze_corpus(corpus_path: str):
|
| 290 |
+
"""Analyze corpus quality before pre-training."""
|
| 291 |
+
print("\nπ Corpus Analysis")
|
| 292 |
+
print("=" * 60)
|
| 293 |
+
|
| 294 |
+
path = Path(corpus_path)
|
| 295 |
+
if not path.exists():
|
| 296 |
+
print(f"β Corpus not found: {path}")
|
| 297 |
+
return
|
| 298 |
+
|
| 299 |
+
total_docs = 0
|
| 300 |
+
total_words = 0
|
| 301 |
+
sources = {}
|
| 302 |
+
sample_texts = []
|
| 303 |
+
|
| 304 |
+
with open(path) as f:
|
| 305 |
+
for i, line in enumerate(f):
|
| 306 |
+
try:
|
| 307 |
+
doc = json.loads(line)
|
| 308 |
+
text = doc.get("text", "")
|
| 309 |
+
source = doc.get("source", "unknown")
|
| 310 |
+
|
| 311 |
+
words = len(text.split())
|
| 312 |
+
total_docs += 1
|
| 313 |
+
total_words += words
|
| 314 |
+
|
| 315 |
+
sources[source] = sources.get(source, 0) + 1
|
| 316 |
+
|
| 317 |
+
if i < 3:
|
| 318 |
+
sample_texts.append(text[:200])
|
| 319 |
+
|
| 320 |
+
except:
|
| 321 |
+
pass
|
| 322 |
+
|
| 323 |
+
est_tokens = int(total_words * 1.3)
|
| 324 |
+
|
| 325 |
+
print(f"Documents: {total_docs:,}")
|
| 326 |
+
print(f"Words: {total_words:,}")
|
| 327 |
+
print(f"Est Tokens: {est_tokens:,}")
|
| 328 |
+
print(f"\nBy Source:")
|
| 329 |
+
for source, count in sorted(sources.items()):
|
| 330 |
+
print(f" {source:15} {count:,}")
|
| 331 |
+
|
| 332 |
+
print(f"\nSample Texts:")
|
| 333 |
+
for i, text in enumerate(sample_texts, 1):
|
| 334 |
+
print(f" [{i}] {text}...")
|
| 335 |
+
|
| 336 |
+
# Quality assessment
|
| 337 |
+
print(f"\n{'=' * 60}")
|
| 338 |
+
if est_tokens >= 10_000_000:
|
| 339 |
+
print("β
EXCELLENT: Corpus has 10M+ tokens - ideal for pre-training")
|
| 340 |
+
elif est_tokens >= 1_000_000:
|
| 341 |
+
print("β
GOOD: Corpus has 1M+ tokens - sufficient for basic pre-training")
|
| 342 |
+
elif est_tokens >= 100_000:
|
| 343 |
+
print("β οΈ MARGINAL: Corpus has 100K+ tokens - may help but limited")
|
| 344 |
+
else:
|
| 345 |
+
print("β INSUFFICIENT: Corpus too small - add more data")
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def main():
|
| 349 |
+
import argparse
|
| 350 |
+
|
| 351 |
+
parser = argparse.ArgumentParser(description="Domain Pre-training for Financial LLM")
|
| 352 |
+
parser.add_argument("--dry-run", action="store_true", help="Print command without executing")
|
| 353 |
+
parser.add_argument("--analyze", action="store_true", help="Analyze corpus only")
|
| 354 |
+
parser.add_argument("--corpus", default="data/corpus/combined/corpus.jsonl")
|
| 355 |
+
parser.add_argument("--epochs", type=int, default=1)
|
| 356 |
+
parser.add_argument("--lr", type=float, default=5e-6)
|
| 357 |
+
|
| 358 |
+
args = parser.parse_args()
|
| 359 |
+
|
| 360 |
+
if args.analyze:
|
| 361 |
+
analyze_corpus(args.corpus)
|
| 362 |
+
return
|
| 363 |
+
|
| 364 |
+
config = PretrainingConfig(
|
| 365 |
+
corpus_file=args.corpus,
|
| 366 |
+
num_epochs=args.epochs,
|
| 367 |
+
learning_rate=args.lr
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
pretrainer = DomainPretrainer(config)
|
| 371 |
+
pretrainer.print_instructions()
|
| 372 |
+
|
| 373 |
+
if args.dry_run:
|
| 374 |
+
pretrainer.prepare_corpus()
|
| 375 |
+
data_dir = pretrainer.convert_to_mlx_format()
|
| 376 |
+
cmd = pretrainer.get_pretrain_command(data_dir)
|
| 377 |
+
print(f"\nπ§ Command (not executed):\n{cmd}")
|
| 378 |
+
else:
|
| 379 |
+
pretrainer.run_pretraining()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
if __name__ == "__main__":
|
| 383 |
+
main()
|
scripts/evaluate_v6.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Quick Evaluation for finance-lora-v6.
|
| 3 |
+
Tests the model with sample prompts from each phase.
|
| 4 |
+
|
| 5 |
+
Author: Ranjit Behera
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
def generate(prompt: str) -> str:
|
| 12 |
+
"""Generate response using mlx_lm.generate."""
|
| 13 |
+
cmd = [
|
| 14 |
+
sys.executable, "-m", "mlx_lm.generate",
|
| 15 |
+
"--model", "models/base/phi3-finance-base",
|
| 16 |
+
"--adapter-path", "models/adapters/finance-lora-v6",
|
| 17 |
+
"--prompt", prompt,
|
| 18 |
+
"--max-tokens", "200"
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
| 23 |
+
return result.stdout
|
| 24 |
+
except Exception as e:
|
| 25 |
+
return f"Error: {e}"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
print("=" * 70)
|
| 30 |
+
print("π§ͺ FINANCE-LORA-V6 EVALUATION")
|
| 31 |
+
print("=" * 70)
|
| 32 |
+
|
| 33 |
+
# Test 1: UPI Email (Phase 1)
|
| 34 |
+
print("\nπ§ TEST 1: UPI Email Extraction (Phase 1)")
|
| 35 |
+
print("-" * 50)
|
| 36 |
+
upi_prompt = """Extract financial entities from this email:
|
| 37 |
+
|
| 38 |
+
Subject: Money received! Rs.500.00 credited
|
| 39 |
+
From: alerts@hdfcbank.net
|
| 40 |
+
|
| 41 |
+
Dear Customer,
|
| 42 |
+
Rs.500.00 has been credited to your account ending 1234 by UPI.
|
| 43 |
+
UPI Ref: 123456789012
|
| 44 |
+
From: customer@okaxis
|
| 45 |
+
Date: 15-Jan-2024
|
| 46 |
+
|
| 47 |
+
Extract: amount, sender, receiver, transaction_id, date, bank
|
| 48 |
+
Output JSON:"""
|
| 49 |
+
|
| 50 |
+
print(f"Prompt: {upi_prompt[:100]}...")
|
| 51 |
+
response = generate(upi_prompt)
|
| 52 |
+
print(f"Response:\n{response}")
|
| 53 |
+
|
| 54 |
+
# Test 2: Bank Statement Row (Phase 2)
|
| 55 |
+
print("\nπ¦ TEST 2: Bank Statement Row (Phase 2)")
|
| 56 |
+
print("-" * 50)
|
| 57 |
+
statement_prompt = """[BANK_STATEMENT]
|
| 58 |
+
15/01/2024 | UPI/CR/415926537890 | AMOUNT CREDITED FROM ROHIT KUMAR | 2500.00 | 15000.00
|
| 59 |
+
|
| 60 |
+
Extract: date, description, amount, balance, type
|
| 61 |
+
Output JSON:"""
|
| 62 |
+
|
| 63 |
+
print(f"Prompt: {statement_prompt[:100]}...")
|
| 64 |
+
response = generate(statement_prompt)
|
| 65 |
+
print(f"Response:\n{response}")
|
| 66 |
+
|
| 67 |
+
# Test 3: PhonePe Statement (Phase 3)
|
| 68 |
+
print("\nπ± TEST 3: PhonePe Statement (Phase 3)")
|
| 69 |
+
print("-" * 50)
|
| 70 |
+
phonepe_prompt = """[PHONEPE]
|
| 71 |
+
Transaction Details:
|
| 72 |
+
Date: Jan 15, 2024 at 3:45 PM
|
| 73 |
+
Paid to: Swiggy
|
| 74 |
+
Amount: βΉ350.00
|
| 75 |
+
Transaction ID: PPT202401153456789012
|
| 76 |
+
Status: Success
|
| 77 |
+
|
| 78 |
+
Extract: date, receiver, amount, transaction_id, status
|
| 79 |
+
Output JSON:"""
|
| 80 |
+
|
| 81 |
+
print(f"Prompt: {phonepe_prompt[:100]}...")
|
| 82 |
+
response = generate(phonepe_prompt)
|
| 83 |
+
print(f"Response:\n{response}")
|
| 84 |
+
|
| 85 |
+
# Test 4: GPay Statement (Phase 3)
|
| 86 |
+
print("\nπ± TEST 4: GPay Statement (Phase 3)")
|
| 87 |
+
print("-" * 50)
|
| 88 |
+
gpay_prompt = """[GPAY]
|
| 89 |
+
You paid βΉ1,200.00 to Zomato
|
| 90 |
+
Jan 16, 2024
|
| 91 |
+
Transaction ID: GPay-TXN-8765432109876543
|
| 92 |
+
Status: Completed
|
| 93 |
+
|
| 94 |
+
Extract: date, receiver, amount, transaction_id, status
|
| 95 |
+
Output JSON:"""
|
| 96 |
+
|
| 97 |
+
print(f"Prompt: {gpay_prompt[:100]}...")
|
| 98 |
+
response = generate(gpay_prompt)
|
| 99 |
+
print(f"Response:\n{response}")
|
| 100 |
+
|
| 101 |
+
print("\n" + "=" * 70)
|
| 102 |
+
print("β
Evaluation Complete!")
|
| 103 |
+
print("=" * 70)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
main()
|
scripts/finetune_v6.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Fine-tune Model v6.
|
| 3 |
+
Final task-specific fine-tuning for UPI emails, bank statements,
|
| 4 |
+
and payment app statements. Uses the domain-pretrained base.
|
| 5 |
+
|
| 6 |
+
Author: Ranjit Behera
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import subprocess
|
| 10 |
+
import argparse
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
def run_finetune():
|
| 14 |
+
base_model = "models/base/phi3-finance-base"
|
| 15 |
+
data_dir = "data/training"
|
| 16 |
+
adapter_path = "models/adapters/finance-lora-v6"
|
| 17 |
+
|
| 18 |
+
print(f"π Starting Fine-tuning v6 using {base_model}...")
|
| 19 |
+
|
| 20 |
+
cmd = [
|
| 21 |
+
"mlx_lm.lora",
|
| 22 |
+
"--model", base_model,
|
| 23 |
+
"--data", data_dir,
|
| 24 |
+
"--train",
|
| 25 |
+
"--iters", "1500",
|
| 26 |
+
"--batch-size", "1",
|
| 27 |
+
"--num-layers", "16",
|
| 28 |
+
"--learning-rate", "1e-5",
|
| 29 |
+
"--adapter-path", adapter_path,
|
| 30 |
+
"--max-seq-length", "1024" # Increased seq length for statements
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
print(f"Command: {' '.join(cmd)}")
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
subprocess.run(cmd, check=True)
|
| 37 |
+
print(f"β
Successfully trained v6 adapters at {adapter_path}")
|
| 38 |
+
except subprocess.CalledProcessError as e:
|
| 39 |
+
print(f"β Fine-tuning failed: {e}")
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
run_finetune()
|
scripts/fuse_model.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Model Fusion Script.
|
| 3 |
+
|
| 4 |
+
Fuses the domain-pretrained adapters into the base model to create
|
| 5 |
+
a standalone finance-native base model. This model can then be
|
| 6 |
+
fine-tuned for specific tasks.
|
| 7 |
+
|
| 8 |
+
Author: Ranjit Behera
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import subprocess
|
| 12 |
+
import argparse
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
def fuse_model(base_model: str, adapter_path: str, output_path: str):
|
| 16 |
+
"""Run mlx_lm.fuse to merge adapters into base model."""
|
| 17 |
+
print(f"Merging {adapter_path} into {base_model}...")
|
| 18 |
+
|
| 19 |
+
cmd = [
|
| 20 |
+
"mlx_lm.fuse",
|
| 21 |
+
"--model", base_model,
|
| 22 |
+
"--adapter-path", adapter_path,
|
| 23 |
+
"--save-path", output_path
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
subprocess.run(cmd, check=True)
|
| 28 |
+
print(f"β
Successfully fused model to {output_path}")
|
| 29 |
+
except subprocess.CalledProcessError as e:
|
| 30 |
+
print(f"β Fusion failed: {e}")
|
| 31 |
+
|
| 32 |
+
if __name__ == "__main__":
|
| 33 |
+
parser = argparse.ArgumentParser(description="Fuse MLX adapters into base model")
|
| 34 |
+
parser.add_argument("--base", default="models/base/phi3-mini", help="Path to base model")
|
| 35 |
+
parser.add_argument("--adapter", default="models/domain-pretrained/phi3-finance", help="Path to adapters")
|
| 36 |
+
parser.add_argument("--output", default="models/base/phi3-finance-base", help="Output path for fused model")
|
| 37 |
+
|
| 38 |
+
args = parser.parse_args()
|
| 39 |
+
|
| 40 |
+
fuse_model(args.base, args.adapter, args.output)
|
scripts/generate_comprehensive_data.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generate Comprehensive Multi-Bank Training Data.
|
| 3 |
+
|
| 4 |
+
Uses realistic templates for HDFC, ICICI, SBI, Axis, Kotak
|
| 5 |
+
to generate training samples for all transaction types.
|
| 6 |
+
|
| 7 |
+
Author: Ranjit Behera
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import random
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from datetime import datetime, timedelta
|
| 14 |
+
|
| 15 |
+
OUTPUT_FILE = Path("data/synthetic/multi_bank_comprehensive.jsonl")
|
| 16 |
+
|
| 17 |
+
# Bank-specific email templates
|
| 18 |
+
TEMPLATES = {
|
| 19 |
+
"hdfc": {
|
| 20 |
+
"upi_debit": [
|
| 21 |
+
"HDFC BANK Dear Customer,\nRs.{amount} has been debited from account {account} to VPA {merchant}@{vpa_suffix} {merchant_name} on {date}.\nYour UPI transaction reference number is {reference}.\nIf you did not authorize this transaction, please call 18002586161.",
|
| 22 |
+
"Dear Customer, INR {amount} has been debited from your HDFC Bank Account XX{account} on {date} by UPI.\n\nTransaction Details:\nAmount: INR {amount}\nUPI Reference: {reference}\nBeneficiary: {merchant}@{vpa_suffix}\nRemarks: {remarks}\nAvailable Balance: INR {balance}",
|
| 23 |
+
],
|
| 24 |
+
"upi_credit": [
|
| 25 |
+
"HDFC BANK Dear Customer,\nRs.{amount} has been credited to account {account} from VPA {sender}@{vpa_suffix} {sender_name} on {date}.\nYour UPI transaction reference number is {reference}.",
|
| 26 |
+
"Dear Customer, INR {amount} has been credited to your HDFC Bank Account XX{account} on {date} by UPI.\n\nUPI Reference: {reference}\nSender: {sender}@{vpa_suffix}\nRemarks: {remarks}\nAvailable Balance: INR {balance}",
|
| 27 |
+
],
|
| 28 |
+
"neft_credit": [
|
| 29 |
+
"Rs.{amount} has been credited to your HDFC Bank A/c XX{account} on {date} through NEFT.\n\nNEFT Reference: HDFC{ref_prefix}N{reference}\nSender Name: {sender_name}\nSender Bank: {sender_bank}\nRemarks: {remarks}\nAvailable Balance: Rs.{balance}",
|
| 30 |
+
],
|
| 31 |
+
"atm": [
|
| 32 |
+
"Rs.{amount} has been withdrawn from your HDFC Bank Account XX{account} at ATM.\n\nDate: {date}\nATM ID: HDFC{atm_id}\nLocation: {location}\nReference: ATM{reference}\nAvailable Balance: Rs.{balance}",
|
| 33 |
+
],
|
| 34 |
+
},
|
| 35 |
+
"icici": {
|
| 36 |
+
"upi_debit": [
|
| 37 |
+
"Dear Customer, Rs. {amount} has been debited from your ICICI Bank Account ending with {account} on {date} at {time}.\n\nMode: UPI\nRef No: {reference}\nTo VPA: {merchant}@{vpa_suffix}\nNarration: {remarks}\nUpdated Balance: Rs. {balance}",
|
| 38 |
+
"Rs.{amount} has been debited from your ICICI Bank Account {account} for UPI txn to VPA-{merchant}@{vpa_suffix} on {date}. Ref:{reference}",
|
| 39 |
+
],
|
| 40 |
+
"upi_credit": [
|
| 41 |
+
"Dear Customer, Rs. {amount} has been credited to your ICICI Bank Account ending with {account} on {date} at {time}.\n\nMode: UPI\nRef No: {reference}\nFrom VPA: {sender}@{vpa_suffix}\nNarration: {remarks}\nUpdated Balance: Rs. {balance}",
|
| 42 |
+
"INR {amount} credited to ICICI Bank A/c {account} on {date} from {sender_name}. UPI Ref: {reference}",
|
| 43 |
+
],
|
| 44 |
+
"imps_credit": [
|
| 45 |
+
"ICICI Bank Acct XX{account} credited with INR {amount} on {date}. IMPS Ref {reference}.",
|
| 46 |
+
],
|
| 47 |
+
"neft_credit": [
|
| 48 |
+
"Rs.{amount} has been credited to your ICICI Bank Account {account} via NEFT.\n\nDate: {date}\nUTR: ICIC{ref_prefix}N{reference}\nSender: {sender_name}\nSender A/c: XXXXXX{sender_acc}\nBank: {sender_bank}\nNarration: {remarks}\nBalance: Rs.{balance}",
|
| 49 |
+
],
|
| 50 |
+
},
|
| 51 |
+
"sbi": {
|
| 52 |
+
"upi_debit": [
|
| 53 |
+
"SBI: Rs.{amount} debited from a/c XX{account} on {date}. UPI txn to {merchant}@{vpa_suffix}. If not done by you,call 1800112211. Ref: {reference}",
|
| 54 |
+
"Dear SBI User, Rs {amount} debited from A/c X{account} on {date} by UPI {merchant_name}. Ref {reference}. If not you, fwd SMS to 9223766666",
|
| 55 |
+
],
|
| 56 |
+
"upi_credit": [
|
| 57 |
+
"Dear SBI User, Rs {amount} credited to A/c X{account} on {date}. UPI Ref {reference}.",
|
| 58 |
+
"Rs {amount} credited to SBI A/c {account} on {date}. IMPS from {sender_name}. Balance: Rs.{balance}",
|
| 59 |
+
],
|
| 60 |
+
"neft_credit": [
|
| 61 |
+
"Dear Customer, Rs.{amount} has been credited to your SBI Account XXXXXXX{account} on {date} through NEFT.\n\nUTR No: SBIN{ref_prefix}{reference}\nRemitter: {sender_name}\nRemitter Bank: {sender_bank}\nPurpose: {remarks}\nBalance: Rs.{balance}",
|
| 62 |
+
],
|
| 63 |
+
},
|
| 64 |
+
"axis": {
|
| 65 |
+
"upi_debit": [
|
| 66 |
+
"Rs.{amount} debited from Axis Bank A/c {account} on {date} to VPA {merchant}@{vpa_suffix}. UPI Ref:{reference}",
|
| 67 |
+
"Axis Bank Acct XX{account} debited for Rs.{amount} on {date}. UPI:{merchant_name}. Ref {reference}. Not you? SMS FREEZE to 5676782",
|
| 68 |
+
"Dear Customer, INR {amount} debited from Axis A/c XX{account} on {date}. Info:UPI-{merchant_name}. Bal:Rs.{balance}",
|
| 69 |
+
],
|
| 70 |
+
"upi_credit": [
|
| 71 |
+
"Rs.{amount} credited to Axis Bank A/c {account} on {date} from {sender_name}. Ref:{reference}",
|
| 72 |
+
"Dear Customer, INR {amount} credited to Axis A/c XX{account} on {date}. Avl Bal:Rs.{balance}",
|
| 73 |
+
],
|
| 74 |
+
"imps_credit": [
|
| 75 |
+
"INR {amount} has been credited to your Axis Bank Account XX{account} via IMPS on {date} at {time}.\n\nIMPS Ref No: {reference}\nSender: {sender_name}\nSender A/c: XXXXXX{sender_acc}\nSender Bank: {sender_bank}\nRemarks: {remarks}\nAvl Bal: INR {balance}",
|
| 76 |
+
],
|
| 77 |
+
},
|
| 78 |
+
"kotak": {
|
| 79 |
+
"upi_debit": [
|
| 80 |
+
"INR {amount} debited from Kotak A/c {account} on {date} to VPA:{merchant}@{vpa_suffix}. Ref No.{reference}",
|
| 81 |
+
"Kotak Bank: Rs.{amount} debited from A/c XX{account} on {date} towards UPI-{merchant_name}. Avl Bal Rs.{balance}. Ref {reference}",
|
| 82 |
+
"Rs {amount} debited via UPI from Kotak Bank A/c XX{account} on {date}. Merchant:{merchant_name}. If not you call 18002740110",
|
| 83 |
+
],
|
| 84 |
+
"upi_credit": [
|
| 85 |
+
"INR {amount} credited to Kotak A/c {account} on {date} from {sender_name}. Ref:{reference}",
|
| 86 |
+
"Rs {amount} credited to Kotak Bank A/c XX{account} on {date}. Info:{remarks}. Balance:Rs.{balance}",
|
| 87 |
+
],
|
| 88 |
+
},
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
# Merchants and categories
|
| 92 |
+
MERCHANTS = [
|
| 93 |
+
("swiggy", "food", "SWIGGY INDIA"),
|
| 94 |
+
("zomato", "food", "ZOMATO MEDIA"),
|
| 95 |
+
("amazon", "shopping", "AMAZON SELLER"),
|
| 96 |
+
("flipkart", "shopping", "FLIPKART PAYMENTS"),
|
| 97 |
+
("myntra", "shopping", "MYNTRA DESIGNS"),
|
| 98 |
+
("uber", "transport", "UBER INDIA"),
|
| 99 |
+
("ola", "transport", "OLA CABS"),
|
| 100 |
+
("rapido", "transport", "RAPIDO BIKE"),
|
| 101 |
+
("bigbasket", "grocery", "BIGBASKET"),
|
| 102 |
+
("blinkit", "grocery", "BLINKIT QUICK"),
|
| 103 |
+
("zepto", "grocery", "ZEPTO NOW"),
|
| 104 |
+
("dmart", "grocery", "DMART RETAIL"),
|
| 105 |
+
("jio", "bills", "RELIANCE JIO"),
|
| 106 |
+
("airtel", "bills", "BHARTI AIRTEL"),
|
| 107 |
+
("electricity", "bills", "ELECTRICITY BOARD"),
|
| 108 |
+
("water", "bills", "WATER BOARD"),
|
| 109 |
+
("netflix", "entertainment", "NETFLIX SERVICES"),
|
| 110 |
+
("hotstar", "entertainment", "DISNEY HOTSTAR"),
|
| 111 |
+
("bookmyshow", "entertainment", "BOOKMYSHOW"),
|
| 112 |
+
("makemytrip", "travel", "MAKEMYTRIP"),
|
| 113 |
+
]
|
| 114 |
+
|
| 115 |
+
VPA_SUFFIXES = ["ybl", "paytm", "okicici", "okhdfcbank", "axl", "sbi", "icici", "kotak"]
|
| 116 |
+
|
| 117 |
+
SENDERS = [
|
| 118 |
+
("amit.kumar", "AMIT KUMAR"),
|
| 119 |
+
("priya.singh", "PRIYA SINGH"),
|
| 120 |
+
("rahul.sharma", "RAHUL SHARMA"),
|
| 121 |
+
("neha.gupta", "NEHA GUPTA"),
|
| 122 |
+
("suresh.patel", "SURESH PATEL"),
|
| 123 |
+
("anita.verma", "ANITA VERMA"),
|
| 124 |
+
]
|
| 125 |
+
|
| 126 |
+
SENDER_BANKS = ["HDFC BANK", "ICICI BANK", "SBI", "AXIS BANK", "KOTAK BANK", "PNB"]
|
| 127 |
+
|
| 128 |
+
LOCATIONS = [
|
| 129 |
+
"MG Road, Bangalore",
|
| 130 |
+
"Connaught Place, Delhi",
|
| 131 |
+
"Bandra West, Mumbai",
|
| 132 |
+
"Hitech City, Hyderabad",
|
| 133 |
+
"Anna Nagar, Chennai",
|
| 134 |
+
]
|
| 135 |
+
|
| 136 |
+
REMARKS = [
|
| 137 |
+
"Food order", "Shopping", "Bill payment", "Rent share",
|
| 138 |
+
"Grocery", "Transport", "Subscription", "Birthday gift",
|
| 139 |
+
"Salary transfer", "Medical", "Education", "Investment",
|
| 140 |
+
]
|
| 141 |
+
|
| 142 |
+
DATE_FORMATS = ["%d-%m-%Y", "%d/%m/%Y", "%d-%m-%y", "%d %b %Y", "%d%m%Y"]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def generate_date():
|
| 146 |
+
"""Generate random date in past 90 days."""
|
| 147 |
+
days_ago = random.randint(1, 90)
|
| 148 |
+
d = datetime.now() - timedelta(days=days_ago)
|
| 149 |
+
fmt = random.choice(DATE_FORMATS)
|
| 150 |
+
return d.strftime(fmt)
|
| 151 |
+
|
| 152 |
+
def generate_time():
|
| 153 |
+
"""Generate random time."""
|
| 154 |
+
h = random.randint(6, 23)
|
| 155 |
+
m = random.randint(0, 59)
|
| 156 |
+
s = random.randint(0, 59)
|
| 157 |
+
return f"{h:02d}:{m:02d}:{s:02d}"
|
| 158 |
+
|
| 159 |
+
def generate_reference():
|
| 160 |
+
"""Generate 12-digit reference."""
|
| 161 |
+
return ''.join([str(random.randint(0, 9)) for _ in range(12)])
|
| 162 |
+
|
| 163 |
+
def generate_account():
|
| 164 |
+
"""Generate 4-digit account."""
|
| 165 |
+
return str(random.randint(1000, 9999))
|
| 166 |
+
|
| 167 |
+
def generate_amount():
|
| 168 |
+
"""Generate realistic amount."""
|
| 169 |
+
options = [
|
| 170 |
+
round(random.uniform(50, 500), 2),
|
| 171 |
+
round(random.uniform(100, 2000), 2),
|
| 172 |
+
random.randint(100, 5000),
|
| 173 |
+
random.randint(500, 15000),
|
| 174 |
+
round(random.uniform(1000, 10000), 2),
|
| 175 |
+
]
|
| 176 |
+
return str(random.choice(options))
|
| 177 |
+
|
| 178 |
+
def generate_balance():
|
| 179 |
+
"""Generate balance."""
|
| 180 |
+
return str(random.randint(10000, 500000))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def generate_samples(n_per_bank=100):
|
| 184 |
+
"""Generate comprehensive multi-bank samples."""
|
| 185 |
+
samples = []
|
| 186 |
+
|
| 187 |
+
for bank, templates in TEMPLATES.items():
|
| 188 |
+
bank_samples = 0
|
| 189 |
+
|
| 190 |
+
for txn_type, template_list in templates.items():
|
| 191 |
+
for _ in range(n_per_bank // len(templates)):
|
| 192 |
+
template = random.choice(template_list)
|
| 193 |
+
|
| 194 |
+
merchant_info = random.choice(MERCHANTS)
|
| 195 |
+
sender_info = random.choice(SENDERS)
|
| 196 |
+
|
| 197 |
+
is_credit = "credit" in txn_type
|
| 198 |
+
|
| 199 |
+
# Fill template
|
| 200 |
+
data = {
|
| 201 |
+
"amount": generate_amount(),
|
| 202 |
+
"account": generate_account(),
|
| 203 |
+
"date": generate_date(),
|
| 204 |
+
"time": generate_time(),
|
| 205 |
+
"reference": generate_reference(),
|
| 206 |
+
"balance": generate_balance(),
|
| 207 |
+
"remarks": random.choice(REMARKS),
|
| 208 |
+
"vpa_suffix": random.choice(VPA_SUFFIXES),
|
| 209 |
+
"ref_prefix": f"260{random.randint(10, 99)}",
|
| 210 |
+
"atm_id": f"000{random.randint(1000, 9999)}",
|
| 211 |
+
"location": random.choice(LOCATIONS),
|
| 212 |
+
"sender_bank": random.choice(SENDER_BANKS),
|
| 213 |
+
"sender_acc": str(random.randint(1000, 9999)),
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
if is_credit:
|
| 217 |
+
data["sender"] = sender_info[0]
|
| 218 |
+
data["sender_name"] = sender_info[1]
|
| 219 |
+
else:
|
| 220 |
+
data["merchant"] = merchant_info[0]
|
| 221 |
+
data["merchant_name"] = merchant_info[2]
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
email_text = template.format(**data)
|
| 225 |
+
except KeyError:
|
| 226 |
+
continue
|
| 227 |
+
|
| 228 |
+
# Create entities
|
| 229 |
+
entities = {
|
| 230 |
+
"amount": data["amount"].replace(",", ""),
|
| 231 |
+
"type": "credit" if is_credit else "debit",
|
| 232 |
+
"date": data["date"],
|
| 233 |
+
"account": data["account"],
|
| 234 |
+
"reference": data["reference"],
|
| 235 |
+
"bank": bank,
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
if not is_credit:
|
| 239 |
+
entities["merchant"] = merchant_info[0]
|
| 240 |
+
entities["category"] = merchant_info[1]
|
| 241 |
+
|
| 242 |
+
# Create training format
|
| 243 |
+
prompt = f"""Extract financial entities from this {bank.upper()} Bank email:
|
| 244 |
+
|
| 245 |
+
{email_text}
|
| 246 |
+
|
| 247 |
+
Extract: amount, type, date, account, reference{', merchant, category' if not is_credit else ''}
|
| 248 |
+
Output JSON:"""
|
| 249 |
+
|
| 250 |
+
completion = json.dumps(entities, indent=2)
|
| 251 |
+
|
| 252 |
+
samples.append({
|
| 253 |
+
"prompt": prompt,
|
| 254 |
+
"completion": completion,
|
| 255 |
+
"bank": bank,
|
| 256 |
+
"txn_type": txn_type
|
| 257 |
+
})
|
| 258 |
+
bank_samples += 1
|
| 259 |
+
|
| 260 |
+
print(f" {bank.upper():10} {bank_samples} samples")
|
| 261 |
+
|
| 262 |
+
return samples
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def main():
|
| 266 |
+
print("=" * 60)
|
| 267 |
+
print("π GENERATING COMPREHENSIVE MULTI-BANK DATA")
|
| 268 |
+
print("=" * 60)
|
| 269 |
+
|
| 270 |
+
print("\nGenerating samples per bank:")
|
| 271 |
+
samples = generate_samples(n_per_bank=100)
|
| 272 |
+
|
| 273 |
+
# Shuffle
|
| 274 |
+
random.seed(42)
|
| 275 |
+
random.shuffle(samples)
|
| 276 |
+
|
| 277 |
+
# Save
|
| 278 |
+
OUTPUT_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 279 |
+
with open(OUTPUT_FILE, 'w') as f:
|
| 280 |
+
for sample in samples:
|
| 281 |
+
f.write(json.dumps(sample) + '\n')
|
| 282 |
+
|
| 283 |
+
print(f"\nβ
Total samples: {len(samples)}")
|
| 284 |
+
print(f" Saved to {OUTPUT_FILE}")
|
| 285 |
+
|
| 286 |
+
# Stats
|
| 287 |
+
from collections import Counter
|
| 288 |
+
bank_counts = Counter(s['bank'] for s in samples)
|
| 289 |
+
type_counts = Counter(s['txn_type'] for s in samples)
|
| 290 |
+
|
| 291 |
+
print("\nπ By transaction type:")
|
| 292 |
+
for t, c in sorted(type_counts.items()):
|
| 293 |
+
print(f" {t:15} {c}")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
if __name__ == "__main__":
|
| 297 |
+
main()
|
scripts/generate_icici_data.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generate ICICI-Specific Training Data.
|
| 3 |
+
|
| 4 |
+
Creates 100 ICICI Bank email samples to improve model accuracy.
|
| 5 |
+
|
| 6 |
+
Author: Ranjit Behera
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import random
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from datetime import datetime, timedelta
|
| 13 |
+
|
| 14 |
+
OUTPUT_FILE = Path("data/synthetic/icici_samples.jsonl")
|
| 15 |
+
|
| 16 |
+
# ICICI-specific email templates (based on real formats)
|
| 17 |
+
ICICI_TEMPLATES = [
|
| 18 |
+
# Template 1: Standard debit
|
| 19 |
+
"Dear Customer, Rs.{amount} is debited from A/c XX{account} for UPI txn to VPA-{merchant}@{suffix} on {date}. Ref:{reference}",
|
| 20 |
+
|
| 21 |
+
# Template 2: Credit
|
| 22 |
+
"INR {amount} credited to ICICI Bank A/c {account} on {date} from {sender}. UPI Ref: {reference}",
|
| 23 |
+
|
| 24 |
+
# Template 3: Credit with IMPS
|
| 25 |
+
"ICICI Bank Acct XX{account} credited with INR {amount} on {date}. IMPS Ref {reference}.",
|
| 26 |
+
|
| 27 |
+
# Template 4: Debit with merchant
|
| 28 |
+
"INR {amount} debited from ICICI Bank A/c {account} on {date} to {merchant} via UPI. Ref: {reference}",
|
| 29 |
+
|
| 30 |
+
# Template 5: Alert format
|
| 31 |
+
"Alert: Rs {amount} debited from your ICICI Bank account ending {account} on {date}. UPI Ref No. {reference}. Not you? Call 1800-200-3344",
|
| 32 |
+
|
| 33 |
+
# Template 6: Credit received
|
| 34 |
+
"Dear Customer, your ICICI Bank A/c XX{account} has been credited with Rs.{amount} on {date}. Ref: {reference}",
|
| 35 |
+
|
| 36 |
+
# Template 7: Transaction alert
|
| 37 |
+
"ICICI Bank: Rs.{amount} has been debited from your account XX{account} on {date} for UPI payment to {merchant}. Ref:{reference}",
|
| 38 |
+
|
| 39 |
+
# Template 8: Balance info
|
| 40 |
+
"Dear Customer, INR {amount} debited from ICICI A/c XX{account} on {date}. Info: UPI-{merchant}. Avl Bal: Rs.{balance}",
|
| 41 |
+
|
| 42 |
+
# Template 9: Statement format
|
| 43 |
+
"Rs {amount} has been credited to your ICICI Bank account {account} on {date} via NEFT. Reference: {reference}",
|
| 44 |
+
|
| 45 |
+
# Template 10: Fund transfer
|
| 46 |
+
"ICICI Bank: Fund Transfer of Rs.{amount} to {merchant} successful. A/c: XX{account}. Date: {date}. Ref: {reference}"
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
VPA_SUFFIXES = ['ybl', 'paytm', 'okicici', 'okhdfcbank', 'axl', 'sbi', 'icici']
|
| 50 |
+
|
| 51 |
+
MERCHANTS = [
|
| 52 |
+
('swiggy', 'food'), ('zomato', 'food'), ('amazon', 'shopping'),
|
| 53 |
+
('flipkart', 'shopping'), ('uber', 'transport'), ('ola', 'transport'),
|
| 54 |
+
('rapido', 'transport'), ('bigbasket', 'grocery'), ('blinkit', 'grocery'),
|
| 55 |
+
('zepto', 'grocery'), ('dmart', 'grocery'), ('jio', 'bills'),
|
| 56 |
+
('airtel', 'bills'), ('electricity', 'bills'), ('water', 'bills'),
|
| 57 |
+
('myntra', 'shopping'), ('ajio', 'shopping'), ('bookmyshow', 'entertainment'),
|
| 58 |
+
('netflix', 'entertainment'), ('hotstar', 'entertainment')
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
SENDERS = [
|
| 62 |
+
'Amit Kumar', 'Priya Singh', 'Rahul Sharma', 'Neha Gupta',
|
| 63 |
+
'Suresh Patel', 'Anita Verma', 'Cashback', 'Refund - Amazon',
|
| 64 |
+
'Interest Credit', 'Dividend - Mutual Fund', 'Salary'
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
DATE_FORMATS = [
|
| 68 |
+
'%d-%m-%Y', '%d/%m/%Y', '%d-%m-%y', '%d %b %Y',
|
| 69 |
+
'%d%m%Y', '%d %B %Y'
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
def generate_random_date():
|
| 73 |
+
"""Generate random date in past 3 months."""
|
| 74 |
+
days_ago = random.randint(1, 90)
|
| 75 |
+
d = datetime.now() - timedelta(days=days_ago)
|
| 76 |
+
fmt = random.choice(DATE_FORMATS)
|
| 77 |
+
return d.strftime(fmt)
|
| 78 |
+
|
| 79 |
+
def generate_reference():
|
| 80 |
+
"""Generate 12-digit reference number."""
|
| 81 |
+
return ''.join([str(random.randint(0, 9)) for _ in range(12)])
|
| 82 |
+
|
| 83 |
+
def generate_account():
|
| 84 |
+
"""Generate 4-digit account number."""
|
| 85 |
+
return str(random.randint(1000, 9999))
|
| 86 |
+
|
| 87 |
+
def generate_amount(is_high=False):
|
| 88 |
+
"""Generate realistic amount."""
|
| 89 |
+
if is_high:
|
| 90 |
+
return str(random.randint(5000, 50000))
|
| 91 |
+
else:
|
| 92 |
+
amounts = [
|
| 93 |
+
round(random.uniform(50, 500), 2),
|
| 94 |
+
round(random.uniform(100, 2000), 2),
|
| 95 |
+
random.randint(100, 5000),
|
| 96 |
+
round(random.uniform(500, 3000), 2)
|
| 97 |
+
]
|
| 98 |
+
return str(random.choice(amounts))
|
| 99 |
+
|
| 100 |
+
def generate_icici_samples(n_samples=100):
|
| 101 |
+
"""Generate ICICI-specific training samples."""
|
| 102 |
+
samples = []
|
| 103 |
+
|
| 104 |
+
for i in range(n_samples):
|
| 105 |
+
template = random.choice(ICICI_TEMPLATES)
|
| 106 |
+
is_credit = 'credited' in template.lower() or 'credit' in template.lower()
|
| 107 |
+
|
| 108 |
+
merchant_info = random.choice(MERCHANTS)
|
| 109 |
+
merchant = merchant_info[0]
|
| 110 |
+
category = merchant_info[1]
|
| 111 |
+
|
| 112 |
+
account = generate_account()
|
| 113 |
+
reference = generate_reference()
|
| 114 |
+
amount = generate_amount(is_high=random.random() < 0.2)
|
| 115 |
+
date = generate_random_date()
|
| 116 |
+
balance = str(random.randint(10000, 500000))
|
| 117 |
+
sender = random.choice(SENDERS)
|
| 118 |
+
suffix = random.choice(VPA_SUFFIXES)
|
| 119 |
+
|
| 120 |
+
# Fill template
|
| 121 |
+
text = template.format(
|
| 122 |
+
amount=amount,
|
| 123 |
+
account=account,
|
| 124 |
+
reference=reference,
|
| 125 |
+
date=date,
|
| 126 |
+
merchant=merchant,
|
| 127 |
+
category=category,
|
| 128 |
+
balance=balance,
|
| 129 |
+
sender=sender,
|
| 130 |
+
suffix=suffix
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# Create entities
|
| 134 |
+
entities = {
|
| 135 |
+
'amount': amount.replace(',', ''),
|
| 136 |
+
'type': 'credit' if is_credit else 'debit',
|
| 137 |
+
'date': date,
|
| 138 |
+
'account': account,
|
| 139 |
+
'reference': reference
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
if not is_credit:
|
| 143 |
+
entities['merchant'] = merchant
|
| 144 |
+
entities['category'] = category
|
| 145 |
+
|
| 146 |
+
# Create training format (prompt/completion)
|
| 147 |
+
prompt = f"""Extract financial entities from this ICICI Bank email:
|
| 148 |
+
|
| 149 |
+
{text}
|
| 150 |
+
|
| 151 |
+
Extract: amount, type, date, account, reference{', merchant, category' if not is_credit else ''}
|
| 152 |
+
Output JSON:"""
|
| 153 |
+
|
| 154 |
+
completion = json.dumps(entities, indent=2)
|
| 155 |
+
|
| 156 |
+
sample = {
|
| 157 |
+
'prompt': prompt,
|
| 158 |
+
'completion': completion,
|
| 159 |
+
'bank': 'icici',
|
| 160 |
+
'entities': entities
|
| 161 |
+
}
|
| 162 |
+
samples.append(sample)
|
| 163 |
+
|
| 164 |
+
# Save
|
| 165 |
+
OUTPUT_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 166 |
+
with open(OUTPUT_FILE, 'w') as f:
|
| 167 |
+
for sample in samples:
|
| 168 |
+
f.write(json.dumps(sample) + '\n')
|
| 169 |
+
|
| 170 |
+
print(f"β
Generated {len(samples)} ICICI samples")
|
| 171 |
+
print(f" Saved to {OUTPUT_FILE}")
|
| 172 |
+
|
| 173 |
+
# Show sample
|
| 174 |
+
print("\nπ§ Sample:")
|
| 175 |
+
print(samples[0]['prompt'][:300])
|
| 176 |
+
|
| 177 |
+
return samples
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
generate_icici_samples(100)
|
scripts/generate_payment_app_data.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Payment App Statement Generator for Phase 3.
|
| 3 |
+
|
| 4 |
+
Generates synthetic training data for PhonePe, GPay, and Paytm
|
| 5 |
+
statement formats with proper prefixes and entity labeling.
|
| 6 |
+
|
| 7 |
+
Supported Apps:
|
| 8 |
+
- PhonePe: [PHONEPE] prefix
|
| 9 |
+
- GPay: [GPAY] prefix
|
| 10 |
+
- Paytm: [PAYTM] prefix
|
| 11 |
+
|
| 12 |
+
Example:
|
| 13 |
+
>>> from scripts.generate_payment_app_data import generate_all
|
| 14 |
+
>>> result = generate_all(samples_per_app=300)
|
| 15 |
+
|
| 16 |
+
Author: Ranjit Behera
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import random
|
| 21 |
+
from datetime import datetime, timedelta
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import List, Dict, Any, Tuple
|
| 24 |
+
|
| 25 |
+
# Seed for reproducibility
|
| 26 |
+
random.seed(42)
|
| 27 |
+
|
| 28 |
+
# PhonePe statement formats
|
| 29 |
+
PHONEPE_FORMATS = [
|
| 30 |
+
# Transaction history format
|
| 31 |
+
"{date} | {type_text} | {merchant} | βΉ{amount} | {status}",
|
| 32 |
+
"{date} {time} | {merchant} | {type_text} Rs.{amount} | Txn ID: {ref}",
|
| 33 |
+
"PhonePe: {type_text} of βΉ{amount} to {merchant} on {date}. UPI Ref: {ref}",
|
| 34 |
+
"{date} - {merchant}@ybl - βΉ{amount} - {status} - Ref: {ref}",
|
| 35 |
+
"Transaction: {type_text} | Amount: βΉ{amount} | To: {merchant} | {date}",
|
| 36 |
+
"{type_text}: βΉ{amount} | {merchant} | {date} {time} | ID: {ref}",
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
# GPay statement formats
|
| 40 |
+
GPAY_FORMATS = [
|
| 41 |
+
# Google Pay export format
|
| 42 |
+
"{date},{merchant},{amount},{type_text},{status},{upi_id},{ref}",
|
| 43 |
+
"Google Pay: {type_text} of βΉ{amount} to {merchant}. {date}. Ref {ref}",
|
| 44 |
+
"{date} | {merchant} | βΉ{amount} {type_text} | UPI: {upi_id} | {ref}",
|
| 45 |
+
"You {action} βΉ{amount} {direction} {merchant}. {date}. UPI Ref: {ref}. -Google Pay",
|
| 46 |
+
"GPay Transaction: {date} | {merchant} | {type_text} βΉ{amount} | Ref: {ref}",
|
| 47 |
+
"{date} {time} - {type_text} - {merchant} - Rs {amount} - {ref}",
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
# Paytm statement formats
|
| 51 |
+
PAYTM_FORMATS = [
|
| 52 |
+
# Paytm history format
|
| 53 |
+
"{date} | {merchant} | {type_text} | βΉ{amount} | {wallet_balance}",
|
| 54 |
+
"Paytm: {type_text} of Rs.{amount} to {merchant}. {date}. Order ID: {ref}",
|
| 55 |
+
"{date} {time} | {type_text} βΉ{amount} | {merchant} | Paytm | Ref: {ref}",
|
| 56 |
+
"You {action} Rs.{amount} to {merchant} using Paytm on {date}. ID: {ref}",
|
| 57 |
+
"Transaction: {date} | {merchant} | Rs {amount} | Type: {type_text} | {status}",
|
| 58 |
+
"Paytm Wallet: {type_text} Rs.{amount} | {merchant} | Balance: βΉ{wallet_balance} | {date}",
|
| 59 |
+
]
|
| 60 |
+
|
| 61 |
+
# Merchants by category
|
| 62 |
+
MERCHANTS_BY_CATEGORY = {
|
| 63 |
+
"food": [
|
| 64 |
+
"Swiggy", "Zomato", "Dominos", "McDonalds", "KFC", "Pizza Hut",
|
| 65 |
+
"Burger King", "Starbucks", "Cafe Coffee Day", "Subway",
|
| 66 |
+
"Behrouz Biryani", "Faasos", "Box8", "EatFit", "Haldirams"
|
| 67 |
+
],
|
| 68 |
+
"shopping": [
|
| 69 |
+
"Amazon", "Flipkart", "Myntra", "Ajio", "Nykaa", "Meesho",
|
| 70 |
+
"Snapdeal", "Shopclues", "Tata Cliq", "FirstCry",
|
| 71 |
+
"Bewakoof", "Urbanic", "Shein", "H&M", "Zara"
|
| 72 |
+
],
|
| 73 |
+
"grocery": [
|
| 74 |
+
"BigBasket", "Zepto", "Blinkit", "Dunzo", "JioMart",
|
| 75 |
+
"Amazon Fresh", "Swiggy Instamart", "DMart Ready",
|
| 76 |
+
"Grofers", "Nature's Basket", "Spencer's", "More Supermarket"
|
| 77 |
+
],
|
| 78 |
+
"transport": [
|
| 79 |
+
"Uber", "Ola", "Rapido", "BluSmart", "IRCTC",
|
| 80 |
+
"RedBus", "AbhiBus", "MakeMyTrip", "Goibibo", "Yatra",
|
| 81 |
+
"Cleartrip", "EaseMyTrip", "IndiGo", "SpiceJet", "Air India"
|
| 82 |
+
],
|
| 83 |
+
"bills": [
|
| 84 |
+
"Airtel", "Jio", "Vodafone Idea", "BSNL", "ACT Fibernet",
|
| 85 |
+
"Tata Power", "Adani Electricity", "MSEB", "BESCOM",
|
| 86 |
+
"Mahanagar Gas", "Indraprastha Gas", "Gujarat Gas"
|
| 87 |
+
],
|
| 88 |
+
"entertainment": [
|
| 89 |
+
"Netflix", "Amazon Prime", "Hotstar", "Zee5", "SonyLiv",
|
| 90 |
+
"Spotify", "Gaana", "JioSaavn", "Apple Music", "YouTube Premium",
|
| 91 |
+
"BookMyShow", "PVR", "INOX", "Carnival Cinemas"
|
| 92 |
+
],
|
| 93 |
+
"recharge": [
|
| 94 |
+
"Airtel Prepaid", "Jio Prepaid", "Vi Prepaid", "BSNL Mobile",
|
| 95 |
+
"Airtel DTH", "Tata Play", "Dish TV", "d2h", "Sun Direct"
|
| 96 |
+
],
|
| 97 |
+
"transfer": [
|
| 98 |
+
"Self Transfer", "Rahul Kumar", "Priya Sharma", "Amit Singh",
|
| 99 |
+
"Neha Patel", "Vikram Reddy", "Bank Transfer", "UPI Transfer"
|
| 100 |
+
],
|
| 101 |
+
"investment": [
|
| 102 |
+
"Zerodha", "Groww", "Upstox", "Angel One", "5paisa",
|
| 103 |
+
"Coin by Zerodha", "Kuvera", "INDmoney", "ET Money",
|
| 104 |
+
"Paytm Money", "PhonePe Mutual Funds", "Scripbox"
|
| 105 |
+
],
|
| 106 |
+
"insurance": [
|
| 107 |
+
"LIC", "HDFC Life", "ICICI Pru", "SBI Life", "Max Life",
|
| 108 |
+
"Bajaj Allianz", "Tata AIA", "PolicyBazaar", "Digit Insurance"
|
| 109 |
+
],
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
# UPI IDs by app
|
| 113 |
+
UPI_SUFFIXES = {
|
| 114 |
+
"phonepe": ["@ybl", "@ibl", "@axl"],
|
| 115 |
+
"gpay": ["@okaxis", "@okhdfcbank", "@okicici", "@oksbi"],
|
| 116 |
+
"paytm": ["@paytm", "@pthdfc", "@ptaxis", "@ptsbi"],
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
# Status options
|
| 120 |
+
STATUSES = ["Success", "Successful", "Completed", "Done", "Processed"]
|
| 121 |
+
FAILED_STATUSES = ["Failed", "Declined", "Cancelled", "Pending"]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def random_date(days_back: int = 180) -> Tuple[str, str]:
|
| 125 |
+
"""Generate random date and time."""
|
| 126 |
+
days_ago = random.randint(0, days_back)
|
| 127 |
+
dt = datetime.now() - timedelta(days=days_ago)
|
| 128 |
+
|
| 129 |
+
date_formats = [
|
| 130 |
+
"%d-%m-%Y", "%d/%m/%Y", "%d %b %Y", "%d %b, %Y",
|
| 131 |
+
"%Y-%m-%d", "%d-%m-%y", "%b %d, %Y"
|
| 132 |
+
]
|
| 133 |
+
time_formats = ["%H:%M", "%I:%M %p", "%H:%M:%S"]
|
| 134 |
+
|
| 135 |
+
date_str = dt.strftime(random.choice(date_formats))
|
| 136 |
+
time_str = dt.strftime(random.choice(time_formats))
|
| 137 |
+
|
| 138 |
+
return date_str, time_str
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def random_amount(category: str = None) -> str:
|
| 142 |
+
"""Generate random amount based on category."""
|
| 143 |
+
ranges = {
|
| 144 |
+
"food": (50, 2000),
|
| 145 |
+
"shopping": (200, 15000),
|
| 146 |
+
"grocery": (100, 5000),
|
| 147 |
+
"transport": (50, 5000),
|
| 148 |
+
"bills": (200, 10000),
|
| 149 |
+
"entertainment": (99, 1500),
|
| 150 |
+
"recharge": (100, 2000),
|
| 151 |
+
"transfer": (500, 50000),
|
| 152 |
+
"investment": (500, 50000),
|
| 153 |
+
"insurance": (1000, 30000),
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
min_val, max_val = ranges.get(category, (50, 10000))
|
| 157 |
+
amount = random.uniform(min_val, max_val)
|
| 158 |
+
|
| 159 |
+
if random.random() < 0.4:
|
| 160 |
+
return f"{amount:,.2f}"
|
| 161 |
+
else:
|
| 162 |
+
return f"{int(amount):,}"
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def random_ref(prefix: str = "") -> str:
|
| 166 |
+
"""Generate random reference number."""
|
| 167 |
+
length = random.choice([10, 12, 14, 16])
|
| 168 |
+
ref = ''.join(str(random.randint(0, 9)) for _ in range(length))
|
| 169 |
+
return f"{prefix}{ref}" if prefix else ref
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def random_wallet_balance() -> str:
|
| 173 |
+
"""Generate random wallet balance."""
|
| 174 |
+
balance = random.uniform(100, 10000)
|
| 175 |
+
return f"{balance:,.2f}"
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def generate_phonepe_row() -> Dict[str, Any]:
|
| 179 |
+
"""Generate a PhonePe statement row."""
|
| 180 |
+
category = random.choice(list(MERCHANTS_BY_CATEGORY.keys()))
|
| 181 |
+
merchant = random.choice(MERCHANTS_BY_CATEGORY[category])
|
| 182 |
+
is_credit = category == "transfer" and random.random() < 0.3
|
| 183 |
+
|
| 184 |
+
date_str, time_str = random_date()
|
| 185 |
+
amount = random_amount(category)
|
| 186 |
+
ref = random_ref()
|
| 187 |
+
status = random.choice(STATUSES)
|
| 188 |
+
upi_suffix = random.choice(UPI_SUFFIXES["phonepe"])
|
| 189 |
+
|
| 190 |
+
type_text = "Received" if is_credit else "Paid"
|
| 191 |
+
|
| 192 |
+
template = random.choice(PHONEPE_FORMATS)
|
| 193 |
+
raw_text = template.format(
|
| 194 |
+
date=date_str,
|
| 195 |
+
time=time_str,
|
| 196 |
+
merchant=merchant,
|
| 197 |
+
amount=amount,
|
| 198 |
+
type_text=type_text,
|
| 199 |
+
status=status,
|
| 200 |
+
ref=ref,
|
| 201 |
+
upi_id=f"{merchant.lower().replace(' ', '')}{upi_suffix}"
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
entities = {
|
| 205 |
+
"date": date_str,
|
| 206 |
+
"amount": amount.replace(",", ""),
|
| 207 |
+
"type": "credit" if is_credit else "debit",
|
| 208 |
+
"merchant": merchant.lower(),
|
| 209 |
+
"category": category,
|
| 210 |
+
"reference": ref,
|
| 211 |
+
"status": status.lower(),
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
return {
|
| 215 |
+
"app": "phonepe",
|
| 216 |
+
"prefix": "[PHONEPE]",
|
| 217 |
+
"raw_text": raw_text,
|
| 218 |
+
"labeled": True,
|
| 219 |
+
"entities": entities
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def generate_gpay_row() -> Dict[str, Any]:
|
| 224 |
+
"""Generate a GPay statement row."""
|
| 225 |
+
category = random.choice(list(MERCHANTS_BY_CATEGORY.keys()))
|
| 226 |
+
merchant = random.choice(MERCHANTS_BY_CATEGORY[category])
|
| 227 |
+
is_credit = category == "transfer" and random.random() < 0.3
|
| 228 |
+
|
| 229 |
+
date_str, time_str = random_date()
|
| 230 |
+
amount = random_amount(category)
|
| 231 |
+
ref = random_ref()
|
| 232 |
+
status = random.choice(STATUSES)
|
| 233 |
+
upi_suffix = random.choice(UPI_SUFFIXES["gpay"])
|
| 234 |
+
upi_id = f"{merchant.lower().replace(' ', '')}{upi_suffix}"
|
| 235 |
+
|
| 236 |
+
type_text = "Credit" if is_credit else "Debit"
|
| 237 |
+
action = "received" if is_credit else "paid"
|
| 238 |
+
direction = "from" if is_credit else "to"
|
| 239 |
+
|
| 240 |
+
template = random.choice(GPAY_FORMATS)
|
| 241 |
+
raw_text = template.format(
|
| 242 |
+
date=date_str,
|
| 243 |
+
time=time_str,
|
| 244 |
+
merchant=merchant,
|
| 245 |
+
amount=amount,
|
| 246 |
+
type_text=type_text,
|
| 247 |
+
status=status,
|
| 248 |
+
ref=ref,
|
| 249 |
+
upi_id=upi_id,
|
| 250 |
+
action=action,
|
| 251 |
+
direction=direction
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
entities = {
|
| 255 |
+
"date": date_str,
|
| 256 |
+
"amount": amount.replace(",", ""),
|
| 257 |
+
"type": "credit" if is_credit else "debit",
|
| 258 |
+
"merchant": merchant.lower(),
|
| 259 |
+
"category": category,
|
| 260 |
+
"reference": ref,
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
return {
|
| 264 |
+
"app": "gpay",
|
| 265 |
+
"prefix": "[GPAY]",
|
| 266 |
+
"raw_text": raw_text,
|
| 267 |
+
"labeled": True,
|
| 268 |
+
"entities": entities
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def generate_paytm_row() -> Dict[str, Any]:
|
| 273 |
+
"""Generate a Paytm statement row."""
|
| 274 |
+
category = random.choice(list(MERCHANTS_BY_CATEGORY.keys()))
|
| 275 |
+
merchant = random.choice(MERCHANTS_BY_CATEGORY[category])
|
| 276 |
+
is_credit = category == "transfer" and random.random() < 0.3
|
| 277 |
+
|
| 278 |
+
date_str, time_str = random_date()
|
| 279 |
+
amount = random_amount(category)
|
| 280 |
+
ref = random_ref("ORD")
|
| 281 |
+
status = random.choice(STATUSES)
|
| 282 |
+
wallet_balance = random_wallet_balance()
|
| 283 |
+
|
| 284 |
+
type_text = "Credit" if is_credit else "Debit"
|
| 285 |
+
action = "received" if is_credit else "sent"
|
| 286 |
+
|
| 287 |
+
template = random.choice(PAYTM_FORMATS)
|
| 288 |
+
raw_text = template.format(
|
| 289 |
+
date=date_str,
|
| 290 |
+
time=time_str,
|
| 291 |
+
merchant=merchant,
|
| 292 |
+
amount=amount,
|
| 293 |
+
type_text=type_text,
|
| 294 |
+
status=status,
|
| 295 |
+
ref=ref,
|
| 296 |
+
wallet_balance=wallet_balance,
|
| 297 |
+
action=action
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
entities = {
|
| 301 |
+
"date": date_str,
|
| 302 |
+
"amount": amount.replace(",", ""),
|
| 303 |
+
"type": "credit" if is_credit else "debit",
|
| 304 |
+
"merchant": merchant.lower(),
|
| 305 |
+
"category": category,
|
| 306 |
+
"reference": ref,
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
if "Wallet" in template:
|
| 310 |
+
entities["wallet_balance"] = wallet_balance.replace(",", "")
|
| 311 |
+
|
| 312 |
+
return {
|
| 313 |
+
"app": "paytm",
|
| 314 |
+
"prefix": "[PAYTM]",
|
| 315 |
+
"raw_text": raw_text,
|
| 316 |
+
"labeled": True,
|
| 317 |
+
"entities": entities
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def generate_all(
|
| 322 |
+
samples_per_app: int = 300,
|
| 323 |
+
output_dir: str = "data/training"
|
| 324 |
+
) -> Dict[str, Any]:
|
| 325 |
+
"""
|
| 326 |
+
Generate complete training dataset for all payment apps.
|
| 327 |
+
|
| 328 |
+
Args:
|
| 329 |
+
samples_per_app: Number of samples per app.
|
| 330 |
+
output_dir: Output directory for JSONL files.
|
| 331 |
+
|
| 332 |
+
Returns:
|
| 333 |
+
Summary dictionary with stats.
|
| 334 |
+
"""
|
| 335 |
+
generators = {
|
| 336 |
+
"phonepe": generate_phonepe_row,
|
| 337 |
+
"gpay": generate_gpay_row,
|
| 338 |
+
"paytm": generate_paytm_row,
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
all_samples = []
|
| 342 |
+
|
| 343 |
+
for app, generator in generators.items():
|
| 344 |
+
for _ in range(samples_per_app):
|
| 345 |
+
sample = generator()
|
| 346 |
+
all_samples.append(sample)
|
| 347 |
+
|
| 348 |
+
# Shuffle
|
| 349 |
+
random.shuffle(all_samples)
|
| 350 |
+
|
| 351 |
+
# Convert to training format with app-specific prefix
|
| 352 |
+
training_data = []
|
| 353 |
+
for sample in all_samples:
|
| 354 |
+
prefix = sample["prefix"]
|
| 355 |
+
prompt = f"{prefix} Extract financial entities from this payment app statement:\n\n{sample['raw_text']}"
|
| 356 |
+
completion = json.dumps(sample["entities"], indent=2)
|
| 357 |
+
training_data.append({
|
| 358 |
+
"prompt": prompt,
|
| 359 |
+
"completion": completion,
|
| 360 |
+
"app": sample["app"] # Keep for analysis
|
| 361 |
+
})
|
| 362 |
+
|
| 363 |
+
# Split train/valid
|
| 364 |
+
split_idx = int(len(training_data) * 0.9)
|
| 365 |
+
train_data = training_data[:split_idx]
|
| 366 |
+
valid_data = training_data[split_idx:]
|
| 367 |
+
|
| 368 |
+
# Save files
|
| 369 |
+
output_path = Path(output_dir)
|
| 370 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 371 |
+
|
| 372 |
+
train_file = output_path / "payment_apps_train.jsonl"
|
| 373 |
+
valid_file = output_path / "payment_apps_valid.jsonl"
|
| 374 |
+
|
| 375 |
+
# Remove app field before saving (just for tracking)
|
| 376 |
+
for filepath, data in [(train_file, train_data), (valid_file, valid_data)]:
|
| 377 |
+
with open(filepath, 'w') as f:
|
| 378 |
+
for item in data:
|
| 379 |
+
save_item = {"prompt": item["prompt"], "completion": item["completion"]}
|
| 380 |
+
f.write(json.dumps(save_item) + '\n')
|
| 381 |
+
|
| 382 |
+
# Save raw samples for reference
|
| 383 |
+
samples_file = output_path / "payment_apps_samples.json"
|
| 384 |
+
with open(samples_file, 'w') as f:
|
| 385 |
+
json.dump(all_samples, f, indent=2)
|
| 386 |
+
|
| 387 |
+
# Stats by app
|
| 388 |
+
app_counts = {}
|
| 389 |
+
for sample in all_samples:
|
| 390 |
+
app = sample["app"]
|
| 391 |
+
app_counts[app] = app_counts.get(app, 0) + 1
|
| 392 |
+
|
| 393 |
+
return {
|
| 394 |
+
"total_samples": len(all_samples),
|
| 395 |
+
"train_samples": len(train_data),
|
| 396 |
+
"valid_samples": len(valid_data),
|
| 397 |
+
"by_app": app_counts,
|
| 398 |
+
"train_file": str(train_file),
|
| 399 |
+
"valid_file": str(valid_file),
|
| 400 |
+
"samples_file": str(samples_file)
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def main():
|
| 405 |
+
"""Generate Phase 3 training data."""
|
| 406 |
+
print("π³ Generating Phase 3: Payment App Statement Data")
|
| 407 |
+
print("=" * 60)
|
| 408 |
+
|
| 409 |
+
result = generate_all(samples_per_app=300)
|
| 410 |
+
|
| 411 |
+
print(f"\nβ
Generated {result['total_samples']} samples")
|
| 412 |
+
print(f"\nπ± By App:")
|
| 413 |
+
for app, count in result['by_app'].items():
|
| 414 |
+
prefix = {"phonepe": "[PHONEPE]", "gpay": "[GPAY]", "paytm": "[PAYTM]"}[app]
|
| 415 |
+
print(f" {app.upper():10} {prefix:12} {count} samples")
|
| 416 |
+
|
| 417 |
+
print(f"\nπ Split:")
|
| 418 |
+
print(f" Train: {result['train_samples']} samples")
|
| 419 |
+
print(f" Valid: {result['valid_samples']} samples")
|
| 420 |
+
|
| 421 |
+
print(f"\nπ Files created:")
|
| 422 |
+
print(f" {result['train_file']}")
|
| 423 |
+
print(f" {result['valid_file']}")
|
| 424 |
+
print(f" {result['samples_file']}")
|
| 425 |
+
|
| 426 |
+
# Show sample
|
| 427 |
+
print("\nπ Sample entries:")
|
| 428 |
+
with open(result['train_file']) as f:
|
| 429 |
+
for i, line in enumerate(f):
|
| 430 |
+
if i >= 3:
|
| 431 |
+
break
|
| 432 |
+
sample = json.loads(line)
|
| 433 |
+
print(f"\n [{i+1}] {sample['prompt'][:80]}...")
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
if __name__ == "__main__":
|
| 437 |
+
main()
|
scripts/generate_statement_data.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generate synthetic bank statement training data for Phase 2.
|
| 3 |
+
|
| 4 |
+
Creates realistic bank statement row samples for all supported banks
|
| 5 |
+
with proper labeling, ready for training.
|
| 6 |
+
|
| 7 |
+
Author: Ranjit Behera
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import random
|
| 12 |
+
from datetime import datetime, timedelta
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import List, Dict, Any
|
| 15 |
+
|
| 16 |
+
# Seed for reproducibility
|
| 17 |
+
random.seed(42)
|
| 18 |
+
|
| 19 |
+
# Bank-specific row formats
|
| 20 |
+
BANK_FORMATS = {
|
| 21 |
+
"hdfc": [
|
| 22 |
+
"{date} | {desc} | {debit} | {credit} | {balance}",
|
| 23 |
+
"{date} {desc} DR:{debit} BAL:{balance}",
|
| 24 |
+
"{date} {desc} Withdrawal: Rs.{debit} Balance: Rs.{balance}",
|
| 25 |
+
],
|
| 26 |
+
"icici": [
|
| 27 |
+
"{date} | {desc} | {debit} | {credit} | {balance}",
|
| 28 |
+
"{date}//ICICI//{desc}//AMT:{amount}//BAL:{balance}",
|
| 29 |
+
"{date} - {desc} - Rs.{amount} - Bal: Rs.{balance}",
|
| 30 |
+
],
|
| 31 |
+
"sbi": [
|
| 32 |
+
"{date} | {desc} | {debit} | {credit} | {balance}",
|
| 33 |
+
"SBI/{date}/{desc}/Rs.{amount}/Bal.{balance}",
|
| 34 |
+
"{date} {desc} Amount: {amount} Available: {balance}",
|
| 35 |
+
],
|
| 36 |
+
"axis": [
|
| 37 |
+
"{date} | {desc} | {debit} | {credit} | {balance}",
|
| 38 |
+
"AXIS-{date}-{desc}-{amount}-{balance}",
|
| 39 |
+
"{date} >> {desc} >> Rs {amount} >> Bal Rs {balance}",
|
| 40 |
+
],
|
| 41 |
+
"kotak": [
|
| 42 |
+
"{date} | {desc} | {debit} | {credit} | {balance}",
|
| 43 |
+
"{date} KOTAK {desc} {amount} BAL:{balance}",
|
| 44 |
+
"{date}: {desc} | Amount: Rs.{amount} | Balance: Rs.{balance}",
|
| 45 |
+
],
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
# Transaction descriptions by category
|
| 49 |
+
DESCRIPTIONS = {
|
| 50 |
+
"upi": [
|
| 51 |
+
"UPI-{merchant}@ybl-PAYMENT",
|
| 52 |
+
"UPI/{merchant}/{ref}",
|
| 53 |
+
"UPI-TRANSFER-{merchant}",
|
| 54 |
+
"IMPS/P2P/{name}",
|
| 55 |
+
"UPI-{phone}-{merchant}",
|
| 56 |
+
"{merchant}@paytm-UPI",
|
| 57 |
+
"UPI-{name}-{ref}",
|
| 58 |
+
],
|
| 59 |
+
"neft": [
|
| 60 |
+
"NEFT-{name}-{ref}",
|
| 61 |
+
"NEFT CR-{bank}-{name}",
|
| 62 |
+
"NEFT/TRANSFER/{account}/{name}",
|
| 63 |
+
"NEFT-INW-{ref}-{name}",
|
| 64 |
+
"RTGS-{bank}-{name}-{ref}",
|
| 65 |
+
],
|
| 66 |
+
"card": [
|
| 67 |
+
"POS {merchant} {city}",
|
| 68 |
+
"ATM WDL {city} {ref}",
|
| 69 |
+
"CARD TXN-{merchant}",
|
| 70 |
+
"ECOM/{merchant}/ONLINE",
|
| 71 |
+
"CC PAYMENT-{card}",
|
| 72 |
+
"DEBIT CARD {merchant} {city}",
|
| 73 |
+
],
|
| 74 |
+
"emi": [
|
| 75 |
+
"EMI-{merchant}-{ref}",
|
| 76 |
+
"AUTO-DEBIT-{merchant}",
|
| 77 |
+
"SB/AUTODR/{merchant}",
|
| 78 |
+
"LOAN EMI-{ref}",
|
| 79 |
+
"ECS/{merchant}/PAYMENT",
|
| 80 |
+
],
|
| 81 |
+
"bill": [
|
| 82 |
+
"BILL PAY-{merchant}",
|
| 83 |
+
"AUTOPAY-{merchant}-{ref}",
|
| 84 |
+
"{merchant} BILL PAYMENT",
|
| 85 |
+
"BBPS/{merchant}/{ref}",
|
| 86 |
+
"ELECTRICITY-{merchant}",
|
| 87 |
+
"MOBILE RECHARGE-{phone}",
|
| 88 |
+
],
|
| 89 |
+
"transfer": [
|
| 90 |
+
"FT-{name}-{account}",
|
| 91 |
+
"SELF TRF-{account}",
|
| 92 |
+
"FUND TRANSFER-{name}",
|
| 93 |
+
"A/C TRANSFER-{ref}",
|
| 94 |
+
"INT TRF-{name}",
|
| 95 |
+
],
|
| 96 |
+
"salary": [
|
| 97 |
+
"SALARY-{company}",
|
| 98 |
+
"SAL-{month}-{company}",
|
| 99 |
+
"NEFT-SALARY-{company}",
|
| 100 |
+
"PAYROLL-{company}-{ref}",
|
| 101 |
+
],
|
| 102 |
+
"cash": [
|
| 103 |
+
"CASH DEP-{city}",
|
| 104 |
+
"ATM DEP-{ref}",
|
| 105 |
+
"CASH DEPOSIT-BR:{branch}",
|
| 106 |
+
"CDM DEPOSIT-{city}",
|
| 107 |
+
],
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
MERCHANTS = [
|
| 111 |
+
"Amazon", "Flipkart", "Swiggy", "Zomato", "Uber", "Ola",
|
| 112 |
+
"BigBasket", "Zepto", "Blinkit", "Dunzo", "Netflix", "Spotify",
|
| 113 |
+
"JioMart", "Myntra", "Nykaa", "BookMyShow", "MakeMyTrip",
|
| 114 |
+
"PhonePe", "Paytm", "HDFC Life", "ICICI Pru", "Airtel", "Jio",
|
| 115 |
+
"Vodafone", "BSNL", "TATA Play", "Hotstar", "Prime Video",
|
| 116 |
+
"GooglePlay", "AppStore", "LinkedIn", "Udemy", "Coursera",
|
| 117 |
+
"LIC", "SBI Life", "Bajaj Finserv", "Tata Capital"
|
| 118 |
+
]
|
| 119 |
+
|
| 120 |
+
NAMES = [
|
| 121 |
+
"Rahul Kumar", "Priya Sharma", "Amit Singh", "Neha Patel",
|
| 122 |
+
"Vikram Reddy", "Anjali Gupta", "Ravi Verma", "Pooja Joshi",
|
| 123 |
+
"Suresh Menon", "Kavita Nair", "Arun Krishnan", "Deepa Iyer",
|
| 124 |
+
"Sanjay Kapoor", "Meera Rao", "Kiran Hegde", "Anita Desai"
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
COMPANIES = [
|
| 128 |
+
"TCS", "Infosys", "Wipro", "HCL Tech", "Tech Mahindra",
|
| 129 |
+
"Accenture", "IBM India", "Microsoft", "Google", "Amazon",
|
| 130 |
+
"Flipkart", "Paytm", "Reliance", "HDFC Bank", "ICICI Bank"
|
| 131 |
+
]
|
| 132 |
+
|
| 133 |
+
BANKS = ["HDFC", "ICICI", "SBI", "AXIS", "KOTAK", "YES", "IDFC", "RBL"]
|
| 134 |
+
CITIES = ["Mumbai", "Delhi", "Bangalore", "Chennai", "Pune", "Hyderabad", "Kolkata", "Ahmedabad"]
|
| 135 |
+
MONTHS = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]
|
| 136 |
+
|
| 137 |
+
# Category mapping
|
| 138 |
+
CATEGORY_MAP = {
|
| 139 |
+
"upi": ["food", "shopping", "transport", "bills", "transfer"],
|
| 140 |
+
"neft": ["transfer", "salary", "investment"],
|
| 141 |
+
"card": ["shopping", "food", "travel", "entertainment"],
|
| 142 |
+
"emi": ["loan", "shopping"],
|
| 143 |
+
"bill": ["bills", "utilities", "telecom"],
|
| 144 |
+
"transfer": ["transfer"],
|
| 145 |
+
"salary": ["salary"],
|
| 146 |
+
"cash": ["cash"],
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def random_date(days_back: int = 180) -> str:
|
| 151 |
+
"""Generate random date."""
|
| 152 |
+
days_ago = random.randint(0, days_back)
|
| 153 |
+
date = datetime.now() - timedelta(days=days_ago)
|
| 154 |
+
|
| 155 |
+
formats = [
|
| 156 |
+
"%d-%m-%Y", "%d/%m/%Y", "%d-%m-%y",
|
| 157 |
+
"%d %b %Y", "%d %b %y", "%Y-%m-%d"
|
| 158 |
+
]
|
| 159 |
+
return date.strftime(random.choice(formats))
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def random_amount(min_val: int = 50, max_val: int = 50000) -> str:
|
| 163 |
+
"""Generate random amount."""
|
| 164 |
+
amount = random.uniform(min_val, max_val)
|
| 165 |
+
|
| 166 |
+
if random.random() < 0.4:
|
| 167 |
+
return f"{amount:,.2f}"
|
| 168 |
+
else:
|
| 169 |
+
return f"{int(amount):,}"
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def random_balance() -> str:
|
| 173 |
+
"""Generate random balance."""
|
| 174 |
+
balance = random.uniform(10000, 500000)
|
| 175 |
+
return f"{balance:,.2f}"
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def random_ref() -> str:
|
| 179 |
+
"""Generate random reference number."""
|
| 180 |
+
length = random.choice([8, 10, 12])
|
| 181 |
+
return ''.join(str(random.randint(0, 9)) for _ in range(length))
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def random_account() -> str:
|
| 185 |
+
"""Generate random account suffix."""
|
| 186 |
+
return ''.join(str(random.randint(0, 9)) for _ in range(4))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def random_phone() -> str:
|
| 190 |
+
"""Generate random phone number."""
|
| 191 |
+
return ''.join(str(random.randint(0, 9)) for _ in range(10))
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def random_card() -> str:
|
| 195 |
+
"""Generate random card suffix."""
|
| 196 |
+
return "XX" + ''.join(str(random.randint(0, 9)) for _ in range(4))
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def generate_description(txn_type: str) -> tuple:
|
| 200 |
+
"""Generate description and metadata."""
|
| 201 |
+
templates = DESCRIPTIONS[txn_type]
|
| 202 |
+
template = random.choice(templates)
|
| 203 |
+
|
| 204 |
+
merchant = random.choice(MERCHANTS)
|
| 205 |
+
name = random.choice(NAMES)
|
| 206 |
+
|
| 207 |
+
desc = template.format(
|
| 208 |
+
merchant=merchant,
|
| 209 |
+
name=name,
|
| 210 |
+
ref=random_ref(),
|
| 211 |
+
bank=random.choice(BANKS),
|
| 212 |
+
account=random_account(),
|
| 213 |
+
city=random.choice(CITIES),
|
| 214 |
+
phone=random_phone(),
|
| 215 |
+
card=random_card(),
|
| 216 |
+
company=random.choice(COMPANIES),
|
| 217 |
+
month=random.choice(MONTHS),
|
| 218 |
+
branch=f"{random.randint(1, 99):02d}"
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
# Determine merchant for category
|
| 222 |
+
if txn_type in ["upi", "card", "emi", "bill"]:
|
| 223 |
+
detected_merchant = merchant.lower()
|
| 224 |
+
else:
|
| 225 |
+
detected_merchant = None
|
| 226 |
+
|
| 227 |
+
# Determine category
|
| 228 |
+
categories = CATEGORY_MAP.get(txn_type, ["other"])
|
| 229 |
+
category = random.choice(categories)
|
| 230 |
+
|
| 231 |
+
return desc, detected_merchant, category
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def generate_row(bank: str) -> Dict[str, Any]:
|
| 235 |
+
"""Generate a single bank statement row."""
|
| 236 |
+
# Transaction type weights
|
| 237 |
+
txn_types = ["upi"] * 40 + ["card"] * 20 + ["neft"] * 15 + ["bill"] * 10 + \
|
| 238 |
+
["emi"] * 5 + ["transfer"] * 5 + ["salary"] * 3 + ["cash"] * 2
|
| 239 |
+
txn_type = random.choice(txn_types)
|
| 240 |
+
|
| 241 |
+
# Generate data
|
| 242 |
+
date = random_date()
|
| 243 |
+
desc, merchant, category = generate_description(txn_type)
|
| 244 |
+
|
| 245 |
+
# Debit or credit
|
| 246 |
+
is_credit = txn_type in ["salary", "cash", "neft"] and random.random() < 0.7
|
| 247 |
+
|
| 248 |
+
if txn_type == "salary":
|
| 249 |
+
amount = random_amount(30000, 150000)
|
| 250 |
+
elif txn_type == "emi":
|
| 251 |
+
amount = random_amount(5000, 30000)
|
| 252 |
+
elif txn_type == "cash" and is_credit:
|
| 253 |
+
amount = random_amount(5000, 50000)
|
| 254 |
+
else:
|
| 255 |
+
amount = random_amount(50, 25000)
|
| 256 |
+
|
| 257 |
+
balance = random_balance()
|
| 258 |
+
|
| 259 |
+
# Format based on bank
|
| 260 |
+
formats = BANK_FORMATS.get(bank, BANK_FORMATS["hdfc"])
|
| 261 |
+
template = random.choice(formats)
|
| 262 |
+
|
| 263 |
+
if is_credit:
|
| 264 |
+
raw_text = template.format(
|
| 265 |
+
date=date, desc=desc,
|
| 266 |
+
debit="", credit=amount,
|
| 267 |
+
balance=balance, amount=amount
|
| 268 |
+
)
|
| 269 |
+
else:
|
| 270 |
+
raw_text = template.format(
|
| 271 |
+
date=date, desc=desc,
|
| 272 |
+
debit=amount, credit="",
|
| 273 |
+
balance=balance, amount=amount
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
# Build entities
|
| 277 |
+
entities = {
|
| 278 |
+
"date": date,
|
| 279 |
+
"description": desc,
|
| 280 |
+
"amount": amount.replace(",", ""),
|
| 281 |
+
"type": "credit" if is_credit else "debit",
|
| 282 |
+
"balance": balance.replace(",", ""),
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
if merchant:
|
| 286 |
+
entities["merchant"] = merchant
|
| 287 |
+
entities["category"] = category
|
| 288 |
+
|
| 289 |
+
return {
|
| 290 |
+
"raw_text": raw_text,
|
| 291 |
+
"date": date,
|
| 292 |
+
"description": desc,
|
| 293 |
+
"debit": None if is_credit else amount,
|
| 294 |
+
"credit": amount if is_credit else None,
|
| 295 |
+
"balance": balance,
|
| 296 |
+
"bank": bank,
|
| 297 |
+
"labeled": True,
|
| 298 |
+
"entities": entities
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def generate_training_data(
|
| 303 |
+
samples_per_bank: int = 100,
|
| 304 |
+
output_dir: str = "data/training"
|
| 305 |
+
) -> Dict[str, Any]:
|
| 306 |
+
"""Generate complete training dataset."""
|
| 307 |
+
|
| 308 |
+
banks = ["hdfc", "icici", "sbi", "axis", "kotak"]
|
| 309 |
+
all_samples = []
|
| 310 |
+
|
| 311 |
+
for bank in banks:
|
| 312 |
+
for _ in range(samples_per_bank):
|
| 313 |
+
row = generate_row(bank)
|
| 314 |
+
all_samples.append(row)
|
| 315 |
+
|
| 316 |
+
# Shuffle
|
| 317 |
+
random.shuffle(all_samples)
|
| 318 |
+
|
| 319 |
+
# Convert to training format with [BANK_STATEMENT] prefix
|
| 320 |
+
training_data = []
|
| 321 |
+
for sample in all_samples:
|
| 322 |
+
prompt = f"[BANK_STATEMENT] Extract financial entities from this bank statement row:\n\n{sample['raw_text']}"
|
| 323 |
+
completion = json.dumps(sample['entities'], indent=2)
|
| 324 |
+
training_data.append({
|
| 325 |
+
"prompt": prompt,
|
| 326 |
+
"completion": completion
|
| 327 |
+
})
|
| 328 |
+
|
| 329 |
+
# Split train/valid
|
| 330 |
+
split_idx = int(len(training_data) * 0.9)
|
| 331 |
+
train_data = training_data[:split_idx]
|
| 332 |
+
valid_data = training_data[split_idx:]
|
| 333 |
+
|
| 334 |
+
# Save files
|
| 335 |
+
output_path = Path(output_dir)
|
| 336 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 337 |
+
|
| 338 |
+
train_file = output_path / "statement_train.jsonl"
|
| 339 |
+
valid_file = output_path / "statement_valid.jsonl"
|
| 340 |
+
|
| 341 |
+
with open(train_file, 'w') as f:
|
| 342 |
+
for item in train_data:
|
| 343 |
+
f.write(json.dumps(item) + '\n')
|
| 344 |
+
|
| 345 |
+
with open(valid_file, 'w') as f:
|
| 346 |
+
for item in valid_data:
|
| 347 |
+
f.write(json.dumps(item) + '\n')
|
| 348 |
+
|
| 349 |
+
# Also save raw samples for reference
|
| 350 |
+
samples_file = output_path / "statement_samples.json"
|
| 351 |
+
with open(samples_file, 'w') as f:
|
| 352 |
+
json.dump(all_samples, f, indent=2)
|
| 353 |
+
|
| 354 |
+
return {
|
| 355 |
+
"total_samples": len(all_samples),
|
| 356 |
+
"train_samples": len(train_data),
|
| 357 |
+
"valid_samples": len(valid_data),
|
| 358 |
+
"banks": banks,
|
| 359 |
+
"train_file": str(train_file),
|
| 360 |
+
"valid_file": str(valid_file),
|
| 361 |
+
"samples_file": str(samples_file)
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def main():
|
| 366 |
+
"""Generate Phase 2 training data."""
|
| 367 |
+
print("π Generating Phase 2: Bank Statement Training Data")
|
| 368 |
+
print("=" * 60)
|
| 369 |
+
|
| 370 |
+
result = generate_training_data(samples_per_bank=100)
|
| 371 |
+
|
| 372 |
+
print(f"\nβ
Generated {result['total_samples']} samples")
|
| 373 |
+
print(f" Banks: {', '.join(b.upper() for b in result['banks'])}")
|
| 374 |
+
print(f" Train: {result['train_samples']} samples")
|
| 375 |
+
print(f" Valid: {result['valid_samples']} samples")
|
| 376 |
+
print(f"\nπ Files created:")
|
| 377 |
+
print(f" {result['train_file']}")
|
| 378 |
+
print(f" {result['valid_file']}")
|
| 379 |
+
print(f" {result['samples_file']}")
|
| 380 |
+
|
| 381 |
+
# Show sample
|
| 382 |
+
print("\nπ Sample training entry:")
|
| 383 |
+
with open(result['train_file']) as f:
|
| 384 |
+
sample = json.loads(f.readline())
|
| 385 |
+
print(f" Prompt: {sample['prompt'][:80]}...")
|
| 386 |
+
print(f" Completion: {sample['completion'][:60]}...")
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
if __name__ == "__main__":
|
| 390 |
+
main()
|
scripts/install_scheduler.sh
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# ============================================
|
| 3 |
+
# Install Auto-Commit Scheduler (cron job)
|
| 4 |
+
# Runs daily at 10 PM IST
|
| 5 |
+
# ============================================
|
| 6 |
+
|
| 7 |
+
SCRIPT_PATH="$HOME/llm-mail-trainer/scripts/auto_commit.sh"
|
| 8 |
+
|
| 9 |
+
# Make script executable
|
| 10 |
+
chmod +x "$SCRIPT_PATH"
|
| 11 |
+
chmod +x "$HOME/llm-mail-trainer/scripts/setup_branches.sh"
|
| 12 |
+
|
| 13 |
+
echo "π§ Setting up daily auto-commit scheduler..."
|
| 14 |
+
|
| 15 |
+
# Check if cron job already exists
|
| 16 |
+
if crontab -l 2>/dev/null | grep -q "auto_commit.sh"; then
|
| 17 |
+
echo "β οΈ Cron job already exists. Removing old one..."
|
| 18 |
+
crontab -l | grep -v "auto_commit.sh" | crontab -
|
| 19 |
+
fi
|
| 20 |
+
|
| 21 |
+
# Add new cron job (10 PM IST = 4:30 PM UTC)
|
| 22 |
+
# Format: minute hour day month weekday command
|
| 23 |
+
(crontab -l 2>/dev/null; echo "30 16 * * * $SCRIPT_PATH") | crontab -
|
| 24 |
+
|
| 25 |
+
echo "β
Cron job installed!"
|
| 26 |
+
echo ""
|
| 27 |
+
echo "π Current cron jobs:"
|
| 28 |
+
crontab -l
|
| 29 |
+
echo ""
|
| 30 |
+
echo "The script will run daily at 10:00 PM IST (4:30 PM UTC)"
|
| 31 |
+
echo ""
|
| 32 |
+
echo "To manually run the scheduler:"
|
| 33 |
+
echo " bash $SCRIPT_PATH"
|
| 34 |
+
echo ""
|
| 35 |
+
echo "To remove the scheduler:"
|
| 36 |
+
echo " crontab -e # and delete the line"
|
| 37 |
+
echo ""
|
| 38 |
+
echo "To check logs:"
|
| 39 |
+
echo " cat ~/llm-mail-trainer/scheduler_logs/commits.log"
|
scripts/quantitative_eval.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Quantitative Evaluation for finance-lora-v6.
|
| 3 |
+
Tests the model on the full test dataset and computes accuracy metrics.
|
| 4 |
+
|
| 5 |
+
Author: Ranjit Behera
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
import re
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from collections import defaultdict
|
| 14 |
+
|
| 15 |
+
MODEL_PATH = "models/base/phi3-finance-base"
|
| 16 |
+
ADAPTER_PATH = "models/adapters/finance-lora-v6"
|
| 17 |
+
TEST_FILE = "data/synthetic/test_emails.json"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def generate(prompt: str) -> str:
|
| 21 |
+
"""Generate response using mlx_lm.generate."""
|
| 22 |
+
cmd = [
|
| 23 |
+
sys.executable, "-m", "mlx_lm.generate",
|
| 24 |
+
"--model", MODEL_PATH,
|
| 25 |
+
"--adapter-path", ADAPTER_PATH,
|
| 26 |
+
"--prompt", prompt,
|
| 27 |
+
"--max-tokens", "200"
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
| 32 |
+
return result.stdout
|
| 33 |
+
except Exception as e:
|
| 34 |
+
return f"Error: {e}"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def parse_json_from_output(output: str) -> dict:
|
| 38 |
+
"""Extract JSON from model output."""
|
| 39 |
+
try:
|
| 40 |
+
# Find JSON in output
|
| 41 |
+
match = re.search(r'\{[^{}]+\}', output, re.DOTALL)
|
| 42 |
+
if match:
|
| 43 |
+
return json.loads(match.group())
|
| 44 |
+
except:
|
| 45 |
+
pass
|
| 46 |
+
return {}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def compare_entities(expected: dict, predicted: dict) -> dict:
|
| 50 |
+
"""Compare expected vs predicted entities."""
|
| 51 |
+
fields = ['amount', 'type', 'date', 'account', 'reference', 'merchant']
|
| 52 |
+
|
| 53 |
+
results = {}
|
| 54 |
+
for field in fields:
|
| 55 |
+
exp_val = str(expected.get(field, '')).lower().strip()
|
| 56 |
+
pred_val = str(predicted.get(field, '')).lower().strip()
|
| 57 |
+
|
| 58 |
+
if exp_val:
|
| 59 |
+
# Normalize amount (remove commas, trailing zeros)
|
| 60 |
+
if field == 'amount':
|
| 61 |
+
exp_val = exp_val.replace(',', '').rstrip('0').rstrip('.')
|
| 62 |
+
pred_val = pred_val.replace(',', '').rstrip('0').rstrip('.')
|
| 63 |
+
|
| 64 |
+
results[field] = {
|
| 65 |
+
'expected': exp_val,
|
| 66 |
+
'predicted': pred_val,
|
| 67 |
+
'correct': exp_val == pred_val
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
return results
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def run_evaluation(limit: int = None):
|
| 74 |
+
"""Run evaluation on test dataset."""
|
| 75 |
+
print("=" * 70)
|
| 76 |
+
print("π QUANTITATIVE EVALUATION - finance-lora-v6")
|
| 77 |
+
print("=" * 70)
|
| 78 |
+
print(f"Model: {MODEL_PATH}")
|
| 79 |
+
print(f"Adapter: {ADAPTER_PATH}")
|
| 80 |
+
print()
|
| 81 |
+
|
| 82 |
+
# Load test data
|
| 83 |
+
with open(TEST_FILE) as f:
|
| 84 |
+
test_data = json.load(f)
|
| 85 |
+
|
| 86 |
+
if limit:
|
| 87 |
+
test_data = test_data[:limit]
|
| 88 |
+
|
| 89 |
+
print(f"Testing {len(test_data)} samples...")
|
| 90 |
+
print()
|
| 91 |
+
|
| 92 |
+
# Track results by bank and field
|
| 93 |
+
bank_stats = defaultdict(lambda: {'correct': 0, 'total': 0})
|
| 94 |
+
field_stats = defaultdict(lambda: {'correct': 0, 'total': 0})
|
| 95 |
+
|
| 96 |
+
for i, sample in enumerate(test_data):
|
| 97 |
+
bank = sample.get('bank', 'unknown')
|
| 98 |
+
body = sample.get('body', sample.get('raw_text', ''))
|
| 99 |
+
expected = sample.get('entities', {})
|
| 100 |
+
|
| 101 |
+
# Create prompt
|
| 102 |
+
prompt = f"""Extract financial entities from this email:
|
| 103 |
+
|
| 104 |
+
{body}
|
| 105 |
+
|
| 106 |
+
Extract: amount, type, date, account, reference, merchant
|
| 107 |
+
Output JSON:"""
|
| 108 |
+
|
| 109 |
+
# Generate prediction
|
| 110 |
+
output = generate(prompt)
|
| 111 |
+
predicted = parse_json_from_output(output)
|
| 112 |
+
|
| 113 |
+
# Compare
|
| 114 |
+
comparison = compare_entities(expected, predicted)
|
| 115 |
+
|
| 116 |
+
# Update stats
|
| 117 |
+
sample_correct = 0
|
| 118 |
+
sample_total = 0
|
| 119 |
+
for field, result in comparison.items():
|
| 120 |
+
field_stats[field]['total'] += 1
|
| 121 |
+
if result['correct']:
|
| 122 |
+
field_stats[field]['correct'] += 1
|
| 123 |
+
sample_correct += 1
|
| 124 |
+
sample_total += 1
|
| 125 |
+
|
| 126 |
+
if sample_total > 0:
|
| 127 |
+
bank_stats[bank]['total'] += 1
|
| 128 |
+
if sample_correct == sample_total:
|
| 129 |
+
bank_stats[bank]['correct'] += 1
|
| 130 |
+
|
| 131 |
+
# Progress
|
| 132 |
+
if (i + 1) % 5 == 0:
|
| 133 |
+
print(f" Processed {i + 1}/{len(test_data)}...")
|
| 134 |
+
|
| 135 |
+
# Print results
|
| 136 |
+
print()
|
| 137 |
+
print("=" * 70)
|
| 138 |
+
print("π RESULTS BY BANK")
|
| 139 |
+
print("=" * 70)
|
| 140 |
+
|
| 141 |
+
total_correct = 0
|
| 142 |
+
total_samples = 0
|
| 143 |
+
|
| 144 |
+
for bank in sorted(bank_stats.keys()):
|
| 145 |
+
stats = bank_stats[bank]
|
| 146 |
+
acc = stats['correct'] / stats['total'] * 100 if stats['total'] > 0 else 0
|
| 147 |
+
status = "β
" if acc >= 90 else "β οΈ" if acc >= 70 else "β"
|
| 148 |
+
print(f" {bank.upper():12} {stats['correct']:3}/{stats['total']:3} = {acc:5.1f}% {status}")
|
| 149 |
+
total_correct += stats['correct']
|
| 150 |
+
total_samples += stats['total']
|
| 151 |
+
|
| 152 |
+
overall_acc = total_correct / total_samples * 100 if total_samples > 0 else 0
|
| 153 |
+
print(f"\n {'OVERALL':12} {total_correct:3}/{total_samples:3} = {overall_acc:5.1f}%")
|
| 154 |
+
|
| 155 |
+
print()
|
| 156 |
+
print("=" * 70)
|
| 157 |
+
print("π RESULTS BY FIELD")
|
| 158 |
+
print("=" * 70)
|
| 159 |
+
|
| 160 |
+
for field in ['amount', 'type', 'date', 'account', 'reference', 'merchant']:
|
| 161 |
+
if field in field_stats:
|
| 162 |
+
stats = field_stats[field]
|
| 163 |
+
acc = stats['correct'] / stats['total'] * 100 if stats['total'] > 0 else 0
|
| 164 |
+
status = "β
" if acc >= 90 else "β οΈ" if acc >= 70 else "β"
|
| 165 |
+
print(f" {field:12} {stats['correct']:3}/{stats['total']:3} = {acc:5.1f}% {status}")
|
| 166 |
+
|
| 167 |
+
print()
|
| 168 |
+
print("=" * 70)
|
| 169 |
+
print("β
Evaluation Complete!")
|
| 170 |
+
print("=" * 70)
|
| 171 |
+
|
| 172 |
+
# Save results
|
| 173 |
+
results = {
|
| 174 |
+
'model': MODEL_PATH,
|
| 175 |
+
'adapter': ADAPTER_PATH,
|
| 176 |
+
'total_samples': total_samples,
|
| 177 |
+
'overall_accuracy': overall_acc,
|
| 178 |
+
'by_bank': {k: v for k, v in bank_stats.items()},
|
| 179 |
+
'by_field': {k: v for k, v in field_stats.items()}
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
with open('evaluation_results_v6.json', 'w') as f:
|
| 183 |
+
json.dump(results, f, indent=2)
|
| 184 |
+
|
| 185 |
+
print(f"\nπΎ Results saved to evaluation_results_v6.json")
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == "__main__":
|
| 189 |
+
import argparse
|
| 190 |
+
parser = argparse.ArgumentParser()
|
| 191 |
+
parser.add_argument('--limit', type=int, default=20, help='Number of samples to test')
|
| 192 |
+
args = parser.parse_args()
|
| 193 |
+
|
| 194 |
+
run_evaluation(limit=args.limit)
|
scripts/retrain_v7.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Combine Training Data and Retrain v7.
|
| 3 |
+
|
| 4 |
+
Adds ICICI samples to existing training data and retrains the model.
|
| 5 |
+
|
| 6 |
+
Author: Ranjit Behera
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import subprocess
|
| 11 |
+
import random
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
def combine_and_retrain():
|
| 15 |
+
print("=" * 60)
|
| 16 |
+
print("π COMBINING DATA AND RETRAINING v7")
|
| 17 |
+
print("=" * 60)
|
| 18 |
+
|
| 19 |
+
# Load existing training data
|
| 20 |
+
train_file = Path("data/training/train.jsonl")
|
| 21 |
+
valid_file = Path("data/training/valid.jsonl")
|
| 22 |
+
icici_file = Path("data/synthetic/icici_samples.jsonl")
|
| 23 |
+
|
| 24 |
+
print("\n1. Loading existing training data...")
|
| 25 |
+
existing_train = []
|
| 26 |
+
with open(train_file, 'r') as f:
|
| 27 |
+
for line in f:
|
| 28 |
+
existing_train.append(json.loads(line))
|
| 29 |
+
print(f" Loaded {len(existing_train)} existing samples")
|
| 30 |
+
|
| 31 |
+
print("\n2. Loading ICICI samples...")
|
| 32 |
+
icici_samples = []
|
| 33 |
+
with open(icici_file, 'r') as f:
|
| 34 |
+
for line in f:
|
| 35 |
+
data = json.loads(line)
|
| 36 |
+
# Keep prompt/completion format
|
| 37 |
+
icici_samples.append({
|
| 38 |
+
'prompt': data['prompt'],
|
| 39 |
+
'completion': data['completion']
|
| 40 |
+
})
|
| 41 |
+
print(f" Loaded {len(icici_samples)} ICICI samples")
|
| 42 |
+
|
| 43 |
+
# Combine
|
| 44 |
+
print("\n3. Combining datasets...")
|
| 45 |
+
combined = existing_train + icici_samples
|
| 46 |
+
random.seed(42)
|
| 47 |
+
random.shuffle(combined)
|
| 48 |
+
|
| 49 |
+
# Split 90/10
|
| 50 |
+
split_idx = int(len(combined) * 0.9)
|
| 51 |
+
new_train = combined[:split_idx]
|
| 52 |
+
new_valid = combined[split_idx:]
|
| 53 |
+
|
| 54 |
+
print(f" New training set: {len(new_train)}")
|
| 55 |
+
print(f" New validation set: {len(new_valid)}")
|
| 56 |
+
|
| 57 |
+
# Backup and save
|
| 58 |
+
print("\n4. Saving combined data...")
|
| 59 |
+
|
| 60 |
+
# Backup original
|
| 61 |
+
train_file.rename(train_file.with_suffix('.jsonl.bak'))
|
| 62 |
+
valid_file.rename(valid_file.with_suffix('.jsonl.bak'))
|
| 63 |
+
|
| 64 |
+
with open(train_file, 'w') as f:
|
| 65 |
+
for sample in new_train:
|
| 66 |
+
f.write(json.dumps(sample) + '\n')
|
| 67 |
+
|
| 68 |
+
with open(valid_file, 'w') as f:
|
| 69 |
+
for sample in new_valid:
|
| 70 |
+
f.write(json.dumps(sample) + '\n')
|
| 71 |
+
|
| 72 |
+
print(f" Saved to {train_file}")
|
| 73 |
+
print(f" Saved to {valid_file}")
|
| 74 |
+
|
| 75 |
+
# Count ICICI in training
|
| 76 |
+
icici_count = sum(1 for s in new_train if 'ICICI' in s.get('text', '').upper())
|
| 77 |
+
print(f"\n ICICI samples in training: ~{icici_count}")
|
| 78 |
+
|
| 79 |
+
print("\nβ
Data combined successfully!")
|
| 80 |
+
print("\n5. Starting v7 training...")
|
| 81 |
+
|
| 82 |
+
# Train v7
|
| 83 |
+
cmd = [
|
| 84 |
+
"mlx_lm.lora",
|
| 85 |
+
"--model", "models/base/phi3-finance-base",
|
| 86 |
+
"--data", "data/training",
|
| 87 |
+
"--train",
|
| 88 |
+
"--iters", "500", # Quick iteration
|
| 89 |
+
"--batch-size", "1",
|
| 90 |
+
"--num-layers", "16",
|
| 91 |
+
"--learning-rate", "1e-5",
|
| 92 |
+
"--adapter-path", "models/adapters/finance-lora-v7",
|
| 93 |
+
"--max-seq-length", "1024"
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
print(f"Command: {' '.join(cmd)}")
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
subprocess.run(cmd, check=True)
|
| 100 |
+
print("\nβ
v7 training complete!")
|
| 101 |
+
except subprocess.CalledProcessError as e:
|
| 102 |
+
print(f"\nβ Training failed: {e}")
|
| 103 |
+
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
combine_and_retrain()
|
scripts/retrain_v8.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Combine All Data and Retrain v8.
|
| 3 |
+
|
| 4 |
+
Combines:
|
| 5 |
+
- Existing training data (2800 samples)
|
| 6 |
+
- Multi-bank comprehensive data (498 samples)
|
| 7 |
+
|
| 8 |
+
Author: Ranjit Behera
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
import random
|
| 13 |
+
import subprocess
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
def combine_and_retrain():
|
| 17 |
+
print("=" * 60)
|
| 18 |
+
print("π COMBINING DATA AND RETRAINING v8")
|
| 19 |
+
print("=" * 60)
|
| 20 |
+
|
| 21 |
+
# Load existing
|
| 22 |
+
train_file = Path("data/training/train.jsonl")
|
| 23 |
+
valid_file = Path("data/training/valid.jsonl")
|
| 24 |
+
multi_bank_file = Path("data/synthetic/multi_bank_comprehensive.jsonl")
|
| 25 |
+
|
| 26 |
+
print("\n1. Loading existing training data...")
|
| 27 |
+
existing = []
|
| 28 |
+
with open(train_file, 'r') as f:
|
| 29 |
+
for line in f:
|
| 30 |
+
existing.append(json.loads(line))
|
| 31 |
+
print(f" Loaded {len(existing)} existing samples")
|
| 32 |
+
|
| 33 |
+
print("\n2. Loading multi-bank comprehensive data...")
|
| 34 |
+
multi_bank = []
|
| 35 |
+
with open(multi_bank_file, 'r') as f:
|
| 36 |
+
for line in f:
|
| 37 |
+
data = json.loads(line)
|
| 38 |
+
multi_bank.append({
|
| 39 |
+
'prompt': data['prompt'],
|
| 40 |
+
'completion': data['completion']
|
| 41 |
+
})
|
| 42 |
+
print(f" Loaded {len(multi_bank)} multi-bank samples")
|
| 43 |
+
|
| 44 |
+
# Combine
|
| 45 |
+
print("\n3. Combining datasets...")
|
| 46 |
+
combined = existing + multi_bank
|
| 47 |
+
random.seed(42)
|
| 48 |
+
random.shuffle(combined)
|
| 49 |
+
|
| 50 |
+
# Split 90/10
|
| 51 |
+
split_idx = int(len(combined) * 0.9)
|
| 52 |
+
new_train = combined[:split_idx]
|
| 53 |
+
new_valid = combined[split_idx:]
|
| 54 |
+
|
| 55 |
+
print(f" New training set: {len(new_train)}")
|
| 56 |
+
print(f" New validation set: {len(new_valid)}")
|
| 57 |
+
|
| 58 |
+
# Backup and save
|
| 59 |
+
print("\n4. Saving combined data...")
|
| 60 |
+
|
| 61 |
+
# Backup
|
| 62 |
+
if train_file.with_suffix('.jsonl.v7.bak').exists():
|
| 63 |
+
pass # Already backed up
|
| 64 |
+
else:
|
| 65 |
+
import shutil
|
| 66 |
+
shutil.copy(train_file, train_file.with_suffix('.jsonl.v7.bak'))
|
| 67 |
+
shutil.copy(valid_file, valid_file.with_suffix('.jsonl.v7.bak'))
|
| 68 |
+
|
| 69 |
+
with open(train_file, 'w') as f:
|
| 70 |
+
for sample in new_train:
|
| 71 |
+
f.write(json.dumps(sample) + '\n')
|
| 72 |
+
|
| 73 |
+
with open(valid_file, 'w') as f:
|
| 74 |
+
for sample in new_valid:
|
| 75 |
+
f.write(json.dumps(sample) + '\n')
|
| 76 |
+
|
| 77 |
+
print(f" Saved to {train_file}")
|
| 78 |
+
|
| 79 |
+
# Count banks
|
| 80 |
+
bank_keywords = ['HDFC', 'ICICI', 'SBI', 'AXIS', 'KOTAK']
|
| 81 |
+
for kw in bank_keywords:
|
| 82 |
+
count = sum(1 for s in new_train if kw in s.get('prompt', '').upper())
|
| 83 |
+
print(f" {kw}: ~{count} samples")
|
| 84 |
+
|
| 85 |
+
print("\nβ
Data combined successfully!")
|
| 86 |
+
print("\n5. Starting v8 training...")
|
| 87 |
+
|
| 88 |
+
# Train v8 - more iterations for more data
|
| 89 |
+
cmd = [
|
| 90 |
+
"mlx_lm.lora",
|
| 91 |
+
"--model", "models/base/phi3-finance-base",
|
| 92 |
+
"--data", "data/training",
|
| 93 |
+
"--train",
|
| 94 |
+
"--iters", "800", # More iterations for bigger dataset
|
| 95 |
+
"--batch-size", "1",
|
| 96 |
+
"--num-layers", "16",
|
| 97 |
+
"--learning-rate", "1e-5",
|
| 98 |
+
"--adapter-path", "models/adapters/finance-lora-v8",
|
| 99 |
+
"--max-seq-length", "1024"
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
print(f"Command: {' '.join(cmd)}")
|
| 103 |
+
|
| 104 |
+
try:
|
| 105 |
+
subprocess.run(cmd, check=True)
|
| 106 |
+
print("\nβ
v8 training complete!")
|
| 107 |
+
except subprocess.CalledProcessError as e:
|
| 108 |
+
print(f"\nβ Training failed: {e}")
|
| 109 |
+
|
| 110 |
+
if __name__ == "__main__":
|
| 111 |
+
combine_and_retrain()
|
scripts/setup_branches.sh
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# ============================================
|
| 3 |
+
# Setup Git Branches
|
| 4 |
+
# Creates feature, dev, main branch structure
|
| 5 |
+
# ============================================
|
| 6 |
+
|
| 7 |
+
PROJECT_DIR="$HOME/llm-mail-trainer"
|
| 8 |
+
cd "$PROJECT_DIR" || exit 1
|
| 9 |
+
|
| 10 |
+
echo "π§ Setting up branch structure..."
|
| 11 |
+
|
| 12 |
+
# Ensure we're on main
|
| 13 |
+
git checkout main 2>/dev/null || git checkout -b main
|
| 14 |
+
|
| 15 |
+
# Create dev branch from main
|
| 16 |
+
git branch -D dev 2>/dev/null
|
| 17 |
+
git checkout -b dev
|
| 18 |
+
echo "β
Created 'dev' branch"
|
| 19 |
+
|
| 20 |
+
# Create feature branch from dev
|
| 21 |
+
git branch -D feature/improvements 2>/dev/null
|
| 22 |
+
git checkout -b feature/improvements
|
| 23 |
+
echo "β
Created 'feature/improvements' branch"
|
| 24 |
+
|
| 25 |
+
# Push all branches to remote
|
| 26 |
+
echo ""
|
| 27 |
+
echo "π Pushing branches to HuggingFace..."
|
| 28 |
+
git push hf main --force 2>/dev/null
|
| 29 |
+
git push hf dev --force 2>/dev/null
|
| 30 |
+
git push hf feature/improvements --force 2>/dev/null
|
| 31 |
+
|
| 32 |
+
echo ""
|
| 33 |
+
echo "π Branch structure:"
|
| 34 |
+
git branch -a
|
| 35 |
+
|
| 36 |
+
echo ""
|
| 37 |
+
echo "β
Branch setup complete!"
|
| 38 |
+
echo ""
|
| 39 |
+
echo "Branch workflow:"
|
| 40 |
+
echo " feature/* β dev β main"
|
| 41 |
+
echo ""
|
| 42 |
+
echo "Commands:"
|
| 43 |
+
echo " git checkout feature/improvements # Work on features"
|
| 44 |
+
echo " git checkout dev # Merge features here"
|
| 45 |
+
echo " git checkout main # Production code"
|
scripts/sync_models.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Sync model files to HuggingFace.
|
| 4 |
+
Run this after pushing code to ensure model files are present.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
from huggingface_hub import HfApi, create_commit, CommitOperationAdd
|
| 13 |
+
except ImportError:
|
| 14 |
+
print("Installing huggingface_hub...")
|
| 15 |
+
os.system("pip install huggingface_hub -q")
|
| 16 |
+
from huggingface_hub import HfApi, create_commit, CommitOperationAdd
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
REPO_ID = "Ranjit0034/finance-entity-extractor"
|
| 20 |
+
PROJECT_DIR = Path.home() / "llm-mail-trainer"
|
| 21 |
+
|
| 22 |
+
# Model files to keep in sync
|
| 23 |
+
MODEL_FILES = [
|
| 24 |
+
(PROJECT_DIR / "models/base/phi3-mini/config.json", "config.json"),
|
| 25 |
+
(PROJECT_DIR / "models/adapters/finance-lora-v2/adapter_config.json", "adapter_config.json"),
|
| 26 |
+
(PROJECT_DIR / "models/adapters/finance-lora-v2/adapters.safetensors", "adapters.safetensors"),
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def check_remote_files(api):
|
| 31 |
+
"""Check which model files exist on HuggingFace."""
|
| 32 |
+
try:
|
| 33 |
+
files = api.list_repo_files(REPO_ID)
|
| 34 |
+
return set(files)
|
| 35 |
+
except Exception as e:
|
| 36 |
+
print(f"Error checking remote: {e}")
|
| 37 |
+
return set()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def sync_models():
|
| 41 |
+
"""Sync model files to HuggingFace."""
|
| 42 |
+
api = HfApi()
|
| 43 |
+
|
| 44 |
+
print("π Checking HuggingFace repository...")
|
| 45 |
+
remote_files = check_remote_files(api)
|
| 46 |
+
|
| 47 |
+
operations = []
|
| 48 |
+
for local_path, repo_path in MODEL_FILES:
|
| 49 |
+
if repo_path not in remote_files:
|
| 50 |
+
if local_path.exists():
|
| 51 |
+
size = local_path.stat().st_size
|
| 52 |
+
print(f" π€ Will upload: {repo_path} ({size/1024:.1f} KB)")
|
| 53 |
+
operations.append(CommitOperationAdd(
|
| 54 |
+
path_in_repo=repo_path,
|
| 55 |
+
path_or_fileobj=str(local_path)
|
| 56 |
+
))
|
| 57 |
+
else:
|
| 58 |
+
print(f" β Local file missing: {local_path}")
|
| 59 |
+
else:
|
| 60 |
+
print(f" β
Already exists: {repo_path}")
|
| 61 |
+
|
| 62 |
+
if operations:
|
| 63 |
+
print(f"\nπ€ Uploading {len(operations)} files...")
|
| 64 |
+
try:
|
| 65 |
+
commit = create_commit(
|
| 66 |
+
repo_id=REPO_ID,
|
| 67 |
+
operations=operations,
|
| 68 |
+
commit_message="sync: Restore model files",
|
| 69 |
+
repo_type="model"
|
| 70 |
+
)
|
| 71 |
+
print(f"β
Uploaded! {commit.commit_url}")
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"β Upload failed: {e}")
|
| 74 |
+
else:
|
| 75 |
+
print("\nβ
All model files are present!")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
sync_models()
|
scripts/test_clean_benchmark.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test Model on Clean UPI Benchmark.
|
| 3 |
+
|
| 4 |
+
Author: Ranjit Behera
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import re
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
|
| 13 |
+
MODEL_PATH = "models/base/phi3-finance-base"
|
| 14 |
+
ADAPTER_PATH = "models/adapters/finance-lora-v7"
|
| 15 |
+
BENCHMARK_FILE = "data/benchmark/clean_upi_benchmark.json"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def generate(prompt: str) -> str:
|
| 19 |
+
cmd = [
|
| 20 |
+
sys.executable, "-m", "mlx_lm.generate",
|
| 21 |
+
"--model", MODEL_PATH,
|
| 22 |
+
"--adapter-path", ADAPTER_PATH,
|
| 23 |
+
"--prompt", prompt,
|
| 24 |
+
"--max-tokens", "200"
|
| 25 |
+
]
|
| 26 |
+
try:
|
| 27 |
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
| 28 |
+
return result.stdout
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return f"Error: {e}"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def parse_json_from_output(output: str) -> dict:
|
| 34 |
+
try:
|
| 35 |
+
match = re.search(r'\{[^{}]+\}', output, re.DOTALL)
|
| 36 |
+
if match:
|
| 37 |
+
return json.loads(match.group())
|
| 38 |
+
except:
|
| 39 |
+
pass
|
| 40 |
+
return {}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def normalize(val: str) -> str:
|
| 44 |
+
if not val:
|
| 45 |
+
return ''
|
| 46 |
+
val = str(val).lower().strip()
|
| 47 |
+
val = val.replace(',', '').replace('.00', '').rstrip('0').rstrip('.')
|
| 48 |
+
return val
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def run_test(limit: int = 20):
|
| 52 |
+
print("=" * 70)
|
| 53 |
+
print("π§ͺ CLEAN UPI BENCHMARK TEST - v7")
|
| 54 |
+
print("=" * 70)
|
| 55 |
+
|
| 56 |
+
with open(BENCHMARK_FILE) as f:
|
| 57 |
+
benchmark = json.load(f)
|
| 58 |
+
|
| 59 |
+
if limit:
|
| 60 |
+
benchmark = benchmark[:limit]
|
| 61 |
+
|
| 62 |
+
print(f"Testing {len(benchmark)} clean HDFC UPI emails...")
|
| 63 |
+
|
| 64 |
+
field_stats = defaultdict(lambda: {'correct': 0, 'total': 0})
|
| 65 |
+
|
| 66 |
+
for i, sample in enumerate(benchmark):
|
| 67 |
+
text = sample['text']
|
| 68 |
+
expected = sample['expected_entities']
|
| 69 |
+
|
| 70 |
+
prompt = f"""Extract financial entities from this HDFC Bank email:
|
| 71 |
+
|
| 72 |
+
{text[:500]}
|
| 73 |
+
|
| 74 |
+
Extract: amount, type, date, account, reference, merchant
|
| 75 |
+
Output JSON:"""
|
| 76 |
+
|
| 77 |
+
output = generate(prompt)
|
| 78 |
+
predicted = parse_json_from_output(output)
|
| 79 |
+
|
| 80 |
+
for field in ['amount', 'type', 'date', 'account', 'reference']:
|
| 81 |
+
exp_val = normalize(expected.get(field, ''))
|
| 82 |
+
pred_val = normalize(predicted.get(field, ''))
|
| 83 |
+
|
| 84 |
+
if exp_val:
|
| 85 |
+
field_stats[field]['total'] += 1
|
| 86 |
+
if exp_val == pred_val:
|
| 87 |
+
field_stats[field]['correct'] += 1
|
| 88 |
+
|
| 89 |
+
if (i + 1) % 5 == 0:
|
| 90 |
+
print(f" Processed {i + 1}/{len(benchmark)}...")
|
| 91 |
+
|
| 92 |
+
print()
|
| 93 |
+
print("=" * 70)
|
| 94 |
+
print("π CLEAN UPI BENCHMARK RESULTS")
|
| 95 |
+
print("=" * 70)
|
| 96 |
+
|
| 97 |
+
total_correct = 0
|
| 98 |
+
total_fields = 0
|
| 99 |
+
|
| 100 |
+
for field in ['amount', 'type', 'date', 'account', 'reference']:
|
| 101 |
+
stats = field_stats[field]
|
| 102 |
+
acc = stats['correct'] / stats['total'] * 100 if stats['total'] > 0 else 0
|
| 103 |
+
status = "β
" if acc >= 90 else "β οΈ" if acc >= 70 else "β"
|
| 104 |
+
print(f" {field:12} {stats['correct']:3}/{stats['total']:3} = {acc:5.1f}% {status}")
|
| 105 |
+
total_correct += stats['correct']
|
| 106 |
+
total_fields += stats['total']
|
| 107 |
+
|
| 108 |
+
overall = total_correct / total_fields * 100 if total_fields > 0 else 0
|
| 109 |
+
print(f"\n {'OVERALL':12} {total_correct:3}/{total_fields:3} = {overall:5.1f}%")
|
| 110 |
+
|
| 111 |
+
print("=" * 70)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
import argparse
|
| 116 |
+
parser = argparse.ArgumentParser()
|
| 117 |
+
parser.add_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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test Model on Multi-Bank Benchmark.
|
| 3 |
+
|
| 4 |
+
Author: Ranjit Behera
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import re
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
|
| 13 |
+
MODEL_PATH = "models/base/phi3-finance-base"
|
| 14 |
+
ADAPTER_PATH = "models/adapters/finee-adapter-v1" # Updated for V1.0
|
| 15 |
+
BENCHMARK_FILE = "data/benchmark/multi_bank_comprehensive.jsonl" # Updated to generated file
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def generate(prompt: str, adapter_path: str = ADAPTER_PATH) -> str:
|
| 19 |
+
cmd = [
|
| 20 |
+
sys.executable, "-m", "mlx_lm.generate",
|
| 21 |
+
"--model", MODEL_PATH,
|
| 22 |
+
"--adapter-path", adapter_path,
|
| 23 |
+
"--prompt", prompt,
|
| 24 |
+
"--max-tokens", "200"
|
| 25 |
+
]
|
| 26 |
+
try:
|
| 27 |
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
| 28 |
+
return result.stdout
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return f"Error: {e}"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def parse_json_from_output(output: str) -> dict:
|
| 34 |
+
try:
|
| 35 |
+
match = re.search(r'\{[^{}]+\}', output, re.DOTALL)
|
| 36 |
+
if match:
|
| 37 |
+
return json.loads(match.group())
|
| 38 |
+
except:
|
| 39 |
+
pass
|
| 40 |
+
return {}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def normalize(val: str) -> str:
|
| 44 |
+
if not val:
|
| 45 |
+
return ''
|
| 46 |
+
val = str(val).lower().strip()
|
| 47 |
+
val = val.replace(',', '').replace('.00', '').rstrip('0').rstrip('.')
|
| 48 |
+
return val
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def run_test(limit: int = None, adapter_path: str = ADAPTER_PATH):
|
| 52 |
+
print("=" * 70)
|
| 53 |
+
print("π§ͺ MULTI-BANK BENCHMARK TEST - v1.0")
|
| 54 |
+
print("=" * 70)
|
| 55 |
+
|
| 56 |
+
# Handle JSONL format (lines of JSON)
|
| 57 |
+
benchmark = []
|
| 58 |
+
try:
|
| 59 |
+
with open(BENCHMARK_FILE) as f:
|
| 60 |
+
if BENCHMARK_FILE.endswith('.jsonl'):
|
| 61 |
+
for line in f:
|
| 62 |
+
if line.strip():
|
| 63 |
+
benchmark.append(json.loads(line))
|
| 64 |
+
else:
|
| 65 |
+
benchmark = json.load(f)
|
| 66 |
+
except FileNotFoundError:
|
| 67 |
+
print(f"Benchmark file not found: {BENCHMARK_FILE}")
|
| 68 |
+
return
|
| 69 |
+
|
| 70 |
+
if limit:
|
| 71 |
+
benchmark = benchmark[:limit]
|
| 72 |
+
|
| 73 |
+
print(f"Testing {len(benchmark)} samples across multiple banks...")
|
| 74 |
+
|
| 75 |
+
field_stats = defaultdict(lambda: {'correct': 0, 'total': 0})
|
| 76 |
+
bank_stats = defaultdict(lambda: {'correct': 0, 'total': 0, 'fields_correct': 0, 'fields_total': 0})
|
| 77 |
+
|
| 78 |
+
for i, sample in enumerate(benchmark):
|
| 79 |
+
# Handle difference between generation format and test format if any
|
| 80 |
+
# The generator produces: "prompt", "completion", "bank", "txn_type"
|
| 81 |
+
# The old benchmark expected: "text", "expected_entities"
|
| 82 |
+
|
| 83 |
+
if 'prompt' in sample and 'completion' in sample:
|
| 84 |
+
# Parse completion JSON string to dict
|
| 85 |
+
try:
|
| 86 |
+
expected = json.loads(sample['completion'])
|
| 87 |
+
except:
|
| 88 |
+
expected = sample['completion']
|
| 89 |
+
|
| 90 |
+
# Extract text from prompt (it's embedded in the prompt string)
|
| 91 |
+
# The prompt format is: ...\n\n{email_text}\n\n...
|
| 92 |
+
# A simple way is to use the raw text if available, but here we only have prompt.
|
| 93 |
+
# We can pass the prompt DIRECTLY to the model if we trained on it!
|
| 94 |
+
# BUT wait, generate() appends its own prompt template?
|
| 95 |
+
# No, mlx_lm.generate takes a prompt.
|
| 96 |
+
# If we pass sample['prompt'], it's the FULL prompt including "Output JSON:".
|
| 97 |
+
prompt = sample['prompt']
|
| 98 |
+
|
| 99 |
+
# For reporting/debugging, we want the bank name
|
| 100 |
+
bank = sample.get('bank', 'unknown')
|
| 101 |
+
|
| 102 |
+
else:
|
| 103 |
+
# Fallback to old format
|
| 104 |
+
text = sample['text']
|
| 105 |
+
expected = sample['expected_entities']
|
| 106 |
+
bank = expected.get('bank', 'unknown')
|
| 107 |
+
|
| 108 |
+
prompt = f"""Extract financial entities from this {bank.upper()} Bank email:
|
| 109 |
+
|
| 110 |
+
{text[:500]}
|
| 111 |
+
|
| 112 |
+
Extract: amount, type, date, account, reference, merchant
|
| 113 |
+
Output JSON:"""
|
| 114 |
+
|
| 115 |
+
output = generate(prompt, adapter_path)
|
| 116 |
+
predicted = parse_json_from_output(output)
|
| 117 |
+
|
| 118 |
+
sample_correct = 0
|
| 119 |
+
sample_total = 0
|
| 120 |
+
|
| 121 |
+
# Define fields to check
|
| 122 |
+
fields_to_check = ['amount', 'type', 'date', 'account', 'reference']
|
| 123 |
+
if 'merchant' in expected: fields_to_check.append('merchant')
|
| 124 |
+
|
| 125 |
+
for field in fields_to_check:
|
| 126 |
+
exp_val = normalize(expected.get(field, ''))
|
| 127 |
+
pred_val = normalize(predicted.get(field, ''))
|
| 128 |
+
|
| 129 |
+
if exp_val:
|
| 130 |
+
field_stats[field]['total'] += 1
|
| 131 |
+
bank_stats[bank]['fields_total'] += 1
|
| 132 |
+
sample_total += 1
|
| 133 |
+
|
| 134 |
+
if exp_val == pred_val:
|
| 135 |
+
field_stats[field]['correct'] += 1
|
| 136 |
+
bank_stats[bank]['fields_correct'] += 1
|
| 137 |
+
sample_correct += 1
|
| 138 |
+
|
| 139 |
+
# Track bank-level (all fields match)
|
| 140 |
+
bank_stats[bank]['total'] += 1
|
| 141 |
+
if sample_total > 0 and sample_correct == sample_total:
|
| 142 |
+
bank_stats[bank]['correct'] += 1
|
| 143 |
+
|
| 144 |
+
if (i + 1) % 10 == 0:
|
| 145 |
+
print(f" Processed {i + 1}/{len(benchmark)}...")
|
| 146 |
+
|
| 147 |
+
print()
|
| 148 |
+
print("=" * 70)
|
| 149 |
+
print("π RESULTS BY FIELD")
|
| 150 |
+
print("=" * 70)
|
| 151 |
+
|
| 152 |
+
total_correct = 0
|
| 153 |
+
total_fields = 0
|
| 154 |
+
|
| 155 |
+
for field in sorted(field_stats.keys()):
|
| 156 |
+
stats = field_stats[field]
|
| 157 |
+
acc = stats['correct'] / stats['total'] * 100 if stats['total'] > 0 else 0
|
| 158 |
+
status = "β
" if acc >= 90 else "β οΈ" if acc >= 70 else "β"
|
| 159 |
+
print(f" {field:12} {stats['correct']:3}/{stats['total']:3} = {acc:5.1f}% {status}")
|
| 160 |
+
total_correct += stats['correct']
|
| 161 |
+
total_fields += stats['total']
|
| 162 |
+
|
| 163 |
+
overall = total_correct / total_fields * 100 if total_fields > 0 else 0
|
| 164 |
+
print(f"\n {'OVERALL':12} {total_correct:3}/{total_fields:3} = {overall:5.1f}%")
|
| 165 |
+
|
| 166 |
+
print()
|
| 167 |
+
print("=" * 70)
|
| 168 |
+
print("π RESULTS BY BANK (Field-Level Accuracy)")
|
| 169 |
+
print("=" * 70)
|
| 170 |
+
|
| 171 |
+
for bank in sorted(bank_stats.keys()):
|
| 172 |
+
stats = bank_stats[bank]
|
| 173 |
+
field_acc = stats['fields_correct'] / stats['fields_total'] * 100 if stats['fields_total'] > 0 else 0
|
| 174 |
+
# full_acc = stats['correct'] / stats['total'] * 100 if stats['total'] > 0 else 0
|
| 175 |
+
|
| 176 |
+
status = "β
" if field_acc >= 90 else "β οΈ" if field_acc >= 70 else "β"
|
| 177 |
+
print(f" {bank.upper():10} Fields: {stats['fields_correct']:3}/{stats['fields_total']:3} = {field_acc:5.1f}% | Full Match: {stats['correct']}/{stats['total']} {status}")
|
| 178 |
+
|
| 179 |
+
print("=" * 70)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
if __name__ == "__main__":
|
| 183 |
+
import argparse
|
| 184 |
+
parser = argparse.ArgumentParser()
|
| 185 |
+
parser.add_argument('--limit', type=int, default=40, help='Number of samples')
|
| 186 |
+
parser.add_argument('--adapter', type=str, default=ADAPTER_PATH, help='Adapter path')
|
| 187 |
+
args = parser.parse_args()
|
| 188 |
+
run_test(limit=args.limit, adapter_path=args.adapter)
|
scripts/test_real_benchmark.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test v6 Model on Real Email Benchmark.
|
| 3 |
+
|
| 4 |
+
Runs the model on 100 real emails from your MBOX
|
| 5 |
+
and measures accuracy per field.
|
| 6 |
+
|
| 7 |
+
Author: Ranjit Behera
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import re
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from collections import defaultdict
|
| 16 |
+
|
| 17 |
+
MODEL_PATH = "models/base/phi3-finance-base"
|
| 18 |
+
ADAPTER_PATH = "models/adapters/finance-lora-v7"
|
| 19 |
+
BENCHMARK_FILE = "data/benchmark/real_emails_benchmark.json"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def generate(prompt: str) -> str:
|
| 23 |
+
"""Generate response using mlx_lm.generate."""
|
| 24 |
+
cmd = [
|
| 25 |
+
sys.executable, "-m", "mlx_lm.generate",
|
| 26 |
+
"--model", MODEL_PATH,
|
| 27 |
+
"--adapter-path", ADAPTER_PATH,
|
| 28 |
+
"--prompt", prompt,
|
| 29 |
+
"--max-tokens", "200"
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
| 34 |
+
return result.stdout
|
| 35 |
+
except Exception as e:
|
| 36 |
+
return f"Error: {e}"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def parse_json_from_output(output: str) -> dict:
|
| 40 |
+
"""Extract JSON from model output."""
|
| 41 |
+
try:
|
| 42 |
+
match = re.search(r'\{[^{}]+\}', output, re.DOTALL)
|
| 43 |
+
if match:
|
| 44 |
+
return json.loads(match.group())
|
| 45 |
+
except:
|
| 46 |
+
pass
|
| 47 |
+
return {}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def normalize_value(val: str) -> str:
|
| 51 |
+
"""Normalize a value for comparison."""
|
| 52 |
+
if not val:
|
| 53 |
+
return ''
|
| 54 |
+
val = str(val).lower().strip()
|
| 55 |
+
val = val.replace(',', '').replace('.00', '').rstrip('0').rstrip('.')
|
| 56 |
+
return val
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def run_real_benchmark(limit: int = 20):
|
| 60 |
+
"""Run benchmark on real emails."""
|
| 61 |
+
print("=" * 70)
|
| 62 |
+
print("π§ͺ REAL EMAIL BENCHMARK - finance-lora-v6")
|
| 63 |
+
print("=" * 70)
|
| 64 |
+
print(f"Model: {MODEL_PATH}")
|
| 65 |
+
print(f"Adapter: {ADAPTER_PATH}")
|
| 66 |
+
print()
|
| 67 |
+
|
| 68 |
+
# Load benchmark
|
| 69 |
+
with open(BENCHMARK_FILE) as f:
|
| 70 |
+
benchmark = json.load(f)
|
| 71 |
+
|
| 72 |
+
# Filter for good candidates (have amount and bank detected)
|
| 73 |
+
good_samples = [s for s in benchmark
|
| 74 |
+
if s['expected_entities'].get('amount')
|
| 75 |
+
and s['expected_entities'].get('bank')]
|
| 76 |
+
|
| 77 |
+
if limit:
|
| 78 |
+
good_samples = good_samples[:limit]
|
| 79 |
+
|
| 80 |
+
print(f"Testing {len(good_samples)} real emails with auto-extracted labels...")
|
| 81 |
+
print()
|
| 82 |
+
|
| 83 |
+
# Track results
|
| 84 |
+
field_stats = defaultdict(lambda: {'correct': 0, 'total': 0})
|
| 85 |
+
bank_stats = defaultdict(lambda: {'correct': 0, 'total': 0})
|
| 86 |
+
|
| 87 |
+
results = []
|
| 88 |
+
|
| 89 |
+
for i, sample in enumerate(good_samples):
|
| 90 |
+
text = sample['text']
|
| 91 |
+
expected = sample['expected_entities']
|
| 92 |
+
bank = expected.get('bank', 'unknown')
|
| 93 |
+
|
| 94 |
+
# Create prompt
|
| 95 |
+
prompt = f"""Extract financial entities from this email:
|
| 96 |
+
|
| 97 |
+
{text[:500]}
|
| 98 |
+
|
| 99 |
+
Extract: amount, type, date, account, reference, merchant
|
| 100 |
+
Output JSON:"""
|
| 101 |
+
|
| 102 |
+
# Generate
|
| 103 |
+
output = generate(prompt)
|
| 104 |
+
predicted = parse_json_from_output(output)
|
| 105 |
+
|
| 106 |
+
# Compare fields
|
| 107 |
+
sample_correct = 0
|
| 108 |
+
sample_total = 0
|
| 109 |
+
|
| 110 |
+
for field in ['amount', 'type', 'date', 'account', 'reference']:
|
| 111 |
+
exp_val = normalize_value(expected.get(field, ''))
|
| 112 |
+
pred_val = normalize_value(predicted.get(field, ''))
|
| 113 |
+
|
| 114 |
+
if exp_val: # Only count if we have expected value
|
| 115 |
+
field_stats[field]['total'] += 1
|
| 116 |
+
sample_total += 1
|
| 117 |
+
if exp_val == pred_val:
|
| 118 |
+
field_stats[field]['correct'] += 1
|
| 119 |
+
sample_correct += 1
|
| 120 |
+
|
| 121 |
+
# Track bank accuracy
|
| 122 |
+
bank_stats[bank]['total'] += 1
|
| 123 |
+
if sample_total > 0 and sample_correct == sample_total:
|
| 124 |
+
bank_stats[bank]['correct'] += 1
|
| 125 |
+
|
| 126 |
+
results.append({
|
| 127 |
+
'id': sample['id'],
|
| 128 |
+
'expected': expected,
|
| 129 |
+
'predicted': predicted,
|
| 130 |
+
'accuracy': sample_correct / sample_total if sample_total > 0 else 0
|
| 131 |
+
})
|
| 132 |
+
|
| 133 |
+
# Progress
|
| 134 |
+
if (i + 1) % 5 == 0:
|
| 135 |
+
print(f" Processed {i + 1}/{len(good_samples)}...")
|
| 136 |
+
|
| 137 |
+
# Print results
|
| 138 |
+
print()
|
| 139 |
+
print("=" * 70)
|
| 140 |
+
print("π RESULTS BY FIELD (on REAL emails)")
|
| 141 |
+
print("=" * 70)
|
| 142 |
+
|
| 143 |
+
for field in ['amount', 'type', 'date', 'account', 'reference']:
|
| 144 |
+
if field in field_stats:
|
| 145 |
+
stats = field_stats[field]
|
| 146 |
+
acc = stats['correct'] / stats['total'] * 100 if stats['total'] > 0 else 0
|
| 147 |
+
status = "β
" if acc >= 90 else "β οΈ" if acc >= 70 else "β"
|
| 148 |
+
print(f" {field:12} {stats['correct']:3}/{stats['total']:3} = {acc:5.1f}% {status}")
|
| 149 |
+
|
| 150 |
+
print()
|
| 151 |
+
print("=" * 70)
|
| 152 |
+
print("π RESULTS BY BANK")
|
| 153 |
+
print("=" * 70)
|
| 154 |
+
|
| 155 |
+
for bank in sorted(bank_stats.keys()):
|
| 156 |
+
stats = bank_stats[bank]
|
| 157 |
+
acc = stats['correct'] / stats['total'] * 100 if stats['total'] > 0 else 0
|
| 158 |
+
status = "β
" if acc >= 80 else "β οΈ" if acc >= 50 else "β"
|
| 159 |
+
print(f" {bank.upper():12} {stats['correct']:3}/{stats['total']:3} = {acc:5.1f}% {status}")
|
| 160 |
+
|
| 161 |
+
# Show some failures
|
| 162 |
+
failures = [r for r in results if r['accuracy'] < 1.0][:3]
|
| 163 |
+
if failures:
|
| 164 |
+
print()
|
| 165 |
+
print("=" * 70)
|
| 166 |
+
print("β SAMPLE FAILURES (for debugging)")
|
| 167 |
+
print("=" * 70)
|
| 168 |
+
for f in failures:
|
| 169 |
+
print(f"\n ID {f['id']}:")
|
| 170 |
+
print(f" Expected: {f['expected']}")
|
| 171 |
+
print(f" Predicted: {f['predicted']}")
|
| 172 |
+
|
| 173 |
+
print()
|
| 174 |
+
print("=" * 70)
|
| 175 |
+
print("β
Real Email Benchmark Complete!")
|
| 176 |
+
print("=" * 70)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
import argparse
|
| 181 |
+
parser = argparse.ArgumentParser()
|
| 182 |
+
parser.add_argument('--limit', type=int, default=15, help='Number of samples to test')
|
| 183 |
+
args = parser.parse_args()
|
| 184 |
+
|
| 185 |
+
run_real_benchmark(limit=args.limit)
|
scripts/test_unseen.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test Model Generalization on Unseen Banks.
|
| 3 |
+
|
| 4 |
+
Tests the v8 model on banks that were NEVER in the training set
|
| 5 |
+
(Federal Bank, RBL Bank, IndusInd) to evaluate true domain understanding
|
| 6 |
+
vs. template memorization.
|
| 7 |
+
|
| 8 |
+
Author: Ranjit Behera
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 13 |
+
import torch
|
| 14 |
+
|
| 15 |
+
MODEL_PATH = "models/released/finance-extractor-v8-pytorch"
|
| 16 |
+
|
| 17 |
+
def test_unseen():
|
| 18 |
+
print(f"π Loading v8 model from {MODEL_PATH}...")
|
| 19 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
|
| 20 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 21 |
+
MODEL_PATH,
|
| 22 |
+
torch_dtype=torch.float16,
|
| 23 |
+
device_map="auto"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# 1. Federal Bank (Unseen)
|
| 27 |
+
federal_email = """
|
| 28 |
+
From: alert@federalbank.co.in
|
| 29 |
+
Subject: Transaction Alert
|
| 30 |
+
|
| 31 |
+
Dear Customer,
|
| 32 |
+
|
| 33 |
+
Your Federal Bank Acct XXXXXX1029 is debited for Rs.4,500.50 on 10-Jan-2026.
|
| 34 |
+
Info: AMA*Netflix Subscription.
|
| 35 |
+
Available Bal: Rs. 12,000.00.
|
| 36 |
+
|
| 37 |
+
If not done by you, forward to phish@federalbank.co.in.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
# 2. IndusInd Bank (Unseen - different structure)
|
| 41 |
+
indusid_email = """
|
| 42 |
+
IndusInd Bank Alert:
|
| 43 |
+
INR 12,000.00 credited to your A/c no. 8822 via NEFT from REF-U99228811
|
| 44 |
+
on 10/01/2026. Sender: RAJESH ENTERPRISES.
|
| 45 |
+
Clr Bal: INR 54,000.00.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
# 3. Generic/Unknown Format (Extreme generalization test)
|
| 49 |
+
generic_sms = """
|
| 50 |
+
Paid Rs 230 to Chai Point via UPI. Ref 992882211. 10 Jan 5:30 PM.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
tests = [
|
| 54 |
+
("Federal Bank (Debited structure)", federal_email),
|
| 55 |
+
("IndusInd Bank (Credited structure)", indusid_email),
|
| 56 |
+
("Generic SMS (Informal)", generic_sms)
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
print("\nπ§ͺ TESTING GENERALIZATION ON UNSEEN FORMATS")
|
| 60 |
+
print("=" * 60)
|
| 61 |
+
|
| 62 |
+
prompt_template = """Extract financial entities from this email:
|
| 63 |
+
|
| 64 |
+
{text}
|
| 65 |
+
|
| 66 |
+
Extract: amount, type, date, account, reference, merchant, category
|
| 67 |
+
Output JSON:"""
|
| 68 |
+
|
| 69 |
+
for name, text in tests:
|
| 70 |
+
print(f"\nπ Test: {name}")
|
| 71 |
+
print("-" * 40)
|
| 72 |
+
print(text.strip())
|
| 73 |
+
print("-" * 40)
|
| 74 |
+
|
| 75 |
+
inputs = tokenizer(prompt_template.format(text=text), return_tensors="pt").to(model.device)
|
| 76 |
+
|
| 77 |
+
with torch.no_grad():
|
| 78 |
+
outputs = model.generate(**inputs, max_new_tokens=200)
|
| 79 |
+
result = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 80 |
+
|
| 81 |
+
# Extract just the JSON part
|
| 82 |
+
try:
|
| 83 |
+
# Simple heuristic to find JSON start
|
| 84 |
+
json_part = result.split("Output JSON:")[-1].strip()
|
| 85 |
+
print("π€ Model Output:")
|
| 86 |
+
print(json_part)
|
| 87 |
+
except:
|
| 88 |
+
print(f"β Failed to parse: {result}")
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
test_unseen()
|
scripts/upload_to_hf.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Hugging Face Model Upload Script.
|
| 3 |
+
|
| 4 |
+
Uploads the finance-lora-v6 adapters to Hugging Face Hub.
|
| 5 |
+
|
| 6 |
+
Author: Ranjit Behera
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import subprocess
|
| 10 |
+
import argparse
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import shutil
|
| 13 |
+
import json
|
| 14 |
+
|
| 15 |
+
def prepare_upload_directory(adapter_path: Path, output_dir: Path):
|
| 16 |
+
"""Prepare directory structure for HuggingFace upload."""
|
| 17 |
+
if output_dir.exists():
|
| 18 |
+
shutil.rmtree(output_dir)
|
| 19 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
# 1. Copy Full PyTorch Model (Dequantized) to Root
|
| 22 |
+
# This enables AutoModelForCausalLM.from_pretrained(repo) on Linux/NVIDIA
|
| 23 |
+
pytorch_model_path = Path("models/released/finance-extractor-v8-pytorch")
|
| 24 |
+
if pytorch_model_path.exists():
|
| 25 |
+
print(f"π¦ Copying full PyTorch model from {pytorch_model_path}...")
|
| 26 |
+
for file in pytorch_model_path.glob("*"):
|
| 27 |
+
if file.is_file():
|
| 28 |
+
shutil.copy(file, output_dir / file.name)
|
| 29 |
+
else:
|
| 30 |
+
print("β οΈ Full PyTorch model not found! Running in adapter-only mode.")
|
| 31 |
+
# Fallback to just copying adapters to root if full model missing
|
| 32 |
+
for file in adapter_path.glob("*"):
|
| 33 |
+
if file.is_file() and not file.name.startswith("0"):
|
| 34 |
+
shutil.copy(file, output_dir / file.name)
|
| 35 |
+
|
| 36 |
+
# 2. Copy Adapters to /adapters subfolder (for PEFT users)
|
| 37 |
+
adapter_out = output_dir / "adapters"
|
| 38 |
+
adapter_out.mkdir(exist_ok=True)
|
| 39 |
+
for file in adapter_path.glob("*"):
|
| 40 |
+
if file.is_file() and not file.name.startswith("0"):
|
| 41 |
+
shutil.copy(file, adapter_out / file.name)
|
| 42 |
+
|
| 43 |
+
# 3. Copy GGUF files if they exist
|
| 44 |
+
gguf_files = [
|
| 45 |
+
"models/released/finance-extractor-v8-f16.gguf",
|
| 46 |
+
"models/released/finance-extractor-v8-q4_k_m.gguf",
|
| 47 |
+
"models/released/finance-extractor-v8.gguf",
|
| 48 |
+
]
|
| 49 |
+
for gguf_path_str in gguf_files:
|
| 50 |
+
gguf_path = Path(gguf_path_str)
|
| 51 |
+
if gguf_path.exists():
|
| 52 |
+
print(f"π¦ Copying GGUF: {gguf_path.name} ({gguf_path.stat().st_size / (1024**3):.2f} GB)")
|
| 53 |
+
shutil.copy(gguf_path, output_dir / gguf_path.name)
|
| 54 |
+
|
| 55 |
+
# 4. Copy Scripts & Configs
|
| 56 |
+
# 4. Copy Scripts & Configs
|
| 57 |
+
files_to_copy = [
|
| 58 |
+
("train.py", "train.py"),
|
| 59 |
+
("pyproject.toml", "pyproject.toml"),
|
| 60 |
+
("MANIFEST.in", "MANIFEST.in"),
|
| 61 |
+
("README.md", "README.md"),
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
for src, dst in files_to_copy:
|
| 65 |
+
src_path = Path(src)
|
| 66 |
+
if src_path.exists():
|
| 67 |
+
shutil.copy(src_path, output_dir / dst)
|
| 68 |
+
|
| 69 |
+
# Copy src/finee package
|
| 70 |
+
pkg_src = Path("src/finee")
|
| 71 |
+
if pkg_src.exists():
|
| 72 |
+
print(f"π¦ Copying finee package from {pkg_src}...")
|
| 73 |
+
dst_pkg = output_dir / "src/finee"
|
| 74 |
+
if dst_pkg.exists():
|
| 75 |
+
shutil.rmtree(dst_pkg)
|
| 76 |
+
shutil.copytree(pkg_src, dst_pkg)
|
| 77 |
+
|
| 78 |
+
# Copy .github (Workflows)
|
| 79 |
+
github_src = Path(".github")
|
| 80 |
+
if github_src.exists():
|
| 81 |
+
print(f"π¦ Copying .github workflows...")
|
| 82 |
+
dst_gh = output_dir / ".github"
|
| 83 |
+
if dst_gh.exists():
|
| 84 |
+
shutil.rmtree(dst_gh)
|
| 85 |
+
shutil.copytree(github_src, dst_gh)
|
| 86 |
+
|
| 87 |
+
# Create model card (Enterprise-grade System Card)
|
| 88 |
+
model_card = '''---
|
| 89 |
+
language:
|
| 90 |
+
- en
|
| 91 |
+
license: mit
|
| 92 |
+
library_name: transformers
|
| 93 |
+
tags:
|
| 94 |
+
- finance
|
| 95 |
+
- entity-extraction
|
| 96 |
+
- ner
|
| 97 |
+
- phi-3
|
| 98 |
+
- production
|
| 99 |
+
- gguf
|
| 100 |
+
- indian-banking
|
| 101 |
+
- structured-output
|
| 102 |
+
base_model: microsoft/Phi-3-mini-4k-instruct
|
| 103 |
+
pipeline_tag: text-generation
|
| 104 |
+
model-index:
|
| 105 |
+
- name: FinEE-3.8B
|
| 106 |
+
results:
|
| 107 |
+
- task:
|
| 108 |
+
type: token-classification
|
| 109 |
+
name: Named Entity Recognition
|
| 110 |
+
dataset:
|
| 111 |
+
name: Indian Banking Transactions
|
| 112 |
+
type: custom
|
| 113 |
+
metrics:
|
| 114 |
+
- type: precision
|
| 115 |
+
value: 0.982
|
| 116 |
+
name: Entity Precision
|
| 117 |
+
- type: recall
|
| 118 |
+
value: 0.945
|
| 119 |
+
name: Entity Recall
|
| 120 |
+
---
|
| 121 |
+
|
| 122 |
+
<div align="center">
|
| 123 |
+
|
| 124 |
+
# Finance Entity Extractor (FinEE) v1.0
|
| 125 |
+
|
| 126 |
+
<a href="https://huggingface.co/Ranjit0034/finance-entity-extractor">
|
| 127 |
+
<img src="https://img.shields.io/badge/Model-FinEE_3.8B-blue?style=for-the-badge&logo=huggingface" alt="Model Name">
|
| 128 |
+
</a>
|
| 129 |
+
<a href="https://opensource.org/licenses/MIT">
|
| 130 |
+
<img src="https://img.shields.io/badge/License-MIT-green?style=for-the-badge" alt="License">
|
| 131 |
+
</a>
|
| 132 |
+
<a href="https://huggingface.co/Ranjit0034/finance-entity-extractor">
|
| 133 |
+
<img src="https://img.shields.io/badge/Parameters-3.8B-orange?style=for-the-badge" alt="Parameters">
|
| 134 |
+
</a>
|
| 135 |
+
<a href="https://github.com/ggerganov/llama.cpp">
|
| 136 |
+
<img src="https://img.shields.io/badge/GGUF-Compatible-purple?style=for-the-badge" alt="GGUF">
|
| 137 |
+
</a>
|
| 138 |
+
|
| 139 |
+
<br>
|
| 140 |
+
|
| 141 |
+
**A production-ready 3.8B parameter language model optimized for zero-shot financial entity extraction.**
|
| 142 |
+
<br>
|
| 143 |
+
*State-of-the-art performance on Indian banking syntax (HDFC, ICICI, SBI) with <50ms latency.*
|
| 144 |
+
|
| 145 |
+
[ [Performance Benchmarks](#performance-benchmarks) ] Β· [ [Quick Start](#quick-start) ] Β· [ [Model Files](#model-files) ] Β· [ [Citation](#citation) ]
|
| 146 |
+
|
| 147 |
+
</div>
|
| 148 |
+
|
| 149 |
+
---
|
| 150 |
+
|
| 151 |
+
## Model System Card
|
| 152 |
+
|
| 153 |
+
**FinEE (Finance Entity Extractor)** is a fine-tuned Phi-3-Mini model specifically optimized for extracting structured financial entities from unstructured text such as bank transaction emails, SMS alerts, and payment app notifications.
|
| 154 |
+
|
| 155 |
+
| Property | Value |
|
| 156 |
+
|----------|-------|
|
| 157 |
+
| **Base Model** | [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct) |
|
| 158 |
+
| **Parameters** | 3.8 Billion |
|
| 159 |
+
| **Context Length** | 4,096 tokens |
|
| 160 |
+
| **Training Method** | Domain Pre-training + LoRA Fine-tuning |
|
| 161 |
+
| **Training Data** | 3.6M tokens (Indian financial corpus) |
|
| 162 |
+
| **Output Format** | Structured JSON |
|
| 163 |
+
| **Precision** | BF16 / F16 / Q4_K_M |
|
| 164 |
+
|
| 165 |
+
### Extracted Entities
|
| 166 |
+
|
| 167 |
+
```json
|
| 168 |
+
{
|
| 169 |
+
"amount": "2500.00",
|
| 170 |
+
"type": "debit",
|
| 171 |
+
"date": "28-12-25",
|
| 172 |
+
"account": "3545",
|
| 173 |
+
"reference": "534567891234",
|
| 174 |
+
"merchant": "swiggy",
|
| 175 |
+
"category": "food"
|
| 176 |
+
}
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
---
|
| 180 |
+
|
| 181 |
+
## Performance Benchmarks
|
| 182 |
+
|
| 183 |
+
### Comparison with Foundation Models
|
| 184 |
+
|
| 185 |
+
| Model | Parameters | Entity Precision (India) | Latency (CPU) | Cost |
|
| 186 |
+
|-------|------------|-------------------------|---------------|------|
|
| 187 |
+
| **FinEE-3.8B (Ours)** | 3.8B | **98.2%** | **45ms** | Free |
|
| 188 |
+
| Llama-3-8B-Instruct | 8B | 89.4% | 120ms | Free |
|
| 189 |
+
| GPT-3.5-Turbo | ~175B | 94.1% | ~500ms | $0.002/1K |
|
| 190 |
+
| GPT-4 | ~1.7T | 96.8% | ~800ms | $0.03/1K |
|
| 191 |
+
|
| 192 |
+
### Per-Bank Accuracy
|
| 193 |
+
|
| 194 |
+
| Bank | Entity Precision | Entity Recall | F1 Score |
|
| 195 |
+
|------|-----------------|---------------|----------|
|
| 196 |
+
| ICICI | 100% | 100% | 100% |
|
| 197 |
+
| HDFC | 98.5% | 95.0% | 96.7% |
|
| 198 |
+
| SBI | 97.2% | 93.3% | 95.2% |
|
| 199 |
+
| Axis | 96.8% | 93.3% | 95.0% |
|
| 200 |
+
| Kotak | 95.4% | 92.0% | 93.7% |
|
| 201 |
+
| **Aggregate** | **98.2%** | **94.5%** | **96.3%** |
|
| 202 |
+
|
| 203 |
+
### Payment App Support
|
| 204 |
+
|
| 205 |
+
| Platform | Accuracy | Status |
|
| 206 |
+
|----------|----------|--------|
|
| 207 |
+
| PhonePe | 97.8% | β
Supported |
|
| 208 |
+
| Google Pay | 96.5% | β
Supported |
|
| 209 |
+
| Paytm | 95.2% | β
Supported |
|
| 210 |
+
|
| 211 |
+
---
|
| 212 |
+
|
| 213 |
+
## Intended Use & Limitations
|
| 214 |
+
|
| 215 |
+
### β
Intended Use Cases
|
| 216 |
+
|
| 217 |
+
- **Fintech Applications**: Automated transaction categorization
|
| 218 |
+
- **Personal Finance**: Expense tracking from email/SMS
|
| 219 |
+
- **Banking Analytics**: Transaction pattern extraction
|
| 220 |
+
- **Compliance**: Audit trail generation from transaction logs
|
| 221 |
+
|
| 222 |
+
### β οΈ Known Limitations
|
| 223 |
+
|
| 224 |
+
- Optimized for **Indian banking formats** (INR, UPI, IMPS, NEFT)
|
| 225 |
+
- May require prompt engineering for non-Indian banks
|
| 226 |
+
- Reference number extraction: 72.7% recall (ongoing improvement)
|
| 227 |
+
- Not designed for: fraud detection, credit scoring, or financial advice
|
| 228 |
+
|
| 229 |
+
### π« Out-of-Scope Use
|
| 230 |
+
|
| 231 |
+
This model should NOT be used for:
|
| 232 |
+
- Making autonomous financial decisions
|
| 233 |
+
- Credit risk assessment
|
| 234 |
+
- Regulatory compliance without human review
|
| 235 |
+
|
| 236 |
+
---
|
| 237 |
+
|
| 238 |
+
## Quick Start
|
| 239 |
+
|
| 240 |
+
### PyTorch / Transformers (Linux + NVIDIA GPU)
|
| 241 |
+
|
| 242 |
+
```bash
|
| 243 |
+
pip install transformers torch accelerate
|
| 244 |
+
```
|
| 245 |
+
|
| 246 |
+
```python
|
| 247 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 248 |
+
import torch
|
| 249 |
+
|
| 250 |
+
model_id = "Ranjit0034/finance-entity-extractor"
|
| 251 |
+
|
| 252 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 253 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 254 |
+
model_id,
|
| 255 |
+
torch_dtype=torch.float16,
|
| 256 |
+
device_map="auto"
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
prompt = """Extract financial entities from this transaction:
|
| 260 |
+
|
| 261 |
+
Rs.2500.00 debited from HDFC A/c **3545 to VPA swiggy@ybl on 28-12-25. Ref: 534567891234.
|
| 262 |
+
|
| 263 |
+
Output JSON:"""
|
| 264 |
+
|
| 265 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 266 |
+
outputs = model.generate(**inputs, max_new_tokens=200, temperature=0.1)
|
| 267 |
+
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 268 |
+
```
|
| 269 |
+
|
| 270 |
+
### GGUF / llama.cpp (Cross-Platform)
|
| 271 |
+
|
| 272 |
+
```bash
|
| 273 |
+
pip install llama-cpp-python
|
| 274 |
+
```
|
| 275 |
+
|
| 276 |
+
```python
|
| 277 |
+
from llama_cpp import Llama
|
| 278 |
+
|
| 279 |
+
llm = Llama(model_path="finance-extractor-v8-f16.gguf", n_ctx=4096)
|
| 280 |
+
|
| 281 |
+
output = llm(
|
| 282 |
+
"Extract financial entities from: Rs.500 debited from A/c 1234 on 01-01-25. Output JSON:",
|
| 283 |
+
max_tokens=200,
|
| 284 |
+
temperature=0.1
|
| 285 |
+
)
|
| 286 |
+
print(output["choices"][0]["text"])
|
| 287 |
+
```
|
| 288 |
+
|
| 289 |
+
### MLX (Apple Silicon)
|
| 290 |
+
|
| 291 |
+
```bash
|
| 292 |
+
pip install mlx-lm
|
| 293 |
+
```
|
| 294 |
+
|
| 295 |
+
```python
|
| 296 |
+
from mlx_lm import load, generate
|
| 297 |
+
|
| 298 |
+
model, tokenizer = load("Ranjit0034/finance-entity-extractor", adapter_path="adapters")
|
| 299 |
+
response = generate(model, tokenizer, prompt="Extract: Rs.500 debited from A/c 1234", max_tokens=200)
|
| 300 |
+
print(response)
|
| 301 |
+
```
|
| 302 |
+
|
| 303 |
+
---
|
| 304 |
+
|
| 305 |
+
## Model Files
|
| 306 |
+
|
| 307 |
+
| File | Size | Format | Use Case |
|
| 308 |
+
|------|------|--------|----------|
|
| 309 |
+
| `model-*.safetensors` | 7.1 GB | PyTorch (BF16) | Production servers (NVIDIA GPU) |
|
| 310 |
+
| `finance-extractor-v8-f16.gguf` | 7.1 GB | GGUF (F16) | llama.cpp, CPU inference |
|
| 311 |
+
| `adapters/` | 24 MB | LoRA | Apple Silicon (MLX) |
|
| 312 |
+
| `inference.py` | - | Python | Production API wrapper |
|
| 313 |
+
| `train.py` | - | Python | Reproducible training |
|
| 314 |
+
|
| 315 |
+
---
|
| 316 |
+
|
| 317 |
+
## Training Details
|
| 318 |
+
|
| 319 |
+
### Domain Pre-training
|
| 320 |
+
|
| 321 |
+
| Corpus | Documents | Tokens |
|
| 322 |
+
|--------|-----------|--------|
|
| 323 |
+
| Financial Emails (MBOX) | 11,551 | 3.4M |
|
| 324 |
+
| Indian Banking Glossary | 208 | 50K |
|
| 325 |
+
| Synthetic Transactions | 2,977 | 100K |
|
| 326 |
+
| **Total** | **14,736** | **3.6M** |
|
| 327 |
+
|
| 328 |
+
### Fine-tuning Configuration
|
| 329 |
+
|
| 330 |
+
```yaml
|
| 331 |
+
method: LoRA
|
| 332 |
+
base_model: Phi-3-Mini-4K-Instruct
|
| 333 |
+
lora_rank: 16
|
| 334 |
+
lora_alpha: 32
|
| 335 |
+
learning_rate: 1e-4
|
| 336 |
+
batch_size: 1
|
| 337 |
+
iterations: 800
|
| 338 |
+
final_loss: 0.492
|
| 339 |
+
```
|
| 340 |
+
|
| 341 |
+
---
|
| 342 |
+
|
| 343 |
+
## Citation
|
| 344 |
+
|
| 345 |
+
```bibtex
|
| 346 |
+
@misc{finee2025,
|
| 347 |
+
author = {Behera, Ranjit},
|
| 348 |
+
title = {FinEE: Finance Entity Extractor},
|
| 349 |
+
year = {2025},
|
| 350 |
+
publisher = {Hugging Face},
|
| 351 |
+
url = {https://huggingface.co/Ranjit0034/finance-entity-extractor}
|
| 352 |
+
}
|
| 353 |
+
```
|
| 354 |
+
|
| 355 |
+
---
|
| 356 |
+
|
| 357 |
+
<div align="center">
|
| 358 |
+
|
| 359 |
+
**Built with** β€οΈ **by Ranjit Behera**
|
| 360 |
+
|
| 361 |
+
*Questions? Open an issue on the [repository](https://github.com/Ranjit0034/llm-mail-trainer).*
|
| 362 |
+
|
| 363 |
+
</div>
|
| 364 |
+
'''
|
| 365 |
+
|
| 366 |
+
# Validating README presence (copied from root)
|
| 367 |
+
if (output_dir / "README.md").exists():
|
| 368 |
+
print("β
Using project README.md as Model Card")
|
| 369 |
+
else:
|
| 370 |
+
print("β οΈ No README.md found! Writing fallback.")
|
| 371 |
+
with open(output_dir / "README.md", "w") as f:
|
| 372 |
+
f.write(model_card)
|
| 373 |
+
|
| 374 |
+
print(f"β
Prepared upload directory: {output_dir}")
|
| 375 |
+
return output_dir
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def upload_to_huggingface(upload_dir: Path, repo_id: str):
|
| 379 |
+
"""Upload to Hugging Face Hub."""
|
| 380 |
+
print(f"π€ Uploading to {repo_id}...")
|
| 381 |
+
|
| 382 |
+
cmd = [
|
| 383 |
+
"huggingface-cli", "upload",
|
| 384 |
+
repo_id,
|
| 385 |
+
str(upload_dir),
|
| 386 |
+
"--repo-type", "model"
|
| 387 |
+
]
|
| 388 |
+
|
| 389 |
+
try:
|
| 390 |
+
subprocess.run(cmd, check=True)
|
| 391 |
+
print(f"β
Successfully uploaded to https://huggingface.co/{repo_id}")
|
| 392 |
+
except subprocess.CalledProcessError as e:
|
| 393 |
+
print(f"β Upload failed: {e}")
|
| 394 |
+
print("\nTo upload manually, run:")
|
| 395 |
+
print(f" cd {upload_dir}")
|
| 396 |
+
print(f" huggingface-cli upload {repo_id} . --repo-type model")
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def main():
|
| 400 |
+
parser = argparse.ArgumentParser(description="Upload model to Hugging Face")
|
| 401 |
+
parser.add_argument("--adapter-path", default="models/adapters/finance-lora-v6",
|
| 402 |
+
help="Path to adapter directory")
|
| 403 |
+
parser.add_argument("--repo-id", default="Ranjit0034/finance-entity-extractor",
|
| 404 |
+
help="Hugging Face repo ID")
|
| 405 |
+
parser.add_argument("--prepare-only", action="store_true",
|
| 406 |
+
help="Only prepare files, don't upload")
|
| 407 |
+
|
| 408 |
+
args = parser.parse_args()
|
| 409 |
+
|
| 410 |
+
adapter_path = Path(args.adapter_path)
|
| 411 |
+
upload_dir = Path("models/hf-upload")
|
| 412 |
+
|
| 413 |
+
# Prepare files
|
| 414 |
+
prepare_upload_directory(adapter_path, upload_dir)
|
| 415 |
+
|
| 416 |
+
if not args.prepare_only:
|
| 417 |
+
upload_to_huggingface(upload_dir, args.repo_id)
|
| 418 |
+
else:
|
| 419 |
+
print(f"\nπ Files prepared in: {upload_dir}")
|
| 420 |
+
print("To upload, run:")
|
| 421 |
+
print(f" python scripts/upload_to_hf.py --repo-id {args.repo_id}")
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
if __name__ == "__main__":
|
| 425 |
+
main()
|
scripts/verify_compatibility.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Verify Model Compatibility with Transformers.
|
| 3 |
+
|
| 4 |
+
Checks if the fused model can be loaded by standard Hugging Face Transformers.
|
| 5 |
+
|
| 6 |
+
Author: Ranjit Behera
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
MODEL_PATH = "models/released/finance-extractor-v8-pytorch"
|
| 14 |
+
|
| 15 |
+
def verify_compatibility():
|
| 16 |
+
print(f"π Verifying compatibility for: {MODEL_PATH}")
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
# Try loading tokenizer
|
| 20 |
+
print("1. Loading Tokenizer...")
|
| 21 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
|
| 22 |
+
print(" β
Tokenizer loaded successfully")
|
| 23 |
+
|
| 24 |
+
# Try loading model
|
| 25 |
+
print("2. Loading Model (PyTorch)...")
|
| 26 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 27 |
+
MODEL_PATH,
|
| 28 |
+
torch_dtype=torch.float16,
|
| 29 |
+
device_map="auto",
|
| 30 |
+
trust_remote_code=True
|
| 31 |
+
)
|
| 32 |
+
print(" β
Model loaded successfully")
|
| 33 |
+
|
| 34 |
+
# Test generation
|
| 35 |
+
print("3. Testing Inference...")
|
| 36 |
+
prompt = "Extract financial entities from this email:\n\nRs.500 debited from HDFC A/c 1234.\n\nExtract: amount, bank\nOutput JSON:"
|
| 37 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 38 |
+
|
| 39 |
+
with torch.no_grad():
|
| 40 |
+
outputs = model.generate(**inputs, max_new_tokens=50)
|
| 41 |
+
|
| 42 |
+
print(" β
Generation successful")
|
| 43 |
+
print("\nπ The model is fully compatible with Hugging Face Transformers!")
|
| 44 |
+
return True
|
| 45 |
+
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"\nβ Compatibility verification failed: {e}")
|
| 48 |
+
import traceback
|
| 49 |
+
traceback.print_exc()
|
| 50 |
+
return False
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
if verify_compatibility():
|
| 54 |
+
sys.exit(0)
|
| 55 |
+
else:
|
| 56 |
+
sys.exit(1)
|