File size: 26,997 Bytes
adabee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
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()