-
Notifications
You must be signed in to change notification settings - Fork 5
/
slot_match.py
80 lines (62 loc) · 2.25 KB
/
slot_match.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from typing import List, Optional, Dict
from rapidfuzz import fuzz
ACCEPTED_RATIO = 80
class FuzzySlotMatch:
slot: str
options: List["FuzzySlotMatchOption"]
def __init__(self, slot: str, options: List["FuzzySlotMatchOption"]):
self.slot = slot
self.options = options
class FuzzySlotMatchOption:
value: str
synonyms: List[str]
sub_options: Optional[FuzzySlotMatch]
def __init__(
self,
value: str,
synonyms: Optional[List[str]] = None,
sub_options: Optional[FuzzySlotMatch] = None,
):
self.value = value
self.synonyms = (
[s.lower() for s in synonyms]
if synonyms is not None
else [self.value.lower()]
)
self.sub_options = sub_options
def _sanitize_input(user_message: str) -> str:
return user_message.lower()
def resolve_slot_match(
user_message: str, slot_match: FuzzySlotMatch, accepted_rate=ACCEPTED_RATIO
) -> Dict[str, any]:
user_message = _sanitize_input(user_message)
for options in slot_match.options:
for value in options.synonyms:
ratio = fuzz.QRatio(user_message, value)
if ratio >= accepted_rate:
return {slot_match.slot: options.value}
if options.sub_options is not None:
resolved_child = resolve_slot_match(
user_message, options.sub_options, accepted_rate=accepted_rate
)
if len(resolved_child) > 0:
resolved_child[slot_match.slot] = options.value
return resolved_child
return {}
def suggest_using_slot_match(
user_message: str, slot_match: FuzzySlotMatch, accepted_rate=ACCEPTED_RATIO
) -> List[str]:
user_message = _sanitize_input(user_message)
suggestions = {} # avoiding duplicates
for option in slot_match.options:
for synonym in option.synonyms:
ratio = fuzz.QRatio(user_message, synonym)
if ratio >= accepted_rate:
suggestions[option.value] = {
"value": option.value,
"ratio": ratio,
}
break
suggestions = list(suggestions.values())
suggestions.sort(key=lambda x: x["ratio"], reverse=True)
return suggestions