Spaces:
Sleeping
Sleeping
Download scripts/clean_and_promote_rules.py from Coeinterns/bank-statement-api: direct link, hf CLI and curl.
- Browser
- Download file 23.3 kB
-
https://huggingface.co/spaces/Coeinterns/bank-statement-api/resolve/main/scripts/clean_and_promote_rules.py
- Command line
-
hf download hf://spaces/Coeinterns/bank-statement-api/scripts/clean_and_promote_rules.py
-
curl -L -o clean_and_promote_rules.py https://huggingface.co/spaces/Coeinterns/bank-statement-api/resolve/main/scripts/clean_and_promote_rules.py
23.3 kB
| #!/usr/bin/env python3 | |
| """ | |
| scripts/clean_and_promote_rules.py | |
| βββββββββββββββββββββββββββββββββββ | |
| Cleans classification rules in the database: | |
| - De-duplicates keywords within same category and rule criteria. | |
| - Resolves category conflicts using classification_flat and domain heuristics. | |
| - Filters and promotes high-quality pending learned logs to classification_rules. | |
| Run in dry-run mode (default): | |
| python scripts/clean_and_promote_rules.py | |
| Commit changes: | |
| python scripts/clean_and_promote_rules.py --commit | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import sys | |
| import re | |
| import argparse | |
| from pathlib import Path | |
| from dotenv import load_dotenv | |
| from sqlalchemy import text | |
| # Setup paths | |
| ROOT = Path(__file__).resolve().parent.parent | |
| sys.path.insert(0, str(ROOT)) | |
| sys.path.insert(0, str(ROOT / "bank-classifier")) | |
| load_dotenv(ROOT / ".env") | |
| from auth.database import SessionLocal | |
| from auth.rule_models import ClassificationRule, ClassificationCategory, LearnedRuleLog | |
| # Known very generic words to filter out from auto-promotion to avoid false matches | |
| GENERIC_STOP_WORDS = { | |
| "services", "services australia", "connect", "boundary", "redirected", "street", | |
| "delights", "traditional", "traveling", "travels", "family trust", "adjustment", | |
| "continental", "smithfield", "leonards", "douglas", "emerald", "carlton", "runcorn", | |
| "calamvale", "robina", "toowong", "hills", "brisban", "melbou", "cremorn", "gold coast", | |
| "sydney", "north", "south", "east", "west", "gate", "plaza", "square", "market", | |
| "station", "app", "web", "online", "payment", "direct", "debit", "credit", "transfer", | |
| "cash", "atm", "ref", "reference", "purpose", "description", "transaction", "amount", | |
| "fee", "fees", "interest", "charge", "refund", "reversal", "adjustment", "commission", | |
| "tax", "ato", "government", "council", "rates", "utility", "bill", "invoice", "payment", | |
| "pay", "card", "visa", "mastercard", "amex", "eftpos", "cheque", "deposit", "withdrawal", | |
| # Suburbs, cities, and highly generic/location words from transaction analysis | |
| "burpengary", "southport", "springwood", "underwood", "ipswich", "mullumbimby", | |
| "wakerley", "fortitude", "cairns", "mooloolaba", "coomera", "caboolture", "morningside", | |
| "annerley", "wollongong", "roseville", "cardwell", "byron", "byron bay", "stanhope", | |
| "stanhope gardens", "north lakes", "geelong", "collingwood", "townsville", "pimlico", | |
| "katoomba", "helensvale", "reedy creek", "buderim", "eightmile", "wetherill", "seaforth", | |
| "balgowlah", "brookvale", "mitchell", "algester", "earlville", "woodridge", "wantirna", | |
| "kingswood", "corrimal", "fairy meadow", "figtree", "goulburn", "maroochydore", "marooch", | |
| "mount waverley", "waverley", "mulgrave", "bentleigh", "sunnypark", "sunnybank", "tingalpa", | |
| "williamsstown", "willy", "reject", "holdings", "stores", "morning", "progress", | |
| "national", "vincent", "oceania", "warrigal", "suprmrkt", "itransfer", "bella", | |
| "bsbane", "seventeen", "braised", "workshops", "upper", "conservatio", "churchill", | |
| "brisbanau", "deception", "mansfield" | |
| } | |
| # Domain conflict resolution map for conflicting keywords not found in classification_flat | |
| DOMAIN_RESOLUTIONS = { | |
| "health fund": "Health Insurance", | |
| "home insurance": "Car & Home Insurance", | |
| "party": "Events & Concerts", | |
| "pilates": "Gym & Swimming", | |
| "prescription": "Pharmacy", | |
| "rego": "Transport & Auto", | |
| "season sushi": "Fast Food", | |
| "shoes": "Footwear", | |
| "smiggle": "Childcare", | |
| "spriggy schools": "Public Education", | |
| "star phones": "Mobile & Internet", | |
| "surfside snax": "Fast Food", | |
| "takeaway": "Fast Food", | |
| "textbook": "Books & Stationery", | |
| "uniform": "Clothing", | |
| "updoc.com.au": "Medical, Health & Fitness", | |
| "vet": "Vet & Medical", | |
| "waxing": "Beauty Treatment", | |
| "yoga": "Gym & Swimming", | |
| "yuens market": "Asian Grocery", | |
| # Resolved conflicts from transaction analysis and domain context | |
| "adventure base": "Leisure & Recreation", | |
| "butcher": "Butcher & Specialty", | |
| "car insurance": "Car & Home Insurance", | |
| "chargrill": "Fast Food", | |
| "coffee": "Cafe & Coffee", | |
| "contents insurance": "Car & Home Insurance", | |
| "ezi*quickcliq": "Public Education", | |
| "family maintenance": "Childcare", | |
| "fitness": "Gym & Swimming", | |
| "gym": "Gym & Swimming", | |
| "haircut": "Hair Salon", | |
| "hairdresser": "Hair Salon", | |
| "merivale": "Dine Out" | |
| } | |
| # Highly generic keywords to discard entirely from database rules (they cause false matches) | |
| KEYWORDS_TO_DISCARD = {"garden", "metro"} | |
| def clean_and_promote(commit: bool = False): | |
| db = SessionLocal() | |
| # Turn off autoflush globally for this session to prevent N+1 SELECT/UPDATE triggers | |
| db.autoflush = False | |
| try: | |
| print(f"=== DB RULE CLEANUP & PROMOTION (commit={commit}) ===") | |
| # Load all categories | |
| categories = db.query(ClassificationCategory).filter(ClassificationCategory.is_active == True).all() | |
| cat_id_by_name = {c.name.lower().strip(): c.id for c in categories} | |
| cat_name_by_id = {c.id: c.name for c in categories} | |
| # Load all active rules | |
| rules = db.query(ClassificationRule).filter(ClassificationRule.is_active == True).all() | |
| print(f"Initial active rules: {len(rules)}") | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Step 1: Resolve Keyword Conflicts | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("\n--- Step 1: Resolving Keyword Conflicts ---") | |
| # A. Discard highly generic location/suburb words from all active rules | |
| discarded_kws_count = 0 | |
| for r in rules: | |
| orig_len = len(r.keywords) | |
| new_kws = [k for k in r.keywords if k.strip().lower() not in KEYWORDS_TO_DISCARD] | |
| if len(new_kws) < orig_len: | |
| removed = [k for k in r.keywords if k.strip().lower() in KEYWORDS_TO_DISCARD] | |
| print(f" [DISCARD] Removed too generic keywords {removed} from rule '{r.name}'") | |
| r.keywords = new_kws | |
| discarded_kws_count += len(removed) | |
| if discarded_kws_count > 0: | |
| print(f"Discarded {discarded_kws_count} instances of generic keywords.") | |
| # Build keyword map | |
| kw_to_categories = {} # kw -> set of category_ids | |
| kw_to_rules = {} # kw -> list of rules | |
| for r in rules: | |
| for kw in r.keywords: | |
| kw_clean = kw.strip().lower() | |
| if not kw_clean: | |
| continue | |
| if kw_clean not in kw_to_categories: | |
| kw_to_categories[kw_clean] = set() | |
| kw_to_rules[kw_clean] = [] | |
| kw_to_categories[kw_clean].add(r.category_id) | |
| kw_to_rules[kw_clean].append(r) | |
| conflicts = {kw: cat_ids for kw, cat_ids in kw_to_categories.items() if len(cat_ids) > 1} | |
| print(f"Found {len(conflicts)} conflicting keywords mapping to multiple categories.") | |
| resolved_count = 0 | |
| for kw, cat_ids in sorted(conflicts.items()): | |
| # A. Check classification_flat first | |
| flat_cat_name = None | |
| res = db.execute( | |
| text("SELECT category, sub_category FROM classification_flat WHERE LOWER(keyword) = :kw AND is_active = true"), | |
| {"kw": kw} | |
| ).fetchone() | |
| if res: | |
| flat_cat_name = res[1] if res[1] else res[0] | |
| # B. Check domain resolutions | |
| correct_cat_name = flat_cat_name or DOMAIN_RESOLUTIONS.get(kw) | |
| if not correct_cat_name: | |
| # If still no mapping, default to first category in set or raise warning | |
| cats_str = ", ".join(cat_name_by_id[cid] for cid in cat_ids) | |
| print(f" [WARN] No predefined resolution for conflict: '{kw}' in [{cats_str}]. Skipping.") | |
| continue | |
| correct_cat_id = cat_id_by_name.get(correct_cat_name.lower().strip()) | |
| if not correct_cat_id: | |
| print(f" [WARN] Target category '{correct_cat_name}' for '{kw}' not found in active categories. Skipping.") | |
| continue | |
| # Apply resolution: remove from rules of incorrect categories | |
| removed_from = [] | |
| for r in kw_to_rules[kw]: | |
| if r.category_id != correct_cat_id: | |
| # Remove from this rule's keywords | |
| r.keywords = [k for k in r.keywords if k.strip().lower() != kw] | |
| removed_from.append(r.name) | |
| if removed_from: | |
| resolved_count += 1 | |
| correct_name = cat_name_by_id[correct_cat_id] | |
| print(f" [RESOLVE] '{kw}' -> Kept in '{correct_name}'. Removed from: {removed_from}") | |
| print(f"Resolved {resolved_count} keyword conflicts.") | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Step 2: De-duplicate Keywords in the Same Category | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("\n--- Step 2: Consolidating Rules in Same Category ---") | |
| # Group active rules by category, priority, match_on, tx_type_filter, and amount range | |
| grouped_rules = {} # key -> list of rules | |
| # Refresh rules after conflict removal | |
| rules = db.query(ClassificationRule).filter(ClassificationRule.is_active == True).all() | |
| for r in rules: | |
| key = ( | |
| r.category_id, | |
| r.priority, | |
| r.match_on, | |
| r.tx_type_filter, | |
| r.amount_min, | |
| r.amount_max | |
| ) | |
| if key not in grouped_rules: | |
| grouped_rules[key] = [] | |
| grouped_rules[key].append(r) | |
| consolidated_count = 0 | |
| deleted_count = 0 | |
| for key, r_list in grouped_rules.items(): | |
| if len(r_list) <= 1: | |
| continue | |
| # Consolidate keywords | |
| all_kws = [] | |
| seen_kws = set() | |
| for r in r_list: | |
| for kw in r.keywords: | |
| kw_clean = kw.strip().lower() | |
| if kw_clean and kw_clean not in seen_kws: | |
| seen_kws.add(kw_clean) | |
| all_kws.append(kw) | |
| # Keep the oldest rule (seeded/migration rules or first created preferred) | |
| r_list.sort(key=lambda x: ( | |
| 0 if x.created_by == 'migration' else 1, | |
| x.created_at or x.id | |
| )) | |
| primary_rule = r_list[0] | |
| primary_rule.keywords = all_kws | |
| # Deactivate/delete secondary rules | |
| deactivated_ids = [] | |
| deactivated_rules = [] | |
| for r in r_list[1:]: | |
| deactivated_ids.append(r.id) | |
| deactivated_rules.append(r.name) | |
| deleted_count += 1 | |
| # Perform bulk update for deactivated rules in this group to avoid Neon PG latency | |
| if deactivated_ids: | |
| db.query(ClassificationRule).filter(ClassificationRule.id.in_(deactivated_ids)).update( | |
| {"is_active": False, "keywords_raw": ""}, | |
| synchronize_session=False | |
| ) | |
| consolidated_count += 1 | |
| cat_name = cat_name_by_id[key[0]] | |
| print(f" [CONSOLIDATE] Category '{cat_name}' (priority={key[1]}, match={key[2]}):") | |
| print(f" * Kept primary rule: '{primary_rule.name}' (ID: {primary_rule.id}) with {len(all_kws)} keywords.") | |
| print(f" * Deactivated duplicate rules: {deactivated_rules}") | |
| print(f"Consolidated {consolidated_count} categories/criteria groups. Deactivated {deleted_count} duplicate rules.") | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Step 3: Promote Pending Learned Rules | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print("\n--- Step 3: Promoting Learned Rule Logs ---") | |
| # Load all pending logs | |
| pending_logs = db.query(LearnedRuleLog).filter(LearnedRuleLog.status == 'pending').all() | |
| print(f"Found {len(pending_logs)} pending learned rule logs.") | |
| # Build active keywords set for checking duplicates (updated after Step 1 & 2) | |
| active_kws = set() | |
| rules = db.query(ClassificationRule).filter(ClassificationRule.is_active == True).all() | |
| for r in rules: | |
| for kw in r.keywords: | |
| active_kws.add(kw.strip().lower()) | |
| promoted_count = 0 | |
| rejected_count = 0 | |
| # Group promoted keywords by target category for consolidated insertion | |
| cat_to_new_kws = {} # category_id -> list of keywords | |
| log_to_approve = [] # list of (log_entry, keyword) | |
| for log in pending_logs: | |
| kw_clean = log.keyword.strip().lower() | |
| # Smart filtering: | |
| # 1. Must contain at least 3 letters | |
| # 2. Must not be in GENERIC_STOP_WORDS | |
| # 3. Must not be in active keywords already | |
| # 4. Must satisfy confidence/hit thresholds | |
| has_three_letters = len(re.sub(r'[^a-zA-Z]', '', kw_clean)) >= 3 | |
| is_stopword = kw_clean in GENERIC_STOP_WORDS | |
| is_duplicate = kw_clean in active_kws | |
| passes_hit_conf = ( | |
| (log.hit_count >= 2 and (log.confidence or 0) >= 0.90) or | |
| (log.hit_count >= 1 and (log.confidence or 0) >= 0.95) | |
| ) | |
| if passes_hit_conf and has_three_letters and not is_stopword and not is_duplicate: | |
| # Find category ID | |
| cat_id = log.category_id or cat_id_by_name.get((log.category or '').lower().strip()) | |
| if not cat_id: | |
| print(f" [REJECT] '{log.keyword}': Target category '{log.category}' not found in active categories.") | |
| log.status = 'rejected' | |
| rejected_count += 1 | |
| continue | |
| if cat_id not in cat_to_new_kws: | |
| cat_to_new_kws[cat_id] = [] | |
| cat_to_new_kws[cat_id].append(log.keyword) | |
| log_to_approve.append((log, log.keyword)) | |
| promoted_count += 1 | |
| else: | |
| reasons = [] | |
| if is_duplicate: reasons.append("already active") | |
| if is_stopword: reasons.append("generic stopword") | |
| if not has_three_letters: reasons.append("less than 3 letters") | |
| if not passes_hit_conf: reasons.append(f"low hits/conf (hits={log.hit_count}, conf={log.confidence})") | |
| # Update status locally (will be saved in bulk at the end) | |
| log.status = 'rejected' | |
| rejected_count += 1 | |
| # Silent log for generic / duplicate, verbose for other rejects | |
| if "already active" not in reasons and "generic stopword" not in reasons: | |
| print(f" [REJECT] '{log.keyword}' -> Suggested: '{log.category_name}' - Reasons: {', '.join(reasons)}") | |
| # Collect log promotions to perform in bulk at the end | |
| log_promotions = {} # log_id -> promoted_rule_id | |
| # Actually add the promoted keywords to the rules in the DB | |
| for cat_id, new_keywords in cat_to_new_kws.items(): | |
| cat_name = cat_name_by_id[cat_id] | |
| # Find the primary active rule for this category | |
| primary_rule = ( | |
| db.query(ClassificationRule) | |
| .filter(ClassificationRule.category_id == cat_id) | |
| .filter(ClassificationRule.is_active == True) | |
| .filter(ClassificationRule.match_on == 'description') | |
| .filter(ClassificationRule.tx_type_filter == None) | |
| .filter(ClassificationRule.amount_min == None) | |
| .filter(ClassificationRule.amount_max == None) | |
| .order_by(ClassificationRule.priority.desc()) | |
| .first() | |
| ) | |
| if primary_rule: | |
| # Add to existing rule | |
| merged_kws = list(primary_rule.keywords) | |
| for kw in new_keywords: | |
| if kw.lower().strip() not in [k.lower().strip() for k in merged_kws]: | |
| merged_kws.append(kw) | |
| primary_rule.keywords = merged_kws | |
| print(f" [PROMOTE] Added {len(new_keywords)} keywords to existing rule '{primary_rule.name}' (Category: {cat_name}).") | |
| # Link log entries in memory | |
| for log, kw in log_to_approve: | |
| log_cat_id = log.category_id or cat_id_by_name.get((log.category or '').lower().strip()) | |
| if log_cat_id == cat_id: | |
| log_promotions[log.id] = primary_rule.id | |
| else: | |
| # Create a new rule for this category | |
| rule_name = f"rule_{cat_name.lower().replace(' ', '_').replace('&', 'and').replace('/', '_')}" | |
| new_rule = ClassificationRule( | |
| name=rule_name, | |
| category_id=cat_id, | |
| priority=5, # learned rule priority | |
| match_on='description', | |
| is_active=True, | |
| created_by='rule_learning_migration', | |
| ) | |
| new_rule.keywords = new_keywords | |
| db.add(new_rule) | |
| db.flush() # get ID | |
| print(f" [PROMOTE] Created new rule '{rule_name}' (Category: {cat_name}) with {len(new_keywords)} keywords.") | |
| # Link log entries in memory | |
| for log, kw in log_to_approve: | |
| log_cat_id = log.category_id or cat_id_by_name.get((log.category or '').lower().strip()) | |
| if log_cat_id == cat_id: | |
| log_promotions[log.id] = new_rule.id | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Step 4: Perform Batch Log Status Updates | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nProcessing promotions: Promoted/Approved={promoted_count}, Rejected={rejected_count}") | |
| if log_promotions: | |
| # Group log IDs by rule ID | |
| rule_to_log_ids = {} | |
| for log_id, rule_id in log_promotions.items(): | |
| if rule_id not in rule_to_log_ids: | |
| rule_to_log_ids[rule_id] = [] | |
| rule_to_log_ids[rule_id].append(log_id) | |
| print(f"Batch updating {len(log_promotions)} approved log entries in database...") | |
| for rule_id, log_ids in rule_to_log_ids.items(): | |
| db.query(LearnedRuleLog).filter(LearnedRuleLog.id.in_(log_ids)).update( | |
| {"status": "approved", "promoted_rule_id": rule_id, "updated_by": "clean_and_promote_migration"}, | |
| synchronize_session=False | |
| ) | |
| # Batch update all other pending logs to rejected | |
| approved_log_ids = list(log_promotions.keys()) | |
| print(f"Batch updating rejected log entries in database...") | |
| db.query(LearnedRuleLog).filter( | |
| LearnedRuleLog.status == 'pending', | |
| ~LearnedRuleLog.id.in_(approved_log_ids) | |
| ).update( | |
| {"status": "rejected", "updated_by": "clean_and_promote_migration"}, | |
| synchronize_session=False | |
| ) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # Step 5: Commit or Rollback | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if commit: | |
| db.commit() | |
| print("\n[SUCCESS] All database modifications committed permanently.") | |
| # Hot-reload pipeline cache | |
| try: | |
| from bank_classifier.rules.rule_schema import _load_category_map_from_db | |
| if hasattr(_load_category_map_from_db, "cache_clear"): | |
| _load_category_map_from_db.cache_clear() | |
| print("Rule engine category cache invalidated successfully.") | |
| except Exception as e: | |
| print(f"Warning: Failed to clear cache: {e}") | |
| else: | |
| db.rollback() | |
| print("\n[DRY RUN] All database modifications rolled back safely.") | |
| except Exception as e: | |
| db.rollback() | |
| print(f"\n[ERROR] Migration script failed: {e}") | |
| raise | |
| finally: | |
| db.close() | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="Clean rules and promote learned logs in database.") | |
| parser.add_argument("--commit", action="store_true", help="Commit changes to the database.") | |
| args = parser.parse_args() | |
| clean_and_promote(commit=args.commit) | |