Files
aiinvoice/item_code_matcher.py
2026-10-07 17:31:08 +05:30

220 lines
8.0 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
from difflib import SequenceMatcher
logger = logging.getLogger(__name__)
DRUG_DATABASE = None # dict: lowercase raw name -> {'item_code','name','parsed'}
# ---- 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='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
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
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 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:
item['item_code_source'] = 'invoice'
continue
if not use_drug_list:
item['item_code_source'] = 'not_found'
continue
matched = extract_item_code_from_drug_list(item.get('description'))
if matched:
item['item_code'] = matched
item['item_code_source'] = 'drug_list_match'
else:
item['item_code_source'] = 'not_found'
return extracted_data