"""RapidFuzz menu matching — fast, no embeddings, no cold start. Handles voice-transcript noise: "hazy ipa beer" → Hazy IPA, "nacho chips" → Nachos, "butter chiken" → Butter Chicken. """ from __future__ import annotations from typing import Optional from rapidfuzz import fuzz MATCH_THRESHOLD = 70 # Words the LLM/customer commonly appends that aren't part of menu names. _NOISE_WORDS = {"beer", "pint", "glass", "bottle", "dish", "plate", "the", "a", "an", "one"} def _normalize(text: str) -> str: words = [w for w in text.lower().replace("-", " ").split() if w not in _NOISE_WORDS] return " ".join(words) or text.lower().strip() def find_dish(query: str, menu: list[dict]) -> tuple[Optional[dict], float]: """Return (best_match_item, confidence 0-100) or (None, score) below threshold.""" if not query or not query.strip() or not menu: return None, 0.0 normalized_query = _normalize(query) def score(name: str) -> float: # token_set handles word-subset matches ("lava cake" → Chocolate Lava # Cake); WRatio handles near-token noise ("nacho chips" → Nachos). return max( fuzz.token_set_ratio(normalized_query, name.lower()), fuzz.WRatio(normalized_query, name.lower()), ) best_item, best_score = max( ((item, score(item["name"])) for item in menu), key=lambda pair: pair[1] ) if best_score < MATCH_THRESHOLD: return None, float(best_score) return best_item, float(best_score)