Spaces:
Sleeping
Sleeping
File size: 1,522 Bytes
a812c01 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | """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)
|