Files
Athena-Deck/speech_text.py
T

277 lines
9.7 KiB
Python
Raw 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 normalize_for_german_speech(text: str) -> str:
"""Turn common visual notation into unambiguous spoken German."""
text = expand_german_abbreviations(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"\[([^]]+)\]\([^)]+\)", 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()