{ "cells": [ { "cell_type": "code", "execution_count": 7, "id": "96e087b6-4196-4109-bb30-b78125fafb54", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "✅ Loaded 40,820 parsed emails\n", "✅ Loaded 499 classification results\n", "Finance emails found: 89\n", "\n", "=== TOP FINANCE SENDERS ===\n", " 18 : \n", " 7 : \"ICICI Bank Privilege Banking\"\n", " 5 : ICICI Bank\n", " 5 : \"HDFC Life\"\n", " 4 : HDFC Bank InstaAlerts\n", " 4 : Groww Digest\n", " 3 : Quora Digest\n", " 3 : Groww\n", " 3 : HDFC Life - no reply\n", " 2 : \"alert @ icicibank . com\"\n", " 2 : Paisabazaar Support\n", " 2 : LinkedIn\n", " 2 : Google Play\n", " 2 : \"ICICI Bank \"\n", " 1 : \"Zerodha Broking Ltd\"\n", "Emails with empty sender: 18\n", "\n", "1. Subject: Funds/Securities Balance\n", " 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", "\n", "2. Subject: Dear Customer, Rs.120.00 has been debited from account 1234 to VPA com\n", " 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", "\n", "3. Subject: 40GB of Data allocated to Jio Number 7855883757\n", " 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", "\n", "4. Subject: Alert for transaction through ICICI Bank iMobile\n", " 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", "\n", "5. Subject: Delivered: Your ICICI Bank Card- ATM / Debit Reissue status\n", " 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", "\n", "=== SAMPLE FINANCE EMAIL BODIES ===\n", "\n", "Real finance emails: 53\n", "\n", "--- Email 1 ---\n", "Subject: Daily Equity Margin Statement for HTV475 - December 24, 2025\n", "Sender: \"Zerodha Broking Ltd\"\n", "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", "\n", "--- Email 2 ---\n", "Subject: ❗ You have done a UPI txn. Check details!\n", "Sender: HDFC Bank InstaAlerts\n", "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", "\n", "--- Email 3 ---\n", "Subject: Funds/Securities Balance\n", "Sender: \n", "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", "\n", "--- Email 4 ---\n", "Subject: Dear Customer, Rs.120.00 has been debited from account 1234 to VPA companyonline\n", "Sender: \n", "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", "\n", "--- Email 5 ---\n", "Subject: ❗ You have done a UPI txn. Check details!\n", "Sender: HDFC Bank InstaAlerts\n", "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", "\n", "=== INPUT TEXT ===\n", "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", "\n", "=== EXTRACTED ENTITIES ===\n", " account: HTV475\n", "=== TESTING ENTITY EXTRACTION ===\n", "\n", "Transaction emails found: 9\n", "\n", "--- Email 1 ---\n", "Subject: ❗ You have done a UPI txn. Check details!\n", "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", "\n", "Extracted:\n", " amount: 200.00\n", " type: debit\n", " account: 3545\n", " date: 24-12-25\n", " reference: 535899488403\n", "\n", "--- Email 2 ---\n", "Subject: Dear Customer, Rs.120.00 has been debited from account 1234 \n", "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", "\n", "Extracted:\n", " amount: 120.00\n", " type: debit\n", " account: 1234\n", " date: 06-12-25\n", " reference: 500000000006\n", "\n", "--- Email 3 ---\n", "Subject: ❗ You have done a UPI txn. Check details!\n", "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", "\n", "Extracted:\n", " amount: 1890.28\n", " type: debit\n", " account: 3545\n", " date: 25-12-25\n", " reference: 535965972977\n", "\n", "✅ Saved 53 finance emails to data/filtered/finance_emails.json\n", "✅ Saved patterns to data/filtered/finance_patterns.json\n" ] } ], "source": [ "# Cell 1: Imports & Load Data\n", "import json\n", "from pathlib import Path\n", "from collections import Counter\n", "\n", "PROJECT = Path.home() / \"llm-mail-trainer\"\n", "\n", "# Load parsed emails (40k)\n", "with open(PROJECT / \"data/parsed/emails.json\", 'r') as f:\n", " parsed_emails = json.load(f)\n", "\n", "# Load classification results (499)\n", "with open(PROJECT / \"data/parsed/classification_results.json\", 'r') as f:\n", " results = json.load(f)\n", "\n", "print(f\"✅ Loaded {len(parsed_emails):,} parsed emails\")\n", "print(f\"✅ Loaded {len(results)} classification results\")\n", "\n", "# Cell 2: Extract finance emails with full details\n", "finance_results = [r for r in results if r['category'] == 'finance']\n", "\n", "# Get full email data for finance emails\n", "finance_ids = [r['id'] for r in finance_results]\n", "finance_emails_full = [e for e in parsed_emails if e['id'] in finance_ids]\n", "\n", "print(f\"Finance emails found: {len(finance_emails_full)}\")\n", "\n", "# Show senders\n", "print(\"\\n=== TOP FINANCE SENDERS ===\")\n", "senders = [e['sender'] for e in finance_emails_full]\n", "for sender, count in Counter(senders).most_common(15):\n", " print(f\" {count:3} : {sender[:60]}\")\n", "\n", "# Cell 3: Check emails with empty sender\n", "empty_sender_emails = [e for e in finance_emails_full if e['sender'].strip() == '']\n", "\n", "print(f\"Emails with empty sender: {len(empty_sender_emails)}\\n\")\n", "\n", "for i, email in enumerate(empty_sender_emails[:5]):\n", " print(f\"{i+1}. Subject: {email['subject'][:70]}\")\n", " print(f\" Body: {email['body'][:150]}...\")\n", " print()\n", "\n", "# Cell 4: View finance email bodies (for pattern discovery)\n", "print(\"=== SAMPLE FINANCE EMAIL BODIES ===\\n\")\n", "\n", "# Filter only emails with known finance senders\n", "finance_senders = ['icici', 'hdfc', 'groww', 'zerodha', 'paisabazaar', 'sbi', 'axis', 'kotak']\n", "\n", "real_finance = []\n", "for e in finance_emails_full:\n", " sender_lower = e['sender'].lower()\n", " subject_lower = e['subject'].lower()\n", " body_lower = e['body'].lower()\n", " \n", " # Check sender or content\n", " if any(fs in sender_lower for fs in finance_senders):\n", " real_finance.append(e)\n", " elif any(kw in body_lower for kw in ['debited', 'credited', 'transaction', 'upi', 'a/c', 'balance']):\n", " real_finance.append(e)\n", "\n", "print(f\"Real finance emails: {len(real_finance)}\\n\")\n", "\n", "# Show 5 samples\n", "for i, email in enumerate(real_finance[:5]):\n", " print(f\"--- Email {i+1} ---\")\n", " print(f\"Subject: {email['subject'][:80]}\")\n", " print(f\"Sender: {email['sender']}\")\n", " print(f\"Body: {email['body'][:300]}\")\n", " print()\n", "\n", "# Cell 5: Pattern extraction functions\n", "import re\n", "\n", "def extract_entities(text):\n", " \"\"\"Extract financial entities from email text.\"\"\"\n", " \n", " entities = {}\n", " \n", " # Amount: Rs.1890.28 or Rs 1,890.28 or ₹1890\n", " amount_match = re.search(r'(?:Rs\\.?|₹)\\s*([\\d,]+(?:\\.\\d{2})?)', text)\n", " if amount_match:\n", " entities['amount'] = amount_match.group(1).replace(',', '')\n", " \n", " # Type: debited or credited\n", " if 'debited' in text.lower():\n", " entities['type'] = 'debit'\n", " elif 'credited' in text.lower():\n", " entities['type'] = 'credit'\n", " \n", " # Account: account XXXX or A/C XXXX\n", " account_match = re.search(r'(?:account|A/C|a/c)\\s*[:\\s]?\\s*(\\w+)', text, re.IGNORECASE)\n", " if account_match:\n", " entities['account'] = account_match.group(1)\n", " \n", " # Date: DD-MM-YY or DD-MM-YYYY\n", " date_match = re.search(r'(\\d{2}-\\d{2}-\\d{2,4})', text)\n", " if date_match:\n", " entities['date'] = date_match.group(1)\n", " \n", " # UPI Reference\n", " ref_match = re.search(r'reference\\s*(?:number|no\\.?)?\\s*(?:is)?\\s*(\\d+)', text, re.IGNORECASE)\n", " if ref_match:\n", " entities['reference'] = ref_match.group(1)\n", " \n", " return entities\n", "\n", "# Test on sample\n", "sample_text = real_finance[0]['body']\n", "print(\"=== INPUT TEXT ===\")\n", "print(sample_text[:300])\n", "print(\"\\n=== EXTRACTED ENTITIES ===\")\n", "extracted = extract_entities(sample_text)\n", "for key, value in extracted.items():\n", " print(f\" {key}: {value}\")\n", "\n", "# Cell 6: Test on transaction emails\n", "print(\"=== TESTING ENTITY EXTRACTION ===\\n\")\n", "\n", "# Find emails with \"debited\" or \"credited\"\n", "transaction_emails = [e for e in real_finance if 'debited' in e['body'].lower() or 'credited' in e['body'].lower()]\n", "\n", "print(f\"Transaction emails found: {len(transaction_emails)}\\n\")\n", "\n", "for i, email in enumerate(transaction_emails[:3]):\n", " print(f\"--- Email {i+1} ---\")\n", " print(f\"Subject: {email['subject'][:60]}\")\n", " print(f\"Body: {email['body'][:200]}...\")\n", " print(f\"\\nExtracted:\")\n", " extracted = extract_entities(email['body'])\n", " for key, value in extracted.items():\n", " print(f\" {key}: {value}\")\n", " print()\n", "\n", "# Cell 7: Save patterns and filtered finance emails\n", "\n", "# Create filtered directory\n", "filtered_dir = PROJECT / \"data/filtered\"\n", "filtered_dir.mkdir(exist_ok=True)\n", "\n", "# Save real finance emails\n", "with open(filtered_dir / \"finance_emails.json\", 'w') as f:\n", " json.dump(real_finance, f, ensure_ascii=False, indent=2)\n", "\n", "# Save patterns configuration\n", "patterns = {\n", " \"amount\": r\"(?:Rs\\.?|₹)\\s*([\\d,]+(?:\\.\\d{2})?)\",\n", " \"type_debit\": \"debited\",\n", " \"type_credit\": \"credited\",\n", " \"account\": r\"(?:account|A/C|a/c)\\s*[:\\s]?\\s*(\\w+)\",\n", " \"date\": r\"(\\d{2}-\\d{2}-\\d{2,4})\",\n", " \"reference\": r\"reference\\s*(?:number|no\\.?)?\\s*(?:is)?\\s*(\\d+)\",\n", " \"finance_senders\": [\"icici\", \"hdfc\", \"groww\", \"zerodha\", \"paisabazaar\", \"sbi\", \"axis\", \"kotak\"],\n", " \"finance_keywords\": [\"debited\", \"credited\", \"transaction\", \"upi\", \"a/c\", \"balance\", \"payment\"]\n", "}\n", "\n", "with open(filtered_dir / \"finance_patterns.json\", 'w') as f:\n", " json.dump(patterns, f, indent=2)\n", "\n", "print(f\"✅ Saved {len(real_finance)} finance emails to data/filtered/finance_emails.json\")\n", "print(f\"✅ Saved patterns to data/filtered/finance_patterns.json\")" ] }, { "cell_type": "code", "execution_count": null, "id": "b2f02e65-c53f-492a-a32d-b07543a37085", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.6" } }, "nbformat": 4, "nbformat_minor": 5 }