"""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 expand_german_abbreviations(text: str) -> str: """Expand unambiguous prose abbreviations, preserving URLs and filenames. Do not guess ambiguous forms such as St., S., Bd., or standalone min. Shared by the optional endpoint enhancer and Qwen's speech preparation. """ dotted = { 'u.a.': 'unter anderem', 'u.U.': 'unter Umständen', 'z.B.': 'zum Beispiel', 'd.h.': 'das heißt', 'i.d.R.': 'in der Regel', 'i.A.': 'im Auftrag', 'i.V.': 'in Vertretung', 'm.E.': 'meines Erachtens', 'm.W.': 'meines Wissens', 'o.g.': 'oben genannt', 's.o.': 'siehe oben', 's.u.': 'siehe unten', 'v.a.': 'vor allem', 'z.T.': 'zum Teil', } words = { 'bzw': 'beziehungsweise', 'ggf': 'gegebenenfalls', 'evtl': 'eventuell', 'usw': 'und so weiter', 'usf': 'und so fort', 'ca': 'circa', 'max': 'maximal', 'inkl': 'inklusive', 'exkl': 'exklusive', 'zzgl': 'zuzüglich', 'bzgl': 'bezüglich', 'bspw': 'beispielsweise', 'sog': 'sogenannt', 'vgl': 'vergleiche', 'Nr': 'Nummer', 'Abs': 'Absatz', 'Abb': 'Abbildung', 'Dr': 'Doktor', 'Prof': 'Professor', } # Work on prose spans only: replacing z.B. inside a URL/path/mail is unsafe. protected = r'(https?://[^\s<>]+|[\w.+-]+@[\w.-]+|(?]+)' rules = [(r'(? str: """Speech-only technical vocabulary; byte/bit unit case is significant. Protect code, paths, addresses, file names and entity IDs before rewriting prose. Product names without a known problematic spelling stay as written. """ protected = ( r'(`[^`\n]+`|https?://[^\s<>]+|[\w.+-]+@[\w.-]+' r'|(?]+' r'|\b[A-Za-z]:[\\/][^\s<>]+' r'|\b[A-Za-z_][\w-]*(?:[.\\][\w-]+)+)' ) units = { 'KiB': 'Kibibyte', 'MiB': 'Mebibyte', 'GiB': 'Gibibyte', 'TiB': 'Tebibyte', 'PiB': 'Pebibyte', 'kB': 'Kilobyte', 'KB': 'Kilobyte', 'MB': 'Megabyte', 'GB': 'Gigabyte', 'TB': 'Terabyte', 'PB': 'Petabyte', 'Kibit': 'Kibibit', 'Mibit': 'Mebibit', 'Gibit': 'Gibibit', 'kbit': 'Kilobit', 'Kbit': 'Kilobit', 'Mbit': 'Megabit', 'Gbit': 'Gigabit', 'Tbit': 'Terabit', 'kb': 'Kilobit', 'Mb': 'Megabit', 'Gb': 'Gigabit', 'MBit': 'Megabit', 'GBit': 'Gigabit', 'kHz': 'Kilohertz', 'MHz': 'Megahertz', 'GHz': 'Gigahertz', 'Hz': 'Hertz', 'ms': 'Millisekunden', 'µs': 'Mikrosekunden', 'μs': 'Mikrosekunden', 'ns': 'Nanosekunden', } vocab = { 'CPU': 'Ce Pe U', 'GPU': 'Ge Pe U', 'RAM': 'Arbeitsspeicher', 'VRAM': 'Grafikspeicher', 'SSD': 'Es Es De', 'HDD': 'Ha De De', 'NVMe': 'En Vau Em E', 'USB': 'U Es Be', 'PCIe': 'Pe Ce I Express', 'SSH': 'Es Es Ha', 'HTTP': 'Ha Te Te Pe', 'HTTPS': 'Ha Te Te Pe Es', 'API': 'A Pe I', 'DNS': 'De En Es', 'DHCP': 'De Ha Ce Pe', 'TCP': 'Te Ce Pe', 'UDP': 'U De Pe', 'IP': 'I Pe', 'IPv4': 'I Pe Version vier', 'IPv6': 'I Pe Version sechs', 'LAN': 'Lan', 'WLAN': 'We Lan', 'VPN': 'Vau Pe En', 'NAS': 'Nas', 'IOPS': 'Ein- und Ausgabeoperationen pro Sekunde', 'TTS': 'Te Te Es', 'STT': 'Es Te Te', 'MCP': 'Em Ce Pe', 'LLM': 'El El Em', 'SQL': 'Es Ku El', 'CLI': 'Ce El I', 'GUI': 'Ge U I', 'UID': 'U I De', 'GID': 'Ge I De', 'ext4': 'Ext vier', 'Ext4': 'Ext vier', 'XFS': 'Iks Ef Es', 'ZFS': 'Zett Ef Es', 'NTFS': 'En Te Ef Es', 'FAT32': 'Fat zweiunddreißig', 'Unraid': 'Anraid', 'Sonarr': 'Sonar', 'Radarr': 'Radar', 'Logfile': 'Logdatei', 'Logfiles': 'Logdateien', 'Logrotate': 'Log Rotation', 'Log Rotate': 'Log Rotation', 'Filesystem': 'Dateisystem', 'Filesystems': 'Dateisysteme', 'Home-Assistant': 'Home Assistant', 'SmartHome': 'Smart Home', } for key in ('Unraid', 'Sonarr', 'Radarr', 'Logfile', 'Logfiles', 'Logrotate', 'Log Rotate', 'Filesystem', 'Filesystems', 'Home-Assistant', 'SmartHome'): vocab[key.lower()] = vocab[key] # B/s and bit/s are only meaningful as units after a numeric quantity. unit_pattern = '|'.join(re.escape(k) for k in sorted(units, key=len, reverse=True)) def prose(value): value = re.sub( r'(? str: """Turn common visual notation into unambiguous spoken German.""" text = expand_german_abbreviations(text) text = prepare_technical_german(text) # 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"(?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) text = re.sub(r"`([^`]+)`", r"\1", 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()