1
1
import json
2
2
import string
3
3
4
+ class NoMatchingIntentError (Exception ):
5
+ pass
6
+
4
7
def Tokenize (input_string ):
5
8
input_string = input_string .strip ()
6
-
7
9
input_string = input_string .translate (str .maketrans ("" , "" , string .punctuation ))
8
-
9
10
words = input_string .split ()
10
-
11
11
return words
12
12
13
13
def train (intents_file_path ):
@@ -16,7 +16,7 @@ def train(intents_file_path):
16
16
17
17
def patterncompare (input_string , intents_file_path ):
18
18
MaxSimilarity = 0
19
- MostSimilarPattern = ""
19
+ MostSimilarPattern = None
20
20
21
21
patterns = []
22
22
Similarity = 0
@@ -25,25 +25,28 @@ def patterncompare(input_string, intents_file_path):
25
25
intents = json .load (json_data )
26
26
27
27
BagOfWords = Tokenize (input_string )
28
-
28
+
29
29
for intent_class in intents ['intents' ]:
30
+
30
31
patterns = intent_class .get ('patterns' )
31
32
for pattern in patterns :
32
33
WordList = Tokenize (pattern )
33
- for word in WordList :
34
- if word in BagOfWords :
35
- Similarity = Similarity + 1
36
- print (Similarity )
37
-
34
+ Similarity = len (set (BagOfWords ) & set (WordList )) / len (set (BagOfWords + WordList ))
35
+ SimilarityPercentage = Similarity * 100
36
+
38
37
if Similarity > MaxSimilarity :
38
+ print (f"Similarity: { SimilarityPercentage :.2f} %" )
39
39
MaxSimilarity = Similarity
40
40
MostSimilarPattern = intent_class
41
-
42
- return MostSimilarPattern
41
+
42
+ if MostSimilarPattern :
43
+ return MostSimilarPattern
44
+ else :
45
+ raise NoMatchingIntentError ("No matching intent class found." )
43
46
44
47
def responsecompare (input_string , intents_file_path , intent_class ):
45
48
MaxSimilarity = 0
46
- MostSimilarResponse = ""
49
+ MostSimilarResponse = None
47
50
48
51
responses = []
49
52
Similarity = 0
@@ -52,21 +55,26 @@ def responsecompare(input_string, intents_file_path, intent_class):
52
55
intents = json .load (json_data )
53
56
54
57
BagOfWords = Tokenize (input_string )
55
-
56
- responses = intent_class .get ('responses' )
58
+
59
+ if intent_class is not None :
60
+ responses = intent_class .get ('responses' )
61
+ else :
62
+ raise NoMatchingIntentError ("No matching intent class found." )
57
63
58
64
for response in responses :
59
65
WordList = Tokenize (response )
60
- for word in WordList :
61
- if word in BagOfWords :
62
- Similarity = Similarity + 1
63
- print (Similarity )
64
-
66
+ Similarity = len (set (BagOfWords ) & set (WordList )) / len (set (BagOfWords + WordList ))
67
+ SimilarityPercentage = Similarity * 100
68
+
65
69
if Similarity > MaxSimilarity :
70
+ print (f"Similarity: { SimilarityPercentage :.2f} %" )
66
71
MaxSimilarity = Similarity
67
72
MostSimilarResponse = response
68
73
69
- return MostSimilarResponse
70
-
74
+ if MostSimilarResponse :
71
75
76
+ return MostSimilarResponse
77
+
78
+ else :
72
79
80
+ raise NoMatchingIntentError ("No matching response found." )
0 commit comments