ovos-padatious 0.1.0__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.
Files changed (43) hide show
  1. ovos-padatious-0.1.0/LICENSE +53 -0
  2. ovos-padatious-0.1.0/MANIFEST.in +3 -0
  3. ovos-padatious-0.1.0/PKG-INFO +91 -0
  4. ovos-padatious-0.1.0/README.md +64 -0
  5. ovos-padatious-0.1.0/ovos_padatious/__init__.py +18 -0
  6. ovos-padatious-0.1.0/ovos_padatious/__main__.py +58 -0
  7. ovos-padatious-0.1.0/ovos_padatious/bracket_expansion.py +183 -0
  8. ovos-padatious-0.1.0/ovos_padatious/entity.py +50 -0
  9. ovos-padatious-0.1.0/ovos_padatious/entity_edge.py +123 -0
  10. ovos-padatious-0.1.0/ovos_padatious/entity_manager.py +38 -0
  11. ovos-padatious-0.1.0/ovos_padatious/id_manager.py +68 -0
  12. ovos-padatious-0.1.0/ovos_padatious/intent.py +79 -0
  13. ovos-padatious-0.1.0/ovos_padatious/intent_container.py +335 -0
  14. ovos-padatious-0.1.0/ovos_padatious/intent_manager.py +32 -0
  15. ovos-padatious-0.1.0/ovos_padatious/match_data.py +81 -0
  16. ovos-padatious-0.1.0/ovos_padatious/opm.py +292 -0
  17. ovos-padatious-0.1.0/ovos_padatious/padaos.py +160 -0
  18. ovos-padatious-0.1.0/ovos_padatious/pos_intent.py +88 -0
  19. ovos-padatious-0.1.0/ovos_padatious/simple_intent.py +139 -0
  20. ovos-padatious-0.1.0/ovos_padatious/train_data.py +53 -0
  21. ovos-padatious-0.1.0/ovos_padatious/trainable.py +44 -0
  22. ovos-padatious-0.1.0/ovos_padatious/training_manager.py +118 -0
  23. ovos-padatious-0.1.0/ovos_padatious/util.py +132 -0
  24. ovos-padatious-0.1.0/ovos_padatious/version.py +6 -0
  25. ovos-padatious-0.1.0/ovos_padatious.egg-info/PKG-INFO +91 -0
  26. ovos-padatious-0.1.0/ovos_padatious.egg-info/SOURCES.txt +42 -0
  27. ovos-padatious-0.1.0/ovos_padatious.egg-info/dependency_links.txt +1 -0
  28. ovos-padatious-0.1.0/ovos_padatious.egg-info/entry_points.txt +3 -0
  29. ovos-padatious-0.1.0/ovos_padatious.egg-info/requires.txt +3 -0
  30. ovos-padatious-0.1.0/ovos_padatious.egg-info/top_level.txt +1 -0
  31. ovos-padatious-0.1.0/ovos_padatious.egg-info/zip-safe +1 -0
  32. ovos-padatious-0.1.0/requirements.txt +3 -0
  33. ovos-padatious-0.1.0/setup.cfg +7 -0
  34. ovos-padatious-0.1.0/setup.py +87 -0
  35. ovos-padatious-0.1.0/tests/__init__.py +0 -0
  36. ovos-padatious-0.1.0/tests/test_all.py +152 -0
  37. ovos-padatious-0.1.0/tests/test_container.py +241 -0
  38. ovos-padatious-0.1.0/tests/test_entity_edge.py +33 -0
  39. ovos-padatious-0.1.0/tests/test_id_manager.py +73 -0
  40. ovos-padatious-0.1.0/tests/test_intent.py +62 -0
  41. ovos-padatious-0.1.0/tests/test_match_data.py +35 -0
  42. ovos-padatious-0.1.0/tests/test_train_data.py +40 -0
  43. ovos-padatious-0.1.0/tests/test_util.py +55 -0
@@ -0,0 +1,53 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
39
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
41
+
42
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
43
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
44
+
45
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
46
+
47
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
48
+
49
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
50
+
51
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
52
+
53
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,3 @@
1
+ include LICENSE
2
+ include requirements.txt
3
+ recursive-include tests *.py
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.1
2
+ Name: ovos-padatious
3
+ Version: 0.1.0
4
+ Summary: A neural network intent parser
5
+ Home-page: https://github.com/OpenVoiceOS/ovos-padatious-pipeline-plugin
6
+ Author: Matthew Scholefield
7
+ License: Apache-2.0
8
+ Description: [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE.md)
9
+ # Padatious
10
+
11
+ An efficient and agile neural network intent parser.
12
+
13
+ This repository contains a OVOS pipeline plugin and bundles a fork of the original [padatious](https://github.com/MycroftAI/padatious) from the defunct MycroftAI
14
+
15
+
16
+ ## Features
17
+
18
+ - Intents are easy to create
19
+ - Requires a relatively small amount of data
20
+ - Intents run independent of each other
21
+ - Easily extract entities (ie. Find the nearest *gas station* -> `place: gas station`)
22
+ - Fast training with a modular approach to neural networks
23
+
24
+ ## Getting Started
25
+
26
+ ### Installing
27
+
28
+ Padatious requires the following native packages to be installed:
29
+
30
+ - [`FANN`][fann] (with dev headers)
31
+ - Python development headers
32
+ - `pip3`
33
+ - `swig`
34
+
35
+ Ubuntu:
36
+
37
+ ```
38
+ sudo apt-get install libfann-dev python3-dev python3-pip swig libfann-dev python3-fann2
39
+ ```
40
+
41
+ Next, install Padatious via `pip3`:
42
+
43
+ ```
44
+ pip3 install padatious
45
+ ```
46
+ Padatious also works in Python 2 if you are unable to upgrade.
47
+
48
+
49
+ [fann]:https://github.com/libfann/fann
50
+
51
+ ### Example
52
+
53
+ Here's a simple example of how to use Padatious:
54
+
55
+ #### program.py
56
+
57
+ ```Python
58
+ from ovos_padatious import IntentContainer
59
+
60
+ container = IntentContainer('intent_cache')
61
+ container.add_intent('hello', ['Hi there!', 'Hello.'])
62
+ container.add_intent('goodbye', ['See you!', 'Goodbye!'])
63
+ container.add_intent('search', ['Search for {query} (using|on) {engine}.'])
64
+ container.train()
65
+
66
+ print(container.calc_intent('Hello there!'))
67
+ print(container.calc_intent('Search for cats on CatTube.'))
68
+
69
+ container.remove_intent('goodbye')
70
+ ```
71
+
72
+
73
+ Keywords: intent-parser parser text text-processing
74
+ Platform: UNKNOWN
75
+ Classifier: Development Status :: 3 - Alpha
76
+ Classifier: Intended Audience :: Developers
77
+ Classifier: Topic :: Text Processing :: Linguistic
78
+ Classifier: License :: OSI Approved :: Apache Software License
79
+ Classifier: Programming Language :: Python :: 2
80
+ Classifier: Programming Language :: Python :: 2.7
81
+ Classifier: Programming Language :: Python :: 3
82
+ Classifier: Programming Language :: Python :: 3.0
83
+ Classifier: Programming Language :: Python :: 3.1
84
+ Classifier: Programming Language :: Python :: 3.2
85
+ Classifier: Programming Language :: Python :: 3.3
86
+ Classifier: Programming Language :: Python :: 3.4
87
+ Classifier: Programming Language :: Python :: 3.5
88
+ Classifier: Programming Language :: Python :: 3.6
89
+ Classifier: Programming Language :: Python :: 3.7
90
+ Classifier: Programming Language :: Python :: 3.8
91
+ Description-Content-Type: text/markdown
@@ -0,0 +1,64 @@
1
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE.md)
2
+ # Padatious
3
+
4
+ An efficient and agile neural network intent parser.
5
+
6
+ This repository contains a OVOS pipeline plugin and bundles a fork of the original [padatious](https://github.com/MycroftAI/padatious) from the defunct MycroftAI
7
+
8
+
9
+ ## Features
10
+
11
+ - Intents are easy to create
12
+ - Requires a relatively small amount of data
13
+ - Intents run independent of each other
14
+ - Easily extract entities (ie. Find the nearest *gas station* -> `place: gas station`)
15
+ - Fast training with a modular approach to neural networks
16
+
17
+ ## Getting Started
18
+
19
+ ### Installing
20
+
21
+ Padatious requires the following native packages to be installed:
22
+
23
+ - [`FANN`][fann] (with dev headers)
24
+ - Python development headers
25
+ - `pip3`
26
+ - `swig`
27
+
28
+ Ubuntu:
29
+
30
+ ```
31
+ sudo apt-get install libfann-dev python3-dev python3-pip swig libfann-dev python3-fann2
32
+ ```
33
+
34
+ Next, install Padatious via `pip3`:
35
+
36
+ ```
37
+ pip3 install padatious
38
+ ```
39
+ Padatious also works in Python 2 if you are unable to upgrade.
40
+
41
+
42
+ [fann]:https://github.com/libfann/fann
43
+
44
+ ### Example
45
+
46
+ Here's a simple example of how to use Padatious:
47
+
48
+ #### program.py
49
+
50
+ ```Python
51
+ from ovos_padatious import IntentContainer
52
+
53
+ container = IntentContainer('intent_cache')
54
+ container.add_intent('hello', ['Hi there!', 'Hello.'])
55
+ container.add_intent('goodbye', ['See you!', 'Goodbye!'])
56
+ container.add_intent('search', ['Search for {query} (using|on) {engine}.'])
57
+ container.train()
58
+
59
+ print(container.calc_intent('Hello there!'))
60
+ print(container.calc_intent('Search for cats on CatTube.'))
61
+
62
+ container.remove_intent('goodbye')
63
+ ```
64
+
@@ -0,0 +1,18 @@
1
+ # Copyright 2017 Mycroft AI, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .intent_container import IntentContainer
16
+ from .match_data import MatchData
17
+
18
+ __version__ = '0.4.8' # Also change in setup.py
@@ -0,0 +1,58 @@
1
+ import inspect
2
+ import json
3
+ from os.path import basename, splitext
4
+
5
+ from argparse import ArgumentParser
6
+
7
+ from ovos_padatious import IntentContainer
8
+
9
+
10
+ def train_setup(parser):
11
+ parser.add_argument('intent_cache', help='Folder to write trained intents to')
12
+ parser.add_argument('input_files', nargs='*', help='Input .intent and .entity files')
13
+ parser.add_argument('-d', '--data', help='Serialized training args', type=json.loads)
14
+ parser.add_argument('-s', '--single-thread', help='Run training in a single thread')
15
+ parser.add_argument('-f', '--force', help='Force retraining if already trained')
16
+ parser.add_argument('-a', '--args', help='Extra args (list) for function', type=json.loads)
17
+ parser.add_argument('-k', '--kwargs', help='Extra kwargs (json) for function', type=json.loads)
18
+
19
+
20
+ def train(parser, args):
21
+ if bool(args.input_files) == bool(args.data):
22
+ parser.error('You must specify one of input_files or --data (but not both)')
23
+
24
+ cont = IntentContainer(args.intent_cache)
25
+ if args.data:
26
+ cont.apply_training_args(args.data)
27
+ else:
28
+ for fn in args.input_files:
29
+ obj_name, ext = splitext(basename(fn))
30
+ if ext == '.intent':
31
+ cont.load_intent(obj_name, fn)
32
+ elif ext == '.entity':
33
+ cont.load_entity(obj_name, fn)
34
+ else:
35
+ parser.error('Unknown file extension: {}'.format(ext))
36
+ kwargs = inspect.signature(cont.train).bind(*(args.args or [])).arguments
37
+ kwargs.update(args.kwargs or {})
38
+ kwargs.setdefault('debug', True)
39
+ kwargs.setdefault('single_thread', args.single_thread)
40
+ kwargs.setdefault('force', args.force)
41
+ if cont.train(**kwargs):
42
+ return 0
43
+ return 10 # timeout
44
+
45
+
46
+ def main():
47
+ parser = ArgumentParser(description='Tool to interact with ovos_padatious via command line')
48
+ p = parser.add_subparsers(dest='action')
49
+ p.required = True
50
+ train_setup(p.add_parser('train'))
51
+
52
+ args = parser.parse_args()
53
+ if args.action == 'train':
54
+ exit(train(parser, args))
55
+
56
+
57
+ if __name__ == '__main__':
58
+ main()
@@ -0,0 +1,183 @@
1
+ # Copyright 2017 Mycroft AI, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ class Fragment(object):
17
+ """(Abstract) empty sentence fragment"""
18
+
19
+ def __init__(self, tree):
20
+ """
21
+ Construct a sentence tree fragment which is merely a wrapper for
22
+ a list of Strings
23
+
24
+ Args:
25
+ tree (?): Base tree for the sentence fragment, type depends on
26
+ subclass, refer to those subclasses
27
+ """
28
+ self._tree = tree
29
+
30
+ def tree(self):
31
+ """Return the represented sentence tree as raw data."""
32
+ return self._tree
33
+
34
+ def expand(self):
35
+ """
36
+ Expanded version of the fragment. In this case an empty sentence.
37
+
38
+ Returns:
39
+ List<List<str>>: A list with an empty sentence (= token/string list)
40
+ """
41
+ return [[]]
42
+
43
+ def __str__(self):
44
+ return self._tree.__str__()
45
+
46
+ def __repr__(self):
47
+ return self._tree.__repr__()
48
+
49
+
50
+ class Word(Fragment):
51
+ """
52
+ Single word in the sentence tree.
53
+
54
+ Construct with a string as argument.
55
+ """
56
+
57
+ def expand(self):
58
+ """
59
+ Creates one sentence that contains exactly that word.
60
+
61
+ Returns:
62
+ List<List<str>>: A list with the given string as sentence
63
+ (= token/string list)
64
+ """
65
+ return [[self._tree]]
66
+
67
+
68
+ class Sentence(Fragment):
69
+ """
70
+ A Sentence made of several concatenations/words.
71
+
72
+ Construct with a List<Fragment> as argument.
73
+ """
74
+
75
+ def expand(self):
76
+ """
77
+ Creates a combination of all sub-sentences.
78
+
79
+ Returns:
80
+ List<List<str>>: A list with all subsentence expansions combined in
81
+ every possible way
82
+ """
83
+ old_expanded = [[]]
84
+ for sub in self._tree:
85
+ sub_expanded = sub.expand()
86
+ new_expanded = []
87
+ while len(old_expanded) > 0:
88
+ sentence = old_expanded.pop()
89
+ for new in sub_expanded:
90
+ new_expanded.append(sentence + new)
91
+ old_expanded = new_expanded
92
+ return old_expanded
93
+
94
+
95
+ class Options(Fragment):
96
+ """
97
+ A Combination of possible sub-sentences.
98
+
99
+ Construct with List<Fragment> as argument.
100
+ """
101
+
102
+ def expand(self):
103
+ """
104
+ Returns all of its options as seperated sub-sentences.
105
+
106
+ Returns:
107
+ List<List<str>>: A list containing the sentences created by all
108
+ expansions of its sub-sentences
109
+ """
110
+ options = []
111
+ for option in self._tree:
112
+ options.extend(option.expand())
113
+ return options
114
+
115
+
116
+ class SentenceTreeParser(object):
117
+ """
118
+ Generate sentence token trees from a list of tokens
119
+ ['1', '(', '2', '|', '3, ')'] -> [['1', '2'], ['1', '3']]
120
+ """
121
+
122
+ def __init__(self, tokens):
123
+ self.tokens = tokens
124
+
125
+ def _parse(self):
126
+ """
127
+ Generate sentence token trees
128
+ ['1', '(', '2', '|', '3, ')'] -> ['1', ['2', '3']]
129
+ """
130
+ self._current_position = 0
131
+ return self._parse_expr()
132
+
133
+ def _parse_expr(self):
134
+ """
135
+ Generate sentence token trees from the current position to
136
+ the next closing parentheses / end of the list and return it
137
+ ['1', '(', '2', '|', '3, ')'] -> ['1', [['2'], ['3']]]
138
+ ['2', '|', '3'] -> [['2'], ['3']]
139
+ """
140
+ # List of all generated sentences
141
+ sentence_list = []
142
+ # Currently active sentence
143
+ cur_sentence = []
144
+ sentence_list.append(Sentence(cur_sentence))
145
+ # Determine which form the current expression has
146
+ while self._current_position < len(self.tokens):
147
+ cur = self.tokens[self._current_position]
148
+ self._current_position += 1
149
+ if cur == '(':
150
+ # Parse the subexpression
151
+ subexpr = self._parse_expr()
152
+ # Check if the subexpression only has one branch
153
+ # -> If so, append "(" and ")" and add it as is
154
+ normal_brackets = False
155
+ if len(subexpr.tree()) == 1:
156
+ normal_brackets = True
157
+ cur_sentence.append(Word('('))
158
+ # add it to the sentence
159
+ cur_sentence.append(subexpr)
160
+ if normal_brackets:
161
+ cur_sentence.append(Word(')'))
162
+ elif cur == '|':
163
+ # Begin parsing a new sentence
164
+ cur_sentence = []
165
+ sentence_list.append(Sentence(cur_sentence))
166
+ elif cur == ')':
167
+ # End parsing the current subexpression
168
+ break
169
+ # TODO anything special about {sth}?
170
+ else:
171
+ cur_sentence.append(Word(cur))
172
+ return Options(sentence_list)
173
+
174
+ def _expand_tree(self, tree):
175
+ """
176
+ Expand a list of sub sentences to all combinated sentences.
177
+ ['1', ['2', '3']] -> [['1', '2'], ['1', '3']]
178
+ """
179
+ return tree.expand()
180
+
181
+ def expand_parentheses(self):
182
+ tree = self._parse()
183
+ return self._expand_tree(tree)
@@ -0,0 +1,50 @@
1
+ # Copyright 2017 Mycroft AI, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from os.path import join
16
+
17
+ from ovos_padatious.simple_intent import SimpleIntent
18
+ from ovos_padatious.trainable import Trainable
19
+
20
+
21
+ class Entity(SimpleIntent, Trainable):
22
+ def __init__(self, name, *args, **kwargs):
23
+ SimpleIntent.__init__(self, name)
24
+ Trainable.__init__(self, name, *args, **kwargs)
25
+
26
+ @staticmethod
27
+ def verify_name(token):
28
+ if token[0] in '{}' or token[-1] in '{}':
29
+ raise ValueError('token must not be surrounded in braces (ie. {word} should be word)')
30
+
31
+ @staticmethod
32
+ def wrap_name(name):
33
+ """Wraps SkillName:entity into SkillName:{entity}"""
34
+ if ':' in name:
35
+ parts = name.split(':')
36
+ intent_name, ent_name = parts[0], parts[1:]
37
+ return intent_name + ':{' + ':'.join(ent_name) + '}'
38
+ else:
39
+ return '{' + name + '}'
40
+
41
+ def save(self, folder):
42
+ prefix = join(folder, self.name)
43
+ SimpleIntent.save(self, prefix)
44
+ self.save_hash(prefix)
45
+
46
+ @classmethod
47
+ def from_file(cls, name, folder):
48
+ self = super(Entity, cls).from_file(name, join(folder, name))
49
+ self.load_hash(join(folder, name))
50
+ return self
@@ -0,0 +1,123 @@
1
+ # Copyright 2017 Mycroft AI, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from fann2 import libfann as fann
16
+
17
+ from ovos_padatious.id_manager import IdManager
18
+ from ovos_padatious.util import StrEnum, resolve_conflicts
19
+
20
+
21
+ class Ids(StrEnum):
22
+ end = ':end'
23
+
24
+
25
+ class EntityEdge(object):
26
+ """
27
+ Represents the left or right side of an entity (a PosIntent)
28
+
29
+ Args:
30
+ direction (int): -1 for left and +1 for right
31
+ token (str): token to attach to (something like {word})
32
+ intent_name (str): name of parent intent
33
+ """
34
+ def __init__(self, direction, token, intent_name):
35
+ self.ids = IdManager(Ids)
36
+ self.intent_name = intent_name
37
+ self.token = token
38
+ self.dir = direction
39
+ self.net = None
40
+
41
+ def get_end(self, sent):
42
+ return len(sent) if self.dir > 0 else -1
43
+
44
+ def vectorize(self, sent, pos):
45
+ unknown = 0
46
+ vector = self.ids.vector()
47
+ end_pos = self.get_end(sent)
48
+ for i in range(pos + self.dir, end_pos, self.dir):
49
+ if sent[i] in self.ids:
50
+ self.ids.assign(vector, sent[i], 1.0 / abs(i - pos))
51
+ else:
52
+ unknown += 1
53
+ self.ids.assign(vector, Ids.end, 1.0 / abs(end_pos - pos))
54
+ return vector
55
+
56
+ def match(self, sent, pos):
57
+ return self.net.run(self.vectorize(sent, pos))[0]
58
+
59
+ def configure_net(self):
60
+ layers = [len(self.ids), 3, 1]
61
+
62
+ self.net = fann.neural_net()
63
+ self.net.create_standard_array(layers)
64
+ self.net.set_activation_function_hidden(fann.SIGMOID_SYMMETRIC_STEPWISE)
65
+ self.net.set_activation_function_output(fann.SIGMOID_STEPWISE)
66
+ self.net.set_train_stop_function(fann.STOPFUNC_BIT)
67
+ self.net.set_bit_fail_limit(0.1)
68
+
69
+ def save(self, prefix):
70
+ prefix += '.' + {-1: 'l', +1: 'r'}[self.dir]
71
+ self.net.save(str(prefix + '.net')) # Must have str()
72
+ self.ids.save(prefix)
73
+
74
+ def load(self, prefix):
75
+ prefix += '.' + {-1: 'l', +1: 'r'}[self.dir]
76
+ self.net = fann.neural_net()
77
+ if not self.net.create_from_file(str(prefix + '.net')): # Must have str()
78
+ raise FileNotFoundError(str(prefix + '.net'))
79
+ self.ids.load(prefix)
80
+
81
+ def train(self, train_data):
82
+ for sent in train_data.my_sents(self.intent_name):
83
+ if self.token in sent:
84
+ for i in range(sent.index(self.token) + self.dir,
85
+ self.get_end(sent), self.dir):
86
+ if sent[i][0] != '{':
87
+ self.ids.add_token(sent[i])
88
+
89
+ inputs, outputs = [], []
90
+
91
+ def pollute(sent, i, out_val):
92
+ """Simulates multiple token words in adjacent entities"""
93
+ for j, check_token in enumerate(sent):
94
+ d = j - i
95
+ if int(d > 0) - int(d < 0) == self.dir and check_token.startswith('{'):
96
+ for pol_len in range(1, 4):
97
+ s = sent[:j] + [':0'] * pol_len + sent[j + 1:]
98
+ p = i + (pol_len - 1) * int(self.dir < 0)
99
+ inputs.append(self.vectorize(s, p))
100
+ outputs.append([out_val])
101
+
102
+ def add_sents(sents, out_fn):
103
+ for sent in sents:
104
+ for i, token in enumerate(sent):
105
+ out_val = out_fn(token)
106
+ inputs.append(self.vectorize(sent, i))
107
+ outputs.append([out_val])
108
+ if out_val == 1.0:
109
+ pollute(sent, i, 1.0)
110
+
111
+ add_sents(train_data.my_sents(self.intent_name), lambda x: float(x == self.token))
112
+ add_sents(train_data.other_sents(self.intent_name), lambda x: 0.0)
113
+ inputs, outputs = resolve_conflicts(inputs, outputs)
114
+
115
+ data = fann.training_data()
116
+ data.set_train_data(inputs, outputs)
117
+
118
+ for _ in range(10):
119
+ self.configure_net()
120
+ self.net.train_on_data(data, 1000, 0, 0)
121
+ self.net.test_data(data)
122
+ if self.net.get_bit_fail() == 0:
123
+ break