Restore German speech notation from legacy TTS gateway

This commit is contained in:
Mikei386 committed 2026-10-06 14:22:41 +02:00
1 parent 41dd7471cd
commit a0056fa56f
6 files changed
+323 -3

No files matched your search

+1
View File
@@ -20,6 +20,7 @@ FILES = ['assets/tts-presets/bundle.safetensors','assets/tts-presets/bundle.json
FILES += ['xvc.py','xvc_runtime.py','xvc_sources.json','xvc-ui.js','deploy/xvc-requirements.lock','deploy/prepare_xvc.py']
FILES += ['cuda_overlay.py','remix.py','remix_runtime.py','remix_worker.py','remix_sources.json','clearvoice_worker.py','deploy/ladypoly/patch_remix.py']
FILES += ['speech_text.py']
FILES += sorted(str(p.relative_to(ROOT)) for p in (ROOT/'deploy/xvc-web').rglob('*') if p.is_file() and not {'__pycache__','.pytest_cache'} & set(p.parts))
FILES += sorted(str(p.relative_to(ROOT)) for p in (ROOT/'deploy/applio-web').rglob('*') if p.is_file() and not {'__pycache__','.pytest_cache'} & set(p.parts))
+28
View File
@@ -0,0 +1,28 @@
# German speech notation
Deck prepares spoken text in `speech_text.prepare_for_speech` before both complete-WAV and streaming TTS generation. Chat text is unchanged. The normalization was ported from the deployed old `mike-ai-tts-gateway` and its `prepare_for_qwen_speech` path.
German examples:
- `29 km/h` → `29 Kilometer pro Stunde`
- `15°–23 °C` → `15 bis 23 Grad`
- `22° / 10°` → `Höchstwert 22 Grad, Tiefstwert 10 Grad`
- `16:09 Uhr` → `16 Uhr 9`
- `05–06 Uhr` → `5 bis 6 Uhr`
- `04.–05.09.` → `4. bis 5. September`
The preparation also handles percentages, IPv4 addresses, postal codes, aspect-ratio cues, selected abbreviations and Markdown. German expansions apply only to German language settings. Hyphenated words retain their punctuation for Qwen prosody. Chunking preserves ordinal dates such as `5. Oktober`.
Validation: 78 speech/endpoint unit tests and two NumPy PCM streaming tests passed on Athena in isolated containers. The upload regression test verifies that valid PCM WAV input retains every frame, including the beginning.
## OpenWebUI recording onset investigation (2026-10-06)
The installed OpenWebUI v0.11.4 conversation recorder starts MediaRecorder after sound is detected and has no pre-roll audio buffer. This can truncate initial speech. Normal dictation starts after asynchronous microphone initialization; speech before recording is ready is not captured. The user reports normal dictation succeeds with a one-second pause but conversation mode mangles the first word.
This is consistent with client-side onset clipping, but the user's original uploaded audio has not been captured and inspected, so an ASR contribution is not ruled out. No OpenWebUI patch was applied. Missing samples cannot be reconstructed in the router.
Official source:
- https://github.com/open-webui/open-webui/blob/v0.11.4/src/lib/components/chat/MessageInput/CallOverlay.svelte
- https://github.com/open-webui/open-webui/blob/v0.11.4/src/lib/components/chat/MessageInput/VoiceRecording.svelte
A similar user report (not proof of the cause here): https://github.com/open-webui/open-webui/discussions/24469
+238
View File
@@ -0,0 +1,238 @@
"""Speech-only text preparation ported from the deployed old Athena TTS gateway.
Source: AI-Profile-Router/platform/docker/tts-gateway/tts_gateway.py.
Preserve Qwen prosody; never rewrite the chat text or switch voice/language.
"""
import re
import unicodedata
GERMAN_MONTHS = {
1: "Januar", 2: "Februar", 3: "März", 4: "April",
5: "Mai", 6: "Juni", 7: "Juli", 8: "August",
9: "September", 10: "Oktober", 11: "November", 12: "Dezember",
}
GERMAN_DIGITS = {
"0": "null", "1": "eins", "2": "zwei", "3": "drei", "4": "vier",
"5": "fünf", "6": "sechs", "7": "sieben", "8": "acht", "9": "neun",
}
def _spoken_date(match: re.Match) -> str:
day = int(match.group(1))
month = int(match.group(2))
year = match.group(3)
month_name = GERMAN_MONTHS.get(month)
if not month_name or not 1 <= day <= 31:
return match.group(0)
result = f"{day}. {month_name}"
if year:
result += f" {year}"
return result
def _spoken_short_date_range(match: re.Match) -> str:
first_day = int(match.group(1))
last_day = int(match.group(2))
month = int(match.group(3))
year = match.group(4)
month_name = GERMAN_MONTHS.get(month)
if not month_name or not 1 <= first_day <= 31 or not 1 <= last_day <= 31:
return match.group(0)
result = f"{first_day}. bis {last_day}. {month_name}"
if year:
result += f" {year}"
return result
def _spoken_full_date_range(match: re.Match) -> str:
first_day = int(match.group(1))
first_month = int(match.group(2))
last_day = int(match.group(3))
last_month = int(match.group(4))
year = match.group(5)
first_name = GERMAN_MONTHS.get(first_month)
last_name = GERMAN_MONTHS.get(last_month)
if (not first_name or not last_name
or not 1 <= first_day <= 31 or not 1 <= last_day <= 31):
return match.group(0)
if first_month == last_month:
result = f"{first_day}. bis {last_day}. {last_name}"
else:
result = f"{first_day}. {first_name} bis {last_day}. {last_name}"
if year:
result += f" {year}"
return result
def _spell_digits(value: str) -> str:
return " ".join(GERMAN_DIGITS[digit] for digit in value)
def _spoken_ipv4(match: re.Match) -> str:
"""Keep IPv4 octets intact while making the separators pronounceable."""
return " Punkt ".join(str(int(part)) for part in match.group(0).split("."))
def _normalize_aspect_ratios(text: str) -> str:
"""Speak colon notation as a ratio only when the surrounding text says so.
A bare ``16:09`` remains a clock time. This deliberately avoids a global
replacement of common ratios because ``16:9`` can also be a valid time.
"""
cue = (
r"(?:Seitenverh[aä]ltnis|Bildseitenverh[aä]ltnis|Bildformat|"
r"Videoformat|Hochformat|Querformat|Format|Aspect[- ]?Ratio)"
)
text = re.sub(
rf"\b({cue}\b(?:\s+(?:von|im|ist|betr[aä]gt))?\s*[\(\[]?\s*)"
rf"(\d{{1,3}})\s*:\s*(\d{{1,3}})",
lambda match: (
f"{match.group(1)}{int(match.group(2))} zu {int(match.group(3))}"
),
text,
flags=re.IGNORECASE,
)
return re.sub(
rf"\b(\d{{1,3}})\s*:\s*(\d{{1,3}})"
rf"(\s*[-‐‑‒–—−]?\s*{cue}\b)",
lambda match: (
f"{int(match.group(1))} zu {int(match.group(2))}{match.group(3)}"
),
text,
flags=re.IGNORECASE,
)
def normalize_for_german_speech(text: str) -> str:
"""Turn common visual notation into unambiguous spoken German."""
text = re.sub(r"\bv\.\s*a\.", "vor allem", text, flags=re.IGNORECASE)
text = re.sub(r"\bca\.", "circa", text, flags=re.IGNORECASE)
text = re.sub(r"\bmax\.", "maximal", text, flags=re.IGNORECASE)
# Run these before the date rule: otherwise 192.168.1.5 could be partly
# interpreted as a visual date.
text = re.sub(
r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
_spoken_ipv4,
text,
)
# A colon is ambiguous between an aspect ratio and a clock time. Resolve
# ratios first, but only when an explicit format cue is present.
text = _normalize_aspect_ratios(text)
text = re.sub(
r"\b([01]?\d|2[0-3]):([0-5]\d)\b(?:\s*Uhr\b)?",
lambda match: f"{int(match.group(1))} Uhr {int(match.group(2))}",
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"\b([01]?\d|2[0-3])\s*[-‐‑‒–—−]\s*"
r"([01]?\d|2[0-3])\s*Uhr\b",
lambda match: f"{int(match.group(1))} bis {int(match.group(2))} Uhr",
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"(-?\d+(?:[,.]\d+)?)[ \t]*°?[ \t]*[-‐‑‒–—−][ \t]*"
r"(-?\d+(?:[,.]\d+)?)[ \t]*°[ \t]*(?:C)?",
r"\1 bis \2 Grad",
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"(-?\d+(?:[,.]\d+)?)[ \t]*°[ \t]*(?:C)?[ \t]*/[ \t]*"
r"(-?\d+(?:[,.]\d+)?)[ \t]*°[ \t]*(?:C)?",
r"Höchstwert \1 Grad, Tiefstwert \2 Grad",
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"(-?\d+(?:[,.]\d+)?)[ \t]*°[ \t]*(?:C)?",
r"\1 Grad",
text,
flags=re.IGNORECASE,
)
# Date ranges are deliberately strict: both variants require dotted
# calendar notation, so ordinary numeric ranges remain untouched.
text = re.sub(
r"\b([0-3]?\d)\.([01]?\d)\.\s*[-‐‑‒–—−]\s*"
r"([0-3]?\d)\.([01]?\d)\.(?:(\d{4})\b)?",
_spoken_full_date_range,
text,
)
text = re.sub(
r"\b([0-3]?\d)\.\s*[-‐‑‒–—−]\s*"
r"([0-3]?\d)\.([01]?\d)\.(?:(\d{4})\b)?",
_spoken_short_date_range,
text,
)
text = re.sub(
r"\b([0-3]?\d)\.([01]?\d)\.(?:(\d{4})\b)?",
_spoken_date,
text,
)
text = re.sub(
r"\bPLZ\s+(\d{5})\b",
lambda match: "Postleitzahl " + _spell_digits(match.group(1)),
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"\((\d{5})\)",
lambda match: "(Postleitzahl " + _spell_digits(match.group(1)) + ")",
text,
)
text = re.sub(
r"https?://(?:www\.)?([^/\s)]+)(?:/[^\s)]*)?",
lambda match: match.group(1),
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"\b([A-Za-z0-9][A-Za-z0-9-]*(?:\.[A-Za-z0-9-]+)*)"
r"\.(de|com|org|net|io|ai)\b",
lambda match: (
match.group(1).replace(".", " Punkt ")
+ " Punkt "
+ (
"de" if match.group(2).lower() == "de"
else " ".join(match.group(2).upper())
)
),
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"(-?\d+(?:[,.]\d+)?)\s*km\s*(?:/\s*)?h\b",
r"\1 Kilometer pro Stunde",
text,
flags=re.IGNORECASE,
)
text = re.sub(r"(\d)\s*%", r"\1 Prozent", text)
text = re.sub(r"\b(\d+)\s*[×x]\s*", r"\1 mal ", text)
return text
def prepare_for_speech(text: str, language: str = "German") -> str:
"""Normalize technical display text without destroying Qwen's prosody."""
text = re.sub(r"```.*?```", " Codeblock. ", text, flags=re.DOTALL)
text = re.sub(r"`([^`]+)`", r"\1", text)
text = re.sub(r"!\[([^]]*)\]\([^)]+\)", r"\1", text)
text = re.sub(r"\[([^]]+)\]\([^)]+\)", r"\1", text)
text = re.sub(r"(?m)^\s{0,3}#{1,6}\s*", "", text)
text = re.sub(r"(?m)^\s*[-*+]\s+", "", text)
text = text.replace("_", " ")
text = text.replace("→", ". ").replace("←", ". ")
if language.lower() in ("de", "german", "deutsch"):
text = normalize_for_german_speech(text)
# Preserve slashes until after unit normalization so km/h becomes
# "Kilometer pro Stunde" instead of the broken "Kilometer, h".
text = text.replace("/", ", ")
text = "".join(
char for char in text
if unicodedata.category(char) not in {"So", "Cs"}
)
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\s*\n+\s*", ". ", text)
return text.strip()
+41
View File
@@ -0,0 +1,41 @@
import unittest
from speech_text import prepare_for_speech
from tts_worker import spoken_chunks
class SpeechPreparationTests(unittest.TestCase):
def test_weather_units_and_ranges(self):
text=prepare_for_speech('15°–23 °C, 93 %, ca. 12 mm, v.a. um 05–06 Uhr, Wind max. 16 km/h.')
for expected in ('15 bis 23 Grad','93 Prozent','circa 12 mm','vor allem','5 bis 6 Uhr','Wind maximal 16 Kilometer pro Stunde'):
self.assertIn(expected,text)
for original in ('29 km/h','29 KM / H','29 kmh'):
self.assertEqual(prepare_for_speech(original),'29 Kilometer pro Stunde')
def test_clock_is_distinct_from_aspect_ratio(self):
text=prepare_for_speech('Beginn um 16:09 Uhr, Fehler um 02:14; das Videoformat ist 16:9.')
self.assertIn('16 Uhr 9',text);self.assertNotIn('16 Uhr 9 Uhr',text)
self.assertIn('2 Uhr 14',text);self.assertIn('Videoformat ist 16 zu 9',text)
def test_dates_and_ip_addresses(self):
text=prepare_for_speech('full_kiosk (192.168.1.5): 2× Timeout seit 01.09. und vom 04.–05.09. sowie 04.09.–06.10.2026.')
for expected in ('full kiosk','192 Punkt 168 Punkt 1 Punkt 5','2 mal Timeout','1. September','4. bis 5. September','4. September bis 6. Oktober 2026'):
self.assertIn(expected,text)
def test_high_low_and_postcode(self):
text=prepare_for_speech('Rastatt (76437), 22° / 10°.')
self.assertIn('Postleitzahl sieben sechs vier drei sieben',text)
self.assertIn('Höchstwert 22 Grad, Tiefstwert 10 Grad',text)
def test_only_speech_is_rewritten(self):
original='## Wind\n- [Quelle](https://example.org): **29 km/h** 😊'
spoken=prepare_for_speech(original)
self.assertIn('29 Kilometer pro Stunde',spoken);self.assertNotIn('https:',spoken);self.assertNotIn('😊',spoken)
self.assertIn('29 km/h',original)
def test_other_languages_do_not_receive_german_words(self):
self.assertNotIn('Kilometer pro Stunde',prepare_for_speech('29 km/h at 02:14','English'))
def test_worker_prepares_before_sentence_splitting(self):
chunks=spoken_chunks(dict(text='Am 05.10.2026 um 02:14 Uhr: 29 km/h. Alles gut!',language='German'))
self.assertIn('5. Oktober 2026',chunks[0]);self.assertIn('2 Uhr 14',chunks[0])
self.assertIn('29 Kilometer pro Stunde',chunks[0]);self.assertEqual(chunks[-1],'Alles gut!')
def test_punctuation_and_hyphenated_words_keep_qwen_prosody(self):
self.assertEqual(prepare_for_speech('Docker-Container – wirklich? Ja!'),'Docker-Container – wirklich? Ja!')
with self.assertRaises(ValueError):spoken_chunks(dict(text='😊',language='German'))
if __name__=='__main__':unittest.main()
+6
View File
@@ -25,6 +25,12 @@ class STTTests(unittest.TestCase):
with self.assertRaises(ValueError):s.build()
class BrowserUploadTests(unittest.TestCase):
def test_valid_pcm_upload_preserves_audio_from_the_first_frame(self):
from stt import normalize_transcription_audio
import struct
out=io.BytesIO();samples=struct.pack('<1600h',*([9000,-9000]*800))
with wave.open(out,'wb') as w:w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(samples)
raw=out.getvalue();self.assertEqual(normalize_transcription_audio(raw),raw)
def handler(self,body,headers=None):
return SimpleNamespace(headers=headers or {'Transfer-Encoding':'chunked'},rfile=io.BytesIO(body))
def test_chunked_upload(self):
+9 -3
View File
@@ -1,5 +1,6 @@
"""Persistent offline Qwen-TTS worker; line-delimited stdin, no prompt logging."""
import contextlib,json,re,sys
from speech_text import prepare_for_speech
from pathlib import Path
class PresetBaseModel:
@@ -20,7 +21,7 @@ def base_presets():
def text_chunks(text,limit=256):
chunks=[];current=''
for sentence in re.split(r'(?<=[.!?])\s+',text.strip()):
for sentence in re.split(r'(?<=[!?])\s+|(?<!\d\.)(?<=\.)\s+',text.strip()):
for word in re.findall(r'\S+\s*',sentence+' '):
if current and len(current)+len(word)>limit:chunks.append(current.strip());current=''
while len(word.strip())>limit:
@@ -29,10 +30,15 @@ def text_chunks(text,limit=256):
if current:chunks.append(current.strip());current=''
return chunks
def spoken_chunks(request):
text=prepare_for_speech(request['text'],request['language'])
if not text:raise ValueError('No speakable text')
return text_chunks(text)
def streaming_wave(model,request):
import numpy as np
root=Path(request['output']);parts=[];rate=None;index=0;total=0
for text in text_chunks(request['text']):
for text in spoken_chunks(request):
for audio,current_rate,_ in model.generate_custom_voice_streaming(text=text,language=request['language'],speaker=request['speaker'],max_new_tokens=1024,chunk_size=4):
if current_rate!=24000 or rate is not None and rate!=current_rate:raise ValueError('Unsupported streaming sample rate')
rate=current_rate;wave=np.asarray(audio).reshape(-1)
@@ -74,7 +80,7 @@ def main():
if request.get('streaming'):
wave,rate=streaming_wave(model,request);pieces=[wave]
else:
for text in text_chunks(request['text']):
for text in spoken_chunks(request):
waves,current_rate=model.generate_custom_voice(text=text,language=request['language'],speaker=request['speaker'],max_new_tokens=1024)
if rate is not None and rate!=current_rate:raise ValueError('Inconsistent sample rate')
rate=current_rate;pieces.append(waves[0])