simphone 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.
- simphone-0.1.0/LICENSE +21 -0
- simphone-0.1.0/PKG-INFO +149 -0
- simphone-0.1.0/README.md +118 -0
- simphone-0.1.0/pyproject.toml +50 -0
- simphone-0.1.0/setup.cfg +4 -0
- simphone-0.1.0/src/simphone/__init__.py +13 -0
- simphone-0.1.0/src/simphone/__main__.py +8 -0
- simphone-0.1.0/src/simphone/cli.py +174 -0
- simphone-0.1.0/src/simphone/distance.py +346 -0
- simphone-0.1.0/src/simphone/g2p.py +406 -0
- simphone-0.1.0/src/simphone/index.py +403 -0
- simphone-0.1.0/src/simphone.egg-info/PKG-INFO +149 -0
- simphone-0.1.0/src/simphone.egg-info/SOURCES.txt +15 -0
- simphone-0.1.0/src/simphone.egg-info/dependency_links.txt +1 -0
- simphone-0.1.0/src/simphone.egg-info/entry_points.txt +2 -0
- simphone-0.1.0/src/simphone.egg-info/requires.txt +13 -0
- simphone-0.1.0/src/simphone.egg-info/top_level.txt +1 -0
simphone-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 nguyenvulebinh
|
|
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.
|
simphone-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: simphone
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Feature-weighted phonetic edit-distance search over a word or span list.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/nguyenvulebinh/simphone
|
|
7
|
+
Project-URL: Repository, https://github.com/nguyenvulebinh/simphone
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: numpy>=1.22
|
|
19
|
+
Requires-Dist: panphon>=0.20
|
|
20
|
+
Requires-Dist: rapidfuzz>=3
|
|
21
|
+
Requires-Dist: numba>=0.57
|
|
22
|
+
Requires-Dist: tqdm>=4.65
|
|
23
|
+
Requires-Dist: sea-g2p>=0.9.1
|
|
24
|
+
Provides-Extra: en
|
|
25
|
+
Requires-Dist: text2phonemesequence>=0.1.4; extra == "en"
|
|
26
|
+
Requires-Dist: transformers>=4.44; extra == "en"
|
|
27
|
+
Requires-Dist: segments; extra == "en"
|
|
28
|
+
Requires-Dist: huggingface_hub>=0.23; extra == "en"
|
|
29
|
+
Requires-Dist: WeTextProcessing>=1.0; extra == "en"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# simphone
|
|
33
|
+
|
|
34
|
+
Find words or spans that sound alike. Each span is turned into phones, then ranked with a feature-weighted edit distance (panphon articulatory cost, plus a penalty when tones differ).
|
|
35
|
+
|
|
36
|
+
Vietnamese phones come from [sea-g2p](https://github.com/pnnbao97/sea-g2p). English phones come from CharsiuG2P.
|
|
37
|
+
|
|
38
|
+
## Vietnamese reading
|
|
39
|
+
|
|
40
|
+
Vietnamese build and search run sea-g2p in two steps, both with `punc_norm=False` (no forced trailing period):
|
|
41
|
+
|
|
42
|
+
1. `Normalizer` expands the spoken form: numbers, dates, units, and abbreviations. `21` becomes `hai mươi mốt`, `km` becomes `ki lô mét`, `COVID-19` becomes `covid mười chín`.
|
|
43
|
+
2. `G2P` turns that spoken form into phones. `21` and `hai mươi mốt` therefore share `hˈaːj mˈyəj mˈoɜt̪`.
|
|
44
|
+
|
|
45
|
+
sea-g2p wraps an English run in `<en>...</en>` (`CPU` becomes `<en>c p u</en>`). `normalize` drops those markers and keeps the words. Search still passes the marked text to G2P, so the English run is read as English and the markers never become phones.
|
|
46
|
+
|
|
47
|
+
## English reading
|
|
48
|
+
|
|
49
|
+
English build and search run two steps:
|
|
50
|
+
|
|
51
|
+
1. [WeTextProcessing](https://github.com/wenet-e2e/WeTextProcessing) English text normalization expands the spoken form (cardinals, ordinals, decimals, dates, times, measures, money). `21` becomes `twenty one`. A number plus a unit expands (`5 km` becomes `five kilometers`). A bare `km` stays `km`.
|
|
52
|
+
2. CharsiuG2P turns each spoken word into phones. `21` and `twenty one` therefore share those phones.
|
|
53
|
+
|
|
54
|
+
## Install
|
|
55
|
+
|
|
56
|
+
`pip install simphone` installs Vietnamese only. Vietnamese search does not need a GPU.
|
|
57
|
+
|
|
58
|
+
English is a separate extra. Install PyTorch yourself first, so a CUDA build already in the environment is kept. This package will not install torch.
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
# CPU. Skip this if torch is already installed.
|
|
62
|
+
pip install torch --index-url https://download.pytorch.org/whl/cpu
|
|
63
|
+
|
|
64
|
+
pip install "simphone[en]"
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The English extra needs Linux x86_64. It uses WeTextProcessing, which depends on pynini, and pynini publishes wheels for that platform only.
|
|
68
|
+
|
|
69
|
+
From a checkout of this repo:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
pip install -e .
|
|
73
|
+
pip install -e ".[en]" # after torch, Linux x86_64
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Calling English without the extra raises an error that tells you to install `simphone[en]`. English out-of-dictionary words use Charsiu's byT5 model; `--device cuda:0` speeds that step only.
|
|
77
|
+
|
|
78
|
+
## Python
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from simphone import PhoneticIndex
|
|
82
|
+
|
|
83
|
+
index = PhoneticIndex.build(
|
|
84
|
+
["mắc", "mác", "mức", "việt nam"],
|
|
85
|
+
lang="vi",
|
|
86
|
+
tone_weight=0.5,
|
|
87
|
+
)
|
|
88
|
+
index.save("vi.index")
|
|
89
|
+
|
|
90
|
+
index = PhoneticIndex.load("vi.index") # skips G2P and the cost matrix
|
|
91
|
+
hits = index.search("mắc", topk=50, prefilter=300, sim_min=0.8)
|
|
92
|
+
# [{"text": "...", "sim": ..., "n_units": 1, "dlen": 0}, ...]
|
|
93
|
+
|
|
94
|
+
batch = index.search_many(
|
|
95
|
+
["mắc", "việt nam"],
|
|
96
|
+
topk=50,
|
|
97
|
+
workers=0, # 0 = all CPUs
|
|
98
|
+
block_size=512,
|
|
99
|
+
)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`sim` is `1 - distance / max(len_a, len_b)`. `dlen` is the difference in whitespace-separated unit counts.
|
|
103
|
+
|
|
104
|
+
Spoken form only, without phones or an index. One string per input, same order:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from simphone import normalize
|
|
108
|
+
|
|
109
|
+
normalize(["21", "km"], lang="vi")
|
|
110
|
+
# ["hai mươi mốt", "ki lô mét"]
|
|
111
|
+
|
|
112
|
+
normalize(["21", "5 km"], lang="en")
|
|
113
|
+
# ["twenty one", "five kilometers"]
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
English normalization needs `simphone[en]` and does not load torch.
|
|
117
|
+
|
|
118
|
+
## Command line
|
|
119
|
+
|
|
120
|
+
Inventory and query files are one span per line. Blank lines and `#` comments are ignored.
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
simphone norm --lang vi --text "21" --text "km"
|
|
124
|
+
simphone norm --lang en --text "21" --text "5 km"
|
|
125
|
+
simphone norm --lang vi --queries spans.txt
|
|
126
|
+
|
|
127
|
+
simphone build --lang vi --inventory spans.txt --save vi.index --tone-weight 0.5
|
|
128
|
+
|
|
129
|
+
simphone search --load vi.index --query "mắc" --topk 50 --sim-min 0.8 --workers 0
|
|
130
|
+
|
|
131
|
+
simphone search --load vi.index --queries queries.txt --workers 0 --block-size 512 --out hits.jsonl
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`--inventory` on `search` builds in memory when you have no saved index. `--tone-weight` is fixed at build time and stored in the index.
|
|
135
|
+
|
|
136
|
+
## Large lists
|
|
137
|
+
|
|
138
|
+
Build the inventory once and `save` it. A later `load` does not phonemize those spans and does not rebuild the panphon matrix. A new query is phonemized on its own, including the Vietnamese or English normalizer above. If that query uses a phone the inventory never saw, only that phone's cost row is added.
|
|
139
|
+
|
|
140
|
+
Searching many queries one call at a time repeats a full scan of the inventory and leaves cores idle. `search_many` / `--queries` is the batch path:
|
|
141
|
+
|
|
142
|
+
- Several queries (at least as many as workers): the queries are split across processes. Each process keeps the inventory in shared memory and runs rapidfuzz on blocks of 512 queries, then reranks the top `--prefilter` with the feature-plus-tone distance.
|
|
143
|
+
- One query, or fewer queries than workers: the inventory is split instead, so that query still uses more than one core.
|
|
144
|
+
|
|
145
|
+
Passing the inventory back in as the query list returns a neighbor list for every span. A span is not returned as its own neighbor.
|
|
146
|
+
|
|
147
|
+
## Tones
|
|
148
|
+
|
|
149
|
+
panphon ignores tone. Vietnamese sea-g2p writes one syllable per space, with stress and a tone mark inside the syllable (`mà` → `mˌaː2`, `má` → `mˈaːɜ`). Those marks are peeled off and attached to the vowel before the distance is computed. The six tones on `ma mà mả mã má mạ` are: no mark, `2`, `4`, `5`, `ɜ` (sắc), `6`. English Charsiu tones stay Chao letters and use the same penalty. `--tone-weight` (default `0.5`) is added when two phones differ only in tone, or in tone as well as in the base phone.
|
simphone-0.1.0/README.md
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# simphone
|
|
2
|
+
|
|
3
|
+
Find words or spans that sound alike. Each span is turned into phones, then ranked with a feature-weighted edit distance (panphon articulatory cost, plus a penalty when tones differ).
|
|
4
|
+
|
|
5
|
+
Vietnamese phones come from [sea-g2p](https://github.com/pnnbao97/sea-g2p). English phones come from CharsiuG2P.
|
|
6
|
+
|
|
7
|
+
## Vietnamese reading
|
|
8
|
+
|
|
9
|
+
Vietnamese build and search run sea-g2p in two steps, both with `punc_norm=False` (no forced trailing period):
|
|
10
|
+
|
|
11
|
+
1. `Normalizer` expands the spoken form: numbers, dates, units, and abbreviations. `21` becomes `hai mươi mốt`, `km` becomes `ki lô mét`, `COVID-19` becomes `covid mười chín`.
|
|
12
|
+
2. `G2P` turns that spoken form into phones. `21` and `hai mươi mốt` therefore share `hˈaːj mˈyəj mˈoɜt̪`.
|
|
13
|
+
|
|
14
|
+
sea-g2p wraps an English run in `<en>...</en>` (`CPU` becomes `<en>c p u</en>`). `normalize` drops those markers and keeps the words. Search still passes the marked text to G2P, so the English run is read as English and the markers never become phones.
|
|
15
|
+
|
|
16
|
+
## English reading
|
|
17
|
+
|
|
18
|
+
English build and search run two steps:
|
|
19
|
+
|
|
20
|
+
1. [WeTextProcessing](https://github.com/wenet-e2e/WeTextProcessing) English text normalization expands the spoken form (cardinals, ordinals, decimals, dates, times, measures, money). `21` becomes `twenty one`. A number plus a unit expands (`5 km` becomes `five kilometers`). A bare `km` stays `km`.
|
|
21
|
+
2. CharsiuG2P turns each spoken word into phones. `21` and `twenty one` therefore share those phones.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
`pip install simphone` installs Vietnamese only. Vietnamese search does not need a GPU.
|
|
26
|
+
|
|
27
|
+
English is a separate extra. Install PyTorch yourself first, so a CUDA build already in the environment is kept. This package will not install torch.
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
# CPU. Skip this if torch is already installed.
|
|
31
|
+
pip install torch --index-url https://download.pytorch.org/whl/cpu
|
|
32
|
+
|
|
33
|
+
pip install "simphone[en]"
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The English extra needs Linux x86_64. It uses WeTextProcessing, which depends on pynini, and pynini publishes wheels for that platform only.
|
|
37
|
+
|
|
38
|
+
From a checkout of this repo:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install -e .
|
|
42
|
+
pip install -e ".[en]" # after torch, Linux x86_64
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Calling English without the extra raises an error that tells you to install `simphone[en]`. English out-of-dictionary words use Charsiu's byT5 model; `--device cuda:0` speeds that step only.
|
|
46
|
+
|
|
47
|
+
## Python
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from simphone import PhoneticIndex
|
|
51
|
+
|
|
52
|
+
index = PhoneticIndex.build(
|
|
53
|
+
["mắc", "mác", "mức", "việt nam"],
|
|
54
|
+
lang="vi",
|
|
55
|
+
tone_weight=0.5,
|
|
56
|
+
)
|
|
57
|
+
index.save("vi.index")
|
|
58
|
+
|
|
59
|
+
index = PhoneticIndex.load("vi.index") # skips G2P and the cost matrix
|
|
60
|
+
hits = index.search("mắc", topk=50, prefilter=300, sim_min=0.8)
|
|
61
|
+
# [{"text": "...", "sim": ..., "n_units": 1, "dlen": 0}, ...]
|
|
62
|
+
|
|
63
|
+
batch = index.search_many(
|
|
64
|
+
["mắc", "việt nam"],
|
|
65
|
+
topk=50,
|
|
66
|
+
workers=0, # 0 = all CPUs
|
|
67
|
+
block_size=512,
|
|
68
|
+
)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`sim` is `1 - distance / max(len_a, len_b)`. `dlen` is the difference in whitespace-separated unit counts.
|
|
72
|
+
|
|
73
|
+
Spoken form only, without phones or an index. One string per input, same order:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from simphone import normalize
|
|
77
|
+
|
|
78
|
+
normalize(["21", "km"], lang="vi")
|
|
79
|
+
# ["hai mươi mốt", "ki lô mét"]
|
|
80
|
+
|
|
81
|
+
normalize(["21", "5 km"], lang="en")
|
|
82
|
+
# ["twenty one", "five kilometers"]
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
English normalization needs `simphone[en]` and does not load torch.
|
|
86
|
+
|
|
87
|
+
## Command line
|
|
88
|
+
|
|
89
|
+
Inventory and query files are one span per line. Blank lines and `#` comments are ignored.
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
simphone norm --lang vi --text "21" --text "km"
|
|
93
|
+
simphone norm --lang en --text "21" --text "5 km"
|
|
94
|
+
simphone norm --lang vi --queries spans.txt
|
|
95
|
+
|
|
96
|
+
simphone build --lang vi --inventory spans.txt --save vi.index --tone-weight 0.5
|
|
97
|
+
|
|
98
|
+
simphone search --load vi.index --query "mắc" --topk 50 --sim-min 0.8 --workers 0
|
|
99
|
+
|
|
100
|
+
simphone search --load vi.index --queries queries.txt --workers 0 --block-size 512 --out hits.jsonl
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`--inventory` on `search` builds in memory when you have no saved index. `--tone-weight` is fixed at build time and stored in the index.
|
|
104
|
+
|
|
105
|
+
## Large lists
|
|
106
|
+
|
|
107
|
+
Build the inventory once and `save` it. A later `load` does not phonemize those spans and does not rebuild the panphon matrix. A new query is phonemized on its own, including the Vietnamese or English normalizer above. If that query uses a phone the inventory never saw, only that phone's cost row is added.
|
|
108
|
+
|
|
109
|
+
Searching many queries one call at a time repeats a full scan of the inventory and leaves cores idle. `search_many` / `--queries` is the batch path:
|
|
110
|
+
|
|
111
|
+
- Several queries (at least as many as workers): the queries are split across processes. Each process keeps the inventory in shared memory and runs rapidfuzz on blocks of 512 queries, then reranks the top `--prefilter` with the feature-plus-tone distance.
|
|
112
|
+
- One query, or fewer queries than workers: the inventory is split instead, so that query still uses more than one core.
|
|
113
|
+
|
|
114
|
+
Passing the inventory back in as the query list returns a neighbor list for every span. A span is not returned as its own neighbor.
|
|
115
|
+
|
|
116
|
+
## Tones
|
|
117
|
+
|
|
118
|
+
panphon ignores tone. Vietnamese sea-g2p writes one syllable per space, with stress and a tone mark inside the syllable (`mà` → `mˌaː2`, `má` → `mˈaːɜ`). Those marks are peeled off and attached to the vowel before the distance is computed. The six tones on `ma mà mả mã má mạ` are: no mark, `2`, `4`, `5`, `ɜ` (sắc), `6`. English Charsiu tones stay Chao letters and use the same penalty. `--tone-weight` (default `0.5`) is added when two phones differ only in tone, or in tone as well as in the base phone.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "simphone"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Feature-weighted phonetic edit-distance search over a word or span list."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 4 - Beta",
|
|
15
|
+
"Intended Audience :: Developers",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.10",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Topic :: Text Processing :: Linguistic",
|
|
21
|
+
]
|
|
22
|
+
# torch is not a dependency. English CharsiuG2P needs the build already in the
|
|
23
|
+
# environment. Vietnamese uses sea-g2p and does not.
|
|
24
|
+
dependencies = [
|
|
25
|
+
"numpy>=1.22",
|
|
26
|
+
"panphon>=0.20",
|
|
27
|
+
"rapidfuzz>=3",
|
|
28
|
+
"numba>=0.57",
|
|
29
|
+
"tqdm>=4.65",
|
|
30
|
+
"sea-g2p>=0.9.1",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
en = [
|
|
35
|
+
"text2phonemesequence>=0.1.4",
|
|
36
|
+
"transformers>=4.44",
|
|
37
|
+
"segments",
|
|
38
|
+
"huggingface_hub>=0.23",
|
|
39
|
+
"WeTextProcessing>=1.0",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[project.urls]
|
|
43
|
+
Homepage = "https://github.com/nguyenvulebinh/simphone"
|
|
44
|
+
Repository = "https://github.com/nguyenvulebinh/simphone"
|
|
45
|
+
|
|
46
|
+
[project.scripts]
|
|
47
|
+
simphone = "simphone.cli:main"
|
|
48
|
+
|
|
49
|
+
[tool.setuptools.packages.find]
|
|
50
|
+
where = ["src"]
|
simphone-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Phonetic similarity search over a list of words or spans."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from simphone.g2p import normalize
|
|
6
|
+
from simphone.index import PhoneticIndex
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
__version__ = version("simphone")
|
|
10
|
+
except PackageNotFoundError:
|
|
11
|
+
__version__ = "0.1.0"
|
|
12
|
+
|
|
13
|
+
__all__ = ["PhoneticIndex", "normalize"]
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Command line for building and searching a phonetic index."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from simphone.g2p import normalize
|
|
11
|
+
from simphone.index import PhoneticIndex, read_span_file
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _queries(args: argparse.Namespace) -> list[str]:
|
|
15
|
+
out = list(args.query or [])
|
|
16
|
+
if args.queries:
|
|
17
|
+
out.extend(read_span_file(args.queries))
|
|
18
|
+
return out
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _print_hits(query: str, hits: list[dict]) -> None:
|
|
22
|
+
print(query)
|
|
23
|
+
if not hits:
|
|
24
|
+
print(" (none)")
|
|
25
|
+
return
|
|
26
|
+
for h in hits:
|
|
27
|
+
dlen = h["dlen"]
|
|
28
|
+
sign = f"{dlen:+d}"
|
|
29
|
+
print(f" {h['text']}\t{h['sim']:.4f}\tn={h['n_units']}\tdlen={sign}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def cmd_norm(args: argparse.Namespace) -> int:
|
|
33
|
+
texts = list(args.text or [])
|
|
34
|
+
if args.queries:
|
|
35
|
+
texts.extend(read_span_file(args.queries))
|
|
36
|
+
if not texts:
|
|
37
|
+
print("pass --text and/or --queries", file=sys.stderr)
|
|
38
|
+
return 1
|
|
39
|
+
for line in normalize(texts, args.lang, workers=args.workers):
|
|
40
|
+
print(line)
|
|
41
|
+
return 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def cmd_build(args: argparse.Namespace) -> int:
|
|
45
|
+
spans = read_span_file(args.inventory)
|
|
46
|
+
if not spans:
|
|
47
|
+
print(f"no spans in {args.inventory}", file=sys.stderr)
|
|
48
|
+
return 1
|
|
49
|
+
print(f"phonemizing {len(spans)} spans ({args.lang})", flush=True)
|
|
50
|
+
index = PhoneticIndex.build(
|
|
51
|
+
spans,
|
|
52
|
+
args.lang,
|
|
53
|
+
tone_weight=args.tone_weight,
|
|
54
|
+
device=args.device,
|
|
55
|
+
cache_dir=args.cache_dir,
|
|
56
|
+
en_locale=args.en_locale,
|
|
57
|
+
workers=args.workers,
|
|
58
|
+
)
|
|
59
|
+
index.save(args.save)
|
|
60
|
+
print(f"saved {len(index.spans)} spans -> {args.save}")
|
|
61
|
+
return 0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def cmd_search(args: argparse.Namespace) -> int:
|
|
65
|
+
queries = _queries(args)
|
|
66
|
+
if not queries:
|
|
67
|
+
print("pass --query and/or --queries", file=sys.stderr)
|
|
68
|
+
return 1
|
|
69
|
+
if args.load:
|
|
70
|
+
index = PhoneticIndex.load(args.load)
|
|
71
|
+
else:
|
|
72
|
+
if not args.inventory or not args.lang:
|
|
73
|
+
print("pass --load, or --inventory with --lang", file=sys.stderr)
|
|
74
|
+
return 1
|
|
75
|
+
spans = read_span_file(args.inventory)
|
|
76
|
+
print(f"phonemizing {len(spans)} spans ({args.lang})", flush=True)
|
|
77
|
+
index = PhoneticIndex.build(
|
|
78
|
+
spans,
|
|
79
|
+
args.lang,
|
|
80
|
+
tone_weight=args.tone_weight,
|
|
81
|
+
device=args.device,
|
|
82
|
+
cache_dir=args.cache_dir,
|
|
83
|
+
en_locale=args.en_locale,
|
|
84
|
+
workers=args.workers,
|
|
85
|
+
)
|
|
86
|
+
hits = index.search_many(
|
|
87
|
+
queries,
|
|
88
|
+
topk=args.topk,
|
|
89
|
+
prefilter=args.prefilter,
|
|
90
|
+
sim_min=args.sim_min,
|
|
91
|
+
workers=args.workers,
|
|
92
|
+
block_size=args.block_size,
|
|
93
|
+
device=args.device,
|
|
94
|
+
cache_dir=args.cache_dir,
|
|
95
|
+
en_locale=args.en_locale,
|
|
96
|
+
)
|
|
97
|
+
rows = [{"query": q, "neighbors": h} for q, h in zip(queries, hits)]
|
|
98
|
+
for row in rows:
|
|
99
|
+
_print_hits(row["query"], row["neighbors"])
|
|
100
|
+
sys.stdout.flush()
|
|
101
|
+
if args.out:
|
|
102
|
+
path = Path(args.out)
|
|
103
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
with path.open("w", encoding="utf-8") as fh:
|
|
105
|
+
for row in rows:
|
|
106
|
+
fh.write(json.dumps(row, ensure_ascii=False))
|
|
107
|
+
fh.write("\n")
|
|
108
|
+
print(f"wrote {len(rows)} rows -> {path}", file=sys.stderr)
|
|
109
|
+
return 0
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
113
|
+
p = argparse.ArgumentParser(
|
|
114
|
+
prog="simphone",
|
|
115
|
+
description="Find phonetically similar words or spans with a feature-weighted edit distance.",
|
|
116
|
+
)
|
|
117
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
118
|
+
|
|
119
|
+
n = sub.add_parser("norm", help="expand spans to their spoken form")
|
|
120
|
+
n.add_argument("--lang", required=True, choices=["vi", "en"])
|
|
121
|
+
n.add_argument("--text", action="append", default=None, help="repeatable span")
|
|
122
|
+
n.add_argument("--queries", default=None, help="file of spans, one per line")
|
|
123
|
+
n.add_argument(
|
|
124
|
+
"--workers",
|
|
125
|
+
type=int,
|
|
126
|
+
default=0,
|
|
127
|
+
help="sea-g2p Rayon threads for Vietnamese (0 = os.cpu_count()). Ignored for English.",
|
|
128
|
+
)
|
|
129
|
+
n.set_defaults(func=cmd_norm)
|
|
130
|
+
|
|
131
|
+
b = sub.add_parser("build", help="phonemize an inventory and save the index")
|
|
132
|
+
b.add_argument("--lang", required=True, choices=["vi", "en"])
|
|
133
|
+
b.add_argument("--inventory", required=True, help="one span per line")
|
|
134
|
+
b.add_argument("--save", required=True, help="directory to write")
|
|
135
|
+
b.add_argument("--tone-weight", type=float, default=0.5)
|
|
136
|
+
b.add_argument("--device", default="cpu", help="English out-of-dictionary G2P device")
|
|
137
|
+
b.add_argument(
|
|
138
|
+
"--workers",
|
|
139
|
+
type=int,
|
|
140
|
+
default=0,
|
|
141
|
+
help="CPU workers for Vietnamese segmentation (0 = os.cpu_count()). "
|
|
142
|
+
"Also sets sea-g2p's Rayon thread count.",
|
|
143
|
+
)
|
|
144
|
+
b.add_argument("--cache-dir", default=None, help="Charsiu model cache (English)")
|
|
145
|
+
b.add_argument("--en-locale", default="eng-us")
|
|
146
|
+
b.set_defaults(func=cmd_build)
|
|
147
|
+
|
|
148
|
+
s = sub.add_parser("search", help="search one or more queries against an inventory")
|
|
149
|
+
s.add_argument("--load", default=None, help="index directory from build")
|
|
150
|
+
s.add_argument("--lang", choices=["vi", "en"], help="required with --inventory")
|
|
151
|
+
s.add_argument("--inventory", default=None, help="build in memory instead of --load")
|
|
152
|
+
s.add_argument("--query", action="append", default=None, help="repeatable span")
|
|
153
|
+
s.add_argument("--queries", default=None, help="file of query spans, one per line")
|
|
154
|
+
s.add_argument("--topk", type=int, default=50)
|
|
155
|
+
s.add_argument("--prefilter", type=int, default=300)
|
|
156
|
+
s.add_argument("--sim-min", type=float, default=0.8)
|
|
157
|
+
s.add_argument("--workers", type=int, default=0, help="0 = os.cpu_count()")
|
|
158
|
+
s.add_argument("--block-size", type=int, default=512)
|
|
159
|
+
s.add_argument("--tone-weight", type=float, default=0.5)
|
|
160
|
+
s.add_argument("--device", default="cpu")
|
|
161
|
+
s.add_argument("--cache-dir", default=None)
|
|
162
|
+
s.add_argument("--en-locale", default="eng-us")
|
|
163
|
+
s.add_argument("--out", default=None, help="JSONL of query rows")
|
|
164
|
+
s.set_defaults(func=cmd_search)
|
|
165
|
+
return p
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def main(argv=None) -> int:
|
|
169
|
+
args = build_parser().parse_args(argv)
|
|
170
|
+
return args.func(args)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
if __name__ == "__main__":
|
|
174
|
+
sys.exit(main())
|