Spaces:
Running
on
Zero
Running
on
Zero
File size: 12,599 Bytes
5ecf3a1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
"""
German Text Preprocessing Module for TTS
Handles normalization of numbers, dates, decimal numbers, and other text elements
to their spoken form in German.
"""
import re
class GermanTextPreprocessor:
"""
Preprocesses German text for TTS by converting numbers, dates, and special
characters into their spoken equivalents.
"""
# Number words for German
ONES = {
0: "", 1: "eins", 2: "zwei", 3: "drei", 4: "vier",
5: "fünf", 6: "sechs", 7: "sieben", 8: "acht", 9: "neun"
}
# Digit names for reading individual digits (including zero)
DIGITS = {
0: "null", 1: "eins", 2: "zwei", 3: "drei", 4: "vier",
5: "fünf", 6: "sechs", 7: "sieben", 8: "acht", 9: "neun"
}
TEENS = {
10: "zehn", 11: "elf", 12: "zwölf", 13: "dreizehn",
14: "vierzehn", 15: "fünfzehn", 16: "sechzehn",
17: "siebzehn", 18: "achtzehn", 19: "neunzehn"
}
TENS = {
2: "zwanzig", 3: "dreißig", 4: "vierzig",
5: "fünfzig", 6: "sechzig", 7: "siebzig",
8: "achtzig", 9: "neunzig"
}
SCALES = [
(1000000000, "Milliarde", "Milliarden"),
(1000000, "Million", "Millionen"),
(1000, "tausend", "tausend")
]
# Ordinal number endings
ORDINAL_ONES = {
1: "erster", 2: "zweiter", 3: "dritter", 4: "vierter",
5: "fünfter", 6: "sechster", 7: "siebter", 8: "achter", 9: "neunter"
}
ORDINAL_TEENS = {
10: "zehnter", 11: "elfter", 12: "zwölfter", 13: "dreizehnter",
14: "vierzehnter", 15: "fünfzehnter", 16: "sechzehnter",
17: "siebzehnter", 18: "achtzehnter", 19: "neunzehnter"
}
# Month names
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"
}
MONTH_ABBREV = {
"jan": "Januar", "feb": "Februar", "mär": "März", "apr": "April",
"mai": "Mai", "jun": "Juni", "jul": "Juli", "aug": "August",
"sep": "September", "sept": "September", "okt": "Oktober",
"nov": "November", "dez": "Dezember"
}
def __init__(self):
"""Initialize the German text preprocessor."""
pass
def _number_to_words(self, num: int) -> str:
"""
Convert a cardinal number to its German word form.
Args:
num: Integer to convert
Returns:
German word representation of the number
"""
if num == 0:
return "null"
if num < 0:
return "minus " + self._number_to_words(-num)
# Handle 1-9
if num < 10:
return self.ONES[num]
# Handle 10-19
if num < 20:
return self.TEENS[num]
# Handle 20-99
if num < 100:
ones = num % 10
tens = num // 10
if ones == 0:
return self.TENS[tens]
else:
ones_word = self.ONES[ones]
# Special case: "eins" becomes "ein" in compound numbers
if ones == 1:
ones_word = "ein"
return f"{ones_word}und{self.TENS[tens]}"
# Handle 100-999
if num < 1000:
hundreds = num // 100
remainder = num % 100
hundreds_word = "einhundert" if hundreds == 1 else f"{self.ONES[hundreds]}hundert"
if remainder == 0:
return hundreds_word
return f"{hundreds_word}{self._number_to_words(remainder)}"
# Handle larger numbers using scales
for scale, singular, plural in self.SCALES:
if num >= scale:
quotient = num // scale
remainder = num % scale
# Format the quotient part
quotient_words = self._number_to_words(quotient)
# Choose singular or plural
if scale == 1000:
scale_word = singular
# Special formatting for thousands
if quotient == 1:
scale_word = "eintausend"
else:
scale_word = f"{quotient_words}tausend"
if remainder == 0:
return scale_word
return f"{scale_word}{self._number_to_words(remainder)}"
else:
scale_word = singular if quotient == 1 else plural
if quotient == 1:
result = f"eine {scale_word}"
else:
result = f"{quotient_words} {scale_word}"
if remainder == 0:
return result
return f"{result} {self._number_to_words(remainder)}"
return str(num)
def _year_to_words(self, year: int) -> str:
"""
Convert a year to its German spoken form.
Args:
year: Year as integer (e.g., 1994, 2019)
Returns:
German spoken form of the year
"""
# For years 1000-1999, split into hundreds
if 1000 <= year <= 1999:
hundreds = year // 100
remainder = year % 100
if remainder == 0:
return self._number_to_words(year)
# Create compound like "neunzehnhundertvierundneunzig"
hundreds_word = self._number_to_words(hundreds)
return f"{hundreds_word}hundert{self._number_to_words(remainder)}"
# For years 2000+, use normal number reading
return self._number_to_words(year)
def _ordinal_to_words(self, num: int) -> str:
"""
Convert a number to its German ordinal form.
Args:
num: Integer to convert to ordinal
Returns:
German ordinal word
"""
if num < 1:
return self._number_to_words(num) + "ter"
# Handle 1-9
if num < 10:
return self.ORDINAL_ONES.get(num, self._number_to_words(num) + "ter")
# Handle 10-19
if num < 20:
return self.ORDINAL_TEENS.get(num, self._number_to_words(num) + "ter")
# For larger numbers, add "ter" to the cardinal
return self._number_to_words(num) + "ter"
def _process_decimal(self, match: re.Match) -> str:
"""
Process decimal numbers like "3,1415" -> "drei komma eins vier eins fünf"
Args:
match: Regex match object containing the decimal number
Returns:
Spoken form of the decimal number
"""
full_number = match.group(0)
parts = full_number.split(',')
# Integer part
integer_part = int(parts[0]) if parts[0] else 0
result = self._number_to_words(integer_part)
# Decimal part - read digit by digit (including zeros)
if len(parts) > 1 and parts[1]:
result += " komma"
for digit in parts[1]:
result += " " + self.DIGITS[int(digit)]
return result
def _process_date(self, match: re.Match) -> str:
"""
Process dates in various formats:
- "20.11.2019" -> "zwanzigster elfter zweitausendneunzehn"
- "1. Jan. 1994" -> "erster Januar neunzehnhundertvierundneunzig"
Args:
match: Regex match object containing the date
Returns:
Spoken form of the date
"""
date_str = match.group(0)
# Pattern 1: DD.MM.YYYY or D.M.YYYY
pattern1 = r'(\d{1,2})\.(\d{1,2})\.(\d{4})'
m1 = re.match(pattern1, date_str)
if m1:
day = int(m1.group(1))
month = int(m1.group(2))
year = int(m1.group(3))
day_word = self._ordinal_to_words(day)
month_word = self._ordinal_to_words(month)
year_word = self._year_to_words(year)
return f"{day_word} {month_word} {year_word}"
# Pattern 2: D. Mon. YYYY or DD. Month YYYY
pattern2 = r'(\d{1,2})\.\s*([A-Za-zä]+)\.?\s*(\d{4})'
m2 = re.match(pattern2, date_str)
if m2:
day = int(m2.group(1))
month_str = m2.group(2).lower()
year = int(m2.group(3))
day_word = self._ordinal_to_words(day)
# Try to find month
month_word = self.MONTH_ABBREV.get(month_str, month_str)
year_word = self._year_to_words(year)
return f"{day_word} {month_word} {year_word}"
# Pattern 3: Just DD.MM or D.M (without year)
pattern3 = r'(\d{1,2})\.(\d{1,2})\.'
m3 = re.match(pattern3, date_str)
if m3:
day = int(m3.group(1))
month = int(m3.group(2))
day_word = self._ordinal_to_words(day)
month_word = self._ordinal_to_words(month)
return f"{day_word} {month_word}"
return date_str
def _process_standalone_number(self, match: re.Match) -> str:
"""
Process standalone cardinal numbers.
Args:
match: Regex match object containing the number
Returns:
Spoken form of the number
"""
num_str = match.group(0)
num = int(num_str)
return self._number_to_words(num)
def preprocess(self, text: str) -> str:
"""
Main preprocessing function that applies all transformations.
Args:
text: Input German text
Returns:
Preprocessed text with numbers, dates, etc. converted to spoken form
"""
# Order matters! More specific patterns first
# 1. Process dates (must come before decimal and integer processing)
# Pattern: DD.MM.YYYY or D.M.YYYY
text = re.sub(
r'\b(\d{1,2})\.(\d{1,2})\.(\d{4})\b',
self._process_date,
text
)
# Pattern: D. Month YYYY or DD. Mon. YYYY
text = re.sub(
r'\b(\d{1,2})\.\s*([A-Za-zäöüÄÖÜ]+)\.?\s*(\d{4})\b',
self._process_date,
text
)
# Pattern: DD.MM. or D.M.
text = re.sub(
r'\b(\d{1,2})\.(\d{1,2})\.',
self._process_date,
text
)
# 2. Process decimal numbers (before integers)
# Pattern: number,digits (e.g., 3,1415 or 0,5)
text = re.sub(
r'\b\d+,\d+\b',
self._process_decimal,
text
)
# 3. Process standalone integers (cardinal numbers)
# This will catch remaining numbers not processed by date/decimal patterns
text = re.sub(
r'\b\d+\b',
self._process_standalone_number,
text
)
# 4. Clean up any extra whitespace
text = re.sub(r'\s+', ' ', text).strip()
return text
# Convenience function for easy import and use
def preprocess_german_text(text: str) -> str:
"""
Convenience function to preprocess German text.
Args:
text: Input German text
Returns:
Preprocessed text with numbers, dates, etc. in spoken form
"""
preprocessor = GermanTextPreprocessor()
return preprocessor.preprocess(text)
# Example usage and testing
if __name__ == "__main__":
preprocessor = GermanTextPreprocessor()
test_cases = [
"Die Zahl ist 3",
"Heute ist der 20.11.2019",
"Geboren am 1. Jan. 1994",
"Pi ist ungefähr 3,1415",
"Es sind 42 Studenten in der Klasse",
"Das Jahr 2023 war interessant",
"Der Preis beträgt 19,99 Euro",
"Am 5.12. ist Nikolaus",
"Die Temperatur ist -5 Grad",
"Es gibt 1000000 Möglichkeiten",
"Im Jahr 1789 begann die Revolution",
]
print("German Text Preprocessing Examples:")
print("=" * 80)
for text in test_cases:
processed = preprocessor.preprocess(text)
print(f"Input: {text}")
print(f"Output: {processed}")
print("-" * 80)
|