flet-stt 0.1.0__py3-none-any.whl
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.
- flet_stt/__init__.py +4 -0
- flet_stt/flet_stt.py +176 -0
- flet_stt-0.1.0.dist-info/METADATA +224 -0
- flet_stt-0.1.0.dist-info/RECORD +9 -0
- flet_stt-0.1.0.dist-info/WHEEL +4 -0
- flutter/flet_stt/lib/flet_stt.dart +3 -0
- flutter/flet_stt/lib/src/extension.dart +15 -0
- flutter/flet_stt/lib/src/stt_service.dart +156 -0
- flutter/flet_stt/pubspec.yaml +19 -0
flet_stt/__init__.py
ADDED
flet_stt/flet_stt.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from typing import Optional
|
|
3
|
+
|
|
4
|
+
import flet as ft
|
|
5
|
+
from flet.controls.control_event import ControlEventHandler
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SttError(Exception):
|
|
9
|
+
"""Raised when a speech-to-text operation fails on the native side."""
|
|
10
|
+
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@ft.control("flet_stt")
|
|
15
|
+
class FletStt(ft.Service):
|
|
16
|
+
"""Speech-to-text service using OS-native recognition.
|
|
17
|
+
|
|
18
|
+
Wraps the Flutter speech_to_text package. On Android this uses Google
|
|
19
|
+
Speech Services (on-device for ~50 languages). On iOS it uses Apple's
|
|
20
|
+
SFSpeechRecognizer.
|
|
21
|
+
|
|
22
|
+
Events:
|
|
23
|
+
on_result: Fires with recognition results.
|
|
24
|
+
e.data is JSON: {"text": "hello", "final": true, "confidence": 0.95}
|
|
25
|
+
on_sound_level: Fires with microphone dB level during listening.
|
|
26
|
+
e.data is JSON: {"level": -6.5}
|
|
27
|
+
on_error: Fires on recognition errors.
|
|
28
|
+
e.data is JSON: {"error": "error_speech_timeout", "permanent": false}
|
|
29
|
+
on_status: Fires on status changes.
|
|
30
|
+
e.data is JSON: {"status": "listening"} or {"status": "notListening"} or {"status": "done"}
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
on_result: Optional[ControlEventHandler["FletStt"]] = None
|
|
34
|
+
on_sound_level: Optional[ControlEventHandler["FletStt"]] = None
|
|
35
|
+
on_error: Optional[ControlEventHandler["FletStt"]] = None
|
|
36
|
+
on_status: Optional[ControlEventHandler["FletStt"]] = None
|
|
37
|
+
|
|
38
|
+
def _check_error(self, result):
|
|
39
|
+
"""Check if Dart returned an error and raise if so."""
|
|
40
|
+
if isinstance(result, str) and result.startswith("error:"):
|
|
41
|
+
raise SttError(result[6:])
|
|
42
|
+
return result
|
|
43
|
+
|
|
44
|
+
async def initialize(self) -> bool:
|
|
45
|
+
"""Initialize the speech recognizer and check availability.
|
|
46
|
+
|
|
47
|
+
Must be called before listen(). Requests microphone permission
|
|
48
|
+
on first call.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
True if speech recognition is available, False otherwise.
|
|
52
|
+
|
|
53
|
+
Raises:
|
|
54
|
+
SttError: If initialization fails on the native side.
|
|
55
|
+
"""
|
|
56
|
+
result = await self._invoke_method(method_name="initialize")
|
|
57
|
+
return self._check_error(result) == "true"
|
|
58
|
+
|
|
59
|
+
async def listen(
|
|
60
|
+
self,
|
|
61
|
+
*,
|
|
62
|
+
locale_id: str = "",
|
|
63
|
+
listen_for_seconds: int = 0,
|
|
64
|
+
pause_for_seconds: int = 0,
|
|
65
|
+
partial_results: bool = True,
|
|
66
|
+
on_device: bool = True,
|
|
67
|
+
cancel_on_error: bool = False,
|
|
68
|
+
sample_rate: int = 0,
|
|
69
|
+
listen_mode: str = "confirmation",
|
|
70
|
+
) -> None:
|
|
71
|
+
"""Start listening for speech.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
locale_id: BCP-47 locale (e.g. "en_US", "ro_RO"). Empty = system default.
|
|
75
|
+
listen_for_seconds: Max listen duration in seconds. 0 = platform default
|
|
76
|
+
(typically ~60s on Android before auto-stop).
|
|
77
|
+
pause_for_seconds: Auto-stop after this many seconds of silence. 0 = platform default.
|
|
78
|
+
partial_results: If True, on_result fires for partial (non-final) results
|
|
79
|
+
during recognition, not just the final result.
|
|
80
|
+
on_device: Prefer on-device recognition when available. Falls back to
|
|
81
|
+
cloud if on-device model isn't installed for the locale.
|
|
82
|
+
cancel_on_error: If True, cancel recognition on error instead of continuing.
|
|
83
|
+
sample_rate: Audio sample rate in Hz. 0 = platform default.
|
|
84
|
+
listen_mode: Recognition mode. One of:
|
|
85
|
+
- "confirmation": short phrases, yes/no responses (default)
|
|
86
|
+
- "search": search query input
|
|
87
|
+
- "dictation": longer free-form text
|
|
88
|
+
|
|
89
|
+
Raises:
|
|
90
|
+
SttError: If listening fails to start.
|
|
91
|
+
"""
|
|
92
|
+
result = await self._invoke_method(
|
|
93
|
+
method_name="listen",
|
|
94
|
+
arguments={
|
|
95
|
+
"locale_id": locale_id,
|
|
96
|
+
"listen_for_seconds": listen_for_seconds,
|
|
97
|
+
"pause_for_seconds": pause_for_seconds,
|
|
98
|
+
"partial_results": partial_results,
|
|
99
|
+
"on_device": on_device,
|
|
100
|
+
"cancel_on_error": cancel_on_error,
|
|
101
|
+
"sample_rate": sample_rate,
|
|
102
|
+
"listen_mode": listen_mode,
|
|
103
|
+
},
|
|
104
|
+
)
|
|
105
|
+
self._check_error(result)
|
|
106
|
+
|
|
107
|
+
async def stop(self) -> None:
|
|
108
|
+
"""Stop listening and trigger the final recognition result.
|
|
109
|
+
|
|
110
|
+
After calling stop(), you'll receive one last on_result event with
|
|
111
|
+
final=True containing the complete recognized text.
|
|
112
|
+
|
|
113
|
+
Raises:
|
|
114
|
+
SttError: If the stop operation fails.
|
|
115
|
+
"""
|
|
116
|
+
result = await self._invoke_method(method_name="stop")
|
|
117
|
+
self._check_error(result)
|
|
118
|
+
|
|
119
|
+
async def cancel(self) -> None:
|
|
120
|
+
"""Cancel listening without triggering a final result.
|
|
121
|
+
|
|
122
|
+
Use this when the user wants to discard the current recognition
|
|
123
|
+
session entirely.
|
|
124
|
+
|
|
125
|
+
Raises:
|
|
126
|
+
SttError: If the cancel operation fails.
|
|
127
|
+
"""
|
|
128
|
+
result = await self._invoke_method(method_name="cancel")
|
|
129
|
+
self._check_error(result)
|
|
130
|
+
|
|
131
|
+
async def system_locale(self) -> dict:
|
|
132
|
+
"""Get the system's default speech recognition locale.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
Dict with "id" and "name" keys, e.g. {"id": "en_US", "name": "English (United States)"}.
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
SttError: If the query fails.
|
|
139
|
+
"""
|
|
140
|
+
result = await self._invoke_method(method_name="system_locale")
|
|
141
|
+
self._check_error(result)
|
|
142
|
+
return json.loads(result)
|
|
143
|
+
|
|
144
|
+
async def is_listening(self) -> bool:
|
|
145
|
+
"""Check whether the speech recognizer is currently listening.
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
True if actively listening, False otherwise.
|
|
149
|
+
"""
|
|
150
|
+
result = await self._invoke_method(method_name="is_listening")
|
|
151
|
+
self._check_error(result)
|
|
152
|
+
return result == "true"
|
|
153
|
+
|
|
154
|
+
async def has_permission(self) -> bool:
|
|
155
|
+
"""Check whether the app has microphone permission.
|
|
156
|
+
|
|
157
|
+
Returns:
|
|
158
|
+
True if permission is granted, False otherwise.
|
|
159
|
+
"""
|
|
160
|
+
result = await self._invoke_method(method_name="has_permission")
|
|
161
|
+
self._check_error(result)
|
|
162
|
+
return result == "true"
|
|
163
|
+
|
|
164
|
+
async def locales(self) -> list[dict]:
|
|
165
|
+
"""Get available speech recognition locales.
|
|
166
|
+
|
|
167
|
+
Returns:
|
|
168
|
+
List of dicts, each with "id" and "name" keys.
|
|
169
|
+
Example: [{"id": "en_US", "name": "English (United States)"}, ...]
|
|
170
|
+
|
|
171
|
+
Raises:
|
|
172
|
+
SttError: If the query fails.
|
|
173
|
+
"""
|
|
174
|
+
result = await self._invoke_method(method_name="locales")
|
|
175
|
+
self._check_error(result)
|
|
176
|
+
return json.loads(result)
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: flet-stt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Speech-to-text for Flet apps via OS-native recognition (Android/iOS)
|
|
5
|
+
Project-URL: Homepage, https://github.com/alex-stoica/flet-stt
|
|
6
|
+
Project-URL: Repository, https://github.com/alex-stoica/flet-stt
|
|
7
|
+
Project-URL: Issues, https://github.com/alex-stoica/flet-stt/issues
|
|
8
|
+
Author-email: Alex Stoica <alexstoica@protonmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Requires-Dist: flet>=0.82.0
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# flet-stt
|
|
23
|
+
|
|
24
|
+
Speech-to-text for Flet apps. Wraps the `speech_to_text` Flutter plugin through a custom Flet extension, giving your Python code access to the OS-native speech recognizer on Android and iOS.
|
|
25
|
+
|
|
26
|
+
On Android this uses Google Speech Services (on-device for ~50 languages, no API key needed). On iOS it uses Apple's SFSpeechRecognizer.
|
|
27
|
+
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
- real-time speech recognition with partial results and alternate transcriptions
|
|
31
|
+
- locale selection (50+ languages, on-device where available)
|
|
32
|
+
- sound level monitoring during listening
|
|
33
|
+
- listen modes: confirmation (short), search, dictation (long-form)
|
|
34
|
+
- configurable pause detection, sample rate, and error handling
|
|
35
|
+
- system locale detection, permission checking, listening state queries
|
|
36
|
+
- proper error and status callbacks
|
|
37
|
+
|
|
38
|
+
## Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install flet-stt
|
|
42
|
+
# or
|
|
43
|
+
poetry add flet-stt
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
In your app's `pyproject.toml`, declare the Android permission and tell Flet where to find the extension for APK builds:
|
|
47
|
+
|
|
48
|
+
```toml
|
|
49
|
+
[project]
|
|
50
|
+
dependencies = [
|
|
51
|
+
"flet>=0.82.0",
|
|
52
|
+
"flet-stt",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
[tool.flet.android.permission]
|
|
56
|
+
"android.permission.RECORD_AUDIO" = true
|
|
57
|
+
|
|
58
|
+
[tool.flet.app]
|
|
59
|
+
exclude = ["flet_stt"]
|
|
60
|
+
|
|
61
|
+
[tool.flet.dev_packages]
|
|
62
|
+
flet-stt = "flet_stt"
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The `exclude` line prevents the extension source from being raw-copied into the APK, which would shadow the installed package and break imports.
|
|
66
|
+
|
|
67
|
+
## Usage
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import json
|
|
71
|
+
import flet as ft
|
|
72
|
+
from flet_stt import FletStt
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def main(page: ft.Page):
|
|
76
|
+
stt = FletStt()
|
|
77
|
+
|
|
78
|
+
def on_result(e):
|
|
79
|
+
data = json.loads(e.data)
|
|
80
|
+
if data["final"]:
|
|
81
|
+
print(f"Recognized: {data['text']} (confidence: {data['confidence']:.0%})")
|
|
82
|
+
|
|
83
|
+
stt.on_result = on_result
|
|
84
|
+
|
|
85
|
+
async def start_listening(e):
|
|
86
|
+
await stt.initialize()
|
|
87
|
+
await stt.listen(partial_results=True, listen_mode="dictation")
|
|
88
|
+
|
|
89
|
+
async def stop_listening(e):
|
|
90
|
+
await stt.stop()
|
|
91
|
+
|
|
92
|
+
page.add(
|
|
93
|
+
ft.Column([
|
|
94
|
+
ft.Button(content="Listen", on_click=start_listening),
|
|
95
|
+
ft.Button(content="Stop", on_click=stop_listening),
|
|
96
|
+
])
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
ft.run(main)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Just instantiate `FletStt`. Do not add it to `page.overlay` or `page.controls` - it's a service, not a visual control, and it registers itself automatically.
|
|
104
|
+
|
|
105
|
+
See the [`examples/`](examples/) folder for more: [`basic.py`](examples/basic.py), [`simple.py`](examples/simple.py), [`continuous.py`](examples/continuous.py), [`locale_picker.py`](examples/locale_picker.py), [`diagnostic.py`](examples/diagnostic.py).
|
|
106
|
+
|
|
107
|
+
## API
|
|
108
|
+
|
|
109
|
+
### `FletStt(on_result=..., on_sound_level=..., on_error=..., on_status=...)`
|
|
110
|
+
|
|
111
|
+
The service. Instantiate once. All callbacks receive an event where `e.data` is a JSON string.
|
|
112
|
+
|
|
113
|
+
### Events
|
|
114
|
+
|
|
115
|
+
| Event | e.data format | Description |
|
|
116
|
+
|---|---|---|
|
|
117
|
+
| `on_result` | `{"text": "hello", "final": true, "confidence": 0.95, "alternates": [...]}` | Recognition result. `final=false` for partial results. |
|
|
118
|
+
| `on_sound_level` | `{"level": -6.5}` | Microphone dB level during listening. |
|
|
119
|
+
| `on_error` | `{"error": "error_speech_timeout", "permanent": false}` | Recognition error. Permanent errors require re-initialization. |
|
|
120
|
+
| `on_status` | `{"status": "listening"}` | Status change: `"listening"`, `"notListening"`, `"done"`. |
|
|
121
|
+
|
|
122
|
+
The `alternates` field in `on_result` is a list of `{"text": "...", "confidence": 0.0}` objects. The first entry matches the main `text` field. Additional entries are alternative transcriptions when the engine provides them (depends on platform/locale).
|
|
123
|
+
|
|
124
|
+
### `await initialize() -> bool`
|
|
125
|
+
|
|
126
|
+
Initialize the speech recognizer and check availability. Must be called before `listen()`. Requests microphone permission on first call. Returns `True` if speech recognition is available.
|
|
127
|
+
|
|
128
|
+
### `await listen(...)`
|
|
129
|
+
|
|
130
|
+
| Parameter | Type | Default | Description |
|
|
131
|
+
|---|---|---|---|
|
|
132
|
+
| `locale_id` | `str` | `""` | BCP-47 locale (e.g. `"en_US"`, `"ro_RO"`). Empty = system default. |
|
|
133
|
+
| `listen_for_seconds` | `int` | `0` | Max listen duration. 0 = platform default (~60s on Android). |
|
|
134
|
+
| `pause_for_seconds` | `int` | `0` | Auto-stop after this many seconds of silence. 0 = platform default. |
|
|
135
|
+
| `partial_results` | `bool` | `True` | Fire `on_result` for partial (non-final) results during recognition. |
|
|
136
|
+
| `on_device` | `bool` | `True` | Prefer on-device recognition when available. |
|
|
137
|
+
| `cancel_on_error` | `bool` | `False` | Cancel recognition on error instead of continuing. |
|
|
138
|
+
| `sample_rate` | `int` | `0` | Audio sample rate in Hz. 0 = platform default. 16000 is recommended for speech. |
|
|
139
|
+
| `listen_mode` | `str` | `"confirmation"` | One of `"confirmation"`, `"search"`, `"dictation"`. |
|
|
140
|
+
|
|
141
|
+
### `await stop()`
|
|
142
|
+
|
|
143
|
+
Stop listening and trigger the final recognition result.
|
|
144
|
+
|
|
145
|
+
### `await cancel()`
|
|
146
|
+
|
|
147
|
+
Cancel listening without triggering a final result.
|
|
148
|
+
|
|
149
|
+
### `await locales() -> list[dict]`
|
|
150
|
+
|
|
151
|
+
Get available locales. Returns list of `{"id": "en_US", "name": "English (United States)"}`.
|
|
152
|
+
|
|
153
|
+
### `await system_locale() -> dict`
|
|
154
|
+
|
|
155
|
+
Get the system's default speech recognition locale. Returns `{"id": "en_US", "name": "English (United States)"}`.
|
|
156
|
+
|
|
157
|
+
### `await is_listening() -> bool`
|
|
158
|
+
|
|
159
|
+
Check whether the speech recognizer is currently listening.
|
|
160
|
+
|
|
161
|
+
### `await has_permission() -> bool`
|
|
162
|
+
|
|
163
|
+
Check whether the app has microphone permission.
|
|
164
|
+
|
|
165
|
+
## Building the APK
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
flet build apk -v
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Or use `build.py` for automated build + deploy (dev-only, has hardcoded local paths):
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
python build.py
|
|
175
|
+
python build.py --skip-flet # reuse existing build dir
|
|
176
|
+
python build.py --skip-install # build only, don't deploy
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
On Windows, set `PYTHONIOENCODING=utf-8` before building to avoid Unicode crashes from Rich's spinner characters.
|
|
180
|
+
|
|
181
|
+
### Installing on device
|
|
182
|
+
|
|
183
|
+
Always do a full uninstall before installing a new APK. Flet's `serious_python` caches the extracted Python environment and won't pick up code changes with `adb install -r`:
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
adb uninstall com.yourapp.package
|
|
187
|
+
adb install build/apk/app-release.apk
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Platform notes
|
|
191
|
+
|
|
192
|
+
### Android
|
|
193
|
+
|
|
194
|
+
- Uses Google Speech Services, pre-installed on all phones with Google Play Services
|
|
195
|
+
- On-device recognition available for ~50 languages (no internet needed)
|
|
196
|
+
- Auto-stops after ~5s of silence or ~60s total - use the continuous example pattern to work around this
|
|
197
|
+
- Requires `RECORD_AUDIO` permission (declared in pyproject.toml, requested at runtime by `initialize()`)
|
|
198
|
+
|
|
199
|
+
### iOS
|
|
200
|
+
|
|
201
|
+
- Uses Apple SFSpeechRecognizer
|
|
202
|
+
- On-device recognition since iOS 15 for major languages
|
|
203
|
+
- Requires `NSSpeechRecognitionUsageDescription` and `NSMicrophoneUsageDescription` in Info.plist
|
|
204
|
+
|
|
205
|
+
### Desktop
|
|
206
|
+
|
|
207
|
+
Does nothing. The service instantiates without error but recognition won't work since there's no native plugin backing it.
|
|
208
|
+
|
|
209
|
+
## How it works
|
|
210
|
+
|
|
211
|
+
```
|
|
212
|
+
your Python app
|
|
213
|
+
-> FletStt (ft.Service)
|
|
214
|
+
-> _invoke_method() over Flet protocol
|
|
215
|
+
-> SttService (FletService, Dart)
|
|
216
|
+
-> speech_to_text plugin
|
|
217
|
+
-> Android SpeechRecognizer / iOS SFSpeechRecognizer
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
The extension is packaged as a standard Python package with a `flutter/` namespace directory containing the Dart code. When you run `flet build apk`, Flet discovers the Dart code in site-packages and includes it as a path dependency in the generated Flutter project.
|
|
221
|
+
|
|
222
|
+
## License
|
|
223
|
+
|
|
224
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
flet_stt/__init__.py,sha256=BD9GPoO4h11x7UNYkPDEaKv_4WskcAFXhLLhLrpYGcs,57
|
|
2
|
+
flet_stt/flet_stt.py,sha256=udhv1n8LD1RsszcNjQq2yUxJ2CUO9FHvT1pS6mLRHAc,6649
|
|
3
|
+
flutter/flet_stt/pubspec.yaml,sha256=FmP2E0hkP77xavGAnC_M78GgajR_4SNGYQb_whCqimA,326
|
|
4
|
+
flutter/flet_stt/lib/flet_stt.dart,sha256=zWfAkYL0djUZZqx2Pf8PshHMfcH9J-vuEJTP_p4yInI,66
|
|
5
|
+
flutter/flet_stt/lib/src/extension.dart,sha256=8M1lg-mmClS-HIUFOZ4Yi8utCYCMM6D5ECX1M7MxQNI,321
|
|
6
|
+
flutter/flet_stt/lib/src/stt_service.dart,sha256=NzFrPm1no9_TtVMSOK-_Yui0-uoZ5ITvs8s4xHMdZeo,4807
|
|
7
|
+
flet_stt-0.1.0.dist-info/METADATA,sha256=--gAQZ7FYZyH4HQTMIYfMyFziYnbEOPRqtaSUs1McZg,8084
|
|
8
|
+
flet_stt-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
9
|
+
flet_stt-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import 'package:flet/flet.dart';
|
|
2
|
+
|
|
3
|
+
import 'stt_service.dart';
|
|
4
|
+
|
|
5
|
+
class Extension extends FletExtension {
|
|
6
|
+
@override
|
|
7
|
+
FletService? createService(Control control) {
|
|
8
|
+
switch (control.type) {
|
|
9
|
+
case "flet_stt":
|
|
10
|
+
return SttService(control: control);
|
|
11
|
+
default:
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import 'dart:convert';
|
|
2
|
+
|
|
3
|
+
import 'package:flet/flet.dart';
|
|
4
|
+
import 'package:speech_to_text/speech_to_text.dart';
|
|
5
|
+
import 'package:speech_to_text/speech_recognition_error.dart';
|
|
6
|
+
import 'package:speech_to_text/speech_recognition_result.dart';
|
|
7
|
+
|
|
8
|
+
class SttService extends FletService {
|
|
9
|
+
SttService({required super.control});
|
|
10
|
+
|
|
11
|
+
final SpeechToText _speech = SpeechToText();
|
|
12
|
+
bool _initialized = false;
|
|
13
|
+
|
|
14
|
+
@override
|
|
15
|
+
void init() {
|
|
16
|
+
super.init();
|
|
17
|
+
control.addInvokeMethodListener(_onMethod);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
@override
|
|
21
|
+
void dispose() {
|
|
22
|
+
control.removeInvokeMethodListener(_onMethod);
|
|
23
|
+
if (_initialized) {
|
|
24
|
+
_speech.cancel();
|
|
25
|
+
}
|
|
26
|
+
super.dispose();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
void _onError(SpeechRecognitionError error) {
|
|
30
|
+
control.triggerEvent("error", jsonEncode({
|
|
31
|
+
"error": error.errorMsg,
|
|
32
|
+
"permanent": error.permanent,
|
|
33
|
+
}));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
void _onStatus(String status) {
|
|
37
|
+
control.triggerEvent("status", jsonEncode({
|
|
38
|
+
"status": status,
|
|
39
|
+
}));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
void _onResult(SpeechRecognitionResult result) {
|
|
43
|
+
control.triggerEvent("result", jsonEncode({
|
|
44
|
+
"text": result.recognizedWords,
|
|
45
|
+
"final": result.finalResult,
|
|
46
|
+
"confidence": result.confidence,
|
|
47
|
+
"alternates": result.alternates.map((a) => {
|
|
48
|
+
"text": a.recognizedWords,
|
|
49
|
+
"confidence": a.confidence,
|
|
50
|
+
}).toList(),
|
|
51
|
+
}));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
void _onSoundLevel(double level) {
|
|
55
|
+
control.triggerEvent("sound_level", jsonEncode({
|
|
56
|
+
"level": level,
|
|
57
|
+
}));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
ListenMode _parseListenMode(String value) {
|
|
61
|
+
switch (value) {
|
|
62
|
+
case "dictation":
|
|
63
|
+
return ListenMode.dictation;
|
|
64
|
+
case "search":
|
|
65
|
+
return ListenMode.search;
|
|
66
|
+
case "confirmation":
|
|
67
|
+
return ListenMode.confirmation;
|
|
68
|
+
default:
|
|
69
|
+
return ListenMode.confirmation;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
Future<dynamic> _onMethod(String name, dynamic args) async {
|
|
74
|
+
try {
|
|
75
|
+
switch (name) {
|
|
76
|
+
case "initialize":
|
|
77
|
+
final available = await _speech.initialize(
|
|
78
|
+
onError: _onError,
|
|
79
|
+
onStatus: _onStatus,
|
|
80
|
+
);
|
|
81
|
+
_initialized = available;
|
|
82
|
+
return available.toString();
|
|
83
|
+
|
|
84
|
+
case "listen":
|
|
85
|
+
if (!_initialized) {
|
|
86
|
+
return "error:not initialized — call initialize() first";
|
|
87
|
+
}
|
|
88
|
+
final a = Map<String, dynamic>.from(args as Map);
|
|
89
|
+
final localeId = a["locale_id"] as String? ?? "";
|
|
90
|
+
final listenForSeconds = a["listen_for_seconds"] as int? ?? 0;
|
|
91
|
+
final pauseForSeconds = a["pause_for_seconds"] as int? ?? 0;
|
|
92
|
+
final partialResults = a["partial_results"] as bool? ?? true;
|
|
93
|
+
final onDevice = a["on_device"] as bool? ?? true;
|
|
94
|
+
final cancelOnError = a["cancel_on_error"] as bool? ?? false;
|
|
95
|
+
final sampleRate = a["sample_rate"] as int? ?? 0;
|
|
96
|
+
final listenMode = _parseListenMode(
|
|
97
|
+
a["listen_mode"] as String? ?? "confirmation");
|
|
98
|
+
|
|
99
|
+
await _speech.listen(
|
|
100
|
+
onResult: _onResult,
|
|
101
|
+
onSoundLevelChange: _onSoundLevel,
|
|
102
|
+
localeId: localeId.isNotEmpty ? localeId : null,
|
|
103
|
+
listenFor: listenForSeconds > 0
|
|
104
|
+
? Duration(seconds: listenForSeconds)
|
|
105
|
+
: null,
|
|
106
|
+
pauseFor: pauseForSeconds > 0
|
|
107
|
+
? Duration(seconds: pauseForSeconds)
|
|
108
|
+
: null,
|
|
109
|
+
partialResults: partialResults,
|
|
110
|
+
onDevice: onDevice,
|
|
111
|
+
cancelOnError: cancelOnError,
|
|
112
|
+
sampleRate: sampleRate > 0 ? sampleRate : null,
|
|
113
|
+
listenMode: listenMode,
|
|
114
|
+
);
|
|
115
|
+
return "ok";
|
|
116
|
+
|
|
117
|
+
case "stop":
|
|
118
|
+
await _speech.stop();
|
|
119
|
+
return "ok";
|
|
120
|
+
|
|
121
|
+
case "cancel":
|
|
122
|
+
await _speech.cancel();
|
|
123
|
+
return "ok";
|
|
124
|
+
|
|
125
|
+
case "locales":
|
|
126
|
+
if (!_initialized) {
|
|
127
|
+
return "error:not initialized — call initialize() first";
|
|
128
|
+
}
|
|
129
|
+
final locales = await _speech.locales();
|
|
130
|
+
final list = locales.map((l) =>
|
|
131
|
+
{"id": l.localeId, "name": l.name}
|
|
132
|
+
).toList();
|
|
133
|
+
return jsonEncode(list);
|
|
134
|
+
|
|
135
|
+
case "system_locale":
|
|
136
|
+
if (!_initialized) {
|
|
137
|
+
return "error:not initialized — call initialize() first";
|
|
138
|
+
}
|
|
139
|
+
final locale = await _speech.systemLocale();
|
|
140
|
+
if (locale == null) {
|
|
141
|
+
return jsonEncode({"id": "", "name": ""});
|
|
142
|
+
}
|
|
143
|
+
return jsonEncode({"id": locale.localeId, "name": locale.name});
|
|
144
|
+
|
|
145
|
+
case "is_listening":
|
|
146
|
+
return _speech.isListening.toString();
|
|
147
|
+
|
|
148
|
+
case "has_permission":
|
|
149
|
+
return (await _speech.hasPermission).toString();
|
|
150
|
+
}
|
|
151
|
+
return null;
|
|
152
|
+
} catch (e) {
|
|
153
|
+
return "error:$e";
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
name: flet_stt
|
|
2
|
+
description: Speech-to-text for Flet
|
|
3
|
+
version: 0.1.0
|
|
4
|
+
publish_to: none
|
|
5
|
+
|
|
6
|
+
environment:
|
|
7
|
+
sdk: '>=3.8.0 <4.0.0'
|
|
8
|
+
flutter: ">=3.32.0"
|
|
9
|
+
|
|
10
|
+
dependencies:
|
|
11
|
+
flet: ">=0.82.0"
|
|
12
|
+
flutter:
|
|
13
|
+
sdk: flutter
|
|
14
|
+
speech_to_text: ^7.3.0
|
|
15
|
+
|
|
16
|
+
dev_dependencies:
|
|
17
|
+
flutter_test:
|
|
18
|
+
sdk: flutter
|
|
19
|
+
flutter_lints: ^6.0.0
|