From 8a5e9acd1e046dbfcaef58a1f41c4f6933ab72ad Mon Sep 17 00:00:00 2001 From: Storm Dragon Date: Sat, 28 Nov 2026 22:14:10 -0500 Subject: [PATCH] Better handling of speech-dispatcher. Allow games to save speech preferences. --- README.md | 65 +++++++++++++++++++++ __init__.py | 9 ++- speech.py | 132 +++++++++++++++++++++++++++++++++++++++++++ tests/test_speech.py | 121 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 326 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e6cffd..ffc55f1 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,71 @@ exit_game() or as the class, game.exit_game() ``` +#### Speech Dispatcher preferences + +Games can offer module, synthesis voice, language, rate, pitch and volume +controls through the existing speech singleton or the package functions below. +`supports_speech_settings()` lets an options menu offer these controls only +when Speech Dispatcher is active. Other providers continue using +accessible_output2, with no settings changes. + +```python +if sg.supports_speech_settings(): + modules = sg.list_speech_modules() # list of module names + errors = sg.apply_speech_settings({"module": modules[0]}) if modules else {} + voices = sg.list_speech_voices() # name, language, variant dictionaries + # Offer these names as choices; voices belong to the selected module. + if voices: + errors.update(sg.apply_speech_settings({"voice": voices[0]["name"]})) + errors.update(sg.apply_speech_settings({"rate": 25, "pitch": 0, "volume": 100})) + # Display/report errors before announcing a successful change. + +# Store this dictionary in the game's existing save data, e.g. as "speech". +saveData["speech"] = sg.get_speech_settings() +# At startup, after loading saveData and before the first spoken menu: +errors = sg.apply_speech_settings(saveData.get("speech", {}), preview=False) +``` + +`get_speech_settings()` returns a copy of successful explicit overrides, not +server defaults. An empty dictionary leaves the connection's system defaults +alone. Games own saving: the library never creates a separate preferences file. +For an INI save such as Grave Racer's `Settings`, store each returned key under +a `speech` section using `str(value)` and pass that section's dictionary back to +`apply_speech_settings()` on startup. Numeric strings from INI are accepted. +Skip applying saved preferences on unsupported providers and retain those saved +preferences if saves move between operating systems. + +Rate, pitch and volume use Speech Dispatcher's integer range **-100 to 100**. +Rate and pitch use 0 for the module's default; volume uses 100 for its normal +volume. These are not percentage controls, and modules may interpret or ignore +some controls differently. A volume of -100 may silence speech; an options menu +should provide a keyboard-accessible recovery action such as setting volume to +100. Changes affect subsequent speech on this game's connection only. + +Successful changes automatically speak "Speech settings preview." through the +updated connection, once after all supplied fields have been applied. Each +module, voice, rate, pitch or volume adjustment therefore previews its new sound. +Pass `previewText="Your sample text"` to customize the sample, or `preview=False` +for silent startup restoration. Repeated samples bypass duplicate suppression +and do not enter speech history. A failed preview returns a `preview` error while +keeping successfully applied preferences. + +The apply function returns `{field: error_message}`. Missing +fields remain unchanged. Invalid values and unavailable modules/voices are not +saved as successful overrides. Other valid fields still apply. A failed module +selection skips its language and voice, while retaining working speech. Module +changes discard the old saved voice, so rebuild the voice choices and select a +voice for the new module. Modules that cannot list voices still allow an explicit +voice name, subject to the server accepting it. Discovery connection errors +propagate; catch them in the game's options UI and report them to the player. + +Before submitting changes, review the diff and test with real speech: change +modules, rebuild voice choices, choose a voice, adjust all three numeric controls, +and verify menu announcements and interruption still work. Save and relaunch the +game to confirm restoration; also try a missing saved module or voice and an +accessible_output2 system. The automated suite uses fake clients and does not +prove audible output or a game's options/save integration. + ### Scoreboard Tracks scores and manages high score tables. diff --git a/__init__.py b/__init__.py index b1e50a1..7262274 100755 --- a/__init__.py +++ b/__init__.py @@ -44,7 +44,9 @@ from .i18n import set_language, set_language_reset, language_code, translated_fi # Import Speech class and functions from .speech import (messagebox, speak, Speech, speak_previous, speak_current, speak_next, set_text_display, - add_speech_listener, remove_speech_listener) + add_speech_listener, remove_speech_listener, + supports_speech_settings, list_speech_modules, list_speech_voices, + get_speech_settings, apply_speech_settings) # Import Scoreboard from .scoreboard import Scoreboard @@ -113,6 +115,11 @@ __all__ = [ 'set_text_display', 'add_speech_listener', 'remove_speech_listener', + 'supports_speech_settings', + 'list_speech_modules', + 'list_speech_voices', + 'get_speech_settings', + 'apply_speech_settings', # Translations 'set_language', 'set_language_reset', 'language_code', 'translated_file', diff --git a/speech.py b/speech.py index ab2de1e..ef5ce32 100644 --- a/speech.py +++ b/speech.py @@ -46,6 +46,7 @@ class Speech: # Try to initialize a speech provider self.provider = None self.providerName = None + self.speechSettings = {} # Try speechd first try: @@ -76,6 +77,112 @@ class Speech: # No speech providers found print("No speech providers found.") + def supports_speech_settings(self): + """Whether this connection supports Speech Dispatcher voice controls.""" + return self.providerName == "speechd" + + def list_speech_modules(self): + """Return available module names; empty on other providers. + + Connection errors propagate to the game's options UI. + """ + if not self.supports_speech_settings(): + return [] + return list(self.spd.list_output_modules()) + + def list_speech_voices(self): + """Return name/language/variant dictionaries for the active module. + + Select a module before listing its voices. An empty list can also mean + that the module cannot enumerate voices. Connection errors propagate. + """ + if not self.supports_speech_settings(): + return [] + return [dict(zip(("name", "language", "variant"), voice)) + for voice in self.spd.list_synthesis_voices()] + + def get_speech_settings(self): + """Return a saveable copy of successfully applied overrides. + + Empty means use the connection's system defaults. This is not a query + of the server defaults. The game owns writing this dictionary to disk. + """ + return dict(self.speechSettings) + + def apply_speech_settings(self, settings, preview=True, previewText=None): + """Apply a partial settings dictionary and return {field: error}. + + Keys: module, language, voice (a synthesis voice name), rate, pitch, + volume. Numeric values are integers from -100 to 100 in Dispatcher + units, not percentages. INI numeric strings are accepted as well. + Missing keys retain their previous values. Only successful changes + are remembered. Unsupported providers return errors without mutation. + No global Dispatcher or screen reader settings are changed. + Successful changes speak one preview using the updated connection. + Set preview=False when restoring a save at startup. previewText can + supply a translated game-specific sample; previews bypass duplicate + suppression and are excluded from speech history. + """ + setters = {"module": "set_output_module", "language": "set_language", + "voice": "set_synthesis_voice", "rate": "set_rate", + "pitch": "set_pitch", "volume": "set_volume"} + errors = {} + values = {} + changed = False + for key, value in settings.items(): + if key not in setters: + errors[key] = "Unknown speech setting" + continue + if not self.supports_speech_settings(): + errors[key] = "Speech settings require Speech Dispatcher" + continue + if key in ("rate", "pitch", "volume"): + try: + if isinstance(value, str): + value = int(value) + if type(value) is not int or not -100 <= value <= 100: + raise ValueError + except ValueError: + errors[key] = "Expected an integer from -100 to 100" + continue + elif not isinstance(value, str) or not value.strip() or any( + char in value for char in ("\r", "\n", "\x00")): + errors[key] = "Expected a nonempty single-line name" + continue + values[key] = value + + # Module first: synthesis voice names belong to a particular module. + for key, setter in setters.items(): + if key not in values: + continue + if key in ("language", "voice") and "module" in errors: + errors[key] = "The requested module could not be selected" + continue + try: + value = values[key] + if key == "module" and value not in self.spd.list_output_modules(): + raise ValueError("Speech module is unavailable") + if key == "voice": + voices = self.spd.list_synthesis_voices() + if voices and value not in [voice[0] for voice in voices]: + raise ValueError("Speech voice is unavailable in this module") + getattr(self.spd, setter)(value) + except Exception as error: + errors[key] = str(error) or type(error).__name__ + continue + if key == "module" and self.speechSettings.get(key) != value: + self.speechSettings.pop("voice", None) + self.speechSettings[key] = value + changed = True + if changed and preview: + try: + self.lastSpoken["text"] = None + self.speak(previewText if previewText is not None else _("Speech settings preview."), + interrupt=True, add_to_history=False) + except Exception as error: + errors["preview"] = str(error) or type(error).__name__ + return errors + def speak(self, text, interrupt=True, priority="normal", add_to_history=True): """Speak text using the configured speech provider and display on screen. @@ -177,6 +284,31 @@ class Speech: # Global instance for backward compatibility _speechInstance = None +def supports_speech_settings(): + """Whether the global speech provider offers Dispatcher settings.""" + return Speech.get_instance().supports_speech_settings() + + +def list_speech_modules(): + """List modules on the global speech connection.""" + return Speech.get_instance().list_speech_modules() + + +def list_speech_voices(): + """List synthesis voices for the global connection's current module.""" + return Speech.get_instance().list_speech_voices() + + +def get_speech_settings(): + """Return successfully applied global speech overrides for saving.""" + return Speech.get_instance().get_speech_settings() + + +def apply_speech_settings(settings, preview=True, previewText=None): + """Apply saved overrides to global speech; return per-field errors.""" + return Speech.get_instance().apply_speech_settings(settings, preview=preview, previewText=previewText) + + def speak(text, interrupt=True, priority="normal", add_to_history=True): """Speak text using the global speech instance. diff --git a/tests/test_speech.py b/tests/test_speech.py index 81aba22..776e896 100644 --- a/tests/test_speech.py +++ b/tests/test_speech.py @@ -222,5 +222,126 @@ class SpeechListenerTests(unittest.TestCase): module.pygame.display.get_surface.assert_called_once_with() +class SpeechSettingsTests(unittest.TestCase): + def setUp(self): + self.module = load_speech() + self.client = Mock() + self.client.list_output_modules.return_value = ("engine-a", "engine-b") + self.client.list_synthesis_voices.return_value = (("Voice A", "en", None),) + with patch.dict(sys.modules, {"speechd": SimpleNamespace(Client=lambda: self.client)}): + self.speech = self.module.Speech() + self.speech.speak = Mock() + + def test_discovery_and_save_restore_with_ini_strings(self): + self.assertTrue(self.speech.supports_speech_settings()) + self.assertEqual(self.speech.list_speech_modules(), ["engine-a", "engine-b"]) + self.assertEqual(self.speech.list_speech_voices(), [ + {"name": "Voice A", "language": "en", "variant": None}]) + self.assertEqual(self.speech.get_speech_settings(), {}) + settings = {"voice": "Voice A", "module": "engine-a", "language": "en", + "rate": "35", "pitch": -100, "volume": 100} + self.assertEqual(self.speech.apply_speech_settings(settings), {}) + saved = self.speech.get_speech_settings() + self.assertEqual(saved["rate"], 35) + self.assertLess(self.client.method_calls.index(unittest.mock.call.set_output_module("engine-a")), + self.client.method_calls.index(unittest.mock.call.set_synthesis_voice("Voice A"))) + self.client.set_rate.assert_called_once_with(35) + self.client.set_pitch.assert_called_once_with(-100) + self.client.set_volume.assert_called_once_with(100) + saved["pitch"] = 999 + self.assertEqual(self.speech.get_speech_settings()["pitch"], -100) + self.assertEqual(self.speech.apply_speech_settings(self.speech.get_speech_settings()), {}) + + def test_bad_values_do_not_reach_dispatcher(self): + for value in (True, 1.5, None, "fast", "1.5", 101, -101): + with self.subTest(value=value): + errors = self.speech.apply_speech_settings({"rate": value}) + self.assertIn("rate", errors) + for value in ("", "bad\nname", "bad\rname", "bad\x00name", None): + self.assertIn("voice", self.speech.apply_speech_settings({"voice": value})) + self.assertIn("unknown", self.speech.apply_speech_settings({"unknown": 1})) + self.client.set_rate.assert_not_called() + self.client.set_synthesis_voice.assert_not_called() + self.assertEqual(self.speech.get_speech_settings(), {}) + + def test_unavailable_module_blocks_dependent_voice_but_restores_rate(self): + errors = self.speech.apply_speech_settings({"module": "missing", "voice": "Voice A", "rate": 25}) + self.assertEqual(set(errors), {"module", "voice"}) + self.client.set_output_module.assert_not_called() + self.client.set_synthesis_voice.assert_not_called() + self.assertEqual(self.speech.get_speech_settings(), {"rate": 25}) + + def test_backend_rejection_keeps_previous_success(self): + self.speech.apply_speech_settings({"rate": 10}) + self.client.set_rate.side_effect = RuntimeError("Disconnected") + errors = self.speech.apply_speech_settings({"rate": 20, "pitch": 30}) + self.assertEqual(errors, {"rate": "Disconnected"}) + self.assertEqual(self.speech.get_speech_settings(), {"rate": 10, "pitch": 30}) + + def test_module_switch_forgets_old_saved_voice_and_rejects_missing_voice(self): + self.speech.apply_speech_settings({"module": "engine-a", "voice": "Voice A"}) + self.speech.apply_speech_settings({"module": "engine-b"}) + self.assertNotIn("voice", self.speech.get_speech_settings()) + self.assertIn("voice", self.speech.apply_speech_settings({"voice": "missing"})) + self.client.list_synthesis_voices.return_value = () + self.assertEqual(self.speech.apply_speech_settings({"voice": "Unlisted voice"}), {}) + + def test_other_providers_are_unchanged(self): + for providerName in (None, "accessible_output2"): + self.speech.providerName = providerName + self.assertFalse(self.speech.supports_speech_settings()) + self.assertEqual(self.speech.list_speech_modules(), []) + self.assertEqual(self.speech.list_speech_voices(), []) + self.assertEqual(set(self.speech.apply_speech_settings({"rate": 10})), {"rate"}) + self.assertEqual(self.speech.get_speech_settings(), {}) + self.client.set_rate.assert_not_called() + + def test_preview_runs_after_every_setting_on_the_same_connection(self): + observed = [] + self.client.set_output_module.side_effect = lambda value: observed.append(("module", value)) + self.client.set_rate.side_effect = lambda value: observed.append(("rate", value)) + self.speech.speak.side_effect = lambda *args, **kwargs: observed.append(("preview", args[0])) + errors = self.speech.apply_speech_settings({"rate": 40, "module": "engine-b"}, + previewText="Voice sample") + self.assertEqual(errors, {}) + self.assertEqual(observed, [("module", "engine-b"), ("rate", 40), ("preview", "Voice sample")]) + self.speech.speak.assert_called_once_with("Voice sample", interrupt=True, add_to_history=False) + + def test_repeated_previews_bypass_duplicate_suppression(self): + for rate in (20, 30): + self.speech.lastSpoken["text"] = "Voice sample" + self.speech.apply_speech_settings({"rate": rate}, previewText="Voice sample") + self.assertIsNone(self.speech.lastSpoken["text"]) + self.assertEqual(self.speech.speak.call_count, 2) + + def test_preview_reaches_dispatcher_after_new_rate_without_history(self): + self.speech.speak = self.module.Speech.speak.__get__(self.speech) + self.speech.displayText = False + with patch.dict(sys.modules, {"speechd": SimpleNamespace()}), \ + patch.object(self.module.pygame.time, "get_ticks", return_value=100): + for rate in (20, 30): + self.assertEqual(self.speech.apply_speech_settings( + {"rate": rate}, previewText="Same sample"), {}) + relevant = [call for call in self.client.method_calls + if call[0] in ("set_rate", "cancel", "say")] + self.assertEqual(relevant, [ + unittest.mock.call.set_rate(20), unittest.mock.call.cancel(), + unittest.mock.call.say("Same sample"), + unittest.mock.call.set_rate(30), unittest.mock.call.cancel(), + unittest.mock.call.say("Same sample")]) + + def test_restoration_empty_or_rejected_changes_do_not_preview(self): + self.speech.apply_speech_settings({"rate": 20}, preview=False) + self.speech.apply_speech_settings({}) + self.speech.apply_speech_settings({"module": "missing"}) + self.speech.speak.assert_not_called() + + def test_preview_failure_is_reported_without_losing_applied_settings(self): + self.speech.speak.side_effect = RuntimeError("Speech disconnected") + self.assertEqual(self.speech.apply_speech_settings({"pitch": 10}), + {"preview": "Speech disconnected"}) + self.assertEqual(self.speech.get_speech_settings(), {"pitch": 10}) + + if __name__ == "__main__": unittest.main()