PyHakka 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.
pyhakka/__init__.py ADDED
@@ -0,0 +1,72 @@
1
+ """PyHakka — Computational linguistics and dialectology toolkit for Hakka Chinese.
2
+
3
+ Default variety: Standard Huiyang Hakka (``huiyang``).
4
+ Default romanization: Hakka Pinyin System Extended (HPS-Ext, ``hps_ext``).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pyhakka.dialects import (
10
+ DEFAULT_DIALECT,
11
+ DEFAULT_SCHEME,
12
+ DialectInfo,
13
+ ToneSpec,
14
+ get_dialect,
15
+ list_dialects,
16
+ )
17
+ from pyhakka.lexicon import (
18
+ CharReading,
19
+ WordReading,
20
+ compare_dialects,
21
+ get_manifest,
22
+ lookup_char,
23
+ lookup_word,
24
+ search_by_pron,
25
+ )
26
+ from pyhakka.phon import (
27
+ CANONICAL_SCHEMES,
28
+ Syllable,
29
+ ValidationResult,
30
+ convert,
31
+ format_syllable,
32
+ parse_syllable,
33
+ parse_syllables,
34
+ validate_syllable,
35
+ )
36
+ from pyhakka.sandhi import (
37
+ SandhiChange,
38
+ SandhiResult,
39
+ apply_sandhi,
40
+ list_sandhi_dialects,
41
+ )
42
+
43
+ __version__ = "0.1.0"
44
+
45
+ __all__ = [
46
+ "CANONICAL_SCHEMES",
47
+ "DEFAULT_DIALECT",
48
+ "DEFAULT_SCHEME",
49
+ "CharReading",
50
+ "DialectInfo",
51
+ "SandhiChange",
52
+ "SandhiResult",
53
+ "Syllable",
54
+ "ToneSpec",
55
+ "ValidationResult",
56
+ "WordReading",
57
+ "__version__",
58
+ "apply_sandhi",
59
+ "compare_dialects",
60
+ "convert",
61
+ "format_syllable",
62
+ "get_dialect",
63
+ "get_manifest",
64
+ "list_dialects",
65
+ "list_sandhi_dialects",
66
+ "lookup_char",
67
+ "lookup_word",
68
+ "parse_syllable",
69
+ "parse_syllables",
70
+ "search_by_pron",
71
+ "validate_syllable",
72
+ ]
pyhakka/_db.py ADDED
@@ -0,0 +1,80 @@
1
+ """Internal read-only SQLite connection manager and Simplified/Traditional bridging."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sqlite3
7
+ from functools import lru_cache
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ DATA_DIR = Path(__file__).resolve().parent / "data"
12
+ DEFAULT_DB_PATH = DATA_DIR / "hakka.sqlite3"
13
+ MANIFEST_PATH = DATA_DIR / "manifest.json"
14
+
15
+ _CONNECTION: sqlite3.Connection | None = None
16
+
17
+
18
+ def get_db_path() -> Path:
19
+ return DEFAULT_DB_PATH
20
+
21
+
22
+ def get_manifest() -> dict[str, Any]:
23
+ return json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
24
+
25
+
26
+ def get_connection() -> sqlite3.Connection:
27
+ global _CONNECTION
28
+ if _CONNECTION is None:
29
+ db_path = get_db_path()
30
+ if not db_path.exists():
31
+ raise FileNotFoundError(
32
+ f"PyHakka database not found at {db_path}. "
33
+ "Run `python3 scripts/build_db.py` to compile it."
34
+ )
35
+ conn = sqlite3.connect(
36
+ f"file:{db_path}?mode=ro",
37
+ uri=True,
38
+ check_same_thread=False,
39
+ )
40
+ conn.row_factory = sqlite3.Row
41
+ _CONNECTION = conn
42
+ return _CONNECTION
43
+
44
+
45
+ @lru_cache(maxsize=8192)
46
+ def expand_char_variants(ch: str) -> tuple[str, ...]:
47
+ """Return `(ch, ...)` including mapped Traditional candidates for a Simplified char."""
48
+ if len(ch) != 1:
49
+ return (ch,)
50
+ conn = get_connection()
51
+ rows = conn.execute(
52
+ "SELECT trad FROM simp_trad WHERE simp = ? ORDER BY trad",
53
+ (ch,),
54
+ ).fetchall()
55
+ if not rows:
56
+ return (ch,)
57
+ seen = {ch}
58
+ out = [ch]
59
+ for r in rows:
60
+ t = r["trad"]
61
+ if t not in seen:
62
+ seen.add(t)
63
+ out.append(t)
64
+ return tuple(out)
65
+
66
+
67
+ @lru_cache(maxsize=8192)
68
+ def to_simplified_char(ch: str) -> str:
69
+ """Return Simplified equivalent of a Traditional char if unique in simp_trad."""
70
+ if len(ch) != 1:
71
+ return ch
72
+ conn = get_connection()
73
+ rows = conn.execute("SELECT simp FROM simp_trad WHERE trad = ?", (ch,)).fetchall()
74
+ if len(rows) == 1:
75
+ return str(rows[0]["simp"])
76
+ return ch
77
+
78
+
79
+ def to_simplified_text(text: str) -> str:
80
+ return "".join(to_simplified_char(ch) for ch in text)
pyhakka/cli.py ADDED
@@ -0,0 +1,293 @@
1
+ """Command-line interface for PyHakka (`pyhakka`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from collections.abc import Sequence
9
+ from dataclasses import asdict
10
+
11
+ import pyhakka
12
+ from pyhakka.dialects import DEFAULT_DIALECT, DEFAULT_SCHEME, get_dialect, list_dialects
13
+ from pyhakka.lexicon import compare_dialects, get_manifest, lookup_char, lookup_word, search_by_pron
14
+ from pyhakka.phon import CANONICAL_SCHEMES, convert, format_syllable
15
+ from pyhakka.sandhi import apply_sandhi, list_sandhi_dialects
16
+
17
+
18
+ def _print_json(obj: object) -> None:
19
+ print(json.dumps(obj, ensure_ascii=False, indent=2))
20
+
21
+
22
+ def _cmd_convert(args: argparse.Namespace) -> int:
23
+ result = convert(
24
+ args.text,
25
+ src=args.src,
26
+ dst=args.dst,
27
+ dialect=args.dialect,
28
+ )
29
+ if args.json:
30
+ _print_json(
31
+ {
32
+ "input": args.text,
33
+ "src": args.src,
34
+ "dst": args.dst,
35
+ "dialect": get_dialect(args.dialect).slug,
36
+ "output": result,
37
+ }
38
+ )
39
+ else:
40
+ print(result)
41
+ return 0
42
+
43
+
44
+ def _cmd_lookup(args: argparse.Namespace) -> int:
45
+ query = args.query.strip()
46
+ is_word = args.word or len(query) > 1
47
+ if is_word:
48
+ rows = lookup_word(query, dialect=args.dialect, scheme=args.scheme)
49
+ if args.json:
50
+ _print_json([asdict(r) for r in rows])
51
+ return 0
52
+ if not rows:
53
+ print(f"(no word entries for {query!r} in {get_dialect(args.dialect).slug})")
54
+ return 0
55
+ for r in rows:
56
+ note = f"\t# {r.note}" if r.note else ""
57
+ print(f"{r.word}\t{r.pron}\t[{r.ipa}]\t({r.entry_type}, {r.source or ''}){note}")
58
+ return 0
59
+
60
+ rows_c = lookup_char(query, dialect=args.dialect, scheme=args.scheme)
61
+ if args.json:
62
+ _print_json([asdict(r) for r in rows_c])
63
+ return 0
64
+ if not rows_c:
65
+ print(f"(no char entries for {query!r} in {get_dialect(args.dialect).slug})")
66
+ return 0
67
+ for r in rows_c:
68
+ tv = f" ({r.tone_value})" if r.tone_value else ""
69
+ note = f"\t# {r.note}" if r.note else ""
70
+ print(f"{r.char}\t{r.pron}\t[{r.ipa}]{tv}{note}")
71
+ return 0
72
+
73
+
74
+ def _cmd_compare(args: argparse.Namespace) -> int:
75
+ dialects_list = (
76
+ [d.strip() for d in args.dialects.split(",") if d.strip()] if args.dialects else None
77
+ )
78
+ res = compare_dialects(
79
+ args.char,
80
+ dialects=dialects_list,
81
+ tier=args.tier,
82
+ scheme=args.scheme,
83
+ )
84
+ if args.json:
85
+ _print_json({slug: [asdict(r) for r in rs] for slug, rs in res.items()})
86
+ return 0
87
+ for slug, rs in res.items():
88
+ prons = " / ".join(dict.fromkeys(r.pron for r in rs)) if rs else "—"
89
+ print(f"{slug:26s}\t{prons}")
90
+ return 0
91
+
92
+
93
+ def _cmd_sandhi(args: argparse.Namespace) -> int:
94
+ res = apply_sandhi(
95
+ args.syllables,
96
+ dialect=args.dialect,
97
+ chars=args.chars,
98
+ profile=args.profile,
99
+ scheme=args.input_scheme,
100
+ )
101
+ formatted = " ".join(
102
+ format_syllable(s, scheme=args.scheme, dialect=res.dialect) for s in res.syllables
103
+ )
104
+ if args.json:
105
+ _print_json(
106
+ {
107
+ "dialect": res.dialect,
108
+ "profile": res.profile,
109
+ "output": formatted,
110
+ "hps_ext": res.hps_ext,
111
+ "changes": [asdict(c) for c in res.changes],
112
+ }
113
+ )
114
+ return 0
115
+ print(formatted)
116
+ if args.verbose and res.changes:
117
+ for chg in res.changes:
118
+ tag = f" ({chg.char})" if chg.char else ""
119
+ print(f" [{chg.index}]{tag} {chg.before} -> {chg.after} <{chg.rule}>")
120
+ return 0
121
+
122
+
123
+ def _cmd_search(args: argparse.Namespace) -> int:
124
+ rows = search_by_pron(
125
+ args.pron,
126
+ dialect=args.dialect,
127
+ scheme=args.scheme,
128
+ scope=args.scope,
129
+ limit=args.limit,
130
+ )
131
+ if args.json:
132
+ _print_json([asdict(r) for r in rows])
133
+ return 0
134
+ if not rows:
135
+ print(f"(no {args.scope} matches for {args.pron!r} in {get_dialect(args.dialect).slug})")
136
+ return 0
137
+ for r in rows:
138
+ head = r.word if hasattr(r, "word") else r.char # type: ignore[union-attr]
139
+ note = f"\t# {r.note}" if r.note else ""
140
+ print(f"{head}\t{r.pron}\t[{r.ipa}]{note}")
141
+ return 0
142
+
143
+
144
+ def _cmd_dialects(args: argparse.Namespace) -> int:
145
+ ds = list_dialects(
146
+ tier=args.tier,
147
+ subgroup=args.subgroup,
148
+ has_words=True if args.with_words else None,
149
+ historical_only=args.historical,
150
+ islands_only=args.islands,
151
+ )
152
+ if args.json:
153
+ _print_json([asdict(d) for d in ds])
154
+ return 0
155
+ for d in ds:
156
+ loc = d.location or ""
157
+ print(
158
+ f"{d.slug:26s}\t{d.tier:7s}\tchars={d.char_count:6d}\twords={d.word_count:6d}\t{loc}"
159
+ )
160
+ print(f"Total: {len(ds)} varieties")
161
+ return 0
162
+
163
+
164
+ def _cmd_info(args: argparse.Namespace) -> int:
165
+ if args.dialect:
166
+ d = get_dialect(args.dialect)
167
+ if args.json:
168
+ _print_json(asdict(d))
169
+ return 0
170
+ print(f"Dialect: {d.slug} ({d.name_trad} / {d.name_simp})")
171
+ print(f"Tier: {d.tier} | License: {d.source_license}")
172
+ print(f"Subgroup: {d.subgroup or '—'}")
173
+ print(f"Location: {d.location or '—'} (lat={d.lat}, lon={d.lon})")
174
+ print(f"Entries: {d.char_count:,} chars, {d.word_count:,} words")
175
+ if d.tones:
176
+ tline = ", ".join(
177
+ f"{k}:{t.name}({t.value or '?'})" for k, t in sorted(d.tones.items())
178
+ )
179
+ print(f"Tones: {tline}")
180
+ if d.slug in list_sandhi_dialects():
181
+ print(f"Sandhi: {', '.join(list_sandhi_dialects()[d.slug])}")
182
+ if d.reference:
183
+ print(f"Source: {d.reference}")
184
+ return 0
185
+
186
+ manifest = get_manifest()
187
+ if args.json:
188
+ _print_json(manifest)
189
+ return 0
190
+ counts = manifest["counts"]
191
+ print(f"PyHakka v{pyhakka.__version__}")
192
+ print(f"Default dialect: {DEFAULT_DIALECT} | Default scheme: {DEFAULT_SCHEME}")
193
+ print(f"Schemes: {', '.join(CANONICAL_SCHEMES)}")
194
+ print(
195
+ f"Database: {counts.get('standard_dialects', 0)} standard + "
196
+ f"{counts['core_dialects']} curated core + "
197
+ f"{counts['mcpdict_dialects']} MCPDict = {counts['total_dialects']} total"
198
+ )
199
+ print(
200
+ f"Records: {counts['total_char_rows']:,} char readings, "
201
+ f"{counts['total_word_rows']:,} word readings"
202
+ )
203
+ return 0
204
+
205
+
206
+ def build_parser() -> argparse.ArgumentParser:
207
+ parser = argparse.ArgumentParser(
208
+ prog="pyhakka",
209
+ description="PyHakka — Hakka Chinese computational linguistics CLI",
210
+ )
211
+ parser.add_argument("--version", action="version", version=f"pyhakka {pyhakka.__version__}")
212
+ sub = parser.add_subparsers(dest="command", required=True)
213
+
214
+ # convert
215
+ p_conv = sub.add_parser("convert", help="Convert between Hakka phonetic schemes")
216
+ p_conv.add_argument("text", help="Space-separated syllables")
217
+ p_conv.add_argument("--from", dest="src", default=DEFAULT_SCHEME, help="Source scheme")
218
+ p_conv.add_argument("--to", dest="dst", default="ipa", help="Target scheme")
219
+ p_conv.add_argument("-d", "--dialect", default=DEFAULT_DIALECT, help="Dialect profile")
220
+ p_conv.add_argument("--json", action="store_true", help="Output JSON")
221
+ p_conv.set_defaults(func=_cmd_convert)
222
+
223
+ # lookup
224
+ p_lk = sub.add_parser("lookup", help="Look up a character or word in a Hakka dialect")
225
+ p_lk.add_argument("query", help="Single character or multi-character word")
226
+ p_lk.add_argument("-d", "--dialect", default=DEFAULT_DIALECT, help="Dialect slug or alias")
227
+ p_lk.add_argument("-s", "--scheme", default=DEFAULT_SCHEME, help="Output scheme")
228
+ p_lk.add_argument("--word", action="store_true", help="Force word-table lookup")
229
+ p_lk.add_argument("--json", action="store_true", help="Output JSON")
230
+ p_lk.set_defaults(func=_cmd_lookup)
231
+
232
+ # compare
233
+ p_cmp = sub.add_parser("compare", help="Compare a character across multiple Hakka dialects")
234
+ p_cmp.add_argument("char", help="Single character")
235
+ p_cmp.add_argument("--dialects", default=None, help="Comma-separated dialect slugs/aliases")
236
+ p_cmp.add_argument("--tier", default="core", choices=("standard", "core", "mcpdict", "all"))
237
+ p_cmp.add_argument("-s", "--scheme", default=DEFAULT_SCHEME, help="Output scheme")
238
+ p_cmp.add_argument("--json", action="store_true", help="Output JSON")
239
+ p_cmp.set_defaults(func=_cmd_compare)
240
+
241
+ # sandhi
242
+ p_sd = sub.add_parser("sandhi", help="Apply tone sandhi and segmental assimilation rules")
243
+ p_sd.add_argument("syllables", help="Space-separated syllables")
244
+ p_sd.add_argument("-d", "--dialect", default=DEFAULT_DIALECT, help="Dialect slug or alias")
245
+ p_sd.add_argument("--chars", default=None, help="Optional aligned Chinese characters")
246
+ p_sd.add_argument("--profile", default="standard", help="Rule profile (standard/traditional/rao)")
247
+ p_sd.add_argument("--input-scheme", default=DEFAULT_SCHEME, help="Input scheme")
248
+ p_sd.add_argument("-s", "--scheme", default="ipa_value", help="Output scheme")
249
+ p_sd.add_argument("-v", "--verbose", action="store_true", help="Show applied rule trace")
250
+ p_sd.add_argument("--json", action="store_true", help="Output JSON")
251
+ p_sd.set_defaults(func=_cmd_sandhi)
252
+
253
+ # search
254
+ p_sr = sub.add_parser("search", help="Reverse-lookup characters or words by pronunciation")
255
+ p_sr.add_argument("pron", help="Pronunciation query")
256
+ p_sr.add_argument("-d", "--dialect", default=DEFAULT_DIALECT, help="Dialect slug or alias")
257
+ p_sr.add_argument("-s", "--scheme", default=DEFAULT_SCHEME, help="Pronunciation scheme")
258
+ p_sr.add_argument("--scope", default="char", choices=("char", "word"))
259
+ p_sr.add_argument("--limit", type=int, default=30, help="Max results")
260
+ p_sr.add_argument("--json", action="store_true", help="Output JSON")
261
+ p_sr.set_defaults(func=_cmd_search)
262
+
263
+ # dialects
264
+ p_dl = sub.add_parser("dialects", help="List available Hakka varieties")
265
+ p_dl.add_argument("--tier", default=None, choices=("standard", "core", "mcpdict"))
266
+ p_dl.add_argument("--subgroup", default=None, help="Filter by subgroup substring")
267
+ p_dl.add_argument("--with-words", action="store_true", help="Only dialects with word tables")
268
+ p_dl.add_argument("--historical", action="store_true", help="Only historical varieties")
269
+ p_dl.add_argument("--islands", action="store_true", help="Only dialect islands")
270
+ p_dl.add_argument("--json", action="store_true", help="Output JSON")
271
+ p_dl.set_defaults(func=_cmd_dialects)
272
+
273
+ # info
274
+ p_in = sub.add_parser("info", help="Show PyHakka or specific dialect metadata")
275
+ p_in.add_argument("dialect", nargs="?", default=None, help="Optional dialect slug/alias")
276
+ p_in.add_argument("--json", action="store_true", help="Output JSON")
277
+ p_in.set_defaults(func=_cmd_info)
278
+
279
+ return parser
280
+
281
+
282
+ def main(argv: Sequence[str] | None = None) -> int:
283
+ parser = build_parser()
284
+ args = parser.parse_args(argv)
285
+ try:
286
+ return int(args.func(args))
287
+ except (KeyError, ValueError) as exc:
288
+ print(f"Error: {exc}", file=sys.stderr)
289
+ return 2
290
+
291
+
292
+ if __name__ == "__main__":
293
+ raise SystemExit(main())
@@ -0,0 +1,4 @@
1
+ [diffend] Oversized file quarantined before diffing.
2
+ name: pyhakka/data/hakka.sqlite3
3
+ size: 41414656 bytes
4
+ sha256: fa795ceb58522835b18f3bd631cea18400c62b0413f3c9b3384f11044b9062e3
@@ -0,0 +1,106 @@
1
+ {
2
+ "schema_version": 1,
3
+ "db_file": "hakka.sqlite3",
4
+ "db_bytes": 41414656,
5
+ "db_sha256": "fa795ceb58522835b18f3bd631cea18400c62b0413f3c9b3384f11044b9062e3",
6
+ "counts": {
7
+ "standard_dialects": 1,
8
+ "core_dialects": 10,
9
+ "mcpdict_dialects": 218,
10
+ "total_dialects": 229,
11
+ "standard_char_rows": 12528,
12
+ "standard_word_rows": 26634,
13
+ "core_char_rows": 64855,
14
+ "core_word_rows": 120189,
15
+ "mcpdict_char_rows": 628461,
16
+ "total_char_rows": 705844,
17
+ "total_word_rows": 146823,
18
+ "simp_trad_pairs": 3311,
19
+ "aliases": 851
20
+ },
21
+ "sources": {
22
+ "Standard-Huiyang": {
23
+ "license": "CC BY 4.0",
24
+ "dialects": 1,
25
+ "char_rows": 12528,
26
+ "word_rows": 26634
27
+ },
28
+ "Hakka-Char-Tables": {
29
+ "license": "CC BY 4.0",
30
+ "dialects": 10,
31
+ "rows": 64855
32
+ },
33
+ "Hakka-Word-Tables": {
34
+ "license": "CC BY 4.0",
35
+ "dialects": 9,
36
+ "rows": 120189
37
+ },
38
+ "MCPDict": {
39
+ "license": "MIT",
40
+ "dialects": 218,
41
+ "rows": 628461
42
+ }
43
+ },
44
+ "core_dialects": [
45
+ {
46
+ "slug": "meixian",
47
+ "tier": "core",
48
+ "char_rows": 3721,
49
+ "word_rows": 4087
50
+ },
51
+ {
52
+ "slug": "changting",
53
+ "tier": "core",
54
+ "char_rows": 6177,
55
+ "word_rows": 16120
56
+ },
57
+ {
58
+ "slug": "xingning",
59
+ "tier": "core",
60
+ "char_rows": 9114,
61
+ "word_rows": 5798
62
+ },
63
+ {
64
+ "slug": "wuhua",
65
+ "tier": "core",
66
+ "char_rows": 5788,
67
+ "word_rows": 3215
68
+ },
69
+ {
70
+ "slug": "dabu-baihou",
71
+ "tier": "core",
72
+ "char_rows": 4884,
73
+ "word_rows": 2099
74
+ },
75
+ {
76
+ "slug": "huiyang-danshui",
77
+ "tier": "core",
78
+ "char_rows": 1052,
79
+ "word_rows": 607
80
+ },
81
+ {
82
+ "slug": "huiyang-1987",
83
+ "tier": "core",
84
+ "char_rows": 1649,
85
+ "word_rows": 0
86
+ },
87
+ {
88
+ "slug": "huidong-daling",
89
+ "tier": "core",
90
+ "char_rows": 959,
91
+ "word_rows": 762
92
+ },
93
+ {
94
+ "slug": "shenzhen-baoan",
95
+ "tier": "core",
96
+ "char_rows": 19026,
97
+ "word_rows": 60867
98
+ },
99
+ {
100
+ "slug": "hongkong-newterritories",
101
+ "tier": "core",
102
+ "char_rows": 12485,
103
+ "word_rows": 26634
104
+ }
105
+ ]
106
+ }