Files
aiinvoice_pharmacyDashboard/item_code_matcher.py
T

437 lines
16 KiB
Python

"""
item_code_matcher.py
---------------------
Looks up an item_code for a drug from a CSV drug list, when the invoice
itself doesn't have one. Self-contained: only needs pandas, which the
project already uses.
Usage:
import item_code_matcher as icm
icm.load_drug_database('drug_list.csv') # call once at startup
code = icm.extract_item_code_from_drug_list('TELMA BETA 30') # -> 'TB-030' or None
CSV format (same as before): columns `item_code`, `name`.
Design notes (why matches are refused rather than guessed):
- Two products that differ only in strength (TELMA BETA 20 / 30 / 40)
can look >90% similar as plain text but are different item codes.
A match is only allowed when every number (strength / pack size) in
the CSV name also appears in the invoice line.
- Dosage form (tablet vs syrup vs injection) is compared separately so
"EPTUS TAB 50MG" never matches an "EPTUS SYRUP 50MG" row, but a form
that's simply missing on one side (most invoices don't print "TAB")
is not held against the match.
- If two different item codes score equally well, the result is None
(left blank for manual entry) rather than picking one arbitrarily.
"""
import os
import re
import logging
import threading
from difflib import SequenceMatcher
logger = logging.getLogger(__name__)
DRUG_DATABASE = None # dict: lowercase raw name -> {'item_code','name','parsed'}
CATALOG_CODES_SET = set() # set of uppercase item codes present in catalog
# ---- Tunables ---------------------------------------------------------
FUZZY_THRESHOLD = 0.85 # minimum spelling similarity for a fuzzy match (0-1)
AMBIGUITY_MARGIN = 0.01 # two different codes scoring this close = don't guess
_NUMBER_RE = re.compile(r'\d+(?:\.\d+)?')
_FORM_WORDS = {
'tab': 'tablet', 'tabs': 'tablet', 'tablet': 'tablet', 'tablets': 'tablet',
'cap': 'capsule', 'caps': 'capsule', 'capsule': 'capsule', 'capsules': 'capsule',
'syp': 'syrup', 'syr': 'syrup', 'syrup': 'syrup',
'inj': 'injection', 'injection': 'injection',
'susp': 'suspension', 'suspension': 'suspension',
'drop': 'drops', 'drops': 'drops',
'cream': 'cream', 'gel': 'gel', 'lotion': 'lotion', 'powder': 'powder',
'oint': 'ointment', 'ointment': 'ointment', 'sachet': 'sachet',
}
def safe_strip(value):
if value is None:
return ''
return str(value).strip()
def similarity_ratio(a, b):
return SequenceMatcher(None, a, b).ratio()
def normalize_drug_name(text):
"""Lower-case and clean a drug name: drop units glued to numbers
(50 MG -> 50), pack marks (10's -> 10), punctuation -> single spaces.
Decimals like 12.5 are kept."""
text = str(text).strip().lower()
text = re.sub(r'(?<=\d)\s*(?:mg|mcg|gm|g|ml|iu)\b', '', text)
text = re.sub(r"(?<=\d)\s*'?s\b", '', text)
text = re.sub(r'[^a-z0-9.]+', ' ', text)
text = re.sub(r'(?<!\d)\.|\.(?!\d)', ' ', text) # dots that aren't decimal points
return re.sub(r'\s+', ' ', text).strip()
def parse_drug_name(text):
"""Split into name / numbers (strength, pack size) / dosage form.
'EPTUS - 50 MG' -> name 'eptus', numbers {'50'}, forms set()
'EPTUS TAB 50MG' -> name 'eptus', numbers {'50'}, forms {'tablet'}"""
normalized = normalize_drug_name(text)
numbers = set(_NUMBER_RE.findall(normalized))
words = _NUMBER_RE.sub(' ', normalized).split()
forms = {_FORM_WORDS[w] for w in words if w in _FORM_WORDS}
name_words = [w for w in words if w not in _FORM_WORDS]
return {'name': ' '.join(name_words), 'numbers': numbers, 'forms': forms}
def load_drug_database(csv_path=None):
if csv_path is None:
csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'drug_list.csv')
"""Load the CSV into memory. Safe to call again to reload (e.g. after
the CSV is updated) — just re-run it, no restart needed."""
global DRUG_DATABASE, CATALOG_CODES_SET
import pandas as pd
if not os.path.exists(csv_path):
logger.warning(f"⚠️ Drug list CSV not found: {csv_path}")
DRUG_DATABASE = {}
return DRUG_DATABASE
try:
df = pd.read_csv(csv_path)
if 'item_code' not in df.columns or 'name' not in df.columns:
logger.warning(f"⚠️ {csv_path} must have 'item_code' and 'name' columns")
DRUG_DATABASE = {}
return DRUG_DATABASE
db = {}
for _, row in df.iterrows():
name = row['name']
if pd.isna(name):
continue
key = str(name).strip().lower()
db[key] = {
'item_code': str(row['item_code']).strip().upper(),
'name': name,
'parsed': parse_drug_name(name),
}
DRUG_DATABASE = db
CATALOG_CODES_SET = {v['item_code'] for v in db.values()}
logger.info(f"✅ Loaded {len(db)} drugs from {csv_path}")
except Exception as e:
logger.error(f"❌ Failed to load {csv_path}: {e}")
DRUG_DATABASE = {}
return DRUG_DATABASE
def extract_item_code_from_drug_list(drug_description):
"""Return the item_code for a drug, or None if there's no confident match."""
if DRUG_DATABASE is None:
load_drug_database()
if not drug_description or not DRUG_DATABASE:
return None
drug_desc = safe_strip(drug_description).lower()
if not drug_desc:
return None
# 1. Exact match on the raw name
if drug_desc in DRUG_DATABASE:
return DRUG_DATABASE[drug_desc]['item_code']
invoice = parse_drug_name(drug_desc)
if not invoice['name']:
return None
invoice_word_count = len(invoice['name'].split())
# 2. Collect candidates that pass the dosage-form and strength guards
scored = []
for data in DRUG_DATABASE.values():
cand = data['parsed']
if invoice['forms'] and cand['forms'] and invoice['forms'] != cand['forms']:
continue # contradicting dosage form (tablet vs syrup)
if not cand['numbers'].issubset(invoice['numbers']):
continue # a strength/pack number on the CSV side isn't on the invoice
if cand['name'] == invoice['name']:
score = 1.0
elif len(cand['name'].split()) == invoice_word_count:
score = similarity_ratio(invoice['name'], cand['name'])
if score < FUZZY_THRESHOLD:
continue
else:
continue
scored.append((score, len(cand['numbers']), data))
if not scored:
return None
# 3. Best score wins; ties broken by whichever matched more numbers;
# a remaining tie between different codes is left unresolved (None)
scored.sort(key=lambda entry: (entry[0], entry[1]), reverse=True)
best_score, best_specificity, best = scored[0]
if len(scored) > 1:
runner_score, runner_specificity, runner = scored[1]
is_tie = (best_score - runner_score <= AMBIGUITY_MARGIN
and best_specificity == runner_specificity)
if is_tie and runner['item_code'] != best['item_code']:
logger.info(f"⚠️ Ambiguous match for '{drug_description}': "
f"'{best['name']}' vs '{runner['name']}' - leaving blank")
return None
return best['item_code']
def enrich_items_with_item_code(extracted_data, use_drug_list=True):
"""Fill item_code on every item in extracted_data['items'] that doesn't
already have one, and mark where each code came from.
use_drug_list=False skips the CSV entirely: codes already on the
invoice are kept, and everything else is left blank for the user
to fill in by hand (the "manual item codes" flow).
Mutates and returns extracted_data. Never overwrites a code the
invoice/OCR already found.
"""
if not extracted_data or not isinstance(extracted_data.get('items'), list):
return extracted_data
for item in extracted_data['items']:
if not isinstance(item, dict):
continue
existing = safe_strip(item.get('item_code'))
if existing:
if not item.get('item_code_source') or item.get('item_code_source') == 'not_found':
item['item_code_source'] = 'invoice'
item['in_csv'] = code_in_catalog(existing)
continue
if not use_drug_list:
item['item_code_source'] = 'not_found'
item['in_csv'] = False
continue
matched = extract_item_code_from_drug_list(item.get('description'))
if matched:
item['item_code'] = matched
item['item_code_source'] = 'drug_list_match'
item['in_csv'] = True
else:
item['item_code_source'] = 'not_found'
item['in_csv'] = False
return extracted_data
def code_in_catalog(code):
"""Check if code exists in the catalog."""
global CATALOG_CODES_SET
if not code:
return False
if not CATALOG_CODES_SET:
load_drug_database()
return str(code).strip().upper() in CATALOG_CODES_SET
_catalog_lock = threading.Lock()
def append_to_drug_catalog(item_code, name, csv_path=None):
"""Safely append a verified item code to drug_list.csv and hot-reload."""
global DRUG_DATABASE, CATALOG_CODES_SET
import csv
if csv_path is None:
csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'drug_list.csv')
code_clean = str(item_code).strip().upper()
name_clean = str(name).strip()
if not code_clean:
return False
# Check if this exact description already matches this item code in catalog
if extract_item_code_from_drug_list(name_clean) == code_clean:
return True
with _catalog_lock:
try:
file_exists = os.path.exists(csv_path)
with open(csv_path, 'a', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
if not file_exists or os.path.getsize(csv_path) == 0:
writer.writerow(['item_code', 'name'])
writer.writerow([code_clean, name_clean])
load_drug_database(csv_path)
logger.info(f"✅ Appended item code to {csv_path}: {code_clean} - {name_clean}")
return True
except Exception as e:
logger.error(f"❌ Failed to append item code to {csv_path}: {e}")
return False
def update_drug_catalog_entry(old_item_code, old_name, new_item_code, new_name, csv_path=None):
"""Safely update an existing item code / drug name in drug_list.csv and hot-reload."""
global DRUG_DATABASE, CATALOG_CODES_SET
import csv
if csv_path is None:
csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'drug_list.csv')
old_code_clean = str(old_item_code or '').strip().upper()
old_name_clean = str(old_name or '').strip()
new_code_clean = str(new_item_code or '').strip().upper()
new_name_clean = str(new_name or '').strip()
if not old_code_clean:
return False, "Existing item code is required"
if not new_code_clean or not new_name_clean:
return False, "New item code and drug name cannot be empty"
if not os.path.exists(csv_path):
return False, f"File {csv_path} not found"
with _catalog_lock:
try:
rows = []
updated = False
with open(csv_path, 'r', newline='', encoding='utf-8-sig', errors='replace') as f:
reader = csv.reader(f)
header = next(reader, None)
if not header:
return False, "CSV file is empty"
rows.append(header)
header_lower = [h.strip().lower() for h in header]
code_idx = header_lower.index('item_code') if 'item_code' in header_lower else 0
name_idx = header_lower.index('name') if 'name' in header_lower else 1
for row in reader:
if len(row) <= max(code_idx, name_idx):
rows.append(row)
continue
r_code = row[code_idx].strip().upper()
r_name = row[name_idx].strip()
if r_code == old_code_clean and (not old_name_clean or r_name.lower() == old_name_clean.lower()):
row[code_idx] = new_code_clean
row[name_idx] = new_name_clean
updated = True
rows.append(row)
if not updated:
return False, f"Catalog item '{old_code_clean}' not found"
with open(csv_path, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(rows)
load_drug_database(csv_path)
logger.info(f"✅ Updated catalog entry in {csv_path}: {old_code_clean} -> {new_code_clean} ({new_name_clean})")
return True, None
except Exception as e:
logger.error(f"❌ Failed to update catalog entry in {csv_path}: {e}")
return False, str(e)
def delete_drug_catalog_entry(item_code, name=None, csv_path=None):
"""Safely delete an item code entry from drug_list.csv and hot-reload."""
global DRUG_DATABASE, CATALOG_CODES_SET
import csv
if csv_path is None:
csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'drug_list.csv')
code_clean = str(item_code or '').strip().upper()
name_clean = str(name or '').strip()
if not code_clean:
return False, "Item code is required"
if not os.path.exists(csv_path):
return False, f"File {csv_path} not found"
with _catalog_lock:
try:
rows = []
deleted = False
with open(csv_path, 'r', newline='', encoding='utf-8-sig', errors='replace') as f:
reader = csv.reader(f)
header = next(reader, None)
if not header:
return False, "CSV file is empty"
rows.append(header)
header_lower = [h.strip().lower() for h in header]
code_idx = header_lower.index('item_code') if 'item_code' in header_lower else 0
name_idx = header_lower.index('name') if 'name' in header_lower else 1
for row in reader:
if len(row) <= max(code_idx, name_idx):
rows.append(row)
continue
r_code = row[code_idx].strip().upper()
r_name = row[name_idx].strip()
if r_code == code_clean and (not name_clean or r_name.lower() == name_clean.lower()):
deleted = True
continue
rows.append(row)
if not deleted:
return False, f"Catalog item '{code_clean}' not found"
with open(csv_path, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(rows)
load_drug_database(csv_path)
logger.info(f"✅ Deleted catalog entry from {csv_path}: {code_clean} ({name_clean})")
return True, None
except Exception as e:
logger.error(f"❌ Failed to delete catalog entry from {csv_path}: {e}")
return False, str(e)
def search_drug_catalog(query, limit=50):
"""Search drug catalog by code or description with prefix-first ranking."""
global DRUG_DATABASE, CATALOG_CODES_SET
if DRUG_DATABASE is None:
load_drug_database()
if not DRUG_DATABASE:
return []
q = str(query or '').strip().lower()
if not q:
return [
{'item_code': item['item_code'], 'name': item['name'], 'category': 'General'}
for item in list(DRUG_DATABASE.values())[:limit]
]
matches = []
for item in DRUG_DATABASE.values():
code_str = str(item.get('item_code', '')).lower()
name_str = str(item.get('name', '')).lower()
if q in code_str or q in name_str:
is_prefix = code_str.startswith(q) or name_str.startswith(q)
matches.append((0 if is_prefix else 1, item))
matches.sort(key=lambda x: (x[0], x[1]['name']))
return [
{'item_code': m[1]['item_code'], 'name': m[1]['name'], 'category': 'General'}
for m in matches[:limit]
]
# Preload drug catalog on import
try:
load_drug_database()
except Exception:
pass