prakob 0.1.0__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.
- prakob/__init__.py +34 -0
- prakob/api.py +136 -0
- prakob/cli.py +70 -0
- prakob/engine.py +464 -0
- prakob/normalizer.py +109 -0
- prakob/parser.py +264 -0
- prakob/static/app.js +241 -0
- prakob/static/index.html +128 -0
- prakob/static/styles.css +488 -0
- prakob/tables.py +174 -0
- prakob/tts.py +377 -0
- prakob-0.1.0.dist-info/METADATA +86 -0
- prakob-0.1.0.dist-info/RECORD +15 -0
- prakob-0.1.0.dist-info/WHEEL +4 -0
- prakob-0.1.0.dist-info/entry_points.txt +2 -0
prakob/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Prakob (ប្រកប): Rule-based Khmer syllable decomposition & TTS spelling pipeline."""
|
|
2
|
+
|
|
3
|
+
from prakob.engine import (
|
|
4
|
+
SpellingStep,
|
|
5
|
+
SyllableSpelling,
|
|
6
|
+
WordSpelling,
|
|
7
|
+
build_ssml,
|
|
8
|
+
build_syllable_spelling,
|
|
9
|
+
format_tts_letter_names,
|
|
10
|
+
spell_text,
|
|
11
|
+
spell_word,
|
|
12
|
+
)
|
|
13
|
+
from prakob.normalizer import normalize_khmer
|
|
14
|
+
from prakob.tts import TTSBackend, register_backend, get_registered_backends
|
|
15
|
+
|
|
16
|
+
__version__ = "0.1.0"
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"__version__",
|
|
20
|
+
"normalize_khmer",
|
|
21
|
+
"parse_syllables",
|
|
22
|
+
"SyllableSlots",
|
|
23
|
+
"spell_word",
|
|
24
|
+
"spell_text",
|
|
25
|
+
"build_syllable_spelling",
|
|
26
|
+
"SyllableSpelling",
|
|
27
|
+
"WordSpelling",
|
|
28
|
+
"SpellingStep",
|
|
29
|
+
"build_ssml",
|
|
30
|
+
"format_tts_letter_names",
|
|
31
|
+
"TTSBackend",
|
|
32
|
+
"register_backend",
|
|
33
|
+
"get_registered_backends",
|
|
34
|
+
]
|
prakob/api.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Layer 2 Web API: FastAPI service connecting the Khmer spelling engine and TTS."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from fastapi import FastAPI, HTTPException
|
|
10
|
+
from fastapi.responses import FileResponse, HTMLResponse
|
|
11
|
+
from fastapi.staticfiles import StaticFiles
|
|
12
|
+
from pydantic import BaseModel, Field
|
|
13
|
+
|
|
14
|
+
from prakob.engine import spell_text
|
|
15
|
+
from prakob.tables import EXAMPLE_WORDS
|
|
16
|
+
from prakob.tts import (
|
|
17
|
+
DEFAULT_VOICE,
|
|
18
|
+
SUPPORTED_VOICES,
|
|
19
|
+
TTSBackendName,
|
|
20
|
+
get_backend_capabilities,
|
|
21
|
+
synthesize_speech,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
PACKAGE_DIR = Path(__file__).resolve().parent
|
|
25
|
+
STATIC_DIR = PACKAGE_DIR / "static"
|
|
26
|
+
DEFAULT_CACHE_DIR = Path(os.getenv("PRAKOB_CACHE_DIR", "audio_cache")).resolve()
|
|
27
|
+
|
|
28
|
+
_SAFE_AUDIO_FILENAME_RE = re.compile(r"^[a-f0-9]{16}\.(mp3|wav)$")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SpellRequest(BaseModel):
|
|
32
|
+
"""Request body for POST /api/spell."""
|
|
33
|
+
|
|
34
|
+
text: str = Field(..., min_length=1, max_length=500, description="Khmer word or phrase")
|
|
35
|
+
tts_backend: TTSBackendName = Field(
|
|
36
|
+
default="auto",
|
|
37
|
+
description="TTS backend to use: auto, edge, azure, mms, or none",
|
|
38
|
+
)
|
|
39
|
+
voice: str = Field(
|
|
40
|
+
default=DEFAULT_VOICE,
|
|
41
|
+
description="Voice identifier (e.g., km-KH-SreymomNeural)",
|
|
42
|
+
)
|
|
43
|
+
rate: str = Field(
|
|
44
|
+
default="-15%",
|
|
45
|
+
pattern=r"^[+-]?\d{1,2}%$",
|
|
46
|
+
description="Speaking rate adjustment for prosody (e.g., -15%)",
|
|
47
|
+
)
|
|
48
|
+
include_audio: bool = Field(
|
|
49
|
+
default=True,
|
|
50
|
+
description="Whether to synthesize audio via Layer 3 TTS",
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def create_app(cache_dir: Path | None = None) -> FastAPI:
|
|
55
|
+
"""Create and configure the FastAPI application."""
|
|
56
|
+
resolved_cache_dir = (cache_dir or DEFAULT_CACHE_DIR).resolve()
|
|
57
|
+
|
|
58
|
+
app = FastAPI(
|
|
59
|
+
title="Prakob (ប្រកប) • Khmer Spelling Engine API",
|
|
60
|
+
version="0.1.0",
|
|
61
|
+
description="Rule-based Khmer syllable decomposition and TTS spelling template pipeline.",
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
if STATIC_DIR.exists():
|
|
65
|
+
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
|
66
|
+
|
|
67
|
+
@app.get("/", response_class=HTMLResponse)
|
|
68
|
+
async def index() -> FileResponse:
|
|
69
|
+
index_path = STATIC_DIR / "index.html"
|
|
70
|
+
if not index_path.exists():
|
|
71
|
+
raise HTTPException(status_code=404, detail="Frontend UI not found")
|
|
72
|
+
return FileResponse(index_path)
|
|
73
|
+
|
|
74
|
+
@app.get("/api/health")
|
|
75
|
+
async def health() -> dict[str, object]:
|
|
76
|
+
return {
|
|
77
|
+
"status": "ok",
|
|
78
|
+
"backends": get_backend_capabilities(),
|
|
79
|
+
"voices": SUPPORTED_VOICES,
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
@app.get("/api/examples")
|
|
83
|
+
async def examples() -> dict[str, object]:
|
|
84
|
+
return {"examples": EXAMPLE_WORDS}
|
|
85
|
+
|
|
86
|
+
@app.post("/api/spell")
|
|
87
|
+
async def spell(req: SpellRequest) -> dict[str, object]:
|
|
88
|
+
result = spell_text(req.text, voice=req.voice, rate=req.rate)
|
|
89
|
+
if not result["syllables"]:
|
|
90
|
+
raise HTTPException(
|
|
91
|
+
status_code=422,
|
|
92
|
+
detail="No Khmer characters detected. Please enter Khmer Unicode text.",
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
audio_url: str | None = None
|
|
96
|
+
tts_backend_used = "none"
|
|
97
|
+
cached = False
|
|
98
|
+
warning: str | None = None
|
|
99
|
+
|
|
100
|
+
if req.include_audio and req.tts_backend != "none":
|
|
101
|
+
tts_res = await synthesize_speech(
|
|
102
|
+
tts_text=str(result["full_tts_text"]),
|
|
103
|
+
ssml=str(result["ssml"]),
|
|
104
|
+
cache_dir=resolved_cache_dir,
|
|
105
|
+
backend=req.tts_backend,
|
|
106
|
+
voice=req.voice,
|
|
107
|
+
rate=req.rate,
|
|
108
|
+
)
|
|
109
|
+
tts_backend_used = tts_res.backend_used
|
|
110
|
+
cached = tts_res.cached
|
|
111
|
+
warning = tts_res.warning
|
|
112
|
+
if tts_res.audio_filename:
|
|
113
|
+
audio_url = f"/audio/cache/{tts_res.audio_filename}"
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
**result,
|
|
117
|
+
"audio_url": audio_url,
|
|
118
|
+
"tts_backend_used": tts_backend_used,
|
|
119
|
+
"audio_cached": cached,
|
|
120
|
+
"warning": warning,
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
@app.get("/audio/cache/{filename}")
|
|
124
|
+
async def get_cached_audio(filename: str) -> FileResponse:
|
|
125
|
+
if not _SAFE_AUDIO_FILENAME_RE.match(filename):
|
|
126
|
+
raise HTTPException(status_code=400, detail="Invalid audio filename")
|
|
127
|
+
target = (resolved_cache_dir / filename).resolve()
|
|
128
|
+
if target.parent != resolved_cache_dir or not target.exists():
|
|
129
|
+
raise HTTPException(status_code=404, detail="Audio clip not found")
|
|
130
|
+
media_type = "audio/wav" if filename.endswith(".wav") else "audio/mpeg"
|
|
131
|
+
return FileResponse(target, media_type=media_type)
|
|
132
|
+
|
|
133
|
+
return app
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
app = create_app()
|
prakob/cli.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Command-line interface for Prakob (ប្រកប)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from prakob.engine import spell_text
|
|
10
|
+
from prakob.tables import EXAMPLE_WORDS
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _ensure_utf8_stdout() -> None:
|
|
14
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
15
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def main(argv: list[str] | None = None) -> int:
|
|
19
|
+
_ensure_utf8_stdout()
|
|
20
|
+
parser = argparse.ArgumentParser(
|
|
21
|
+
prog="prakob",
|
|
22
|
+
description="Khmer syllable decomposition and TTS spelling template engine (ប្រកប).",
|
|
23
|
+
)
|
|
24
|
+
sub = parser.add_subparsers(dest="command")
|
|
25
|
+
|
|
26
|
+
spell_cmd = sub.add_parser("spell", help="Decompose Khmer text and print template output.")
|
|
27
|
+
spell_cmd.add_argument("text", help="Khmer word or phrase to spell")
|
|
28
|
+
spell_cmd.add_argument("--json", action="store_true", help="Print full structured JSON")
|
|
29
|
+
spell_cmd.add_argument("--ssml", action="store_true", help="Print generated SSML")
|
|
30
|
+
|
|
31
|
+
serve_cmd = sub.add_parser("serve", help="Run the FastAPI web prototype.")
|
|
32
|
+
serve_cmd.add_argument("--host", default="127.0.0.1", help="Bind host (default: 127.0.0.1)")
|
|
33
|
+
serve_cmd.add_argument("--port", type=int, default=8000, help="Bind port (default: 8000)")
|
|
34
|
+
serve_cmd.add_argument("--reload", action="store_true", help="Enable auto-reload")
|
|
35
|
+
|
|
36
|
+
sub.add_parser("examples", help="Run the engine on the built-in benchmark examples.")
|
|
37
|
+
|
|
38
|
+
args = parser.parse_args(argv)
|
|
39
|
+
|
|
40
|
+
if args.command == "serve":
|
|
41
|
+
import uvicorn
|
|
42
|
+
|
|
43
|
+
uvicorn.run("prakob.api:app", host=args.host, port=args.port, reload=args.reload)
|
|
44
|
+
return 0
|
|
45
|
+
|
|
46
|
+
if args.command == "examples":
|
|
47
|
+
for item in EXAMPLE_WORDS:
|
|
48
|
+
res = spell_text(item["word"])
|
|
49
|
+
print(f"[{item['category']}] {item['word']} ({item['meaning']})")
|
|
50
|
+
print(f" -> {res['full_tts_text']}")
|
|
51
|
+
return 0
|
|
52
|
+
|
|
53
|
+
if args.command == "spell":
|
|
54
|
+
res = spell_text(args.text)
|
|
55
|
+
if args.json:
|
|
56
|
+
print(json.dumps(res, ensure_ascii=False, indent=2))
|
|
57
|
+
elif args.ssml:
|
|
58
|
+
print(res["ssml"])
|
|
59
|
+
else:
|
|
60
|
+
print(f"Input: {res['input']}")
|
|
61
|
+
print(f"Normalized: {res['normalized']}")
|
|
62
|
+
print(f"TTS Text: {res['full_tts_text']}")
|
|
63
|
+
return 0
|
|
64
|
+
|
|
65
|
+
parser.print_help()
|
|
66
|
+
return 0
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
if __name__ == "__main__":
|
|
70
|
+
raise SystemExit(main())
|
prakob/engine.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
"""Steps 3 & 4: Lookup mapping, progressive template assembly, and SSML formatting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
|
|
9
|
+
from prakob.normalizer import normalize_khmer
|
|
10
|
+
from prakob.parser import SyllableSlots, parse_syllables
|
|
11
|
+
from prakob.tables import (
|
|
12
|
+
COENG,
|
|
13
|
+
COMBINED_VOWELS,
|
|
14
|
+
CONSONANT_TTS_NAMES,
|
|
15
|
+
DIACRITIC_MAP,
|
|
16
|
+
INDEPENDENT_VOWEL_TTS_NAMES,
|
|
17
|
+
SAMYOK_SANNYA,
|
|
18
|
+
SHIFTER_MAP,
|
|
19
|
+
SINGLE_VOWELS,
|
|
20
|
+
VOWEL_TTS_NAMES,
|
|
21
|
+
is_base_consonant,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# Split mixed input into Khmer word tokens and non-Khmer separators
|
|
25
|
+
_KHMER_WORD_RE = re.compile(r"[\u1780-\u17DD]+")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(slots=True)
|
|
29
|
+
class SpellingStep:
|
|
30
|
+
"""One progressive spoken/visual step inside a syllable."""
|
|
31
|
+
|
|
32
|
+
stage: str # e.g., "cluster", "shifter", "vowel", "final", "diacritic", "inherent"
|
|
33
|
+
spoken_phrase: str
|
|
34
|
+
partial_result: str
|
|
35
|
+
template_fragment: str
|
|
36
|
+
|
|
37
|
+
def to_dict(self) -> dict[str, str]:
|
|
38
|
+
return {
|
|
39
|
+
"stage": self.stage,
|
|
40
|
+
"spoken_phrase": self.spoken_phrase,
|
|
41
|
+
"partial_result": self.partial_result,
|
|
42
|
+
"template_fragment": self.template_fragment,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(slots=True)
|
|
47
|
+
class SyllableSpelling:
|
|
48
|
+
"""Complete decomposition + spelling template for one syllable."""
|
|
49
|
+
|
|
50
|
+
slots: SyllableSlots
|
|
51
|
+
pattern_id: str
|
|
52
|
+
vowel_spoken_name: str | None
|
|
53
|
+
steps: list[SpellingStep] = field(default_factory=list)
|
|
54
|
+
template_segment: str = ""
|
|
55
|
+
|
|
56
|
+
def to_dict(self) -> dict[str, object]:
|
|
57
|
+
return {
|
|
58
|
+
"raw": self.slots.raw,
|
|
59
|
+
"initial": self.slots.initial,
|
|
60
|
+
"shifter": self.slots.shifter,
|
|
61
|
+
"subscript": self.slots.subscript,
|
|
62
|
+
"extra_subscripts": self.slots.extra_subscripts,
|
|
63
|
+
"vowel": self.slots.vowel,
|
|
64
|
+
"vowel_name": self.vowel_spoken_name,
|
|
65
|
+
"final": self.slots.final,
|
|
66
|
+
"final_subscript": self.slots.final_subscript,
|
|
67
|
+
"diacritic": self.slots.diacritic,
|
|
68
|
+
"is_independent_vowel": self.slots.is_independent_vowel,
|
|
69
|
+
"pattern_id": self.pattern_id,
|
|
70
|
+
"steps": [s.to_dict() for s in self.steps],
|
|
71
|
+
"template_segment": self.template_segment,
|
|
72
|
+
"codepoints": [cp.to_dict() for cp in self.slots.codepoints],
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(slots=True)
|
|
77
|
+
class WordSpelling:
|
|
78
|
+
"""Complete spelling result for one Khmer word."""
|
|
79
|
+
|
|
80
|
+
word: str
|
|
81
|
+
syllables: list[SyllableSpelling]
|
|
82
|
+
full_tts_text: str
|
|
83
|
+
|
|
84
|
+
def to_dict(self) -> dict[str, object]:
|
|
85
|
+
return {
|
|
86
|
+
"word": self.word,
|
|
87
|
+
"syllables": [s.to_dict() for s in self.syllables],
|
|
88
|
+
"full_tts_text": self.full_tts_text,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def lookup_vowel(vowel: str | None) -> tuple[str, str] | None:
|
|
93
|
+
"""Priority-based vowel lookup (Priority 1 combined vowels before Priority 2 single)."""
|
|
94
|
+
if not vowel:
|
|
95
|
+
return None
|
|
96
|
+
if vowel in COMBINED_VOWELS:
|
|
97
|
+
return COMBINED_VOWELS[vowel]
|
|
98
|
+
if vowel in SINGLE_VOWELS:
|
|
99
|
+
return SINGLE_VOWELS[vowel]
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _classify_pattern(slots: SyllableSlots, is_multi_syllable: bool) -> str:
|
|
104
|
+
"""Assign Chapter 3 pattern ID (P1..P5) for reporting/inspection."""
|
|
105
|
+
if is_multi_syllable:
|
|
106
|
+
return "P5"
|
|
107
|
+
if slots.subscript and slots.vowel and slots.final:
|
|
108
|
+
return "P2+P3"
|
|
109
|
+
if slots.subscript and slots.vowel:
|
|
110
|
+
return "P2"
|
|
111
|
+
if slots.vowel and slots.final:
|
|
112
|
+
return "P3"
|
|
113
|
+
if not slots.vowel and slots.final:
|
|
114
|
+
return "P4"
|
|
115
|
+
if slots.vowel:
|
|
116
|
+
return "P1"
|
|
117
|
+
return "P0"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def build_syllable_spelling(
|
|
121
|
+
slots: SyllableSlots, *, is_multi_syllable: bool = False
|
|
122
|
+
) -> SyllableSpelling:
|
|
123
|
+
"""Step 3 & 4: Map slots via lookup tables and assemble progressive template segments."""
|
|
124
|
+
if slots.is_independent_vowel:
|
|
125
|
+
steps: list[SpellingStep] = []
|
|
126
|
+
current = slots.initial
|
|
127
|
+
if slots.final:
|
|
128
|
+
partial = current + slots.final
|
|
129
|
+
frag = f"{current} ប្រកបនឹង {slots.final}, {partial}"
|
|
130
|
+
steps.append(
|
|
131
|
+
SpellingStep(
|
|
132
|
+
stage="final",
|
|
133
|
+
spoken_phrase=f"ប្រកបនឹង {slots.final}",
|
|
134
|
+
partial_result=partial,
|
|
135
|
+
template_fragment=frag,
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
current = partial
|
|
139
|
+
else:
|
|
140
|
+
steps.append(
|
|
141
|
+
SpellingStep(
|
|
142
|
+
stage="independent_vowel",
|
|
143
|
+
spoken_phrase=f"ស្រៈ {slots.initial}",
|
|
144
|
+
partial_result=current,
|
|
145
|
+
template_fragment=current,
|
|
146
|
+
)
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
if slots.diacritic and slots.diacritic in DIACRITIC_MAP:
|
|
150
|
+
_, phrase = DIACRITIC_MAP[slots.diacritic]
|
|
151
|
+
current = current + slots.diacritic
|
|
152
|
+
frag = f"{phrase}, {current}"
|
|
153
|
+
steps.append(
|
|
154
|
+
SpellingStep(
|
|
155
|
+
stage="diacritic",
|
|
156
|
+
spoken_phrase=phrase,
|
|
157
|
+
partial_result=current,
|
|
158
|
+
template_fragment=frag,
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
return SyllableSpelling(
|
|
163
|
+
slots=slots,
|
|
164
|
+
pattern_id="P0-IND",
|
|
165
|
+
vowel_spoken_name=None,
|
|
166
|
+
steps=steps,
|
|
167
|
+
template_segment="; ".join(s.template_fragment for s in steps),
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
steps = []
|
|
171
|
+
fragments: list[str] = []
|
|
172
|
+
current = slots.initial
|
|
173
|
+
has_head_prefix = False
|
|
174
|
+
|
|
175
|
+
# 1. Subscripts (Coeng + Subscript -> "ជើង <C>")
|
|
176
|
+
if slots.subscript:
|
|
177
|
+
all_subs = [slots.subscript, *slots.extra_subscripts]
|
|
178
|
+
sub_phrases = " ".join(f"ជើង {sub}" for sub in all_subs)
|
|
179
|
+
cluster_text = slots.initial + "".join(f"{COENG}{sub}" for sub in all_subs)
|
|
180
|
+
frag = f"{slots.initial} {sub_phrases}, {cluster_text}"
|
|
181
|
+
steps.append(
|
|
182
|
+
SpellingStep(
|
|
183
|
+
stage="cluster",
|
|
184
|
+
spoken_phrase=sub_phrases,
|
|
185
|
+
partial_result=cluster_text,
|
|
186
|
+
template_fragment=frag,
|
|
187
|
+
)
|
|
188
|
+
)
|
|
189
|
+
fragments.append(frag)
|
|
190
|
+
current = cluster_text
|
|
191
|
+
has_head_prefix = True
|
|
192
|
+
|
|
193
|
+
# 2. Register shifter (៉ / ៊)
|
|
194
|
+
if slots.shifter and slots.shifter in SHIFTER_MAP:
|
|
195
|
+
_, shifter_phrase = SHIFTER_MAP[slots.shifter]
|
|
196
|
+
next_text = current + slots.shifter
|
|
197
|
+
if has_head_prefix:
|
|
198
|
+
frag = f"{shifter_phrase}, {next_text}"
|
|
199
|
+
else:
|
|
200
|
+
frag = f"{current} {shifter_phrase}, {next_text}"
|
|
201
|
+
steps.append(
|
|
202
|
+
SpellingStep(
|
|
203
|
+
stage="shifter",
|
|
204
|
+
spoken_phrase=shifter_phrase,
|
|
205
|
+
partial_result=next_text,
|
|
206
|
+
template_fragment=frag,
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
fragments.append(frag)
|
|
210
|
+
current = next_text
|
|
211
|
+
has_head_prefix = True
|
|
212
|
+
|
|
213
|
+
# 3. Vowel (Priority 1 combined vowel -> Priority 2 single vowel)
|
|
214
|
+
vowel_info = lookup_vowel(slots.vowel)
|
|
215
|
+
vowel_spoken_name = vowel_info[0] if vowel_info else None
|
|
216
|
+
if vowel_info and slots.vowel:
|
|
217
|
+
_, vowel_phrase = vowel_info
|
|
218
|
+
next_text = current + slots.vowel
|
|
219
|
+
if has_head_prefix:
|
|
220
|
+
frag = f"{vowel_phrase}, {next_text}"
|
|
221
|
+
else:
|
|
222
|
+
frag = f"{current} {vowel_phrase}, {next_text}"
|
|
223
|
+
steps.append(
|
|
224
|
+
SpellingStep(
|
|
225
|
+
stage="vowel",
|
|
226
|
+
spoken_phrase=vowel_phrase,
|
|
227
|
+
partial_result=next_text,
|
|
228
|
+
template_fragment=frag,
|
|
229
|
+
)
|
|
230
|
+
)
|
|
231
|
+
fragments.append(frag)
|
|
232
|
+
current = next_text
|
|
233
|
+
has_head_prefix = True
|
|
234
|
+
|
|
235
|
+
# Pre-final Samyok Sannya (័) as in ស័ក
|
|
236
|
+
has_pre_samyok = slots.diacritic == SAMYOK_SANNYA and slots.final is not None
|
|
237
|
+
if has_pre_samyok and slots.diacritic in DIACRITIC_MAP:
|
|
238
|
+
_, dia_phrase = DIACRITIC_MAP[slots.diacritic]
|
|
239
|
+
next_text = current + slots.diacritic
|
|
240
|
+
frag = f"{dia_phrase}, {next_text}" if has_head_prefix else f"{current} {dia_phrase}, {next_text}"
|
|
241
|
+
steps.append(
|
|
242
|
+
SpellingStep(
|
|
243
|
+
stage="diacritic",
|
|
244
|
+
spoken_phrase=dia_phrase,
|
|
245
|
+
partial_result=next_text,
|
|
246
|
+
template_fragment=frag,
|
|
247
|
+
)
|
|
248
|
+
)
|
|
249
|
+
fragments.append(frag)
|
|
250
|
+
current = next_text
|
|
251
|
+
has_head_prefix = True
|
|
252
|
+
|
|
253
|
+
# 4. Final consonant (ប្រកបនឹង <Final>)
|
|
254
|
+
if slots.final:
|
|
255
|
+
final_part = slots.final + (
|
|
256
|
+
f"{COENG}{slots.final_subscript}" if slots.final_subscript else ""
|
|
257
|
+
)
|
|
258
|
+
next_text = current + final_part
|
|
259
|
+
if slots.final_subscript:
|
|
260
|
+
spoken = f"ប្រកបនឹង {slots.final} ជើង {slots.final_subscript}"
|
|
261
|
+
else:
|
|
262
|
+
spoken = f"ប្រកបនឹង {slots.final}"
|
|
263
|
+
if has_head_prefix:
|
|
264
|
+
frag = f"{spoken}, {next_text}"
|
|
265
|
+
else:
|
|
266
|
+
frag = f"{current} {spoken}, {next_text}"
|
|
267
|
+
steps.append(
|
|
268
|
+
SpellingStep(
|
|
269
|
+
stage="final",
|
|
270
|
+
spoken_phrase=spoken,
|
|
271
|
+
partial_result=next_text,
|
|
272
|
+
template_fragment=frag,
|
|
273
|
+
)
|
|
274
|
+
)
|
|
275
|
+
fragments.append(frag)
|
|
276
|
+
current = next_text
|
|
277
|
+
has_head_prefix = True
|
|
278
|
+
|
|
279
|
+
# 5. Trailing diacritic (e.g. Bantoc ់ in កាត់)
|
|
280
|
+
if slots.diacritic and not has_pre_samyok and slots.diacritic in DIACRITIC_MAP:
|
|
281
|
+
_, dia_phrase = DIACRITIC_MAP[slots.diacritic]
|
|
282
|
+
next_text = current + slots.diacritic
|
|
283
|
+
frag = f"{dia_phrase}, {next_text}" if has_head_prefix else f"{current} {dia_phrase}, {next_text}"
|
|
284
|
+
steps.append(
|
|
285
|
+
SpellingStep(
|
|
286
|
+
stage="diacritic",
|
|
287
|
+
spoken_phrase=dia_phrase,
|
|
288
|
+
partial_result=next_text,
|
|
289
|
+
template_fragment=frag,
|
|
290
|
+
)
|
|
291
|
+
)
|
|
292
|
+
fragments.append(frag)
|
|
293
|
+
current = next_text
|
|
294
|
+
|
|
295
|
+
# 6. Bare consonant with inherent vowel (e.g. រ in រទេះ)
|
|
296
|
+
if not steps:
|
|
297
|
+
steps.append(
|
|
298
|
+
SpellingStep(
|
|
299
|
+
stage="inherent",
|
|
300
|
+
spoken_phrase=slots.initial,
|
|
301
|
+
partial_result=slots.initial,
|
|
302
|
+
template_fragment=slots.initial,
|
|
303
|
+
)
|
|
304
|
+
)
|
|
305
|
+
fragments.append(slots.initial)
|
|
306
|
+
|
|
307
|
+
return SyllableSpelling(
|
|
308
|
+
slots=slots,
|
|
309
|
+
pattern_id=_classify_pattern(slots, is_multi_syllable),
|
|
310
|
+
vowel_spoken_name=vowel_spoken_name,
|
|
311
|
+
steps=steps,
|
|
312
|
+
template_segment="; ".join(fragments),
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def spell_word(raw_word: str) -> WordSpelling:
|
|
317
|
+
"""Run the 4-step decomposition and template pipeline on a single Khmer word."""
|
|
318
|
+
normalized = normalize_khmer(raw_word.strip())
|
|
319
|
+
parsed_slots = parse_syllables(normalized)
|
|
320
|
+
is_multi = len(parsed_slots) > 1
|
|
321
|
+
syllables = [
|
|
322
|
+
build_syllable_spelling(slot, is_multi_syllable=is_multi)
|
|
323
|
+
for slot in parsed_slots
|
|
324
|
+
]
|
|
325
|
+
|
|
326
|
+
if not syllables:
|
|
327
|
+
return WordSpelling(word=normalized, syllables=[], full_tts_text="")
|
|
328
|
+
|
|
329
|
+
parts = [s.template_segment for s in syllables]
|
|
330
|
+
if is_multi:
|
|
331
|
+
parts.append(f"អានថា {normalized}")
|
|
332
|
+
full_tts_text = "; ".join(parts)
|
|
333
|
+
|
|
334
|
+
return WordSpelling(
|
|
335
|
+
word=normalized,
|
|
336
|
+
syllables=syllables,
|
|
337
|
+
full_tts_text=full_tts_text,
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _tts_token(token: str) -> str:
|
|
342
|
+
"""Map an individual letter or vowel name token to its spoken TTS form."""
|
|
343
|
+
if token in CONSONANT_TTS_NAMES:
|
|
344
|
+
return CONSONANT_TTS_NAMES[token]
|
|
345
|
+
if token in INDEPENDENT_VOWEL_TTS_NAMES:
|
|
346
|
+
return INDEPENDENT_VOWEL_TTS_NAMES[token]
|
|
347
|
+
if token in VOWEL_TTS_NAMES:
|
|
348
|
+
return VOWEL_TTS_NAMES[token]
|
|
349
|
+
return token
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _tts_partial_blend(blend: str) -> str:
|
|
353
|
+
"""Ensure bare consonant+subscript partials (e.g. ផ្ទ, ក្ត) are spoken as open syllables."""
|
|
354
|
+
if (
|
|
355
|
+
COENG in blend
|
|
356
|
+
and not blend.endswith(f"{COENG}រ")
|
|
357
|
+
and all(ch == COENG or is_base_consonant(ch) for ch in blend)
|
|
358
|
+
):
|
|
359
|
+
return f"{blend}រ"
|
|
360
|
+
return blend
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def format_tts_letter_names(tts_text: str) -> str:
|
|
364
|
+
"""Rewrite individual letter tokens in a spelling script to their spoken letter names.
|
|
365
|
+
|
|
366
|
+
Keeps the displayed spelling template clean while ensuring TTS voices read
|
|
367
|
+
canonical letter names (e.g., ក -> ករ /kɑː/) instead of reduced consonant sounds
|
|
368
|
+
or swallowed final consonants, without altering whole-word `អានថា` targets.
|
|
369
|
+
"""
|
|
370
|
+
if not tts_text.strip():
|
|
371
|
+
return ""
|
|
372
|
+
|
|
373
|
+
stages = [part.strip() for part in tts_text.split(";") if part.strip()]
|
|
374
|
+
rewritten: list[str] = []
|
|
375
|
+
|
|
376
|
+
for stage in stages:
|
|
377
|
+
if stage.startswith("អានថា "):
|
|
378
|
+
rewritten.append(stage)
|
|
379
|
+
continue
|
|
380
|
+
|
|
381
|
+
if "," in stage:
|
|
382
|
+
prefix, blend = stage.split(",", 1)
|
|
383
|
+
prefix_tokens = [_tts_token(tok) for tok in prefix.strip().split()]
|
|
384
|
+
blend_fmt = _tts_partial_blend(blend.strip())
|
|
385
|
+
rewritten.append(f"{' '.join(prefix_tokens)}, {blend_fmt}")
|
|
386
|
+
else:
|
|
387
|
+
tokens = [_tts_token(tok) for tok in stage.split()]
|
|
388
|
+
rewritten.append(" ".join(tokens))
|
|
389
|
+
|
|
390
|
+
return "; ".join(rewritten)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def build_ssml(
|
|
394
|
+
tts_text: str,
|
|
395
|
+
*,
|
|
396
|
+
voice: str = "km-KH-SreymomNeural",
|
|
397
|
+
rate: str = "-15%",
|
|
398
|
+
) -> str:
|
|
399
|
+
"""Wrap readable spelling template text in Azure-compatible SSML (Section 3.4.3)."""
|
|
400
|
+
if not tts_text.strip():
|
|
401
|
+
return ""
|
|
402
|
+
|
|
403
|
+
spoken_text = format_tts_letter_names(tts_text)
|
|
404
|
+
stages = [part.strip() for part in spoken_text.split(";") if part.strip()]
|
|
405
|
+
lines: list[str] = [
|
|
406
|
+
'<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="km-KH">',
|
|
407
|
+
f' <voice name="{html.escape(voice, quote=True)}">',
|
|
408
|
+
f' <prosody rate="{html.escape(rate, quote=True)}">',
|
|
409
|
+
]
|
|
410
|
+
|
|
411
|
+
for idx, stage in enumerate(stages):
|
|
412
|
+
is_read_as = stage.startswith("អានថា ")
|
|
413
|
+
if "," in stage:
|
|
414
|
+
prefix, blend = stage.split(",", 1)
|
|
415
|
+
prefix_escaped = html.escape(prefix.strip())
|
|
416
|
+
blend_escaped = html.escape(blend.strip())
|
|
417
|
+
# Insert a 200ms break after the opening consonant before the connector
|
|
418
|
+
tokens = prefix_escaped.split(" ", 1)
|
|
419
|
+
if len(tokens) == 2:
|
|
420
|
+
spoken_line = (
|
|
421
|
+
f' {tokens[0]} <break time="200ms"/> {tokens[1]} '
|
|
422
|
+
f'<break time="250ms"/> {blend_escaped}'
|
|
423
|
+
)
|
|
424
|
+
else:
|
|
425
|
+
spoken_line = f' {prefix_escaped} <break time="250ms"/> {blend_escaped}'
|
|
426
|
+
elif is_read_as:
|
|
427
|
+
_, target = stage.split(" ", 1)
|
|
428
|
+
spoken_line = f' អានថា <break time="200ms"/> {html.escape(target.strip())}'
|
|
429
|
+
else:
|
|
430
|
+
spoken_line = f" {html.escape(stage)}"
|
|
431
|
+
|
|
432
|
+
lines.append(spoken_line)
|
|
433
|
+
if idx < len(stages) - 1:
|
|
434
|
+
next_is_read_as = stages[idx + 1].startswith("អានថា ")
|
|
435
|
+
pause_ms = "450ms" if next_is_read_as else "400ms"
|
|
436
|
+
lines.append(f' <break time="{pause_ms}"/>')
|
|
437
|
+
|
|
438
|
+
lines.extend([" </prosody>", " </voice>", "</speak>"])
|
|
439
|
+
return "\n".join(lines)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def spell_text(
|
|
443
|
+
text: str,
|
|
444
|
+
*,
|
|
445
|
+
voice: str = "km-KH-SreymomNeural",
|
|
446
|
+
rate: str = "-15%",
|
|
447
|
+
) -> dict[str, object]:
|
|
448
|
+
"""Run the full preprocessing pipeline on arbitrary Khmer input (one or more words)."""
|
|
449
|
+
normalized = normalize_khmer(text.strip())
|
|
450
|
+
khmer_tokens = _KHMER_WORD_RE.findall(normalized)
|
|
451
|
+
|
|
452
|
+
words: list[WordSpelling] = [spell_word(tok) for tok in khmer_tokens]
|
|
453
|
+
all_syllables = [syl.to_dict() for w in words for syl in w.syllables]
|
|
454
|
+
full_tts_text = "; ".join(w.full_tts_text for w in words if w.full_tts_text)
|
|
455
|
+
ssml = build_ssml(full_tts_text, voice=voice, rate=rate) if full_tts_text else ""
|
|
456
|
+
|
|
457
|
+
return {
|
|
458
|
+
"input": text,
|
|
459
|
+
"normalized": normalized,
|
|
460
|
+
"words": [w.to_dict() for w in words],
|
|
461
|
+
"syllables": all_syllables,
|
|
462
|
+
"full_tts_text": full_tts_text,
|
|
463
|
+
"ssml": ssml,
|
|
464
|
+
}
|