to-hakka 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.
to_hakka-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 HakkaCL Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: to-hakka
3
+ Version: 0.1.0
4
+ Summary: Standardized Chinese-to-Hakka romanization (Standard Huiyang Hakka, HPS-Ext & IPA) with word-level disambiguation.
5
+ Author: HakkaCL Contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/HakkaCL/to-hakka
8
+ Project-URL: Repository, https://github.com/HakkaCL/to-hakka
9
+ Project-URL: Issues, https://github.com/HakkaCL/to-hakka/issues
10
+ Keywords: hakka,huiyang,pinyin,g2p,romanization,ipa,chinese,nlp
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Text Processing :: Linguistic
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=8.0; extra == "dev"
26
+ Requires-Dist: ruff>=0.4; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # to-hakka (Python)
30
+
31
+ 標準惠陽腔客家話漢字轉拼音工具庫([`HakkaCL/to-hakka`](https://github.com/HakkaCL/to-hakka) Monorepo 之 Python 套件,零第三方執行期依賴)。
32
+
33
+ - **標準腔調**:標準惠陽腔(六調 `44/11/31/53/1/5`、泥來分立 `n`/`l`、保留 `ien/ied`、遇三 `u`、流攝 `eu`、濁去歸去聲 `5`)
34
+ - **記音方案**:客家語拼音擴展方案(HPS-Ext)與國際音標(IPA 調類/五度調值/趙元任調號)
35
+ - **功能**:簡繁無縫輸入、詞級正向最大匹配多音字消歧、候選異讀查詢、`customize()` 自訂詞典覆寫與命令行工具 `to-hakka`。
@@ -0,0 +1,7 @@
1
+ # to-hakka (Python)
2
+
3
+ 標準惠陽腔客家話漢字轉拼音工具庫([`HakkaCL/to-hakka`](https://github.com/HakkaCL/to-hakka) Monorepo 之 Python 套件,零第三方執行期依賴)。
4
+
5
+ - **標準腔調**:標準惠陽腔(六調 `44/11/31/53/1/5`、泥來分立 `n`/`l`、保留 `ien/ied`、遇三 `u`、流攝 `eu`、濁去歸去聲 `5`)
6
+ - **記音方案**:客家語拼音擴展方案(HPS-Ext)與國際音標(IPA 調類/五度調值/趙元任調號)
7
+ - **功能**:簡繁無縫輸入、詞級正向最大匹配多音字消歧、候選異讀查詢、`customize()` 自訂詞典覆寫與命令行工具 `to-hakka`。
@@ -0,0 +1,67 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "to-hakka"
7
+ version = "0.1.0"
8
+ description = "Standardized Chinese-to-Hakka romanization (Standard Huiyang Hakka, HPS-Ext & IPA) with word-level disambiguation."
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ {name = "HakkaCL Contributors"},
14
+ ]
15
+ keywords = [
16
+ "hakka",
17
+ "huiyang",
18
+ "pinyin",
19
+ "g2p",
20
+ "romanization",
21
+ "ipa",
22
+ "chinese",
23
+ "nlp",
24
+ ]
25
+ classifiers = [
26
+ "Development Status :: 4 - Beta",
27
+ "Intended Audience :: Developers",
28
+ "License :: OSI Approved :: MIT License",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Programming Language :: Python :: 3.13",
34
+ "Topic :: Text Processing :: Linguistic",
35
+ "Typing :: Typed",
36
+ ]
37
+ dependencies = []
38
+
39
+ [project.optional-dependencies]
40
+ dev = [
41
+ "pytest>=8.0",
42
+ "ruff>=0.4",
43
+ ]
44
+
45
+ [project.scripts]
46
+ to-hakka = "to_hakka.cli:main"
47
+
48
+ [project.urls]
49
+ Homepage = "https://github.com/HakkaCL/to-hakka"
50
+ Repository = "https://github.com/HakkaCL/to-hakka"
51
+ Issues = "https://github.com/HakkaCL/to-hakka/issues"
52
+
53
+ [tool.setuptools.packages.find]
54
+ where = ["src"]
55
+
56
+ [tool.setuptools.package-data]
57
+ to_hakka = ["py.typed", "data/huiyang_chars.tsv", "data/huiyang_words.tsv", "data/simp_trad.tsv"]
58
+
59
+ [tool.pytest.ini_options]
60
+ testpaths = ["tests"]
61
+
62
+ [tool.ruff]
63
+ line-length = 100
64
+ target-version = "py310"
65
+
66
+ [tool.ruff.lint]
67
+ select = ["E4", "E7", "E9", "F", "I", "UP", "B", "PIE"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,33 @@
1
+ """to-hakka — Standardized Chinese-to-Hakka romanization (Standard Huiyang Hakka, HPS-Ext)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from to_hakka.converter import (
6
+ ToHakka,
7
+ customize,
8
+ get_hakka,
9
+ get_hakka_candidates,
10
+ get_hakka_list,
11
+ get_hakka_text,
12
+ get_ipa,
13
+ get_ipa_list,
14
+ get_ipa_text,
15
+ )
16
+ from to_hakka.ipa import HUIYANG_TONE_VALUES, hps_to_ipa
17
+
18
+ __version__ = "0.1.0"
19
+
20
+ __all__ = [
21
+ "HUIYANG_TONE_VALUES",
22
+ "ToHakka",
23
+ "__version__",
24
+ "customize",
25
+ "get_hakka",
26
+ "get_hakka_candidates",
27
+ "get_hakka_list",
28
+ "get_hakka_text",
29
+ "get_ipa",
30
+ "get_ipa_list",
31
+ "get_ipa_text",
32
+ "hps_to_ipa",
33
+ ]
@@ -0,0 +1,63 @@
1
+ """Command-line interface for `to-hakka`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from collections.abc import Sequence
8
+
9
+ import to_hakka
10
+
11
+
12
+ def build_parser() -> argparse.ArgumentParser:
13
+ parser = argparse.ArgumentParser(
14
+ prog="to-hakka",
15
+ description="Convert Chinese text to Standard Huiyang Hakka (HPS-Ext / IPA).",
16
+ )
17
+ parser.add_argument("--version", action="version", version=f"to-hakka {to_hakka.__version__}")
18
+ parser.add_argument("text", help="Input Chinese text (Traditional or Simplified)")
19
+ parser.add_argument("--inline", action="store_true", help="Annotate characters inline")
20
+ parser.add_argument(
21
+ "--format",
22
+ choices=("hps", "ipa", "ipa-value", "ipa-chao"),
23
+ default="hps",
24
+ help="Output phonetic format (default: hps)",
25
+ )
26
+ parser.add_argument("--json", action="store_true", help="Output JSON token list")
27
+ return parser
28
+
29
+
30
+ def main(argv: Sequence[str] | None = None) -> int:
31
+ parser = build_parser()
32
+ args = parser.parse_args(argv)
33
+
34
+ if args.json:
35
+ if args.format == "hps":
36
+ pairs = to_hakka.get_hakka_list(args.text)
37
+ else:
38
+ style = {"ipa": "class", "ipa-value": "value", "ipa-chao": "chao"}[args.format]
39
+ pairs = to_hakka.get_ipa_list(args.text, tone_style=style)
40
+ print(
41
+ json.dumps(
42
+ [{"char": ch, "pron": pr} for ch, pr in pairs],
43
+ ensure_ascii=False,
44
+ indent=2,
45
+ )
46
+ )
47
+ return 0
48
+
49
+ if args.format == "hps":
50
+ out = to_hakka.get_hakka_text(args.text) if args.inline else to_hakka.get_hakka(args.text)
51
+ else:
52
+ style = {"ipa": "class", "ipa-value": "value", "ipa-chao": "chao"}[args.format]
53
+ out = (
54
+ to_hakka.get_ipa_text(args.text, tone_style=style)
55
+ if args.inline
56
+ else to_hakka.get_ipa(args.text, tone_style=style)
57
+ )
58
+ print(out)
59
+ return 0
60
+
61
+
62
+ if __name__ == "__main__":
63
+ raise SystemExit(main())
@@ -0,0 +1,241 @@
1
+ """Core Standard Huiyang Hakka G2P engine (FMM word segmentation + simp/trad bridge)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from functools import lru_cache
7
+ from pathlib import Path
8
+
9
+ from to_hakka.ipa import hps_to_ipa
10
+
11
+ _DATA_DIR = Path(__file__).resolve().parent / "data"
12
+
13
+
14
+ def _load_tsv_multi(path: Path) -> dict[str, tuple[str, ...]]:
15
+ out: dict[str, tuple[str, ...]] = {}
16
+ for line in path.read_text(encoding="utf-8").splitlines():
17
+ if not line or "\t" not in line:
18
+ continue
19
+ key, vals = line.split("\t", 1)
20
+ out[key] = tuple(v for v in vals.split("|") if v)
21
+ return out
22
+
23
+
24
+ def _load_simp_trad(path: Path) -> dict[str, str]:
25
+ out: dict[str, str] = {}
26
+ for line in path.read_text(encoding="utf-8").splitlines():
27
+ if not line or "\t" not in line:
28
+ continue
29
+ s, t = line.split("\t", 1)
30
+ out[s] = t
31
+ return out
32
+
33
+
34
+ @lru_cache(maxsize=1)
35
+ def _load_default_tables() -> tuple[
36
+ dict[str, tuple[str, ...]],
37
+ dict[str, tuple[str, ...]],
38
+ dict[str, str],
39
+ ]:
40
+ chars = _load_tsv_multi(_DATA_DIR / "huiyang_chars.tsv")
41
+ words = _load_tsv_multi(_DATA_DIR / "huiyang_words.tsv")
42
+ simp_trad = _load_simp_trad(_DATA_DIR / "simp_trad.tsv")
43
+ return chars, words, simp_trad
44
+
45
+
46
+ class ToHakka:
47
+ """Standard Huiyang Hakka text-to-Hakka romanization converter."""
48
+
49
+ def __init__(
50
+ self,
51
+ chars: Mapping[str, tuple[str, ...]] | None = None,
52
+ words: Mapping[str, tuple[str, ...]] | None = None,
53
+ simp_trad: Mapping[str, str] | None = None,
54
+ ) -> None:
55
+ if chars is None or words is None or simp_trad is None:
56
+ d_chars, d_words, d_st = _load_default_tables()
57
+ self._chars: dict[str, tuple[str, ...]] = dict(d_chars if chars is None else chars)
58
+ self._words: dict[str, tuple[str, ...]] = dict(d_words if words is None else words)
59
+ self._simp_trad: dict[str, str] = dict(d_st if simp_trad is None else simp_trad)
60
+ else:
61
+ self._chars = dict(chars)
62
+ self._words = dict(words)
63
+ self._simp_trad = dict(simp_trad)
64
+
65
+ self._max_word_len = max((len(w) for w in self._words), default=1)
66
+
67
+ def customize(self, entries: Mapping[str, str | None]) -> ToHakka:
68
+ """Return a new converter with custom word/character overrides applied.
69
+
70
+ Pass ``None`` as the value to remove an existing entry.
71
+ """
72
+ new_chars = dict(self._chars)
73
+ new_words = dict(self._words)
74
+ for key, val in entries.items():
75
+ if not key:
76
+ continue
77
+ if len(key) == 1:
78
+ if val is None:
79
+ new_chars.pop(key, None)
80
+ else:
81
+ new_chars[key] = (val.strip(),)
82
+ else:
83
+ if val is None:
84
+ new_words.pop(key, None)
85
+ else:
86
+ new_words[key] = (val.strip(),)
87
+ return ToHakka(chars=new_chars, words=new_words, simp_trad=self._simp_trad)
88
+
89
+ def _to_trad_str(self, s: str) -> str:
90
+ st = self._simp_trad
91
+ return "".join(st.get(ch, ch) for ch in s)
92
+
93
+ def _lookup_word_prons(self, chunk: str) -> tuple[str, ...] | None:
94
+ hit = self._words.get(chunk)
95
+ if hit is not None:
96
+ return hit
97
+ trad = self._to_trad_str(chunk)
98
+ if trad != chunk:
99
+ return self._words.get(trad)
100
+ return None
101
+
102
+ def _lookup_char_prons(self, ch: str) -> tuple[str, ...] | None:
103
+ hit = self._chars.get(ch)
104
+ if hit is not None:
105
+ return hit
106
+ trad = self._simp_trad.get(ch)
107
+ if trad is not None:
108
+ return self._chars.get(trad)
109
+ return None
110
+
111
+ def get_hakka_candidates(self, text: str) -> list[tuple[str, list[str]]]:
112
+ """Convert `text` into per-character `(char, candidates)` pairs in HPS-Ext."""
113
+ out: list[tuple[str, list[str]]] = []
114
+ n = len(text)
115
+ i = 0
116
+ max_len = self._max_word_len
117
+
118
+ while i < n:
119
+ matched_word = False
120
+ upper = min(max_len, n - i)
121
+ for length in range(upper, 1, -1):
122
+ chunk = text[i : i + length]
123
+ w_prons = self._lookup_word_prons(chunk)
124
+ if w_prons is None:
125
+ continue
126
+ primary_syls = w_prons[0].split()
127
+ if len(primary_syls) != length:
128
+ continue
129
+ # Collect per-position readings from word variants + char fallbacks
130
+ for pos in range(length):
131
+ ch = chunk[pos]
132
+ cands: list[str] = []
133
+ for wp in w_prons:
134
+ ws = wp.split()
135
+ if len(ws) == length and ws[pos] not in cands:
136
+ cands.append(ws[pos])
137
+ c_prons = self._lookup_char_prons(ch)
138
+ if c_prons:
139
+ for cp in c_prons:
140
+ if cp not in cands:
141
+ cands.append(cp)
142
+ out.append((ch, cands))
143
+ i += length
144
+ matched_word = True
145
+ break
146
+
147
+ if not matched_word:
148
+ ch = text[i]
149
+ c_prons = self._lookup_char_prons(ch)
150
+ out.append((ch, list(c_prons) if c_prons else []))
151
+ i += 1
152
+
153
+ return out
154
+
155
+ def get_hakka_list(self, text: str) -> list[tuple[str, str | None]]:
156
+ """Convert `text` into per-character `(char, hps_ext | None)` pairs."""
157
+ return [
158
+ (ch, cands[0] if cands else None)
159
+ for ch, cands in self.get_hakka_candidates(text)
160
+ ]
161
+
162
+ def get_hakka_text(self, text: str) -> str:
163
+ """Annotate `text` inline with HPS-Ext readings: ``今(gim1)日(ngid7)``."""
164
+ parts: list[str] = []
165
+ for ch, pron in self.get_hakka_list(text):
166
+ if pron is not None:
167
+ parts.append(f"{ch}({pron})")
168
+ else:
169
+ parts.append(ch)
170
+ return "".join(parts)
171
+
172
+ def get_hakka(self, text: str) -> str:
173
+ """Return space-separated HPS-Ext syllables for recognized characters in `text`."""
174
+ return " ".join(pron for _, pron in self.get_hakka_list(text) if pron is not None)
175
+
176
+ def get_ipa_list(
177
+ self, text: str, *, tone_style: str = "class"
178
+ ) -> list[tuple[str, str | None]]:
179
+ """Convert `text` into per-character `(char, ipa | None)` pairs."""
180
+ return [
181
+ (ch, hps_to_ipa(pron, tone_style=tone_style) if pron is not None else None)
182
+ for ch, pron in self.get_hakka_list(text)
183
+ ]
184
+
185
+ def get_ipa_text(self, text: str, *, tone_style: str = "class") -> str:
186
+ """Annotate `text` inline with IPA readings."""
187
+ parts: list[str] = []
188
+ for ch, pron in self.get_ipa_list(text, tone_style=tone_style):
189
+ if pron is not None:
190
+ parts.append(f"{ch}[{pron}]")
191
+ else:
192
+ parts.append(ch)
193
+ return "".join(parts)
194
+
195
+ def get_ipa(self, text: str, *, tone_style: str = "class") -> str:
196
+ """Return space-separated IPA syllables for recognized characters in `text`."""
197
+ return " ".join(
198
+ pron for _, pron in self.get_ipa_list(text, tone_style=tone_style) if pron is not None
199
+ )
200
+
201
+
202
+ _DEFAULT_CONVERTER: ToHakka | None = None
203
+
204
+
205
+ def _default() -> ToHakka:
206
+ global _DEFAULT_CONVERTER
207
+ if _DEFAULT_CONVERTER is None:
208
+ _DEFAULT_CONVERTER = ToHakka()
209
+ return _DEFAULT_CONVERTER
210
+
211
+
212
+ def get_hakka_list(text: str) -> list[tuple[str, str | None]]:
213
+ return _default().get_hakka_list(text)
214
+
215
+
216
+ def get_hakka_text(text: str) -> str:
217
+ return _default().get_hakka_text(text)
218
+
219
+
220
+ def get_hakka(text: str) -> str:
221
+ return _default().get_hakka(text)
222
+
223
+
224
+ def get_hakka_candidates(text: str) -> list[tuple[str, list[str]]]:
225
+ return _default().get_hakka_candidates(text)
226
+
227
+
228
+ def get_ipa_list(text: str, *, tone_style: str = "class") -> list[tuple[str, str | None]]:
229
+ return _default().get_ipa_list(text, tone_style=tone_style)
230
+
231
+
232
+ def get_ipa_text(text: str, *, tone_style: str = "class") -> str:
233
+ return _default().get_ipa_text(text, tone_style=tone_style)
234
+
235
+
236
+ def get_ipa(text: str, *, tone_style: str = "class") -> str:
237
+ return _default().get_ipa(text, tone_style=tone_style)
238
+
239
+
240
+ def customize(entries: Mapping[str, str | None]) -> ToHakka:
241
+ return _default().customize(entries)