Debian Codegraph @

plyer/platforms/android/stt.py

raw symbols SCIP
1 from android.runnable import run_on_ui_thread
2
3 from jnius import autoclass
4 from jnius import java_method
5 from jnius import PythonJavaClass
6
7 from plyer.facades import STT
8 from plyer.platforms.android import activity
9
10 ArrayList = autoclass('java.util.ArrayList')
11 Bundle = autoclass('android.os.Bundle')
12 Context = autoclass('android.content.Context')
13 Intent = autoclass('android.content.Intent')
14 RecognizerIntent = autoclass('android.speech.RecognizerIntent')
15 RecognitionListener = autoclass('android.speech.RecognitionListener')
16 SpeechRecognizer = autoclass('android.speech.SpeechRecognizer')
17
18 SpeechResults = SpeechRecognizer.RESULTS_RECOGNITION
19
20
21 class SpeechListener(PythonJavaClass):
22 __javainterfaces__ = ['android/speech/RecognitionListener']
23
24 # class variables because PythonJavaClass class failed
25 # to see them later in getters and setters
26 _error_callback = None
27 _result_callback = None
28 _partial_result_callback = None
29 _volume_callback = None
30
31 def __init__(self):
32 super().__init__()
33
34 # overwrite class variables in the object
35 self._error_callback = None
36 self._result_callback = None
37 self._partial_result_callback = None
38 self._volume_callback = None
39
40 # error handling
41 @property
42 def error_callback(self):
43 return self._error_callback
44
45 @error_callback.setter
46 def error_callback(self, callback):
47 '''
48 Set error callback. It is called when error occurs.
49
50 :param callback: function with one parameter for error message
51 '''
52
53 self._error_callback = callback
54
55 # result handling
56 @property
57 def result_callback(self):
58 return self._result_callback
59
60 @result_callback.setter
61 def result_callback(self, callback):
62 '''
63 Set result callback. It is called when results are received.
64
65 :param callback: function with one parameter for lists of strings
66 '''
67
68 self._result_callback = callback
69
70 @property
71 def partial_result_callback(self):
72 return self._partial_result_callback
73
74 @partial_result_callback.setter
75 def partial_result_callback(self, callback):
76 '''
77 Set partial result callback. It is called when partial results are
78 received while the listener is still in listening mode.
79
80 :param callback: function with one parameter for lists of strings
81 '''
82
83 self._partial_result_callback = callback
84
85 # voice changes handling
86 @property
87 def volume_callback(self):
88 return self._volume_callback
89
90 @volume_callback.setter
91 def volume_callback(self, callback):
92 '''
93 Set volume voice callback.
94
95 It is called when loudness of the voice changes.
96
97 :param callback: function with one parameter for volume RMS dB (float).
98 '''
99 self._volume_callback = callback
100
101 # Implementation Java Interfaces
102 @java_method('()V')
103 def onBeginningOfSpeech(self):
104 pass
105
106 @java_method('([B)V')
107 def onBufferReceived(self, buffer):
108 pass
109
110 @java_method('()V')
111 def onEndOfSpeech(self):
112 pass
113
114 @java_method('(I)V')
115 def onError(self, error):
116 msg = ''
117 if error == SpeechRecognizer.ERROR_AUDIO:
118 msg = 'audio'
119 if error == SpeechRecognizer.ERROR_CLIENT:
120 msg = 'client'
121 if error == SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
122 msg = 'insufficient_permissions'
123 if error == SpeechRecognizer.ERROR_NETWORK:
124 msg = 'network'
125 if error == SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
126 msg = 'network_timeout'
127 if error == SpeechRecognizer.ERROR_NO_MATCH:
128 msg = 'no_match'
129 if error == SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
130 msg = 'recognizer_busy'
131 if error == SpeechRecognizer.ERROR_SERVER:
132 msg = 'server'
133 if error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
134 msg = 'speech_timeout'
135
136 if msg and self.error_callback:
137 self.error_callback('error:' + msg)
138
139 @java_method('(ILandroid/os/Bundle;)V')
140 def onEvent(self, event_type, params):
141 pass
142
143 @java_method('(Landroid/os/Bundle;)V')
144 def onPartialResults(self, results):
145 texts = []
146 matches = results.getStringArrayList(SpeechResults)
147 for match in matches.toArray():
148 if isinstance(match, bytes):
149 match = match.decode('utf-8')
150 texts.append(match)
151
152 if texts and self.partial_result_callback:
153 self.partial_result_callback(texts)
154
155 @java_method('(Landroid/os/Bundle;)V')
156 def onReadyForSpeech(self, params):
157 pass
158
159 @java_method('(Landroid/os/Bundle;)V')
160 def onResults(self, results):
161 texts = []
162 matches = results.getStringArrayList(SpeechResults)
163 for match in matches.toArray():
164 if isinstance(match, bytes):
165 match = match.decode('utf-8')
166 texts.append(match)
167
168 if texts and self.result_callback:
169 self.result_callback(texts)
170
171 @java_method('(F)V')
172 def onRmsChanged(self, rmsdB):
173 if self.volume_callback:
174 self.volume_callback(rmsdB)
175
176
177 class AndroidSpeech(STT):
178 '''
179 Android Speech Implementation.
180
181 Android class `SpeechRecognizer`'s listening deactivates automatically.
182
183 Class methods `_on_error()`, `_on_result()` listeners. You can find
184 documentation here:
185 https://developer.android.com/reference/android/speech/RecognitionListener
186 '''
187
188 def _on_error(self, msg):
189 self.errors.append(msg)
190 self.stop()
191
192 def _on_result(self, messages):
193 self.results.extend(messages)
194 self.stop()
195
196 def _on_partial(self, messages):
197 self.partial_results.extend(messages)
198
199 @run_on_ui_thread
200 def _start(self):
201 intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
202 intent.putExtra(
203 RecognizerIntent.EXTRA_CALLING_PACKAGE,
204 activity.getPackageName()
205 )
206
207 # language preferences
208 intent.putExtra(
209 RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, self.language
210 )
211 intent.putExtra(
212 RecognizerIntent.EXTRA_LANGUAGE_MODEL,
213 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH
214 )
215
216 # results settings
217 intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1000)
218 intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, True)
219 if self.prefer_offline:
220 intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, True)
221
222 # listener and callbacks
223 listener = SpeechListener()
224 listener.error_callback = self._on_error
225 listener.result_callback = self._on_result
226 listener.partial_result_callback = self._on_partial
227
228 # create recognizer and start
229 self.speech = SpeechRecognizer.createSpeechRecognizer(activity)
230 self.speech.setRecognitionListener(listener)
231 self.speech.startListening(intent)
232
233 @run_on_ui_thread
234 def _stop(self):
235 if not self.speech:
236 return
237
238 # stop listening
239 self.speech.stopListening()
240
241 # free object
242 self.speech.destroy()
243 self.speech = None
244
245 def _exist(self):
246 return bool(
247 SpeechRecognizer.isRecognitionAvailable(activity)
248 )
249
250
251 def instance():
252 return AndroidSpeech()