From 13eefd0c84cb4a96e28b2ce2dd81b28dbe0f8a64 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 05:34:01 +0000 Subject: [PATCH] Voice: numbers are spoken digit by digit 431 becomes "vier drei eins" / "four three one", a decimal comma or point is said as "Komma" / "point", using the crew callouts' digit words of the game's language. Applies to the executive officer, the coach, crew reports and the voice test, with or without text clean-up. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_018daq29kru65UEEQQM3E6AK --- data/i18n/de.json | 1 + data/i18n/en.json | 1 + data/manual/18-llm.de.md | 2 +- data/manual/18-llm.en.md | 2 +- docs/manual/manual.de.md | 2 +- docs/manual/manual.en.md | 2 +- src/core/game_voice.py | 12 +++++++++--- src/llm/voice.py | 19 +++++++++++++++++++ tests/test_llm_voice.py | 17 +++++++++++++++-- 9 files changed, 49 insertions(+), 9 deletions(-) diff --git a/data/i18n/de.json b/data/i18n/de.json index 79116e34..28a03f29 100644 --- a/data/i18n/de.json +++ b/data/i18n/de.json @@ -7598,6 +7598,7 @@ "voice.help.tts_top_p": "Niedriger = weniger Ausreißer (Qwen-Standard 1,0). Links/Rechts ±0,05", "voice.help.tts_seed": "Feste Zahl = gleicher Vortrag über alle Sätze; -1 = zufällig. Eingabe: tippen", "voice.help.tts_clean": "Entfernt Emojis, Markdown, „haha“ und *lacht* vor dem Sprechen.", + "voice.digit_point": "Komma", "voice.seed_random": "-1 (zufällig)", "llm.invalid.tts_temperature": "Temperature muss zwischen 0 und 2 liegen.", "llm.invalid.tts_top_p": "top_p muss zwischen 0,05 und 1 liegen.", diff --git a/data/i18n/en.json b/data/i18n/en.json index 92913c84..5335b711 100644 --- a/data/i18n/en.json +++ b/data/i18n/en.json @@ -7598,6 +7598,7 @@ "voice.help.tts_top_p": "Lower = fewer outliers (Qwen default 1.0). Left/Right ±0.05", "voice.help.tts_seed": "Fixed number = same delivery across sentences; -1 = random. Enter: type", "voice.help.tts_clean": "Removes emojis, Markdown, \"haha\" and *laughs* before speaking.", + "voice.digit_point": "point", "voice.seed_random": "-1 (random)", "llm.invalid.tts_temperature": "Temperature must be between 0 and 2.", "llm.invalid.tts_top_p": "top_p must be between 0.05 and 1.", diff --git a/data/manual/18-llm.de.md b/data/manual/18-llm.de.md index 97a3335b..7b314b69 100644 --- a/data/manual/18-llm.de.md +++ b/data/manual/18-llm.de.md @@ -24,7 +24,7 @@ Das Modell läuft auf einem Server, nie auf der uConsole selbst. Der Schlüssel Ein OpenAI-kompatibler Sprachdienst (`/audio/speech`) gibt dem Ersten Offizier und der Crew eine natürliche Stimme. Er ist ab Werk aus; ohne ihn spricht die Crew weiter über `espeak-ng`, und sonst ändert sich nichts. Eingerichtet wird er unter `F10` Optionen, Seite 2, **Sprachmodell**, Seite **2 Stimme** (`Tab` oder `Bild auf`/`Bild ab` wechselt, ein Klick auf den Reiter auch): an/aus, die Serveradresse (voreingestellt `https://api.openai.com/v1`), das Sprechmodell (voreingestellt `gpt-4o-mini-tts`; `tts-1` geht auch), die Stimme (`Links`/`Rechts` wechselt durch die OpenAI-Stimmen, `Eingabe` tippt einen anderen Namen), der API-Schlüssel, **Erster Offizier spricht**, **Crew-Meldungen mit dieser Stimme** und **Stimme testen**, das einen Probesatz spricht und die Dauer zeigt. - Seite **3 Klang**: **Temperature** (niedriger = ruhiger und gleichmäßiger, höher = lebhafter; Qwen-Standard 0,9), **top_p** (niedriger = weniger Ausreißer; Qwen-Standard 1,0), **Seed** (eine feste Zahl hält den Vortrag über alle Sätze gleich; -1 = zufällig) und **Text vor dem Sprechen bereinigen** (ab Werk an: Emojis, Markdown, Links, „haha“ und Regieanweisungen wie *lacht* fallen weg). `Links`/`Rechts` ändern die Zahlen schrittweise, `Eingabe` oder ein Klick tippt eine. Temperature, top_p und Seed gehen nur an Dienste, die sie annehmen, etwa einen Qwen-TTS-Server hinter der OpenAI-kompatiblen Adresse; OpenAIs eigener Dienst bekommt sie nie, und ein Server, der sie ablehnt, wird ohne sie gefragt. -- Erster Offizier: Seine Antworten (Lagemeldung, Frage, getippter Befehl, Klassifizierungshilfe, Einweisung) und die Tipps des Coachs werden auf der uConsole gesprochen, sobald sie eintreffen. Lange Antworten enden nach etwa 700 Zeichen an einem Satzende. +- Erster Offizier: Seine Antworten (Lagemeldung, Frage, getippter Befehl, Klassifizierungshilfe, Einweisung) und die Tipps des Coachs werden auf der uConsole gesprochen, sobald sie eintreffen. Zahlen werden immer Ziffer für Ziffer gesprochen wie auf Wache (431 als „vier drei eins“, 0,9 als „null Komma neun“). Lange Antworten enden nach etwa 700 Zeichen an einem Satzende. - Crew: Mit eingeschalteten **gesprochenen Crew-Meldungen** (Optionen, Seite 2) spricht die Crew mit derselben Stimme statt mit `espeak-ng`; eine Meldung, die der Dienst nicht liefern kann, spricht `espeak-ng`. Meldungen, die älter als 20 s sind, fallen weg, statt verspätet zu kommen. - Der Schlüssel liegt in `~/.u-jagd/tts_key` oder kommt aus `U_JAGD_TTS_KEY`. Bleibt er leer, gilt der Schlüssel des Sprachmodells, wenn beide Adressen denselben Server nennen. Wie dieser gelangt er nie in Einstellungen, Spielstände, Protokolle oder einen Browser. - Die Stimme spielt auf einem eigenen Tonkanal und schneidet nie den Sonarton ab; Anfragen und Dekodieren laufen neben dem Spiel, ein langsamer Dienst hält also kein Bild an. Mit ausgeschaltetem Spielton wird nichts gesprochen. diff --git a/data/manual/18-llm.en.md b/data/manual/18-llm.en.md index 10aeb89d..615a8006 100644 --- a/data/manual/18-llm.en.md +++ b/data/manual/18-llm.en.md @@ -24,7 +24,7 @@ The model runs on a server, never on the uConsole itself. The key is typed as as An OpenAI-compatible speech service (`/audio/speech`) gives the executive officer and the crew a natural voice. It is off by default; without it the crew keeps its `espeak-ng` voice and nothing else changes. Set it up under `F10` Options, page 2, **Language model**, page **2 Voice** (`Tab` or `PgUp`/`PgDn` switches pages, a click on the tab too): on/off, the server address (preset `https://api.openai.com/v1`), the speech model (preset `gpt-4o-mini-tts`; `tts-1` works as well), the voice (`Left`/`Right` cycles the OpenAI voices, `Enter` types another name), the API key, **Executive officer speaks**, **Crew reports in this voice** and **Test voice**, which says a sample sentence and shows how long it took. - Page **3 Sound**: **Temperature** (lower = calmer and steadier, higher = livelier; Qwen default 0.9), **top_p** (lower = fewer outliers; Qwen default 1.0), **Seed** (a fixed number keeps the same delivery across sentences; -1 = random) and **Clean text before speaking** (on by default: emojis, Markdown, links, "haha" and stage directions such as *laughs* are removed). `Left`/`Right` step the numbers, `Enter` or a click types one. Temperature, top_p and seed are sent only to services that take them, such as a Qwen-TTS server behind the OpenAI-compatible address; OpenAI's own endpoint never gets them, and a server that refuses them is asked without. -- Executive officer: his answers (situation report, question, typed order, classification help, briefing) and the coach's tips are spoken on the uConsole as they arrive. Long answers are cut at a sentence end after about 700 characters. +- Executive officer: his answers (situation report, question, typed order, classification help, briefing) and the coach's tips are spoken on the uConsole as they arrive. Numbers are always spoken digit by digit, as on a watch (431 is "four three one", 0.9 is "zero point niner"). Long answers are cut at a sentence end after about 700 characters. - Crew: with **Spoken crew reports** switched on (options page 2) the crew's calls use the same voice instead of `espeak-ng`; a call the service cannot deliver is said by `espeak-ng`. Calls older than 20 s are dropped instead of said late. - The key lives in `~/.u-jagd/tts_key` or comes from `U_JAGD_TTS_KEY`. Left empty, the language model's key is used when both addresses name the same server. Like the model's key it never enters the settings, saves, logs or a browser. - The voice plays on its own audio channel and never cuts the sonar tone; requests and decoding run beside the game, so a slow service never stalls a frame. With the game sound off nothing is spoken. diff --git a/docs/manual/manual.de.md b/docs/manual/manual.de.md index 4100a542..94010dc1 100644 --- a/docs/manual/manual.de.md +++ b/docs/manual/manual.de.md @@ -2516,7 +2516,7 @@ Das Modell läuft auf einem Server, nie auf der uConsole selbst. Der Schlüssel Ein OpenAI-kompatibler Sprachdienst (`/audio/speech`) gibt dem Ersten Offizier und der Crew eine natürliche Stimme. Er ist ab Werk aus; ohne ihn spricht die Crew weiter über `espeak-ng`, und sonst ändert sich nichts. Eingerichtet wird er unter `F10` Optionen, Seite 2, **Sprachmodell**, Seite **2 Stimme** (`Tab` oder `Bild auf`/`Bild ab` wechselt, ein Klick auf den Reiter auch): an/aus, die Serveradresse (voreingestellt `https://api.openai.com/v1`), das Sprechmodell (voreingestellt `gpt-4o-mini-tts`; `tts-1` geht auch), die Stimme (`Links`/`Rechts` wechselt durch die OpenAI-Stimmen, `Eingabe` tippt einen anderen Namen), der API-Schlüssel, **Erster Offizier spricht**, **Crew-Meldungen mit dieser Stimme** und **Stimme testen**, das einen Probesatz spricht und die Dauer zeigt. - Seite **3 Klang**: **Temperature** (niedriger = ruhiger und gleichmäßiger, höher = lebhafter; Qwen-Standard 0,9), **top_p** (niedriger = weniger Ausreißer; Qwen-Standard 1,0), **Seed** (eine feste Zahl hält den Vortrag über alle Sätze gleich; -1 = zufällig) und **Text vor dem Sprechen bereinigen** (ab Werk an: Emojis, Markdown, Links, „haha“ und Regieanweisungen wie *lacht* fallen weg). `Links`/`Rechts` ändern die Zahlen schrittweise, `Eingabe` oder ein Klick tippt eine. Temperature, top_p und Seed gehen nur an Dienste, die sie annehmen, etwa einen Qwen-TTS-Server hinter der OpenAI-kompatiblen Adresse; OpenAIs eigener Dienst bekommt sie nie, und ein Server, der sie ablehnt, wird ohne sie gefragt. -- Erster Offizier: Seine Antworten (Lagemeldung, Frage, getippter Befehl, Klassifizierungshilfe, Einweisung) und die Tipps des Coachs werden auf der uConsole gesprochen, sobald sie eintreffen. Lange Antworten enden nach etwa 700 Zeichen an einem Satzende. +- Erster Offizier: Seine Antworten (Lagemeldung, Frage, getippter Befehl, Klassifizierungshilfe, Einweisung) und die Tipps des Coachs werden auf der uConsole gesprochen, sobald sie eintreffen. Zahlen werden immer Ziffer für Ziffer gesprochen wie auf Wache (431 als „vier drei eins“, 0,9 als „null Komma neun“). Lange Antworten enden nach etwa 700 Zeichen an einem Satzende. - Crew: Mit eingeschalteten **gesprochenen Crew-Meldungen** (Optionen, Seite 2) spricht die Crew mit derselben Stimme statt mit `espeak-ng`; eine Meldung, die der Dienst nicht liefern kann, spricht `espeak-ng`. Meldungen, die älter als 20 s sind, fallen weg, statt verspätet zu kommen. - Der Schlüssel liegt in `~/.u-jagd/tts_key` oder kommt aus `U_JAGD_TTS_KEY`. Bleibt er leer, gilt der Schlüssel des Sprachmodells, wenn beide Adressen denselben Server nennen. Wie dieser gelangt er nie in Einstellungen, Spielstände, Protokolle oder einen Browser. - Die Stimme spielt auf einem eigenen Tonkanal und schneidet nie den Sonarton ab; Anfragen und Dekodieren laufen neben dem Spiel, ein langsamer Dienst hält also kein Bild an. Mit ausgeschaltetem Spielton wird nichts gesprochen. diff --git a/docs/manual/manual.en.md b/docs/manual/manual.en.md index 5856914a..60978e13 100644 --- a/docs/manual/manual.en.md +++ b/docs/manual/manual.en.md @@ -2515,7 +2515,7 @@ The model runs on a server, never on the uConsole itself. The key is typed as as An OpenAI-compatible speech service (`/audio/speech`) gives the executive officer and the crew a natural voice. It is off by default; without it the crew keeps its `espeak-ng` voice and nothing else changes. Set it up under `F10` Options, page 2, **Language model**, page **2 Voice** (`Tab` or `PgUp`/`PgDn` switches pages, a click on the tab too): on/off, the server address (preset `https://api.openai.com/v1`), the speech model (preset `gpt-4o-mini-tts`; `tts-1` works as well), the voice (`Left`/`Right` cycles the OpenAI voices, `Enter` types another name), the API key, **Executive officer speaks**, **Crew reports in this voice** and **Test voice**, which says a sample sentence and shows how long it took. - Page **3 Sound**: **Temperature** (lower = calmer and steadier, higher = livelier; Qwen default 0.9), **top_p** (lower = fewer outliers; Qwen default 1.0), **Seed** (a fixed number keeps the same delivery across sentences; -1 = random) and **Clean text before speaking** (on by default: emojis, Markdown, links, "haha" and stage directions such as *laughs* are removed). `Left`/`Right` step the numbers, `Enter` or a click types one. Temperature, top_p and seed are sent only to services that take them, such as a Qwen-TTS server behind the OpenAI-compatible address; OpenAI's own endpoint never gets them, and a server that refuses them is asked without. -- Executive officer: his answers (situation report, question, typed order, classification help, briefing) and the coach's tips are spoken on the uConsole as they arrive. Long answers are cut at a sentence end after about 700 characters. +- Executive officer: his answers (situation report, question, typed order, classification help, briefing) and the coach's tips are spoken on the uConsole as they arrive. Numbers are always spoken digit by digit, as on a watch (431 is "four three one", 0.9 is "zero point niner"). Long answers are cut at a sentence end after about 700 characters. - Crew: with **Spoken crew reports** switched on (options page 2) the crew's calls use the same voice instead of `espeak-ng`; a call the service cannot deliver is said by `espeak-ng`. Calls older than 20 s are dropped instead of said late. - The key lives in `~/.u-jagd/tts_key` or comes from `U_JAGD_TTS_KEY`. Left empty, the language model's key is used when both addresses name the same server. Like the model's key it never enters the settings, saves, logs or a browser. - The voice plays on its own audio channel and never cuts the sonar tone; requests and decoding run beside the game, so a slow service never stalls a frame. With the game sound off nothing is spoken. diff --git a/src/core/game_voice.py b/src/core/game_voice.py index 869d0054..9880c7c5 100644 --- a/src/core/game_voice.py +++ b/src/core/game_voice.py @@ -17,6 +17,7 @@ import time import urllib.parse from collections import deque +from src.core.callouts import PREFIX as CALLOUT_PREFIX from src.core.i18n import localize, message from src.llm import keystore from src.llm import voice as voice_model @@ -92,12 +93,17 @@ class VoiceMixin: return False if role == "xo" and not self.preferences.tts_xo: return False - request = self.voice.say(text, self.llm_language(), role) + request = self.voice.say(self._voice_text(text), self.llm_language(), role) if request is None: return False self._voice_queue.append(request) return True + def _voice_text(self, text) -> str: + """Numbers digit by digit in the game's language ("vier drei eins").""" + digits = [self.tr(f"{CALLOUT_PREFIX}digit_{digit}") for digit in range(10)] + return voice_model.spell_digits(text, digits, self.tr("voice.digit_point")) + def voice_advisor_entry(self, entry) -> None: """Speak a finished answer the uConsole's own executive officer gave.""" if entry.get("status") != "done" or not entry.get("answer"): @@ -187,8 +193,8 @@ class VoiceMixin: if not self.voice_ready(): self.voice_test = dict(status="failed", error="no_audio") return False - request = self.voice.say(localize(message("voice.test.phrase"), self.tr), - self.llm_language(), "test") + phrase = localize(message("voice.test.phrase"), self.tr) + request = self.voice.say(self._voice_text(phrase), self.llm_language(), "test") if request is None: self.voice_test = dict(status="failed", error="busy") return False diff --git a/src/llm/voice.py b/src/llm/voice.py index 6ee1cc1b..a7bf21c9 100644 --- a/src/llm/voice.py +++ b/src/llm/voice.py @@ -113,6 +113,25 @@ _EMOJI = re.compile("[\U0001F000-\U0001FAFF\U00002600-\U000027BF\U00002B00-\U000 _BULLET = re.compile(r"^\s*(?:[-*•]|\d+[.)])\s+", re.MULTILINE) +# A number, with an optional decimal part ("431", "0,9", "12.5"). +_NUMBER = re.compile(r"\d+(?:[.,]\d+)?") + + +def spell_digits(text, digits, point: str) -> str: + """Every number digit by digit, the way a watch speaks it: "431" becomes + "vier drei eins" (``digits`` are the ten words, ``point`` the word for a + decimal comma or point).""" + if type(text) is not str: + return "" + + def spell(match) -> str: + words = [point if char in ".," else digits[int(char)] for char in match.group()] + return " " + " ".join(words) + " " + + text = re.sub(r" {2,}", " ", _NUMBER.sub(spell, text)) + return re.sub(r" ([,.!?;:])", r"\1", text).strip() + + def clean_for_speech(text) -> str: """Only what a person would say: no emojis, Markdown, links, laughter ("haha", "lol") or stage directions (*laughs*, (seufzt), [pause]).""" diff --git a/tests/test_llm_voice.py b/tests/test_llm_voice.py index ab2b81a8..f27ebff5 100644 --- a/tests/test_llm_voice.py +++ b/tests/test_llm_voice.py @@ -117,6 +117,17 @@ def test_anything_else_is_refused(raw): voice.parse_wav(raw) +@pytest.mark.parametrize("text,said", [ + ("Peilung 431, Entfernung 0,9 sm.", "Peilung vier drei eins, Entfernung null Komma neun sm."), + ("Kurs 270!", "Kurs zwo sieben null!"), + ("F7 drücken", "F sieben drücken"), + ("Keine Zahl.", "Keine Zahl."), +], ids=["bearing_and_decimal", "punctuation", "inside_a_word", "none"]) +def test_numbers_are_spoken_digit_by_digit(text, said): + digits = "null eins zwo drei vier fünf sechs sieben acht neun".split() + assert voice.spell_digits(text, digits, "Komma") == said + + def test_clip_is_resampled_to_the_mixer_and_levelled(): pcm = voice.to_pcm(TONE, 24000, 22050) assert pcm.dtype == np.int16 and abs(len(pcm) - 22050) <= 1 @@ -282,8 +293,9 @@ def test_off_by_default_the_crew_keeps_espeak(monkeypatch): def test_executive_officer_speaks_his_answer(): - with FakeLlmServer("Lage ruhig, kein Kontakt.") as llm, FakeSpeechServer() as speech: + with FakeLlmServer("Lage ruhig, Kontakt in 431.") as llm, FakeSpeechServer() as speech: game = _game() + game._set_preference("language", "de") mixer = _Mixer(game) game.preferences = dataclasses.replace(game.preferences, llm_enabled=True, llm_url=llm.url, llm_model="m") @@ -291,7 +303,8 @@ def test_executive_officer_speaks_his_answer(): _voice_on(game, speech) assert isinstance(game.advisor_ask("situation"), dict) assert _pump(game, lambda: mixer.played) - assert speech.requests[0]["input"] == "Lage ruhig, kein Kontakt." + # Numbers digit by digit, the way the watch speaks them. + assert speech.requests[0]["input"] == "Lage ruhig, Kontakt in vier drei eins." # Switched off: the next answer stays silent. game.set_voice_preference("tts_xo", False) assert isinstance(game.advisor_ask("situation"), dict)