Files

375 lines
15 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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.-]+|(?<!\w)/[^\s<>]+)'
rules = [(r'(?<![\w./@-])' + r'[ \t\u00a0\u202f]*'.join(re.escape(c) for c in key)
+ r'(?![\w/@-])', value) for key, value in dotted.items()]
rules += [(r'(?<![\w./@-])' + re.escape(key) + r'\.(?![\w/@-])', value)
for key, value in words.items()]
# Boundaries also prevent matching abbreviation fragments in filenames.
def prose(value):
for pattern, replacement in rules:
value = re.sub(pattern, replacement, value, flags=re.IGNORECASE)
return value
spans = re.split(protected, text)
return ''.join(value if i % 2 else prose(value) for i, value in enumerate(spans))
def prepare_technical_german(text: str) -> 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'|(?<![\w:])(?:/(?!s\b|min\b|h\b)|~/)[^\s<>]+'
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 = {
'CEST': 'Ce E Es Te', 'CET': 'Ce E Te', 'UTC': 'U Te Ce',
'MESZ': 'Em E Es Zett', 'MEZ': 'Em E Zett',
'MP3': 'Em Pe drei', 'mp3': 'Em Pe drei', 'PCM': 'Pe Ce Em',
'API/MCP': 'A Pe I und Em Ce Pe',
'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):
# Restrict log-field rules to known names and literal values.
fields = {'transcoding': 'Transkodierung', 'format': 'Format',
'tracksImported': 'importierte Titel', 'tracksMissing': 'fehlende Titel',
'RestartCount': 'Neustarts'}
value = re.sub(
r'(?<![\w./@-])(' + '|'.join(fields) + r')\s*(?:=|:)\s*(false|true|raw|\d+)(?!\w|\.\w)',
lambda m: fields[m[1]] + ' gleich ' +
{'false': 'falsch', 'true': 'wahr', 'raw': 'unverändert'}.get(m[2], m[2]), value)
value = re.sub(
r'(?<![\w./-])(\d+)\s*/\s*(\d+)\s*(kbps|Kbps|Mbps|Gbps|Tbps)\b',
lambda m: m[1] + ' ' + m[3] + ' oder ' + m[2] + ' ' + m[3], value)
value = re.sub(
r'(?<![\w./-])(\d+(?:[,.]\d+)?)\s+s\b(?![\w/]|\.[\w])',
lambda m: m[1] + ' Sekunden', value)
value = re.sub(
r'(?<![\w./-])(\d+(?:[,.]\d+)?)\s*(kWh|Wh|kW|W|mV|V|mA|A)(?![\w/-]|\.[\w])',
lambda m: m[1] + ' ' + {'kWh': 'Kilowattstunden', 'Wh': 'Wattstunden',
'kW': 'Kilowatt', 'W': 'Watt', 'mV': 'Millivolt', 'V': 'Volt',
'mA': 'Milliampere', 'A': 'Ampere'}[m[2]], value)
value = re.sub(
r'(?<![\w.-])(\d+(?:[,.]\d+)?)\s*(B|bit)\s*/\s*s\b',
lambda m: m[1] + (' Byte' if m[2] == 'B' else ' Bit') + ' pro Sekunde', value)
value = re.sub(
r'(?<![\w.-])(\d+(?:[,.]\d+)?)\s*(kbps|Kbps|Mbps|Gbps|Tbps)\b',
lambda m: m[1] + ' ' + {'k': 'Kilobit', 'K': 'Kilobit',
'M': 'Megabit', 'G': 'Gigabit', 'T': 'Terabit'}[m[2][0]] + ' pro Sekunde', value)
# Allow units attached to digits, but not embedded in identifiers.
value = re.sub(
r'(?<![\w.-])(?:(\d+(?:[,.]\d+)?)[ \t]*)?(' + unit_pattern
+ r')(?![\w-]|\.[\w]|/(?!s\b|min\b|h\b))(?:[ \t]*/[ \t]*(s|min|h)\b)?',
lambda m: (m[1] + ' ' if m[1] else '') + units[m[2]]
+ ({'s': ' pro Sekunde', 'min': ' pro Minute', 'h': ' pro Stunde'}[m[3]] if m[3] else ''), value)
pattern = '|'.join(re.escape(k) for k in sorted(vocab, key=len, reverse=True))
return re.sub(r'(?<![\w./@-])(' + pattern + r')(?![\w/@-]|\.[\w])',
lambda m: vocab[m[0]], value)
spans = re.split(protected, text)
return ''.join(value if i % 2 else prose(value) for i, value in enumerate(spans))
def normalize_for_german_speech(text: str) -> 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()