| 1 |
#!/usr/bin/env python3 |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Fenrir TTY screen reader |
| 5 |
# By Chrys, Storm Dragon, and contributors. |
| 6 |
|
| 7 |
import subprocess |
| 8 |
import time |
| 9 |
|
| 10 |
from fenrirscreenreader.core import debug |
| 11 |
from fenrirscreenreader.utils.speechd_utils import ( |
| 12 |
get_synthesis_voice_name, |
| 13 |
parse_synthesis_voice_line, |
| 14 |
) |
| 15 |
|
| 16 |
|
| 17 |
MODULE_QUERY_TIMEOUT = 5 |
| 18 |
VOICE_QUERY_TIMEOUT = 8 |
| 19 |
VOICE_TEST_TIMEOUT = 8 |
| 20 |
|
| 21 |
|
| 22 |
def query_speechd_modules(timeout=MODULE_QUERY_TIMEOUT): |
| 23 |
"""Return available Speech Dispatcher output modules.""" |
| 24 |
result = subprocess.run( |
| 25 |
["spd-say", "-O"], |
| 26 |
capture_output=True, |
| 27 |
text=True, |
| 28 |
timeout=timeout, |
| 29 |
check=False, |
| 30 |
) |
| 31 |
if result.returncode != 0: |
| 32 |
raise RuntimeError(result.stderr.strip() or "module discovery failed") |
| 33 |
return [ |
| 34 |
line.strip() |
| 35 |
for line in result.stdout.splitlines()[1:] |
| 36 |
if line.strip() and line.strip().lower() != "dummy" |
| 37 |
] |
| 38 |
|
| 39 |
|
| 40 |
def query_speechd_voices(module, timeout=VOICE_QUERY_TIMEOUT): |
| 41 |
"""Return the synthesis voices exposed by one output module.""" |
| 42 |
result = subprocess.run( |
| 43 |
["spd-say", "-o", module, "-L"], |
| 44 |
capture_output=True, |
| 45 |
text=True, |
| 46 |
timeout=timeout, |
| 47 |
check=False, |
| 48 |
) |
| 49 |
if result.returncode != 0: |
| 50 |
raise RuntimeError( |
| 51 |
result.stderr.strip() or f"voice discovery failed for {module}" |
| 52 |
) |
| 53 |
|
| 54 |
voices = [] |
| 55 |
for line in result.stdout.splitlines()[1:]: |
| 56 |
if not line.strip(): |
| 57 |
continue |
| 58 |
voice = get_synthesis_voice_name(module, line) |
| 59 |
if module.lower() == "voxin": |
| 60 |
voice_data = parse_synthesis_voice_line(line) |
| 61 |
if voice_data is not None: |
| 62 |
voice_name, language, _variant = voice_data |
| 63 |
voice = f"{voice_name}|{language}" if language else None |
| 64 |
if voice: |
| 65 |
voices.append(voice) |
| 66 |
return voices |
| 67 |
|
| 68 |
|
| 69 |
def test_speechd_voice(module, voice, message, timeout=VOICE_TEST_TIMEOUT): |
| 70 |
"""Play one bounded voice test and return when Speech Dispatcher finishes.""" |
| 71 |
result = subprocess.run( |
| 72 |
["spd-say", "-C", "-w", "-o", module, "-y", voice, message], |
| 73 |
capture_output=True, |
| 74 |
text=True, |
| 75 |
timeout=timeout, |
| 76 |
check=False, |
| 77 |
) |
| 78 |
if result.returncode != 0: |
| 79 |
raise RuntimeError(result.stderr.strip() or "voice test failed") |
| 80 |
return True |
| 81 |
|
| 82 |
|
| 83 |
class SpeechDiscoveryManager: |
| 84 |
"""Cache and coordinate asynchronous Speech Dispatcher discovery.""" |
| 85 |
|
| 86 |
def __init__(self): |
| 87 |
self.env = None |
| 88 |
self.cache_timeout = 300 |
| 89 |
self._modules = None |
| 90 |
self._modules_timestamp = 0 |
| 91 |
self._voices = {} |
| 92 |
self._voice_timestamps = {} |
| 93 |
self._module_callbacks = [] |
| 94 |
self._voice_callbacks = {} |
| 95 |
self._task_ids = set() |
| 96 |
self._module_task_id = None |
| 97 |
self._voice_task_ids = {} |
| 98 |
|
| 99 |
def initialize(self, environment): |
| 100 |
self.env = environment |
| 101 |
|
| 102 |
def shutdown(self): |
| 103 |
task_manager = self.env["runtime"].get("BackgroundTaskManager") |
| 104 |
if task_manager: |
| 105 |
for task_id in self._task_ids: |
| 106 |
task_manager.cancel_task(task_id) |
| 107 |
self._task_ids.clear() |
| 108 |
self._module_callbacks = [] |
| 109 |
self._voice_callbacks = {} |
| 110 |
|
| 111 |
def get_cached_modules(self): |
| 112 |
if not self._cache_is_current(self._modules_timestamp): |
| 113 |
return None |
| 114 |
return list(self._modules) if self._modules is not None else None |
| 115 |
|
| 116 |
def get_cached_voices(self, module): |
| 117 |
if not self._cache_is_current(self._voice_timestamps.get(module, 0)): |
| 118 |
return None |
| 119 |
voices = self._voices.get(module) |
| 120 |
return list(voices) if voices is not None else None |
| 121 |
|
| 122 |
def request_modules(self, callback, refresh=False): |
| 123 |
modules = None if refresh else self.get_cached_modules() |
| 124 |
if modules is not None: |
| 125 |
callback(modules, "") |
| 126 |
return None |
| 127 |
|
| 128 |
self._module_callbacks.append(callback) |
| 129 |
if self._module_task_id is not None: |
| 130 |
return self._module_task_id |
| 131 |
|
| 132 |
task_id = self._submit_task(query_speechd_modules, self._finish_modules) |
| 133 |
if task_id is None: |
| 134 |
self._finish_modules(self._submission_failure()) |
| 135 |
return None |
| 136 |
self._module_task_id = task_id |
| 137 |
return task_id |
| 138 |
|
| 139 |
def request_voices(self, module, callback, refresh=False): |
| 140 |
voices = None if refresh else self.get_cached_voices(module) |
| 141 |
if voices is not None: |
| 142 |
callback(module, voices, "") |
| 143 |
return None |
| 144 |
|
| 145 |
callbacks = self._voice_callbacks.setdefault(module, []) |
| 146 |
callbacks.append(callback) |
| 147 |
if module in self._voice_task_ids: |
| 148 |
return self._voice_task_ids[module] |
| 149 |
|
| 150 |
task_id = self._submit_task( |
| 151 |
query_speechd_voices, |
| 152 |
lambda result: self._finish_voices(module, result), |
| 153 |
module, |
| 154 |
) |
| 155 |
if task_id is None: |
| 156 |
self._finish_voices(module, self._submission_failure()) |
| 157 |
return None |
| 158 |
self._voice_task_ids[module] = task_id |
| 159 |
return task_id |
| 160 |
|
| 161 |
def request_voice_test(self, module, voice, message, callback): |
| 162 |
task_id = self._submit_task( |
| 163 |
test_speechd_voice, |
| 164 |
lambda result: callback( |
| 165 |
bool(result.get("succeeded")), result.get("error", "") |
| 166 |
), |
| 167 |
module, |
| 168 |
voice, |
| 169 |
message, |
| 170 |
) |
| 171 |
if task_id is None: |
| 172 |
callback(False, "background task manager is unavailable") |
| 173 |
return task_id |
| 174 |
|
| 175 |
def invalidate_cache(self): |
| 176 |
self._modules = None |
| 177 |
self._modules_timestamp = 0 |
| 178 |
self._voices = {} |
| 179 |
self._voice_timestamps = {} |
| 180 |
|
| 181 |
def _cache_is_current(self, timestamp): |
| 182 |
return timestamp > 0 and time.time() - timestamp < self.cache_timeout |
| 183 |
|
| 184 |
def _submit_task(self, function, callback, *args): |
| 185 |
task_manager = self.env["runtime"]["BackgroundTaskManager"] |
| 186 |
|
| 187 |
def finish(result): |
| 188 |
self._task_ids.discard(result.get("task_id")) |
| 189 |
callback(result) |
| 190 |
|
| 191 |
task_id = task_manager.submit_task(function, finish, *args) |
| 192 |
if task_id is None: |
| 193 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 194 |
"SpeechDiscoveryManager could not submit background task", |
| 195 |
debug.DebugLevel.ERROR, |
| 196 |
) |
| 197 |
return None |
| 198 |
self._task_ids.add(task_id) |
| 199 |
return task_id |
| 200 |
|
| 201 |
@staticmethod |
| 202 |
def _submission_failure(): |
| 203 |
return { |
| 204 |
"task_id": None, |
| 205 |
"succeeded": False, |
| 206 |
"value": None, |
| 207 |
"error": "background task manager is unavailable", |
| 208 |
} |
| 209 |
|
| 210 |
def _finish_modules(self, result): |
| 211 |
self._module_task_id = None |
| 212 |
callbacks = self._module_callbacks |
| 213 |
self._module_callbacks = [] |
| 214 |
error = result.get("error", "") |
| 215 |
modules = [] |
| 216 |
if result.get("succeeded"): |
| 217 |
modules = list(result.get("value") or []) |
| 218 |
self._modules = modules |
| 219 |
self._modules_timestamp = time.time() |
| 220 |
self._run_callbacks(callbacks, list(modules), error) |
| 221 |
|
| 222 |
def _finish_voices(self, module, result): |
| 223 |
self._voice_task_ids.pop(module, None) |
| 224 |
callbacks = self._voice_callbacks.pop(module, []) |
| 225 |
error = result.get("error", "") |
| 226 |
voices = [] |
| 227 |
if result.get("succeeded"): |
| 228 |
voices = list(result.get("value") or []) |
| 229 |
self._voices[module] = voices |
| 230 |
self._voice_timestamps[module] = time.time() |
| 231 |
self._run_callbacks(callbacks, module, list(voices), error) |
| 232 |
|
| 233 |
def _run_callbacks(self, callbacks, *args): |
| 234 |
for callback in callbacks: |
| 235 |
try: |
| 236 |
callback(*args) |
| 237 |
except Exception as error: |
| 238 |
self.env["runtime"]["DebugManager"].write_debug_out( |
| 239 |
"SpeechDiscoveryManager callback failed: " + str(error), |
| 240 |
debug.DebugLevel.ERROR, |
| 241 |
) |