tiny-voca-da / frontend /danish-v4.patch
inlanger's picture
tiny-voca-da v0.1: frontend v4 + sm9 vocoder (ONNX fp32/int8, PyTorch, frontend, recipe, samples)
adabee1 verified
Raw History Blame Contribute Delete
27 kB
diff --git a/src/tiny_voca/danish_g2p.py b/src/tiny_voca/danish_g2p.py
new file mode 100644
index 0000000..9aaf07b
--- /dev/null
+++ b/src/tiny_voca/danish_g2p.py
@@ -0,0 +1,69 @@
+"""Danish G2P for words the NST lexicon lacks (frontend v4).
+
+A DeepPhonemizer (MIT) forward transformer trained on the packaged CC0 NST lexicon
+(kit ``scripts/g2p_train.py``). Its outputs are the frontend's own NST tokens with
+their stress level, so a compound such as ``familieretshuset`` keeps NST symbols
+and stød instead of going to eSpeak. Each (NST phone, stress) pair is one model
+symbol; ``da_g2p_nst_v1.symbols.json`` maps them back.
+
+The shipped file holds only the weights and the DeepPhonemizer config (it loads
+with ``weights_only=True``), is verified by SHA-256 before use and always runs
+on CPU, so annotation and inference give the same tokens. A word the model
+cannot read (no input symbols, or an empty prediction) returns ``None`` and the
+caller falls back to eSpeak.
+"""
+
+from functools import lru_cache
+import hashlib
+from importlib import resources
+import io
+import json
+
+from .danish_g2p_data import G2P_METADATA
+
+
+def _resource(name):
+ return resources.files("tiny_voca").joinpath("resources", name).read_bytes()
+
+
+@lru_cache(maxsize=1)
+def _model():
+ import torch
+ from dp.model.model import ModelType, create_model
+ from dp.model.predictor import Predictor
+ from dp.preprocessing.text import Preprocessor
+
+ raw = _resource(G2P_METADATA["resource"])
+ if hashlib.sha256(raw).hexdigest() != G2P_METADATA["sha256"]:
+ raise RuntimeError("Packaged Danish G2P model SHA-256 differs from the frontend identity")
+ symbols_raw = _resource(G2P_METADATA["symbols"])
+ if hashlib.sha256(symbols_raw).hexdigest() != G2P_METADATA["symbols_sha256"]:
+ raise RuntimeError("Packaged Danish G2P symbol table SHA-256 differs")
+ state = torch.load(io.BytesIO(raw), map_location="cpu", weights_only=True)
+ config = state["config"]
+ model = create_model(ModelType(config["model"]["type"]), config=config)
+ model.load_state_dict(state["model"])
+ model.eval()
+ decode = {char: (phone, stress) for phone, stress, char in json.loads(symbols_raw)["pairs"]}
+ return Predictor(model=model, preprocessor=Preprocessor.from_config(config)), decode, frozenset(
+ config["preprocessing"]["text_symbols"])
+
+
+def readable(word):
+ """True when every character of the casefolded word is a model input symbol."""
+ _, _, symbols = _model()
+ folded = word.casefold()
+ return any(c.isalpha() for c in folded) and all(c in symbols for c in folded)
+
+
+@lru_cache(maxsize=65536)
+def predict(word):
+ """One word -> tuple of (NST phone, stress) pairs, or None."""
+ import torch
+ if not readable(word):
+ return None
+ predictor, decode, _ = _model()
+ with torch.inference_mode():
+ result = predictor([word.casefold()], lang="da", batch_size=1)[0]
+ units = tuple(decode[c] for c in result.phonemes if c in decode)
+ return units or None
diff --git a/src/tiny_voca/danish_lexicon.py b/src/tiny_voca/danish_lexicon.py
index a1e51a1..f9ddf93 100644
--- a/src/tiny_voca/danish_lexicon.py
+++ b/src/tiny_voca/danish_lexicon.py
@@ -1,9 +1,25 @@
-"""Offline NST dictionary first, explicit eSpeak fallback for Danish v3.
+"""Offline NST dictionary first, then explicit fallbacks, for Danish v4.
The compiled CC0 resource is shipped inside the Python package and verified
before use. Missing/modified data is an error, never a silent switch back to
v2. The resource stores a deterministic canonical variant, not contextual POS
disambiguation. ``words_with_trace`` exposes the selected source and ambiguity.
+
+Version 4 changes only what happens to words NST lacks (v3 sent every unknown
+span to eSpeak's Danish voice, which has no stød and reads English words as
+Danish). In order:
+
+1. ``enog…`` numerals are derived from NST's ``toog…`` entries (NST has every
+ ``toog…`` form and no ``enog…`` one), ``"to:?`` -> ``"e:n``.
+2. English: a text piece that lingua (Apache-2.0) finds English goes to eSpeak's
+ English voice as a whole; so does an unknown span that is English on its own.
+ The thresholds are part of the profile identity (``LANGUAGE_POLICY``).
+3. Danish words: the NST-trained G2P (``danish_g2p``), which keeps NST tokens and
+ stød. All-capital words of up to five letters are initialisms and stay with
+ eSpeak, which spells them.
+4. Anything else (digits, other symbols) goes to eSpeak's Danish voice as before.
+
+``replace_symbols`` reads ``&``, ``§``, ``=`` and ``+`` as words before chunking.
"""
from functools import lru_cache
@@ -11,11 +27,25 @@ import gzip
import hashlib
from importlib import resources
import json
+import re
import unicodedata
from .danish_nst_data import LEXICON_METADATA
from .danish_nst_inventory import CONVERTER_VERSION, LEXICON_SCHEMA, SELECTION_POLICY, parse_sampa
+LINGUA_VERSION = "2.1.1"
+LANGUAGE_POLICY = (f"lingua-language-detector=={LINGUA_VERSION}:da|en;piece>=3words@0.90;"
+ "text@0.95+(piece<=2words|piece@0.50);unknown-span-1word@0.93;unknown-span-2+words@0.85;"
+ "espeak-en:iə=i+ə,ʊə=ʊ+ə,r=ɹ-v1")
+DERIVED_POLICY = 'enog-from-toog:"to:?->"e:n-v1'
+SYMBOL_POLICY = "da-symbols-v1:&=og,§=paragraf,==lig med,+=plus"
+ENGLISH_VOICE = "en"
+# eSpeak's English voice uses three phones outside the Danish inventory. Only English pieces and
+# spans are respelled with inventory phones (no new token IDs); Danish ``canonical`` stays strict.
+ENGLISH_PHONES = {"iə": ("i", "ə"), "ʊə": ("ʊ", "ə"), "r": ("ɹ",)}
+_SYMBOLS = {"&": " og ", "§": " paragraf ", "=": " lig med ", "+": " plus "}
+_TOOG_PREFIX, _ENOG_PREFIX = '"to:?', '"e:n'
+
@lru_cache(maxsize=1)
def _lexicon():
@@ -49,9 +79,7 @@ def _lexicon():
return entries, folded, folded_variants, max(len(key.split()) for key in entries)
-def lookup(phrase):
- """Selected dictionary record or None. Does not invoke eSpeak."""
- key = " ".join(unicodedata.normalize("NFKC", phrase).split())
+def _lookup_nst(key):
entries, folded, folded_variants, _ = _lexicon()
matched, mode = key, "exact"
if matched not in entries:
@@ -66,22 +94,126 @@ def lookup(phrase):
folded_variants.get(key.casefold(), []) if mode == "casefold" else []}
+def _derived(key):
+ """``enog…`` numerals (21, 31, …, 91 and their ordinals) from NST's ``toog…``."""
+ if " " in key or not key.casefold().startswith("enog"):
+ return None
+ base = _lookup_nst("toog" + key[4:])
+ if base is None or not base["sampa"].startswith(_TOOG_PREFIX):
+ return None
+ return {**base, "orthography": key, "sampa": _ENOG_PREFIX + base["sampa"][len(_TOOG_PREFIX):],
+ "source_id": "derived:" + base["source_id"], "variant_count": 1, "match": "derived",
+ "derived_from": base["orthography"], "alternative_sampa": [], "casefold_alternatives": []}
+
+
+def lookup(phrase):
+ """Selected dictionary record (NST, or derived from NST) or None. Does not invoke eSpeak."""
+ key = " ".join(unicodedata.normalize("NFKC", phrase).split())
+ return _lookup_nst(key) or _derived(key)
+
+
@lru_cache(maxsize=32768)
def _parsed(sampa):
return tuple(tuple(word) for word in parse_sampa(sampa))
-def words_with_trace(piece, fallback=None):
+def replace_symbols(text):
+ for symbol, words in _SYMBOLS.items():
+ text = text.replace(symbol, words)
+ return re.sub(r"\s+", " ", text).strip()
+
+
+@lru_cache(maxsize=1)
+def _detector():
+ from importlib.metadata import version
+ if version("lingua-language-detector") != LINGUA_VERSION:
+ raise RuntimeError(f"Danish v4 requires lingua-language-detector=={LINGUA_VERSION}")
+ from lingua import Language, LanguageDetectorBuilder
+ return LanguageDetectorBuilder.from_languages(Language.DANISH, Language.ENGLISH).build(), Language.ENGLISH
+
+
+@lru_cache(maxsize=65536)
+def english_confidence(text):
+ detector, english = _detector()
+ return detector.compute_language_confidence(text, english)
+
+
+def english_pieces(text, pieces):
+ """For each text piece (between punctuation marks): is it English as a whole?
+
+ A piece of three or more words decides by itself. Inside a text that is English as a whole,
+ a short piece ("…, man.") follows the text, because one or two words are too few to judge.
+ """
+ whole = english_confidence(text) if pieces else 0.0
+ flags = []
+ for piece in pieces:
+ confidence, size = english_confidence(piece), len(piece.split())
+ flags.append((size >= 3 and confidence >= 0.90) or (whole >= 0.95 and (size <= 2 or confidence >= 0.50)))
+ return flags
+
+
+def _english_span(phrase):
+ return english_confidence(phrase) >= (0.93 if len(phrase.split()) == 1 else 0.85)
+
+
+def _english(text, fallback):
+ return [[(item, level if index == 0 else 0) for phone, level in word
+ for index, item in enumerate(ENGLISH_PHONES.get(phone, (phone,)))] for word in fallback(text, ENGLISH_VOICE)]
+
+
+def _initialism(word):
+ letters = [c for c in word if c.isalpha()]
+ return 0 < len(letters) <= 5 and all(c.isupper() for c in letters)
+
+
+def _unknown_span(phrase, fallback):
+ """Words NST lacks -> (words, trace rows), sources in the order of the module docstring."""
+ if _english_span(phrase):
+ return _english(phrase, fallback), [{"source": "espeak-en", "text": phrase, "word_count": len(phrase.split()),
+ "reason": "english-span", "stød_verified": False}]
+ from .danish_g2p import predict
+ words, trace, pending = [], [], []
+
+ def flush():
+ if pending:
+ text = " ".join(pending)
+ words.extend(fallback(text, "da"))
+ trace.append({"source": "espeak-fallback", "text": text, "word_count": len(pending),
+ "reason": "not-in-compiled-nst", "stød_verified": False})
+ pending.clear()
+
+ for word in phrase.split():
+ units = None if _initialism(word) else predict(word)
+ if units is None:
+ pending.append(word)
+ continue
+ flush()
+ words.append(units)
+ trace.append({"source": "g2p", "text": word, "word_count": 1, "reason": "not-in-compiled-nst"})
+ flush()
+ return words, trace
+
+
+def _espeak(text, voice):
+ from .text import espeak_words
+ return espeak_words(text, voice)
+
+
+def words_with_trace(piece, fallback=None, english=None):
"""Return parsed word units plus a source trace for each matched span.
Multiword NST entries use longest matching spans. Unknown contiguous spans
- go to eSpeak's Danish voice together, retaining context within that span.
- eSpeak fallback is recorded and never advertised as stød-aware.
+ are resolved by ``_unknown_span``. ``english`` is the piece-level language
+ decision (``english_pieces``); None decides from the piece alone.
+ ``fallback(text, voice)`` replaces eSpeak in offline audits.
"""
- if fallback is None:
- from .text import espeak_words
- fallback = lambda value: espeak_words(value, "da")
+ fallback = fallback or _espeak
+ if english is None:
+ english = english_pieces(piece, [piece])[0]
parts = piece.split()
+ if english:
+ return _english(piece, fallback), [{"source": "espeak-en", "text": piece, "word_count": len(parts),
+ "reason": "english-piece", "stød_verified": False}]
_, _, _, maximum = _lexicon()
def match_at(start):
@@ -98,17 +230,16 @@ def words_with_trace(piece, fallback=None):
if match is not None:
end, phrase, record = match
words.extend(_parsed(record["sampa"]))
- trace.append({"source": "nst", "text": phrase, "word_count": end - index, **record})
+ trace.append({"source": "nst" if record["match"] != "derived" else "nst-derived",
+ "text": phrase, "word_count": end - index, **record})
index = end
else:
end = index + 1
while end < len(parts) and match_at(end) is None:
end += 1
- phrase = " ".join(parts[index:end])
- converted = fallback(phrase)
+ converted, rows = _unknown_span(" ".join(parts[index:end]), fallback)
words.extend(converted)
- trace.append({"source": "espeak-fallback", "text": phrase, "word_count": end - index,
- "reason": "not-in-compiled-nst", "stød_verified": False})
+ trace.extend(rows)
index = end
return words, trace
@@ -117,30 +248,41 @@ def words(piece):
return words_with_trace(piece)[0]
+def pieces_with_trace(normalized, fallback=None):
+ """Normalized text -> (``(is_punctuation, value)`` pieces for ``text.tokenize``, trace)."""
+ from .languages import DANISH
+ from .text import chunks
+ parts = list(chunks(normalized, DANISH))
+ english = iter(english_pieces(normalized, [piece for punctuation, piece in parts if not punctuation]))
+ pieces, trace = [], []
+ for punctuation, piece in parts:
+ if punctuation:
+ pieces.append((True, piece))
+ else:
+ converted, sources = words_with_trace(piece, fallback, next(english))
+ pieces.append((False, converted))
+ trace.extend(sources)
+ return pieces, trace
+
+
def explain(text, fallback=None):
"""Whole-text diagnostic using exactly the same normalizer/tokenizer.
Returns the chosen NST IDs, alternatives, fallback spans and final model
input. This is source provenance, not a judgement of the rendered audio.
- ``fallback`` is an optional eSpeak-compatible callable for offline audits.
+ ``fallback`` is an optional ``(text, voice)`` eSpeak-compatible callable for offline audits.
"""
from .languages import DANISH
- from .text import chunks, normalize_text, tokenize
+ from .text import normalize_text, tokenize
normalized = normalize_text(text, DANISH)
- pieces, trace = [], []
- for punctuation, piece in chunks(normalized, DANISH):
- if punctuation:
- pieces.append((True, piece))
- else:
- converted, sources = words_with_trace(piece, fallback)
- pieces.append((False, converted))
- trace.extend(sources)
+ pieces, trace = pieces_with_trace(normalized, fallback)
phones = tokenize(pieces, DANISH)
- nst_words = sum(row["word_count"] for row in trace if row["source"] == "nst")
- fallback_words = sum(row["word_count"] for row in trace if row["source"] == "espeak-fallback")
+ count = lambda *sources: sum(row["word_count"] for row in trace if row["source"] in sources)
return {"text": text, "normalized_text": normalized, "profile_digest": DANISH.digest,
"symbols": list(phones.symbols), "ids": list(phones.ids), "stress": list(phones.stress),
"unknown": list(phones.unknown), "token_count": len(phones.ids), "sources": trace,
- "nst_words": nst_words, "fallback_words": fallback_words,
+ "nst_words": count("nst", "nst-derived"), "derived_words": count("nst-derived"),
+ "g2p_words": count("g2p"), "english_words": count("espeak-en"),
+ "fallback_words": count("espeak-fallback"),
"ambiguous_spans": sum(row.get("variant_count", 0) > 1 or bool(row.get("casefold_alternatives"))
for row in trace)}
diff --git a/src/tiny_voca/languages.py b/src/tiny_voca/languages.py
index 0dde1a9..d13e689 100644
--- a/src/tiny_voca/languages.py
+++ b/src/tiny_voca/languages.py
@@ -110,7 +110,7 @@ class LanguageProfile:
if self.normalizer is not None:
value["normalizer"] = self.normalizer
if self.pronunciation:
- value["phonemizer"] = "nst-lexicon+espeak-fallback"
+ value["phonemizer"] = self.pronunciation.get("phonemizer", "nst-lexicon+espeak-fallback")
value["pronunciation"] = dict(self.pronunciation)
value["phonetic_classes"] = {
"vowels": sorted(self.vowel_set), "voiceless": sorted(self.voiceless),
@@ -226,24 +226,40 @@ _DA_ALIGNER_LABELS = {"?a": "a", "?ɑ": "ɑ", "ε": "ɛ", "ɐ̯": "ɐ", "ɒː":
from . import danish_nst_inventory as _nst
from .danish_nst_data import LEXICON_METADATA as _NST_METADATA
from .danish_numbers import NORMALIZER_VERSION as _DA_NORMALIZER
+from .danish_g2p_data import G2P_METADATA as _G2P_METADATA
+from .danish_lexicon import DERIVED_POLICY as _DERIVED, LANGUAGE_POLICY as _LANGUAGE, SYMBOL_POLICY as _SYMBOLS
+
+# Version 4 (same 220 symbols and IDs as version 3): NST-trained G2P for unknown Danish words,
+# English pieces/spans to eSpeak's English voice, derived enog… numerals, more abbreviations and
+# symbol words (see ``danish_lexicon``). New annotations; v3 checkpoints are branched with
+# ``--init-from --new-data``, never resumed.
+_DA_EXPANSIONS = {"nr": "nummer", "kl": "klokken", "ca": "cirka", "dr": "doktor",
+ "prof": "professor", "min": "minutter", "sek": "sekunder",
+ "bl.a": "blandt andet", "f.eks": "for eksempel", "pga": "på grund af",
+ "osv": "og så videre", "m.v": "med videre", "mv": "med videre", "m.m": "med mere",
+ "mht": "med hensyn til", "evt": "eventuelt", "inkl": "inklusive", "ekskl": "eksklusive",
+ "jf": "jævnfør", "vha": "ved hjælp af", "ifm": "i forbindelse med", "iflg": "ifølge",
+ "dvs": "det vil sige", "hhv": "henholdsvis", "ift": "i forhold til", "vedr": "vedrørende",
+ "tlf": "telefon", "o.l": "og lignende", "kr": "kroner", "mio": "millioner", "mia": "milliarder"}
DANISH = LanguageProfile(
- language="da", locale="da-DK", version=3, espeak_voice="da",
+ language="da", locale="da-DK", version=4, espeak_voice="da",
consonants=_DA_CONSONANTS + _nst.CONSONANTS, vowels=_DA_VOWELS + _nst.VOWELS,
ordered_phones=_DA_CONSONANTS + _DA_VOWELS + _nst.PHONES,
voiceless=frozenset(("p", "t", "k", "f", "s", "ʃ", "h", "tʃ", "ʔ", "s-", "t-", "p-", "x", "θ")) | _nst.VOICELESS,
fricatives=frozenset(("f", "s", "ʃ", "s-", "x", "θ")) | _nst.FRICATIVES,
abbreviations=frozenset(("nr", "kl", "ca", "dr", "prof", "min", "sek")),
- expansions=MappingProxyType({"nr": "nummer", "kl": "klokken", "ca": "cirka", "dr": "doktor",
- "prof": "professor", "min": "minutter", "sek": "sekunder"}),
+ expansions=MappingProxyType(_DA_EXPANSIONS),
canonical_map=MappingProxyType(_DA_CANONICAL),
aligner_labels=MappingProxyType({**_DA_ALIGNER_LABELS, **_nst.ALIGNER_LABELS}),
default_asr_language="da",
normalizer=_DA_NORMALIZER,
pronunciation=MappingProxyType({**_NST_METADATA,
"stød": "previous-segment-composite-v1", "stress": "first-vowel-of-syllable-v1",
- "sentence_prominence": "ignored-no-model-channel", "fallback": "espeak-ng-1.52.0-da-unknown-span",
- "lookup": "longest-multiword-exact-then-casefold-v1"}))
+ "sentence_prominence": "ignored-no-model-channel",
+ "fallback": "v4:derived-enog>english-espeak-ng-1.52.0-en>nst-g2p>espeak-ng-1.52.0-da-unknown-span",
+ "lookup": "longest-multiword-exact-then-casefold-v1", "derived": _DERIVED, "language_detection": _LANGUAGE,
+ "symbols": _SYMBOLS, "g2p": dict(_G2P_METADATA), "phonemizer": "nst-lexicon+nst-g2p+espeak-en+espeak-fallback"}))
PROFILES = MappingProxyType({"en": ENGLISH, "it": ITALIAN, "da": DANISH})
diff --git a/src/tiny_voca/text.py b/src/tiny_voca/text.py
index 5ea4008..9a84a8b 100644
--- a/src/tiny_voca/text.py
+++ b/src/tiny_voca/text.py
@@ -153,7 +153,8 @@ def normalize_text(text, profile=None):
profile = resolve(profile)
if profile.language == "da":
from .danish_numbers import normalize_danish_text
- text = normalize_danish_text(text)
+ from .danish_lexicon import replace_symbols
+ text = replace_symbols(normalize_danish_text(text))
text = re.sub(r"\.{3,}", "…", text)
text = re.sub(r"-{2,}|\s-\s", "—", text)
if profile.expansions:
@@ -335,15 +336,13 @@ def phonemize(text, profile=None):
if profile.language == "en" and _frontend == "own":
return tokenize(_dizione().pieces(text))
voice = ESPEAK_VOICE if profile.language == "en" else profile.espeak_voice
+ if profile.language == "da":
+ # Danish v4 decides English pieces from the whole text, so it builds all pieces at once.
+ from .danish_lexicon import pieces_with_trace
+ return tokenize(pieces_with_trace(normalize_text(text, profile))[0], profile)
pieces = []
for punctuation, piece in chunks(normalize_text(text, profile), profile):
- if punctuation:
- pieces.append((True, piece))
- elif profile.language == "da":
- from .danish_lexicon import words as danish_words
- pieces.append((False, danish_words(piece)))
- else:
- pieces.append((False, espeak_words(piece, voice)))
+ pieces.append((True, piece) if punctuation else (False, espeak_words(piece, voice)))
return tokenize(pieces, profile)
diff --git a/tests/test_danish_frontend.py b/tests/test_danish_frontend.py
index a153355..a85318a 100644
--- a/tests/test_danish_frontend.py
+++ b/tests/test_danish_frontend.py
@@ -28,7 +28,7 @@ class DanishProfileTests(unittest.TestCase):
def test_unique_vocabulary_config_roundtrip_and_profile_identity(self):
self.assertIs(profile_for("da"), DANISH)
self.assertEqual(len(DANISH.symbols), 177)
- self.assertEqual(DANISH.version, 3)
+ self.assertEqual(DANISH.version, 4)
self.assertEqual(len(DANISH.symbols), len(set(DANISH.symbols)))
self.assertEqual(DANISH.normalizer, NORMALIZER_VERSION)
config = Config.for_language("da", ("DA1",))
diff --git a/tests/test_danish_nst.py b/tests/test_danish_nst.py
index 08fd629..ad9212e 100644
--- a/tests/test_danish_nst.py
+++ b/tests/test_danish_nst.py
@@ -90,13 +90,15 @@ class NSTDictionaryTests(unittest.TestCase):
self.assertEqual(lookup("HUND")["match"], "casefold")
def test_fallback_is_explicit_and_dictionary_spans_do_not_use_it(self):
+ # v4: an unknown Danish-looking word goes to the NST G2P; an initialism still goes to eSpeak.
observed = []
- def fallback(value):
- observed.append(value)
+ def fallback(value, voice):
+ observed.append((value, voice))
return [[("k", 0), ("u", 1)]]
- converted, trace = words_with_trace("hun quuxblørgz hund", fallback)
- self.assertEqual(observed, ["quuxblørgz"])
- self.assertEqual([row["source"] for row in trace], ["nst", "espeak-fallback", "nst"])
+ converted, trace = words_with_trace("hun quuxblørgz XYZ hund", fallback, english=False)
+ self.assertEqual(observed, [("XYZ", "da")])
+ self.assertEqual([row["source"] for row in trace], ["nst", "g2p", "espeak-fallback", "nst"])
+ self.assertTrue(all(phone.startswith("nst:") for phone, _ in converted[1]))
self.assertIn(("nst:nˀ", 0), converted[-1])
def test_modified_packaged_resource_is_a_hard_error(self):
diff --git a/tests/test_danish_v4.py b/tests/test_danish_v4.py
new file mode 100644
index 0000000..9bda395
--- /dev/null
+++ b/tests/test_danish_v4.py
@@ -0,0 +1,69 @@
+"""Danish frontend v4: derived enog… numerals, abbreviations, symbol words, English pieces, NST G2P."""
+import unittest
+from unittest import mock
+
+from tiny_voca import danish_g2p
+from tiny_voca.danish_lexicon import explain, lookup, words_with_trace
+from tiny_voca.languages import DANISH
+from tiny_voca.text import normalize_text, phonemize
+
+
+class DanishV4Tests(unittest.TestCase):
+ def test_enog_numerals_are_derived_from_nst_toog(self):
+ record = lookup("enogtres")
+ self.assertEqual(record["match"], "derived")
+ self.assertEqual(record["sampa"], '"e:n$6w$"tRes')
+ self.assertEqual(lookup("Enogtyve")["derived_from"], "toogtyve")
+ self.assertIsNone(lookup("enogquux"))
+ result = explain("Der var 61 gæster.")
+ self.assertEqual(result["derived_words"], 1)
+ self.assertEqual(result["fallback_words"], 0)
+
+ def test_abbreviations_and_symbols_become_words(self):
+ self.assertEqual(normalize_text("Vi så bl.a. en sæl, f.eks. ved Skagen.", DANISH),
+ "Vi så blandt andet en sæl, for eksempel ved Skagen.")
+ self.assertEqual(normalize_text("Hansen & Søn, § 3.", DANISH), "Hansen og Søn, paragraf tre.")
+
+ def test_english_piece_goes_to_the_english_voice_as_a_whole(self):
+ result = explain("I don't know why but it really got to me, man.")
+ self.assertEqual({row["source"] for row in result["sources"]}, {"espeak-en"})
+ self.assertEqual(result["unknown"], [])
+ danish = explain("Det er en god dag i dag.")
+ self.assertEqual(danish["english_words"], 0)
+
+ def test_unknown_danish_word_uses_g2p_with_nst_tokens(self):
+ result = explain("Familieretshuset har åbent.")
+ self.assertGreaterEqual(result["g2p_words"], 1)
+ self.assertEqual(result["fallback_words"], 0)
+ self.assertEqual(result["unknown"], [])
+ self.assertEqual(result["ids"], list(phonemize("Familieretshuset har åbent.", DANISH).ids))
+
+ def test_initialisms_stay_with_espeak(self):
+ observed = []
+ def fallback(value, voice):
+ observed.append((value, voice))
+ return [[("d", 0), ("e", 1)]]
+ _, trace = words_with_trace("AUH", fallback, english=False)
+ self.assertEqual(observed, [("AUH", "da")])
+ self.assertEqual(trace[0]["source"], "espeak-fallback")
+
+ def test_modified_g2p_resource_is_a_hard_error(self):
+ danish_g2p._model.cache_clear()
+ danish_g2p.predict.cache_clear()
+ try:
+ with mock.patch("tiny_voca.danish_g2p._resource", return_value=b"modified"):
+ with self.assertRaisesRegex(RuntimeError, "SHA-256"):
+ danish_g2p.predict("familieretshuset")
+ finally:
+ danish_g2p._model.cache_clear()
+ danish_g2p.predict.cache_clear()
+
+ def test_profile_identity_names_every_v4_rule(self):
+ pronunciation = DANISH.identity()["pronunciation"]
+ for key in ("g2p", "language_detection", "derived", "symbols"):
+ self.assertIn(key, pronunciation)
+ self.assertEqual(DANISH.version, 4)
+
+
+if __name__ == "__main__":
+ unittest.main()