ovos-ww-plugin-wakeforge 0.0.1a2__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.
- ovos_ww_plugin_wakeforge-0.0.1a2/LICENSE +203 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/PKG-INFO +111 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/README.md +88 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/ovos_ww_plugin_wakeforge/__init__.py +146 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/ovos_ww_plugin_wakeforge/inference.py +446 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/ovos_ww_plugin_wakeforge/version.py +7 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/ovos_ww_plugin_wakeforge.egg-info/PKG-INFO +111 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/ovos_ww_plugin_wakeforge.egg-info/SOURCES.txt +13 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/ovos_ww_plugin_wakeforge.egg-info/dependency_links.txt +1 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/ovos_ww_plugin_wakeforge.egg-info/entry_points.txt +2 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/ovos_ww_plugin_wakeforge.egg-info/requires.txt +10 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/ovos_ww_plugin_wakeforge.egg-info/top_level.txt +1 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/pyproject.toml +51 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/setup.cfg +4 -0
- ovos_ww_plugin_wakeforge-0.0.1a2/test/test_wakeforge.py +117 -0
|
@@ -0,0 +1,203 @@
|
|
|
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 2025 Casimiro Ferreira
|
|
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.
|
|
203
|
+
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ovos-ww-plugin-wakeforge
|
|
3
|
+
Version: 0.0.1a2
|
|
4
|
+
Summary: OVOS wake word plugin for models trained with wakeforge
|
|
5
|
+
Author-email: JarbasAi <jarbasai@mailfence.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/OpenVoiceOS/ovos-ww-plugin-wakeforge
|
|
8
|
+
Project-URL: Repository, https://github.com/OpenVoiceOS/ovos-ww-plugin-wakeforge
|
|
9
|
+
Keywords: mycroft,ovos,plugin,wake,word,wakeforge
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: onnxruntime>=1.20
|
|
14
|
+
Requires-Dist: numpy
|
|
15
|
+
Requires-Dist: requests
|
|
16
|
+
Requires-Dist: ovos-plugin-manager<3.0.0,>=2.1.0
|
|
17
|
+
Requires-Dist: ovos-utils<1.0.0,>=0.0.14
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest<9; extra == "test"
|
|
20
|
+
Requires-Dist: onnx; extra == "test"
|
|
21
|
+
Requires-Dist: ovoscope<1.0.0,>=0.19.0a1; extra == "test"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# ovos-ww-plugin-wakeforge
|
|
25
|
+
|
|
26
|
+
An OVOS wake-word plugin for custom models trained with
|
|
27
|
+
[wakeforge](https://github.com/TigreGotico/wakeforge).
|
|
28
|
+
|
|
29
|
+
Wakeforge trains a wake-word detector from a single phrase and exports a two-file
|
|
30
|
+
ONNX pipeline: a feature extractor and a classifier head. This plugin loads that
|
|
31
|
+
pipeline and runs it as an always-on hotword engine. The runtime uses
|
|
32
|
+
`onnxruntime` and `numpy` only. It does not need PyTorch.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install ovos-ww-plugin-wakeforge
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Train a model
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install wakeforge
|
|
44
|
+
wakeforge-quickstart "hey jarvis" ./hey_jarvis
|
|
45
|
+
# → ./hey_jarvis/best_f1_featurizer.onnx + ./hey_jarvis/best_f1.onnx
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Configure
|
|
49
|
+
|
|
50
|
+
In `mycroft.conf`, point a hotword at the two ONNX files. Use local paths or URLs.
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"listener": {
|
|
55
|
+
"wake_word": "hey_jarvis"
|
|
56
|
+
},
|
|
57
|
+
"hotwords": {
|
|
58
|
+
"hey_jarvis": {
|
|
59
|
+
"module": "ovos-ww-plugin-wakeforge",
|
|
60
|
+
"listen": true,
|
|
61
|
+
"featurizer": "~/hey_jarvis/best_f1_featurizer.onnx",
|
|
62
|
+
"model": "~/hey_jarvis/best_f1.onnx",
|
|
63
|
+
"threshold": 0.5
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Config keys
|
|
70
|
+
|
|
71
|
+
| key | default | description |
|
|
72
|
+
|-----|---------|-------------|
|
|
73
|
+
| `featurizer` | — (required) | feature-extractor ONNX (path or URL) |
|
|
74
|
+
| `model` | — (required) | classifier-head ONNX (path or URL) |
|
|
75
|
+
| `vad` | none | optional VAD ONNX for an extra channel |
|
|
76
|
+
| `threshold` | `0.5` | detection threshold |
|
|
77
|
+
| `smoothing` | `ema` | `ema` \| `mean` \| `max` |
|
|
78
|
+
| `patience` | `3` | consecutive above-threshold frames to fire |
|
|
79
|
+
| `debounce_sec` | `1.0` | minimum seconds between triggers |
|
|
80
|
+
| `window_size` | `5` | smoother rolling window (mean/max) |
|
|
81
|
+
| `ema_alpha` | `0.3` | EMA responsiveness |
|
|
82
|
+
| `streaming` | `false` | use the stateful streaming (GRU) head |
|
|
83
|
+
| `gru_window` | `100` | window the streaming head was exported with |
|
|
84
|
+
| `hidden_dim` | `128` | GRU hidden size of the streaming head |
|
|
85
|
+
|
|
86
|
+
URL models are cached under `${XDG_DATA_HOME}/wakeforge/`.
|
|
87
|
+
|
|
88
|
+
## Related projects
|
|
89
|
+
|
|
90
|
+
- [TigreGotico/wakeforge](https://github.com/TigreGotico/wakeforge) trains the ONNX models this plugin loads.
|
|
91
|
+
- [OpenVoiceOS/ovos-plugin-manager](https://github.com/OpenVoiceOS/ovos-plugin-manager) loads and manages this plugin alongside other STT, TTS, and wake-word plugins.
|
|
92
|
+
- [OpenVoiceOS/ovos-ww-plugin-precise-onnx](https://github.com/OpenVoiceOS/ovos-ww-plugin-precise-onnx) is a sibling wake-word plugin that runs Precise models through ONNX.
|
|
93
|
+
|
|
94
|
+
## Credits
|
|
95
|
+
|
|
96
|
+
Developed by [TigreGótico](https://tigregotico.pt) for
|
|
97
|
+
[OpenVoiceOS](https://openvoiceos.org).
|
|
98
|
+
|
|
99
|
+
[](https://nlnet.nl/project/OpenVoiceOS)
|
|
100
|
+
|
|
101
|
+
This project was funded through the [NGI0 Commons Fund](https://nlnet.nl/commonsfund),
|
|
102
|
+
a fund established by [NLnet](https://nlnet.nl) with financial support from the
|
|
103
|
+
European Commission's [Next Generation Internet](https://ngi.eu) programme, under
|
|
104
|
+
the aegis of [DG Communications Networks, Content and Technology](https://commission.europa.eu/about-european-commission/departments-and-executive-agencies/communications-networks-content-and-technology_en)
|
|
105
|
+
under grant agreement No [101135429](https://cordis.europa.eu/project/id/101135429).
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
Apache-2.0
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# ovos-ww-plugin-wakeforge
|
|
2
|
+
|
|
3
|
+
An OVOS wake-word plugin for custom models trained with
|
|
4
|
+
[wakeforge](https://github.com/TigreGotico/wakeforge).
|
|
5
|
+
|
|
6
|
+
Wakeforge trains a wake-word detector from a single phrase and exports a two-file
|
|
7
|
+
ONNX pipeline: a feature extractor and a classifier head. This plugin loads that
|
|
8
|
+
pipeline and runs it as an always-on hotword engine. The runtime uses
|
|
9
|
+
`onnxruntime` and `numpy` only. It does not need PyTorch.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install ovos-ww-plugin-wakeforge
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Train a model
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install wakeforge
|
|
21
|
+
wakeforge-quickstart "hey jarvis" ./hey_jarvis
|
|
22
|
+
# → ./hey_jarvis/best_f1_featurizer.onnx + ./hey_jarvis/best_f1.onnx
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Configure
|
|
26
|
+
|
|
27
|
+
In `mycroft.conf`, point a hotword at the two ONNX files. Use local paths or URLs.
|
|
28
|
+
|
|
29
|
+
```json
|
|
30
|
+
{
|
|
31
|
+
"listener": {
|
|
32
|
+
"wake_word": "hey_jarvis"
|
|
33
|
+
},
|
|
34
|
+
"hotwords": {
|
|
35
|
+
"hey_jarvis": {
|
|
36
|
+
"module": "ovos-ww-plugin-wakeforge",
|
|
37
|
+
"listen": true,
|
|
38
|
+
"featurizer": "~/hey_jarvis/best_f1_featurizer.onnx",
|
|
39
|
+
"model": "~/hey_jarvis/best_f1.onnx",
|
|
40
|
+
"threshold": 0.5
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Config keys
|
|
47
|
+
|
|
48
|
+
| key | default | description |
|
|
49
|
+
|-----|---------|-------------|
|
|
50
|
+
| `featurizer` | — (required) | feature-extractor ONNX (path or URL) |
|
|
51
|
+
| `model` | — (required) | classifier-head ONNX (path or URL) |
|
|
52
|
+
| `vad` | none | optional VAD ONNX for an extra channel |
|
|
53
|
+
| `threshold` | `0.5` | detection threshold |
|
|
54
|
+
| `smoothing` | `ema` | `ema` \| `mean` \| `max` |
|
|
55
|
+
| `patience` | `3` | consecutive above-threshold frames to fire |
|
|
56
|
+
| `debounce_sec` | `1.0` | minimum seconds between triggers |
|
|
57
|
+
| `window_size` | `5` | smoother rolling window (mean/max) |
|
|
58
|
+
| `ema_alpha` | `0.3` | EMA responsiveness |
|
|
59
|
+
| `streaming` | `false` | use the stateful streaming (GRU) head |
|
|
60
|
+
| `gru_window` | `100` | window the streaming head was exported with |
|
|
61
|
+
| `hidden_dim` | `128` | GRU hidden size of the streaming head |
|
|
62
|
+
|
|
63
|
+
URL models are cached under `${XDG_DATA_HOME}/wakeforge/`.
|
|
64
|
+
|
|
65
|
+
## Related projects
|
|
66
|
+
|
|
67
|
+
- [TigreGotico/wakeforge](https://github.com/TigreGotico/wakeforge) trains the ONNX models this plugin loads.
|
|
68
|
+
- [OpenVoiceOS/ovos-plugin-manager](https://github.com/OpenVoiceOS/ovos-plugin-manager) loads and manages this plugin alongside other STT, TTS, and wake-word plugins.
|
|
69
|
+
- [OpenVoiceOS/ovos-ww-plugin-precise-onnx](https://github.com/OpenVoiceOS/ovos-ww-plugin-precise-onnx) is a sibling wake-word plugin that runs Precise models through ONNX.
|
|
70
|
+
|
|
71
|
+
## Credits
|
|
72
|
+
|
|
73
|
+
Developed by [TigreGótico](https://tigregotico.pt) for
|
|
74
|
+
[OpenVoiceOS](https://openvoiceos.org).
|
|
75
|
+
|
|
76
|
+
[](https://nlnet.nl/project/OpenVoiceOS)
|
|
77
|
+
|
|
78
|
+
This project was funded through the [NGI0 Commons Fund](https://nlnet.nl/commonsfund),
|
|
79
|
+
a fund established by [NLnet](https://nlnet.nl) with financial support from the
|
|
80
|
+
European Commission's [Next Generation Internet](https://ngi.eu) programme, under
|
|
81
|
+
the aegis of [DG Communications Networks, Content and Technology](https://commission.europa.eu/about-european-commission/departments-and-executive-agencies/communications-networks-content-and-technology_en)
|
|
82
|
+
under grant agreement No [101135429](https://cordis.europa.eu/project/id/101135429).
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## License
|
|
87
|
+
|
|
88
|
+
Apache-2.0
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""OVOS wake-word plugin for models trained with wakeforge.
|
|
2
|
+
|
|
3
|
+
Loads a wakeforge two-file ONNX pipeline (featurizer + classifier head) and runs
|
|
4
|
+
it as an always-on hotword detector. Pure runtime: numpy + onnxruntime, no torch.
|
|
5
|
+
"""
|
|
6
|
+
from os import makedirs
|
|
7
|
+
from os.path import isfile, join, expanduser
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
import requests
|
|
11
|
+
from ovos_plugin_manager.templates.hotwords import HotWordEngine
|
|
12
|
+
from ovos_utils.log import LOG
|
|
13
|
+
from ovos_utils.xdg_utils import xdg_data_home
|
|
14
|
+
|
|
15
|
+
from ovos_ww_plugin_wakeforge.inference import (
|
|
16
|
+
OnnxStreamingWakeWord,
|
|
17
|
+
OnnxWakeWordInferencer,
|
|
18
|
+
PredictionSmoother,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class WakeForgeHotwordPlugin(HotWordEngine):
|
|
23
|
+
"""Detect a wake word using a model trained with wakeforge.
|
|
24
|
+
|
|
25
|
+
wakeforge exports a two-file ONNX pipeline — a feature extractor and a
|
|
26
|
+
classifier head. Point this plugin at both (local paths or HTTP URLs) via the
|
|
27
|
+
``hotwords.<phrase>`` section of ``mycroft.conf``::
|
|
28
|
+
|
|
29
|
+
"hotwords": {
|
|
30
|
+
"hey_jarvis": {
|
|
31
|
+
"module": "ovos-ww-plugin-wakeforge",
|
|
32
|
+
"featurizer": "/path/to/best_f1_featurizer.onnx",
|
|
33
|
+
"model": "/path/to/best_f1.onnx",
|
|
34
|
+
"threshold": 0.5
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
Recognised config keys:
|
|
39
|
+
featurizer (str): path/URL to the feature-extractor ONNX (required).
|
|
40
|
+
model (str): path/URL to the classifier-head ONNX (required).
|
|
41
|
+
vad (str): optional path/URL to a VAD ONNX (extra channel).
|
|
42
|
+
threshold (float): detection threshold, default 0.5.
|
|
43
|
+
smoothing (str): ``"ema"`` | ``"mean"`` | ``"max"``, default ``"ema"``.
|
|
44
|
+
patience (int): consecutive above-threshold frames to fire, default 3.
|
|
45
|
+
debounce_sec (float): minimum seconds between triggers, default 1.0.
|
|
46
|
+
window_size (int): smoother rolling-window size (mean/max), default 5.
|
|
47
|
+
ema_alpha (float): EMA responsiveness, default 0.3.
|
|
48
|
+
streaming (bool): use the stateful streaming head (GRU), default False.
|
|
49
|
+
gru_window (int): window the streaming head was exported with, default 100.
|
|
50
|
+
hidden_dim (int): GRU hidden size for the streaming head, default 128.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, key_phrase="hey jarvis", config=None):
|
|
54
|
+
super().__init__(key_phrase, config)
|
|
55
|
+
self.trigger_flag = False
|
|
56
|
+
|
|
57
|
+
self.threshold = float(self.config.get("threshold", 0.5))
|
|
58
|
+
self.streaming = bool(self.config.get("streaming", False))
|
|
59
|
+
|
|
60
|
+
featurizer = self.config.get("featurizer")
|
|
61
|
+
model = self.config.get("model")
|
|
62
|
+
if not featurizer or not model:
|
|
63
|
+
raise ValueError(
|
|
64
|
+
"wakeforge plugin needs both 'featurizer' and 'model' ONNX paths "
|
|
65
|
+
"in the hotword config (train one with `wakeforge-quickstart`)."
|
|
66
|
+
)
|
|
67
|
+
featurizer = self._resolve(featurizer)
|
|
68
|
+
model = self._resolve(model)
|
|
69
|
+
vad = self.config.get("vad")
|
|
70
|
+
vad = self._resolve(vad) if vad else None
|
|
71
|
+
|
|
72
|
+
self.smoother = PredictionSmoother(
|
|
73
|
+
method=self.config.get("smoothing", "ema"),
|
|
74
|
+
window_size=int(self.config.get("window_size", 5)),
|
|
75
|
+
threshold=self.threshold,
|
|
76
|
+
patience=int(self.config.get("patience", 3)),
|
|
77
|
+
debounce_sec=float(self.config.get("debounce_sec", 1.0)),
|
|
78
|
+
ema_alpha=float(self.config.get("ema_alpha", 0.3)),
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
if self.streaming:
|
|
82
|
+
self.engine = OnnxStreamingWakeWord(
|
|
83
|
+
featurizer, model,
|
|
84
|
+
window=int(self.config.get("gru_window", 100)),
|
|
85
|
+
hidden_dim=int(self.config.get("hidden_dim", 128)),
|
|
86
|
+
)
|
|
87
|
+
else:
|
|
88
|
+
self.engine = OnnxWakeWordInferencer(featurizer, model, vad_path=vad,
|
|
89
|
+
device="cpu")
|
|
90
|
+
self._cache = None
|
|
91
|
+
LOG.info(f"wakeforge wake word '{self.key_phrase}' loaded "
|
|
92
|
+
f"(streaming={self.streaming}, threshold={self.threshold})")
|
|
93
|
+
|
|
94
|
+
def _resolve(self, model):
|
|
95
|
+
"""Resolve a model reference to a local file path, downloading URLs."""
|
|
96
|
+
if model.startswith("http"):
|
|
97
|
+
return self.download_model(model)
|
|
98
|
+
path = expanduser(model)
|
|
99
|
+
if not isfile(path):
|
|
100
|
+
raise ValueError(f"Model not found: {path}")
|
|
101
|
+
return path
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def download_model(url):
|
|
105
|
+
"""Download an ONNX model to the XDG data dir (cached) and return its path."""
|
|
106
|
+
name = url.split("/")[-1]
|
|
107
|
+
folder = join(xdg_data_home(), "wakeforge")
|
|
108
|
+
model_path = join(folder, name)
|
|
109
|
+
if not isfile(model_path):
|
|
110
|
+
LOG.info(f"Downloading wakeforge ONNX model: {url}")
|
|
111
|
+
response = requests.get(url)
|
|
112
|
+
response.raise_for_status()
|
|
113
|
+
makedirs(folder, exist_ok=True)
|
|
114
|
+
with open(model_path, "wb") as f:
|
|
115
|
+
f.write(response.content)
|
|
116
|
+
LOG.info(f"Model downloaded to {model_path}")
|
|
117
|
+
return model_path
|
|
118
|
+
|
|
119
|
+
def update(self, chunk):
|
|
120
|
+
"""Process a raw 16-bit PCM chunk and update the trigger flag."""
|
|
121
|
+
audio = np.frombuffer(chunk, dtype=np.int16).astype(np.float32) / 32768.0
|
|
122
|
+
if audio.size == 0:
|
|
123
|
+
return
|
|
124
|
+
if self.streaming:
|
|
125
|
+
prob = self.engine.push(audio)
|
|
126
|
+
self.smoother.update(prob)
|
|
127
|
+
else:
|
|
128
|
+
_, self._cache = self.engine.infer_streaming(
|
|
129
|
+
audio, self._cache, smoother=self.smoother)
|
|
130
|
+
if self.smoother.is_triggered():
|
|
131
|
+
self.trigger_flag = True
|
|
132
|
+
|
|
133
|
+
def found_wake_word(self):
|
|
134
|
+
"""Return True (once) if the wake word fired since the last call."""
|
|
135
|
+
if self.trigger_flag:
|
|
136
|
+
self.trigger_flag = False
|
|
137
|
+
self.reset()
|
|
138
|
+
return True
|
|
139
|
+
return False
|
|
140
|
+
|
|
141
|
+
def reset(self):
|
|
142
|
+
"""Clear streaming/smoothing state between detections."""
|
|
143
|
+
self.smoother.reset()
|
|
144
|
+
self._cache = None
|
|
145
|
+
if self.streaming:
|
|
146
|
+
self.engine.reset()
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
# Vendored from wakeforge/inference.py (https://github.com/TigreGotico/wakeforge).
|
|
2
|
+
# wakeforge is the source of truth — keep this copy in sync on runtime changes.
|
|
3
|
+
# Pure runtime: numpy + onnxruntime only, no torch.
|
|
4
|
+
"""ONNX-only wake word inference — no PyTorch dependency at runtime."""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
from collections import deque
|
|
9
|
+
from typing import Optional
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import onnxruntime as ort
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PredictionSmoother:
|
|
16
|
+
"""Smooths raw per-frame predictions for robust wake word detection.
|
|
17
|
+
|
|
18
|
+
Inspired by openWakeWord's prediction buffer + patience mechanism
|
|
19
|
+
and EfficientWord-Net's relaxation time.
|
|
20
|
+
|
|
21
|
+
Supports three smoothing methods:
|
|
22
|
+
- ``"ema"``: Exponential moving average (fast response, smooth decay).
|
|
23
|
+
- ``"mean"``: Rolling window mean (stable, uniform weighting).
|
|
24
|
+
- ``"max"``: Rolling window max (aggressive, catches peaks).
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
method: Smoothing method — ``"ema"``, ``"mean"``, or ``"max"``.
|
|
28
|
+
window_size: Number of frames in the rolling buffer (for mean/max).
|
|
29
|
+
threshold: Detection threshold for ``is_triggered()``.
|
|
30
|
+
patience: Number of consecutive above-threshold frames required.
|
|
31
|
+
debounce_sec: Minimum seconds between consecutive triggers.
|
|
32
|
+
frame_rate_hz: Approximate frame rate for debounce timing.
|
|
33
|
+
ema_alpha: Smoothing factor for EMA (default 0.3). Higher = more responsive.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
method: str = "ema",
|
|
39
|
+
window_size: int = 5,
|
|
40
|
+
threshold: float = 0.5,
|
|
41
|
+
patience: int = 3,
|
|
42
|
+
debounce_sec: float = 1.0,
|
|
43
|
+
frame_rate_hz: float = 10.0,
|
|
44
|
+
ema_alpha: float = 0.3,
|
|
45
|
+
) -> None:
|
|
46
|
+
if method not in ("ema", "mean", "max"):
|
|
47
|
+
raise ValueError(f"Unknown smoothing method: {method!r}. Use 'ema', 'mean', or 'max'.")
|
|
48
|
+
self.method = method
|
|
49
|
+
self.window_size = window_size
|
|
50
|
+
self.threshold = threshold
|
|
51
|
+
self.patience = patience
|
|
52
|
+
self.debounce_frames = int(debounce_sec * frame_rate_hz)
|
|
53
|
+
self.ema_alpha = ema_alpha
|
|
54
|
+
|
|
55
|
+
self._buffer: deque = deque(maxlen=window_size)
|
|
56
|
+
self._ema_value: float = 0.0
|
|
57
|
+
self._consecutive_above: int = 0
|
|
58
|
+
self._frames_since_trigger: int = self.debounce_frames # allow first trigger
|
|
59
|
+
self._smoothed: float = 0.0
|
|
60
|
+
|
|
61
|
+
def update(self, raw_prob: float) -> float:
|
|
62
|
+
"""Feed a new raw prediction and return the smoothed value.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
raw_prob: Raw sigmoid probability from model.
|
|
66
|
+
|
|
67
|
+
Returns:
|
|
68
|
+
Smoothed probability.
|
|
69
|
+
"""
|
|
70
|
+
self._frames_since_trigger += 1
|
|
71
|
+
|
|
72
|
+
if self.method == "ema":
|
|
73
|
+
self._ema_value = self.ema_alpha * raw_prob + (1.0 - self.ema_alpha) * self._ema_value
|
|
74
|
+
self._smoothed = self._ema_value
|
|
75
|
+
elif self.method == "mean":
|
|
76
|
+
self._buffer.append(raw_prob)
|
|
77
|
+
self._smoothed = sum(self._buffer) / len(self._buffer)
|
|
78
|
+
elif self.method == "max":
|
|
79
|
+
self._buffer.append(raw_prob)
|
|
80
|
+
self._smoothed = max(self._buffer)
|
|
81
|
+
|
|
82
|
+
if self._smoothed >= self.threshold:
|
|
83
|
+
self._consecutive_above += 1
|
|
84
|
+
else:
|
|
85
|
+
self._consecutive_above = 0
|
|
86
|
+
|
|
87
|
+
return self._smoothed
|
|
88
|
+
|
|
89
|
+
def is_triggered(self) -> bool:
|
|
90
|
+
"""Check if a detection should fire.
|
|
91
|
+
|
|
92
|
+
Returns True when smoothed probability exceeds threshold for
|
|
93
|
+
``patience`` consecutive frames AND debounce window has elapsed.
|
|
94
|
+
|
|
95
|
+
Returns:
|
|
96
|
+
True if wake word detected.
|
|
97
|
+
"""
|
|
98
|
+
if (self._consecutive_above >= self.patience
|
|
99
|
+
and self._frames_since_trigger >= self.debounce_frames):
|
|
100
|
+
self._frames_since_trigger = 0
|
|
101
|
+
self._consecutive_above = 0
|
|
102
|
+
return True
|
|
103
|
+
return False
|
|
104
|
+
|
|
105
|
+
def reset(self) -> None:
|
|
106
|
+
"""Reset smoother state."""
|
|
107
|
+
self._buffer.clear()
|
|
108
|
+
self._ema_value = 0.0
|
|
109
|
+
self._consecutive_above = 0
|
|
110
|
+
self._frames_since_trigger = self.debounce_frames
|
|
111
|
+
self._smoothed = 0.0
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class OnnxWakeWordInferencer:
|
|
115
|
+
"""Run wake word detection using multiple ONNX sessions.
|
|
116
|
+
|
|
117
|
+
This class has no dependency on PyTorch. Only numpy and onnxruntime are required.
|
|
118
|
+
|
|
119
|
+
A text featurizer ONNX can optionally be supplied alongside the audio featurizer.
|
|
120
|
+
When present, :meth:`infer` accepts ``text_token_ids`` and appends the resulting
|
|
121
|
+
text embedding as extra feature channels before running the classifier head —
|
|
122
|
+
exactly the same pattern used for the optional VAD channel.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
extractor_path: Path to the audio feature extractor ONNX file.
|
|
126
|
+
head_path: Path to the classifier head ONNX file.
|
|
127
|
+
vad_path: Optional path to a VAD ONNX file (e.g. Silero VAD).
|
|
128
|
+
text_extractor_path: Optional path to a text-encoder ONNX file.
|
|
129
|
+
The ONNX must accept ``[1, seq_len]`` int64 token IDs and return
|
|
130
|
+
``[1, 1, D]`` or ``[1, D]`` float32 embeddings.
|
|
131
|
+
text_emb_dim: Output embedding dimension of the text featurizer (``D``).
|
|
132
|
+
sample_rate: Expected audio sample rate in Hz (default 16000).
|
|
133
|
+
device: ``"cpu"``, ``"cuda"``, or ``"auto"`` (selects CUDA if available).
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
def __init__(self, extractor_path: str, head_path: str,
|
|
137
|
+
vad_path: Optional[str] = None,
|
|
138
|
+
text_extractor_path: Optional[str] = None,
|
|
139
|
+
text_emb_dim: int = 128,
|
|
140
|
+
sample_rate: int = 16000, device: str = "auto") -> None:
|
|
141
|
+
if device == "auto":
|
|
142
|
+
available = ort.get_available_providers()
|
|
143
|
+
device = "cuda" if "CUDAExecutionProvider" in available else "cpu"
|
|
144
|
+
providers = (["CUDAExecutionProvider", "CPUExecutionProvider"]
|
|
145
|
+
if device == "cuda" else ["CPUExecutionProvider"])
|
|
146
|
+
self.extractor = ort.InferenceSession(extractor_path, providers=providers)
|
|
147
|
+
self.head = ort.InferenceSession(head_path, providers=providers)
|
|
148
|
+
self.vad = ort.InferenceSession(vad_path, providers=providers) if vad_path else None
|
|
149
|
+
self.text_ext = (
|
|
150
|
+
ort.InferenceSession(text_extractor_path, providers=providers)
|
|
151
|
+
if text_extractor_path else None
|
|
152
|
+
)
|
|
153
|
+
self._text_emb_dim = text_emb_dim
|
|
154
|
+
self.sample_rate = sample_rate
|
|
155
|
+
|
|
156
|
+
self._ext_input = self.extractor.get_inputs()[0].name
|
|
157
|
+
self._ext_output = self.extractor.get_outputs()[0].name
|
|
158
|
+
self._head_input = self.head.get_inputs()[0].name
|
|
159
|
+
self._head_output = self.head.get_outputs()[0].name
|
|
160
|
+
|
|
161
|
+
if self.vad:
|
|
162
|
+
self._vad_input = self.vad.get_inputs()[0].name
|
|
163
|
+
self._vad_output = self.vad.get_outputs()[0].name
|
|
164
|
+
if self.text_ext:
|
|
165
|
+
self._text_input = self.text_ext.get_inputs()[0].name
|
|
166
|
+
self._text_output = self.text_ext.get_outputs()[0].name
|
|
167
|
+
|
|
168
|
+
def _run_text(self, token_ids: "list[int]", target_t: int) -> np.ndarray:
|
|
169
|
+
"""Encode token IDs and expand to ``[1, target_t, D]``."""
|
|
170
|
+
ids = np.array([token_ids], dtype=np.int64) # [1, seq_len]
|
|
171
|
+
out = self.text_ext.run([self._text_output], {self._text_input: ids})[0]
|
|
172
|
+
# out may be [1, 1, D] or [1, D]
|
|
173
|
+
if out.ndim == 2:
|
|
174
|
+
out = out[:, np.newaxis, :] # [1, 1, D]
|
|
175
|
+
return np.repeat(out, target_t, axis=1) # [1, target_t, D]
|
|
176
|
+
|
|
177
|
+
def _run_vad(self, wav: np.ndarray, target_t: int) -> np.ndarray:
|
|
178
|
+
"""Run VAD and interpolate to match target time dimension."""
|
|
179
|
+
# Silero VAD (v4+) specific: expects 512 sample chunks
|
|
180
|
+
chunk_size = 512
|
|
181
|
+
B, L = wav.shape
|
|
182
|
+
# Pad to multiple of chunk_size
|
|
183
|
+
pad_len = (chunk_size - (L % chunk_size)) % chunk_size
|
|
184
|
+
if pad_len > 0:
|
|
185
|
+
wav = np.pad(wav, ((0, 0), (0, pad_len)))
|
|
186
|
+
|
|
187
|
+
L_padded = wav.shape[1]
|
|
188
|
+
T_chunks = L_padded // chunk_size
|
|
189
|
+
|
|
190
|
+
# Reshape to batch of chunks
|
|
191
|
+
chunks = wav.reshape(B * T_chunks, chunk_size)
|
|
192
|
+
|
|
193
|
+
# Run VAD
|
|
194
|
+
# Note: some Silero versions expect [B, L] or [B, T, 512].
|
|
195
|
+
# We assume [B_total, 512] for consistency with the feats.py wrapper.
|
|
196
|
+
vad_out = self.vad.run([self._vad_output], {self._vad_input: chunks})[0]
|
|
197
|
+
# [B * T_chunks, 1]
|
|
198
|
+
vad_probs = vad_out.reshape(B, T_chunks, 1)
|
|
199
|
+
|
|
200
|
+
if T_chunks == target_t:
|
|
201
|
+
return vad_probs
|
|
202
|
+
|
|
203
|
+
# Linear interpolation to match base feature length
|
|
204
|
+
# [B, T_chunks, 1] -> [B, target_t, 1]
|
|
205
|
+
x = np.linspace(0, 1, T_chunks)
|
|
206
|
+
x_new = np.linspace(0, 1, target_t)
|
|
207
|
+
|
|
208
|
+
aligned = np.zeros((B, target_t, 1), dtype=np.float32)
|
|
209
|
+
for b in range(B):
|
|
210
|
+
# numpy.interp expects 1D arrays
|
|
211
|
+
aligned[b, :, 0] = np.interp(x_new, x, vad_probs[b, :, 0])
|
|
212
|
+
|
|
213
|
+
return aligned
|
|
214
|
+
|
|
215
|
+
def infer(self, audio: np.ndarray,
|
|
216
|
+
text_token_ids: "Optional[list[int]]" = None) -> float:
|
|
217
|
+
"""Infer wake word probability for a single audio waveform.
|
|
218
|
+
|
|
219
|
+
Args:
|
|
220
|
+
audio: 1-D float32 numpy array at ``self.sample_rate``.
|
|
221
|
+
text_token_ids: Optional list of integer token IDs for the keyword.
|
|
222
|
+
Required when ``text_extractor_path`` was supplied at init.
|
|
223
|
+
The token scheme must match whatever the text-encoder ONNX expects.
|
|
224
|
+
|
|
225
|
+
Returns:
|
|
226
|
+
Sigmoid probability in [0, 1].
|
|
227
|
+
"""
|
|
228
|
+
if audio.ndim != 1:
|
|
229
|
+
raise ValueError("audio must be a 1-D numpy array")
|
|
230
|
+
wav = audio[np.newaxis, :].astype(np.float32) # [1, T]
|
|
231
|
+
feats = self.extractor.run(
|
|
232
|
+
[self._ext_output], {self._ext_input: wav}
|
|
233
|
+
)[0] # [1, T, F]
|
|
234
|
+
|
|
235
|
+
if self.vad:
|
|
236
|
+
vad_probs = self._run_vad(wav, feats.shape[1])
|
|
237
|
+
feats = np.concatenate([feats, vad_probs], axis=-1)
|
|
238
|
+
|
|
239
|
+
if self.text_ext is not None and text_token_ids is not None:
|
|
240
|
+
text_feats = self._run_text(text_token_ids, feats.shape[1])
|
|
241
|
+
feats = np.concatenate([feats, text_feats], axis=-1) # [1, T, F+D]
|
|
242
|
+
|
|
243
|
+
logit = self.head.run(
|
|
244
|
+
[self._head_output], {self._head_input: feats}
|
|
245
|
+
)[0] # [1] or scalar
|
|
246
|
+
logit_val = float(np.asarray(logit).ravel()[0])
|
|
247
|
+
return float(1.0 / (1.0 + np.exp(-logit_val)))
|
|
248
|
+
|
|
249
|
+
def infer_batch(self, audio_batch: np.ndarray,
|
|
250
|
+
text_token_ids: "Optional[list[int]]" = None) -> np.ndarray:
|
|
251
|
+
"""Infer for a batch of equal-length waveforms.
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
audio_batch: float32 array of shape ``[B, T]``.
|
|
255
|
+
text_token_ids: Optional token IDs shared across the batch.
|
|
256
|
+
|
|
257
|
+
Returns:
|
|
258
|
+
Sigmoid probabilities array of shape ``[B]``.
|
|
259
|
+
"""
|
|
260
|
+
if audio_batch.ndim != 2:
|
|
261
|
+
raise ValueError("audio_batch must be a 2-D numpy array [B, T]")
|
|
262
|
+
wav = audio_batch.astype(np.float32)
|
|
263
|
+
feats = self.extractor.run([self._ext_output], {self._ext_input: wav})[0]
|
|
264
|
+
|
|
265
|
+
if self.vad:
|
|
266
|
+
vad_probs = self._run_vad(wav, feats.shape[1])
|
|
267
|
+
feats = np.concatenate([feats, vad_probs], axis=-1)
|
|
268
|
+
|
|
269
|
+
if self.text_ext is not None and text_token_ids is not None:
|
|
270
|
+
B = feats.shape[0]
|
|
271
|
+
text_feats = self._run_text(text_token_ids, feats.shape[1]) # [1, T, D]
|
|
272
|
+
text_feats = np.repeat(text_feats, B, axis=0) # [B, T, D]
|
|
273
|
+
feats = np.concatenate([feats, text_feats], axis=-1)
|
|
274
|
+
|
|
275
|
+
logits = self.head.run([self._head_output], {self._head_input: feats})[0]
|
|
276
|
+
logits = np.asarray(logits).ravel()
|
|
277
|
+
return (1.0 / (1.0 + np.exp(-logits))).astype(np.float32)
|
|
278
|
+
|
|
279
|
+
def infer_streaming(self, audio_chunk: np.ndarray,
|
|
280
|
+
cache: np.ndarray | None,
|
|
281
|
+
smoother: Optional[PredictionSmoother] = None,
|
|
282
|
+
) -> tuple[float, np.ndarray]:
|
|
283
|
+
"""Process one audio chunk with a rolling feature cache.
|
|
284
|
+
|
|
285
|
+
Args:
|
|
286
|
+
audio_chunk: 1-D float32 array (one chunk of audio).
|
|
287
|
+
cache: Previous feature cache [T_cached, F] or None for first call.
|
|
288
|
+
smoother: Optional PredictionSmoother for temporal smoothing.
|
|
289
|
+
|
|
290
|
+
Returns:
|
|
291
|
+
(probability, updated_cache) — probability is smoothed if
|
|
292
|
+
smoother is provided, raw otherwise.
|
|
293
|
+
"""
|
|
294
|
+
wav = audio_chunk[np.newaxis, :].astype(np.float32) # [1, T_chunk]
|
|
295
|
+
new_feats = self.extractor.run(
|
|
296
|
+
[self._ext_output], {self._ext_input: wav}
|
|
297
|
+
)[0] # [1, T_new, F]
|
|
298
|
+
|
|
299
|
+
if self.vad:
|
|
300
|
+
vad_probs = self._run_vad(wav, new_feats.shape[1])
|
|
301
|
+
new_feats = np.concatenate([new_feats, vad_probs], axis=-1)
|
|
302
|
+
|
|
303
|
+
new_feats = new_feats.squeeze(0) # [T_new, F_total]
|
|
304
|
+
|
|
305
|
+
if cache is None:
|
|
306
|
+
cache = new_feats
|
|
307
|
+
else:
|
|
308
|
+
cache = np.concatenate([cache, new_feats], axis=0)
|
|
309
|
+
|
|
310
|
+
# Keep last 50 frames (matching SlidingFeatureCacheTensor default)
|
|
311
|
+
window = 50
|
|
312
|
+
if cache.shape[0] > window:
|
|
313
|
+
cache = cache[-window:]
|
|
314
|
+
|
|
315
|
+
feats_input = cache[np.newaxis, :, :] # [1, T_cached, F]
|
|
316
|
+
logit = self.head.run(
|
|
317
|
+
[self._head_output], {self._head_input: feats_input}
|
|
318
|
+
)[0]
|
|
319
|
+
logit_val = float(np.asarray(logit).ravel()[0])
|
|
320
|
+
prob = float(1.0 / (1.0 + np.exp(-logit_val)))
|
|
321
|
+
if smoother is not None:
|
|
322
|
+
prob = smoother.update(prob)
|
|
323
|
+
return prob, cache
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
class OnnxStreamingWakeWord:
|
|
327
|
+
"""Stateful streaming wake-word inference — ONNX only, O(chunk) per step.
|
|
328
|
+
|
|
329
|
+
Pairs a featurizer ONNX with a *streaming* head ONNX exported via
|
|
330
|
+
:meth:`wakeforge.model.GruClassifierHead.export_streaming_onnx`. Unlike
|
|
331
|
+
:meth:`OnnxWakeWordInferencer.infer_streaming` (which re-runs the head over a
|
|
332
|
+
cached feature window each call), this carries the GRU hidden state and a
|
|
333
|
+
sliding window of GRU outputs as model state, so the head never recomputes
|
|
334
|
+
history — the always-on / MCU pattern. No PyTorch at runtime.
|
|
335
|
+
|
|
336
|
+
Usage::
|
|
337
|
+
|
|
338
|
+
sw = OnnxStreamingWakeWord("feat.onnx", "head_streaming.onnx")
|
|
339
|
+
for chunk in audio_chunks: # e.g. 0.1 s of 16 kHz audio
|
|
340
|
+
prob = sw.push(chunk)
|
|
341
|
+
|
|
342
|
+
Args:
|
|
343
|
+
featurizer_path: Feature extractor ONNX.
|
|
344
|
+
streaming_head_path: Streaming head ONNX (state I/O).
|
|
345
|
+
window: GRU-output window length the head was exported with.
|
|
346
|
+
hidden_dim: GRU hidden size of the head.
|
|
347
|
+
"""
|
|
348
|
+
|
|
349
|
+
def __init__(self, featurizer_path: str, streaming_head_path: str,
|
|
350
|
+
window: int = 100, hidden_dim: int = 128,
|
|
351
|
+
hop_samples: int = 160, context_samples: int = 640) -> None:
|
|
352
|
+
providers = ["CPUExecutionProvider"]
|
|
353
|
+
self.ext = ort.InferenceSession(featurizer_path, providers=providers)
|
|
354
|
+
self.head = ort.InferenceSession(streaming_head_path, providers=providers)
|
|
355
|
+
self._ext_in = self.ext.get_inputs()[0].name
|
|
356
|
+
self._ext_out = self.ext.get_outputs()[0].name
|
|
357
|
+
self.window = window
|
|
358
|
+
self.hidden_dim = hidden_dim
|
|
359
|
+
self.hop = hop_samples # featurizer hop (for frame accounting)
|
|
360
|
+
self.context = context_samples # left-context carried for clean MFCC
|
|
361
|
+
self.reset()
|
|
362
|
+
|
|
363
|
+
def reset(self) -> None:
|
|
364
|
+
"""Clear the carried GRU state and audio context (call between utterances)."""
|
|
365
|
+
self._h = np.zeros((1, 1, self.hidden_dim), dtype=np.float32)
|
|
366
|
+
self._ow = np.zeros((1, self.window, self.hidden_dim), dtype=np.float32)
|
|
367
|
+
self._ctx = np.zeros(0, dtype=np.float32)
|
|
368
|
+
|
|
369
|
+
def push(self, audio_chunk: np.ndarray) -> float:
|
|
370
|
+
"""Feed one audio chunk, advance state frame-by-frame, return the score.
|
|
371
|
+
|
|
372
|
+
The chunk is featurized *with* a left-context tail from the previous
|
|
373
|
+
call so MFCC frames are computed with proper context (avoiding chunk-edge
|
|
374
|
+
artifacts); only the frames belonging to the new audio are streamed
|
|
375
|
+
through the stateful head (O(1) per frame). Returns the sigmoid
|
|
376
|
+
probability after the last new frame.
|
|
377
|
+
"""
|
|
378
|
+
chunk = audio_chunk.astype(np.float32)
|
|
379
|
+
buf = np.concatenate([self._ctx, chunk])
|
|
380
|
+
wav = buf[np.newaxis, :]
|
|
381
|
+
feats = self.ext.run([self._ext_out], {self._ext_in: wav})[0] # [1, T, F]
|
|
382
|
+
# Frames attributable to the new chunk (the rest came from context).
|
|
383
|
+
n_new = max(1, int(round(len(chunk) / self.hop)))
|
|
384
|
+
n_new = min(n_new, feats.shape[1])
|
|
385
|
+
self._ctx = buf[-self.context:] if self.context else np.zeros(0, dtype=np.float32)
|
|
386
|
+
logit_val = 0.0
|
|
387
|
+
for t in range(feats.shape[1] - n_new, feats.shape[1]):
|
|
388
|
+
frame = feats[:, t:t + 1, :].astype(np.float32)
|
|
389
|
+
logit, self._h, self._ow = self.head.run(
|
|
390
|
+
None, {"feat_frame": frame, "h_in": self._h, "out_window": self._ow})
|
|
391
|
+
logit_val = float(np.asarray(logit).ravel()[0])
|
|
392
|
+
return float(1.0 / (1.0 + np.exp(-logit_val)))
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def cli_main() -> None:
|
|
396
|
+
"""CLI entry point for ``wakeforge-infer``.
|
|
397
|
+
|
|
398
|
+
Run a trained ONNX wake-word model on an audio file and print the
|
|
399
|
+
confidence score.
|
|
400
|
+
"""
|
|
401
|
+
import argparse
|
|
402
|
+
import logging
|
|
403
|
+
import sys
|
|
404
|
+
|
|
405
|
+
import numpy as np
|
|
406
|
+
|
|
407
|
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
|
|
408
|
+
|
|
409
|
+
parser = argparse.ArgumentParser(
|
|
410
|
+
prog="wakeforge-infer",
|
|
411
|
+
description="Score an audio file with a trained ONNX wake-word model.",
|
|
412
|
+
)
|
|
413
|
+
parser.add_argument("--featurizer", required=True, help="Path to featurizer ONNX file.")
|
|
414
|
+
parser.add_argument("--model", required=True, help="Path to head ONNX file.")
|
|
415
|
+
parser.add_argument("--audio", required=True, help="Path to WAV file (16 kHz mono float32).")
|
|
416
|
+
parser.add_argument("--threshold", type=float, default=0.5, help="Detection threshold (default 0.5).")
|
|
417
|
+
parser.add_argument("--device", default="auto", choices=["auto", "cpu", "cuda"])
|
|
418
|
+
args = parser.parse_args()
|
|
419
|
+
|
|
420
|
+
try:
|
|
421
|
+
import soundfile as sf
|
|
422
|
+
except ImportError:
|
|
423
|
+
try:
|
|
424
|
+
import torchaudio
|
|
425
|
+
wav, sr = torchaudio.load(args.audio)
|
|
426
|
+
if sr != 16000:
|
|
427
|
+
import torchaudio.functional as F_ta
|
|
428
|
+
wav = F_ta.resample(wav, sr, 16000)
|
|
429
|
+
audio = wav.squeeze().numpy().astype(np.float32)
|
|
430
|
+
except ImportError:
|
|
431
|
+
print("Install soundfile or torchaudio to load audio files.", file=sys.stderr)
|
|
432
|
+
sys.exit(1)
|
|
433
|
+
else:
|
|
434
|
+
audio, sr = sf.read(args.audio, dtype="float32", always_2d=False)
|
|
435
|
+
if sr != 16000:
|
|
436
|
+
print(f"Warning: sample rate is {sr} Hz, expected 16000.", file=sys.stderr)
|
|
437
|
+
|
|
438
|
+
model = OnnxWakeWordInferencer(args.featurizer, args.model, device=args.device)
|
|
439
|
+
score = model.infer(audio)
|
|
440
|
+
detected = score >= args.threshold
|
|
441
|
+
print(f"score={score:.4f} threshold={args.threshold} detected={detected}")
|
|
442
|
+
sys.exit(0 if detected else 1)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
if __name__ == "__main__":
|
|
446
|
+
cli_main()
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# START_VERSION_BLOCK
|
|
2
|
+
VERSION_MAJOR = 0
|
|
3
|
+
VERSION_MINOR = 0
|
|
4
|
+
VERSION_BUILD = 1
|
|
5
|
+
VERSION_ALPHA = 2
|
|
6
|
+
# END_VERSION_BLOCK
|
|
7
|
+
__version__ = f"{VERSION_MAJOR}.{VERSION_MINOR}.{VERSION_BUILD}a{VERSION_ALPHA}" if VERSION_ALPHA else f"{VERSION_MAJOR}.{VERSION_MINOR}.{VERSION_BUILD}"
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ovos-ww-plugin-wakeforge
|
|
3
|
+
Version: 0.0.1a2
|
|
4
|
+
Summary: OVOS wake word plugin for models trained with wakeforge
|
|
5
|
+
Author-email: JarbasAi <jarbasai@mailfence.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/OpenVoiceOS/ovos-ww-plugin-wakeforge
|
|
8
|
+
Project-URL: Repository, https://github.com/OpenVoiceOS/ovos-ww-plugin-wakeforge
|
|
9
|
+
Keywords: mycroft,ovos,plugin,wake,word,wakeforge
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: onnxruntime>=1.20
|
|
14
|
+
Requires-Dist: numpy
|
|
15
|
+
Requires-Dist: requests
|
|
16
|
+
Requires-Dist: ovos-plugin-manager<3.0.0,>=2.1.0
|
|
17
|
+
Requires-Dist: ovos-utils<1.0.0,>=0.0.14
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest<9; extra == "test"
|
|
20
|
+
Requires-Dist: onnx; extra == "test"
|
|
21
|
+
Requires-Dist: ovoscope<1.0.0,>=0.19.0a1; extra == "test"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# ovos-ww-plugin-wakeforge
|
|
25
|
+
|
|
26
|
+
An OVOS wake-word plugin for custom models trained with
|
|
27
|
+
[wakeforge](https://github.com/TigreGotico/wakeforge).
|
|
28
|
+
|
|
29
|
+
Wakeforge trains a wake-word detector from a single phrase and exports a two-file
|
|
30
|
+
ONNX pipeline: a feature extractor and a classifier head. This plugin loads that
|
|
31
|
+
pipeline and runs it as an always-on hotword engine. The runtime uses
|
|
32
|
+
`onnxruntime` and `numpy` only. It does not need PyTorch.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install ovos-ww-plugin-wakeforge
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Train a model
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install wakeforge
|
|
44
|
+
wakeforge-quickstart "hey jarvis" ./hey_jarvis
|
|
45
|
+
# → ./hey_jarvis/best_f1_featurizer.onnx + ./hey_jarvis/best_f1.onnx
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Configure
|
|
49
|
+
|
|
50
|
+
In `mycroft.conf`, point a hotword at the two ONNX files. Use local paths or URLs.
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{
|
|
54
|
+
"listener": {
|
|
55
|
+
"wake_word": "hey_jarvis"
|
|
56
|
+
},
|
|
57
|
+
"hotwords": {
|
|
58
|
+
"hey_jarvis": {
|
|
59
|
+
"module": "ovos-ww-plugin-wakeforge",
|
|
60
|
+
"listen": true,
|
|
61
|
+
"featurizer": "~/hey_jarvis/best_f1_featurizer.onnx",
|
|
62
|
+
"model": "~/hey_jarvis/best_f1.onnx",
|
|
63
|
+
"threshold": 0.5
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Config keys
|
|
70
|
+
|
|
71
|
+
| key | default | description |
|
|
72
|
+
|-----|---------|-------------|
|
|
73
|
+
| `featurizer` | — (required) | feature-extractor ONNX (path or URL) |
|
|
74
|
+
| `model` | — (required) | classifier-head ONNX (path or URL) |
|
|
75
|
+
| `vad` | none | optional VAD ONNX for an extra channel |
|
|
76
|
+
| `threshold` | `0.5` | detection threshold |
|
|
77
|
+
| `smoothing` | `ema` | `ema` \| `mean` \| `max` |
|
|
78
|
+
| `patience` | `3` | consecutive above-threshold frames to fire |
|
|
79
|
+
| `debounce_sec` | `1.0` | minimum seconds between triggers |
|
|
80
|
+
| `window_size` | `5` | smoother rolling window (mean/max) |
|
|
81
|
+
| `ema_alpha` | `0.3` | EMA responsiveness |
|
|
82
|
+
| `streaming` | `false` | use the stateful streaming (GRU) head |
|
|
83
|
+
| `gru_window` | `100` | window the streaming head was exported with |
|
|
84
|
+
| `hidden_dim` | `128` | GRU hidden size of the streaming head |
|
|
85
|
+
|
|
86
|
+
URL models are cached under `${XDG_DATA_HOME}/wakeforge/`.
|
|
87
|
+
|
|
88
|
+
## Related projects
|
|
89
|
+
|
|
90
|
+
- [TigreGotico/wakeforge](https://github.com/TigreGotico/wakeforge) trains the ONNX models this plugin loads.
|
|
91
|
+
- [OpenVoiceOS/ovos-plugin-manager](https://github.com/OpenVoiceOS/ovos-plugin-manager) loads and manages this plugin alongside other STT, TTS, and wake-word plugins.
|
|
92
|
+
- [OpenVoiceOS/ovos-ww-plugin-precise-onnx](https://github.com/OpenVoiceOS/ovos-ww-plugin-precise-onnx) is a sibling wake-word plugin that runs Precise models through ONNX.
|
|
93
|
+
|
|
94
|
+
## Credits
|
|
95
|
+
|
|
96
|
+
Developed by [TigreGótico](https://tigregotico.pt) for
|
|
97
|
+
[OpenVoiceOS](https://openvoiceos.org).
|
|
98
|
+
|
|
99
|
+
[](https://nlnet.nl/project/OpenVoiceOS)
|
|
100
|
+
|
|
101
|
+
This project was funded through the [NGI0 Commons Fund](https://nlnet.nl/commonsfund),
|
|
102
|
+
a fund established by [NLnet](https://nlnet.nl) with financial support from the
|
|
103
|
+
European Commission's [Next Generation Internet](https://ngi.eu) programme, under
|
|
104
|
+
the aegis of [DG Communications Networks, Content and Technology](https://commission.europa.eu/about-european-commission/departments-and-executive-agencies/communications-networks-content-and-technology_en)
|
|
105
|
+
under grant agreement No [101135429](https://cordis.europa.eu/project/id/101135429).
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
Apache-2.0
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
ovos_ww_plugin_wakeforge/__init__.py
|
|
5
|
+
ovos_ww_plugin_wakeforge/inference.py
|
|
6
|
+
ovos_ww_plugin_wakeforge/version.py
|
|
7
|
+
ovos_ww_plugin_wakeforge.egg-info/PKG-INFO
|
|
8
|
+
ovos_ww_plugin_wakeforge.egg-info/SOURCES.txt
|
|
9
|
+
ovos_ww_plugin_wakeforge.egg-info/dependency_links.txt
|
|
10
|
+
ovos_ww_plugin_wakeforge.egg-info/entry_points.txt
|
|
11
|
+
ovos_ww_plugin_wakeforge.egg-info/requires.txt
|
|
12
|
+
ovos_ww_plugin_wakeforge.egg-info/top_level.txt
|
|
13
|
+
test/test_wakeforge.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ovos_ww_plugin_wakeforge
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ovos-ww-plugin-wakeforge"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "OVOS wake word plugin for models trained with wakeforge"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
authors = [{name = "JarbasAi", email = "jarbasai@mailfence.com"}]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
|
|
14
|
+
keywords = [
|
|
15
|
+
"mycroft",
|
|
16
|
+
"ovos",
|
|
17
|
+
"plugin",
|
|
18
|
+
"wake",
|
|
19
|
+
"word",
|
|
20
|
+
"wakeforge",
|
|
21
|
+
]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"onnxruntime>=1.20",
|
|
24
|
+
"numpy",
|
|
25
|
+
"requests",
|
|
26
|
+
"ovos-plugin-manager>=2.1.0,<3.0.0",
|
|
27
|
+
"ovos-utils>=0.0.14,<1.0.0",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
test = [
|
|
32
|
+
"pytest<9",
|
|
33
|
+
"onnx",
|
|
34
|
+
"ovoscope>=0.19.0a1,<1.0.0",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
[project.urls]
|
|
38
|
+
Homepage = "https://github.com/OpenVoiceOS/ovos-ww-plugin-wakeforge"
|
|
39
|
+
Repository = "https://github.com/OpenVoiceOS/ovos-ww-plugin-wakeforge"
|
|
40
|
+
|
|
41
|
+
[project.entry-points."opm.wake_word"]
|
|
42
|
+
ovos-ww-plugin-wakeforge = "ovos_ww_plugin_wakeforge:WakeForgeHotwordPlugin"
|
|
43
|
+
|
|
44
|
+
[tool.setuptools]
|
|
45
|
+
include-package-data = true
|
|
46
|
+
|
|
47
|
+
[tool.setuptools.packages.find]
|
|
48
|
+
include = ["ovos_ww_plugin_wakeforge*"]
|
|
49
|
+
|
|
50
|
+
[tool.setuptools.dynamic]
|
|
51
|
+
version = {attr = "ovos_ww_plugin_wakeforge.version.__version__"}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Functional tests for ovos-ww-plugin-wakeforge.
|
|
2
|
+
|
|
3
|
+
A real trained wakeforge model is large and language/phrase specific, so these
|
|
4
|
+
tests synthesise a tiny two-file ONNX pipeline (featurizer + energy head) and
|
|
5
|
+
drive the plugin through the real onnxruntime sessions. This exercises the full
|
|
6
|
+
plumbing — PCM decode, feature cache, smoothing, trigger/reset — without torch
|
|
7
|
+
or a downloaded model.
|
|
8
|
+
|
|
9
|
+
The synthetic head fires on high-energy audio and stays quiet on silence, so the
|
|
10
|
+
detection assertions are deterministic.
|
|
11
|
+
"""
|
|
12
|
+
import numpy as np
|
|
13
|
+
import onnx
|
|
14
|
+
import pytest
|
|
15
|
+
from onnx import TensorProto, helper, numpy_helper
|
|
16
|
+
|
|
17
|
+
from ovos_ww_plugin_wakeforge import WakeForgeHotwordPlugin
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _build_featurizer(path):
|
|
21
|
+
"""audio [1, T] float32 -> feats [1, T, 1] float32 (Unsqueeze on axis 2)."""
|
|
22
|
+
axes = numpy_helper.from_array(np.array([2], dtype=np.int64), name="axes")
|
|
23
|
+
node = helper.make_node("Unsqueeze", ["audio", "axes"], ["feats"])
|
|
24
|
+
graph = helper.make_graph(
|
|
25
|
+
[node], "featurizer",
|
|
26
|
+
inputs=[helper.make_tensor_value_info("audio", TensorProto.FLOAT, [1, "T"])],
|
|
27
|
+
outputs=[helper.make_tensor_value_info("feats", TensorProto.FLOAT, [1, "T", 1])],
|
|
28
|
+
initializer=[axes],
|
|
29
|
+
)
|
|
30
|
+
model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
|
|
31
|
+
onnx.save(model, path)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _build_head(path):
|
|
35
|
+
"""feats [1, T, 1] -> logit [1] = mean(|feats|) * 40 - 4 (energy detector)."""
|
|
36
|
+
scale = numpy_helper.from_array(np.array(40.0, dtype=np.float32), name="scale")
|
|
37
|
+
bias = numpy_helper.from_array(np.array(4.0, dtype=np.float32), name="bias")
|
|
38
|
+
nodes = [
|
|
39
|
+
helper.make_node("Abs", ["feats"], ["a"]),
|
|
40
|
+
helper.make_node("ReduceMean", ["a"], ["m"], axes=[1, 2], keepdims=0),
|
|
41
|
+
helper.make_node("Mul", ["m", "scale"], ["s"]),
|
|
42
|
+
helper.make_node("Sub", ["s", "bias"], ["logit"]),
|
|
43
|
+
]
|
|
44
|
+
graph = helper.make_graph(
|
|
45
|
+
nodes, "head",
|
|
46
|
+
inputs=[helper.make_tensor_value_info("feats", TensorProto.FLOAT, [1, "T", 1])],
|
|
47
|
+
outputs=[helper.make_tensor_value_info("logit", TensorProto.FLOAT, [1])],
|
|
48
|
+
initializer=[scale, bias],
|
|
49
|
+
)
|
|
50
|
+
model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 13)])
|
|
51
|
+
onnx.save(model, path)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@pytest.fixture(scope="module")
|
|
55
|
+
def models(tmp_path_factory):
|
|
56
|
+
d = tmp_path_factory.mktemp("wakeforge_models")
|
|
57
|
+
feat, head = str(d / "feat.onnx"), str(d / "head.onnx")
|
|
58
|
+
_build_featurizer(feat)
|
|
59
|
+
_build_head(head)
|
|
60
|
+
return feat, head
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _engine(models, **cfg):
|
|
64
|
+
feat, head = models
|
|
65
|
+
config = {"featurizer": feat, "model": head}
|
|
66
|
+
config.update(cfg)
|
|
67
|
+
return WakeForgeHotwordPlugin(key_phrase="hey jarvis", config=config)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _pcm(value, n=1600):
|
|
71
|
+
"""n int16 samples all set to `value`, as raw little-endian bytes."""
|
|
72
|
+
return (np.full(n, value, dtype=np.int16)).tobytes()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_missing_config_raises(models):
|
|
76
|
+
with pytest.raises(ValueError):
|
|
77
|
+
WakeForgeHotwordPlugin(key_phrase="x", config={})
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_loads(models):
|
|
81
|
+
eng = _engine(models)
|
|
82
|
+
assert eng.engine is not None
|
|
83
|
+
assert not eng.found_wake_word()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_silence_does_not_trigger(models):
|
|
87
|
+
eng = _engine(models)
|
|
88
|
+
for _ in range(10):
|
|
89
|
+
eng.update(_pcm(0))
|
|
90
|
+
assert not eng.found_wake_word()
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_loud_audio_triggers(models):
|
|
94
|
+
eng = _engine(models, patience=3)
|
|
95
|
+
detected = False
|
|
96
|
+
for _ in range(8):
|
|
97
|
+
eng.update(_pcm(16384)) # ~0.5 full-scale -> high energy
|
|
98
|
+
if eng.found_wake_word():
|
|
99
|
+
detected = True
|
|
100
|
+
break
|
|
101
|
+
assert detected, "high-energy audio should fire the synthetic detector"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_found_wake_word_resets(models):
|
|
105
|
+
eng = _engine(models, patience=3)
|
|
106
|
+
for _ in range(8):
|
|
107
|
+
eng.update(_pcm(16384))
|
|
108
|
+
if eng.found_wake_word():
|
|
109
|
+
break
|
|
110
|
+
# consumed once; immediately polling again must be False
|
|
111
|
+
assert not eng.found_wake_word()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_opm_discovery():
|
|
115
|
+
"""Plugin is discoverable through the ovos-plugin-manager entry point."""
|
|
116
|
+
from ovos_plugin_manager.wakewords import find_wake_word_plugins
|
|
117
|
+
assert "ovos-ww-plugin-wakeforge" in find_wake_word_plugins()
|