porcupine.py
Go to the documentation of this file.
1 #
2 # Copyright 2018-2022 Picovoice Inc.
3 #
4 # You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"
5 # file accompanying this source.
6 #
7 # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
8 # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
9 # specific language governing permissions and limitations under the License.
10 #
11 
12 import os
13 from ctypes import *
14 from enum import Enum
15 
16 
17 class PorcupineError(Exception):
18  pass
19 
20 
22  pass
23 
24 
26  pass
27 
28 
30  pass
31 
32 
34  pass
35 
36 
38  pass
39 
40 
42  pass
43 
44 
46  pass
47 
48 
50  pass
51 
52 
54  pass
55 
56 
58  pass
59 
60 
62  pass
63 
64 
65 class Porcupine(object):
66  """
67  Python binding for Porcupine wake word engine. It detects utterances of given keywords within an incoming stream of
68  audio in real-time. It processes incoming audio in consecutive frames and for each frame emits the detection result.
69  The number of samples per frame can be attained by calling `.frame_length`. The incoming audio needs to have a
70  sample rate equal to `.sample_rate` and be 16-bit linearly-encoded. Porcupine operates on single-channel audio.
71  """
72 
73  class PicovoiceStatuses(Enum):
74  SUCCESS = 0
75  OUT_OF_MEMORY = 1
76  IO_ERROR = 2
77  INVALID_ARGUMENT = 3
78  STOP_ITERATION = 4
79  KEY_ERROR = 5
80  INVALID_STATE = 6
81  RUNTIME_ERROR = 7
82  ACTIVATION_ERROR = 8
83  ACTIVATION_LIMIT_REACHED = 9
84  ACTIVATION_THROTTLED = 10
85  ACTIVATION_REFUSED = 11
86 
87  _PICOVOICE_STATUS_TO_EXCEPTION = {
88  PicovoiceStatuses.OUT_OF_MEMORY: PorcupineMemoryError,
89  PicovoiceStatuses.IO_ERROR: PorcupineIOError,
90  PicovoiceStatuses.INVALID_ARGUMENT: PorcupineInvalidArgumentError,
91  PicovoiceStatuses.STOP_ITERATION: PorcupineStopIterationError,
92  PicovoiceStatuses.KEY_ERROR: PorcupineKeyError,
93  PicovoiceStatuses.INVALID_STATE: PorcupineInvalidStateError,
94  PicovoiceStatuses.RUNTIME_ERROR: PorcupineRuntimeError,
95  PicovoiceStatuses.ACTIVATION_ERROR: PorcupineActivationError,
96  PicovoiceStatuses.ACTIVATION_LIMIT_REACHED: PorcupineActivationLimitError,
97  PicovoiceStatuses.ACTIVATION_THROTTLED: PorcupineActivationThrottledError,
98  PicovoiceStatuses.ACTIVATION_REFUSED: PorcupineActivationRefusedError
99  }
100 
101  class CPorcupine(Structure):
102  pass
103 
104  def __init__(self, access_key, library_path, model_path, keyword_paths, sensitivities):
105  """
106  Constructor.
107 
108  :param access_key: AccessKey obtained from Picovoice Console.
109  :param library_path: Absolute path to Porcupine's dynamic library.
110  :param model_path: Absolute path to the file containing model parameters.
111  :param keyword_paths: Absolute paths to keyword model files.
112  :param sensitivities: Sensitivities for detecting keywords. Each value should be a number within [0, 1]. A
113  higher sensitivity results in fewer misses at the cost of increasing the false alarm rate.
114  """
115 
116  if not access_key:
117  raise ValueError("access_key should be a non-empty string.")
118 
119  if not os.path.exists(library_path):
120  raise IOError("Couldn't find Porcupine's dynamic library at '%s'." % library_path)
121 
122  library = cdll.LoadLibrary(library_path)
123 
124  if not os.path.exists(model_path):
125  raise IOError("Couldn't find model file at '%s'." % model_path)
126 
127  if len(keyword_paths) != len(sensitivities):
128  raise ValueError("Number of keywords does not match the number of sensitivities.")
129 
130  for x in keyword_paths:
131  if not os.path.exists(os.path.expanduser(x)):
132  raise IOError("Couldn't find keyword file at '%s'." % x)
133 
134  for x in sensitivities:
135  if not (0 <= x <= 1):
136  raise ValueError('A sensitivity value should be within [0, 1].')
137 
138  init_func = library.pv_porcupine_init
139  init_func.argtypes = [
140  c_char_p,
141  c_char_p,
142  c_int,
143  POINTER(c_char_p),
144  POINTER(c_float),
145  POINTER(POINTER(self.CPorcupine))]
146  init_func.restype = self.PicovoiceStatuses
147 
148  self._handle = POINTER(self.CPorcupine)()
149 
150  status = init_func(
151  access_key.encode('utf-8'),
152  model_path.encode('utf-8'),
153  len(keyword_paths),
154  (c_char_p * len(keyword_paths))(*[os.path.expanduser(x).encode('utf-8') for x in keyword_paths]),
155  (c_float * len(keyword_paths))(*sensitivities),
156  byref(self._handle))
157  if status is not self.PicovoiceStatuses.SUCCESS:
158  raise self._PICOVOICE_STATUS_TO_EXCEPTION[status]()
159 
160  self._delete_func = library.pv_porcupine_delete
161  self._delete_func.argtypes = [POINTER(self.CPorcupine)]
162  self._delete_func.restype = None
163 
164  self.process_func = library.pv_porcupine_process
165  self.process_func.argtypes = [POINTER(self.CPorcupine), POINTER(c_short), POINTER(c_int)]
166  self.process_func.restype = self.PicovoiceStatuses
167 
168  version_func = library.pv_porcupine_version
169  version_func.argtypes = []
170  version_func.restype = c_char_p
171  self._version = version_func().decode('utf-8')
172 
173  self._frame_length = library.pv_porcupine_frame_length()
174 
175  self._sample_rate = library.pv_sample_rate()
176 
177  def delete(self):
178  """Releases resources acquired by Porcupine."""
179 
180  self._delete_func(self._handle)
181 
182  def process(self, pcm):
183  """
184  Processes a frame of the incoming audio stream and emits the detection result.
185 
186  :param pcm: A frame of audio samples. The number of samples per frame can be attained by calling
187  `.frame_length`. The incoming audio needs to have a sample rate equal to `.sample_rate` and be 16-bit
188  linearly-encoded. Porcupine operates on single-channel audio.
189  :return: Index of observed keyword at the end of the current frame. Indexing is 0-based and matches the ordering
190  of keyword models provided to the constructor. If no keyword is detected then it returns -1.
191  """
192 
193  if len(pcm) != self.frame_length:
194  raise ValueError("Invalid frame length. expected %d but received %d" % (self.frame_length, len(pcm)))
195 
196  result = c_int()
197  status = self.process_func(self._handle, (c_short * len(pcm))(*pcm), byref(result))
198  if status is not self.PicovoiceStatuses.SUCCESS:
199  raise self._PICOVOICE_STATUS_TO_EXCEPTION[status]()
200 
201  return result.value
202 
203  @property
204  def version(self):
205  """Version"""
206 
207  return self._version
208 
209  @property
210  def frame_length(self):
211  """Number of audio samples per frame."""
212 
213  return self._frame_length
214 
215  @property
216  def sample_rate(self):
217  """Audio sample rate accepted by Picovoice."""
218 
219  return self._sample_rate
python.porcupine.Porcupine._sample_rate
_sample_rate
Definition: porcupine.py:175
python.porcupine.Porcupine.__init__
def __init__(self, access_key, library_path, model_path, keyword_paths, sensitivities)
Definition: porcupine.py:104
python.porcupine.PorcupineKeyError
Definition: porcupine.py:37
python.porcupine.PorcupineActivationRefusedError
Definition: porcupine.py:61
python.porcupine.Porcupine.CPorcupine
Definition: porcupine.py:101
python.porcupine.Porcupine.sample_rate
def sample_rate(self)
Definition: porcupine.py:216
python.porcupine.Porcupine.PicovoiceStatuses
Definition: porcupine.py:73
python.porcupine.Porcupine._PICOVOICE_STATUS_TO_EXCEPTION
_PICOVOICE_STATUS_TO_EXCEPTION
Definition: porcupine.py:87
python.porcupine.PorcupineInvalidStateError
Definition: porcupine.py:41
python.porcupine.Porcupine.frame_length
def frame_length(self)
Definition: porcupine.py:210
python.porcupine.PorcupineIOError
Definition: porcupine.py:25
python.porcupine.PorcupineActivationError
Definition: porcupine.py:49
python.porcupine.PorcupineRuntimeError
Definition: porcupine.py:45
python.porcupine.PorcupineActivationLimitError
Definition: porcupine.py:53
python.porcupine.Porcupine._delete_func
_delete_func
Definition: porcupine.py:160
python.porcupine.Porcupine.delete
def delete(self)
Definition: porcupine.py:177
python.porcupine.PorcupineError
Definition: porcupine.py:17
python.porcupine.Porcupine._version
_version
Definition: porcupine.py:171
python.porcupine.Porcupine._frame_length
_frame_length
Definition: porcupine.py:173
python.porcupine.PorcupineInvalidArgumentError
Definition: porcupine.py:29
python.porcupine.PorcupineMemoryError
Definition: porcupine.py:21
python.porcupine.Porcupine._handle
_handle
Definition: porcupine.py:148
python.porcupine.PorcupineActivationThrottledError
Definition: porcupine.py:57
python.porcupine.Porcupine.process
def process(self, pcm)
Definition: porcupine.py:182
python.porcupine.Porcupine
Definition: porcupine.py:65
python.porcupine.Porcupine.version
def version(self)
Definition: porcupine.py:204
python.porcupine.PorcupineStopIterationError
Definition: porcupine.py:33
python.porcupine.Porcupine.process_func
process_func
Definition: porcupine.py:164


picovoice_driver
Author(s):
autogenerated on Fri Apr 1 2022 02:14:50