kham-core 0.8.0

Pure Rust Thai word segmentation engine — no_std compatible
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Thai keyword extraction using TF × inverse-corpus-frequency (TF-IDF proxy).
//!
//! [`KeyExtractor`] segments text with the built-in tokenizer, discards
//! stopwords and single-character tokens, then ranks content words by how
//! often they appear in the document relative to their frequency in the Thai
//! National Corpus (TNC).
//!
//! The scoring formula uses only basic `f32` arithmetic (no transcendentals),
//! keeping the module `no_std` compatible:
//!
//! ```text
//! TF(t)        = occurrences(t, doc) / total_content_tokens(doc)
//! IDF_proxy(t) = (max_tnc_freq + 1) / (tnc_freq(t) + 1)
//! score(t)     = TF(t) × IDF_proxy(t)
//! ```
//!
//! Words absent from TNC receive the maximum IDF weight — they are likely
//! domain-specific and therefore the most distinctive keywords.
//!
//! ```rust
//! use kham_core::keyword::KeyExtractor;
//!
//! let kex = KeyExtractor::builtin();
//! let kws = kex.extract("การพัฒนาซอฟต์แวร์เป็นสิ่งสำคัญในยุคดิจิทัล", 5);
//! assert!(!kws.is_empty());
//! // Results are always sorted by score descending
//! for pair in kws.windows(2) {
//!     assert!(pair[0].score >= pair[1].score);
//! }
//! ```

use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;

use crate::freq::FreqMap;
use crate::segmenter::Tokenizer;
use crate::stopwords::StopwordSet;
use crate::token::TokenKind;

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// A keyword extracted from a document with its relevance score.
///
/// Scores are computed as `TF × IDF_proxy`:
/// - **TF**: how often the word appears in this document (normalized by total
///   content tokens)
/// - **IDF_proxy**: `(max_tnc_freq + 1) / (tnc_freq + 1)` — rare corpus
///   words receive a higher weight than common function words
///
/// Keywords are returned sorted by `score` descending.
#[derive(Debug, Clone, PartialEq)]
pub struct Keyword {
    /// The word text.
    pub word: String,
    /// TF × IDF_proxy score. Higher means more document-distinctive.
    pub score: f32,
    /// Raw occurrence count of this word in the document.
    pub count: usize,
}

/// Thai keyword extractor using TF × inverse-corpus-frequency scoring.
///
/// Backed by the built-in 62k-word tokenizer, the TNC frequency table
/// (~106k entries), and the Thai stopword list (~1 029 entries).
///
/// Construction is O(n) in the TNC table size — reuse the returned instance
/// rather than calling [`builtin()`](KeyExtractor::builtin) on every query.
///
/// # Filtering rules
///
/// A token is eligible as a keyword when **all** of the following hold:
/// 1. Kind is `Thai`, `Latin`, `Number`, or `Named` (whitespace, punctuation,
///    emoji, and unknown tokens are always skipped)
/// 2. Character length ≥ 2 (single-char tokens are too coarse to be keywords)
/// 3. Not in the built-in Thai stopword list
///
/// # Examples
///
/// ```rust
/// use kham_core::keyword::KeyExtractor;
///
/// let kex = KeyExtractor::builtin();
///
/// // Rare domain-specific word outranks a common word
/// // "ซอฟต์แวร์" (software) is rare in TNC and should appear as a top keyword
/// let kws = kex.extract("นักพัฒนาซอฟต์แวร์เขียนซอฟต์แวร์ทุกวัน", 5);
/// assert!(kws.iter().any(|k| k.word == "ซอฟต์แวร์"));
/// ```
pub struct KeyExtractor {
    tokenizer: Tokenizer,
    freq: FreqMap,
    stops: StopwordSet,
    max_corpus_freq: u32,
}

impl KeyExtractor {
    /// Create a keyword extractor backed by the built-in tokenizer, TNC
    /// frequency table, and Thai stopword list.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kham_core::keyword::KeyExtractor;
    ///
    /// let kex = KeyExtractor::builtin();
    /// assert!(!kex.extract("กินข้าวกับปลา", 5).is_empty());
    /// ```
    pub fn builtin() -> Self {
        let freq = FreqMap::builtin();
        let max_corpus_freq = freq.max_freq();
        Self {
            tokenizer: Tokenizer::new(),
            freq,
            stops: StopwordSet::builtin(),
            max_corpus_freq,
        }
    }

    /// Extract up to `max_n` keywords from `text`, ranked by TF-IDF score.
    ///
    /// Returns an empty `Vec` when `text` is empty, contains no eligible
    /// content words, or `max_n` is zero.
    ///
    /// Ties in score are broken alphabetically so results are deterministic.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use kham_core::keyword::KeyExtractor;
    ///
    /// let kex = KeyExtractor::builtin();
    ///
    /// // Edge cases
    /// assert!(kex.extract("", 5).is_empty());
    /// assert!(kex.extract("กินข้าวกับปลา", 0).is_empty());
    ///
    /// // Score order is non-increasing
    /// let kws = kex.extract("การเรียนภาษาโปรแกรมมิ่งเป็นทักษะสำคัญสำหรับนักพัฒนา", 10);
    /// for pair in kws.windows(2) {
    ///     assert!(
    ///         pair[0].score >= pair[1].score,
    ///         "out-of-order: {:?} before {:?}", pair[0], pair[1]
    ///     );
    /// }
    /// ```
    pub fn extract(&self, text: &str, max_n: usize) -> Vec<Keyword> {
        if text.is_empty() || max_n == 0 {
            return Vec::new();
        }

        let tokens = self.tokenizer.segment(text);

        // Count all content tokens for the TF denominator.
        // Count candidate tokens (non-stop, len ≥ 2) for keyword scoring.
        let mut total_content: usize = 0;
        let mut counts: BTreeMap<String, usize> = BTreeMap::new();

        for token in &tokens {
            match token.kind {
                TokenKind::Whitespace
                | TokenKind::Punctuation
                | TokenKind::Emoji
                | TokenKind::Unknown => continue,
                _ => {}
            }

            total_content += 1;

            // Single-char tokens and stopwords are counted in the denominator
            // but excluded from the keyword candidates.
            if token.text.chars().count() < 2 || self.stops.contains(token.text) {
                continue;
            }

            *counts.entry(String::from(token.text)).or_insert(0) += 1;
        }

        if total_content == 0 || counts.is_empty() {
            return Vec::new();
        }

        let total_f = total_content as f32;
        // IDF numerator: max corpus frequency + 1 (avoids div-by-zero for max entry).
        let idf_num = self.max_corpus_freq as f32 + 1.0;

        let mut results: Vec<Keyword> = counts
            .into_iter()
            .map(|(word, count)| {
                let tf = count as f32 / total_f;
                let corpus_freq = self.freq.get(&word);
                let idf = idf_num / (corpus_freq as f32 + 1.0);
                Keyword {
                    word,
                    score: tf * idf,
                    count,
                }
            })
            .collect();

        // Sort: score DESC, word ASC for deterministic ties
        results.sort_unstable_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(core::cmp::Ordering::Equal)
                .then(a.word.cmp(&b.word))
        });

        results.truncate(max_n);
        results
    }

    /// Extract up to `max_n` multi-word keyphrases (bigrams and trigrams) from
    /// `text`, ranked by TF × average-IDF score.
    ///
    /// Phrases are formed from adjacent content tokens — tokens that pass the
    /// same eligibility rules as [`extract`]: non-whitespace, non-punctuation,
    /// non-emoji, non-unknown, character length ≥ 2, and not a stopword. A
    /// bigram is two such consecutive tokens; a trigram is three.
    ///
    /// The IDF for a phrase is the average IDF of its constituent words.
    ///
    /// Returns an empty `Vec` when `text` has fewer than 2 eligible tokens or
    /// `max_n` is zero.
    ///
    /// # Example
    /// ```rust
    /// use kham_core::keyword::KeyExtractor;
    ///
    /// let kex = KeyExtractor::builtin();
    /// let phrases = kex.extract_phrases("นักพัฒนาซอฟต์แวร์เขียนโค้ดทุกวัน", 5);
    /// // Each keyword word field contains a space-separated phrase
    /// assert!(phrases.iter().all(|k| k.word.contains(' ')));
    /// ```
    pub fn extract_phrases(&self, text: &str, max_n: usize) -> Vec<Keyword> {
        if text.is_empty() || max_n == 0 {
            return Vec::new();
        }

        let tokens = self.tokenizer.segment(text);

        // Collect eligible content token texts
        let content: Vec<&str> = tokens
            .iter()
            .filter(|t| {
                !matches!(
                    t.kind,
                    TokenKind::Whitespace
                        | TokenKind::Punctuation
                        | TokenKind::Emoji
                        | TokenKind::Unknown
                )
            })
            .filter(|t| t.text.chars().count() >= 2 && !self.stops.contains(t.text))
            .map(|t| t.text)
            .collect();

        if content.len() < 2 {
            return Vec::new();
        }

        let total_f = content.len() as f32;
        let idf_num = self.max_corpus_freq as f32 + 1.0;

        let mut counts: BTreeMap<String, usize> = BTreeMap::new();

        // Bigrams
        for w in content.windows(2) {
            let phrase = alloc::format!("{} {}", w[0], w[1]);
            *counts.entry(phrase).or_insert(0) += 1;
        }
        // Trigrams
        for w in content.windows(3) {
            let phrase = alloc::format!("{} {} {}", w[0], w[1], w[2]);
            *counts.entry(phrase).or_insert(0) += 1;
        }

        let mut results: Vec<Keyword> = counts
            .into_iter()
            .map(|(phrase, count)| {
                let tf = count as f32 / total_f;
                let parts: Vec<&str> = phrase.split(' ').collect();
                let avg_idf = parts
                    .iter()
                    .map(|w| idf_num / (self.freq.get(w) as f32 + 1.0))
                    .sum::<f32>()
                    / parts.len() as f32;
                Keyword {
                    word: phrase,
                    score: tf * avg_idf,
                    count,
                }
            })
            .collect();

        results.sort_unstable_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(core::cmp::Ordering::Equal)
                .then(a.word.cmp(&b.word))
        });
        results.truncate(max_n);
        results
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn kex() -> KeyExtractor {
        KeyExtractor::builtin()
    }

    // ── edge cases ──────────────────────────────────────────────────────────

    #[test]
    fn empty_text_returns_empty() {
        assert!(kex().extract("", 5).is_empty());
    }

    #[test]
    fn zero_max_n_returns_empty() {
        assert!(kex().extract("กินข้าวกับปลา", 0).is_empty());
    }

    #[test]
    fn only_stopwords_returns_empty() {
        // "และ" "หรือ" "ของ" are all stopwords
        assert!(kex().extract("และหรือของ", 5).is_empty());
    }

    #[test]
    fn only_single_chars_returns_empty() {
        // Single Thai characters are below the min-length threshold
        assert!(kex().extract("ก ข ค ง", 5).is_empty());
    }

    // ── result properties ────────────────────────────────────────────────────

    #[test]
    fn respects_max_n() {
        let kws = kex().extract("การพัฒนาซอฟต์แวร์เป็นสิ่งสำคัญในยุคดิจิทัลสำหรับนักพัฒนา", 3);
        assert!(kws.len() <= 3, "expected ≤ 3 results, got {}", kws.len());
    }

    #[test]
    fn results_sorted_by_score_descending() {
        let kws = kex().extract("การเรียนภาษาโปรแกรมมิ่งเป็นทักษะสำคัญสำหรับนักพัฒนาซอฟต์แวร์", 10);
        for pair in kws.windows(2) {
            assert!(
                pair[0].score >= pair[1].score,
                "sort order violated: {:?} before {:?}",
                pair[0],
                pair[1]
            );
        }
    }

    #[test]
    fn count_reflects_occurrences() {
        // "ซอฟต์แวร์" appears 3 times in the input
        let kws = kex().extract("นักพัฒนาซอฟต์แวร์เขียนซอฟต์แวร์และทดสอบซอฟต์แวร์ทุกวัน", 10);
        let sw = kws.iter().find(|k| k.word == "ซอฟต์แวร์");
        assert!(sw.is_some(), "expected ซอฟต์แวร์ in keywords; got: {kws:?}");
        assert_eq!(sw.unwrap().count, 3, "expected count=3 for ซอฟต์แวร์");
    }

    #[test]
    fn stopwords_not_in_results() {
        let kws = kex().extract("กินข้าวกับปลาและดื่มน้ำ", 20);
        // "กับ" and "และ" are stopwords and must not appear
        assert!(
            kws.iter().all(|k| k.word != "กับ" && k.word != "และ"),
            "stopword found in results: {kws:?}"
        );
    }

    #[test]
    fn all_scores_positive() {
        let kws = kex().extract("การพัฒนาซอฟต์แวร์ต้องการทักษะและประสบการณ์", 10);
        assert!(
            kws.iter().all(|k| k.score > 0.0),
            "expected all scores > 0; got: {kws:?}"
        );
    }

    // ── IDF weighting ────────────────────────────────────────────────────────

    #[test]
    fn rare_word_outranks_common_word_with_same_count() {
        // Both appear once; rare corpus word should score higher.
        // "ไดโนเสาร์" (dinosaur) is rare in TNC; "คน" (person) is very common.
        let kws = kex().extract("ไดโนเสาร์กินคน", 10);
        let rare = kws.iter().find(|k| k.word == "ไดโนเสาร์");
        let common = kws.iter().find(|k| k.word == "คน");
        if let (Some(r), Some(c)) = (rare, common) {
            assert!(
                r.score > c.score,
                "expected ไดโนเสาร์ ({}) to outscore คน ({})",
                r.score,
                c.score
            );
        }
    }

    #[test]
    fn repeated_word_scores_higher_than_single_occurrence() {
        // "ซอฟต์แวร์" ×3 vs "นักพัฒนา" ×1 — same IDF, TF difference wins
        let kws = kex().extract("นักพัฒนาซอฟต์แวร์เขียนซอฟต์แวร์และทดสอบซอฟต์แวร์", 10);
        let sw = kws.iter().find(|k| k.word == "ซอฟต์แวร์");
        let dev = kws.iter().find(|k| k.word == "นักพัฒนา");
        if let (Some(s), Some(d)) = (sw, dev) {
            assert!(
                s.score > d.score,
                "expected ซอฟต์แวร์ (×3, score {}) > นักพัฒนา (×1, score {})",
                s.score,
                d.score
            );
        }
    }

    // ── mixed script ─────────────────────────────────────────────────────────

    #[test]
    fn latin_tokens_included_as_candidates() {
        let kws = kex().extract("เขียน Python และใช้ Python ทุกวัน", 10);
        // "Python" appears twice and is a Latin token — must be in results
        let py = kws.iter().find(|k| k.word == "Python");
        assert!(py.is_some(), "expected Python in keywords; got: {kws:?}");
        assert_eq!(py.unwrap().count, 2);
    }

    #[test]
    fn punctuation_not_in_results() {
        let kws = kex().extract("กินข้าว, ดื่มน้ำ. นอนหลับ!", 20);
        assert!(
            kws.iter()
                .all(|k| !k.word.chars().all(|c| c.is_ascii_punctuation())),
            "punctuation token found in results: {kws:?}"
        );
    }

    // extract_phrases tests ----------------------------------------------------

    #[test]
    fn extract_phrases_empty_input() {
        assert!(kex().extract_phrases("", 5).is_empty());
    }

    #[test]
    fn extract_phrases_contains_space() {
        let phrases = kex().extract_phrases("นักพัฒนาซอฟต์แวร์เขียนโค้ดทุกวัน", 5);
        assert!(
            phrases.iter().all(|k| k.word.contains(' ')),
            "all phrases should contain a space; got: {phrases:?}"
        );
    }

    #[test]
    fn extract_phrases_score_order() {
        let phrases = kex().extract_phrases("การพัฒนาซอฟต์แวร์เป็นสิ่งสำคัญในยุคดิจิทัลสำหรับนักพัฒนา", 10);
        for pair in phrases.windows(2) {
            assert!(
                pair[0].score >= pair[1].score,
                "sort order violated: {:?} before {:?}",
                pair[0],
                pair[1]
            );
        }
    }
}