File size: 15,369 Bytes
fdc4749 |
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 |
import subprocess
import logging
import string
from pathlib import Path
from collections import OrderedDict
from nltk.tokenize import TweetTokenizer
from typing import List, Dict, Optional
import re
# Constants
SUPPORTED_LANGUAGES = {'eu', 'es'}
SUPPORTED_SYMBOLS = {'sampa', 'ipa'}
SAMPA_TO_IPA = OrderedDict([
("p", "p"), ("b", "b"), ("t", "t"), ("c", "c"), ("d", "d"),
("k", "k"), ("g", "ɡ"), ("tS", "tʃ"), ("ts", "ts"), ("ts`", "tʂ"),
("gj", "ɟ"), ("jj", "ʝ"), ("f", "f"), ("B", "β"), ("T", "θ"),
("D", "ð"), ("s", "s"), ("s`", "ʂ"), ("S", "ʃ"), ("x", "x"),
("G", "ɣ"), ("m", "m"), ("n", "n"), ("J", "ɲ"), ("l", "l"),
("L", "ʎ"), ("r", "ɾ"), ("rr", "r"), ("j", "j"), ("w", "w"),
("i", "i"), ("'i", "'i"), ("e", "e"), ("'e", "'e"), ("a", "a"),
("'a", "'a"), ("o", "o"), ("'o", "'o"), ("u", "u"), ("'u", "'u"),
("y", "y"), ("Z", "ʒ"), ("h", "h"), ("ph", "pʰ"), ("kh", "kʰ"),
("th", "tʰ")
])
MULTICHAR_TO_SINGLECHAR = {
"tʃ": "C",
"ts": "V",
"tʂ": "P",
"'i": "I",
"'e": "E",
"'a": "A",
"'o": "O",
"'u": "U",
"pʰ": "H",
"kʰ": "K",
"tʰ": "T"
}
class PhonemizerError(Exception):
"""Custom exception for Phonemizer errors."""
pass
class Phonemizer:
def __init__(self, language: str = "eu", symbol: str = "sampa",
path_modulo1y2: str = "modulo1y2/modulo1y2",
path_dicts: str = "dict") -> None:
"""Initialize the Phonemizer with the given language and symbol."""
if language not in SUPPORTED_LANGUAGES:
raise PhonemizerError(f"Unsupported language: {language}")
if symbol not in SUPPORTED_SYMBOLS:
raise PhonemizerError(f"Unsupported symbol type: {symbol}")
self.language = language
self.symbol = symbol
self.path_modulo1y2 = Path(path_modulo1y2)
self.path_dicts = Path(path_dicts)
self.logger = logging.getLogger(__name__)
# Initialize SAMPA to IPA dictionary
self._sampa_to_ipa_dict = SAMPA_TO_IPA
# Initialize word splitter regex
self._word_splitter = re.compile(r'\w+|[^\w\s]', re.UNICODE)
self._validate_paths()
def normalize(self, text: str) -> str:
"""Normalize the given text using an external command."""
try:
command = self._build_normalization_command()
process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding='ISO-8859-15',
shell=True
)
stdout, stderr = process.communicate(input=text)
if process.returncode != 0:
# Filter out the SetDur warning from the error message
filtered_stderr = '\n'.join(line for line in stderr.split('\n')
if 'Warning: argument not used SetDur' not in line)
if filtered_stderr.strip(): # Only raise error if there are other errors
error_msg = f"Normalization failed: {filtered_stderr}"
self.logger.error(error_msg)
raise PhonemizerError(error_msg)
return stdout.strip()
except Exception as e:
error_msg = f"Error during normalization: {str(e)}"
self.logger.error(error_msg)
return text
def getPhonemes(self, text: str, separate_phonemes: bool = False, use_single_char: bool = False) -> str:
"""Extract phonemes from the given text.
Args:
text (str): The input text to convert to phonemes
separate_phonemes (bool): If True, keeps spaces between phonemes. If False, produces compact phoneme strings.
Defaults to False.
use_single_char (bool): When `symbol` is "ipa" and True, collapse multichar IPA sequences
into mapped single characters (uses `_transform_multichar_phonemes`).
Defaults to False.
Returns:
str: The phoneme sequence with words separated by " | "
"""
try:
# Pre-process text to handle dots consistently
# Replace multiple dots with a single dot to avoid issues with ellipsis
text = re.sub(r'\.{2,}', '.', text)
# Process input line-by-line so we preserve original newlines
lines = text.split('\n')
per_line_outputs = []
for line in lines:
# If the input line is empty, preserve empty line
if not line.strip():
per_line_outputs.append('')
continue
command = self._build_phoneme_extraction_command()
proc = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding='ISO-8859-15',
shell=True
)
stdout, stderr = proc.communicate(input=line)
if proc.returncode != 0:
error_msg = f"Phoneme extraction failed: {stderr}"
self.logger.error(error_msg)
raise PhonemizerError(error_msg)
# Replace any internal newlines in tool output with sentinel (shouldn't normally occur for single line)
stdout_line = stdout.replace('\n', ' | _ | ')
# Split into words and handle each separately for this line
word_phonemes = stdout_line.split(" | ")
result_phonemes = []
cleaned_phonemes = []
for phoneme_seq in word_phonemes:
if not phoneme_seq.strip():
continue
if phoneme_seq.strip() == "_":
continue
cleaned_phonemes.append(phoneme_seq.strip())
# Tokenize the original line into words/punctuation
words = self._word_splitter.findall(line)
# Count non-punctuation words
non_punct_words = [w for w in words if w not in string.punctuation]
# Ensure we have enough phonemes for all non-punctuation words
if len(cleaned_phonemes) < len(non_punct_words):
while len(cleaned_phonemes) < len(non_punct_words):
if cleaned_phonemes:
cleaned_phonemes.append(cleaned_phonemes[-1])
else:
cleaned_phonemes.append("a")
# Process words and phonemes together for this line
phoneme_idx = 0
word_idx = 0
line_result = []
while word_idx < len(words):
word = words[word_idx]
if word in string.punctuation:
line_result.append(word)
word_idx += 1
continue
# Regular word processing
if phoneme_idx < len(cleaned_phonemes):
phonemes = cleaned_phonemes[phoneme_idx].split()
if self.symbol == "sampa":
if separate_phonemes:
processed_phonemes = " ".join(p for p in phonemes if p != "-")
else:
processed_phonemes = "".join(p for p in phonemes if p != "-")
else:
ipa_phonemes = [self._sampa_to_ipa_dict.get(p, p) for p in phonemes if p != "-"]
if separate_phonemes:
processed_phonemes = " ".join(ipa_phonemes)
else:
# Start with spaced IPA tokens to allow matching multichar tokens
processed_phonemes = " ".join(ipa_phonemes)
if use_single_char:
processed_phonemes = self._transform_multichar_phonemes(processed_phonemes)
# Remove spaces for compact form
processed_phonemes = processed_phonemes.replace(" ", "")
line_result.append(processed_phonemes)
phoneme_idx += 1
word_idx += 1
else:
# No phoneme left for this word: skip it
word_idx += 1
# If there are leftover phonemes, append them
while phoneme_idx < len(cleaned_phonemes):
phonemes = cleaned_phonemes[phoneme_idx].split()
if self.symbol == "sampa":
processed_phonemes = " ".join(p for p in phonemes if p != "-")
else:
ipa_phonemes = [self._sampa_to_ipa_dict.get(p, p) for p in phonemes if p != "-"]
if separate_phonemes:
processed_phonemes = " ".join(ipa_phonemes)
else:
processed_phonemes = " ".join(ipa_phonemes)
if use_single_char:
processed_phonemes = self._transform_multichar_phonemes(processed_phonemes)
processed_phonemes = processed_phonemes.replace(" ", "")
line_result.append(processed_phonemes)
phoneme_idx += 1
# Format final output for this line using spacing rules
out_parts = []
# Keep a parallel map to the original words so we can decide sentence splits
orig_map = []
for idx, token in enumerate(line_result):
is_punct = token in string.punctuation
if not is_punct:
normalized = re.sub(r"\s+", " ", token.strip())
out_parts.append(normalized)
# Map this output token to the corresponding original word (if available)
if idx < len(words):
orig_map.append(words[idx])
else:
orig_map.append(None)
else:
out_parts.append(token)
if idx < len(words):
orig_map.append(words[idx])
else:
orig_map.append(None)
final_line = ""
for i, tok in enumerate(out_parts):
if i == 0:
final_line += tok
continue
prev = out_parts[i-1]
if tok in string.punctuation:
final_line = final_line.rstrip(' ')
final_line += (' ' if separate_phonemes else ' ') + tok
# Preserve input line boundaries: do NOT insert newlines mid-line.
# Always add the standard separator after punctuation.
if i < len(out_parts) - 1:
final_line += (' ' if separate_phonemes else ' ')
else:
if prev in string.punctuation:
final_line += tok
else:
sep = ' ' if separate_phonemes else ' '
final_line += sep + tok
# If a sentence-ending punctuation is followed by a capital letter,
# split into separate lines (keeps numeric periods like "1980. urtean" intact).
# This turns "... ? Ni ..." into two lines at the sentence boundary.
split_line = re.sub(r"(?<=[\?\!\.])\s+(?=[A-ZÁÉÍÓÚÜÑ])", "\n", final_line)
per_line_outputs.append(split_line)
return "\n".join(per_line_outputs)
except Exception as e:
error_msg = f"Error in phoneme extraction: {str(e)}"
self.logger.error(error_msg)
return ""
def _build_normalization_command(self) -> str:
"""Build the command string for normalization."""
modulo_path = self._get_file_path() / self.path_modulo1y2
dict_path = self._get_file_path() / self.path_dicts
dict_file = f"{self.language}_dicc"
return f'{modulo_path} -TxtMode=Word -Lang={self.language} -HDic={dict_path/dict_file}'
def _build_phoneme_extraction_command(self) -> str:
"""Build the command string for phoneme extraction."""
modulo_path = self._get_file_path() / self.path_modulo1y2
dict_path = self._get_file_path() / self.path_dicts
dict_file = f"{self.language}_dicc"
return f'{modulo_path} -Lang={self.language} -HDic={dict_path/dict_file}'
def _get_file_path(self) -> Path:
return Path(__file__).parent
def _validate_paths(self) -> None:
"""Validate paths with enhanced error reporting."""
try:
if not self.path_modulo1y2.exists():
raise PhonemizerError(f"Modulo1y2 executable not found at: {self.path_modulo1y2}")
if not self.path_dicts.exists():
raise PhonemizerError(f"Dictionary directory not found at: {self.path_dicts}")
# Check for both possible dictionary files
dict_file = self.path_dicts / f"{self.language}_dicc"
if not dict_file.exists():
# Try with .dic extension as fallback
dict_file_alt = self.path_dicts / f"{self.language}_dicc.dic"
if not dict_file_alt.exists():
raise PhonemizerError(f"Dictionary file not found at either {dict_file} or {dict_file_alt}")
except Exception as e:
self.logger.error(f"Path validation error: {str(e)}")
raise
def _transform_multichar_phonemes(self, phoneme_sequence: str) -> str:
"""
Transform multicharacter IPA phonemes to single characters using the MULTICHAR_TO_SINGLECHAR mapping.
Args:
phoneme_sequence (str): A string containing phonemes separated by spaces
Returns:
str: The transformed phoneme sequence with multicharacter phonemes replaced by single characters
"""
# Split the sequence into individual phonemes
phonemes = phoneme_sequence.split()
transformed_phonemes = []
for phoneme in phonemes:
# Check if the phoneme exists in our mapping
if phoneme in MULTICHAR_TO_SINGLECHAR:
transformed_phonemes.append(MULTICHAR_TO_SINGLECHAR[phoneme])
else:
transformed_phonemes.append(phoneme)
return " ".join(transformed_phonemes)
|