"""Load the unmodified workbook once; preserve source notes and row numbers.""" import re import unicodedata from pathlib import Path from openpyxl import load_workbook from rapidfuzz import fuzz, process from aliases import ALIASES DATA_PATH = Path(__file__).resolve().parent / "Diagnosis, Ingredients, Dosage.xlsx" def clean(value): return "" if value is None else str(value).strip() def normalize(name): text = str(name).lower() text = "".join("" if unicodedata.category(c).startswith("S") else c for c in text) return " ".join(re.sub(r"[^\w\s]|_", " ", text).split()) def base_name(name): return normalize(re.sub(r"\([^)]*\)", "", name)) def parse_dose(value): match = re.match(r"^([\d,]+(?:\.\d+)?)\s*(?:mg\b)?\s*(.*)$", clean(value), re.I | re.S) if not match: return None, clean(value) return float(match[1].replace(",", "")), match[2].strip() def parse_fixed(value): text = clean(value) match = re.fullmatch(r"Multiple\s+(?:of|fo)\s+(\d+(?:\.\d+)?)\s*mg", text, re.I) if match and float(match[1]) > 0: return {"type": "multiple", "step_mg": float(match[1])} match = re.fullmatch(r"(\d+(?:\.\d+)?)\s*mg", text, re.I) if match and float(match[1]) > 0: return {"type": "exact", "dose_mg": float(match[1])} return {"type": "none"} class Formulary: def __init__(self, path=DATA_PATH): self.ingredients = [] self.diagnoses = [] self.error = None workbook = None try: workbook = load_workbook(path, data_only=True) sheet = workbook["Ingredient dosage"] # Skip the continuation of any merged ingredient, not the next ingredient. continuations = {r for block in sheet.merged_cells.ranges if block.min_col <= 2 <= block.max_col for r in range(block.min_row + 1, block.max_row + 1)} for row in range(4, sheet.max_row + 1): if row in continuations: continue name = clean(sheet.cell(row, 2).value) if not name: break purity = sheet.cell(row, 3).value minimum, min_note = parse_dose(sheet.cell(row, 4).value) maximum, max_note = parse_dose(sheet.cell(row, 5).value) self.ingredients.append({ "name": name, "normalized_name": normalize(name), "purity": f"{purity * 100:g}%" if isinstance(purity, (int, float)) else clean(purity), "min_mg": minimum, "max_mg": maximum, "min_note": min_note, "max_note": max_note, "fixed_rule": parse_fixed(sheet.cell(row, 6).value), "source_row": row, }) category = "" for row in workbook["Diagnosis & ingredients"].iter_rows(min_row=4, max_col=9, values_only=True): category = clean(row[1]) or category if clean(row[2]): self.diagnoses.append({"category": category, "diagnosis": clean(row[2]), "ingredients": [clean(v) for v in row[3:9] if clean(v)]}) if not self.ingredients or not self.diagnoses: raise ValueError("The required sheets contain no records") except Exception as exc: self.error = str(exc) self.ingredients = [] self.diagnoses = [] finally: if workbook is not None: workbook.close() def match(self, name): query = normalize(name) names = [r["normalized_name"] for r in self.ingredients] # An exact row name wins (e.g. "Vitamin K2" is its own row); other brands of the # same compound are listed so the reply can mention them, never silently swapped in. if query in names: row = self.ingredients[names.index(query)] others = [r["name"] for r in self.ingredients if r is not row and base_name(r["name"]) == base_name(row["name"])] return {"status": "ok", **row, "other_products": others} # A generic name with several branded rows and no exact row is ambiguous. generic = [r for r in self.ingredients if base_name(r["name"]) == query] if len(generic) > 1: return {"status": "ambiguous", "candidates": [r["name"] for r in generic]} alias = ALIASES.get(query) if alias and normalize(alias) in names: return {"status": "ok", **self.ingredients[names.index(normalize(alias))]} matches = process.extract(query, names, scorer=fuzz.token_set_ratio, limit=None, score_cutoff=60) if not matches or matches[0][1] < 85: return {"status": "not_found", "query": name, "suggestions": [self.ingredients[i]["name"] for _, _, i in matches[:3]]} candidates = [self.ingredients[i] for _, score, i in matches if score >= 85 and matches[0][1] - score <= 5] if len(candidates) > 1: return {"status": "ambiguous", "candidates": [r["name"] for r in candidates]} return {"status": "ok", **candidates[0]} def match_diagnosis(self, diagnosis): query = normalize(diagnosis) scores = [] for row in self.diagnoses: parts = [row["diagnosis"], *row["diagnosis"].split("/")] score = max(fuzz.token_set_ratio(query, normalize(part)) for part in parts) scores.append((score, row)) scores.sort(key=lambda item: item[0], reverse=True) if not scores or scores[0][0] < 85: return {"status": "not_found", "suggestions": [r["diagnosis"] for s, r in scores[:3] if s >= 60]} candidates = [r for s, r in scores if s >= 85 and scores[0][0] - s <= 5] if len(candidates) > 1: return {"status": "ambiguous", "candidates": [r["diagnosis"] for r in candidates]} return {"status": "ok", **candidates[0]} DATA = Formulary()