nebulento 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.1
2
+ Name: nebulento
3
+ Version: 0.0.1
4
+ Summary: dead simple fuzzy matching intent parser
5
+ Home-page: https://github.com/OpenJarbas/nebulento
6
+ Author: jarbasai
7
+ Author-email: jarbasai@mailfence.com
8
+ License: apache-2.0
9
+ Description: # Nebulento
10
+
11
+ *A lightweight, dead simple fuzzy matching intent parser*
12
+
13
+ Built on top of [rapidfuzz](https://github.com/maxbachmann/rapidfuzz)
14
+
15
+ Finds the closest matching intent via fuzzy match between the text and all of the training sentences you provided. Works best when you have a small number of sentences (dozens to hundreds) and need some resiliency to spelling errors (i.e., from text chat).
16
+
17
+ ## Usage
18
+
19
+ ```python
20
+ from nebulento import IntentContainer, MatchStrategy
21
+
22
+ container = IntentContainer(fuzzy_strategy=MatchStrategy.TOKEN_SET_RATIO)
23
+
24
+ container.add_intent('hello', [
25
+ 'hello', 'hi', 'how are you', "what's up"
26
+ ])
27
+ container.add_intent('buy', [
28
+ 'buy {item}', 'purchase {item}', 'get {item}', 'get {item} for me'
29
+ ])
30
+ container.add_entity('item', [
31
+ 'milk', 'cheese'
32
+ ])
33
+
34
+ container.calc_intent('hello')
35
+ # {'best_match': 'hello',
36
+ # 'conf': 1.0,
37
+ # 'entities': {},
38
+ # 'match_strategy': 'TOKEN_SET_RATIO',
39
+ # 'name': 'hello',
40
+ # 'utterance': 'hello',
41
+ # 'utterance_consumed': 'hello',
42
+ # 'utterance_remainder': ''}
43
+
44
+ container.calc_intent('buy milk')
45
+ # {'best_match': 'buy {item}',
46
+ # 'conf': 0.71875,
47
+ # 'entities': {'item': ['milk']},
48
+ # 'match_strategy': 'TOKEN_SET_RATIO',
49
+ # 'name': 'buy',
50
+ # 'utterance': 'buy milk',
51
+ # 'utterance_consumed': 'buy milk',
52
+ # 'utterance_remainder': ''}
53
+
54
+
55
+ container.add_intent('look_at_thing', ['I see {thing} (in|on) {place}'])
56
+ container.add_entity("place", ["floor", "table"])
57
+
58
+ container.calc_intent('I see trash in the floor')
59
+ #{'best_match': 'i see {thing} in {place}',
60
+ # 'conf': 0.65625,
61
+ # 'entities': {'place': ['floor']},
62
+ # 'match_strategy': 'TOKEN_SET_RATIO',
63
+ # 'name': 'look_at_thing',
64
+ # 'utterance': 'i see trash in the floor',
65
+ # 'utterance_consumed': 'i see in floor',
66
+ # 'utterance_remainder': 'trash the'}
67
+
68
+ container.add_entity("thing", ["food"])
69
+ container.calc_intent('I see food in the table')
70
+ #{'best_match': 'i see {thing} in {place}',
71
+ # 'conf': 0.7007978723404256,
72
+ # 'entities': {'place': ['table'], 'thing': ['food']},
73
+ # 'match_strategy': 'TOKEN_SET_RATIO',
74
+ # 'name': 'look_at_thing',
75
+ # 'utterance': 'i see food in the table',
76
+ # 'utterance_consumed': 'i see in table food',
77
+ # 'utterance_remainder': 'the'}
78
+
79
+ ```
80
+
81
+ ## Match Strategies
82
+
83
+ - **Ratio**: Use `MatchStrategy.RATIO` when you need to compare strings and determine their overall similarity. It is effective for handling cases where strings have minor differences due to typos or spelling variations.
84
+ - **Partial Ratio**: `MatchStrategy.PARTIAL_RATIO` is useful when you want to focus on the best matching substring between two strings. It handles cases where one string is a subset or prefix of the other, providing a more targeted similarity measure.
85
+ - **Token Set Ratio**: `MatchStrategy.TOKEN_SET_RATIO` is ideal when you want to compare strings without considering their word order. It captures the essence of the strings’ content, making it suitable for scenarios where word arrangement might vary but the overall content remains similar.
86
+ - **Token Sort Ratio**: Use `MatchStrategy.TOKEN_SORT_RATIO` when you want to compare strings and consider word order variations. It is particularly effective when the words are expected to be similar, but their arrangement may differ.
87
+
88
+ Platform: UNKNOWN
89
+ Description-Content-Type: text/markdown
@@ -0,0 +1,78 @@
1
+ # Nebulento
2
+
3
+ *A lightweight, dead simple fuzzy matching intent parser*
4
+
5
+ Built on top of [rapidfuzz](https://github.com/maxbachmann/rapidfuzz)
6
+
7
+ Finds the closest matching intent via fuzzy match between the text and all of the training sentences you provided. Works best when you have a small number of sentences (dozens to hundreds) and need some resiliency to spelling errors (i.e., from text chat).
8
+
9
+ ## Usage
10
+
11
+ ```python
12
+ from nebulento import IntentContainer, MatchStrategy
13
+
14
+ container = IntentContainer(fuzzy_strategy=MatchStrategy.TOKEN_SET_RATIO)
15
+
16
+ container.add_intent('hello', [
17
+ 'hello', 'hi', 'how are you', "what's up"
18
+ ])
19
+ container.add_intent('buy', [
20
+ 'buy {item}', 'purchase {item}', 'get {item}', 'get {item} for me'
21
+ ])
22
+ container.add_entity('item', [
23
+ 'milk', 'cheese'
24
+ ])
25
+
26
+ container.calc_intent('hello')
27
+ # {'best_match': 'hello',
28
+ # 'conf': 1.0,
29
+ # 'entities': {},
30
+ # 'match_strategy': 'TOKEN_SET_RATIO',
31
+ # 'name': 'hello',
32
+ # 'utterance': 'hello',
33
+ # 'utterance_consumed': 'hello',
34
+ # 'utterance_remainder': ''}
35
+
36
+ container.calc_intent('buy milk')
37
+ # {'best_match': 'buy {item}',
38
+ # 'conf': 0.71875,
39
+ # 'entities': {'item': ['milk']},
40
+ # 'match_strategy': 'TOKEN_SET_RATIO',
41
+ # 'name': 'buy',
42
+ # 'utterance': 'buy milk',
43
+ # 'utterance_consumed': 'buy milk',
44
+ # 'utterance_remainder': ''}
45
+
46
+
47
+ container.add_intent('look_at_thing', ['I see {thing} (in|on) {place}'])
48
+ container.add_entity("place", ["floor", "table"])
49
+
50
+ container.calc_intent('I see trash in the floor')
51
+ #{'best_match': 'i see {thing} in {place}',
52
+ # 'conf': 0.65625,
53
+ # 'entities': {'place': ['floor']},
54
+ # 'match_strategy': 'TOKEN_SET_RATIO',
55
+ # 'name': 'look_at_thing',
56
+ # 'utterance': 'i see trash in the floor',
57
+ # 'utterance_consumed': 'i see in floor',
58
+ # 'utterance_remainder': 'trash the'}
59
+
60
+ container.add_entity("thing", ["food"])
61
+ container.calc_intent('I see food in the table')
62
+ #{'best_match': 'i see {thing} in {place}',
63
+ # 'conf': 0.7007978723404256,
64
+ # 'entities': {'place': ['table'], 'thing': ['food']},
65
+ # 'match_strategy': 'TOKEN_SET_RATIO',
66
+ # 'name': 'look_at_thing',
67
+ # 'utterance': 'i see food in the table',
68
+ # 'utterance_consumed': 'i see in table food',
69
+ # 'utterance_remainder': 'the'}
70
+
71
+ ```
72
+
73
+ ## Match Strategies
74
+
75
+ - **Ratio**: Use `MatchStrategy.RATIO` when you need to compare strings and determine their overall similarity. It is effective for handling cases where strings have minor differences due to typos or spelling variations.
76
+ - **Partial Ratio**: `MatchStrategy.PARTIAL_RATIO` is useful when you want to focus on the best matching substring between two strings. It handles cases where one string is a subset or prefix of the other, providing a more targeted similarity measure.
77
+ - **Token Set Ratio**: `MatchStrategy.TOKEN_SET_RATIO` is ideal when you want to compare strings without considering their word order. It captures the essence of the strings’ content, making it suitable for scenarios where word arrangement might vary but the overall content remains similar.
78
+ - **Token Sort Ratio**: Use `MatchStrategy.TOKEN_SORT_RATIO` when you want to compare strings and consider word order variations. It is particularly effective when the words are expected to be similar, but their arrangement may differ.
@@ -0,0 +1,97 @@
1
+ import logging
2
+ from nebulento.fuzz import MatchStrategy, match_one
3
+ from nebulento.bracket_expansion import expand_template, expand_slots
4
+ import quebra_frases
5
+
6
+ LOG = logging.getLogger('nebulento')
7
+
8
+
9
+ class IntentContainer:
10
+ def __init__(self, fuzzy_strategy=MatchStrategy.DAMERAU_LEVENSHTEIN_SIMILARITY,
11
+ ignore_case=True):
12
+ self.fuzzy_strategy = fuzzy_strategy
13
+ self.ignore_case = ignore_case
14
+ self.registered_intents = {}
15
+ self.registered_entities = {}
16
+
17
+ def match_entities(self, sentence):
18
+ if self.ignore_case:
19
+ sentence = sentence.lower()
20
+ matches = {}
21
+ for entity, samples in self.registered_entities.items():
22
+ chunked = quebra_frases.chunk(sentence, samples)
23
+ matches[entity] = [s for s in samples if s in chunked]
24
+ return matches
25
+
26
+ def match_fuzzy(self, sentence):
27
+ if self.ignore_case:
28
+ sentence = sentence.lower()
29
+ entities = self.match_entities(sentence)
30
+ for intent, samples in self.registered_intents.items():
31
+ samples = self.registered_intents[intent]
32
+
33
+ sent, score = match_one(sentence, samples,
34
+ strategy=self.fuzzy_strategy)
35
+ remainder = [
36
+ w for w in quebra_frases.word_tokenize(sentence)
37
+ if w not in quebra_frases.word_tokenize(sent)]
38
+ consumed = [
39
+ w for w in quebra_frases.word_tokenize(sentence)
40
+ if w in quebra_frases.word_tokenize(sent)]
41
+
42
+ tagged_entities = {}
43
+ for ent, v in entities.items():
44
+ if v and any("{" + ent + "}" in s for s in samples):
45
+ score = 0.25 + score * 0.75
46
+ tagged_entities[ent] = v
47
+ consumed += [_ for _ in v if _ not in consumed]
48
+ remainder = [_ for _ in remainder if _ not in v]
49
+ remainder = " ".join(remainder)
50
+ consumed = " ".join(consumed)
51
+ yield {"best_match": sent,
52
+ "conf": min(score, 1),
53
+ "entities": tagged_entities,
54
+ "match_strategy": self.fuzzy_strategy.name,
55
+ "utterance": sentence,
56
+ "utterance_remainder": remainder,
57
+ "utterance_consumed": consumed,
58
+ "name": intent}
59
+
60
+ def add_intent(self, name, lines):
61
+ expanded = []
62
+ for l in lines:
63
+ expanded += expand_template(l)
64
+ if self.ignore_case:
65
+ expanded = [l.lower() for l in expanded]
66
+ self.registered_intents[name] = expanded
67
+
68
+ def remove_intent(self, name):
69
+ if name in self.registered_intents:
70
+ del self.registered_intents[name]
71
+
72
+ def add_entity(self, name, lines):
73
+ expanded = []
74
+ for l in lines:
75
+ expanded += expand_template(l)
76
+ if self.ignore_case:
77
+ expanded = [l.lower() for l in expanded]
78
+ self.registered_entities[name] = expanded
79
+
80
+ def remove_entity(self, name):
81
+ if name in self.registered_entities:
82
+ del self.registered_entities[name]
83
+
84
+ def calc_intents(self, query):
85
+ for intent in self.match_fuzzy(query):
86
+ yield intent
87
+
88
+ def calc_intent(self, query):
89
+ return max(
90
+ self.calc_intents(query),
91
+ key=lambda x: x["conf"],
92
+ default={"best_match": None,
93
+ "conf": 0,
94
+ "match_strategy": self.fuzzy_strategy,
95
+ "utterance": query,
96
+ "name": None}
97
+ )
@@ -0,0 +1,72 @@
1
+ import itertools
2
+ import re
3
+ from typing import List, Dict
4
+
5
+
6
+ def expand_template(template: str) -> List[str]:
7
+ def expand_optional(text):
8
+ """Replace [optional] with two options: one with and one without."""
9
+ return re.sub(r"\[([^\[\]]+)\]", lambda m: f"({m.group(1)}|)", text)
10
+
11
+ def expand_alternatives(text):
12
+ """Expand (alternative|choices) into a list of choices."""
13
+ parts = []
14
+ for segment in re.split(r"(\([^\(\)]+\))", text):
15
+ if segment.startswith("(") and segment.endswith(")"):
16
+ options = segment[1:-1].split("|")
17
+ parts.append(options)
18
+ else:
19
+ parts.append([segment])
20
+ return itertools.product(*parts)
21
+
22
+ def fully_expand(texts):
23
+ """Iteratively expand alternatives until all possibilities are covered."""
24
+ result = set(texts)
25
+ while True:
26
+ expanded = set()
27
+ for text in result:
28
+ options = list(expand_alternatives(text))
29
+ expanded.update(["".join(option).strip() for option in options])
30
+ if expanded == result: # No new expansions found
31
+ break
32
+ result = expanded
33
+ return sorted(result) # Return a sorted list for consistency
34
+
35
+ # Expand optional items first
36
+ template = expand_optional(template)
37
+
38
+ # Fully expand all combinations of alternatives
39
+ return fully_expand([template])
40
+
41
+
42
+ def expand_slots(template: str, slots: Dict[str, List[str]]) -> List[str]:
43
+ """Expand a template by first expanding alternatives and optional components,
44
+ then substituting slot placeholders with their corresponding options.
45
+
46
+ Args:
47
+ template (str): The input string template to expand.
48
+ slots (dict): A dictionary where keys are slot names and values are lists of possible replacements.
49
+
50
+ Returns:
51
+ list[str]: A list of all expanded combinations.
52
+ """
53
+ # Expand alternatives and optional components
54
+ base_expansions = expand_template(template)
55
+
56
+ # Process slots
57
+ all_sentences = []
58
+ for sentence in base_expansions:
59
+ matches = re.findall(r"\{([^\{\}]+)\}", sentence)
60
+ if matches:
61
+ # Create all combinations for slots in the sentence
62
+ slot_options = [slots.get(match, [f"{{{match}}}"]) for match in matches]
63
+ for combination in itertools.product(*slot_options):
64
+ filled_sentence = sentence
65
+ for slot, replacement in zip(matches, combination):
66
+ filled_sentence = filled_sentence.replace(f"{{{slot}}}", replacement)
67
+ all_sentences.append(filled_sentence)
68
+ else:
69
+ # No slots to expand
70
+ all_sentences.append(sentence)
71
+
72
+ return all_sentences
@@ -0,0 +1,88 @@
1
+ import logging
2
+ from difflib import SequenceMatcher
3
+ from enum import IntEnum, auto
4
+
5
+ import rapidfuzz
6
+
7
+ LOG = logging.getLogger('nebulento')
8
+
9
+
10
+ class MatchStrategy(IntEnum):
11
+ SIMPLE_RATIO = auto()
12
+ RATIO = auto()
13
+ PARTIAL_RATIO = auto()
14
+ TOKEN_SORT_RATIO = auto()
15
+ TOKEN_SET_RATIO = auto()
16
+ PARTIAL_TOKEN_RATIO = auto()
17
+ PARTIAL_TOKEN_SORT_RATIO = auto()
18
+ PARTIAL_TOKEN_SET_RATIO = auto()
19
+ DAMERAU_LEVENSHTEIN_SIMILARITY = auto()
20
+
21
+
22
+ def fuzzy_match(x, against, strategy=MatchStrategy.SIMPLE_RATIO):
23
+ """Perform a 'fuzzy' comparison between two strings.
24
+ Returns:
25
+ float: match percentage -- 1.0 for perfect match,
26
+ down to 0.0 for no match at all.
27
+ """
28
+ if strategy == MatchStrategy.RATIO:
29
+ score = rapidfuzz.fuzz.ratio(x, against) / 100
30
+ elif strategy == MatchStrategy.PARTIAL_RATIO:
31
+ score = rapidfuzz.fuzz.partial_ratio(x, against) / 100
32
+ elif strategy == MatchStrategy.TOKEN_SORT_RATIO:
33
+ score = rapidfuzz.fuzz.token_sort_ratio(x, against) / 100
34
+ elif strategy == MatchStrategy.TOKEN_SET_RATIO:
35
+ score = rapidfuzz.fuzz.token_set_ratio(x, against) / 100
36
+ elif strategy == MatchStrategy.PARTIAL_TOKEN_SORT_RATIO:
37
+ score = rapidfuzz.fuzz.partial_token_sort_ratio(x, against) / 100
38
+ elif strategy == MatchStrategy.PARTIAL_TOKEN_SET_RATIO:
39
+ score = rapidfuzz.fuzz.partial_token_set_ratio(x, against) / 100
40
+ elif strategy == MatchStrategy.PARTIAL_TOKEN_RATIO:
41
+ score = rapidfuzz.fuzz.partial_token_ratio(x, against) / 100
42
+ elif strategy == MatchStrategy.DAMERAU_LEVENSHTEIN_SIMILARITY:
43
+ score = rapidfuzz.distance.DamerauLevenshtein.normalized_similarity(x, against)
44
+ else:
45
+ score = SequenceMatcher(None, x, against).ratio()
46
+
47
+ return score
48
+
49
+
50
+ def match_one(query, choices, match_func=None,
51
+ strategy=MatchStrategy.DAMERAU_LEVENSHTEIN_SIMILARITY):
52
+ """
53
+ Find best match from a list or dictionary given an input
54
+
55
+ Arguments:
56
+ query: string to test
57
+ choices: list or dictionary of choices
58
+
59
+ Returns: tuple with best match, score
60
+ """
61
+ return match_all(query, choices, match_func, strategy)[0]
62
+
63
+
64
+ def match_all(query, choices, match_func=None,
65
+ strategy=MatchStrategy.DAMERAU_LEVENSHTEIN_SIMILARITY):
66
+ """
67
+ match scores from a list or dictionary given an input
68
+
69
+ Arguments:
70
+ query: string to test
71
+ choices: list or dictionary of choices
72
+
73
+ Returns: list of tuples (match, score)
74
+ """
75
+ match_func = match_func or fuzzy_match
76
+ if isinstance(choices, dict):
77
+ _choices = list(choices.keys())
78
+ elif isinstance(choices, list):
79
+ _choices = choices
80
+ else:
81
+ raise ValueError('a list or dict of choices must be provided')
82
+ matches = []
83
+ for c in _choices:
84
+ if isinstance(choices, dict):
85
+ matches.append((choices[c], match_func(query, c, strategy)))
86
+ else:
87
+ matches.append((c, match_func(query, c, strategy)))
88
+ return sorted(matches, key=lambda k: k[1], reverse=True)
@@ -0,0 +1,6 @@
1
+ # START_VERSION_BLOCK
2
+ VERSION_MAJOR = 0
3
+ VERSION_MINOR = 0
4
+ VERSION_BUILD = 1
5
+ VERSION_ALPHA = 0
6
+ # END_VERSION_BLOCK
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.1
2
+ Name: nebulento
3
+ Version: 0.0.1
4
+ Summary: dead simple fuzzy matching intent parser
5
+ Home-page: https://github.com/OpenJarbas/nebulento
6
+ Author: jarbasai
7
+ Author-email: jarbasai@mailfence.com
8
+ License: apache-2.0
9
+ Description: # Nebulento
10
+
11
+ *A lightweight, dead simple fuzzy matching intent parser*
12
+
13
+ Built on top of [rapidfuzz](https://github.com/maxbachmann/rapidfuzz)
14
+
15
+ Finds the closest matching intent via fuzzy match between the text and all of the training sentences you provided. Works best when you have a small number of sentences (dozens to hundreds) and need some resiliency to spelling errors (i.e., from text chat).
16
+
17
+ ## Usage
18
+
19
+ ```python
20
+ from nebulento import IntentContainer, MatchStrategy
21
+
22
+ container = IntentContainer(fuzzy_strategy=MatchStrategy.TOKEN_SET_RATIO)
23
+
24
+ container.add_intent('hello', [
25
+ 'hello', 'hi', 'how are you', "what's up"
26
+ ])
27
+ container.add_intent('buy', [
28
+ 'buy {item}', 'purchase {item}', 'get {item}', 'get {item} for me'
29
+ ])
30
+ container.add_entity('item', [
31
+ 'milk', 'cheese'
32
+ ])
33
+
34
+ container.calc_intent('hello')
35
+ # {'best_match': 'hello',
36
+ # 'conf': 1.0,
37
+ # 'entities': {},
38
+ # 'match_strategy': 'TOKEN_SET_RATIO',
39
+ # 'name': 'hello',
40
+ # 'utterance': 'hello',
41
+ # 'utterance_consumed': 'hello',
42
+ # 'utterance_remainder': ''}
43
+
44
+ container.calc_intent('buy milk')
45
+ # {'best_match': 'buy {item}',
46
+ # 'conf': 0.71875,
47
+ # 'entities': {'item': ['milk']},
48
+ # 'match_strategy': 'TOKEN_SET_RATIO',
49
+ # 'name': 'buy',
50
+ # 'utterance': 'buy milk',
51
+ # 'utterance_consumed': 'buy milk',
52
+ # 'utterance_remainder': ''}
53
+
54
+
55
+ container.add_intent('look_at_thing', ['I see {thing} (in|on) {place}'])
56
+ container.add_entity("place", ["floor", "table"])
57
+
58
+ container.calc_intent('I see trash in the floor')
59
+ #{'best_match': 'i see {thing} in {place}',
60
+ # 'conf': 0.65625,
61
+ # 'entities': {'place': ['floor']},
62
+ # 'match_strategy': 'TOKEN_SET_RATIO',
63
+ # 'name': 'look_at_thing',
64
+ # 'utterance': 'i see trash in the floor',
65
+ # 'utterance_consumed': 'i see in floor',
66
+ # 'utterance_remainder': 'trash the'}
67
+
68
+ container.add_entity("thing", ["food"])
69
+ container.calc_intent('I see food in the table')
70
+ #{'best_match': 'i see {thing} in {place}',
71
+ # 'conf': 0.7007978723404256,
72
+ # 'entities': {'place': ['table'], 'thing': ['food']},
73
+ # 'match_strategy': 'TOKEN_SET_RATIO',
74
+ # 'name': 'look_at_thing',
75
+ # 'utterance': 'i see food in the table',
76
+ # 'utterance_consumed': 'i see in table food',
77
+ # 'utterance_remainder': 'the'}
78
+
79
+ ```
80
+
81
+ ## Match Strategies
82
+
83
+ - **Ratio**: Use `MatchStrategy.RATIO` when you need to compare strings and determine their overall similarity. It is effective for handling cases where strings have minor differences due to typos or spelling variations.
84
+ - **Partial Ratio**: `MatchStrategy.PARTIAL_RATIO` is useful when you want to focus on the best matching substring between two strings. It handles cases where one string is a subset or prefix of the other, providing a more targeted similarity measure.
85
+ - **Token Set Ratio**: `MatchStrategy.TOKEN_SET_RATIO` is ideal when you want to compare strings without considering their word order. It captures the essence of the strings’ content, making it suitable for scenarios where word arrangement might vary but the overall content remains similar.
86
+ - **Token Sort Ratio**: Use `MatchStrategy.TOKEN_SORT_RATIO` when you want to compare strings and consider word order variations. It is particularly effective when the words are expected to be similar, but their arrangement may differ.
87
+
88
+ Platform: UNKNOWN
89
+ Description-Content-Type: text/markdown
@@ -0,0 +1,13 @@
1
+ LICENSE.md
2
+ README.md
3
+ setup.py
4
+ nebulento/__init__.py
5
+ nebulento/bracket_expansion.py
6
+ nebulento/fuzz.py
7
+ nebulento/version.py
8
+ nebulento.egg-info/PKG-INFO
9
+ nebulento.egg-info/SOURCES.txt
10
+ nebulento.egg-info/dependency_links.txt
11
+ nebulento.egg-info/requires.txt
12
+ nebulento.egg-info/top_level.txt
13
+ test/test_nebulento.py
@@ -0,0 +1,2 @@
1
+ rapidfuzz
2
+ quebra_frases
@@ -0,0 +1 @@
1
+ nebulento
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,61 @@
1
+ import os
2
+ import os.path
3
+
4
+ from setuptools import setup
5
+
6
+ BASEDIR = os.path.abspath(os.path.dirname(__file__))
7
+
8
+
9
+ def required(requirements_file):
10
+ """ Read requirements file and remove comments and empty lines. """
11
+ with open(os.path.join(BASEDIR, requirements_file), 'r') as f:
12
+ requirements = f.read().splitlines()
13
+ if 'MYCROFT_LOOSE_REQUIREMENTS' in os.environ:
14
+ print('USING LOOSE REQUIREMENTS!')
15
+ requirements = [r.replace('==', '>=').replace('~=', '>=') for r in requirements]
16
+ return [pkg for pkg in requirements
17
+ if pkg.strip() and not pkg.startswith("#")]
18
+
19
+
20
+ def get_version():
21
+ version_file = os.path.join(BASEDIR, 'nebulento', 'version.py')
22
+ major, minor, build, alpha = (None, None, None, None)
23
+ with open(version_file) as f:
24
+ for line in f:
25
+ if 'VERSION_MAJOR' in line:
26
+ major = line.split('=')[1].strip()
27
+ elif 'VERSION_MINOR' in line:
28
+ minor = line.split('=')[1].strip()
29
+ elif 'VERSION_BUILD' in line:
30
+ build = line.split('=')[1].strip()
31
+ elif 'VERSION_ALPHA' in line:
32
+ alpha = line.split('=')[1].strip()
33
+
34
+ if ((major and minor and build and alpha) or
35
+ '# END_VERSION_BLOCK' in line):
36
+ break
37
+ version = f"{major}.{minor}.{build}"
38
+ if int(alpha):
39
+ version += f"a{alpha}"
40
+ return version
41
+
42
+
43
+ def get_description():
44
+ with open(os.path.join(BASEDIR, "README.md"), "r") as f:
45
+ long_description = f.read()
46
+ return long_description
47
+
48
+
49
+ setup(
50
+ name='nebulento',
51
+ version=get_version(),
52
+ packages=['nebulento'],
53
+ url='https://github.com/OpenJarbas/nebulento',
54
+ license='apache-2.0',
55
+ author='jarbasai',
56
+ author_email='jarbasai@mailfence.com',
57
+ install_requires=required('requirements.txt'),
58
+ description='dead simple fuzzy matching intent parser',
59
+ long_description=get_description(),
60
+ long_description_content_type="text/markdown"
61
+ )
@@ -0,0 +1,232 @@
1
+ import unittest
2
+
3
+ from nebulento import IntentContainer, MatchStrategy
4
+
5
+
6
+ class TestIntentContainer(unittest.TestCase):
7
+ def test_syntax(self):
8
+ container = IntentContainer()
9
+ container.add_intent('hello', ["(hello|hi|hey) world"])
10
+ self.assertEqual(set(container.registered_intents["hello"]),
11
+ set(['hello world', 'hi world', 'hey world']))
12
+
13
+ container = IntentContainer()
14
+ container.add_intent('hello', ["hello (world|)"])
15
+ self.assertEqual(set(container.registered_intents["hello"]),
16
+ set(['hello world', 'hello']))
17
+
18
+ container.add_intent('hey', ["hey [world]"])
19
+ self.assertEqual(set(container.registered_intents["hey"]),
20
+ set(['hey world', 'hey']))
21
+
22
+ container.add_intent('hi', ["hi [{person}|people]"])
23
+ self.assertEqual(set(container.registered_intents["hi"]),
24
+ set(['hi {person}', 'hi people', 'hi']))
25
+
26
+ # test intent parsing
27
+ def test_intents(self):
28
+ container = IntentContainer()
29
+ container.add_intent('hello', [
30
+ 'hello', 'hi', 'how are you', "what's up"
31
+ ])
32
+ container.add_intent('buy', [
33
+ 'buy {item}', 'purchase {item}', 'get {item}', 'get {item} for me'
34
+ ])
35
+ container.add_entity('item', [
36
+ 'milk', 'cheese'
37
+ ])
38
+ self.assertEqual(container.calc_intent('hello'),
39
+ {'best_match': 'hello',
40
+ 'conf': 1.0,
41
+ 'entities': {},
42
+ 'match_strategy': 'DAMERAU_LEVENSHTEIN_SIMILARITY',
43
+ 'name': 'hello',
44
+ 'utterance': 'hello',
45
+ 'utterance_consumed': 'hello',
46
+ 'utterance_remainder': ''})
47
+
48
+ self.assertEqual(container.calc_intent('buy milk'),
49
+ {'best_match': 'buy {item}',
50
+ 'conf': 0.625,
51
+ 'entities': {'item': ['milk']},
52
+ 'match_strategy': 'DAMERAU_LEVENSHTEIN_SIMILARITY',
53
+ 'name': 'buy',
54
+ 'utterance': 'buy milk',
55
+ 'utterance_consumed': 'buy milk',
56
+ 'utterance_remainder': ''})
57
+ self.assertEqual(container.calc_intent('buy beer'),
58
+ {'best_match': 'buy {item}',
59
+ 'conf': 0.5,
60
+ 'entities': {},
61
+ 'match_strategy': 'DAMERAU_LEVENSHTEIN_SIMILARITY',
62
+ 'name': 'buy',
63
+ 'utterance': 'buy beer',
64
+ 'utterance_consumed': 'buy',
65
+ 'utterance_remainder': 'beer'}
66
+ )
67
+
68
+ def test_case(self):
69
+ container = IntentContainer()
70
+ container.add_intent('test', ['Testing cAPitalizAtion'])
71
+ self.assertEqual(
72
+ container.calc_intent('Testing cAPitalizAtion')['conf'], 1.0)
73
+ self.assertEqual(
74
+ container.calc_intent('teStiNg CapitalIzation')['conf'], 1.0)
75
+
76
+ container = IntentContainer(ignore_case=False)
77
+ container.add_intent('test', ['Testing cAPitalizAtion'])
78
+ self.assertEqual(
79
+ container.calc_intent('teStiNg CapitalIzation')['conf'],
80
+ 0.6363636363636364)
81
+
82
+ def test_entities(self):
83
+ container = IntentContainer()
84
+ container.add_intent('test3', ['I see {thing} (in|on) {place}'])
85
+ self.assertEqual(
86
+ container.calc_intent('I see a bin in there'),
87
+ {'best_match': 'i see {thing} in {place}',
88
+ 'conf': 0.5416666666666667,
89
+ 'entities': {},
90
+ 'match_strategy': 'DAMERAU_LEVENSHTEIN_SIMILARITY',
91
+ 'name': 'test3',
92
+ 'utterance': 'i see a bin in there',
93
+ 'utterance_consumed': 'i see in',
94
+ 'utterance_remainder': 'a bin there'}
95
+ )
96
+ container.add_entity("place", ["floor", "table"])
97
+ self.assertEqual(
98
+ container.calc_intent('I see trash in the floor'),
99
+ {'best_match': 'i see {thing} in {place}',
100
+ 'conf': 0.53125,
101
+ 'entities': {'place': ['floor']},
102
+ 'match_strategy': 'DAMERAU_LEVENSHTEIN_SIMILARITY',
103
+ 'name': 'test3',
104
+ 'utterance': 'i see trash in the floor',
105
+ 'utterance_consumed': 'i see in floor',
106
+ 'utterance_remainder': 'trash the'}
107
+ )
108
+ container.add_entity("thing", ["food"])
109
+ self.assertEqual(
110
+ container.calc_intent('I see food in the table'),
111
+ {'best_match': 'i see {thing} in {place}',
112
+ 'conf': 0.6484375,
113
+ 'entities': {'place': ['table'], 'thing': ['food']},
114
+ 'match_strategy': 'DAMERAU_LEVENSHTEIN_SIMILARITY',
115
+ 'name': 'test3',
116
+ 'utterance': 'i see food in the table',
117
+ 'utterance_consumed': 'i see in table food',
118
+ 'utterance_remainder': 'the'}
119
+ )
120
+
121
+ # test match strategies
122
+ def test_token_set(self):
123
+ container = IntentContainer(
124
+ fuzzy_strategy=MatchStrategy.TOKEN_SET_RATIO)
125
+ container.add_intent('buy', [
126
+ 'buy {item}', 'purchase {item}', 'get {item}', 'get {item} for me'
127
+ ])
128
+ container.add_entity('item', [
129
+ 'milk', 'cheese'
130
+ ])
131
+ self.assertEqual(container.calc_intent('buy milk'),
132
+ {'best_match': 'buy {item}',
133
+ 'conf': 0.6666666666666667,
134
+ 'entities': {'item': ['milk']},
135
+ 'match_strategy': 'TOKEN_SET_RATIO',
136
+ 'name': 'buy',
137
+ 'utterance': 'buy milk',
138
+ 'utterance_consumed': 'buy milk',
139
+ 'utterance_remainder': ''})
140
+ self.assertEqual(container.calc_intent('buy beer'),
141
+ {'best_match': 'buy {item}',
142
+ 'conf': 0.5555555555555556,
143
+ 'entities': {},
144
+ 'match_strategy': 'TOKEN_SET_RATIO',
145
+ 'name': 'buy',
146
+ 'utterance': 'buy beer',
147
+ 'utterance_consumed': 'buy',
148
+ 'utterance_remainder': 'beer'})
149
+
150
+ def test_token_sort(self):
151
+ container = IntentContainer(
152
+ fuzzy_strategy=MatchStrategy.TOKEN_SORT_RATIO)
153
+ container.add_intent('buy', [
154
+ 'buy {item}', 'purchase {item}', 'get {item}', 'get {item} for me'
155
+ ])
156
+ container.add_entity('item', [
157
+ 'milk', 'cheese'
158
+ ])
159
+ self.assertEqual(container.calc_intent('buy milk'),
160
+ {'best_match': 'buy {item}',
161
+ 'conf': 0.6666666666666667,
162
+ 'entities': {'item': ['milk']},
163
+ 'match_strategy': 'TOKEN_SORT_RATIO',
164
+ 'name': 'buy',
165
+ 'utterance': 'buy milk',
166
+ 'utterance_consumed': 'buy milk',
167
+ 'utterance_remainder': ''})
168
+ self.assertEqual(container.calc_intent('buy beer'),
169
+ {'best_match': 'buy {item}',
170
+ 'conf': 0.33333333333333337,
171
+ 'entities': {},
172
+ 'match_strategy': 'TOKEN_SORT_RATIO',
173
+ 'name': 'buy',
174
+ 'utterance': 'buy beer',
175
+ 'utterance_consumed': 'buy',
176
+ 'utterance_remainder': 'beer'})
177
+
178
+ def test_partial_token_set(self):
179
+ container = IntentContainer(
180
+ fuzzy_strategy=MatchStrategy.PARTIAL_TOKEN_SET_RATIO)
181
+ container.add_intent('buy', [
182
+ 'buy {item}', 'purchase {item}', 'get {item}', 'get {item} for me'
183
+ ])
184
+ container.add_entity('item', [
185
+ 'milk', 'cheese'
186
+ ])
187
+ self.assertEqual(container.calc_intent('buy milk'),
188
+ {'best_match': 'buy {item}',
189
+ 'conf': 1,
190
+ 'entities': {'item': ['milk']},
191
+ 'match_strategy': 'PARTIAL_TOKEN_SET_RATIO',
192
+ 'name': 'buy',
193
+ 'utterance': 'buy milk',
194
+ 'utterance_consumed': 'buy milk',
195
+ 'utterance_remainder': ''})
196
+ self.assertEqual(container.calc_intent('buy beer'),
197
+ {'best_match': 'buy {item}',
198
+ 'conf': 1.0,
199
+ 'entities': {},
200
+ 'match_strategy': 'PARTIAL_TOKEN_SET_RATIO',
201
+ 'name': 'buy',
202
+ 'utterance': 'buy beer',
203
+ 'utterance_consumed': 'buy',
204
+ 'utterance_remainder': 'beer'})
205
+
206
+ def test_partial_token_sort(self):
207
+ container = IntentContainer(
208
+ fuzzy_strategy=MatchStrategy.PARTIAL_TOKEN_SORT_RATIO)
209
+ container.add_intent('buy', [
210
+ 'buy {item}', 'purchase {item}', 'get {item}', 'get {item} for me'
211
+ ])
212
+ container.add_entity('item', [
213
+ 'milk', 'cheese'
214
+ ])
215
+ self.assertEqual(container.calc_intent('buy milk'),
216
+ {'best_match': 'buy {item}',
217
+ 'conf': 0.7857142857142857,
218
+ 'entities': {'item': ['milk']},
219
+ 'match_strategy': 'PARTIAL_TOKEN_SORT_RATIO',
220
+ 'name': 'buy',
221
+ 'utterance': 'buy milk',
222
+ 'utterance_consumed': 'buy milk',
223
+ 'utterance_remainder': ''})
224
+ self.assertEqual(container.calc_intent('buy beer'),
225
+ {'best_match': 'buy {item}',
226
+ 'conf': 0.5454545454545454,
227
+ 'entities': {},
228
+ 'match_strategy': 'PARTIAL_TOKEN_SORT_RATIO',
229
+ 'name': 'buy',
230
+ 'utterance': 'buy beer',
231
+ 'utterance_consumed': 'buy',
232
+ 'utterance_remainder': 'beer'})