rishe 0.4.0

Rishe (ریشه): High-performance Persian NLP engine in Rust — tokenization, SBD, lemmatization, ezafe detection, informal→formal normalization, stemming, spell checking, embeddings
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
use crate::normalize_ops::{ALL_PUNCT, PERSIAN_LETTERS};
use crate::stopwords;
use aho_corasick::{AhoCorasick, AhoCorasickBuilder, MatchKind};
use std::sync::OnceLock;

const ZWNJ: char = '\u{200C}';
const PERSIAN_DIGITS: &str = "۰۱۲۳۴۵۶۷۸۹";
const ARABIC_DIGITS: &str = "٠١٢٣٤٥٦٧٨٩";
const DIACRITICS: &str = "ًٌٍَُِّْ";
const VS16: char = '\u{FE0F}';
const ZWJ: char = '\u{200D}';
const OFFENSIVE_WORDS: &str = include_str!("../data/offensive_words.txt");

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MaskOp {
    Url,
    Email,
    Mention,
    Hashtag,
    Emoji,
    Html,
    NonPersian,
    Stopwords,
    Offensive,
    Digits,
    Diacritics,
    Punctuation,
}

impl MaskOp {
    pub fn from_name(name: &str) -> Option<Self> {
        Some(match name {
            "url" | "urls" => Self::Url,
            "email" | "emails" => Self::Email,
            "mention" | "mentions" => Self::Mention,
            "hashtag" | "hashtags" => Self::Hashtag,
            "emoji" | "emojis" => Self::Emoji,
            "html" | "html_tag" | "html_tags" => Self::Html,
            "non_persian" | "non_persian_letters" => Self::NonPersian,
            "stopword" | "stopwords" => Self::Stopwords,
            "offensive" | "offensive_words" => Self::Offensive,
            "digit" | "digits" => Self::Digits,
            "diacritic" | "diacritics" => Self::Diacritics,
            "punctuation" | "punctuations" => Self::Punctuation,
            _ => return None,
        })
    }

    pub fn default_mask(self) -> &'static str {
        match self {
            Self::Url => "<URL>",
            Self::Email => "<EMAIL>",
            Self::Mention | Self::Hashtag | Self::Html => " ",
            _ => "",
        }
    }

    pub fn apply(self, text: &str, mask: Option<&str>) -> String {
        let mask = mask.unwrap_or_else(|| self.default_mask());
        match self {
            Self::Url => mask_urls(text, mask),
            Self::Email => mask_emails(text, mask),
            Self::Mention => mask_sigil(text, '@', mask),
            Self::Hashtag => mask_sigil(text, '#', mask),
            Self::Emoji => mask_emojis(text, mask),
            Self::Html => mask_html(text, mask),
            Self::NonPersian => mask_non_persian(text, mask, false, false),
            Self::Stopwords => mask_stopwords(text, mask),
            Self::Offensive => mask_offensive(text, mask),
            Self::Digits => mask_digits(text, mask),
            Self::Diacritics => mask_diacritics(text, mask),
            Self::Punctuation => mask_punctuation(text, mask),
        }
    }
}

pub fn mask_urls(text: &str, mask: &str) -> String {
    if !text.contains("http") {
        return text.trim().to_string();
    }

    let mut out = String::with_capacity(text.len());
    let mut i = 0;

    while i < text.len() {
        if text[i..].starts_with("http://") || text[i..].starts_with("https://") {
            let mut end = text.len();
            for (offset, ch) in text[i..].char_indices() {
                if ch.is_whitespace() {
                    end = i + offset;
                    break;
                }
            }
            out.push_str(mask);
            i = end;
        } else {
            let ch = text[i..].chars().next().unwrap();
            out.push(ch);
            i += ch.len_utf8();
        }
    }

    out.trim().to_string()
}

pub fn mask_emails(text: &str, mask: &str) -> String {
    if !text.contains('@') {
        return text.trim().to_string();
    }

    let spans = email_spans(text);
    if spans.is_empty() {
        return text.trim().to_string();
    }

    let mut out = String::with_capacity(text.len());
    let mut last = 0;
    for (start, end) in spans {
        out.push_str(&text[last..start]);
        out.push_str(mask);
        last = end;
    }
    out.push_str(&text[last..]);
    out.trim().to_string()
}

pub(crate) fn email_spans(text: &str) -> Vec<(usize, usize)> {
    let bytes = text.as_bytes();
    let mut spans = Vec::new();
    let mut i = 0;

    while i < bytes.len() {
        if bytes[i] == b'@' {
            let mut start = i;
            while start > 0 && is_email_local(bytes[start - 1] as char) {
                start -= 1;
            }
            while start < i && !text.is_char_boundary(start) {
                start += 1;
            }

            let mut domain_end = i + 1;
            while domain_end < bytes.len() && is_email_domain(bytes[domain_end] as char) {
                domain_end += 1;
            }

            let mut match_end = None;
            for dot in (i + 1..domain_end).rev() {
                if bytes[dot] != b'.' || dot == i + 1 {
                    continue;
                }
                let mut run_end = dot + 1;
                while run_end < domain_end && bytes[run_end].is_ascii_alphabetic() {
                    run_end += 1;
                }
                if run_end - (dot + 1) >= 2 {
                    match_end = Some(run_end);
                    break;
                }
            }

            if start < i {
                if let Some(end) = match_end {
                    spans.push((start, end));
                    i = end;
                    continue;
                }
            }
        }
        i += 1;
    }
    spans
}

fn is_email_local(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || matches!(ch, '.' | '_' | '%' | '+' | '-')
}

fn is_email_domain(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-')
}

pub fn mask_sigil(text: &str, sigil: char, mask: &str) -> String {
    if !text.contains(sigil) {
        return text.trim().to_string();
    }

    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == sigil {
            while chars.peek().is_some_and(|next| !next.is_whitespace()) {
                chars.next();
            }
            out.push_str(mask);
        } else {
            out.push(ch);
        }
    }

    out.trim().to_string()
}

pub fn mask_emojis(text: &str, mask: &str) -> String {
    if !text.chars().any(is_emoji_base) {
        return text.trim().to_string();
    }

    let chars: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;

    while i < chars.len() {
        let ch = chars[i];

        if is_regional(ch) && i + 1 < chars.len() && is_regional(chars[i + 1]) {
            out.push_str(mask);
            i += 2;
            continue;
        }

        if is_emoji_base(ch) {
            out.push_str(mask);
            i += 1;
            if i < chars.len() && is_skin_tone(chars[i]) {
                i += 1;
            }
            if i < chars.len() && chars[i] == VS16 {
                i += 1;
            }
            while i + 1 < chars.len() && chars[i] == ZWJ && is_emoji_base(chars[i + 1]) {
                i += 2;
                if i < chars.len() && is_skin_tone(chars[i]) {
                    i += 1;
                }
                if i < chars.len() && chars[i] == VS16 {
                    i += 1;
                }
            }
            continue;
        }

        out.push(ch);
        i += 1;
    }

    out.trim().to_string()
}

pub(crate) fn is_emoji_base(ch: char) -> bool {
    matches!(
        ch as u32,
        0x2600..=0x26FF
            | 0x2700..=0x27BF
            | 0x1F000..=0x1F02F
            | 0x1F0A0..=0x1F0FF
            | 0x1F100..=0x1F1FF
            | 0x1F200..=0x1F2FF
            | 0x1F300..=0x1F5FF
            | 0x1F600..=0x1F64F
            | 0x1F680..=0x1F6FF
            | 0x1F700..=0x1F77F
            | 0x1F780..=0x1F7FF
            | 0x1F800..=0x1F8FF
            | 0x1F900..=0x1F9FF
            | 0x1FA00..=0x1FA6F
            | 0x1FA70..=0x1FAFF
    )
}

pub(crate) fn is_regional(ch: char) -> bool {
    matches!(ch as u32, 0x1F1E6..=0x1F1FF)
}

fn is_skin_tone(ch: char) -> bool {
    matches!(ch as u32, 0x1F3FB..=0x1F3FF)
}

pub fn mask_html(text: &str, mask: &str) -> String {
    if !text.contains('<') && !text.contains('&') {
        return text.trim().to_string();
    }

    let unescaped = html_unescape(text);
    let mut out = String::with_capacity(unescaped.len());
    let mut i = 0;

    while i < unescaped.len() {
        if unescaped.as_bytes()[i] == b'<' {
            if let Some(close) = unescaped[i..].find('>') {
                if close > 1 {
                    out.push_str(mask);
                    i += close + 1;
                    continue;
                }
            }
        }
        let ch = unescaped[i..].chars().next().unwrap();
        out.push(ch);
        i += ch.len_utf8();
    }

    out.trim().to_string()
}

fn html_unescape(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut i = 0;

    while i < text.len() {
        if text.as_bytes()[i] == b'&' {
            if let Some(semi) = text[i..].find(';').filter(|semi| *semi <= 32) {
                if let Some(replacement) = decode_entity(&text[i + 1..i + semi]) {
                    out.push_str(&replacement);
                    i += semi + 1;
                    continue;
                }
            }
        }
        let ch = text[i..].chars().next().unwrap();
        out.push(ch);
        i += ch.len_utf8();
    }

    out
}

// ponytail: common HTML entities and numeric references only; add the full
// HTML5 table if real input needs it.
fn decode_entity(entity: &str) -> Option<String> {
    let named = match entity {
        "amp" => "&",
        "lt" => "<",
        "gt" => ">",
        "quot" => "\"",
        "apos" => "'",
        "nbsp" => "\u{00A0}",
        _ => "",
    };
    if !named.is_empty() {
        return Some(named.to_string());
    }

    if let Some(hex) = entity
        .strip_prefix("#x")
        .or_else(|| entity.strip_prefix("#X"))
    {
        return u32::from_str_radix(hex, 16)
            .ok()
            .and_then(char::from_u32)
            .map(|ch| ch.to_string());
    }
    if let Some(decimal) = entity.strip_prefix('#') {
        return decimal
            .parse::<u32>()
            .ok()
            .and_then(char::from_u32)
            .map(|ch| ch.to_string());
    }
    None
}

pub fn mask_non_persian(
    text: &str,
    mask: &str,
    keep_english: bool,
    keep_diacritics: bool,
) -> String {
    let mut out = String::with_capacity(text.len());

    for ch in text.chars() {
        let allowed = PERSIAN_LETTERS.contains(ch)
            || ch == ZWNJ
            || ch == ' '
            || PERSIAN_DIGITS.contains(ch)
            || ALL_PUNCT.contains(ch)
            || (keep_diacritics && DIACRITICS.contains(ch))
            || (keep_english && (ch.is_ascii_alphanumeric() || ch.is_ascii_punctuation()));

        if allowed {
            out.push(ch);
        } else {
            out.push_str(mask);
        }
    }

    out.trim().to_string()
}

pub fn mask_stopwords(text: &str, mask: &str) -> String {
    replace_words(text, stopword_matcher(), mask)
}

pub fn mask_offensive(text: &str, mask: &str) -> String {
    replace_words(text, offensive_matcher(), mask)
}

static STOPWORD_MATCHER: OnceLock<AhoCorasick> = OnceLock::new();
static OFFENSIVE_MATCHER: OnceLock<AhoCorasick> = OnceLock::new();

fn stopword_matcher() -> &'static AhoCorasick {
    STOPWORD_MATCHER.get_or_init(|| build_matcher(stopwords::stopwords()))
}

fn offensive_matcher() -> &'static AhoCorasick {
    OFFENSIVE_MATCHER.get_or_init(|| {
        build_matcher(
            OFFENSIVE_WORDS
                .lines()
                .map(str::trim)
                .filter(|word| !word.is_empty())
                .map(str::to_owned),
        )
    })
}

fn build_matcher<I, P>(patterns: I) -> AhoCorasick
where
    I: IntoIterator<Item = P>,
    P: AsRef<[u8]>,
{
    AhoCorasickBuilder::new()
        .match_kind(MatchKind::LeftmostLongest)
        .build(patterns)
        .expect("valid Aho-Corasick patterns")
}

fn replace_words(text: &str, matcher: &AhoCorasick, mask: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut last = 0;

    for found in matcher.find_iter(text) {
        if !word_boundary(text, found.start(), found.end()) {
            continue;
        }
        out.push_str(&text[last..found.start()]);
        out.push_str(mask);
        last = found.end();
    }
    out.push_str(&text[last..]);
    out.trim().to_string()
}

fn word_boundary(text: &str, start: usize, end: usize) -> bool {
    let before = text[..start]
        .chars()
        .next_back()
        .map_or(true, |ch| !is_persian_letter(ch));
    let after = text[end..]
        .chars()
        .next()
        .map_or(true, |ch| !is_persian_letter(ch));
    before && after
}

fn is_persian_letter(ch: char) -> bool {
    PERSIAN_LETTERS.contains(ch) || ch == ZWNJ
}

pub fn mask_digits(text: &str, mask: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        if ch.is_ascii_digit() || PERSIAN_DIGITS.contains(ch) || ARABIC_DIGITS.contains(ch) {
            out.push_str(mask);
        } else {
            out.push(ch);
        }
    }
    out.trim().to_string()
}

pub fn mask_diacritics(text: &str, mask: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        if DIACRITICS.contains(ch) {
            out.push_str(mask);
        } else {
            out.push(ch);
        }
    }
    out
}

pub fn mask_punctuation(text: &str, mask: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        if ALL_PUNCT.contains(ch) || ch.is_ascii_punctuation() {
            out.push_str(mask);
        } else {
            out.push(ch);
        }
    }
    out.trim().to_string()
}

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

    #[test]
    fn masks_links_and_contacts() {
        assert_eq!(
            MaskOp::Url.apply("برای اطلاعات بیشتر به https://shekar.io مراجعه کنید.", None),
            "برای اطلاعات بیشتر به <URL> مراجعه کنید."
        );
        assert_eq!(
            MaskOp::Email.apply("برای تماس با ما به info@shekar.io ایمیل بزنید.", None),
            "برای تماس با ما به <EMAIL> ایمیل بزنید."
        );
        assert_eq!(
            mask_emails("mail info@a.co, ok", "<EMAIL>"),
            "mail <EMAIL>, ok"
        );
        assert_eq!(
            MaskOp::Url.apply("x https://a.b y", Some("[MASK]")),
            "x [MASK] y"
        );
    }

    #[test]
    fn masks_social_tokens() {
        assert_eq!(
            MaskOp::Mention.apply("سلام @user! چطوری؟", None),
            "سلام   چطوری؟"
        );
        assert_eq!(MaskOp::Hashtag.apply("#سلام #خوش_آمدید", None), "");
    }

    #[test]
    fn masks_emoji_sequences() {
        assert_eq!(
            MaskOp::Emoji.apply("درود بر شما😊!🌟", None),
            "درود بر شما!"
        );
        assert_eq!(MaskOp::Emoji.apply("family 👨‍👩‍👧‍👦", None), "family");
        assert_eq!(MaskOp::Emoji.apply("flag 🇮🇷", None), "flag");
    }

    #[test]
    fn masks_html_tags_and_entities() {
        assert_eq!(
            MaskOp::Html.apply("<p>این یک <strong>متن</strong> نمونه است.</p>", None),
            "این یک  متن  نمونه است."
        );
        assert_eq!(mask_html("a &amp; b", ""), "a & b");
        assert_eq!(mask_html("&#1587;&#x644;&#x627;&#1605;", ""), "سلام");
    }

    #[test]
    fn masks_non_persian_letters() {
        assert_eq!(MaskOp::NonPersian.apply("سلام hello 123!", None), "سلام  !");
        assert_eq!(
            mask_non_persian("سلام hello 123!", "", true, false),
            "سلام hello 123!"
        );
    }

    #[test]
    fn masks_stopwords_and_offensive_words() {
        assert_eq!(MaskOp::Stopwords.apply("این کتاب است", None), "کتاب");
        assert_eq!(mask_stopwords("کتاب و دفتر", ""), "کتاب  دفتر");
        assert_eq!(MaskOp::Offensive.apply("این بی‌شرف است", None), "این  است");
    }

    #[test]
    fn masks_digits_diacritics_punctuation() {
        assert_eq!(
            MaskOp::Digits.apply("این متن 1234 شامل اعداد است.", None),
            "این متن  شامل اعداد است."
        );
        assert_eq!(
            MaskOp::Diacritics.apply("کُجا نِشانِ قَدَم ناتَمام خواهَد ماند؟", None),
            "کجا نشان قدم ناتمام خواهد ماند؟"
        );
        assert_eq!(
            MaskOp::Punctuation.apply("دریغ است ایران که ویران شود!", None),
            "دریغ است ایران که ویران شود"
        );
    }

    #[test]
    fn op_names_resolve() {
        assert_eq!(MaskOp::from_name("url"), Some(MaskOp::Url));
        assert_eq!(MaskOp::from_name("stopwords"), Some(MaskOp::Stopwords));
        assert_eq!(MaskOp::from_name("nope"), None);
    }
}