prakob 0.1.0__tar.gz

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.
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ .venv/
5
+ venv/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ .pytest_cache/
10
+ audio_cache/
11
+ .env
12
+ video/
13
+ videos/
prakob-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.5
2
+ Name: prakob
3
+ Version: 0.1.0
4
+ Summary: Rule-based Khmer syllable decomposition, phonetic spelling template engine (ប្រកប), and TTS pipeline.
5
+ Requires-Python: >=3.10
6
+ Provides-Extra: all
7
+ Requires-Dist: azure-cognitiveservices-speech>=1.41.0; extra == 'all'
8
+ Requires-Dist: edge-tts>=7.0.0; extra == 'all'
9
+ Requires-Dist: fastapi>=0.115.0; extra == 'all'
10
+ Requires-Dist: pydantic>=2.9.0; extra == 'all'
11
+ Requires-Dist: scipy>=1.14.0; extra == 'all'
12
+ Requires-Dist: torch>=2.4.0; extra == 'all'
13
+ Requires-Dist: transformers>=4.46.0; extra == 'all'
14
+ Requires-Dist: uvicorn[standard]>=0.32.0; extra == 'all'
15
+ Provides-Extra: azure
16
+ Requires-Dist: azure-cognitiveservices-speech>=1.41.0; extra == 'azure'
17
+ Provides-Extra: dev
18
+ Requires-Dist: httpx2>=2.14.0; extra == 'dev'
19
+ Requires-Dist: pytest>=8.3.0; extra == 'dev'
20
+ Provides-Extra: edge
21
+ Requires-Dist: edge-tts>=7.0.0; extra == 'edge'
22
+ Provides-Extra: mms
23
+ Requires-Dist: scipy>=1.14.0; extra == 'mms'
24
+ Requires-Dist: torch>=2.4.0; extra == 'mms'
25
+ Requires-Dist: transformers>=4.46.0; extra == 'mms'
26
+ Provides-Extra: nlp
27
+ Requires-Dist: khmer-nltk>=1.6; extra == 'nlp'
28
+ Provides-Extra: server
29
+ Requires-Dist: fastapi>=0.115.0; extra == 'server'
30
+ Requires-Dist: pydantic>=2.9.0; extra == 'server'
31
+ Requires-Dist: uvicorn[standard]>=0.32.0; extra == 'server'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # Prakob (ប្រកប)
35
+
36
+ Rule-based Khmer syllable decomposition, phonetic spelling template engine, and pre-trained TTS web prototype.
37
+
38
+ ## Architecture
39
+
40
+ 1. **Presentation Layer (`src/prakob/static/`)**: Clean web UI (**KhmerSpell / ប្រកប**) with color-coded syllable slots, progressive spelling breakdown, Unicode memory inspector (highlighting invisible `U+17D2` Coeng signs), SSML viewer, and audio player.
41
+ 2. **Application Logic Layer (`src/prakob/`)**:
42
+ - `normalizer.py`: Strips zero-width artifacts (`U+200B`/`U+200C`) and reorders mis-typed clusters into canonical Unicode L2/22-290 order (`ខែ្មរ` → `ខ្មែរ`, `េ`+`ា` → `ោ`).
43
+ - `parser.py`: Segments unspaced Khmer text into orthographic syllables using the one-character lookahead rule and extracts 6 linguistic slots (`initial`, `shifter`, `subscript`, `vowel`, `final`, `diacritic`).
44
+ - `engine.py`: Applies Longest-Match-First lookup tables (Priority 1 combined vowels like `ោះ`/`ាំ` before Priority 2 single vowels), injects progressive blends, formats punctuation pauses, and generates Azure-compatible SSML.
45
+ - `api.py`: FastAPI REST API (`POST /api/spell`, `GET /api/examples`, `GET /api/health`, `GET /audio/cache/{filename}`).
46
+ 3. **Speech Synthesis Layer (`src/prakob/tts.py`)**: Pluggable pre-trained Khmer TTS backends (`azure`, `edge`, `mms`, or `none`) with content-hashed caching under `audio_cache/`.
47
+
48
+ ## Quick Start
49
+
50
+ ```bash
51
+ # Install dependencies
52
+ uv sync --extra dev
53
+
54
+ # Run the web prototype
55
+ uv run prakob serve --port 8000
56
+
57
+ # Spell a word from the CLI
58
+ uv run prakob spell "សាលារៀន"
59
+
60
+ # Run the test suite
61
+ uv run pytest
62
+ ```
63
+
64
+ ## Test
65
+
66
+ ```txt
67
+ Input: សាលារៀន
68
+ Normalized: សាលារៀន
69
+ TTS Text: ស ដាក់ស្រៈ អា, សា; ល ដាក់ស្រៈ អា, លា; រ ដាក់ស្រៈ អៀ, រៀ; ប្រកបនឹង ន, រៀន; អានថា សាលារៀន
70
+ ```
71
+
72
+ ## Demo Videos
73
+
74
+ Sample renders of the engine and TTS backends (see [`assets/`](assets/)):
75
+
76
+ ### All 33 Khmer consonants
77
+
78
+ <video src="assets/prakob_khmer_alphabets_all_33_small.mp4" controls preload="metadata"></video>
79
+
80
+ [▶ Play video](assets/prakob_khmer_alphabets_all_33.mp4)
81
+
82
+ ### Optional TTS Backends
83
+
84
+ - **Edge Neural TTS (default fallback):** Included via `edge-tts` (`km-KH-SreymomNeural`, `km-KH-PisethNeural`).
85
+ - **Azure AI Speech (SSML precision):** Install `uv sync --extra azure` and set `AZURE_SPEECH_KEY` and `AZURE_SPEECH_REGION`.
86
+ - **Local Offline VITS (`facebook/mms-tts-khm`):** Install `uv sync --extra mms`.
prakob-0.1.0/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # Prakob (ប្រកប)
2
+
3
+ Rule-based Khmer syllable decomposition, phonetic spelling template engine, and pre-trained TTS web prototype.
4
+
5
+ ## Architecture
6
+
7
+ 1. **Presentation Layer (`src/prakob/static/`)**: Clean web UI (**KhmerSpell / ប្រកប**) with color-coded syllable slots, progressive spelling breakdown, Unicode memory inspector (highlighting invisible `U+17D2` Coeng signs), SSML viewer, and audio player.
8
+ 2. **Application Logic Layer (`src/prakob/`)**:
9
+ - `normalizer.py`: Strips zero-width artifacts (`U+200B`/`U+200C`) and reorders mis-typed clusters into canonical Unicode L2/22-290 order (`ខែ្មរ` → `ខ្មែរ`, `េ`+`ា` → `ោ`).
10
+ - `parser.py`: Segments unspaced Khmer text into orthographic syllables using the one-character lookahead rule and extracts 6 linguistic slots (`initial`, `shifter`, `subscript`, `vowel`, `final`, `diacritic`).
11
+ - `engine.py`: Applies Longest-Match-First lookup tables (Priority 1 combined vowels like `ោះ`/`ាំ` before Priority 2 single vowels), injects progressive blends, formats punctuation pauses, and generates Azure-compatible SSML.
12
+ - `api.py`: FastAPI REST API (`POST /api/spell`, `GET /api/examples`, `GET /api/health`, `GET /audio/cache/{filename}`).
13
+ 3. **Speech Synthesis Layer (`src/prakob/tts.py`)**: Pluggable pre-trained Khmer TTS backends (`azure`, `edge`, `mms`, or `none`) with content-hashed caching under `audio_cache/`.
14
+
15
+ ## Quick Start
16
+
17
+ ```bash
18
+ # Install dependencies
19
+ uv sync --extra dev
20
+
21
+ # Run the web prototype
22
+ uv run prakob serve --port 8000
23
+
24
+ # Spell a word from the CLI
25
+ uv run prakob spell "សាលារៀន"
26
+
27
+ # Run the test suite
28
+ uv run pytest
29
+ ```
30
+
31
+ ## Test
32
+
33
+ ```txt
34
+ Input: សាលារៀន
35
+ Normalized: សាលារៀន
36
+ TTS Text: ស ដាក់ស្រៈ អា, សា; ល ដាក់ស្រៈ អា, លា; រ ដាក់ស្រៈ អៀ, រៀ; ប្រកបនឹង ន, រៀន; អានថា សាលារៀន
37
+ ```
38
+
39
+ ## Demo Videos
40
+
41
+ Sample renders of the engine and TTS backends (see [`assets/`](assets/)):
42
+
43
+ ### All 33 Khmer consonants
44
+
45
+ <video src="assets/prakob_khmer_alphabets_all_33_small.mp4" controls preload="metadata"></video>
46
+
47
+ [▶ Play video](assets/prakob_khmer_alphabets_all_33.mp4)
48
+
49
+ ### Optional TTS Backends
50
+
51
+ - **Edge Neural TTS (default fallback):** Included via `edge-tts` (`km-KH-SreymomNeural`, `km-KH-PisethNeural`).
52
+ - **Azure AI Speech (SSML precision):** Install `uv sync --extra azure` and set `AZURE_SPEECH_KEY` and `AZURE_SPEECH_REGION`.
53
+ - **Local Offline VITS (`facebook/mms-tts-khm`):** Install `uv sync --extra mms`.
Binary file
@@ -0,0 +1,56 @@
1
+ [project]
2
+ name = "prakob"
3
+ version = "0.1.0"
4
+ description = "Rule-based Khmer syllable decomposition, phonetic spelling template engine (ប្រកប), and TTS pipeline."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ dependencies = []
8
+
9
+ [project.optional-dependencies]
10
+ edge = [
11
+ "edge-tts>=7.0.0",
12
+ ]
13
+ azure = [
14
+ "azure-cognitiveservices-speech>=1.41.0",
15
+ ]
16
+ mms = [
17
+ "transformers>=4.46.0",
18
+ "torch>=2.4.0",
19
+ "scipy>=1.14.0",
20
+ ]
21
+ server = [
22
+ "fastapi>=0.115.0",
23
+ "uvicorn[standard]>=0.32.0",
24
+ "pydantic>=2.9.0",
25
+ ]
26
+ nlp = [
27
+ "khmer-nltk>=1.6",
28
+ ]
29
+ all = [
30
+ "edge-tts>=7.0.0",
31
+ "azure-cognitiveservices-speech>=1.41.0",
32
+ "transformers>=4.46.0",
33
+ "torch>=2.4.0",
34
+ "scipy>=1.14.0",
35
+ "fastapi>=0.115.0",
36
+ "uvicorn[standard]>=0.32.0",
37
+ "pydantic>=2.9.0",
38
+ ]
39
+ dev = [
40
+ "httpx2>=2.14.0",
41
+ "pytest>=8.3.0",
42
+ ]
43
+
44
+ [project.scripts]
45
+ prakob = "prakob.cli:main"
46
+
47
+ [build-system]
48
+ requires = ["hatchling"]
49
+ build-backend = "hatchling.build"
50
+
51
+ [tool.hatch.build.targets.wheel]
52
+ packages = ["src/prakob"]
53
+
54
+ [tool.pytest.ini_options]
55
+ testpaths = ["tests"]
56
+ pythonpath = ["src"]
@@ -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
+ ]
@@ -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()
@@ -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())