text2spoken 0.0.2a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- text2spoken/__init__.py +50 -0
- text2spoken/datetimes.py +119 -0
- text2spoken/numbers.py +90 -0
- text2spoken/tables.py +352 -0
- text2spoken/text.py +156 -0
- text2spoken/units.py +98 -0
- text2spoken/version.py +10 -0
- text2spoken-0.0.2a1.dist-info/METADATA +100 -0
- text2spoken-0.0.2a1.dist-info/RECORD +12 -0
- text2spoken-0.0.2a1.dist-info/WHEEL +5 -0
- text2spoken-0.0.2a1.dist-info/licenses/LICENSE +202 -0
- text2spoken-0.0.2a1.dist-info/top_level.txt +1 -0
text2spoken/__init__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Text normalization: rewriting written text into the words a voice should speak.
|
|
2
|
+
|
|
3
|
+
``normalize(text, lang)`` is the entry point. It runs the raw text through the
|
|
4
|
+
per-concern passes in this package — dates and times, hyphen-joined
|
|
5
|
+
word/digit pairs, units and ordinal indicators, then a word-by-word pass that
|
|
6
|
+
expands contractions, titles, fractions and bare numbers — so that nothing
|
|
7
|
+
reaches the phonemizer as digits or symbols.
|
|
8
|
+
|
|
9
|
+
The language-specific lookup tables live in :mod:`text2spoken.tables`,
|
|
10
|
+
apart from the code that applies them, so a new language is a data change.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from text2spoken.datetimes import (
|
|
14
|
+
_normalize_dates_and_times,
|
|
15
|
+
pronounce_date,
|
|
16
|
+
pronounce_time,
|
|
17
|
+
)
|
|
18
|
+
from text2spoken.numbers import (
|
|
19
|
+
_get_number_separators,
|
|
20
|
+
_normalize_number_word,
|
|
21
|
+
is_fraction,
|
|
22
|
+
)
|
|
23
|
+
from text2spoken.tables import CONTRACTIONS, TITLES, UNITS
|
|
24
|
+
from text2spoken.text import (
|
|
25
|
+
_normalize_word,
|
|
26
|
+
_normalize_word_hyphen_digit,
|
|
27
|
+
expand_word,
|
|
28
|
+
normalize,
|
|
29
|
+
)
|
|
30
|
+
from text2spoken.units import _normalize_units
|
|
31
|
+
from text2spoken.version import __version__
|
|
32
|
+
|
|
33
|
+
expand_dates_and_times = _normalize_dates_and_times
|
|
34
|
+
expand_hyphen_digits = _normalize_word_hyphen_digit
|
|
35
|
+
expand_units = _normalize_units
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"CONTRACTIONS",
|
|
39
|
+
"TITLES",
|
|
40
|
+
"UNITS",
|
|
41
|
+
"__version__",
|
|
42
|
+
"expand_dates_and_times",
|
|
43
|
+
"expand_hyphen_digits",
|
|
44
|
+
"expand_units",
|
|
45
|
+
"expand_word",
|
|
46
|
+
"is_fraction",
|
|
47
|
+
"normalize",
|
|
48
|
+
"pronounce_date",
|
|
49
|
+
"pronounce_time",
|
|
50
|
+
]
|
text2spoken/datetimes.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Spoken forms for the date and time patterns that survive into raw text."""
|
|
2
|
+
import datetime
|
|
3
|
+
import re
|
|
4
|
+
from datetime import date
|
|
5
|
+
import logging
|
|
6
|
+
|
|
7
|
+
from ovos_date_parser import nice_time, nice_date
|
|
8
|
+
|
|
9
|
+
LOG = logging.getLogger("text2spoken")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def pronounce_date(date_obj: date, full_lang: str) -> str:
|
|
13
|
+
"""
|
|
14
|
+
Pronounces a date object using ovos-date-parser.
|
|
15
|
+
"""
|
|
16
|
+
return nice_date(date_obj, full_lang)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def pronounce_time(time_string: str, full_lang: str) -> str:
|
|
20
|
+
"""
|
|
21
|
+
Pronounces a time string using ovos-date-parser.
|
|
22
|
+
Handles military time like "15h01" and converts it to a
|
|
23
|
+
datetime.time object before passing it to nice_time.
|
|
24
|
+
"""
|
|
25
|
+
try:
|
|
26
|
+
hours, mins = time_string.split("h")
|
|
27
|
+
time_obj = datetime.time(int(hours), int(mins))
|
|
28
|
+
# Use nice_time from ovos-date-parser
|
|
29
|
+
return nice_time(time_obj, full_lang, speech=True, use_24hour=True, use_ampm=False)
|
|
30
|
+
except Exception as e:
|
|
31
|
+
LOG.warning(f"Failed to parse time string '{time_string}': {e}")
|
|
32
|
+
return time_string.replace("h", " ")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _normalize_dates_and_times(text: str, full_lang: str, date_format: str = "DMY") -> str:
|
|
36
|
+
"""
|
|
37
|
+
Helper function to normalize dates and times using regular expressions.
|
|
38
|
+
This prepares the strings for pronunciation.
|
|
39
|
+
"""
|
|
40
|
+
lang_code = full_lang.split("-")[0]
|
|
41
|
+
# Pre-process with regex to handle English am/pm times.
|
|
42
|
+
# Anchored to a preceding digit so ordinary words containing "am"/"pm"
|
|
43
|
+
# (e.g. "I am happy", "spam") are never touched.
|
|
44
|
+
if lang_code == "en":
|
|
45
|
+
text = re.sub(
|
|
46
|
+
r"(?i)\b(\d+)\s*([ap])\.?m\.?\b",
|
|
47
|
+
lambda m: f"{m.group(1)} {m.group(2).upper()} M",
|
|
48
|
+
text,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
# Normalize times like "15h01" to words
|
|
52
|
+
time_pattern = re.compile(r"(\d{1,2})h(\d{2})", re.IGNORECASE)
|
|
53
|
+
|
|
54
|
+
def replace_time(match):
|
|
55
|
+
time_str = match.group(0)
|
|
56
|
+
return pronounce_time(time_str, full_lang)
|
|
57
|
+
|
|
58
|
+
text = time_pattern.sub(replace_time, text)
|
|
59
|
+
|
|
60
|
+
# Find dates like "DD/MM/YYYY" or "YYYY/MM/DD"
|
|
61
|
+
date_pattern = re.compile(r"(\d{1,4})[/-](\d{1,2})[/-](\d{1,4})")
|
|
62
|
+
|
|
63
|
+
# Expand every date found in the text, not just the first one.
|
|
64
|
+
result_parts = []
|
|
65
|
+
pos = 0
|
|
66
|
+
for match in date_pattern.finditer(text):
|
|
67
|
+
# Get the three parts of the date string
|
|
68
|
+
part1_str, part2_str, part3_str = match.groups()
|
|
69
|
+
p1, p2, p3 = int(part1_str), int(part2_str), int(part3_str)
|
|
70
|
+
|
|
71
|
+
# Initialize month, day, and year
|
|
72
|
+
month, day, year = None, None, None
|
|
73
|
+
|
|
74
|
+
# Determine year first based on length (4 digits)
|
|
75
|
+
if len(part1_str) == 4:
|
|
76
|
+
year, rest_parts = p1, [p2, p3]
|
|
77
|
+
elif len(part3_str) == 4:
|
|
78
|
+
year, rest_parts = p3, [p1, p2]
|
|
79
|
+
else:
|
|
80
|
+
# If no 4-digit year, it's ambiguous, assume a 2-digit year.
|
|
81
|
+
# We'll assume the last part is the year based on common patterns.
|
|
82
|
+
year = p3
|
|
83
|
+
# Expand 2-digit year to 4-digit year
|
|
84
|
+
if year < 100:
|
|
85
|
+
# Assume years 00-29 are 2000-2029, 30-99 are 1930-1999
|
|
86
|
+
year = 2000 + year if year < 30 else 1900 + year
|
|
87
|
+
rest_parts = [p1, p2]
|
|
88
|
+
|
|
89
|
+
# From the remaining parts, try to determine day and month
|
|
90
|
+
if day is None and any(p > 12 and len(str(p)) == 2 for p in rest_parts):
|
|
91
|
+
# If a two-digit number is > 12, it's a day
|
|
92
|
+
day_candidate = next((p for p in rest_parts if p > 12), None)
|
|
93
|
+
if day_candidate:
|
|
94
|
+
day = day_candidate
|
|
95
|
+
rest_parts.remove(day_candidate)
|
|
96
|
+
month = rest_parts[0]
|
|
97
|
+
|
|
98
|
+
# Fallback to date_format if day/month are still ambiguous
|
|
99
|
+
if day is None or month is None:
|
|
100
|
+
if date_format.lower() == "mdy":
|
|
101
|
+
month, day = rest_parts[0], rest_parts[1]
|
|
102
|
+
else: # default to DD/MM/YY
|
|
103
|
+
day, month = rest_parts[0], rest_parts[1]
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
date_obj = date(year, month, day)
|
|
107
|
+
replacement = pronounce_date(date_obj, full_lang)
|
|
108
|
+
except (ValueError, IndexError) as e:
|
|
109
|
+
LOG.warning(f"Could not parse date from '{match.group(0)}': {e}")
|
|
110
|
+
replacement = match.group(0)
|
|
111
|
+
|
|
112
|
+
result_parts.append(text[pos:match.start()])
|
|
113
|
+
result_parts.append(replacement)
|
|
114
|
+
pos = match.end()
|
|
115
|
+
|
|
116
|
+
result_parts.append(text[pos:])
|
|
117
|
+
text = "".join(result_parts)
|
|
118
|
+
|
|
119
|
+
return text
|
text2spoken/numbers.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Spoken forms for numbers: separators, fractions and digit strings."""
|
|
2
|
+
import logging
|
|
3
|
+
import string
|
|
4
|
+
|
|
5
|
+
from ovos_number_parser import pronounce_number, pronounce_fraction
|
|
6
|
+
from ovos_number_parser.util import is_numeric
|
|
7
|
+
from unicode_rbnf import FormatPurpose
|
|
8
|
+
|
|
9
|
+
LOG = logging.getLogger("text2spoken")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _get_number_separators(full_lang: str) -> tuple[str, str]:
|
|
13
|
+
"""
|
|
14
|
+
Determines decimal and thousands separators based on language.
|
|
15
|
+
Defaults to '.' decimal and ',' thousands for most languages.
|
|
16
|
+
Special cases:
|
|
17
|
+
- 'pt', 'es', 'fr', 'de': ',' decimal and '.' thousands.
|
|
18
|
+
"""
|
|
19
|
+
lang_code = full_lang.split("-")[0]
|
|
20
|
+
decimal_separator = '.'
|
|
21
|
+
thousands_separator = ','
|
|
22
|
+
if lang_code in ["pt", "es", "fr", "de"]:
|
|
23
|
+
decimal_separator = ','
|
|
24
|
+
thousands_separator = '.'
|
|
25
|
+
return decimal_separator, thousands_separator
|
|
26
|
+
|
|
27
|
+
def is_fraction(word: str) -> bool:
|
|
28
|
+
"""Checks if a word is a fraction like '3/3'."""
|
|
29
|
+
if "/" in word:
|
|
30
|
+
parts = word.split("/")
|
|
31
|
+
if len(parts) == 2:
|
|
32
|
+
n1, n2 = parts
|
|
33
|
+
return n1.isdigit() and n2.isdigit()
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
def _normalize_number_word(word: str, full_lang: str, rbnf_engine) -> str:
|
|
37
|
+
"""
|
|
38
|
+
Helper function to normalize a single word that is a number, handling
|
|
39
|
+
decimal and thousands separators based on locale.
|
|
40
|
+
"""
|
|
41
|
+
cleaned_word = word.rstrip(string.punctuation)
|
|
42
|
+
|
|
43
|
+
# Handle fractions like '3/3'
|
|
44
|
+
if is_fraction(cleaned_word):
|
|
45
|
+
try:
|
|
46
|
+
return pronounce_fraction(cleaned_word, full_lang) + word[len(cleaned_word):]
|
|
47
|
+
except Exception as e:
|
|
48
|
+
LOG.error(f"ovos-number-parser failed to pronounce fraction: {word} - ({e})")
|
|
49
|
+
return word
|
|
50
|
+
|
|
51
|
+
# Handle numbers with locale-specific separators
|
|
52
|
+
decimal_separator, thousands_separator = _get_number_separators(full_lang)
|
|
53
|
+
temp_cleaned_word = cleaned_word
|
|
54
|
+
|
|
55
|
+
# Check if the word contains a thousands separator followed by digits and a decimal separator
|
|
56
|
+
# This is a specific check for formats like '123.456,78'
|
|
57
|
+
has_thousands_and_decimal = (
|
|
58
|
+
thousands_separator in temp_cleaned_word and
|
|
59
|
+
decimal_separator in temp_cleaned_word and
|
|
60
|
+
temp_cleaned_word.index(thousands_separator) < temp_cleaned_word.index(decimal_separator)
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
if has_thousands_and_decimal:
|
|
64
|
+
temp_cleaned_word = temp_cleaned_word.replace(thousands_separator, "")
|
|
65
|
+
temp_cleaned_word = temp_cleaned_word.replace(decimal_separator, ".")
|
|
66
|
+
elif decimal_separator in temp_cleaned_word and is_numeric(temp_cleaned_word.replace(decimal_separator, ".", 1)):
|
|
67
|
+
# Handle cases like '1,2' -> '1.2'
|
|
68
|
+
temp_cleaned_word = temp_cleaned_word.replace(decimal_separator, ".")
|
|
69
|
+
elif thousands_separator in temp_cleaned_word and is_numeric(temp_cleaned_word.replace(thousands_separator, "", 1)):
|
|
70
|
+
# Handle cases like '1.234' -> '1234'
|
|
71
|
+
temp_cleaned_word = temp_cleaned_word.replace(thousands_separator, "")
|
|
72
|
+
|
|
73
|
+
# Check if the word is a valid number after processing
|
|
74
|
+
if is_numeric(temp_cleaned_word):
|
|
75
|
+
try:
|
|
76
|
+
num = float(temp_cleaned_word) if "." in temp_cleaned_word else int(temp_cleaned_word)
|
|
77
|
+
return pronounce_number(num, lang=full_lang) + word[len(cleaned_word):]
|
|
78
|
+
except Exception as e:
|
|
79
|
+
LOG.error(f"ovos-number-parser failed to pronounce number: {word} - ({e})")
|
|
80
|
+
return word
|
|
81
|
+
|
|
82
|
+
elif rbnf_engine and cleaned_word.isdigit():
|
|
83
|
+
try:
|
|
84
|
+
pronounced_number = rbnf_engine.format_number(cleaned_word, FormatPurpose.CARDINAL).text
|
|
85
|
+
return pronounced_number + word[len(cleaned_word):]
|
|
86
|
+
except Exception as e:
|
|
87
|
+
LOG.error(f"unicode-rbnf failed to pronounce number: {word} - ({e})")
|
|
88
|
+
return word
|
|
89
|
+
|
|
90
|
+
return word
|
text2spoken/tables.py
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
"""Per-language lookup tables consumed by the normalization pipeline.
|
|
2
|
+
|
|
3
|
+
Keys are ISO-639 language codes; a locale tag is reduced to its language
|
|
4
|
+
subtag before lookup, so "pt-BR" and "pt-PT" share one table.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# A dictionary of common contractions and their expanded forms.
|
|
8
|
+
# This list is very comprehensive for English.
|
|
9
|
+
CONTRACTIONS = {
|
|
10
|
+
"en": {
|
|
11
|
+
"I'd": "I would",
|
|
12
|
+
"I'll": "I will",
|
|
13
|
+
"I'm": "I am",
|
|
14
|
+
"I've": "I have",
|
|
15
|
+
"ain't": "is not",
|
|
16
|
+
"aren't": "are not",
|
|
17
|
+
"can't": "can not",
|
|
18
|
+
"could've": "could have",
|
|
19
|
+
"couldn't": "could not",
|
|
20
|
+
"didn't": "did not",
|
|
21
|
+
"doesn't": "does not",
|
|
22
|
+
"don't": "do not",
|
|
23
|
+
"gonna": "going to",
|
|
24
|
+
"gotta": "got to",
|
|
25
|
+
"hadn't": "had not",
|
|
26
|
+
"hasn't": "has not",
|
|
27
|
+
"haven't": "have not",
|
|
28
|
+
"he'd": "he would",
|
|
29
|
+
"he'll": "he will",
|
|
30
|
+
"he's": "he is",
|
|
31
|
+
"how'd": "how did",
|
|
32
|
+
"how'll": "how will",
|
|
33
|
+
"how's": "how is",
|
|
34
|
+
"isn't": "is not",
|
|
35
|
+
"it'd": "it would",
|
|
36
|
+
"it'll": "it will",
|
|
37
|
+
"it's": "it is",
|
|
38
|
+
"might've": "might have",
|
|
39
|
+
"mightn't": "might not",
|
|
40
|
+
"must've": "must have",
|
|
41
|
+
"mustn't": "must not",
|
|
42
|
+
"needn't": "need not",
|
|
43
|
+
"oughtn't": "ought not",
|
|
44
|
+
"shan't": "shall not",
|
|
45
|
+
"she'd": "she would",
|
|
46
|
+
"she'll": "she will",
|
|
47
|
+
"she's": "she is",
|
|
48
|
+
"should've": "should have",
|
|
49
|
+
"shouldn't": "should not",
|
|
50
|
+
"somebody's": "somebody is",
|
|
51
|
+
"someone'd": "someone would",
|
|
52
|
+
"someone'll": "someone will",
|
|
53
|
+
"someone's": "someone is",
|
|
54
|
+
"that'd": "that would",
|
|
55
|
+
"that'll": "that will",
|
|
56
|
+
"that's": "that is",
|
|
57
|
+
"there'd": "there would",
|
|
58
|
+
"there're": "there are",
|
|
59
|
+
"there's": "there is",
|
|
60
|
+
"they'd": "they would",
|
|
61
|
+
"they'll": "they will",
|
|
62
|
+
"they're": "they are",
|
|
63
|
+
"they've": "they have",
|
|
64
|
+
"wasn't": "was not",
|
|
65
|
+
"we'd": "we would",
|
|
66
|
+
"we'll": "we will",
|
|
67
|
+
"we're": "we are",
|
|
68
|
+
"we've": "we have",
|
|
69
|
+
"weren't": "were not",
|
|
70
|
+
"what'd": "what did",
|
|
71
|
+
"what'll": "what will",
|
|
72
|
+
"what're": "what are",
|
|
73
|
+
"what's": "what is",
|
|
74
|
+
"what've": "what have",
|
|
75
|
+
"whats": "what is",
|
|
76
|
+
"when'd": "when did",
|
|
77
|
+
"when's": "when is",
|
|
78
|
+
"where'd": "where did",
|
|
79
|
+
"where's": "where is",
|
|
80
|
+
"where've": "where have",
|
|
81
|
+
"who'd": "who would",
|
|
82
|
+
"who'd've": "who would have",
|
|
83
|
+
"who'll": "who will",
|
|
84
|
+
"who're": "who are",
|
|
85
|
+
"who's": "who is",
|
|
86
|
+
"who've": "who have",
|
|
87
|
+
"why'd": "why did",
|
|
88
|
+
"why're": "why are",
|
|
89
|
+
"why's": "why is",
|
|
90
|
+
"won't": "will not",
|
|
91
|
+
"won't've": "will not have",
|
|
92
|
+
"would've": "would have",
|
|
93
|
+
"wouldn't": "would not",
|
|
94
|
+
"wouldn't've": "would not have",
|
|
95
|
+
"y'ain't": "you are not",
|
|
96
|
+
"y'aint": "you are not",
|
|
97
|
+
"y'all": "you all",
|
|
98
|
+
"ya'll": "you all",
|
|
99
|
+
"you'd": "you would",
|
|
100
|
+
"you'd've": "you would have",
|
|
101
|
+
"you'll": "you will",
|
|
102
|
+
"you're": "you are",
|
|
103
|
+
"you've": "you have",
|
|
104
|
+
"I'm'a": "I am going to",
|
|
105
|
+
"I'm'o": "I am going to",
|
|
106
|
+
"I'll've": "I will have",
|
|
107
|
+
"I'd've": "I would have",
|
|
108
|
+
"Whatcha": "What are you",
|
|
109
|
+
"amn't": "am not",
|
|
110
|
+
"'cause": "because",
|
|
111
|
+
"can't've": "cannot have",
|
|
112
|
+
"couldn't've": "could not have",
|
|
113
|
+
"daren't": "dare not",
|
|
114
|
+
"daresn't": "dare not",
|
|
115
|
+
"dasn't": "dare not",
|
|
116
|
+
"everyone's": "everyone is",
|
|
117
|
+
"gimme": "give me",
|
|
118
|
+
"gon't": "go not",
|
|
119
|
+
"hadn't've": "had not have",
|
|
120
|
+
"he've": "he would have",
|
|
121
|
+
"he'll've": "he will have",
|
|
122
|
+
"he'd've": "he would have",
|
|
123
|
+
"here's": "here is",
|
|
124
|
+
"how're": "how are",
|
|
125
|
+
"how'd'y": "how do you do",
|
|
126
|
+
"howd'y": "how do you do",
|
|
127
|
+
"howdy": "how do you do",
|
|
128
|
+
"'tis": "it is",
|
|
129
|
+
"'twas": "it was",
|
|
130
|
+
"it'll've": "it will have",
|
|
131
|
+
"it'd've": "it would have",
|
|
132
|
+
"kinda": "kind of",
|
|
133
|
+
"let's": "let us",
|
|
134
|
+
"ma'am": "madam",
|
|
135
|
+
"may've": "may have",
|
|
136
|
+
"mayn't": "may not",
|
|
137
|
+
"mightn't've": "might not have",
|
|
138
|
+
"mustn't've": "must not have",
|
|
139
|
+
"needn't've": "need not have",
|
|
140
|
+
"ol'": "old",
|
|
141
|
+
"oughtn't've": "ought not have",
|
|
142
|
+
"sha'n't": "shall not",
|
|
143
|
+
"shan't": "shall not",
|
|
144
|
+
"shalln't": "shall not",
|
|
145
|
+
"shan't've": "shall not have",
|
|
146
|
+
"she'd've": "she would have",
|
|
147
|
+
"shouldn't've": "should not have",
|
|
148
|
+
"so've": "so have",
|
|
149
|
+
"so's": "so is",
|
|
150
|
+
"something's": "something is",
|
|
151
|
+
"that're": "that are",
|
|
152
|
+
"that'd've": "that would have",
|
|
153
|
+
"there'll": "there will",
|
|
154
|
+
"there'd've": "there would have",
|
|
155
|
+
"these're": "these are",
|
|
156
|
+
"they'll've": "they will have",
|
|
157
|
+
"they'd've": "they would have",
|
|
158
|
+
"this's": "this is",
|
|
159
|
+
"this'll": "this will",
|
|
160
|
+
"this'd": "this would",
|
|
161
|
+
"those're": "those are",
|
|
162
|
+
"to've": "to have",
|
|
163
|
+
"wanna": "want to",
|
|
164
|
+
"we'll've": "we will have",
|
|
165
|
+
"we'd've": "we would have",
|
|
166
|
+
"what'll've": "what will have",
|
|
167
|
+
"when've": "when have",
|
|
168
|
+
"where're": "where are",
|
|
169
|
+
"which's": "which is",
|
|
170
|
+
"who'll've": "who will have",
|
|
171
|
+
"why've": "why have",
|
|
172
|
+
"will've": "will have",
|
|
173
|
+
"y'all're": "you all are",
|
|
174
|
+
"y'all've": "you all have",
|
|
175
|
+
"y'all'd": "you all would",
|
|
176
|
+
"y'all'd've": "you all would have",
|
|
177
|
+
"you'll've": "you will have"
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
# Dictionaries for titles, units, and their full word equivalents.
|
|
182
|
+
TITLES = {
|
|
183
|
+
"en": {
|
|
184
|
+
"Dr.": "Doctor",
|
|
185
|
+
"Mr.": "Mister",
|
|
186
|
+
"Prof.": "Professor"
|
|
187
|
+
},
|
|
188
|
+
"ca": {
|
|
189
|
+
"Dr.": "Doctor",
|
|
190
|
+
"Sr.": "Senyor",
|
|
191
|
+
"Sra.": "Senyora",
|
|
192
|
+
"Prof.": "Professor"
|
|
193
|
+
},
|
|
194
|
+
"es": {
|
|
195
|
+
"Dr.": "Doctor",
|
|
196
|
+
"Sr.": "Señor",
|
|
197
|
+
"Sra.": "Señora",
|
|
198
|
+
"Prof.": "Profesor",
|
|
199
|
+
"D.": "Don",
|
|
200
|
+
"Dña.": "Doña"
|
|
201
|
+
},
|
|
202
|
+
"pt": {
|
|
203
|
+
"Dr.": "Doutor",
|
|
204
|
+
"Sr.": "Senhor",
|
|
205
|
+
"Sra.": "Senhora",
|
|
206
|
+
"Prof.": "Professor",
|
|
207
|
+
"Drª.": "Doutora",
|
|
208
|
+
"Eng.": "Engenheiro",
|
|
209
|
+
"D.": "Dom",
|
|
210
|
+
"Dª": "Dona"
|
|
211
|
+
},
|
|
212
|
+
"gl": {
|
|
213
|
+
"Dr.": "Doutor",
|
|
214
|
+
"Sr.": "Señor",
|
|
215
|
+
"Sra.": "Señora",
|
|
216
|
+
"Prof.": "Profesor",
|
|
217
|
+
"Srta.": "Señorita"
|
|
218
|
+
},
|
|
219
|
+
"fr": {
|
|
220
|
+
"Dr.": "Docteur",
|
|
221
|
+
"M.": "Monsieur",
|
|
222
|
+
"Mme": "Madame",
|
|
223
|
+
"Mlle": "Mademoiselle",
|
|
224
|
+
"Prof.": "Professeur",
|
|
225
|
+
"Pr.": "Professeur"
|
|
226
|
+
},
|
|
227
|
+
"it": {
|
|
228
|
+
"Dr.": "Dottore",
|
|
229
|
+
"Sig.": "Signore",
|
|
230
|
+
"Sig.ra": "Signora",
|
|
231
|
+
"Prof.": "Professore",
|
|
232
|
+
"Dott.ssa": "Dottoressa",
|
|
233
|
+
"Sig.na": "Signorina"
|
|
234
|
+
},
|
|
235
|
+
"nl": {
|
|
236
|
+
"Dr.": "Dokter",
|
|
237
|
+
"Dhr.": "De Heer",
|
|
238
|
+
"Mevr.": "Mevrouw",
|
|
239
|
+
"Prof.": "Professor",
|
|
240
|
+
"Drs.": "Dokterandus",
|
|
241
|
+
"Ing.": "Ingenieur"
|
|
242
|
+
},
|
|
243
|
+
"de": {
|
|
244
|
+
"Dr.": "Doktor",
|
|
245
|
+
"Prof.": "Professor"
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
UNITS = {
|
|
250
|
+
"en": {
|
|
251
|
+
"€": "euros",
|
|
252
|
+
"%": "per cent",
|
|
253
|
+
"°C": "degrees celsius",
|
|
254
|
+
"°F": "degrees fahrenheit",
|
|
255
|
+
"°K": "degrees kelvin",
|
|
256
|
+
"°": "degrees",
|
|
257
|
+
"$": "dollars",
|
|
258
|
+
"£": "pounds",
|
|
259
|
+
"km": "kilometers",
|
|
260
|
+
"m": "meters",
|
|
261
|
+
"cm": "centimeters",
|
|
262
|
+
"mm": "millimeters",
|
|
263
|
+
"ft": "feet",
|
|
264
|
+
"in": "inches",
|
|
265
|
+
"yd": "yards",
|
|
266
|
+
"mi": "miles",
|
|
267
|
+
"kg": "kilograms",
|
|
268
|
+
"g": "grams",
|
|
269
|
+
"lb": "pounds",
|
|
270
|
+
"oz": "ounces",
|
|
271
|
+
"L": "liters",
|
|
272
|
+
"mL": "milliliters",
|
|
273
|
+
"gal": "gallons",
|
|
274
|
+
"qt": "quarts",
|
|
275
|
+
"pt": "pints",
|
|
276
|
+
"hr": "hours",
|
|
277
|
+
"min": "minutes",
|
|
278
|
+
"s": "seconds"
|
|
279
|
+
},
|
|
280
|
+
"pt": {
|
|
281
|
+
"€": "euros",
|
|
282
|
+
"%": "por cento",
|
|
283
|
+
"°C": "graus celsius",
|
|
284
|
+
"°F": "graus fahrenheit",
|
|
285
|
+
"°K": "graus kelvin",
|
|
286
|
+
"°": "graus",
|
|
287
|
+
"$": "dólares",
|
|
288
|
+
"£": "libras",
|
|
289
|
+
"km": "quilômetros",
|
|
290
|
+
"m": "metros",
|
|
291
|
+
"cm": "centímetros",
|
|
292
|
+
"mm": "milímetros",
|
|
293
|
+
"kg": "quilogramas",
|
|
294
|
+
"g": "gramas",
|
|
295
|
+
"L": "litros",
|
|
296
|
+
"mL": "mililitros",
|
|
297
|
+
"h": "horas",
|
|
298
|
+
"min": "minutos",
|
|
299
|
+
"s": "segundos"
|
|
300
|
+
},
|
|
301
|
+
"es": {
|
|
302
|
+
"€": "euros",
|
|
303
|
+
"%": "por ciento",
|
|
304
|
+
"°C": "grados celsius",
|
|
305
|
+
"°F": "grados fahrenheit",
|
|
306
|
+
"°K": "grados kelvin",
|
|
307
|
+
"°": "grados",
|
|
308
|
+
"$": "dólares",
|
|
309
|
+
"£": "libras",
|
|
310
|
+
"km": "kilómetros",
|
|
311
|
+
"m": "metros",
|
|
312
|
+
"cm": "centímetros",
|
|
313
|
+
"kg": "kilogramos",
|
|
314
|
+
"g": "gramos",
|
|
315
|
+
"L": "litros",
|
|
316
|
+
"mL": "millilitros"
|
|
317
|
+
},
|
|
318
|
+
"fr": {
|
|
319
|
+
"€": "euros",
|
|
320
|
+
"%": "pour cent",
|
|
321
|
+
"°C": "degrés celsius",
|
|
322
|
+
"°F": "degrés fahrenheit",
|
|
323
|
+
"°K": "degrés kelvin",
|
|
324
|
+
"°": "degrés",
|
|
325
|
+
"$": "dollars",
|
|
326
|
+
"£": "livres",
|
|
327
|
+
"km": "kilomètres",
|
|
328
|
+
"m": "mètres",
|
|
329
|
+
"cm": "centimètres",
|
|
330
|
+
"kg": "kilogrammes",
|
|
331
|
+
"g": "grammes",
|
|
332
|
+
"L": "litres",
|
|
333
|
+
"mL": "millilitres"
|
|
334
|
+
},
|
|
335
|
+
"de": {
|
|
336
|
+
"€": "Euro",
|
|
337
|
+
"%": "Prozent",
|
|
338
|
+
"°C": "Grad Celsius",
|
|
339
|
+
"°F": "Grad Fahrenheit",
|
|
340
|
+
"°K": "Grad Kelvin",
|
|
341
|
+
"°": "Grad",
|
|
342
|
+
"$": "Dollar",
|
|
343
|
+
"£": "Pfund",
|
|
344
|
+
"km": "Kilometer",
|
|
345
|
+
"m": "Meter",
|
|
346
|
+
"cm": "Zentimeter",
|
|
347
|
+
"kg": "Kilogramm",
|
|
348
|
+
"g": "Gramm",
|
|
349
|
+
"L": "Liter",
|
|
350
|
+
"mL": "Milliliter"
|
|
351
|
+
}
|
|
352
|
+
}
|
text2spoken/text.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""The text normalization pipeline: raw written text to speakable words."""
|
|
2
|
+
import logging
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from unicode_rbnf import RbnfEngine
|
|
6
|
+
|
|
7
|
+
from text2spoken.datetimes import _normalize_dates_and_times
|
|
8
|
+
from text2spoken.numbers import _normalize_number_word
|
|
9
|
+
from text2spoken.tables import CONTRACTIONS, TITLES
|
|
10
|
+
from text2spoken.units import _normalize_units
|
|
11
|
+
|
|
12
|
+
LOG = logging.getLogger("text2spoken")
|
|
13
|
+
|
|
14
|
+
def _normalize_word_hyphen_digit(text: str) -> str:
|
|
15
|
+
"""
|
|
16
|
+
Helper function to normalize words attached to digits with a hyphen,
|
|
17
|
+
such as 'sub-23' -> 'sub 23'.
|
|
18
|
+
|
|
19
|
+
A hyphen (or en-dash/em-dash) directly between two digit runs, such as
|
|
20
|
+
'3-2' or '1139-1185', is left untouched: that is a score or a range,
|
|
21
|
+
not a word glued to a digit, and it is up to the phonemizer to read it
|
|
22
|
+
as such.
|
|
23
|
+
"""
|
|
24
|
+
# Regex to find a word (\w+) followed by a hyphen/en-dash/em-dash and a
|
|
25
|
+
# digit (\d+).
|
|
26
|
+
pattern = re.compile(r"(\w+)[-–—](\d+)")
|
|
27
|
+
|
|
28
|
+
def _replace(match: "re.Match") -> str:
|
|
29
|
+
word_part = match.group(1)
|
|
30
|
+
if word_part.isdigit():
|
|
31
|
+
# digit-dash-digit is a range or score (e.g. '3-2', '1139-1185')
|
|
32
|
+
return match.group(0)
|
|
33
|
+
return f"{word_part} {match.group(2)}"
|
|
34
|
+
|
|
35
|
+
text = pattern.sub(_replace, text)
|
|
36
|
+
return text
|
|
37
|
+
|
|
38
|
+
def _normalize_word(word: str, full_lang: str, rbnf_engine) -> str:
|
|
39
|
+
"""
|
|
40
|
+
Helper function to normalize a single word.
|
|
41
|
+
"""
|
|
42
|
+
lang_code = full_lang.split("-")[0]
|
|
43
|
+
word = word.replace("’", "'")
|
|
44
|
+
|
|
45
|
+
if word in CONTRACTIONS.get(lang_code, {}):
|
|
46
|
+
return CONTRACTIONS[lang_code][word]
|
|
47
|
+
|
|
48
|
+
if word in TITLES.get(lang_code, {}):
|
|
49
|
+
return TITLES[lang_code][word]
|
|
50
|
+
|
|
51
|
+
# Delegate number parsing to the new helper function
|
|
52
|
+
normalized_number = _normalize_number_word(word, full_lang, rbnf_engine)
|
|
53
|
+
if normalized_number != word:
|
|
54
|
+
return normalized_number
|
|
55
|
+
|
|
56
|
+
return word
|
|
57
|
+
|
|
58
|
+
def expand_word(word: str, lang: str) -> str:
|
|
59
|
+
"""Expand one word: a contraction, a title, a fraction or a number."""
|
|
60
|
+
rbnf_engine = None
|
|
61
|
+
try:
|
|
62
|
+
rbnf_engine = RbnfEngine.for_language(lang.split("-")[0])
|
|
63
|
+
except (ValueError, KeyError) as e:
|
|
64
|
+
LOG.debug(f"RBNF engine not available for language '{lang}': {e}")
|
|
65
|
+
return _normalize_word(word, lang, rbnf_engine)
|
|
66
|
+
|
|
67
|
+
def normalize(text: str, lang: str) -> str:
|
|
68
|
+
"""
|
|
69
|
+
Normalize a text string for speech by expanding contractions and titles and converting dates, times, numbers, units, and fractions into spoken forms.
|
|
70
|
+
|
|
71
|
+
Parameters:
|
|
72
|
+
text (str): Input text to normalize.
|
|
73
|
+
lang (str): Locale language tag (e.g., "en", "en-US") that determines language-specific rules.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
str: The normalized text with expanded contractions and titles and with dates, times, numbers, units, and fractions converted to their spoken equivalents.
|
|
77
|
+
|
|
78
|
+
Notes:
|
|
79
|
+
Date and time normalization is attempted for the locale and is silently skipped if unsupported. Numeric formatting may use a locale RBNF engine when available; otherwise a fallback is used.
|
|
80
|
+
"""
|
|
81
|
+
full_lang = lang
|
|
82
|
+
lang_code = full_lang.split("-")[0]
|
|
83
|
+
dialog = text
|
|
84
|
+
|
|
85
|
+
# Step 1: Handle dates and times with ovos-date-parser
|
|
86
|
+
date_format = "MDY" if full_lang.lower() == "en-us" else "DMY"
|
|
87
|
+
try:
|
|
88
|
+
dialog = _normalize_dates_and_times(dialog, full_lang, date_format)
|
|
89
|
+
except: # throws exception on unsupported langs
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
# Step 2: Normalize words with hyphens and digits
|
|
93
|
+
dialog = _normalize_word_hyphen_digit(dialog)
|
|
94
|
+
|
|
95
|
+
# Step 3: Expand units attached to numbers
|
|
96
|
+
dialog = _normalize_units(dialog, full_lang)
|
|
97
|
+
|
|
98
|
+
# Step 4: Normalize word-by-word
|
|
99
|
+
words = dialog.split()
|
|
100
|
+
rbnf_engine = None
|
|
101
|
+
try:
|
|
102
|
+
rbnf_engine = RbnfEngine.for_language(lang_code)
|
|
103
|
+
except (ValueError, KeyError) as e:
|
|
104
|
+
LOG.debug(f"RBNF engine not available for language '{lang_code}': {e}")
|
|
105
|
+
|
|
106
|
+
normalized_words = [_normalize_word(word, full_lang, rbnf_engine) for word in words]
|
|
107
|
+
dialog = " ".join(normalized_words)
|
|
108
|
+
|
|
109
|
+
return dialog
|
|
110
|
+
if __name__ == "__main__":
|
|
111
|
+
# --- Example usage for demonstration purposes ---
|
|
112
|
+
|
|
113
|
+
# General normalization examples
|
|
114
|
+
print("General English example: " + normalize('I\'m Dr. Prof. 3/3 0.5% of 12345€, 5ft, and 10kg', 'en'))
|
|
115
|
+
print(
|
|
116
|
+
f"Word Salad Portuguese (Dr. Prof. 3/3 0,5% de 12345€, 5m, e 10kg): {normalize('Dr. Prof. 3/3 0,5% de 12345€, 5m, e 10kg', 'pt')}")
|
|
117
|
+
print(
|
|
118
|
+
f"Word Salad Portuguese (Dr. Prof. 3/3 0.5% de 12345€, 5m, e 10kg): {normalize('Dr. Prof. 3/3 0.5% de 12345€, 5m, e 10kg', 'pt')}")
|
|
119
|
+
|
|
120
|
+
# Portuguese examples with comma decimal separator
|
|
121
|
+
print("\n--- Portuguese Decimal Separator Examples ---")
|
|
122
|
+
print(
|
|
123
|
+
f"Original: 'A coima aplicada é de 1,2 milhões de euros.' Normalized: '{normalize('A coima aplicada é de 1,2 milhões de euros.', 'pt')}'")
|
|
124
|
+
print(
|
|
125
|
+
f"Original: 'Agora, tem 1,88 metros e muito para contar.' Normalized: '{normalize('Agora, tem 1,88 metros e muito para contar.', 'pt')}'")
|
|
126
|
+
print(
|
|
127
|
+
f"Original: 'Ainda temos 1,7 milhões de pobres!' Normalized: '{normalize('Ainda temos 1,7 milhões de pobres!', 'pt')}'")
|
|
128
|
+
print(f"Original: 'O lucro foi de 123.456,78€.' Normalized: '{normalize('O lucro foi de 123.456,78€.', 'pt')}'")
|
|
129
|
+
print(f"Normalized: '{normalize('O lucro foi de 123.456,78€.', 'pt-PT')}'")
|
|
130
|
+
|
|
131
|
+
# English dates and times
|
|
132
|
+
print("\n--- English Date & Time Examples ---")
|
|
133
|
+
print(f"English date (MDY format): {normalize('The date is 08/03/2025', 'en-US')}")
|
|
134
|
+
print(f"English ambiguous date (MDY assumed): {normalize('The report is due 15/05/2025', 'en-US')}")
|
|
135
|
+
print(f"English date with dashes: {normalize('The event is on 11-04-2025', 'en-US')}")
|
|
136
|
+
print(f"English AM/PM time: {normalize('The meeting is at 10am', 'en-US')}")
|
|
137
|
+
print(f"English military time: {normalize('The party is at 19h30', 'en-US')}")
|
|
138
|
+
print(f"English month name: {normalize('The report is due 15 May 2025', 'en-US')}")
|
|
139
|
+
|
|
140
|
+
# Portuguese dates and times
|
|
141
|
+
print("\n--- Portuguese Date & Time Examples ---")
|
|
142
|
+
print(f"Portuguese date (A data é 03/08/2025): {normalize('A data é 03/08/2025', 'pt')}")
|
|
143
|
+
print(
|
|
144
|
+
f"Portuguese ambiguous date (O relatório é para 15/05/2025): {normalize('O relatório é para 15/05/2025', 'pt')}")
|
|
145
|
+
print(
|
|
146
|
+
f"Portuguese date with dashes (O evento é no dia 25-10-2024): {normalize('O evento é no dia 25-10-2024', 'pt')}")
|
|
147
|
+
print(f"Portuguese military time (O encontro é às 14h30): {normalize('O encontro é às 14h30', 'pt')}")
|
|
148
|
+
|
|
149
|
+
# Other examples
|
|
150
|
+
print(f"\n--- Other Examples ---")
|
|
151
|
+
print(f"English fraction: {normalize('The fraction is 1/2', 'en')}")
|
|
152
|
+
print(f"English plural fraction: {normalize('There are 3/4 of a cup', 'en')}")
|
|
153
|
+
print(f"Spanish example with units: {normalize('The temperature is 25ºC', 'es')}")
|
|
154
|
+
print(f"Portuguese with punctuation: {normalize('12345€, 5m e 10kg', 'pt')}")
|
|
155
|
+
print(
|
|
156
|
+
f"Portuguese word-digit: {normalize('Esta temporada leva oito jogos ao serviço da equipa sub-23 leonina.', 'pt')}")
|
text2spoken/units.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Expansion of units and ordinal indicators attached to numbers."""
|
|
2
|
+
import logging
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from ovos_number_parser import pronounce_number
|
|
6
|
+
|
|
7
|
+
from text2spoken.numbers import _get_number_separators
|
|
8
|
+
from text2spoken.tables import UNITS
|
|
9
|
+
|
|
10
|
+
LOG = logging.getLogger("text2spoken")
|
|
11
|
+
|
|
12
|
+
def _normalize_units(text: str, full_lang: str) -> str:
|
|
13
|
+
"""
|
|
14
|
+
Helper function to normalize units attached to numbers.
|
|
15
|
+
This function handles symbolic and alphanumeric units separately
|
|
16
|
+
to avoid issues with word boundaries.
|
|
17
|
+
"""
|
|
18
|
+
# "º" (U+00BA, masculine ordinal indicator, e.g. "1º andar") looks like
|
|
19
|
+
# "°" (U+00B0, degree sign) but is not the same character. Only treat it
|
|
20
|
+
# as a degree sign when it is actually used as a temperature unit
|
|
21
|
+
# (e.g. "20ºC" / "20ºc"), so ordinals are not corrupted into degrees.
|
|
22
|
+
# Case-insensitive to match the (IGNORECASE) unit regex below.
|
|
23
|
+
text = re.sub(r"º(?=\s?[CFK]\b)", "°", text, flags=re.IGNORECASE)
|
|
24
|
+
|
|
25
|
+
# Any remaining "º" is a genuine ordinal indicator attached to a digit
|
|
26
|
+
# (e.g. "1º andar", "20º"). normalize() must never leave raw digits in
|
|
27
|
+
# the output, so expand these as ordinal numbers, falling back to a
|
|
28
|
+
# plain cardinal (still dropping the "º") if ordinal pronunciation is
|
|
29
|
+
# unavailable for the language.
|
|
30
|
+
def _replace_ordinal_indicator(match: "re.Match") -> str:
|
|
31
|
+
number = int(match.group(1))
|
|
32
|
+
try:
|
|
33
|
+
return pronounce_number(number, full_lang, ordinals=True)
|
|
34
|
+
except Exception as e:
|
|
35
|
+
LOG.error(f"Failed to pronounce ordinal number: {number}º - ({e})")
|
|
36
|
+
return pronounce_number(number, full_lang)
|
|
37
|
+
|
|
38
|
+
text = re.sub(r"(\d+)º", _replace_ordinal_indicator, text)
|
|
39
|
+
|
|
40
|
+
lang_code = full_lang.split("-")[0]
|
|
41
|
+
if lang_code in UNITS:
|
|
42
|
+
# Determine number separators for the language
|
|
43
|
+
decimal_separator, thousands_separator = _get_number_separators(full_lang)
|
|
44
|
+
|
|
45
|
+
# Separate units into symbolic and alphanumeric
|
|
46
|
+
symbolic_units = {k: v for k, v in UNITS[lang_code].items() if not k.isalnum()}
|
|
47
|
+
alphanumeric_units = {k: v for k, v in UNITS[lang_code].items() if k.isalnum()}
|
|
48
|
+
|
|
49
|
+
# Create regex pattern for symbolic units and replace them first
|
|
50
|
+
sorted_symbolic = sorted(symbolic_units.keys(), key=len, reverse=True)
|
|
51
|
+
symbolic_pattern_str = "|".join(re.escape(unit) for unit in sorted_symbolic)
|
|
52
|
+
if symbolic_pattern_str:
|
|
53
|
+
# Pattern to match numbers with optional thousands and decimal separators
|
|
54
|
+
number_pattern_str = rf"(\d+[{re.escape(thousands_separator)}]?\d*[{re.escape(decimal_separator)}]?\d*)"
|
|
55
|
+
symbolic_pattern = re.compile(number_pattern_str + r"\s*(" + symbolic_pattern_str + r")", re.IGNORECASE)
|
|
56
|
+
|
|
57
|
+
def replace_symbolic(match):
|
|
58
|
+
number = match.group(1)
|
|
59
|
+
# Remove thousands separator and replace decimal separator for parsing
|
|
60
|
+
if thousands_separator in number and decimal_separator in number:
|
|
61
|
+
number = number.replace(thousands_separator, "").replace(decimal_separator, ".")
|
|
62
|
+
elif decimal_separator != "." and decimal_separator in number:
|
|
63
|
+
number = number.replace(decimal_separator, ".")
|
|
64
|
+
unit_symbol = match.group(2)
|
|
65
|
+
# The regex is IGNORECASE (e.g. "°c" matches "°C"), so the
|
|
66
|
+
# matched text may not share the dict key's exact case.
|
|
67
|
+
unit_word = (symbolic_units.get(unit_symbol)
|
|
68
|
+
or symbolic_units.get(unit_symbol.upper())
|
|
69
|
+
or symbolic_units.get(unit_symbol.lower()))
|
|
70
|
+
try:
|
|
71
|
+
return f"{pronounce_number(float(number) if '.' in number else int(number), full_lang)} {unit_word}"
|
|
72
|
+
except Exception as e:
|
|
73
|
+
LOG.error(f"Failed to pronounce number with unit: {number}{unit_symbol} - ({e})")
|
|
74
|
+
return match.group(0)
|
|
75
|
+
|
|
76
|
+
text = symbolic_pattern.sub(replace_symbolic, text)
|
|
77
|
+
|
|
78
|
+
# Create regex pattern for alphanumeric units and replace them next
|
|
79
|
+
sorted_alphanumeric = sorted(alphanumeric_units.keys(), key=len, reverse=True)
|
|
80
|
+
alphanumeric_pattern_str = "|".join(re.escape(unit) for unit in sorted_alphanumeric)
|
|
81
|
+
if alphanumeric_pattern_str:
|
|
82
|
+
number_pattern_str = rf"(\d+[{re.escape(thousands_separator)}]?\d*[{re.escape(decimal_separator)}]?\d*)"
|
|
83
|
+
alphanumeric_pattern = re.compile(number_pattern_str + r"\s*(" + alphanumeric_pattern_str + r")\b",
|
|
84
|
+
re.IGNORECASE)
|
|
85
|
+
|
|
86
|
+
def replace_alphanumeric(match):
|
|
87
|
+
number = match.group(1)
|
|
88
|
+
# Remove thousands separator and replace decimal separator for parsing
|
|
89
|
+
if thousands_separator in number and decimal_separator in number:
|
|
90
|
+
number = number.replace(thousands_separator, "").replace(decimal_separator, ".")
|
|
91
|
+
elif decimal_separator != "." and decimal_separator in number:
|
|
92
|
+
number = number.replace(decimal_separator, ".")
|
|
93
|
+
unit_symbol = match.group(2)
|
|
94
|
+
unit_word = alphanumeric_units[unit_symbol]
|
|
95
|
+
return f"{pronounce_number(float(number) if '.' in number else int(number), full_lang)} {unit_word}"
|
|
96
|
+
|
|
97
|
+
text = alphanumeric_pattern.sub(replace_alphanumeric, text)
|
|
98
|
+
return text
|
text2spoken/version.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: text2spoken
|
|
3
|
+
Version: 0.0.2a1
|
|
4
|
+
Summary: Rewrite written text into the words a voice speaks: numbers, dates, times, units, titles and contractions
|
|
5
|
+
Author-email: JarbasAI <jarbasai@mailfence.com>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/TigreGotico/text2spoken
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: ovos-number-parser>=0.4.0
|
|
16
|
+
Requires-Dist: ovos-date-parser>=0.6.4a1
|
|
17
|
+
Requires-Dist: unicode_rbnf>=2.0.0
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest; extra == "test"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# text2spoken
|
|
23
|
+
|
|
24
|
+
text2spoken rewrites written text into the words a voice speaks. It expands numbers, dates, times, units, titles and contractions. A phonemizer then reads words, not digits or symbols.
|
|
25
|
+
|
|
26
|
+
## Quickstart
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install --pre text2spoken
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from text2spoken import normalize
|
|
34
|
+
|
|
35
|
+
print(normalize("Dr. Smith paid 3/4 of the bill at 25°C.", "en"))
|
|
36
|
+
print(normalize("O Sr. Silva pagou 10kg às 14h30.", "pt-PT"))
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```text
|
|
40
|
+
Doctor Smith paid three quarters of the bill at twenty five degrees celsius.
|
|
41
|
+
O Senhor Silva pagou dez quilogramas às catorze e trinta.
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Where this fits
|
|
45
|
+
|
|
46
|
+
Alone: it turns written text into spoken words, with `from text2spoken import normalize`.
|
|
47
|
+
In the stack: it is the normalisation stage. A frontend or a TTS library calls it before phonemization, and it calls `ovos-number-parser`, `ovos-date-parser` and `unicode_rbnf`.
|
|
48
|
+
Through scriptconv: scriptconv has no `normalize` extra. Install `text2spoken` directly.
|
|
49
|
+
|
|
50
|
+
## What `normalize` does
|
|
51
|
+
|
|
52
|
+
`normalize(text, lang)` runs four passes in this order:
|
|
53
|
+
|
|
54
|
+
1. It expands dates and times, such as `03/08/2025` and `14h30`.
|
|
55
|
+
2. It splits a word from a digit that a hyphen joins, such as `sub-23`. A range such as `3-2` stays as it is.
|
|
56
|
+
3. It expands units and ordinal indicators, such as `10kg`, `25°C` and `1º`.
|
|
57
|
+
4. It reads each word, and expands contractions, titles, fractions and numbers.
|
|
58
|
+
|
|
59
|
+
Each pass is also a plain function, so a frontend can compose them and add its own rules. See [docs/api.md](docs/api.md).
|
|
60
|
+
|
|
61
|
+
The language tag selects the rules. The tables use the part before the first hyphen, so `pt-BR` and `pt-PT` share one table. `en-US` reads an ambiguous date as month first, and every other tag reads it as day first.
|
|
62
|
+
|
|
63
|
+
## Languages
|
|
64
|
+
|
|
65
|
+
These languages have tables in `text2spoken/tables.py`:
|
|
66
|
+
|
|
67
|
+
| Table | Languages |
|
|
68
|
+
| --- | --- |
|
|
69
|
+
| `CONTRACTIONS` | en |
|
|
70
|
+
| `TITLES` | ca, de, en, es, fr, gl, it, nl, pt |
|
|
71
|
+
| `UNITS` | de, en, es, fr, pt |
|
|
72
|
+
|
|
73
|
+
This command prints the same list from the installed package:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
python -c "from text2spoken import CONTRACTIONS, TITLES, UNITS; [print(sorted(t)) for t in (CONTRACTIONS, TITLES, UNITS)]"
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Numbers, dates and times come from `ovos-number-parser` and `ovos-date-parser`, so those packages set their language coverage.
|
|
80
|
+
|
|
81
|
+
To add a language, add its entries to `text2spoken/tables.py`. A new language needs no code change.
|
|
82
|
+
|
|
83
|
+
## Behaviour to know
|
|
84
|
+
|
|
85
|
+
- The library uses no network and loads no model, so it works offline.
|
|
86
|
+
- A language that the parsers do not support keeps its digits. The library logs an error and returns the text.
|
|
87
|
+
- A `text` or `lang` value of the wrong type raises `TypeError` or `AttributeError` from the code that reads it.
|
|
88
|
+
- Importing the library imports `ovos-date-parser`, which sets the import time.
|
|
89
|
+
- `ovos-config`, a dependency of `ovos-date-parser`, creates `~/.config/mycroft` at import.
|
|
90
|
+
|
|
91
|
+
## Development
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
uv pip install --prerelease=allow -e ".[test]"
|
|
95
|
+
pytest tests
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Licence
|
|
99
|
+
|
|
100
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
text2spoken/__init__.py,sha256=tGUnKx7mLTS83PXhizo-eJ7MYMWvkibwZIMFrod8UsQ,1469
|
|
2
|
+
text2spoken/datetimes.py,sha256=ZU_OhMW5LgmeiFmOWnCIFp8BIsUdQD2albzHT9xux-8,4392
|
|
3
|
+
text2spoken/numbers.py,sha256=Cz_hsqB9lL9zv3nuDkepamWHeRFJdrrl_g96rOgSMDY,3782
|
|
4
|
+
text2spoken/tables.py,sha256=RJPI30KFfkyUEzmRlCbCgezWPv5bYlSxlS1Lt2kj6gk,9725
|
|
5
|
+
text2spoken/text.py,sha256=zpb4B9KgBaJAaw6AigdDbv6-HGiJyMsErjffm0WlOw0,7064
|
|
6
|
+
text2spoken/units.py,sha256=F-Sbz2DJZecR6_PT-vZ9klCS5U3noagOpXXaJywe2vg,5429
|
|
7
|
+
text2spoken/version.py,sha256=bnn56eZMSfhGARN80wnH9MfTv5i5iSuTTHzeoeoQDb8,237
|
|
8
|
+
text2spoken-0.0.2a1.dist-info/licenses/LICENSE,sha256=JBPAOkIXtKdcPVf305lJfqrNVYQ0beL0DenojOGR0EI,11346
|
|
9
|
+
text2spoken-0.0.2a1.dist-info/METADATA,sha256=ZBa_OVGOlZt2uxOuFB5O1p0V1Ab3BtCqMGM5FHcUeWU,3795
|
|
10
|
+
text2spoken-0.0.2a1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
text2spoken-0.0.2a1.dist-info/top_level.txt,sha256=XqjmOV2yDxubrqC_aw5JrPslVXaKYipolDOxUBgnmXQ,12
|
|
12
|
+
text2spoken-0.0.2a1.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 TigreGotico Lda
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
text2spoken
|