underthesea_core 3.3.1

Underthesea Core
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
extern crate pyo3;
extern crate regex;

use pyo3::prelude::*;
use pyo3::types::PyModule;
use std::collections::HashSet;

pub mod classifier;
pub mod crf;
pub mod fasttext;
pub mod featurizers;
pub mod lr;
pub mod preprocessor;
pub mod svm;
pub mod text;

// Re-export CRF types
use crf::model::CRFModel;
use crf::serialization::{CRFFormat, ModelLoader, ModelSaver};
use crf::tagger::CRFTagger;
use crf::trainer::{CRFTrainer as RustCRFTrainer, LossFunction, TrainerConfig, TrainingInstance};

// Re-export LR types
use lr::model::LRModel;
use lr::predictor::LRClassifier;
use lr::serialization::{LRFormat, LRModelLoader, LRModelSaver};
use lr::trainer::{
    LRTrainer as RustLRTrainer, TrainerConfig as LRTrainerConfig,
    TrainingInstance as LRTrainingInstance,
};

// Re-export Text types
use text::tfidf::{TfIdfConfig, TfIdfVectorizer};

// Re-export SVM types
use svm::LinearSVC;

// Re-export Classifier types
use classifier::{Label, Sentence, TextClassifier};

// Re-export Preprocessor types
use preprocessor::TextPreprocessor;

#[pyclass]
pub struct CRFFeaturizer {
    pub object: featurizers::CRFFeaturizer,
}

#[pymethods]
impl CRFFeaturizer {
    #[new]
    pub fn new(feature_configs: Vec<String>, dictionary: HashSet<String>) -> PyResult<Self> {
        Ok(CRFFeaturizer {
            object: featurizers::CRFFeaturizer::new(feature_configs, dictionary),
        })
    }

    pub fn process(
        self_: PyRef<Self>,
        sentences: Vec<Vec<Vec<String>>>,
    ) -> PyResult<Vec<Vec<Vec<String>>>> {
        let output = self_.object.process(sentences);
        Ok(output)
    }
}

// ============================================================================
// Python bindings for CRF classes
// ============================================================================

/// Python wrapper for CRF Model
#[pyclass(name = "CRFModel")]
pub struct PyCRFModel {
    model: CRFModel,
}

#[pymethods]
impl PyCRFModel {
    /// Create a new empty CRF model
    #[new]
    pub fn new() -> PyResult<Self> {
        Ok(Self {
            model: CRFModel::new(),
        })
    }

    /// Create a model with predefined labels
    #[staticmethod]
    pub fn with_labels(labels: Vec<String>) -> PyResult<Self> {
        Ok(Self {
            model: CRFModel::with_labels(labels),
        })
    }

    /// Get the number of labels
    #[getter]
    pub fn num_labels(&self) -> usize {
        self.model.num_labels
    }

    /// Get the number of attributes
    #[getter]
    pub fn num_attributes(&self) -> usize {
        self.model.num_attributes
    }

    /// Get the number of state features
    pub fn num_state_features(&self) -> usize {
        self.model.num_state_features()
    }

    /// Get the number of transition features
    pub fn num_transition_features(&self) -> usize {
        self.model.num_transition_features()
    }

    /// Get all label names
    pub fn get_labels(&self) -> Vec<String> {
        self.model.labels.labels().to_vec()
    }

    /// Save the model to a file in CRFsuite format (compatible with python-crfsuite)
    pub fn save(&self, path: String) -> PyResult<()> {
        let saver = ModelSaver::new();
        saver
            .save(&self.model, path, CRFFormat::CRFsuite)
            .map_err(pyo3::exceptions::PyIOError::new_err)
    }

    /// Load a model from a file
    #[staticmethod]
    pub fn load(path: String) -> PyResult<Self> {
        let loader = ModelLoader::new();
        let model = loader
            .load(path, CRFFormat::Auto)
            .map_err(pyo3::exceptions::PyIOError::new_err)?;
        Ok(Self { model })
    }

    /// Get the L2 norm squared of all weights
    pub fn l2_norm_squared(&self) -> f64 {
        self.model.l2_norm_squared()
    }

    /// Get the L1 norm of all weights
    pub fn l1_norm(&self) -> f64 {
        self.model.l1_norm()
    }

    fn __repr__(&self) -> String {
        format!(
            "CRFModel(num_labels={}, num_attributes={}, state_features={}, transition_features={})",
            self.model.num_labels,
            self.model.num_attributes,
            self.model.num_state_features(),
            self.model.num_transition_features()
        )
    }
}

/// Python wrapper for CRF Tagger
#[pyclass(name = "CRFTagger")]
pub struct PyCRFTagger {
    tagger: CRFTagger,
}

#[pymethods]
impl PyCRFTagger {
    /// Create a new tagger with an empty model
    #[new]
    pub fn new() -> PyResult<Self> {
        Ok(Self {
            tagger: CRFTagger::new(),
        })
    }

    /// Create a tagger from a model
    #[staticmethod]
    pub fn from_model(model: &PyCRFModel) -> PyResult<Self> {
        Ok(Self {
            tagger: CRFTagger::from_model(model.model.clone()),
        })
    }

    /// Load a model from file
    pub fn load(&mut self, path: String) -> PyResult<()> {
        self.tagger
            .load(path)
            .map_err(pyo3::exceptions::PyIOError::new_err)
    }

    /// Tag a sequence of observations
    ///
    /// Args:
    ///     features: List of feature lists, one per token.
    ///               Each inner list contains feature strings like "word=hello".
    ///
    /// Returns:
    ///     List of label strings
    pub fn tag(&self, features: Vec<Vec<String>>) -> Vec<String> {
        self.tagger.tag(&features)
    }

    /// Tag a sequence and return the score along with labels
    pub fn tag_with_score(&self, features: Vec<Vec<String>>) -> (Vec<String>, f64) {
        let result = self.tagger.tag_with_score(&features);
        let labels: Vec<String> = result
            .labels
            .iter()
            .map(|&id| {
                self.tagger
                    .model()
                    .id_to_label(id)
                    .unwrap_or("O")
                    .to_string()
            })
            .collect();
        (labels, result.score)
    }

    /// Compute marginal probabilities for each position and label
    pub fn marginals(&self, features: Vec<Vec<String>>) -> Vec<Vec<f64>> {
        self.tagger.compute_marginals(&features)
    }

    /// Get the number of labels
    pub fn num_labels(&self) -> usize {
        self.tagger.num_labels()
    }

    /// Get all label names
    pub fn labels(&self) -> Vec<String> {
        self.tagger.labels()
    }

    fn __repr__(&self) -> String {
        format!("CRFTagger(num_labels={})", self.tagger.num_labels())
    }
}

/// Python wrapper for CRF Trainer
#[pyclass(name = "CRFTrainer")]
pub struct PyCRFTrainer {
    trainer: RustCRFTrainer,
}

#[pymethods]
impl PyCRFTrainer {
    /// Create a new trainer with default configuration
    ///
    /// Args:
    ///     loss_function: "lbfgs" (recommended), "nll" for SGD, or "perceptron" for Structured Perceptron
    ///     l1_penalty: L1 regularization penalty (for lbfgs and nll)
    ///     l2_penalty: L2 regularization penalty (for lbfgs and nll)
    ///     learning_rate: Learning rate (only for perceptron)
    ///     max_iterations: Maximum number of training iterations
    ///     averaging: Whether to use averaged perceptron (only for perceptron)
    ///     verbose: Verbosity level (0=quiet, 1=progress, 2=detailed)
    #[new]
    #[pyo3(signature = (loss_function="lbfgs", l1_penalty=0.0, l2_penalty=0.01, learning_rate=0.1, max_iterations=100, averaging=true, verbose=1))]
    pub fn new(
        loss_function: &str,
        l1_penalty: f64,
        l2_penalty: f64,
        learning_rate: f64,
        max_iterations: usize,
        averaging: bool,
        verbose: u8,
    ) -> PyResult<Self> {
        let loss = match loss_function {
            "lbfgs"
            | "LBFGS"
            | "l-bfgs"
            | "L-BFGS"
            | "nll"
            | "NLL"
            | "negative_log_likelihood"
            | "sgd"
            | "SGD" => LossFunction::LBFGS {
                l1_penalty,
                l2_penalty,
            },
            "perceptron" | "Perceptron" | "structured_perceptron" => {
                LossFunction::StructuredPerceptron { learning_rate }
            }
            _ => {
                return Err(pyo3::exceptions::PyValueError::new_err(format!(
                    "Unknown loss function: {}. Use 'lbfgs' (recommended) or 'perceptron'",
                    loss_function
                )));
            }
        };

        let config = TrainerConfig {
            loss_function: loss,
            max_iterations,
            epsilon: 1e-5,
            averaging,
            verbose: verbose as i32,
        };

        Ok(Self {
            trainer: RustCRFTrainer::with_config(config),
        })
    }

    /// Set L1 regularization penalty
    pub fn set_l1_penalty(&mut self, penalty: f64) {
        self.trainer.set_l1_penalty(penalty);
    }

    /// Set L2 regularization penalty
    pub fn set_l2_penalty(&mut self, penalty: f64) {
        self.trainer.set_l2_penalty(penalty);
    }

    /// Set maximum iterations
    pub fn set_max_iterations(&mut self, max_iter: usize) {
        self.trainer.set_max_iterations(max_iter);
    }

    /// Train the model on the given data
    ///
    /// Args:
    ///     X: List of sequences, where each sequence is a list of feature lists
    ///        (one feature list per token)
    ///     y: List of label sequences, where each sequence is a list of label strings
    ///
    /// Returns:
    ///     Trained CRFModel
    pub fn train(&mut self, x: Vec<Vec<Vec<String>>>, y: Vec<Vec<String>>) -> PyResult<PyCRFModel> {
        if x.len() != y.len() {
            return Err(pyo3::exceptions::PyValueError::new_err(format!(
                "X and y must have the same length: {} vs {}",
                x.len(),
                y.len()
            )));
        }

        // Convert to training instances
        let data: Vec<TrainingInstance> = x
            .into_iter()
            .zip(y)
            .map(|(features, labels)| TrainingInstance::new(features, labels))
            .collect();

        // Train
        let model = self.trainer.train(&data);

        Ok(PyCRFModel { model })
    }

    /// Get the current model (during or after training)
    pub fn get_model(&self) -> PyCRFModel {
        PyCRFModel {
            model: self.trainer.get_model().clone(),
        }
    }

    fn __repr__(&self) -> String {
        "CRFTrainer()".to_string()
    }
}

// ============================================================================
// Python bindings for LR classes
// ============================================================================

/// Python wrapper for LR Model
#[pyclass(name = "LRModel")]
pub struct PyLRModel {
    model: LRModel,
}

#[pymethods]
impl PyLRModel {
    /// Create a new empty LR model
    #[new]
    pub fn new() -> PyResult<Self> {
        Ok(Self {
            model: LRModel::new(),
        })
    }

    /// Create a model with predefined classes
    #[staticmethod]
    pub fn with_classes(classes: Vec<String>) -> PyResult<Self> {
        Ok(Self {
            model: LRModel::with_classes(classes),
        })
    }

    /// Get the number of classes
    #[getter]
    pub fn num_classes(&self) -> usize {
        self.model.num_classes
    }

    /// Get the number of features
    #[getter]
    pub fn num_features(&self) -> usize {
        self.model.num_features
    }

    /// Get the number of non-zero weights
    pub fn num_weights(&self) -> usize {
        self.model.num_weights()
    }

    /// Get all class labels
    pub fn get_classes(&self) -> Vec<String> {
        self.model.get_classes()
    }

    /// Save the model to a file
    pub fn save(&self, path: String) -> PyResult<()> {
        let saver = LRModelSaver::new();
        saver
            .save(&self.model, path, LRFormat::Native)
            .map_err(pyo3::exceptions::PyIOError::new_err)
    }

    /// Load a model from a file
    #[staticmethod]
    pub fn load(path: String) -> PyResult<Self> {
        let loader = LRModelLoader::new();
        let model = loader
            .load(path, LRFormat::Auto)
            .map_err(pyo3::exceptions::PyIOError::new_err)?;
        Ok(Self { model })
    }

    /// Get the L2 norm squared of all weights
    pub fn l2_norm_squared(&self) -> f64 {
        self.model.l2_norm_squared()
    }

    /// Get the L1 norm of all weights
    pub fn l1_norm(&self) -> f64 {
        self.model.l1_norm()
    }

    fn __repr__(&self) -> String {
        format!(
            "LRModel(num_classes={}, num_features={}, num_weights={})",
            self.model.num_classes,
            self.model.num_features,
            self.model.num_weights()
        )
    }
}

/// Python wrapper for LR Classifier
#[pyclass(name = "LRClassifier")]
pub struct PyLRClassifier {
    classifier: LRClassifier,
}

#[pymethods]
impl PyLRClassifier {
    /// Create a new classifier with an empty model
    #[new]
    pub fn new() -> PyResult<Self> {
        Ok(Self {
            classifier: LRClassifier::new(),
        })
    }

    /// Create a classifier from a model
    #[staticmethod]
    pub fn from_model(model: &PyLRModel) -> PyResult<Self> {
        Ok(Self {
            classifier: LRClassifier::from_model(model.model.clone()),
        })
    }

    /// Load a model from file
    #[staticmethod]
    pub fn load(path: String) -> PyResult<Self> {
        let classifier = LRClassifier::load(path).map_err(pyo3::exceptions::PyIOError::new_err)?;
        Ok(Self { classifier })
    }

    /// Predict the most likely class for the given features
    ///
    /// Args:
    ///     features: List of feature strings like "word=hello"
    ///
    /// Returns:
    ///     The predicted class label
    pub fn predict(&self, features: Vec<String>) -> String {
        self.classifier.predict(&features)
    }

    /// Predict with probability for the most likely class
    ///
    /// Returns:
    ///     Tuple of (class_label, probability)
    pub fn predict_with_prob(&self, features: Vec<String>) -> (String, f64) {
        self.classifier.predict_with_prob(&features)
    }

    /// Get probability distribution over all classes
    ///
    /// Returns:
    ///     List of (class_label, probability) tuples, sorted by probability descending
    pub fn predict_proba(&self, features: Vec<String>) -> Vec<(String, f64)> {
        self.classifier.predict_proba(&features)
    }

    /// Get top-k most likely classes with probabilities
    pub fn predict_top_k(&self, features: Vec<String>, k: usize) -> Vec<(String, f64)> {
        self.classifier.predict_top_k(&features, k)
    }

    /// Get the number of classes
    pub fn num_classes(&self) -> usize {
        self.classifier.num_classes()
    }

    /// Get all class labels
    pub fn classes(&self) -> Vec<String> {
        self.classifier.classes()
    }

    fn __repr__(&self) -> String {
        format!(
            "LRClassifier(num_classes={})",
            self.classifier.num_classes()
        )
    }
}

/// Python wrapper for LR Trainer
#[pyclass(name = "LRTrainer")]
pub struct PyLRTrainer {
    trainer: RustLRTrainer,
}

#[pymethods]
impl PyLRTrainer {
    /// Create a new trainer with configuration
    ///
    /// Args:
    ///     l1_penalty: L1 regularization penalty (lasso)
    ///     l2_penalty: L2 regularization penalty (ridge)
    ///     learning_rate: Learning rate for SGD
    ///     max_epochs: Maximum number of training epochs
    ///     batch_size: Mini-batch size (1 = pure SGD)
    ///     tol: Convergence tolerance for early stopping
    ///     verbose: Verbosity level (0=quiet, 1=progress, 2=detailed)
    #[new]
    #[pyo3(signature = (l1_penalty=0.0, l2_penalty=0.01, learning_rate=0.1, max_epochs=100, batch_size=1, tol=1e-4, verbose=1))]
    pub fn new(
        l1_penalty: f64,
        l2_penalty: f64,
        learning_rate: f64,
        max_epochs: usize,
        batch_size: usize,
        tol: f64,
        verbose: u8,
    ) -> PyResult<Self> {
        let config = LRTrainerConfig {
            l1_penalty,
            l2_penalty,
            learning_rate,
            max_epochs,
            batch_size: batch_size.max(1),
            tol,
            verbose,
        };

        Ok(Self {
            trainer: RustLRTrainer::with_config(config),
        })
    }

    /// Set L1 regularization penalty
    pub fn set_l1_penalty(&mut self, penalty: f64) {
        self.trainer.set_l1_penalty(penalty);
    }

    /// Set L2 regularization penalty
    pub fn set_l2_penalty(&mut self, penalty: f64) {
        self.trainer.set_l2_penalty(penalty);
    }

    /// Set learning rate
    pub fn set_learning_rate(&mut self, lr: f64) {
        self.trainer.set_learning_rate(lr);
    }

    /// Set maximum epochs
    pub fn set_max_epochs(&mut self, epochs: usize) {
        self.trainer.set_max_epochs(epochs);
    }

    /// Set batch size
    pub fn set_batch_size(&mut self, size: usize) {
        self.trainer.set_batch_size(size);
    }

    /// Train the model on the given data
    ///
    /// Args:
    ///     X: List of feature lists, one per instance.
    ///        Each inner list contains feature strings like "word=hello".
    ///     y: List of class labels, one per instance.
    ///
    /// Returns:
    ///     Trained LRModel
    pub fn train(&mut self, x: Vec<Vec<String>>, y: Vec<String>) -> PyResult<PyLRModel> {
        if x.len() != y.len() {
            return Err(pyo3::exceptions::PyValueError::new_err(format!(
                "X and y must have the same length: {} vs {}",
                x.len(),
                y.len()
            )));
        }

        // Convert to training instances
        let data: Vec<LRTrainingInstance> = x
            .into_iter()
            .zip(y)
            .map(|(features, label)| LRTrainingInstance::new(features, label))
            .collect();

        // Train
        let model = self.trainer.train(&data);

        Ok(PyLRModel { model })
    }

    /// Get the current model
    pub fn get_model(&self) -> PyLRModel {
        PyLRModel {
            model: self.trainer.get_model().clone(),
        }
    }

    fn __repr__(&self) -> String {
        "LRTrainer()".to_string()
    }
}

// ============================================================================
// Python bindings for Text classes
// ============================================================================

/// Python wrapper for TF-IDF Vectorizer
#[pyclass(name = "TfIdfVectorizer")]
pub struct PyTfIdfVectorizer {
    vectorizer: TfIdfVectorizer,
}

#[pymethods]
impl PyTfIdfVectorizer {
    /// Create a new TfIdfVectorizer with optional configuration
    ///
    /// Args:
    ///     min_df: Minimum document frequency (default: 1)
    ///     max_df: Maximum document frequency ratio (default: 1.0)
    ///     max_features: Maximum vocabulary size, 0 for unlimited (default: 0)
    ///     sublinear_tf: Use sublinear TF scaling (default: False)
    ///     lowercase: Convert text to lowercase (default: True)
    ///     ngram_range: Tuple of (min_n, max_n) for n-grams (default: (1, 1))
    ///     min_token_length: Minimum token length (default: 2, matches sklearn)
    ///     norm: Apply L2 normalization (default: True)
    #[new]
    #[pyo3(signature = (min_df=1, max_df=1.0, max_features=0, sublinear_tf=false, lowercase=true, ngram_range=(1, 1), min_token_length=2, norm=true))]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        min_df: usize,
        max_df: f64,
        max_features: usize,
        sublinear_tf: bool,
        lowercase: bool,
        ngram_range: (usize, usize),
        min_token_length: usize,
        norm: bool,
    ) -> PyResult<Self> {
        let config = TfIdfConfig {
            min_df,
            max_df,
            max_features,
            sublinear_tf,
            lowercase,
            ngram_range,
            min_token_length,
            norm,
        };
        Ok(Self {
            vectorizer: TfIdfVectorizer::with_config(config),
        })
    }

    /// Fit the vectorizer on a list of documents
    ///
    /// Args:
    ///     documents: List of text documents
    pub fn fit(&mut self, documents: Vec<String>) {
        self.vectorizer.fit(&documents);
    }

    /// Transform a document into sparse TF-IDF features
    ///
    /// Args:
    ///     document: Text document to transform
    ///
    /// Returns:
    ///     List of (feature_index, tfidf_value) tuples
    pub fn transform(&self, document: &str) -> Vec<(u32, f64)> {
        self.vectorizer.transform(document)
    }

    /// Transform a document into a dense TF-IDF vector
    ///
    /// Args:
    ///     document: Text document to transform
    ///
    /// Returns:
    ///     List of TF-IDF values (length = vocab_size)
    pub fn transform_dense(&self, document: &str) -> Vec<f64> {
        self.vectorizer.transform_dense(document)
    }

    /// Transform a document into feature strings for LRClassifier
    ///
    /// Args:
    ///     document: Text document to transform
    ///
    /// Returns:
    ///     List of feature strings like "tfidf_0=0.1234"
    pub fn transform_to_features(&self, document: &str) -> Vec<String> {
        self.vectorizer.transform_to_features(document)
    }

    /// Fit and transform documents in one step
    ///
    /// Args:
    ///     documents: List of text documents
    ///
    /// Returns:
    ///     List of sparse TF-IDF vectors
    pub fn fit_transform(&mut self, documents: Vec<String>) -> Vec<Vec<(u32, f64)>> {
        self.vectorizer.fit_transform(&documents)
    }

    /// Get the vocabulary size
    #[getter]
    pub fn vocab_size(&self) -> usize {
        self.vectorizer.vocab_size()
    }

    /// Get the number of documents used for fitting
    #[getter]
    pub fn n_docs(&self) -> usize {
        self.vectorizer.n_docs()
    }

    /// Check if the vectorizer has been fitted
    pub fn is_fitted(&self) -> bool {
        self.vectorizer.is_fitted()
    }

    /// Get all feature names (vocabulary words in order)
    pub fn get_feature_names(&self) -> Vec<String> {
        self.vectorizer.get_feature_names()
    }

    /// Get the IDF values for all features
    pub fn get_idf(&self) -> Vec<f64> {
        self.vectorizer.idf_values().to_vec()
    }

    /// Get top features by IDF value
    ///
    /// Args:
    ///     n: Number of top features to return
    ///
    /// Returns:
    ///     List of (word, idf_value) tuples
    pub fn top_features_by_idf(&self, n: usize) -> Vec<(String, f64)> {
        self.vectorizer.top_features_by_idf(n)
    }

    /// Get the index of a word in the vocabulary
    ///
    /// Returns None if the word is not in the vocabulary
    pub fn get_index(&self, word: &str) -> Option<u32> {
        self.vectorizer.get_index(word)
    }

    /// Get the word at a given index
    ///
    /// Returns None if the index is out of bounds
    pub fn get_word(&self, index: u32) -> Option<String> {
        self.vectorizer.get_word(index).map(|s| s.to_string())
    }

    /// Save the vectorizer to a file
    pub fn save(&self, path: String) -> PyResult<()> {
        let data = bincode::serialize(&self.vectorizer).map_err(|e| {
            pyo3::exceptions::PyIOError::new_err(format!("Serialization error: {}", e))
        })?;
        std::fs::write(&path, data)
            .map_err(|e| pyo3::exceptions::PyIOError::new_err(format!("Write error: {}", e)))?;
        Ok(())
    }

    /// Load a vectorizer from a file
    #[staticmethod]
    pub fn load(path: String) -> PyResult<Self> {
        let data = std::fs::read(&path)
            .map_err(|e| pyo3::exceptions::PyIOError::new_err(format!("Read error: {}", e)))?;
        let vectorizer: TfIdfVectorizer = bincode::deserialize(&data).map_err(|e| {
            pyo3::exceptions::PyIOError::new_err(format!("Deserialization error: {}", e))
        })?;
        Ok(Self { vectorizer })
    }

    fn __repr__(&self) -> String {
        if self.vectorizer.is_fitted() {
            format!(
                "TfIdfVectorizer(vocab_size={}, n_docs={})",
                self.vectorizer.vocab_size(),
                self.vectorizer.n_docs()
            )
        } else {
            "TfIdfVectorizer(not fitted)".to_string()
        }
    }
}

#[pymodule]
fn underthesea_core(_py: Python, m: &Bound<PyModule>) -> PyResult<()> {
    m.add_class::<CRFFeaturizer>()?;
    m.add_class::<PyCRFModel>()?;
    m.add_class::<PyCRFTagger>()?;
    m.add_class::<PyCRFTrainer>()?;
    // LR classes
    m.add_class::<PyLRModel>()?;
    m.add_class::<PyLRClassifier>()?;
    m.add_class::<PyLRTrainer>()?;
    // Text classes
    m.add_class::<PyTfIdfVectorizer>()?;
    // SVM classes
    m.add_class::<LinearSVC>()?;
    // Classifier classes
    m.add_class::<TextClassifier>()?;
    m.add_class::<Label>()?;
    m.add_class::<Sentence>()?;
    // Preprocessor classes
    m.add_class::<TextPreprocessor>()?;
    // FastText classes
    m.add_class::<PyFastText>()?;
    Ok(())
}

// ============================================================================
// Python bindings for FastText
// ============================================================================

/// Python wrapper for FastText model (language identification, text classification)
#[pyclass(name = "FastText")]
pub struct PyFastText {
    model: fasttext::FastTextModel,
}

#[pymethods]
impl PyFastText {
    /// Load a FastText model from a .bin or .ftz file
    #[staticmethod]
    pub fn load(path: &str) -> PyResult<Self> {
        let model =
            fasttext::FastTextModel::load(path).map_err(pyo3::exceptions::PyIOError::new_err)?;
        Ok(Self { model })
    }

    /// Predict the top-k labels for the given text
    #[pyo3(signature = (text, k=1))]
    pub fn predict(&self, text: &str, k: usize) -> Vec<(String, f32)> {
        self.model.predict(text, k)
    }

    /// Get all label strings
    pub fn get_labels(&self) -> Vec<String> {
        self.model.get_labels()
    }

    /// Get the hidden vector for a text
    pub fn get_hidden(&self, text: &str) -> Vec<f32> {
        self.model.get_hidden(text)
    }

    /// Get the input feature IDs for a text
    pub fn get_features(&self, text: &str) -> Vec<i32> {
        self.model.get_features(text)
    }

    /// Model dimensionality
    #[getter]
    pub fn dim(&self) -> i32 {
        self.model.dim()
    }

    /// Number of words in the dictionary
    #[getter]
    pub fn nwords(&self) -> i32 {
        self.model.nwords()
    }

    /// Number of labels
    #[getter]
    pub fn nlabels(&self) -> i32 {
        self.model.nlabels()
    }
}