khammoon 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.
khammoon-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
khammoon-0.1.0/NOTICE ADDED
@@ -0,0 +1,18 @@
1
+ khammoon
2
+ Copyright 2026 The khammoon authors
3
+
4
+ The source code in this repository is licensed under the Apache License,
5
+ Version 2.0 (see LICENSE).
6
+
7
+ The trained model weights in khammoon/model/ (model.onnx, weights.npz) are
8
+ licensed separately under Creative Commons Attribution-NonCommercial-ShareAlike
9
+ 4.0 International (see khammoon/model/LICENSE), because the model was trained on
10
+ data released under NonCommercial terms:
11
+ - BEST2009 corpus, NECTEC (CC BY-NC-SA 3.0)
12
+ - WangchanThaiInstruct, VISTEC/AIResearch (per row CC BY-NC 4.0 / CC BY-SA 4.0)
13
+
14
+ This product includes software derived from PyThaiNLP
15
+ (https://github.com/PyThaiNLP/pythainlp), licensed under the Apache License,
16
+ Version 2.0: the Thai Character Cluster rules in khammoon/tcc.py
17
+ (Theeramunkong et al. 2000; TCC by Jakkrit TeCho, grammar by Wittawat
18
+ Jitkrittum, Python code by Korakot Chaovavanich).
@@ -0,0 +1,225 @@
1
+ Metadata-Version: 2.4
2
+ Name: khammoon
3
+ Version: 0.1.0
4
+ Summary: Thai morpheme (คำมูล) segmenter: a 4 MB character model that runs on CPU
5
+ License: Apache-2.0 (code); CC-BY-NC-SA-4.0 (bundled model weights)
6
+ Project-URL: Homepage, https://github.com/warit-s/khammoon-segmenter
7
+ Project-URL: Repository, https://github.com/warit-s/khammoon-segmenter
8
+ Project-URL: Model, https://huggingface.co/typhoon-ai/khammoon
9
+ Project-URL: Data, https://huggingface.co/datasets/typhoon-ai/khammoon-data
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Natural Language :: Thai
13
+ Classifier: Topic :: Text Processing :: Linguistic
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ License-File: NOTICE
18
+ Requires-Dist: numpy>=1.21
19
+ Provides-Extra: onnx
20
+ Requires-Dist: onnxruntime>=1.15; extra == "onnx"
21
+ Provides-Extra: train
22
+ Requires-Dist: torch>=2.1; extra == "train"
23
+ Requires-Dist: huggingface_hub; extra == "train"
24
+ Requires-Dist: onnx; extra == "train"
25
+ Provides-Extra: baselines
26
+ Requires-Dist: pythainlp>=5; extra == "baselines"
27
+ Requires-Dist: attacut; extra == "baselines"
28
+ Requires-Dist: nlpo3; extra == "baselines"
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest; extra == "test"
31
+ Dynamic: license-file
32
+
33
+ # khammoon — Thai morpheme segmenter
34
+
35
+ khammoon splits Thai text into **morphemes** in the sense of Thai grammar (คำมูล, *khammoon*): the
36
+ smallest units that still carry meaning on their own, as defined by the annotation guideline in
37
+ [`linguistics/`](linguistics/).
38
+ It is a 4 MB character-level model that runs on a CPU with nothing but `numpy`; no GPU and no LLM.
39
+
40
+ ```python
41
+ from khammoon import segment
42
+
43
+ segment("นักเรียนโรงเรียนสอนคนตาบอดทำงานขะมักเขม้น")
44
+ # ['นัก', 'เรียน', 'โรง', 'เรียน', 'สอน', 'คน', 'ตา', 'บอด', 'ทำ', 'งาน', 'ขะมัก', 'เขม้น']
45
+ ```
46
+
47
+ ## What a morpheme is
48
+
49
+ Ordinary Thai word segmenters keep compounds together; khammoon splits them down to their
50
+ meaningful parts. `สินค้า` ("goods") is the compound สิน (wealth) + ค้า (trade), so it becomes
51
+ `สิน|ค้า`, whereas `ราคา` ("price") has no meaningful parts (รา + คา) and stays whole. Following
52
+ the guideline, Pali–Sanskrit compounds read back-to-front (`ประวัติศาสตร์`) and loanwords
53
+ (`วิปครีม`) are not split, and foreign-script text is split only at whitespace (`COVID-19`).
54
+
55
+ ## Install
56
+
57
+ ```bash
58
+ pip install . # from this directory; needs only numpy
59
+ pip install ".[onnx]" # adds onnxruntime: about 2.4x faster, identical output
60
+ pip install ".[train]" # to train or evaluate (torch, pythainlp, ...)
61
+ ```
62
+
63
+ | backend | dependencies | speed (1 CPU thread) |
64
+ |---|---|---|
65
+ | `onnx` | numpy + onnxruntime | ~30k characters/s |
66
+ | `numpy` | numpy | ~13k characters/s |
67
+
68
+ The default `backend="auto"` uses `onnx` when onnxruntime is installed and `numpy` otherwise.
69
+ Both backends produce the same segmentation on every sentence of the development set.
70
+
71
+ ## Usage
72
+
73
+ ```python
74
+ from khammoon import Segmenter
75
+
76
+ seg = Segmenter() # loads the bundled model
77
+ seg("ไปที่ www.google.com เลย") # ['ไป', 'ที่', ' ', 'www.google.com', ' ', 'เลย']
78
+ seg.segment_batch(["ข้อความแรก", "ข้อความที่สอง"]) # batching is faster than one call per text
79
+ Segmenter(threshold=0.3) # lower threshold: more boundaries, higher recall
80
+ Segmenter(backend="numpy") # force the pure-numpy backend
81
+ ```
82
+
83
+ ```bash
84
+ khammoon "โรงเรียนสอนคนตาบอด" # โรง|เรียน|สอน|คน|ตา|บอด
85
+ cat corpus.txt | khammoon --sep " " # reads stdin line by line
86
+ ```
87
+
88
+ Guarantees: `"".join(tokens) == text` always holds (characters are never added, removed or
89
+ normalised); every whitespace character is its own token; and boundaries are placed only between
90
+ Thai Character Clusters, so no token is misspelled (for example, none starts with the vowel `า`).
91
+
92
+ ## Results
93
+
94
+ The evaluation set is the **test set**: the Wangchan reference, 2,000 documents segmented by three
95
+ trained annotators following the guideline and adjudicated (Fleiss κ 0.991). It was never used
96
+ during development: not for training, model selection or threshold choice. The metric is
97
+ boundary precision / recall / F1, pooled over all boundaries, ignoring boundaries adjacent to
98
+ whitespace (those are fixed by the input, and the human annotation treats runs of whitespace
99
+ inconsistently). Confidence intervals and the full discussion are in the technical report.
100
+
101
+ | method | precision | recall | F1 |
102
+ |---|---|---|---|
103
+ | PyThaiNLP `newmm` (BEST-style words) | 0.962 | 0.687 | 0.802 |
104
+ | nlpO3 (`newmm` in Rust) | 0.961 | 0.693 | 0.805 |
105
+ | deepcut | 0.972 | 0.875 | 0.921 |
106
+ | AttaCut | 0.981 | 0.874 | 0.925 |
107
+ | syllable segmentation (PyThaiNLP `syllable_tokenize`) | 0.821 | 0.991 | 0.898 |
108
+ | unigram Viterbi over the LLM-label lexicon | 0.975 | 0.881 | 0.925 |
109
+ | Qwen3-30B-A3B two-pass LLM segmenter that produced the training labels | 0.975 | 0.948 | 0.962 |
110
+ | the same BiLSTM trained on the uncorrected LLM labels | 0.977 | 0.948 | 0.962 |
111
+ | **khammoon 0.1.0** | **0.992** | **0.993** | **0.992** |
112
+
113
+ `newmm`, deepcut and AttaCut segment into BEST2009 *words*, not morphemes, so their recall is
114
+ low; the table measures distance to the morpheme definition, not the quality of those tools
115
+ at their own task (`scripts/baselines_test.py`). The Qwen3-30B-A3B row scores the saved outputs of
116
+ the same LLM segmenter that labelled the training text, run on the test set texts
117
+ (`scripts/eval_llm_outputs.py`). khammoon is about 30,000 times smaller than that LLM, runs on a
118
+ CPU, and makes about 5 times fewer errors (1 − F1: 0.008 vs 0.038). Models trained on its output
119
+ perform on par with those trained on word segmenters on POS tagging, NER and sentiment
120
+ classification; see the technical report.
121
+
122
+ The model has ~1.06M parameters (4.2 MB).
123
+
124
+ ## Data
125
+
126
+ All data are released as [`typhoon-ai/khammoon-data`](https://huggingface.co/datasets/typhoon-ai/khammoon-data).
127
+
128
+ | config | source | role |
129
+ |---|---|---|
130
+ | `llm_labelled` | BEST2009 train + WangchanThaiInstruct train, segmented by an LLM (Qwen3-30B-A3B, two passes following the guideline) and then corrected; 180,206 documents, 70M characters | training |
131
+ | `dev` | development set: BEST2009 reference, 2,252 sentences, human-labelled | label correction, fine-tuning, model and threshold selection; split into dev-train (1,484) and dev-val (768), marked `devtrain` / `devval` in the `dev_split` field |
132
+ | `test` | test set: Wangchan reference, 2,000 documents, human-labelled | evaluation only |
133
+
134
+ Training rows whose text also occurs in either human set were removed before training. The
135
+ cross-domain split (news, novels and encyclopedia text for development; instruction data in
136
+ finance, legal, medical and retail for testing) is deliberate.
137
+
138
+ **All of the data is open, for developers and researchers to build on.** Besides the model, we
139
+ release the human-labelled development and test sets (a common benchmark with a fixed protocol), the 70M
140
+ characters of LLM-labelled text with both the original LLM labels and the corrected ones (training
141
+ data for new segmenters, and a record of where an LLM annotator goes wrong), and the LLM's outputs
142
+ on the reference sets (the strongest baseline, reproducible without a GPU). Use them to train your
143
+ own segmenter, compare against ours on the same test set, or study Thai morphology and
144
+ tokenization; the licenses of the source texts apply (see [License](#license)).
145
+
146
+ ## Method
147
+
148
+ 1. **Character tagging.** The model predicts, before every character, whether a boundary
149
+ falls there. Boundaries are allowed only at Thai Character Cluster (TCC) edges and are forced
150
+ at whitespace edges; a boundary is placed where the predicted probability exceeds the
151
+ threshold (0.5).
152
+ 2. **Label correction, round 1.** The LLM systematically under-splits frequent Thai compounds
153
+ (`สินค้า`, `กฎหมาย`, `ข้อมูล`). We build a table of strings that dev-train always
154
+ segments the same way (at least twice) and rewrite every occurrence in the LLM labels to match, and we
155
+ merge foreign-script spans that the guideline keeps whole (`COVID-19`, `People's`) and
156
+ parenthesised heading markers (`(๒)`).
157
+ 3. **Train and fine-tune.** A BiLSTM (character embedding → convolutions with kernels 3/5/7 →
158
+ 2-layer BiLSTM, 256-character windows) is trained on the round-1 labels and fine-tuned on
159
+ dev-train.
160
+ 4. **Label correction, round 2.** The fine-tuned model re-segments the whole LLM-labelled corpus;
161
+ only boundaries between two Thai letters are taken from it, all others keep the round-1
162
+ labels. This spreads the human conventions over the 70M characters of LLM-labelled text.
163
+ 5. **Mixed fine-tuning.** A new model is trained on the round-2 labels and fine-tuned with half
164
+ of every batch from dev-train and half from the LLM-labelled text, so it does not forget what
165
+ the development set lacks (it is 2009 text without `COVID-19` and splits every hyphen). The
166
+ mixing ratio (0% or 50% LLM-labelled data, chosen by a rule fixed beforehand: the largest
167
+ LLM-labelled share whose dev-val F1 is within 0.0005 of the best), the number of steps and the
168
+ threshold were selected on dev-val; the released model was then fine-tuned on the whole
169
+ development set with those values.
170
+ 6. **Export** to ONNX (`model.onnx`) and to raw weights (`weights.npz`) for the numpy backend.
171
+
172
+ | dev-val F1 | before fine-tuning | human-only fine-tuning | 50% LLM-labelled fine-tuning |
173
+ |---|---|---|---|
174
+ | LLM labels after round 1 | 0.9916 | 0.9970 | 0.9957 |
175
+ | LLM labels after round 2 | 0.9955 | 0.9974 | 0.9972 (selected) |
176
+
177
+ Every step can be rerun from the released data; see [`scripts/README.md`](scripts/README.md). The technical report describing this work is linked from the model card on Hugging Face.
178
+
179
+ ## Limitations
180
+
181
+ - Only one cross-domain test set; there is no human-annotated set for social-media or general
182
+ web text yet.
183
+ - Most remaining errors are rare proper names and transliterations, and Pali–Sanskrit
184
+ compounds that are over-split.
185
+ - The test set was evaluated three times. Each change of method was motivated by the
186
+ development set or by examples outside the test set, never by test results: (1) F1 0.9916;
187
+ (2) after fixing an inference bug found through a README example (text-final characters were
188
+ mis-segmented because training documents are newline-delimited, and batches contained padding),
189
+ 0.9917; (3) after label-correction round 2 and mixed fine-tuning (prompted by `COVID-19` being
190
+ split), P 0.9917 / R 0.9928 / F1 0.9923, the numbers in the table.
191
+ - The developer had seen error analyses on the Wangchan reference in an earlier experiment,
192
+ before this split was fixed. The foreign-script merge rule follows Step 2 of the guideline but
193
+ may have been influenced by what was seen.
194
+
195
+ ## License
196
+
197
+ | part | license |
198
+ |---|---|
199
+ | code (all `.py` files, scripts, tests) | [Apache-2.0](LICENSE) |
200
+ | model weights (`khammoon/model/model.onnx`, `weights.npz`) | [CC BY-NC-SA 4.0](khammoon/model/LICENSE); no commercial use, because the training data carry NonCommercial terms |
201
+ | data (`typhoon-ai/khammoon-data`) | per row, inherited from the source: CC BY-NC-SA 3.0 (BEST2009), CC BY-NC 4.0 or CC BY-SA 4.0 (WangchanThaiInstruct) |
202
+
203
+ The wheel installed by pip bundles the model weights, so that part falls under CC BY-NC-SA 4.0;
204
+ see [NOTICE](NOTICE).
205
+
206
+ ## Citation
207
+
208
+ If you use khammoon, the guideline or the data, please cite the technical report:
209
+
210
+ ```bibtex
211
+ @techreport{khammoon2026,
212
+ title = {khammoon: From a Linguistic Guideline to a Thai Morpheme Segmenter},
213
+ author = {Sirichotedumrong, Warit and Na-Thalang, Adisai and Wittayasakpan, Chanakan and
214
+ Phatcharoen, Kritsadha and Pipatanakul, Kunat},
215
+ institution = {Typhoon, SCB DataX},
216
+ year = {2026},
217
+ url = {https://github.com/warit-s/khammoon-segmenter}
218
+ }
219
+ ```
220
+
221
+ ## Credits
222
+
223
+ TCC rules ported from [PyThaiNLP](https://github.com/PyThaiNLP/pythainlp) (Apache-2.0;
224
+ Theeramunkong et al. 2000). Training data from the BEST2009 corpus (NECTEC) and
225
+ WangchanThaiInstruct (VISTEC/AIResearch).
@@ -0,0 +1,193 @@
1
+ # khammoon — Thai morpheme segmenter
2
+
3
+ khammoon splits Thai text into **morphemes** in the sense of Thai grammar (คำมูล, *khammoon*): the
4
+ smallest units that still carry meaning on their own, as defined by the annotation guideline in
5
+ [`linguistics/`](linguistics/).
6
+ It is a 4 MB character-level model that runs on a CPU with nothing but `numpy`; no GPU and no LLM.
7
+
8
+ ```python
9
+ from khammoon import segment
10
+
11
+ segment("นักเรียนโรงเรียนสอนคนตาบอดทำงานขะมักเขม้น")
12
+ # ['นัก', 'เรียน', 'โรง', 'เรียน', 'สอน', 'คน', 'ตา', 'บอด', 'ทำ', 'งาน', 'ขะมัก', 'เขม้น']
13
+ ```
14
+
15
+ ## What a morpheme is
16
+
17
+ Ordinary Thai word segmenters keep compounds together; khammoon splits them down to their
18
+ meaningful parts. `สินค้า` ("goods") is the compound สิน (wealth) + ค้า (trade), so it becomes
19
+ `สิน|ค้า`, whereas `ราคา` ("price") has no meaningful parts (รา + คา) and stays whole. Following
20
+ the guideline, Pali–Sanskrit compounds read back-to-front (`ประวัติศาสตร์`) and loanwords
21
+ (`วิปครีม`) are not split, and foreign-script text is split only at whitespace (`COVID-19`).
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pip install . # from this directory; needs only numpy
27
+ pip install ".[onnx]" # adds onnxruntime: about 2.4x faster, identical output
28
+ pip install ".[train]" # to train or evaluate (torch, pythainlp, ...)
29
+ ```
30
+
31
+ | backend | dependencies | speed (1 CPU thread) |
32
+ |---|---|---|
33
+ | `onnx` | numpy + onnxruntime | ~30k characters/s |
34
+ | `numpy` | numpy | ~13k characters/s |
35
+
36
+ The default `backend="auto"` uses `onnx` when onnxruntime is installed and `numpy` otherwise.
37
+ Both backends produce the same segmentation on every sentence of the development set.
38
+
39
+ ## Usage
40
+
41
+ ```python
42
+ from khammoon import Segmenter
43
+
44
+ seg = Segmenter() # loads the bundled model
45
+ seg("ไปที่ www.google.com เลย") # ['ไป', 'ที่', ' ', 'www.google.com', ' ', 'เลย']
46
+ seg.segment_batch(["ข้อความแรก", "ข้อความที่สอง"]) # batching is faster than one call per text
47
+ Segmenter(threshold=0.3) # lower threshold: more boundaries, higher recall
48
+ Segmenter(backend="numpy") # force the pure-numpy backend
49
+ ```
50
+
51
+ ```bash
52
+ khammoon "โรงเรียนสอนคนตาบอด" # โรง|เรียน|สอน|คน|ตา|บอด
53
+ cat corpus.txt | khammoon --sep " " # reads stdin line by line
54
+ ```
55
+
56
+ Guarantees: `"".join(tokens) == text` always holds (characters are never added, removed or
57
+ normalised); every whitespace character is its own token; and boundaries are placed only between
58
+ Thai Character Clusters, so no token is misspelled (for example, none starts with the vowel `า`).
59
+
60
+ ## Results
61
+
62
+ The evaluation set is the **test set**: the Wangchan reference, 2,000 documents segmented by three
63
+ trained annotators following the guideline and adjudicated (Fleiss κ 0.991). It was never used
64
+ during development: not for training, model selection or threshold choice. The metric is
65
+ boundary precision / recall / F1, pooled over all boundaries, ignoring boundaries adjacent to
66
+ whitespace (those are fixed by the input, and the human annotation treats runs of whitespace
67
+ inconsistently). Confidence intervals and the full discussion are in the technical report.
68
+
69
+ | method | precision | recall | F1 |
70
+ |---|---|---|---|
71
+ | PyThaiNLP `newmm` (BEST-style words) | 0.962 | 0.687 | 0.802 |
72
+ | nlpO3 (`newmm` in Rust) | 0.961 | 0.693 | 0.805 |
73
+ | deepcut | 0.972 | 0.875 | 0.921 |
74
+ | AttaCut | 0.981 | 0.874 | 0.925 |
75
+ | syllable segmentation (PyThaiNLP `syllable_tokenize`) | 0.821 | 0.991 | 0.898 |
76
+ | unigram Viterbi over the LLM-label lexicon | 0.975 | 0.881 | 0.925 |
77
+ | Qwen3-30B-A3B two-pass LLM segmenter that produced the training labels | 0.975 | 0.948 | 0.962 |
78
+ | the same BiLSTM trained on the uncorrected LLM labels | 0.977 | 0.948 | 0.962 |
79
+ | **khammoon 0.1.0** | **0.992** | **0.993** | **0.992** |
80
+
81
+ `newmm`, deepcut and AttaCut segment into BEST2009 *words*, not morphemes, so their recall is
82
+ low; the table measures distance to the morpheme definition, not the quality of those tools
83
+ at their own task (`scripts/baselines_test.py`). The Qwen3-30B-A3B row scores the saved outputs of
84
+ the same LLM segmenter that labelled the training text, run on the test set texts
85
+ (`scripts/eval_llm_outputs.py`). khammoon is about 30,000 times smaller than that LLM, runs on a
86
+ CPU, and makes about 5 times fewer errors (1 − F1: 0.008 vs 0.038). Models trained on its output
87
+ perform on par with those trained on word segmenters on POS tagging, NER and sentiment
88
+ classification; see the technical report.
89
+
90
+ The model has ~1.06M parameters (4.2 MB).
91
+
92
+ ## Data
93
+
94
+ All data are released as [`typhoon-ai/khammoon-data`](https://huggingface.co/datasets/typhoon-ai/khammoon-data).
95
+
96
+ | config | source | role |
97
+ |---|---|---|
98
+ | `llm_labelled` | BEST2009 train + WangchanThaiInstruct train, segmented by an LLM (Qwen3-30B-A3B, two passes following the guideline) and then corrected; 180,206 documents, 70M characters | training |
99
+ | `dev` | development set: BEST2009 reference, 2,252 sentences, human-labelled | label correction, fine-tuning, model and threshold selection; split into dev-train (1,484) and dev-val (768), marked `devtrain` / `devval` in the `dev_split` field |
100
+ | `test` | test set: Wangchan reference, 2,000 documents, human-labelled | evaluation only |
101
+
102
+ Training rows whose text also occurs in either human set were removed before training. The
103
+ cross-domain split (news, novels and encyclopedia text for development; instruction data in
104
+ finance, legal, medical and retail for testing) is deliberate.
105
+
106
+ **All of the data is open, for developers and researchers to build on.** Besides the model, we
107
+ release the human-labelled development and test sets (a common benchmark with a fixed protocol), the 70M
108
+ characters of LLM-labelled text with both the original LLM labels and the corrected ones (training
109
+ data for new segmenters, and a record of where an LLM annotator goes wrong), and the LLM's outputs
110
+ on the reference sets (the strongest baseline, reproducible without a GPU). Use them to train your
111
+ own segmenter, compare against ours on the same test set, or study Thai morphology and
112
+ tokenization; the licenses of the source texts apply (see [License](#license)).
113
+
114
+ ## Method
115
+
116
+ 1. **Character tagging.** The model predicts, before every character, whether a boundary
117
+ falls there. Boundaries are allowed only at Thai Character Cluster (TCC) edges and are forced
118
+ at whitespace edges; a boundary is placed where the predicted probability exceeds the
119
+ threshold (0.5).
120
+ 2. **Label correction, round 1.** The LLM systematically under-splits frequent Thai compounds
121
+ (`สินค้า`, `กฎหมาย`, `ข้อมูล`). We build a table of strings that dev-train always
122
+ segments the same way (at least twice) and rewrite every occurrence in the LLM labels to match, and we
123
+ merge foreign-script spans that the guideline keeps whole (`COVID-19`, `People's`) and
124
+ parenthesised heading markers (`(๒)`).
125
+ 3. **Train and fine-tune.** A BiLSTM (character embedding → convolutions with kernels 3/5/7 →
126
+ 2-layer BiLSTM, 256-character windows) is trained on the round-1 labels and fine-tuned on
127
+ dev-train.
128
+ 4. **Label correction, round 2.** The fine-tuned model re-segments the whole LLM-labelled corpus;
129
+ only boundaries between two Thai letters are taken from it, all others keep the round-1
130
+ labels. This spreads the human conventions over the 70M characters of LLM-labelled text.
131
+ 5. **Mixed fine-tuning.** A new model is trained on the round-2 labels and fine-tuned with half
132
+ of every batch from dev-train and half from the LLM-labelled text, so it does not forget what
133
+ the development set lacks (it is 2009 text without `COVID-19` and splits every hyphen). The
134
+ mixing ratio (0% or 50% LLM-labelled data, chosen by a rule fixed beforehand: the largest
135
+ LLM-labelled share whose dev-val F1 is within 0.0005 of the best), the number of steps and the
136
+ threshold were selected on dev-val; the released model was then fine-tuned on the whole
137
+ development set with those values.
138
+ 6. **Export** to ONNX (`model.onnx`) and to raw weights (`weights.npz`) for the numpy backend.
139
+
140
+ | dev-val F1 | before fine-tuning | human-only fine-tuning | 50% LLM-labelled fine-tuning |
141
+ |---|---|---|---|
142
+ | LLM labels after round 1 | 0.9916 | 0.9970 | 0.9957 |
143
+ | LLM labels after round 2 | 0.9955 | 0.9974 | 0.9972 (selected) |
144
+
145
+ Every step can be rerun from the released data; see [`scripts/README.md`](scripts/README.md). The technical report describing this work is linked from the model card on Hugging Face.
146
+
147
+ ## Limitations
148
+
149
+ - Only one cross-domain test set; there is no human-annotated set for social-media or general
150
+ web text yet.
151
+ - Most remaining errors are rare proper names and transliterations, and Pali–Sanskrit
152
+ compounds that are over-split.
153
+ - The test set was evaluated three times. Each change of method was motivated by the
154
+ development set or by examples outside the test set, never by test results: (1) F1 0.9916;
155
+ (2) after fixing an inference bug found through a README example (text-final characters were
156
+ mis-segmented because training documents are newline-delimited, and batches contained padding),
157
+ 0.9917; (3) after label-correction round 2 and mixed fine-tuning (prompted by `COVID-19` being
158
+ split), P 0.9917 / R 0.9928 / F1 0.9923, the numbers in the table.
159
+ - The developer had seen error analyses on the Wangchan reference in an earlier experiment,
160
+ before this split was fixed. The foreign-script merge rule follows Step 2 of the guideline but
161
+ may have been influenced by what was seen.
162
+
163
+ ## License
164
+
165
+ | part | license |
166
+ |---|---|
167
+ | code (all `.py` files, scripts, tests) | [Apache-2.0](LICENSE) |
168
+ | model weights (`khammoon/model/model.onnx`, `weights.npz`) | [CC BY-NC-SA 4.0](khammoon/model/LICENSE); no commercial use, because the training data carry NonCommercial terms |
169
+ | data (`typhoon-ai/khammoon-data`) | per row, inherited from the source: CC BY-NC-SA 3.0 (BEST2009), CC BY-NC 4.0 or CC BY-SA 4.0 (WangchanThaiInstruct) |
170
+
171
+ The wheel installed by pip bundles the model weights, so that part falls under CC BY-NC-SA 4.0;
172
+ see [NOTICE](NOTICE).
173
+
174
+ ## Citation
175
+
176
+ If you use khammoon, the guideline or the data, please cite the technical report:
177
+
178
+ ```bibtex
179
+ @techreport{khammoon2026,
180
+ title = {khammoon: From a Linguistic Guideline to a Thai Morpheme Segmenter},
181
+ author = {Sirichotedumrong, Warit and Na-Thalang, Adisai and Wittayasakpan, Chanakan and
182
+ Phatcharoen, Kritsadha and Pipatanakul, Kunat},
183
+ institution = {Typhoon, SCB DataX},
184
+ year = {2026},
185
+ url = {https://github.com/warit-s/khammoon-segmenter}
186
+ }
187
+ ```
188
+
189
+ ## Credits
190
+
191
+ TCC rules ported from [PyThaiNLP](https://github.com/PyThaiNLP/pythainlp) (Apache-2.0;
192
+ Theeramunkong et al. 2000). Training data from the BEST2009 corpus (NECTEC) and
193
+ WangchanThaiInstruct (VISTEC/AIResearch).
@@ -0,0 +1,5 @@
1
+ """khammoon — Thai morpheme (คำมูล) segmentation with a small CPU model."""
2
+ from .segmenter import Segmenter, segment
3
+
4
+ __version__ = "0.1.0"
5
+ __all__ = ["Segmenter", "segment", "__version__"]