scirs2-python 0.4.3

Python bindings for SciRS2 - A comprehensive scientific computing library in Rust (SciPy alternative)
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
//! Python bindings for scirs2-text
//!
//! This module provides Python bindings for text processing operations,
//! including tokenization, vectorization, sentiment analysis, stemming,
//! string similarity metrics, and text cleaning.

use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};

// NumPy types for Python array interface
use scirs2_numpy::{IntoPyArray, PyArray1, PyArray2, PyArrayMethods};

// Direct imports from scirs2-text
use scirs2_text::{
    // Cleansing functions
    cleansing::{
        expand_contractions, normalize_unicode, normalize_whitespace, remove_accents,
        replace_emails, replace_urls, strip_html_tags,
    },
    // Sentiment
    sentiment::{LexiconSentimentAnalyzer, Sentiment},
    // Stemming
    stemming::{LancasterStemmer, PorterStemmer, SnowballStemmer, Stemmer},
    // Tokenization
    tokenize::{
        CharacterTokenizer, NgramTokenizer, RegexTokenizer, SentenceTokenizer, Tokenizer,
        WhitespaceTokenizer, WordTokenizer,
    },
    // Vectorization
    vectorize::{CountVectorizer, TfidfVectorizer, Vectorizer},
};

// ========================================
// TOKENIZATION
// ========================================

/// Word tokenizer
#[pyclass(name = "WordTokenizer")]
pub struct PyWordTokenizer {
    inner: WordTokenizer,
}

#[pymethods]
impl PyWordTokenizer {
    #[new]
    #[pyo3(signature = (lowercase=true))]
    fn new(lowercase: bool) -> Self {
        Self {
            inner: WordTokenizer::new(lowercase),
        }
    }

    fn tokenize(&self, text: &str) -> PyResult<Vec<String>> {
        self.inner
            .tokenize(text)
            .map_err(|e| PyRuntimeError::new_err(format!("Tokenization failed: {}", e)))
    }

    fn tokenize_batch(&self, texts: &Bound<'_, PyList>) -> PyResult<Vec<Vec<String>>> {
        let texts_owned: Vec<String> = texts
            .iter()
            .map(|item| item.extract::<String>())
            .collect::<PyResult<Vec<String>>>()?;
        let text_strs: Vec<&str> = texts_owned.iter().map(|s| s.as_str()).collect();
        self.inner
            .tokenize_batch(&text_strs)
            .map_err(|e| PyRuntimeError::new_err(format!("Batch tokenization failed: {}", e)))
    }
}

/// Sentence tokenizer
#[pyclass(name = "SentenceTokenizer")]
pub struct PySentenceTokenizer {
    inner: SentenceTokenizer,
}

#[pymethods]
impl PySentenceTokenizer {
    #[new]
    fn new() -> Self {
        Self {
            inner: SentenceTokenizer::new(),
        }
    }

    fn tokenize(&self, text: &str) -> PyResult<Vec<String>> {
        self.inner
            .tokenize(text)
            .map_err(|e| PyRuntimeError::new_err(format!("Tokenization failed: {}", e)))
    }
}

/// Character tokenizer
#[pyclass(name = "CharacterTokenizer")]
pub struct PyCharacterTokenizer {
    inner: CharacterTokenizer,
}

#[pymethods]
impl PyCharacterTokenizer {
    #[new]
    #[pyo3(signature = (use_grapheme_clusters=true))]
    fn new(use_grapheme_clusters: bool) -> Self {
        Self {
            inner: CharacterTokenizer::new(use_grapheme_clusters),
        }
    }

    fn tokenize(&self, text: &str) -> PyResult<Vec<String>> {
        self.inner
            .tokenize(text)
            .map_err(|e| PyRuntimeError::new_err(format!("Tokenization failed: {}", e)))
    }
}

/// N-gram tokenizer
#[pyclass(name = "NgramTokenizer")]
pub struct PyNgramTokenizer {
    inner: NgramTokenizer,
}

#[pymethods]
impl PyNgramTokenizer {
    #[new]
    #[pyo3(signature = (n=2))]
    fn new(n: usize) -> PyResult<Self> {
        let tokenizer = NgramTokenizer::new(n).map_err(|e| {
            PyRuntimeError::new_err(format!("NgramTokenizer creation failed: {}", e))
        })?;
        Ok(Self { inner: tokenizer })
    }

    fn tokenize(&self, text: &str) -> PyResult<Vec<String>> {
        self.inner
            .tokenize(text)
            .map_err(|e| PyRuntimeError::new_err(format!("Tokenization failed: {}", e)))
    }
}

/// Whitespace tokenizer
#[pyclass(name = "WhitespaceTokenizer")]
pub struct PyWhitespaceTokenizer {
    inner: WhitespaceTokenizer,
}

#[pymethods]
impl PyWhitespaceTokenizer {
    #[new]
    fn new() -> Self {
        Self {
            inner: WhitespaceTokenizer::new(),
        }
    }

    fn tokenize(&self, text: &str) -> PyResult<Vec<String>> {
        self.inner
            .tokenize(text)
            .map_err(|e| PyRuntimeError::new_err(format!("Tokenization failed: {}", e)))
    }
}

/// Regex tokenizer
#[pyclass(name = "RegexTokenizer")]
pub struct PyRegexTokenizer {
    inner: RegexTokenizer,
}

#[pymethods]
impl PyRegexTokenizer {
    #[new]
    #[pyo3(signature = (pattern, gaps=false))]
    fn new(pattern: &str, gaps: bool) -> PyResult<Self> {
        let tokenizer = RegexTokenizer::new(pattern, gaps).map_err(|e| {
            PyRuntimeError::new_err(format!("RegexTokenizer creation failed: {}", e))
        })?;
        Ok(Self { inner: tokenizer })
    }

    fn tokenize(&self, text: &str) -> PyResult<Vec<String>> {
        self.inner
            .tokenize(text)
            .map_err(|e| PyRuntimeError::new_err(format!("Tokenization failed: {}", e)))
    }
}

// ========================================
// VECTORIZATION
// ========================================

/// Count vectorizer (bag-of-words)
#[pyclass(name = "CountVectorizer")]
pub struct PyCountVectorizer {
    inner: CountVectorizer,
}

#[pymethods]
impl PyCountVectorizer {
    #[new]
    #[pyo3(signature = (binary=false))]
    fn new(binary: bool) -> Self {
        Self {
            inner: CountVectorizer::new(binary),
        }
    }

    fn fit(&mut self, texts: &Bound<'_, PyList>) -> PyResult<()> {
        let texts_owned: Vec<String> = texts
            .iter()
            .map(|item| item.extract::<String>())
            .collect::<PyResult<Vec<String>>>()?;
        let text_strs: Vec<&str> = texts_owned.iter().map(|s| s.as_str()).collect();
        self.inner
            .fit(&text_strs)
            .map_err(|e| PyRuntimeError::new_err(format!("Fit failed: {}", e)))
    }

    fn transform(&self, py: Python, text: &str) -> PyResult<Py<PyArray1<f64>>> {
        let result = self
            .inner
            .transform(text)
            .map_err(|e| PyRuntimeError::new_err(format!("Transform failed: {}", e)))?;
        Ok(result.into_pyarray(py).unbind())
    }

    fn transform_batch(
        &self,
        py: Python,
        texts: &Bound<'_, PyList>,
    ) -> PyResult<Py<PyArray2<f64>>> {
        let texts_owned: Vec<String> = texts
            .iter()
            .map(|item| item.extract::<String>())
            .collect::<PyResult<Vec<String>>>()?;
        let text_strs: Vec<&str> = texts_owned.iter().map(|s| s.as_str()).collect();
        let result = self
            .inner
            .transform_batch(&text_strs)
            .map_err(|e| PyRuntimeError::new_err(format!("Batch transform failed: {}", e)))?;
        Ok(result.into_pyarray(py).unbind())
    }

    fn fit_transform(
        &mut self,
        py: Python,
        texts: &Bound<'_, PyList>,
    ) -> PyResult<Py<PyArray2<f64>>> {
        let texts_owned: Vec<String> = texts
            .iter()
            .map(|item| item.extract::<String>())
            .collect::<PyResult<Vec<String>>>()?;
        let text_strs: Vec<&str> = texts_owned.iter().map(|s| s.as_str()).collect();
        let result = self
            .inner
            .fit_transform(&text_strs)
            .map_err(|e| PyRuntimeError::new_err(format!("Fit transform failed: {}", e)))?;
        Ok(result.into_pyarray(py).unbind())
    }

    fn vocabulary_size(&self) -> usize {
        self.inner.vocabulary_size()
    }

    fn get_feature_names(&self) -> Vec<String> {
        let vocab = self.inner.vocabulary();
        let mut features: Vec<(usize, String)> = vocab
            .token_to_index()
            .iter()
            .map(|(token, &idx)| (idx, token.clone()))
            .collect();
        features.sort_by_key(|(idx, _)| *idx);
        features.into_iter().map(|(_, token)| token).collect()
    }
}

/// TF-IDF vectorizer
#[pyclass(name = "TfidfVectorizer")]
pub struct PyTfidfVectorizer {
    inner: TfidfVectorizer,
}

#[pymethods]
impl PyTfidfVectorizer {
    #[new]
    #[pyo3(signature = (lowercase=true, norm=true, norm_type=None))]
    fn new(lowercase: bool, norm: bool, norm_type: Option<String>) -> Self {
        Self {
            inner: TfidfVectorizer::new(lowercase, norm, norm_type),
        }
    }

    fn fit(&mut self, texts: &Bound<'_, PyList>) -> PyResult<()> {
        let texts_owned: Vec<String> = texts
            .iter()
            .map(|item| item.extract::<String>())
            .collect::<PyResult<Vec<String>>>()?;
        let text_strs: Vec<&str> = texts_owned.iter().map(|s| s.as_str()).collect();
        self.inner
            .fit(&text_strs)
            .map_err(|e| PyRuntimeError::new_err(format!("Fit failed: {}", e)))
    }

    fn transform(&self, py: Python, text: &str) -> PyResult<Py<PyArray1<f64>>> {
        let result = self
            .inner
            .transform(text)
            .map_err(|e| PyRuntimeError::new_err(format!("Transform failed: {}", e)))?;
        Ok(result.into_pyarray(py).unbind())
    }

    fn transform_batch(
        &self,
        py: Python,
        texts: &Bound<'_, PyList>,
    ) -> PyResult<Py<PyArray2<f64>>> {
        let texts_owned: Vec<String> = texts
            .iter()
            .map(|item| item.extract::<String>())
            .collect::<PyResult<Vec<String>>>()?;
        let text_strs: Vec<&str> = texts_owned.iter().map(|s| s.as_str()).collect();
        let result = self
            .inner
            .transform_batch(&text_strs)
            .map_err(|e| PyRuntimeError::new_err(format!("Batch transform failed: {}", e)))?;
        Ok(result.into_pyarray(py).unbind())
    }

    fn fit_transform(
        &mut self,
        py: Python,
        texts: &Bound<'_, PyList>,
    ) -> PyResult<Py<PyArray2<f64>>> {
        let texts_owned: Vec<String> = texts
            .iter()
            .map(|item| item.extract::<String>())
            .collect::<PyResult<Vec<String>>>()?;
        let text_strs: Vec<&str> = texts_owned.iter().map(|s| s.as_str()).collect();
        let result = self
            .inner
            .fit_transform(&text_strs)
            .map_err(|e| PyRuntimeError::new_err(format!("Fit transform failed: {}", e)))?;
        Ok(result.into_pyarray(py).unbind())
    }

    fn vocabulary_size(&self) -> usize {
        self.inner.vocabulary_size()
    }

    fn get_feature_names(&self) -> Vec<String> {
        let vocab = self.inner.vocabulary();
        let mut features: Vec<(usize, String)> = vocab
            .token_to_index()
            .iter()
            .map(|(token, &idx)| (idx, token.clone()))
            .collect();
        features.sort_by_key(|(idx, _)| *idx);
        features.into_iter().map(|(_, token)| token).collect()
    }
}

// ========================================
// SENTIMENT ANALYSIS
// ========================================

/// Convert Sentiment enum to string for Python
fn sentiment_to_string(sentiment: &Sentiment) -> String {
    match sentiment {
        Sentiment::Positive => "positive".to_string(),
        Sentiment::Negative => "negative".to_string(),
        Sentiment::Neutral => "neutral".to_string(),
    }
}

/// Lexicon-based sentiment analyzer
#[pyclass(name = "LexiconSentimentAnalyzer")]
pub struct PyLexiconSentimentAnalyzer {
    inner: LexiconSentimentAnalyzer,
}

#[pymethods]
impl PyLexiconSentimentAnalyzer {
    #[new]
    fn new() -> Self {
        Self {
            inner: LexiconSentimentAnalyzer::with_basiclexicon(),
        }
    }

    fn analyze(&self, py: Python, text: &str) -> PyResult<Py<PyAny>> {
        let result = self
            .inner
            .analyze(text)
            .map_err(|e| PyRuntimeError::new_err(format!("Sentiment analysis failed: {}", e)))?;

        // Convert to Python dict
        let dict = PyDict::new(py);
        dict.set_item("sentiment", sentiment_to_string(&result.sentiment))?;
        dict.set_item("score", result.score)?;
        dict.set_item("confidence", result.confidence)?;

        let word_counts = PyDict::new(py);
        word_counts.set_item("positive_words", result.word_counts.positive_words)?;
        word_counts.set_item("negative_words", result.word_counts.negative_words)?;
        word_counts.set_item("neutral_words", result.word_counts.neutral_words)?;
        word_counts.set_item("total_words", result.word_counts.total_words)?;
        dict.set_item("word_counts", word_counts)?;

        Ok(dict.into())
    }
}

// ========================================
// STEMMING
// ========================================

/// Porter stemmer
#[pyclass(name = "PorterStemmer")]
pub struct PyPorterStemmer {
    inner: PorterStemmer,
}

#[pymethods]
impl PyPorterStemmer {
    #[new]
    fn new() -> Self {
        Self {
            inner: PorterStemmer::new(),
        }
    }

    fn stem(&self, word: &str) -> PyResult<String> {
        self.inner
            .stem(word)
            .map_err(|e| PyRuntimeError::new_err(format!("Stemming failed: {}", e)))
    }

    fn stem_batch(&self, words: &Bound<'_, PyList>) -> PyResult<Vec<String>> {
        let words_owned: Vec<String> = words
            .iter()
            .map(|item| item.extract::<String>())
            .collect::<PyResult<Vec<String>>>()?;
        let word_strs: Vec<&str> = words_owned.iter().map(|s| s.as_str()).collect();
        self.inner
            .stem_batch(&word_strs)
            .map_err(|e| PyRuntimeError::new_err(format!("Batch stemming failed: {}", e)))
    }
}

/// Snowball stemmer
#[pyclass(name = "SnowballStemmer")]
pub struct PySnowballStemmer {
    inner: SnowballStemmer,
}

#[pymethods]
impl PySnowballStemmer {
    #[new]
    #[pyo3(signature = (language="english"))]
    fn new(language: &str) -> PyResult<Self> {
        let stemmer = SnowballStemmer::new(language).map_err(|e| {
            PyRuntimeError::new_err(format!("SnowballStemmer creation failed: {}", e))
        })?;
        Ok(Self { inner: stemmer })
    }

    fn stem(&self, word: &str) -> PyResult<String> {
        self.inner
            .stem(word)
            .map_err(|e| PyRuntimeError::new_err(format!("Stemming failed: {}", e)))
    }

    fn stem_batch(&self, words: &Bound<'_, PyList>) -> PyResult<Vec<String>> {
        let words_owned: Vec<String> = words
            .iter()
            .map(|item| item.extract::<String>())
            .collect::<PyResult<Vec<String>>>()?;
        let word_strs: Vec<&str> = words_owned.iter().map(|s| s.as_str()).collect();
        self.inner
            .stem_batch(&word_strs)
            .map_err(|e| PyRuntimeError::new_err(format!("Batch stemming failed: {}", e)))
    }
}

/// Lancaster stemmer
#[pyclass(name = "LancasterStemmer")]
pub struct PyLancasterStemmer {
    inner: LancasterStemmer,
}

#[pymethods]
impl PyLancasterStemmer {
    #[new]
    fn new() -> Self {
        Self {
            inner: LancasterStemmer::new(),
        }
    }

    fn stem(&self, word: &str) -> PyResult<String> {
        self.inner
            .stem(word)
            .map_err(|e| PyRuntimeError::new_err(format!("Stemming failed: {}", e)))
    }

    fn stem_batch(&self, words: &Bound<'_, PyList>) -> PyResult<Vec<String>> {
        let words_owned: Vec<String> = words
            .iter()
            .map(|item| item.extract::<String>())
            .collect::<PyResult<Vec<String>>>()?;
        let word_strs: Vec<&str> = words_owned.iter().map(|s| s.as_str()).collect();
        self.inner
            .stem_batch(&word_strs)
            .map_err(|e| PyRuntimeError::new_err(format!("Batch stemming failed: {}", e)))
    }
}

// ========================================
// STRING SIMILARITY METRICS
// ========================================

/// Levenshtein distance
#[pyfunction]
fn levenshtein_distance_py(s1: &str, s2: &str) -> usize {
    scirs2_text::distance::levenshtein_distance(s1, s2)
}

/// Cosine similarity between two vectors
#[pyfunction]
fn cosine_similarity_py(
    vec1: &Bound<'_, PyArray1<f64>>,
    vec2: &Bound<'_, PyArray1<f64>>,
) -> PyResult<f64> {
    let v1_binding = vec1.readonly();
    let v2_binding = vec2.readonly();
    let v1_view = v1_binding.as_array();
    let v2_view = v2_binding.as_array();

    scirs2_text::distance::cosine_similarity(v1_view, v2_view)
        .map_err(|e| PyRuntimeError::new_err(format!("Similarity calculation failed: {}", e)))
}

/// Jaccard similarity between two token sets
#[pyfunction]
fn jaccard_similarity_py(s1: &str, s2: &str) -> PyResult<f64> {
    scirs2_text::distance::jaccard_similarity(s1, s2, None)
        .map_err(|e| PyRuntimeError::new_err(format!("Similarity calculation failed: {}", e)))
}

// ========================================
// TEXT CLEANING
// ========================================

/// Strip HTML tags
#[pyfunction]
fn strip_html_tags_py(text: &str) -> String {
    strip_html_tags(text)
}

/// Replace URLs with a replacement string
#[pyfunction]
#[pyo3(signature = (text, replacement="<URL>"))]
fn replace_urls_py(text: &str, replacement: &str) -> String {
    replace_urls(text, replacement)
}

/// Replace emails with a replacement string
#[pyfunction]
#[pyo3(signature = (text, replacement="<EMAIL>"))]
fn replace_emails_py(text: &str, replacement: &str) -> String {
    replace_emails(text, replacement)
}

/// Expand contractions
#[pyfunction]
fn expand_contractions_py(text: &str) -> String {
    expand_contractions(text)
}

/// Normalize Unicode
#[pyfunction]
fn normalize_unicode_py(text: &str) -> PyResult<String> {
    normalize_unicode(text)
        .map_err(|e| PyRuntimeError::new_err(format!("Unicode normalization failed: {}", e)))
}

/// Normalize whitespace
#[pyfunction]
fn normalize_whitespace_py(text: &str) -> String {
    normalize_whitespace(text)
}

/// Remove accents
#[pyfunction]
fn remove_accents_py(text: &str) -> String {
    remove_accents(text)
}

/// Python module registration
pub fn register_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    // Tokenization
    m.add_class::<PyWordTokenizer>()?;
    m.add_class::<PySentenceTokenizer>()?;
    m.add_class::<PyCharacterTokenizer>()?;
    m.add_class::<PyNgramTokenizer>()?;
    m.add_class::<PyWhitespaceTokenizer>()?;
    m.add_class::<PyRegexTokenizer>()?;

    // Vectorization
    m.add_class::<PyCountVectorizer>()?;
    m.add_class::<PyTfidfVectorizer>()?;

    // Sentiment analysis
    m.add_class::<PyLexiconSentimentAnalyzer>()?;

    // Stemming
    m.add_class::<PyPorterStemmer>()?;
    m.add_class::<PySnowballStemmer>()?;
    m.add_class::<PyLancasterStemmer>()?;

    // String similarity metrics
    m.add_function(wrap_pyfunction!(levenshtein_distance_py, m)?)?;
    m.add_function(wrap_pyfunction!(cosine_similarity_py, m)?)?;
    m.add_function(wrap_pyfunction!(jaccard_similarity_py, m)?)?;

    // Text cleaning
    m.add_function(wrap_pyfunction!(strip_html_tags_py, m)?)?;
    m.add_function(wrap_pyfunction!(replace_urls_py, m)?)?;
    m.add_function(wrap_pyfunction!(replace_emails_py, m)?)?;
    m.add_function(wrap_pyfunction!(expand_contractions_py, m)?)?;
    m.add_function(wrap_pyfunction!(normalize_unicode_py, m)?)?;
    m.add_function(wrap_pyfunction!(normalize_whitespace_py, m)?)?;
    m.add_function(wrap_pyfunction!(remove_accents_py, m)?)?;

    Ok(())
}